<?php

namespace CatLab\Charon\Laravel\Database;

use CatLab\Charon\Laravel\PropertySetterException;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Class Model
 * @package CatLab\Charon\Laravel\Models
 */
class Model extends \Illuminate\Database\Eloquent\Model
{
    /**
     * @var Model[][]
     */
    private $addedChildren;

    /**
     * @var Model[][]
     */
    private $removedChildren;

    /**
     * @var Model[][]
     */
    private $editedChildren;

    /**
     * Save model and all its children
     */
    public function saveRecursively()
    {
        $this->save();
        $this->saveTheChildren();
    }

    /**
     * Save all related entities.
     * @throws PropertySetterException
     */
    protected function saveTheChildren()
    {
        $toReload = [];

        if (isset($this->addedChildren)) {
            foreach ($this->addedChildren as $relation => $children) {
                $relationship = call_user_func([ $this, $relation ]);
                if ($relationship instanceof HasMany) {
                    $relationship->saveMany($children);
                } else {
                    throw new PropertySetterException(
                        "Relationship " . get_class($relationship) . " is not implemented yet."
                    );
                }

                // Also save the children
                foreach ($children as $child) {
                    if ($child instanceof Model) {
                        $child->saveTheChildren();
                    }
                }

                $toReload[$relation] = true;
            }
        }

        if (isset($this->removedChildren)) {
            foreach ($this->removedChildren as $relation => $children) {
                $relationship = call_user_func([ $this, $relation ]);

                if ($relationship instanceof HasMany) {

                    foreach ($children as $child) {
                        $child->delete();
                    }

                } else {
                    throw new PropertySetterException(
                        "Relationship " . get_class($relationship) . " is not implemented yet."
                    );
                }

                $toReload[$relation] = true;
            }
        }

        if (isset($this->editedChildren)) {
            foreach ($this->editedChildren as $relation => $children) {
                $relationship = call_user_func([ $this, $relation ]);

                foreach ($children as $child) {
                    if ($child instanceof Model) {
                        $child->saveRecursively();
                    } else {
                        $child->save();
                    }
                }

                $toReload[$relation] = true;
            }
        }

        $toReload = array_keys($toReload);
        foreach ($toReload as $reload) {
            unset($this->relations[$reload]);
        }
    }

    /**
     * Add children to a related entity.
     * @param $name
     * @param array $childEntities
     * @param array $setterParameters
     */
    public function addChildrenToEntity($name, array $childEntities, $setterParameters = [])
    {
        // For each relationship, keep a list of all children that were added.
        if (!isset($this->addedChildren[$name])) {
            $this->addedChildren[$name] = [];
        }

        foreach ($childEntities as $child) {
            $this->$name->add($child);
            $this->addedChildren[$name][] = $child;
        }
    }

    /**
     *
     */
    public function editChildrenInEntity($name, $childEntities, $parameters)
    {
        // For each relationship, keep a list of all children that were added.
        if (!isset($this->editedChildren[$name])) {
            $this->editedChildren[$name] = [];
        }

        foreach ($childEntities as $childEntity) {
            $this->editedChildren[$name][] = $childEntity;
        }
    }

    public function removeChildrenFromEntity($name, $childEntities, $parameters)
    {
        // For each relationship, keep a list of all children that were added.
        if (!isset($this->removedChildren[$name])) {
            $this->removedChildren[$name] = [];
        }

        foreach ($childEntities as $child) {
            $this->removedChildren[$name][] = $child;
        }

        //$this->$name = $this->$name->except($childEntities);
    }
}


<?php

namespace CatLab\Charon\Laravel\Controllers;

use CatLab\Base\Helpers\ArrayHelper;
use CatLab\Base\Models\Database\WhereParameter;
use CatLab\Base\Models\Grammar\AndConjunction;
use CatLab\Base\Models\Grammar\OrConjunction;
use CatLab\Charon\Collections\ResourceCollection;
use CatLab\Charon\Enums\Action;
use CatLab\Charon\Factories\EntityFactory;
use CatLab\Charon\Interfaces\SerializableResource;
use CatLab\Charon\Laravel\InputParsers\JsonBodyInputParser;
use CatLab\Charon\Laravel\InputParsers\PostInputParser;
use CatLab\Charon\Models\ResourceDefinition;
use CatLab\Charon\Models\ResourceResponse;
use CatLab\Laravel\Database\SelectQueryTransformer;
use CatLab\Charon\Interfaces\Context;
use CatLab\Charon\Interfaces\ResourceDefinition as ResourceDefinitionContract;
use CatLab\Charon\Interfaces\ResourceTransformer as ResourceTransformerContract;

use CatLab\Charon\Laravel\Resolvers\PropertyResolver;
use CatLab\Charon\Laravel\Resolvers\PropertySetter;
use CatLab\Charon\Laravel\Transformers\ResourceTransformer;
use CatLab\Charon\Models\RESTResource;
use CatLab\Requirements\Exceptions\ResourceValidationException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\Relations\Relation;

use Illuminate\Http\JsonResponse;
use Request;
use Response;

/**
 * Class ResourceController
 * @package CatLab\RESTResource\Laravel\Controllers
 */
trait ResourceController
{
    /**
     * @var ResourceDefinitionContract
     */
    protected $resourceDefinition;

    /**
     * @var ResourceTransformer
     */
    protected $resourceTransformer;

    /**
     * From a query builder, filter models based on input and processor and return the resulting
     * models.
     * Since order is important, the returned Collection will be a plain laravel collection!
     * @param $queryBuilder
     * @param Context $context
     * @param ResourceDefinition|string|null $resourceDefinition
     * @param int|null $records
     * @return Model[]
     */
    public function getModels($queryBuilder, Context $context, $resourceDefinition = null, $records = null)
    {
        $resourceDefinition = $resourceDefinition ?? $this->resourceDefinition;
        $records = $records ?? $this->getRecordLimit();

        return $this->filterAndGet($queryBuilder, $resourceDefinition, $context, $records);
    }

    /**
     * @deprecated Use getModels()
     * @param $model
     * @param $resourceDefinition
     * @param Context $context
     * @param int $records
     * @return mixed
     */
    public function filterAndGet($model, $resourceDefinition, Context $context, $records = null)
    {
        if (!isset($records)) {
            $records = $this->getRecordLimit();
        }

        $filter = $this->resourceTransformer->getFilters(
            Request::query(),
            $resourceDefinition,
            $context,
            $records
        );

        // Translate parameters to larevel query
        $selectQueryTransformer = new SelectQueryTransformer();
        $selectQueryTransformer->toLaravel($model, $filter);

        // Process eager loading
        $this->resourceTransformer->processEagerLoading($model, $resourceDefinition, $context);

        if (
            $model instanceof Builder ||
            $model instanceof Relation
        ) {
            $models = $model->get();
        } else {
            $models = $model;
        }

        if ($filter->isReverse()) {
            $models = $models->reverse();
        }

        return $models;
    }

    /**
     * @param Builder $query
     * @param $wheres
     */
    private function processWhere(Builder $query, $wheres)
    {
        $self = $this;
        foreach ($wheres as $where) {

            /** @var WhereParameter $where */
            $query->where(function(Builder $query) use ($self, $where) {

                if ($comparison = $where->getComparison()) {
                    $query->where($comparison->getSubject(), $comparison->getOperator(), $comparison->getValue());
                }

                foreach ($where->getChildren() as $child) {
                    if ($child instanceof AndConjunction) {
                        $query->where(function (Builder $query) use ($self, $child) {
                            $this->processWhere($query, [ $child->getSubject() ]);
                        });
                    } elseif ($child instanceof OrConjunction) {
                        $query->orWhere(function (Builder $query) use ($self, $child) {
                            $this->processWhere($query, [ $child->getSubject() ]);
                        });
                    } else {
                        throw new \InvalidArgumentException("Got an unknown conjunction");
                    }
                }
            });
        }
    }

    /**
     * @param ResourceDefinitionContract $resourceDefinition
     * @param ResourceTransformerContract $resourceTransformer
     * @return $this
     */
    public function setResourceDefinition(
        ResourceDefinitionContract $resourceDefinition,
        ResourceTransformerContract $resourceTransformer = null
    ) {
        $this->resourceDefinition = $resourceDefinition;

        if (!isset($resourceTransformer)) {
            $this->resourceTransformer = $this->createResourceTransformer();
        }

        return $this;
    }

    /**
     * @return ResourceDefinitionContract
     */
    public function getResourceDefinition(): ResourceDefinitionContract
    {
        return $this->resourceDefinition;
    }

    /**
     * @return ResourceTransformer
     */
    public function getResourceTransformer(): ResourceTransformer
    {
        return $this->resourceTransformer;
    }

    /**
     * @param mixed $entity
     * @param Context $context
     * @param null $resourceDefinition
     * @return \CatLab\Charon\Interfaces\RESTResource|RESTResource
     */
    public function toResource($entity, Context $context, $resourceDefinition = null) : RESTResource
    {
        return $this->resourceTransformer->toResource(
            $resourceDefinition ?? $this->resourceDefinition,
            $entity,
            $context
        );
    }

    /**
     * @param mixed $entities
     * @param Context $context
     * @param null $resourceDefinition
     * @return ResourceCollection
     * @throws \CatLab\Charon\Exceptions\InvalidEntityException
     */
    public function toResources($entities, Context $context, $resourceDefinition = null) : ResourceCollection
    {
        return $this->resourceTransformer->toResources(
            $resourceDefinition ?? $this->resourceDefinition,
            $entities,
            $context
        );
    }

    /**
     * Transform a resource into (an existing?) entity.
     * @param RESTResource $resource
     * @param Context $context
     * @param null $existingEntity
     * @param null $resourceDefinition
     * @param null $entityFactory
     * @return mixed
     */
    public function toEntity(
        RESTResource $resource,
        Context $context,
        $existingEntity = null,
        $resourceDefinition = null,
        $entityFactory = null
    ) {
        $resourceDefinition = $resourceDefinition ?? $this->resourceDefinition;
        $entityFactory = $entityFactory ?? new EntityFactory();

        return $this->resourceTransformer->toEntity(
            $resource,
            $resourceDefinition,
            $entityFactory,
            $context,
            $existingEntity
        );
    }

    /**
     * @param Context $context
     * @param null $resourceDefinition
     * @return RESTResource
     * @throws \CatLab\Charon\Exceptions\InvalidContextAction
     */
    public function bodyToResource(Context $context, $resourceDefinition = null) : RESTResource
    {
        $resources = $this->bodyToResources($context, $resourceDefinition);
        return $resources->first();
    }

    /**
     * @param Context $context
     * @param null $resourceDefinition
     * @return \CatLab\Charon\Collections\ResourceCollection
     */
    public function bodyToResources(Context $context, $resourceDefinition = null) : ResourceCollection
    {
        $resourceDefinition = $resourceDefinition ?? $this->resourceDefinition;
        return $this->resourceTransformer->fromInput($resourceDefinition, $context, $this->getRequest());
    }

    /**
     * @param Context $context
     * @param $resourceDefinition
     * @return array
     * @throws \CatLab\Charon\Exceptions\InvalidContextAction
     */
    public function bodyIdentifiersToEntities(Context $context, $resourceDefinition = null)
    {
        $resourceDefinition = $resourceDefinition ?? $this->resourceDefinition;

        $identifiers = $this->resourceTransformer->identifiersFromInput(
            $resourceDefinition,
            $context
        );

        return $this->resourceTransformer->entitiesFromIdentifiers(
            $resourceDefinition,
            $identifiers,
            new EntityFactory(),
            $context
        );
    }

    /**
     * @param string $action
     * @param array $parameters
     * @return Context|string
     */
    protected function getContext($action = Action::VIEW, $parameters = []) : \CatLab\Charon\Interfaces\Context
    {
        $context = new \CatLab\Charon\Models\Context($action, $parameters);

        if ($toShow = \Request::input(ResourceTransformer::FIELDS_PARAMETER)) {
            if (is_string($toShow)) {
                $context->showFields(array_map('trim', explode(',', $toShow)));
            }
        }

        if ($toExpand = \Request::input(ResourceTransformer::EXPAND_PARAMETER)) {
            if (is_string($toExpand)) {
                $context->expandFields(array_map('trim', explode(',', $toExpand)));
            }
        }

        $context->setUrl(\Request::url());
        $this->setInputParsers($context);

        return $context;
    }

    /**
     * Set the input parsers that will be used to turn requests into resources.
     * @param \CatLab\Charon\Models\Context $context
     */
    protected function setInputParsers(\CatLab\Charon\Models\Context $context)
    {
        $context->addInputParser(JsonBodyInputParser::class);
        // $context->addInputParser(PostInputParser::class);
    }

    /**
     * @param int $id
     * @param string $resource
     * @return \Illuminate\Http\JsonResponse
     */
    protected function notFound($id, $resource)
    {
        if ($resource) {
            throw new ModelNotFoundException('Resource ' . $id . ' ' . $resource . ' not found.');
        } else {
            throw new ModelNotFoundException('Resource ' . $id . ' not found.');
        }
    }

    /**
     * Output a resource or a collection of resources
     *
     * @param $models
     * @param array $parameters
     * @param null $resourceDefinition
     * @return \Illuminate\Http\JsonResponse
     */
    protected function outputList($models, array $parameters = [], $resourceDefinition = null)
    {
        $resources = $this->filteredModelsToResources($models, $parameters, $resourceDefinition);
        return $this->toResponse($resources);
    }

    /**
     * @param $models
     * @param array $parameters
     * @param null $resourceDefinition
     * @return array|\mixed[]
     */
    protected function filteredModelsToResources($models, array $parameters = [], $resourceDefinition = null)
    {
        $resourceDefinition = $resourceDefinition ?? $this->resourceDefinition;
        $context = $this->getContext(Action::INDEX, $parameters);

        $models = $this->filterAndGet(
            $models,
            $resourceDefinition,
            $context,
            $this->getRecordLimit()
        );

        return $this->modelsToResources($models, $context, $resourceDefinition);
    }

    /**
     * @return int
     */
    protected function getRecordLimit()
    {
        $records = Request::input('records', 10);
        if (!is_numeric($records)) {
            $records = 10;
        }
        return $records;
    }

    /**
     * Output a resource or a collection of resources
     * @deprecated Use getModels(), toResource() and toResources()
     *
     * @param $models
     * @param array $parameters
     * @return \Illuminate\Http\JsonResponse
     */
    protected function output($models, array $parameters = [])
    {
        if (ArrayHelper::isIterable($models)) {
            $context = $this->getContext(Action::INDEX, $parameters);
        } else {
            $context = $this->getContext(Action::VIEW, $parameters);
        }

        $output = $this->modelsToResources($models, $context);
        return $this->toResponse($output);
    }

    /**
     * Take one or multiple models and transform them into one or multiple resources.
     * Notice: When non-model content is found, it is returned "as-is".
     * @deprecated Use toResources() or toResource().
     * @param Model|Model[] $models
     * @param Context $context
     * @param null $resourceDefinition
     * @return RESTResource|RESTResource[]|mixed
     */
    protected function modelsToResources($models, Context $context, $resourceDefinition = null)
    {
        if (ArrayHelper::isIterable($models)) {
            return $this->toResources($models, $context, $resourceDefinition);
        } elseif ($models instanceof Model) {
            return $this->toResource($models, $context, $resourceDefinition);
        } else {
            return $models;
        }
    }

    /**
     * @param ResourceValidationException $e
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function getValidationErrorResponse(ResourceValidationException $e)
    {
        return $this->toResponse([
            'error' => [
                'message' => 'Could not decode resource.',
                'issues' => $e->getMessages()->toMap()
            ]
        ])->setStatusCode(400);
    }

    /**
     * @deprecated Use new ResourceResponse()
     * @param $data
     * @param Context|null $context
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function toResponse($data, Context $context = null)
    {
        if ($data instanceof SerializableResource) {
            return new ResourceResponse($data, $context);
        } else {
            return JsonResponse::create($this->resourceToArray($data));
        }
    }

    /**
     * Convert collections or resources to arrays.
     * @param $data
     * @return array|mixed
     */
    protected function resourceToArray($data)
    {
        if ($data instanceof ResourceCollection) {
            return $data->toArray();
        } else if ($data instanceof RESTResource) {
            return $data->toArray();
        } else if (ArrayHelper::isIterable($data)) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->resourceToArray($v);
            }
            return $data;
        }

        return $data;
    }

    /**
     * @return Request
     */
    protected function getRequest()
    {
        if (method_exists(\Illuminate\Http\Request::class, 'instance')) {
            return Request::instance();
        } else {
            return Request::getInstance();
        }
    }

    /**
     * Create (and return) a resource transformer.
     * @return ResourceTransformer
     */
    protected function createResourceTransformer()
    {
        return new ResourceTransformer(
            new PropertyResolver(),
            new PropertySetter()
        );
    }
}


<?php

namespace Nails\Captcha\Driver;

use Nails\Factory;
use Nails\Common\Driver\Base;
use Nails\Captcha\Exception\CaptchaDriverException;

class ReCaptcha extends Base implements \Nails\Captcha\Interfaces\Driver
{
    /**
     * Returns the form markup for the captcha
     * @return string
     */
    public function generate()
    {
        $sClientKey = appSetting('site_key_client', 'nails/driver-captcha-recaptcha');

        if (empty($sClientKey)) {
            throw new CaptchaDriverException('ReCaptcha not configured.');
        }

        $oAsset = Factory::service('Asset');
        $oAsset->load('https://www.google.com/recaptcha/api.js');

        $oResponse = Factory::factory('CaptchaForm', 'nails/module-captcha');
        $oResponse->setHtml('

');

        return $oResponse;
    }

    // --------------------------------------------------------------------------

    /**
     * Verifies a user's captcha entry from POST Data
     * @return boolean
     */
    public function verify()
    {
        $sServerKey = appSetting('site_key_server', 'nails/driver-captcha-recaptcha');

        if ($sServerKey) {

            $oHttpClient = Factory::factory('HttpClient');
            $oInput      = Factory::service('Input');

            try {

                $oResponse = $oHttpClient->post(
                    'https://www.google.com/recaptcha/api/siteverify',
                    [
                        'form_params' => [
                            'secret'   => $sServerKey,
                            'response' => $oInput->post('g-recaptcha-response'),
                            'remoteip' => $oInput->ipAddress(),
                        ],
                    ]
                );

                if ($oResponse->getStatusCode() !== 200) {
                    throw new CaptchaDriverException('Google returned a non 200 response.');
                }

                $oResponse = json_decode((string) $oResponse->getBody());

                if (empty($oResponse->success)) {
                    throw new CaptchaDriverException('Google returned an unsuccessful response.');
                }

                return true;

            } catch (\Exception $e) {
                return false;
            }

        } else {
            return false;
        }
    }
}


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: Button.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
//include_once("InputElement.php");

/**
 * Button class is element for Button
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class Button extends InputElement
{
    /**
     * Image file name
     *
     * @var string
     */
    public $image;
 	public $sortable;
    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->image = isset($xmlArr["ATTRIBUTES"]["IMAGE"]) ? $xmlArr["ATTRIBUTES"]["IMAGE"] : null;
        $this->sortable = isset($xmlArr["ATTRIBUTES"]["SORTABLE"]) ? $xmlArr["ATTRIBUTES"]["SORTABLE"] : null;

    }

    /**
     * Render element, according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $style = $this->getStyle();
        $func = $this->getEnabled() == 'N' ? "" : $this->getFunction();
        $id	   = $this->objectName;

        if ($this->image)
        {
            $imagesPath = Openbizx::$app->getImageUrl();
            $out = "image . "\" border=0 title=\"" . $this->text . "\" />";
            if ($func != "") {
                $out = "htmlAttr $style $func>" . $out . "";
            }
        }
        else
        {
            $out = $this->getText();
            //$out = "<input id=\"$id\" type='button' value='$out' $this->htmlAttr $style $func>";
            $out = "htmlAttr $style $func>".$out."";
        }

        return $out . "\n" . $this->addSCKeyScript();
    }

 /**
     * Set the sort flag of the element
     *
     * @param integer $flag 1 or 0
     * @return void
     */
    public function setSortFlag($flag=null)
    {
        $this->sortFlag = $flag;
    }

    /**
     * Render label,
     * When render table, it return the table header; when render array, it return the display name
     *
     * @return string HTML text
     */
    public function renderLabel()
    {
        if ($this->sortable == "Y")
        {
            $rule = $this->objectName;

            $function = $this->formName . ".SortRecord($rule,$this->sortFlag)";
            if($this->sortFlag == "ASC" || $this->sortFlag == "DESC"){
            	$class=" class=\"current\" ";
            }else{
            	$class=" class=\"normal\" ";
            }
            if ($this->sortFlag == "ASC")
            	$span_class = " class=\"sort_up\" ";
            else if ($this->sortFlag == "DESC")
                $span_class = " class=\"sort_down\" ";
            $sHTML = "" . $this->label ."";
            $sHTML .= "";
        }
        else
        {
            $sHTML = $this->label;
        }
        return $sHTML;
    }

    public function matchRemoteMethod($method)
    {
        return ($this->sortable == "Y" && $method == "sortrecord");
    }
}

?>


<?php

/**
 * Email [ MODEL ]
 * Modelo responável por configurar a Mailgun, validar os dados e disparar e-mails do sistema!
 *
 * @copyright (c) 2017, Edinei J. Bauer
 */

namespace EmailControl;

use Helpers\Template;
use Mailgun\Mailgun;

class EmailMailgun
{

    /** CORPO DO E-MAIL */
    private $assunto = "";
    private $mensagem = "";
    private $html = "";
    private $nome = "Anônimo";
    private $email;
    private $anexo;

    private $emailRemetente;
    private $nomeRemetente;
    private $mailGunApi;
    private $mailGunDomain;
    private $library = "email-control";
    private $folder;
    private $template;
    private $data;

    /** CONSTROLE */
    private $result;

    public function __construct($library = null)
    {
        if ($library)
            $this->setLibrary($library);
        $this->nomeRemetente = "Contato" . defined('SITENAME') ? " " . SITENAME : "";
        $this->emailRemetente = defined('EMAIL') ? EMAIL : "contato@ontab.com.br";
        $this->mailGunApi = defined('MAILGUNKEY') ? MAILGUNKEY : null;
        $this->mailGunDomain = defined('MAILGUNDOMAIN') ? MAILGUNDOMAIN : (defined('EMAIL') && !empty(EMAIL) ? explode('@', EMAIL)[1] : "ontab.com.br");
    }

    /**
     * @param string $template
     * @param mixed $data
     */
    public function setTemplate(string $template, $data = null)
    {
        $this->template = $template;
        if ($data && is_array($data))
            $this->setData($data);
    }

    /**
     * @param mixed $folder
     */
    public function setFolder($folder)
    {
        $this->folder = $folder;
    }

    /**
     * @param array $data
     */
    public function setData(array $data)
    {
        $this->data = $this->preData($data);
    }

    /**
     * @param mixed $library
     */
    public function setLibrary($library)
    {
        $this->library = $library;
    }

    /**
     * @param mixed $assunto
     */
    public function setAssunto($assunto)
    {
        $this->assunto = $assunto;
    }

    /**
     * @param mixed $mensagem
     */
    public function setMensagem($mensagem)
    {
        $this->mensagem = $mensagem;
    }

    /**
     * @param mixed $nome
     */
    public function setDestinatarioNome($nome)
    {
        $this->nome = $nome;
    }

    /**
     * @param mixed $email
     */
    public function setDestinatarioEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @param mixed $emailRemetente
     */
    public function setRemetenteEmail($emailRemetente)
    {
        $this->emailRemetente = $emailRemetente;
    }

    /**
     * @param mixed $nomeRemetente
     */
    public function setRemetenteNome($nomeRemetente)
    {
        $this->nomeRemetente = $nomeRemetente;
    }

    public function setAnexo($file, $name)
    {
        $this->anexo[$file] = $name;
    }

    /**
     * <b>Verificar Envio:</b> Executando um getResult é possível verificar se foi ou não efetuado
     * o envio do e-mail. Para mensagens execute o getError();
     * @return BOOL $Result = TRUE or FALSE
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * @param mixed $email
     */
    public function enviar($email = null)
    {
        if(!$this->data) $this->data = $this->preData([]);
        $tpl = new Template($this->library);
        $this->data['email_header'] = $tpl->getShow("model/header", $this->data);
        $this->data['email_footer'] = $tpl->getShow("model/footer", $this->data);

        if($this->template) {
            if ($this->folder) {
                $tpl->setFolder($this->folder);
                $this->data['email_content'] = $tpl->getShow($this->template, $this->data);
                $tpl->setFolder(null);
            } else {
                $this->data['email_content'] = $tpl->getShow($this->template, $this->data);
            }
        } else {
            $this->data['email_content'] = $tpl->getShow("model/container", $this->data);
        }

        $this->html = $tpl->getShow("model/base", $this->data);

        $this->clear();

        if ($email)
            $this->checkEmailDestinatario($email);
        else
            $this->sendEmail();
    }

    /*
     * ***************************************
     * **********  PRIVATE METHODS  **********
     * ***************************************
     */

    private function sendEmail()
    {
        if($this->mailGunApi) {
            $param = [
                'from' => "{$this->nomeRemetente} <{$this->emailRemetente}>",
                'to' => $this->email,
                'subject' => $this->assunto,
                'text' => $this->mensagem,
                'html' => $this->html
            ];

            $param = $this->checkAnexo($param);

            $mg = Mailgun::create($this->mailGunApi);
            $this->result = $mg->messages()->send($this->mailGunDomain, $param);
        }
    }

    /**
     * @param string $string1
     * @param string $string2
     */
    private function checkEmailInString(string $string1, string $string2)
    {
        if (preg_match('/@/i', $string1)) {
            $this->nome = $string2;
            $this->email = $string1;
        } else {
            $this->nome = $string1;
            $this->email = $string2;
        }
    }

    private function checkEmailDestinatario($email)
    {
        if (is_array($email)) {
            foreach ($email as $i => $m) {
                if (is_numeric($i)) {
                    foreach ($m as $a => $b) {
                        if (is_string($a) && is_string($b))
                            $this->checkEmailInString($a, $b);
                    }
                } elseif (is_string($i) && is_string($m)) {
                    $this->checkEmailInString($i, $m);
                }
                $this->sendEmail();
            }

        } elseif (is_string($email)) {
            $this->email = $email;
            $this->sendEmail();
        }
    }

    private function checkAnexo($param)
    {
        if ($this->anexo) {
            $anexo = "";
            foreach ($this->anexo as $file => $name) {
                $anexo .= (!empty($anexo) ? ", " : "") . "['filePath' => '{$file}', 'filename' => '{$name}']";
            }
            $param['attachment'] = $anexo;
        }

        return $param;
    }

    //Limpa código e espaços!
    private function clear()
    {
        $this->html = trim($this->html);
        $this->assunto = trim(strip_tags($this->assunto));
        $this->mensagem = trim(strip_tags($this->mensagem));
    }

    /**
     * Configura informações básicas que são submetidas aos templates de email
     *
     * @param array $data
     * @return array
     */
    private function preData(array $data): array
    {
        if ($this->template)
            $data = $this->preDataTemplate($data);

        list($color, $background) = $this->getColorDefault();

        $data['assunto'] = $data['assunto'] ?? $this->assunto;
        $data['title'] = $data['title'] ?? $data['assunto'];
        $data['mensagem'] = $data['mensagem'] ?? $this->mensagem;
        $data['remetenteEmail'] = $data['remetenteEmail'] ?? $this->emailRemetente;
        $data['remetenteNome'] = $data['remetenteNome'] ?? $this->nomeRemetente;
        $data['destinatarioEmail'] = $data['destinatarioEmail'] ?? $this->email;
        $data['destinatarioNome'] = $data['destinatarioNome'] ?? $this->nome;
        $data['email'] = $data['email'] ?? $this->email;
        $data['nome'] = $data['nome'] ?? $this->nome;
        $data['footerColor'] = $data['footerColor'] ?? "dddddd";
        $data['headerColor'] = $data['headerTextColor'] ?? $color;
        $data['headerColor'] = $data['headerColor'] ?? $background;

        if ($data)
            $this->preDataClass($data);

        return $data;
    }

    private function getColorDefault()
    {
        if(file_exists(PATH_HOME . "public/assets/theme.min.css")) {
            $theme = file_get_contents(PATH_HOME . "public/assets/theme.min.css");
            $theme = explode('.theme{', $theme)[1];
            $color = trim(explode('!important', explode('color:', $theme)[1])[0]);
            $backgroun = trim(explode('!important', explode('background-color:', $theme)[1])[0]);
            return [$color, $backgroun];
        }

        return ["#111", "70bbd9"];
    }

    /**
     *
     * @param array $data
     * @return array
     */
    private function preDataTemplate(array $data): array
    {
        switch ($this->template) {
            case "password":
                $data['assunto'] = "Recuperação de Senha";
        }

        return $data;
    }

    /**
     * Verifica se existe parâmetros de informação do email submetidos ao template
     * que não estão informados na classe
     *
     * @param array $data
     * @return array $data
     */
    private function preDataClass(array $data): array
    {
        if ($data['assunto'] && !$this->assunto)
            $this->assunto = $data['assunto'];
        if ($data['mensagem'] && !$this->mensagem)
            $this->mensagem = $data['mensagem'];
        if ($data['remetenteEmail'] && !$this->emailRemetente)
            $this->emailRemetente = $data['remetenteEmail'];
        if ($data['remetenteNome'] && !$this->nomeRemetente)
            $this->nomeRemetente = $data['remetenteNome'];
        if ($data['destinatarioEmail'] && !$this->email)
            $this->email = $data['email'];
        if ($data['destinatarioNome'] && !$this->nome)
            $this->nome = $data['nome'];
        if ($data['email'] && !$this->email)
            $this->email = $data['email'];
        if ($data['nome'] && !$this->nome)
            $this->nome = $data['nome'];

        return $data;
    }

}


<?php

namespace Openbizx;

use Openbizx\Object\ObjectFactory;
/**
 * Description of Openbizx
 *
 * @author agus
 */
class Openbizx
{
    /**
     *
     * @var \Openbizx\Application
     */
    public static $app;

    private static $_objectFactory = null;

    /**
     * Return the version of OpenBiz Framework
     *
     * @return string
     */
    public static function getVersion()
    {
        return '3.1';
    }

    /**
     * Get the metadata object by object name
     *
     * @param string $objectName object name
     * @param number $isNew 0 = not new, 1 new object
     * @return object
     */
    public static function getObject($objectName, $isNew = 0)
    {
        return self::objectFactory()->getObject($objectName,$isNew);
    }

    /**
     * Get the service object
     *
     * @param string $service service name
     * @return object the service object
     */
    public static function getService($service, $new = 0)
    {
        $defaultPackage = "service";
        $serviceName = $service;
        if (strpos($service, ".") === false) {
            $serviceName = $defaultPackage . "." . $service;
        }
        return Openbizx::getObject($serviceName, $new);
    }

    /**
     * Get the openbiz data object by object name.
     * It's functional same as getObject() method, just this method can return more eclipse friendly result,
     * it can support IDE's code auto completaion.
     *
     * @param string $objectName object name
     * @return BizDataObj  if the return object is a BizDataObj then return, or return null
     * @example ../../example/DataObject.php
     */
    public static function getDataObject($objectName)
    {
        $obj = Openbizx::getObject($objectName, 0);
        if (is_a($obj, 'BizDataObj')) {
            return $obj;
        }
    }

    /**
     * Get the openbiz form object by object name.
     * It's functional same as getObject() method, just this method can return more eclipse friendly result,
     * it can support IDE's code auto completaion.
     *
     * @param string $objectName object name
     * @return EasyForm  if the return object is a EasyForm then return, or return null
     * @example ../../example/FormObject.php
     */
    public static function getFormObject($objectName)
    {
        $obj = Openbizx::getObject($objectName, 0);
        if (is_a($obj, 'Openbizx\Easy\EasyForm')) {
            return $obj;
        }
    }

    /**
     * Get the openbiz view object by object name.
     * It's functional same as getObject() method, just this method can return more eclipse friendly result,
     * it can support IDE's code auto completaion.
     *
     * @param string $objectName object name
     * @return WebPage  if the return object is a WebPage then return, or return null
     * @example ../../example/ViewObject.php
     */
    public static function getWebpageObject($objectName)
    {
        return Openbizx::getObject($objectName, 0);
    }

    /**
     * Get get the ObjectFactory object
     *
     * @return ObjectFactory the ObjectFactory object
     */
    public static function objectFactory()
    {
        if (!self::$_objectFactory) {
            self::$_objectFactory = new ObjectFactory();
        }
        return self::$_objectFactory;
    }
}


<?php
namespace T3v\T3vContent\ViewHelpers;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\Core\ViewHelper\TagBuilder;

use T3v\T3vCore\ViewHelpers\AbstractTagBasedViewHelper;

/**
 * The headline link view helper class.
 *
 * @package T3v\T3vContent\ViewHelpers
 */
class HeadlineLinkViewHelper extends AbstractTagBasedViewHelper {
  /**
   * The tag name.
   *
   * @var string
   */
  protected $tagName = 'h1';

  /**
   * The view helper render function.
   *
   * @param string $content The content of the headline
   * @param int $layout The optional layout (UID) of the headline, defaults to `100`
   * @param string $cssClass The optional CSS class of the headline, defaults to `ce__title`
   * @return string The rendered headline
   */
  public function render($content = null, $layout = 100, $cssClass = 'ce__title') {
    $content  = (string) $content;
    $layout   = intval($layout);
    $cssClass = (string) $cssClass;

    if (empty($content)) {
      $content = $this->renderChildren();
    }

    if (!empty($content) && $layout != 0 && $layout != 100) {
      $tagName = "h{$layout}";

      $this->tag->setTagName($tagName);
      $this->tag->addAttribute('class', $cssClass);

      $link = $this->createLink($content);

      $this->tag->setContent($link->render());

      return $this->tag->render();
    }
  }

  /**
   * Creates a link.
   *
   * @param string $content The content of the link
   * @param string $href The optional href attribute of the link, defaults to `#`
   * @param string $title The optional title attribute of the link
   * @return \TYPO3\CMS\Fluid\Core\ViewHelper\TagBuilder The link
   */
  protected function createLink($content, $href = '#', $title = null) {
    $content = (string) $content;
    $href    = (string) $href;
    $title   = (string) $title;

    if (empty($title)) {
      $title = $content;
    }

    $link = GeneralUtility::makeInstance('TYPO3\CMS\Fluid\Core\ViewHelper\TagBuilder');
    $link->setTagName('a');
    $link->addAttribute('href', $href);
    $link->addAttribute('title', $title);
    $link->setContent($content);

    return $link;
  }
}


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */
namespace DoctrineModule\Service\Authentication;

use DoctrineModule\Authentication\Adapter\ObjectRepository;
use DoctrineModule\Service\AbstractFactory;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Factory to create authentication adapter object.
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @since   0.1.0
 * @author  Tim Roediger <superdweebie@gmail.com>
 */
class AdapterFactory extends AbstractFactory
{
    /**
     * {@inheritDoc}
     *
     * @return \DoctrineModule\Authentication\Adapter\ObjectRepository
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var $options \DoctrineModule\Options\Authentication */
        $options = $this->getOptions($serviceLocator, 'authentication');

        if (is_string($objectManager = $options->getObjectManager())) {
            $options->setObjectManager($serviceLocator->get($objectManager));
        }

        return new ObjectRepository($options);
    }

    /**
     * {@inheritDoc}
     */
    public function getOptionsClass()
    {
        return 'DoctrineModule\Options\Authentication';
    }
}


<?php
/**
 * Ensures that all fatal errors are rendered as JSON.
 */
App::uses('ExceptionRenderer', 'Error');

/**
 * StatelessAuthExceptionRenderer
 */
class SerializerExceptionRenderer extends ExceptionRenderer {

	/**
	 * construct a new instance of this class
	 *
	 * @param Exception $exception the exception being thrown
	 */
	public function __construct(Exception $exception) {
		parent::__construct($exception);
	}

	/**
	 * render the Exception to the end user, if the Exception is an instance of
	 * BaseSerializerException call our custom renderer else, call the parent
	 * render method
	 *
	 * @return void
	 */
	public function render() {
		if ($this->error instanceof ValidationBaseSerializerException) {
			return $this->renderValidationSerializerException($this->error);
		} elseif ($this->error instanceof BaseSerializerException) {
			return $this->renderSerializerException($this->error);
		} elseif ($this->error instanceof CakeException) {
			return $this->renderCakeException($this->error);
		} elseif ($this->error instanceof HttpException) {
			return $this->renderHttpException($this->error);
		} else {
			// This isn't a standard CakeException, render it using the default error500 method
			return $this->error500($this->error);
		}
	}

	/**
	 * render exceptions of type HttpException
	 *
	 * @param HttpException $error the HttpException error to render
	 * @return void
	 */
	protected function renderHttpException(HttpException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderHttpAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderHttpAsJson($error);
		}

		return $this->defaultHttpRender($error);
	}

	/**
	 * render exceptions of type CakeException
	 *
	 * @param CakeException $error the CakeException error to render
	 * @return void
	 */
	protected function renderCakeException(CakeException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderCakeAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderCakeAsJson($error);
		}

		return $this->defaultCakeRender($error);
	}

	/**
	 * render exceptions of type BaseSerializerException
	 *
	 * @param BaseSerializerException $error the BaseSerializerException error to render
	 * @return void
	 */
	protected function renderSerializerException(BaseSerializerException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderSerializerAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderSerializerAsJson($error);
		}

		return $this->defaultSerializerRender($error);
	}

	/**
	 * render exceptions of type ValidationBaseSerializerException
	 *
	 * @param ValidationBaseSerializerException $error the ValidationBaseSerializerException error to render
	 * @return void
	 */
	protected function renderValidationSerializerException(ValidationBaseSerializerException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderValidationSerializerAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderValidationSerializerAsJson($error);
		}

		return $this->defaultValidationSerializerRender($error);
	}

	/**
	 * render the HttpException for a JSON request
	 *
	 * @param HttpException $error an instance of HttpException
	 * @return void
	 */
	protected function renderHttpAsJson(HttpException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');

		$url = $this->controller->request->here();
		$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
		$this->controller->response->statusCode($code);
		$this->controller->set(array(
			'code' => $code,
			'name' => h(get_class($error)),
			'message' => h($error->getMessage()),
			'url' => h($url),
			'error' => $error,
			'_serialize' => array('code', 'name', 'message', 'url')
		));
		$this->_outputMessage($this->template);
	}

	/**
	 * render the HttpException for a JSON API request
	 *
	 * @param HttpException $error an instance of HttpException
	 * @return void
	 */
	protected function renderHttpAsJsonApi(HttpException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		// Set the correct Status Code
		$this->controller->response->statusCode($error->getCode());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				'id' => null,
				'href' => null,
				'status' => h($error->getCode()),
				'code' => h(get_class($error)),
				'title' => h($error->getMessage()),
				'detail' => h($error->getMessage()),
				'links' => array(),
				'paths' => array(),
			),
		);
		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

	/**
	 * render the HttpException in the general case
	 *
	 * @param HttpException $error an instance of HttpException
	 * @return void
	 */
	protected function defaultHttpRender(HttpException $error) {
		$url = $this->controller->request->here();
		$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
		$this->controller->response->statusCode($code);
		$this->controller->set(array(
			'code' => $code,
			'name' => h(get_class($error)),
			'message' => h($error->getMessage()),
			'url' => h($url),
			'error' => $error,
			'_serialize' => array('code', 'name', 'message', 'url')
		));
		$template = ($code >= 400 && $code < 500) ? 'error400' : 'error500';
		$this->_outputMessage($template);
	}

	/**
	 * render the CakeException for a JSON request
	 *
	 * @param CakeException $error an instance of CakeException
	 * @return void
	 */
	protected function renderCakeAsJson(CakeException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');

		$url = $this->controller->request->here();
		$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
		$this->controller->response->statusCode($code);
		$this->controller->set(array(
			'code' => $code,
			'name' => h(get_class($error)),
			'message' => h($error->getMessage()),
			'url' => h($url),
			'error' => $error,
			'_serialize' => array('code', 'name', 'message', 'url')
		));
		$this->controller->set($error->getAttributes());
		$this->_outputMessage($this->template);
	}

	/**
	 * render the CakeException for a JSON API request
	 *
	 * @param CakeException $error an instance of CakeException
	 * @return void
	 */
	protected function renderCakeAsJsonApi(CakeException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		// Set the correct Status Code
		$this->controller->response->statusCode($error->getCode());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				'id' => null,
				'href' => null,
				'status' => h($error->getCode()),
				'code' => h(get_class($error)),
				'title' => h($error->getMessage()),
				'detail' => h($error->getAttributes()),
				'links' => array(),
				'paths' => array(),
			),
		);
		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

	/**
	 * render the CakeException in the general case
	 *
	 * @param CakeException $error an instance of CakeException
	 * @return void
	 */
	protected function defaultCakeRender(CakeException $error) {
		$url = $this->controller->request->here();
		$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
		$this->controller->response->statusCode($code);
		$this->controller->set(array(
			'code' => $code,
			'name' => h(get_class($error)),
			'message' => h($error->getMessage()),
			'url' => h($url),
			'error' => $error,
			'_serialize' => array('code', 'name', 'message', 'url')
		));
		$this->controller->set($error->getAttributes());
		$template = ($code >= 400 && $code < 500) ? 'error400' : 'error500';
		$this->_outputMessage($template);
	}

	/**
	 * render the BaseSerializerException in the general case
	 *
	 * @param BaseSerializerException $error an instance of BaseSerializerException
	 * @return void
	 */
	protected function defaultSerializerRender(BaseSerializerException $error) {
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's expectations
		$this->controller->set('id', $error->id());
		$this->controller->set('href', $error->href());
		$this->controller->set('status', $error->status());
		$this->controller->set('code', $error->code());
		$this->controller->set('title', $error->title());
		$this->controller->set('detail', $error->detail());
		$this->controller->set('links', $error->links());
		$this->controller->set('paths', $error->paths());
		$this->controller->set('error', $error);

		$this->controller->set('url', $this->controller->request->here());

		if (empty($template)) {
			$template = "SerializersErrors./Errors/serializer_exception";
		}

		$this->controller->render($template);
		$this->controller->afterFilter();
		return $this->controller->response->send();
	}

	/**
	 * render the BaseSerializerException for a JSON request
	 *
	 * @param BaseSerializerException $error an instance of BaseSerializerException
	 * @return void
	 */
	protected function renderSerializerAsJson(BaseSerializerException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');
		$this->controller->response->statusCode($error->status());

		// set all the values we have from our exception to populate the json object
		$this->controller->set('id', h($error->id()));
		$this->controller->set('href', h($error->href()));
		$this->controller->set('status', h($error->status()));
		$this->controller->set('code', h($error->code()));
		$this->controller->set('title', h($error->title()));
		$this->controller->set('detail', h($error->detail()));
		$this->controller->set('links', h($error->links()));
		$this->controller->set('paths', h($error->paths()));

		$this->controller->set('_serialize', array(
			'id', 'href', 'status', 'code', 'title ', 'detail', 'links', 'paths'
		));

		if (empty($template)) {
			$template = "SerializersErrors./Errors/serializer_exception";
		}

		$this->controller->render($template);
		$this->controller->afterFilter();
		return $this->controller->response->send();
	}

	/**
	 * render the BaseSerializerException for a JSON API request
	 *
	 * @param BaseSerializerException $error an instance of BaseSerializerException
	 * @return void
	 */
	protected function renderSerializerAsJsonApi(BaseSerializerException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		// Set the correct Status Code
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				array(
					'id' => h($error->id()),
					'href' => h($error->href()),
					'status' => h($error->status()),
					'code' => h($error->code()),
					'title' => h($error->title()),
					'detail' => h($error->detail()),
					'links' => $error->links(),
					'paths' => $error->paths(),
				),
			),
		);
		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

	/**
	 * render the ValidationBaseSerializerException in the general case
	 *
	 * @param ValidationBaseSerializerException $error an instance of ValidationBaseSerializerException
	 * @return void
	 */
	protected function defaultValidationSerializerRender(ValidationBaseSerializerException $error) {
		$this->addHttpCodes();
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's expectations
		$this->controller->set('title', $error->title());
		$this->controller->set('validationErrors', $error->validationErrors());
		$this->controller->set('status', $error->status());
		$this->controller->set('error', $error);

		$this->controller->set('url', $this->controller->request->here());

		if (empty($template)) {
			$template = "SerializersErrors./Errors/validation_serializer_exception";
		}

		$this->controller->render($template);
		$this->controller->afterFilter();
		return $this->controller->response->send();
	}

	/**
	 * render the ValidationBaseSerializerException for a JSON request
	 *
	 * @param ValidationBaseSerializerException $error an instance of ValidationBaseSerializerException
	 * @return void
	 */
	protected function renderValidationSerializerAsJson(ValidationBaseSerializerException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');
		$this->addHttpCodes();
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => $error->validationErrors(),
		);

		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

	/**
	 * render the ValidationBaseSerializerException for a JSON API request
	 *
	 * @param ValidationBaseSerializerException $error an instance of ValidationBaseSerializerException
	 * @return void
	 */
	protected function renderValidationSerializerAsJsonApi(ValidationBaseSerializerException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		$this->addHttpCodes();
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				array(
					'id' => h($error->id()),
					'href' => h($error->href()),
					'status' => h($error->status()),
					'code' => h($error->code()),
					'title' => h($error->title()),
					'detail' => h($error->validationErrors()),
					'links' => h($error->links()),
					'paths' => h($error->paths()),
				),
			),
		);

		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

	/**
	 * add additional HTTP codes to the CakeResponse Object
	 *
	 * @return void
	 */
	protected function addHttpCodes() {
		$defaultCodes = array(
			422 => 'Unprocessable Entity',
		);
		$this->controller->response->httpCodes($defaultCodes);
	}

	/**
	 * is this request a JsonApi style request
	 *
	 * @return bool returns true if JsonApi media request, false otherwise
	 */
	protected function isJsonApiRequest() {
		return $this->controller->request->accepts('application/vnd.api+json');
	}

	/**
	 * is this request for Json
	 *
	 * @return bool returns true if Json media request, false otherwise
	 */
	protected function isJsonRequest() {
		return $this->controller->request->accepts('application/json');
	}

}


<?php

namespace ASM;

use ASM\Driver as SessionDriver;

class SessionManager
{
    const READ_ONLY = 'READ_ONLY';
    const WRITE_LOCK = 'WRITE_LOCK';

    const CACHE_SKIP = 'skip';
    const CACHE_PUBLIC = 'public';
    const CACHE_PRIVATE = 'private';
    const CACHE_NO_CACHE = 'nocache';

    /**
     * @var SessionConfig
     */
    protected $sessionConfig;

    /**
     * @var \ASM\Driver
     */
    protected $driver;

    /**
     *
     */
    const lockSleepTime = 1000;

    /**
     * @param SessionConfig $sessionConfig
     * @param SessionDriver $driver
     * @param ValidationConfig $validationConfig
     */
    function __construct(
        SessionConfig $sessionConfig,
        SessionDriver $driver,
        ValidationConfig $validationConfig = null)
    {
        $this->sessionConfig = $sessionConfig;
        $this->driver = $driver;

        if ($validationConfig) {
            $this->validationConfig = $validationConfig;
        }
        else {
            $this->validationConfig = new ValidationConfig(
                null,
                null,
                null
            );
        }
    }

    function getSessionConfig()
    {
        return $this->sessionConfig;
    }

    function getLockMode()
    {
        return $this->sessionConfig->getLockMode();
    }

    public function openSessionFromCookie(array $cookieData, $userProfile = null)
    {
        if (!array_key_exists($this->sessionConfig->getSessionName(), $cookieData)) {
            return null;
        }

        $sessionID = $cookieData[$this->sessionConfig->getSessionName()];

        $existingSession = $this->openSessionByID($sessionID, $userProfile);

        if ($existingSession == null) {
            return $this->driver->createSession($this, $userProfile);
        }

        return $existingSession;
    }

    /**
     * Opens an existing session.
     *
     * Opens and returns the data for an existing session, if and only if the
     * client sent a valid existing session ID. Otherwise returns null.
     *
     * @param array $cookieData
     * @param null $userProfile
     * @return Session|null
     */
    public function openSessionByID($sessionID, $userProfile = null)
    {
        $session = $this->driver->openSessionByID(
            $sessionID,
            $this,
            $userProfile
        );

        if ($session == null) {
            $this->invalidSessionAccessed();
        }

        return $session;
    }

    /**
     * Create a new session or open existing session.
     *
     * Opens and returns the data for an existing session, if and only if the
     * client sent a valid existing session ID. Otherwise creates a new session.
     *
     * @param array $cookieData
     * @param $userProfile
     * @return Session
     */
    function createSession(array $cookieData, $userProfile = null)
    {
        if (!array_key_exists($this->sessionConfig->getSessionName(), $cookieData)) {
            return $this->driver->createSession($this, $userProfile);
        }

        $sessionID = $cookieData[$this->sessionConfig->getSessionName()];
        $existingSession = $this->openSessionByID($sessionID, $userProfile);

        if ($existingSession !== null) {
            return $existingSession;
        }

        $this->invalidSessionAccessed();
        return $this->driver->createSession($this, $userProfile);
    }

//    /**
//     *
//     */
//    function regenerateSessionID() {
//        $newSessionID = $this->makeSessionKey();
//        $zombieTime = $this->sessionConfig->getZombieTime();
//
//        if ($zombieTime > 0) {
//            $this->driver->setupZombieID(
//                $this->sessionID,
//                $newSessionID,
//                $this->sessionConfig->getZombieTime()
//            );
//        }
//
//        $this->sessionID = $newSessionID;
//    }

//    /**
//     * Load the session data from storage.
//     */
//    function loadData($sessionID) {
//        $maxLoops = 5;
//        $newData = null;
//
//        for ($i=0 ; $i<$maxLoops ; $i++) {
//            $newData = $this->driver->getData($sessionID);
//
//            if ($newData == null) {
//                //No session data was available. Check to see if there is a mapping
//                //for a zombie key to an active session key
//                $regeneratedID = $this->driver->findSessionIDFromZombieID($sessionID);
//
//                if ($regeneratedID) {
//                    //The user is trying to use a recently re-generated key.
//                    $this->zombieKeyDetected();
//                    $sessionID = $regeneratedID;
//                    $newData = $this->driver->getData($sessionID);
//                }
//                else {
//                    //Session id was not valid, and was not mapped from a zombie key to a live
//                    //key. Therefore it's a totally dead key.
//                    $this->invalidSessionAccessed();
//                    return [null, []];
//                }
//            }
//        }
//
//        return [$sessionID, $newData];
//    }

//    /**
//     * A zombie key was detected. If the user
//     */
//    private function zombieKeyDetected() {
//        $zombieKeyAccessedCallable = $this->validationConfig->getZombieKeyAccessedCallable();
//
//        if (!$zombieKeyAccessedCallable) {
//            return;
//        }
//
//        call_user_func($zombieKeyAccessedCallable, $this);
//    }

//    /**
//     *
//     */
//    public function saveData($saveData) {
//        $this->driver->save($this->sessionID, $saveData);
//    }

//    /**
//     * @throws FailedToAcquireLockException
//     */
//    function acquireLock() {
//        if ($this->sessionID == null) {
//            throw new AsmException("Cannot acquire lock, session is not open.");
//        }
//
//        $totalTimeWaitedForLock = 0;
//
//        do {
//            $lockAcquired = $this->driver->acquireLock(
//                $this->sessionID,
//                $this->sessionConfig->getLockMilliSeconds(),
//                $this->sessionConfig->getMaxLockWaitTimeMilliseconds()
//            );
//
//            if ($totalTimeWaitedForLock >= $this->sessionConfig->getMaxLockWaitTimeMilliseconds()) {
//                throw new FailedToAcquireLockException("Failed to acquire lock for session data after time $totalTimeWaitedForLock ");
//            }
//
//            if (!$lockAcquired) {
//                //Wait one millisecond to prevent hammering driver.
//                //TODO - change to random sleep time?
//                usleep(self::lockSleepTime);
//            }
//
//            $totalTimeWaitedForLock += self::lockSleepTime;
//
//        } while(!$lockAcquired);
//    }

//    /**
//     * @return bool
//     * @throws LockAlreadyReleasedException
//     */
//    function releaseLock() {
//        $lockReleased = $this->driver->releaseLock($this->sessionID);
//
//        if (!$lockReleased) {
//            // lock was force removed by a different script, or this script went over
//            // the $this->sessionConfig->lockTime Either way - bad things are likely to happen
//            $lostLockCallable = $this->validationConfig->getLockWasForceReleasedCallable();
//            $continueExecution = false;
//            if ($lostLockCallable) {
//                $continueExecution = call_user_func($lostLockCallable, $this);
//            }
//
//            if ($continueExecution === true) {
//                return false;
//            }
//
//            throw new LockAlreadyReleasedException("The lock for the session has already been released.");
//        }
//
//        return true;
//    }

//    /**
//     * Renews a lock. This allows long running operations to keep a lock open longer
//     * than the SessionConfig::$lockMilliSeconds time. If the lock fails to be renewed
//     * an exception is thrown. This can happen when another process force releases a
//     * lock.
//     * @throws FailedToAcquireLockException
//     */
//    function renewLock() {
//        $renewed = $this->driver->renewLock(
//            $this->sessionID,
//            $this->sessionConfig->getLockMilliSeconds()
//        );
//
//        if (!$renewed) {
//            throw new FailedToAcquireLockException("Failed to renew lock.");
//        }
//    }

//    /**
//     *
//     */
//    function forceReleaseLock() {
//        //TODO - should this only be callable after the session is started?
//        $this->driver->forceReleaseLock($this->sessionID);
//    }

    /**
     *
     */
    private function invalidSessionAccessed()
    {
        $invalidSessionAccessed = $this->validationConfig->getInvalidSessionAccessedCallable();

        if (!$invalidSessionAccessed) {
            return;
        }

        call_user_func($invalidSessionAccessed, $this);
    }

    /**
     * @param $newProfile
     * @param $existingProfiles
     * @return mixed|null
     * @throws AsmException
     */
    function performProfileSecurityCheck($newProfile, $existingProfiles)
    {
        if ($newProfile === null) {
            return $existingProfiles;
        }

        if (is_string($newProfile) == false &&
            (!(is_object($newProfile) && method_exists($newProfile, '__toString')))) {
            throw new AsmException(
                "userProfile must be a string or an object containing a __toString method.",
                AsmException::BAD_ARGUMENT
            );
        }

        $profileChangedCallable = $this->validationConfig->getProfileChangedCallable();
        if (!$profileChangedCallable) {
            return $existingProfiles;
        }

        foreach ($existingProfiles as $sessionProfile) {
            if ($newProfile === $sessionProfile) {
                return $existingProfiles;
            }
        }

        $newProfiles = call_user_func($profileChangedCallable, $this, $newProfile, $existingProfiles);

        if (is_array($newProfiles) == false) {
            throw new AsmException(
                "The profileChangedCallable must return an array of the allowed session profiles, but instead a ".gettype($newProfiles)."was returned",
                AsmException::BAD_ARGUMENT
            );
        }

        return $newProfiles;
    }

//    /**
//     * Add session profile to the approved session profile list
//     */
//    function addProfile($sessionProfile) {
//        $this->driver->addProfile($this->sessionID, $sessionProfile);
//    }

    /**
     *
     */
    function destroyExpiredSessions()
    {

    }

    /**
     * @param $sessionID
     */
    function deleteSession($sessionID)
    {
        $this->driver->deleteSessionByID($sessionID);
    }

    /**
     * @param $sessionId
     * @param $privacy
     * @param $lastModifiedTime
     * @param $domain
     * @param $path
     * @param $secure
     * @param $httpOnly
     * @return array
     * @throws AsmException
     */
    function getHeaders(
        $sessionId,
        $privacy,
        $domain,
        $path,
        $secure,
        $httpOnly
    ) {
        $time = time();

        $headers = [];
        $headers["Set-Cookie"] = ASM::generateCookieHeaderString($time,
            $this->sessionConfig->getSessionName(),
            $sessionId,
            $this->sessionConfig->getLifetime(),
            $path,
            $domain,
            $secure,
            $httpOnly);

        $cachingHeaders = ASM::getCacheControlPrivacyHeader(
            $privacy
        );

        $headers = array_merge($headers, $cachingHeaders);

        return $headers;
    }
}


<?php

namespace Clio\Layout;

use Clio\Clio;
use Clio\Styling\Markup\Justification;
use Clio\Styling\Style;

/**
 * This class is part of the Clio Open Source project, Clio.1happyplace.com
 * Copyright, Katie Ayres, katie@1happyplace.com
 *
 * Available through the MIT license
 * @license MIT
 *
 * The Title class is the base class for other title widgets.  Used alone
 * it creates a simple title.
 *
 */
class Title
{
    /**
     * The clio object that handles the output to the terminal
     * @var Clio|null
     */
    protected $clio = null;

    /**
     * The justification of the title
     * @var int | string | null
     */
    protected $justification = null;

    /**
     * The style to use for the title
     * @var Style|null
     */
    protected $style = null;

    /**
     * The number of lines to place before
     * @var int
     */
    protected $spaceBefore = 2;

    /**
     * The number of lines to place after
     * @var int
     */
    protected $spaceAfter = 1;

    /**
     * The overall height of the title in number of lines, even lines will place the empty line below
     * @var int
     */
    protected $height = 1;

    /**
     * Title constructor.
     * @param Clio $clio -the Clio object, generally want just one instance to represent the current terminal
     * @param int | string $justification - Justification constant
     * @param Style $style
     * @param int $spaceBefore
     * @param int $spaceAfter
     * @param int $height
     */
    public function __construct($clio, $justification = "left", $style, $spaceBefore = 2, $spaceAfter = 1, $height = 1)
    {
        // save the Clio object
        $this->clio = $clio;

        // set a default justification of left
        $this->justification = Justification::getJustificationConstant($justification);

        $this->style = $style;
        $this->spaceBefore = $spaceBefore;
        $this->spaceAfter = $spaceAfter;
        $this->height = $height;

    }

    /**
     * Prepare the text, if the text has no length, return false to indicate something went wrong
     * @param $text
     * @return bool
     */
    protected function prepareText(&$text) {

        // check if it is a string
        if (!is_string($text)) {

            // it is not, raise a flag
            return false;
        }

        // trim any front or ending spaces
        $text = trim($text);

        // if there is no text, no need to continue
        if (strlen($text) == 0) {

            // there is not text, raise a flag
            return false;
        }

        return true;
    }

    /**
     * Display one Title
     *
     * @param string $text - the text of the title
     * @return $this
     */
    public function display($text) {

        // prepare the text for the particular style of text
        // if it returns false, the text is bad
        if (!$this->prepareText($text)) {

            // chaining
            return $this;
        }

        // justify the text
        $text = $this->clio->justify($text, $this->justification);

        // create the specified number of lines before
        if ($this->spaceBefore > 0) {

            //  move down the space before number of lines
            $this->clio->newLine($this->spaceBefore);
        }

        // calculate any empty lines needed to create the height
        $top = $bottom = 0;

        // if there was anything higher than one requiring empty styled lines
        if ($this->height > 1) {

            // take off the actual title line
            $spaces = $this->height - 1;

            // the top will be the base value of dividing by two
            $top = intdiv($spaces,2);

            // the bottom will be that base value + the remainder
            $bottom = intdiv($spaces,2) + ($spaces % 2);
        }

        // set up the styling
        $this->clio->style($this->style);

        // display any empty lines needed above the title for the height
        $this->displayEmptyLines($top);

        // display the title text
        $this->clio->line($text);

        // display any empty lines needed below the title for the height
        $this->displayEmptyLines($bottom);

        // clear the formatting
        $this->clio->clear();

        // if there is space after
        if ($this->spaceAfter > 0) {

            // display the space after
            $this->clio->newLine($this->spaceAfter);
        }

        // chaining
        return $this;
    }

    /**
     * Helper function to output a number of lines that have the full width
     * @param $lines
     */
    private function displayEmptyLines($lines)
    {
        // create an empty line
        $emptyLine = str_pad(" ", $this->clio->getWidth());

        // if there is more than one line
        for ($i = 0; $i < $lines; ++$i) {

            // generate an empty line
            $this->clio->line($emptyLine);
        }

    }

}


<?php namespace Foothing\RepositoryController\Controllers;

use Foothing\RepositoryController\Resources\LoaderInterface;
use Foothing\RepositoryController\Resources\Mapper;
use Foothing\RepositoryController\Resources\WriterInterface;
use Foothing\Request\Laravel\RemoteQuery;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class ResourceController extends Controller {
	/**
	 * @var LoaderInterface
	 */
	protected $loader;

	/**
	 * @var WriterInterface
	 */
	protected $writer;

	/**
	 * @var Mapper
	 */
	protected $mapper;

	function __construct(LoaderInterface $loader, WriterInterface $writer, Mapper $mapper) {
		$this->loader = $loader;
		$this->writer = $writer;
		$this->mapper = $mapper;
	}

	/**
	 * /api/v1/resources/[resource]/{id?}/{relation?}?with=rel1,rel2&qparams={}
	 *
	 * @param Request $request
	 * @param string  $resource
	 * @param int     $id
	 * @param string  $args
	 *
	 * @return mixed
	 */
	public function getIndex(Request $request, $resource, $id = null, $args = null) {
		// Resource.
		$resource = $this->mapper->map($resource);

		if ($relations = $request->input('with')) {
			$relations = explode(",", $relations);
		}

		if ($id) {
			$result = $this->loader->loadEntity($resource, $id, $relations);

			// @TODO return child relation as resource.
			// We'll need the parent entity ID in order
			// to trigger repository access for child, i.e.
			// get:/resources/users/1/profile we need to
			// know which key bind profile to users.

			if ($args) {
				$args = explode("/", $args);
				return $result->{$args[0]};
			} else {
				return $result;
			}
		}

		else {
			$page = $request->get('page', 1);
			$ipp = $request->get('ipp', 50);

            // Apply criteria.
            $this->loader->query(RemoteQuery::spawn($request->input('qparams')));

            // Load.
            return $this->loader->loadEntities($resource, $page - 1, $ipp, $relations);
		}
	}

	public function putIndex(Request $request, $resource, $id) {
		$resource = $this->mapper->map($resource);
		return $this->writer->update($resource, $request->all(), $id);
	}

    public function putBulk(Request $request, $resource) {
        $resource = $this->mapper->map($resource);
        return $this->writer->bulkUpdate($resource, $request->all());
    }

	public function postIndex(Request $request, $resource) {
		$resource = $this->mapper->map($resource);
		return $this->writer->create($resource, $request->all());
	}

    public function postBulk(Request $request, $resource) {
        $resource = $this->mapper->map($resource);
        return $this->writer->bulkCreate($resource, $request->all());
    }

	public function deleteIndex($resource, $id) {
		$resource = $this->mapper->map($resource);
		return response()->json($this->writer->delete($resource, $id));
	}

    public function putLink($resource, $id, $relation, $related, $relatedId) {
        $resource = $this->mapper->map($resource);
        $related = $this->mapper->map($related);
        return response()->json($this->writer->link($resource, $id, $relation, $related, $relatedId));
    }

    public function deleteLink($resource, $id, $relation, $related, $relatedId) {
        $resource = $this->mapper->map($resource);
        $related = $this->mapper->map($related);
        return response()->json($this->writer->unlink($resource, $id, $relation, $related, $relatedId));
    }

}


<?php

namespace JetFire\Framework\Providers;

use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use JetFire\Db\Model;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;

/**
 * Class ConsoleProvider
 * @package JetFire\Framework\Providers
 */
class ConsoleProvider extends Provider
{

    /**
     * @var Application
     */
    protected $cli;
    /**
     * @var
     */
    protected $commands;

    /**
     * @return Application
     */
    public function getCli()
    {
        return $this->cli;
    }

    /**
     * ConsoleProvider constructor.
     * @param Application $cli
     * @param array $commands
     */
    public function init(Application $cli, $commands = [])
    {
        $this->cli = $cli;
        $this->commands = $commands;
    }

    /**
     * @param $orm
     * @param string $default_db
     */
    public function ormCommands($orm, $default_db = 'default')
    {
        if (is_array($orm)) {
            foreach ($orm as $o) {
                call_user_func_array([$this, $o . 'Commands'], [$default_db]);
            }
        }

        $this->setCommands();
    }

    /**
     * @param string $default_db
     */
    private function pdoCommands($default_db = 'default')
    {

    }

    /**
     * @param string $default_db
     */
    private function redbeanCommands($default_db = 'default')
    {

    }

    /**
     * @param string $default_db
     */
    private function doctrineCommands($default_db = 'default')
    {
        /** @var EntityManager $em */
        $em = Model::orm('doctrine')->db($default_db)->getOrm();
        $helperSet = new HelperSet([
            'db' => new ConnectionHelper($em->getConnection()),
            'em' => new EntityManagerHelper($em),
            'dialog' => new \Symfony\Component\Console\Helper\QuestionHelper(),
        ]);
        $this->cli->setCatchExceptions(true);
        $this->cli->setHelperSet($helperSet);
        ConsoleRunner::addCommands($this->cli);
    }

    /**
     *
     */
    private function setCommands()
    {
        foreach ($this->commands['di'] as $command) {
            $this->cli->add($this->app->get($command));
        }
        foreach ($this->commands['new'] as $instance) {
            $this->cli->add(new $instance);
        }
    }

    /**
     * @throws \Exception
     */
    public function run()
    {
        $this->cli->run();
    }

}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\EventListener;

use Imatic\Bundle\ViewBundle\Templating\Helper\Layout\LayoutHelper;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * Kernel subscriber.
 *
 * @author Pavel Batecko <pavel.batecko@imatic.cz>
 */
class KernelSubscriber implements EventSubscriberInterface
{
    /** @var LayoutHelper */
    private $layoutHelper;
    /** @var TranslatorInterface */
    private $translator;
    /** @var bool */
    private $debug;
    /** @var object|null */
    private $lastException;

    /**
     * @param LayoutHelper        $layoutHelper
     * @param TranslatorInterface $translator
     * @param bool                $debug
     */
    public function __construct(LayoutHelper $layoutHelper, TranslatorInterface $translator, $debug)
    {
        $this->layoutHelper = $layoutHelper;
        $this->translator = $translator;
        $this->debug = $debug;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => 'onKernelResponse',
            KernelEvents::EXCEPTION => 'onKernelException',
        ];
    }

    /**
     * On kernel response.
     *
     * @param FilterResponseEvent $event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        if ($event->isMasterRequest()) {
            $request = $event->getRequest();
            $response = $event->getResponse();

            if ($request->isXmlHttpRequest() && !$response->isRedirection()) {
                // flash messages
                if ($request->hasSession() && !$response->headers->has('X-Flash-Messages')) {
                    $this->setFlashMessageHeader($response, $request->getSession());
                }

                // title, fullTitle
                $this->setTitleHeaders($response);

                // exception info (debug only)
                if ($this->debug && $this->lastException) {
                    $this->setExceptionHeader($response, $this->lastException);
                    $this->lastException = null;
                }
            }
        }
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($this->debug) {
            $this->lastException = $event->getException();
        }
    }

    private function setFlashMessageHeader(Response $response, SessionInterface $session)
    {
        $flashBag = $session->getFlashBag();

        $flashes = [];

        foreach ($flashBag->all() as $type => $messages) {
            for ($i = 0; isset($messages[$i]); ++$i) {
                $flashes[] = [
                    'type' => $type,
                    'message' => $this->translator->trans($messages[$i], [], 'messages'),
                ];
            }
        }

        $response->headers->set(
            'X-Flash-Messages',
            \json_encode($flashes)
        );
    }

    private function setTitleHeaders(Response $response)
    {
        $title = [];

        if ($this->layoutHelper->hasTitle()) {
            $title['title'] = $this->layoutHelper->getTitle();
        }

        if ($this->layoutHelper->hasFullTitle()) {
            $title['fullTitle'] = $this->layoutHelper->getFullTitle();
        }

        if (!empty($title)) {
            $response->headers->set(
                'X-Title',
                \json_encode($title)
            );
        }
    }

    private function setExceptionHeader(Response $response, $exception)
    {
        $info = [
            'className' => \get_class($exception),
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'trace' => $exception->getTraceAsString(),
        ];

        // make sure all string values are valid UTF-8
        // (error messages coming from the OS may not be UTF-8 encoded)
        \array_walk($info, function (&$value) {
            if (\is_string($value)) {
                $value = \iconv('UTF-8', 'UTF-8//IGNORE', $value);
            }
        });

        $jsonString = \json_encode($info);

        if (false !== $jsonString) {
            $response->headers->set('X-Debug-Exception', $jsonString);
        }
    }
}


<?php

namespace JetFire\Framework\Providers;

use DebugBar\Bridge\DoctrineCollector;
use DebugBar\Bridge\Twig\TwigCollector;
use DebugBar\Bridge\Twig\TwigProfilerDumperHtml;
use DebugBar\StandardDebugBar;
use Twig_Profiler_Profile;

/**
 * Class LogProvider
 * @package JetFire\Framework\Providers
 */
class DebugBarProvider extends Provider{

    /**
     * @var StandardDebugBar
     */
    protected $debugBar;
    /**
     * @var \DebugBar\JavascriptRenderer
     */
    protected $debugBarRenderer;

    /**
     * DebugBarProvider constructor.
     * @param StandardDebugBar $debugBar
     */
    public function init(StandardDebugBar $debugBar){
        $this->debugBar = $debugBar;
        $this->debugBarRenderer = $debugBar->getJavascriptRenderer();
    }

    /**
     * @return StandardDebugBar
     */
    public function getDebugBar()
    {
        return $this->debugBar;
    }

    /**
     * @param StandardDebugBar $debugBar
     */
    public function setDebugBar($debugBar)
    {
        $this->debugBar = $debugBar;
    }

    /**
     * @return \DebugBar\JavascriptRenderer
     */
    public function getDebugBarRenderer()
    {
        return $this->debugBarRenderer;
    }

    /**
     * @param \DebugBar\JavascriptRenderer $debugBarRenderer
     */
    public function setDebugBarRenderer($debugBarRenderer)
    {
        $this->debugBarRenderer = $debugBarRenderer;
    }

    /**
     * @param $value
     */
    public function debug($value){
        $this->debugBar["messages"]->addMessage($value);
    }

    /**
     * @return \DebugBar\DataCollector\DataCollectorInterface|mixed
     */
    public function messages(){
        return $this->debugBar["messages"];
    }

    /**
     * @param TwigProfilerDumperHtml $dumper
     * @param Twig_Profiler_Profile $profiler
     * @throws \DebugBar\DebugBarException
     */
    public function loadTwigDebugger(TwigProfilerDumperHtml $dumper, Twig_Profiler_Profile $profiler){
        $this->debugBar->addCollector(new TwigCollector($dumper,$profiler));
    }

    /**
     * @param $debug_stack
     * @throws \DebugBar\DebugBarException
     */
    public function loadDoctrineDebugger($debug_stack){
        $this->debugBar->addCollector(new DoctrineCollector($debug_stack));
    }

}


<?php

namespace Del;

final class SessionManager
{
    /**
     * Creates a secure session
     * @param $name
     * @param int $lifetime
     * @param string $path
     * @param null $domain
     * @param null $secure
     */
    public static function sessionStart($name, $lifetime = 0, $path = '/', $domain = null, $secure = null)
    {
        // Set the cookie name before we start.
        session_name($name . '_Session');

        // Set the domain to default to the current domain.
        $domain = isset($domain) ? $domain : $_SERVER['SERVER_NAME'];

        // Set the default secure value to whether the site is being accessed with SSL
        $secure = isset($secure) ? $secure : isset($_SERVER['HTTPS']);

        // Set the cookie settings and start the session
        session_set_cookie_params($lifetime, $path, $domain, $secure, true);

        $id = session_id();
        if(empty($id)) {
            session_start();
        }

        // Make sure the session hasn't expired, and destroy it if it has
        if (self::validateSession()) {

            // Check to see if the session is new or a hijacking attempt
            if (!self::preventHijacking()) {

                // Reset session data and regenerate id
                $_SESSION = array();
                $_SESSION['ipAddress'] = $_SERVER['REMOTE_ADDR'];
                $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
                self::regenerateSession();

                // Give a 5% chance of the session id changing on any request
            } elseif (self::shouldRandomlyRegenerate()) {
                self::regenerateSession();
            }
        } else {
            self::destroySession();
        }
    }

    private function shouldRandomlyRegenerate()
    {
        return rand(1, 100) <= 5;
    }

    /**
     * Checks session IP and user agent are still the same
     * @return bool
     */
    private static function preventHijacking()
    {
        if (!isset($_SESSION['ipAddress']) || !isset($_SESSION['userAgent'])) {
            return false;
        }
        if ($_SESSION['ipAddress'] != $_SERVER['REMOTE_ADDR']) {
            return false;
        }
        if ($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
            return false;
        }
        return true;
    }

    /**
     *  Creates a fresh session Id to make it harder to hack
     *  If the site is very slow in parts increase the expiry time
     *  10 seconds is a good default which allows ajax calls to work
     *  without losing the session
     */
    private static function  regenerateSession()
    {
        // If this session is obsolete it means there already is a new id
        if (isset($_SESSION['OBSOLETE']) && $_SESSION['OBSOLETE'] == true) {
            return;
        }

        // Set current session to expire in 10 seconds
        $_SESSION['OBSOLETE'] = true;
        $_SESSION['EXPIRES'] = time() + 10;

        // Create new session without destroying the old one
        session_regenerate_id(false);

        // Grab current session ID and close both sessions to allow other scripts to use them
        $newSession = session_id();
        session_write_close();

        // Set session ID to the new one, and start it back up again
        session_id($newSession);
        session_start();

        // Now we unset the obsolete and expiration values for the session we want to keep
        unset($_SESSION['OBSOLETE']);
        unset($_SESSION['EXPIRES']);
    }

    /**
     * Checks whether the session has expired or not
     * @return bool
     */
    private static function validateSession()
    {
        if (isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
            return false;
        }

        if (isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
            return false;
        }

        return true;
    }

    /**
     *  Resets the session
     */
    public static function destroySession()
    {
        $id = session_id();
        if(!empty($id)) {
            $_SESSION = array();
            session_destroy();
            session_start();
        }
    }

    /**
     * @param $key
     * @param $val
     */
    public static function set($key, $val)
    {
        $_SESSION[$key] = $val;
    }

    /**
     * @param $key
     * @return null
     */
    public static function get($key)
    {
        return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
    }

    /**
     * @param $key
     * @param $val
     */
    public static function destroy($key)
    {
        unset($_SESSION[$key]);
    }
}


<?php
namespace Natsu90\Nexmo;

use Natsu90\Nexmo\AbstractNexmoClient;
use GuzzleHttp\Client;

class NexmoAccount extends AbstractNexmoClient {

    public $end_point = 'https://rest.nexmo.com';

    public function getBalance()
    {
        $response = $this->client->get('/account/get-balance/'.$this->nexmo_key.'/'.$this->nexmo_secret);

        return $response->json()['value'];
    }

    private function validateOriginator($inp){
        // Remove any invalid characters
        $ret = preg_replace('/[^a-zA-Z0-9]/', '', (string)$inp);
        if(preg_match('/[a-zA-Z]/', $inp)){
            // Alphanumeric format so make sure it's < 11 chars
            $ret = substr($ret, 0, 11);
        } else {
            // Numerical, remove any prepending '00'
            if(substr($ret, 0, 2) == '00'){
                $ret = substr($ret, 2);
                $ret = substr($ret, 0, 15);
            }
        }

        return (string)$ret;
    }

    public function sendMessage($from, $to, $text, $data = array())
    {
        // Making sure strings are UTF-8 encoded
        if ( !is_numeric($from) && !mb_check_encoding($from, 'UTF-8') ) {
            $this->error = array('error' => '$from needs to be a valid UTF-8 encoded string');
            return false;
        }
        if ( !mb_check_encoding($text, 'UTF-8') ) {
            $this->error = array('error' => '$message needs to be a valid UTF-8 encoded string');
            return false;
        }

        $isUnicode = max(array_map('ord', str_split($text))) > 127;

        // Make sure $from is valid
        $from = $this->validateOriginator($from);

        $body = array(
                        'api_key' => $this->nexmo_key,
                        'api_secret' => $this->nexmo_secret,
                        'from' => $from,
                        'to' => $to,
                        'text' => $text,
                        'type' => $isUnicode ? 'unicode' : 'text'
                    );

        $body = array_merge($data, $body);

        $response = $this->client->post('/sms/json', array(
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
                'body' => $body
            ));

        return $response->json();
    }

    public function getOutboundPricing($countryCode, $prefix = false)
    {
        return true;
    }

    public function getPhonePricing($phoneNumber, $productCode = 'sms')
    {
        if(!in_array($productCode, array('sms','voice')))
            throw new Exception("Invalid product code");
        return true;
    }

    /*
        Define moCallBackUrl & drCallBackUrl in array input, otherwise it will read as blank & get overwritten.
    */
    public function updateAccountSettings($data = array())
    {
        $response = $this->client->post('/account/settings/'.$this->nexmo_key.'/'.$this->nexmo_secret, array(
                        'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
                        'query' => $data
                    ));

        return $response->json();
    }

    public function topUpAccount($transactionId)
    {
        $response = $this->client->get('/account/top-up/'.$this->nexmo_key.'/'.$this->nexmo_secret.'/'.$transactionId, array(
                        'exceptions' => false
                    ));

        return $response->getStatusCode() == 200;
    }

    public function getInboundNumbers($data = array())
    {
        $response = $this->client->get('/account/numbers/'.$this->nexmo_key.'/'.$this->nexmo_secret, array(
                        'query' => $data
                    ));

        return $response->json();
    }

    public function getAvailableInboundNumbers($countryCode, $data = array())
    {
        $response = $this->client->get('/number/search/'.$this->nexmo_key.'/'.$this->nexmo_secret.'/'.$countryCode, array(
                        'query' => $data,
                        'exceptions' => false,
                    ));

        $success = $response->getStatusCode() == 200;
        if(!$success) {
            if($response->getStatusCode() == 420)
                $this->error = array_merge(array('message' => 'Probably invalid ISO country code.'), $response->json());
            else
                $this->error = $response->json();
            return false;
        }

        return $response->json();
    }

    public function buyNumber($countryCode, $phoneNumber)
    {
        $response = $this->client->post('/number/buy/'.$this->nexmo_key.'/'.$this->nexmo_secret.'/'.$countryCode.'/'.$phoneNumber, array(
                        'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
                        'exceptions' => false
                    ));

        $success = $response->getStatusCode() == 200;
        if(!$success)
            $this->error = $response->getStatusCode();

        return $success;
    }

    public function cancelNumber($countryCode, $phoneNumber)
    {
        $response = $this->client->post('/number/cancel/'.$this->nexmo_key.'/'.$this->nexmo_secret.'/'.$countryCode.'/'.$phoneNumber, array(
                        'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
                        'exceptions' => false
                    ));

        $success = $response->getStatusCode() == 200;
        if(!$success)
            $this->error = $response->getStatusCode();

        return $success;
    }

    public function updateNumber($countryCode, $phoneNumber, $moHttpUrl, $data = array(), $overwrite = false)
    {
        $data['moHttpUrl'] = $moHttpUrl;
        $response = $this->client->post('/number/update/'.$this->nexmo_key.'/'.$this->nexmo_secret.'/'.strtoupper($countryCode).'/'.$phoneNumber, array(
                        'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
                        'query' => $data,
                        'exceptions' => false
                    ));

        $success = $response->getStatusCode() == 200;
        if(!$success)
            $this->error = $response->getBody();

        return $success;
    }
}