<?php
namespace Mabs\JQueryAjaxBundle\Twig;

/**
 *
 * @author Mohamed Aymen Ben Slimane <med.aymen3@gmail.com>
 *
 */
class JqueryAjaxExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('ja_request', $this->remoteCall(), array(
                'is_safe' => array(
                    'html'
                )
            )),
            new \Twig_SimpleFunction('ja_submit', $this->submitTag(), array(
                'is_safe' => array(
                    'html'
                )
            )),
            new \Twig_SimpleFunction('ja_link', $this->linkTag(), array(
                'is_safe' => array(
                    'html'
                )
            ))
        );
    }

    /**
     * Generate Js function to send ajax request.
     *
     * @param array $options
     */
    public function remoteCall($options = array())
    {
        return function ($options) {
            $type = isset($options['type']) ? $options['type'] : "POST";
            $dataType = isset($options['dataType']) ? $options['dataType'] : "html";
            $js = "$.ajax({
							url: '" . $options['url'] . "',
							type: '" . $type . "',
							dataType: '" . $dataType . "',";

            if (isset($options['before'])) {
                $before = str_replace('"', "'", $options['before']);
                $js .= "beforeSend: function(){" . $before . "},";
            }

            $js .= "success: function( data ){ $('" . $options['update'] . "').html(data);";

            if (isset($options['after'])) {
                $after = str_replace('"', "'", $options['after']);
                $js .= $after;
            }

            $js .= "}";

            if (isset($options['complete'])) {
                $complete = str_replace('"', "'", $options['complete']);
                $js .= ",complete: function(){" . $complete . "},";
            }

            $js .= "});";

            return $js;
        };
    }

     /**
     * Generate Js function to send ajax form data.
     *
     * @param array $options
     */
    public function submitCall($options = array())
    {
    	return function ($options) {
    		$type = isset($options['type']) ? $options['type'] : "POST";
    		$dataType = isset($options['dataType']) ? $options['dataType'] : "html";
    		$js = "$.ajax({
		    		url: '" . $options['url'] . "',
		    		type: '" . $type . "',
		    		data: $(this.form.elements).serializeArray(),
		    		dataType: '" . $dataType . "',";
    		if (isset($options['before'])) {
    			$before = str_replace('"', "'", $options['before']);
    			$js .= "beforeSend: function(){" . $before . "},";
    		}
    		$js .= "success: function( data ){";
    		if (isset($options['success'])) {
    			$success = str_replace('"', "'", $options['success']);
    			$js .= $success ;
    		}
    		if (isset($options['after'])) {
    			$after = str_replace('"', "'", $options['after']);
    			$js .= $after;
    		}

    		$js .= "}});";

    		return $js;
    	};
    }

    /**
     * Generate link tag with js function to send ajax request
     *
     * @param array $options
     */
    public function linkTag($options = array())
    {
        $jsRequest = $this->remoteCall();

        return function ($options) use($jsRequest)
        {
            $confirm = '';
            if (isset($options['confirm']) && $options['confirm'] === true) {

                $msg = "Are you sure you want to perform this action?";
                if(isset($options['confirm_msg'])) {
                    $msg = htmlentities(str_replace("'", '"', $options['confirm_msg']), ENT_QUOTES);
                }
            	$confirm .= "if(confirm('".$msg."'))" ;
            }
            $html = '';
            $html .= $options['text'];
            $html .= '';

            return $html;
        };
    }

     /**
     * Generate submit button tag with js function to send ajax form
     *
     * @param array $options
     */
    public function submitTag($options = array())
    {
    	$jsSubmit = $this->submitCall();

    	return function ($options) use($jsSubmit)
    	{
    		$confirm = '';
    		if (isset($options['confirm']) && $options['confirm'] === true) {

    			$msg = "Are you sure you want to perform this action?";
    			if(isset($options['confirm_msg'])) {
    				$msg = htmlentities(str_replace("'", '"', $options['confirm_msg']), ENT_QUOTES);
    			}
    			$confirm .= "if(confirm('".$msg."'))" ;
    		}
    		$html = '<button class="' . (isset($options['class']) ? $options['class'] : "") . '"
    		id="' . (isset($options['id']) ? $options['id'] : "") . '"
    		onclick="' .$confirm. call_user_func($jsSubmit, $options) . 'return false;">';
    		$html .= $options['text'];
    		$html .= '</button>';

    		return $html;
    	};
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'mabs_jquery_ajax';
    }
}


<?php

namespace Rswork\Silex\Extension;

use Symfony\Component\Routing\Generator\UrlGenerator;

/**
 * Twig extension for the bundle.
 */
class Combine extends \Twig_Extension
{

    private $app;

    public function __construct(\Pimple $app)
    {
        $this->app = $app;
    }

    /**
     * Getter.
     *
     * @return array
     */
    public function getFunctions()
    {
        return array(
            'combine_url' => new \Twig_Function_Method($this, 'getCombineUrl'),
        );
    }

    /**
     * Getter.
     *
     * @return string
     */
    public function getCombineUrl()
    {
        $combine = $this->app['combine'];

        $args = func_get_args();

        if( isset( $args[0] ) ) {
            $files = $args[0];
        } else {
            $files = '';
        }

        if( is_array( $files ) ) {
            $files = implode( $files, ',' );
        }

        if( isset( $args[1] ) ) {
            $base = $args[1];
        } else {
            $base = '';
        }

        return $this
            ->app['url_generator']
            ->generate(
                $this->app['combine.bind_to'],
                array(
                    'f'=>$files,
                    'b'=>$base,
                ),
                UrlGenerator::ABSOLUTE_URL
            )
        ;
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'combine_extension';
    }
}


<?php

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

namespace EmailControl;

use ConnCrud\Read;
use Helpers\Check;
use SparkPost\SparkPost;
use GuzzleHttp\Client;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;

class Email
{
    private $assunto;
    private $mensagem;
    private $html;
    private $template;
    private $destinatarioNome;
    private $destinatarioEmail;
    private $anexo;
    private $variables;
    private $remetenteEmail;
    private $remetenteNome;

    private $replyToEmail;
    private $replyToNome;

    private $error;
    private $result;

    public function __construct()
    {
        if (defined("EMAIL")) {
            $this->remetenteNome = "Contato" . (defined('SITENAME') ? " " . SITENAME : "");
            $this->remetenteEmail = EMAIL;
            $this->destinatarioNome = "";
            $this->variables = [];
            $this->anexo = [];
            $this->assunto = "Contato " . (defined('SITENAME') ? SITENAME : "");
        }
    }

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

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

    /**
     * @param string $nome
     */
    public function setDestinatarioNome(string $nome)
    {
        $this->destinatarioNome = trim(strip_tags($nome));
    }

    /**
     * @param int $template
     */
    public function setTemplate(int $template)
    {
        $this->template = $template;
    }

    /**
     * Seta Variáveis para os templates
     * @param array $variables
     */
    public function setVariables(array $variables = [])
    {
        $this->variables = array_merge($this->variables, $variables);
    }

    /**
     * @param string|array $email
     */
    public function setDestinatarioEmail($email)
    {
        if (!empty($email)) {
            if (is_array($email)) {
                if (isset($email['email'])) {
                    if (!empty($email['name'])) {
                        $this->destinatarioEmail[] = ['address' => [
                            'name' => trim(strip_tags($email['name'])),
                            'email' => trim($email['email'])
                        ]];
                    } else {
                        $this->destinatarioEmail[] = ['address' => ['name' => $this->prepareNameFromEmail($email['email']), 'email' => trim($email['email'])]];
                    }
                } else {
                    foreach ($email as $item) {
                        if (is_array($item) && !empty($item['email']) && Check::email($item['email'])) {
                            if (!empty($item['name'])) {
                                $this->destinatarioEmail[] = ['address' => [
                                    'name' => trim(strip_tags($item['name'])),
                                    'email' => trim(strip_tags($item['email']))
                                ]];
                            } else {
                                $this->destinatarioEmail[] = ['address' => ['email' => trim($item['email'])]];
                            }
                        } elseif (is_string($item) && Check::email($item)) {
                            $this->destinatarioEmail[] = ['address' => ['name' => $this->prepareNameFromEmail($item), 'email' => trim($item)]];
                        }
                    }
                }
            } elseif (is_string($email) && Check::email($email)) {
                $this->destinatarioEmail[] = ['address' => ['name' => $this->prepareNameFromEmail($email), 'email' => trim($email)]];
            }
        }
    }

    /**
     * @param string $emailRemetente
     */
    public function setRemetenteEmail(string $emailRemetente)
    {
        $this->remetenteEmail = trim(strip_tags($emailRemetente));
    }

    /**
     * @param string $nomeRemetente
     */
    public function setRemetenteNome(string $nomeRemetente)
    {
        $this->remetenteNome = trim(strip_tags($nomeRemetente));
    }

    /**
     * @param string $replyToEmail
     */
    public function setReplyToEmail(string $replyToEmail)
    {
        $this->replyToEmail = trim(strip_tags($replyToEmail));
    }

    /**
     * @param string $replyToNome
     */
    public function setReplyToNome(string $replyToNome)
    {
        $this->replyToNome = trim(strip_tags($replyToNome));
    }

    /**
     * Recebe string json com informações do(s) anexo(s)
     * @param string $file
     */
    public function setAnexo(string $file)
    {
        $anexos = json_decode($file, true);
        if (is_array($anexos)) {
            foreach ($anexos as $anexo) {
                $this->anexo[] = [
                    "name" => $anexo['name'],
                    "type" => $anexo['type'],
                    "data" => base64_encode(file_get_contents(PATH_HOME . $anexo['url']))
                ];
            }
        }
    }

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

    /**
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * @return mixed
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * Envia Email
     */
    public function enviar()
    {
        if (!empty($this->assunto) && !empty($this->destinatarioEmail) && !empty($this->mensagem)) {
            //informações básicas presentes

            $this->html = $this->getTemplateHtml();

            //verifica meio de envio
            if (defined("EMAILKEY") && !empty(EMAILKEY) && defined("EMAIL") && !empty(EMAIL)) {

                //sparkpost ativo no sistema, utiliza-o para envio
                $this->sparkPost();

            } else {
                if (defined("EMAIL") && !empty(EMAIL))
                    $this->error = "Nenhum sistema de envio de email ativo. Vá em Integrações no menu de Dashboard e Ative SparkPost.";
                else
                    $this->error = "Email de Envio não identificado.";
            }
        }
    }

    /**
     * Obtém o HTML do email
     *
     * @return string
     */
    public function getEmailContent(): string
    {
        if (!empty($this->assunto) && !empty($this->destinatarioEmail) && !empty($this->mensagem))
            return $this->getTemplateHtml();

        return "";
    }

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

    private function sparkPost()
    {
        try {
            $httpClient = new GuzzleAdapter(new Client());
            $sparky = new SparkPost($httpClient, ['key' => EMAILKEY, 'async' => false]);

            $response = $sparky->transmissions->post([
                'content' => [
                    'from' => ['name' => $this->remetenteNome, 'email' => $this->remetenteEmail],
                    'subject' => $this->assunto,
                    'html' => $this->html,
                    'text' => trim(strip_tags($this->mensagem)),
                    'attachments' => $this->anexo,
                ],
                'recipients' => $this->destinatarioEmail
            ]);

            if ($response->getStatusCode() === 200)
                $this->result = $response->getBody()['results']['id'];
            else
                $this->error = $response->getStatusCode();

        } catch (\Exception $e) {
            $this->error = 'Erro Inexperado ao enviar';
        }
    }

    /**
     * Retorna estrutura HTML com variáveis aplicada no template
     * @return string
     */
    private function getTemplateHtml(): string
    {
        if ($this->template) {
            $read = new Read();
            $read->exeRead("email_template", "WHERE id = :id", "id={$this->template}");
            if ($read->getResult()) {
                $url = json_decode($read->getResult()[0]['template'], true)[0]['url'];
                $template = pathinfo($url, PATHINFO_BASENAME);
                $dirTemplate = pathinfo($url, PATHINFO_DIRNAME);
            }
        }

        if (!isset($template)) {
            $dirTemplate = PATH_HOME . VENDOR . "email-control/public/tpl/model";
            $template = "content.tpl";
        }

        $this->setVariables($this->getVariablesDefault());

        $this->variables['content'] = $this->getContent($dirTemplate, $template);

        return $this->getHtml();

    }

    /**
     * Retorna o Content (corpo) do email
     * @param string $dir
     * @param string $template
     */
    private function getContent(string $dir, string $template): string
    {
        try {
            $smart = new \Smarty();
            $smart->setTemplateDir($dir);

            foreach ($this->variables as $name => $value)
                $smart->assign($name, $value);

            $retorno = $smart->fetch($template);
            $smart->clearAllAssign();

            return $retorno;

        } catch (\Exception $e) {
            $this->error = "Smarty Template Error: {$e->getMessage()}";
        }

        return "";
    }

    /**
     * Obtém o Html para email
     * @return string
     */
    private function getHtml(): string
    {
        try {
            $smart = new \Smarty();
            $smart->setTemplateDir(PATH_HOME . VENDOR . "email-control/public/tpl/model");

            foreach ($this->variables as $name => $value)
                $smart->assign($name, $value);

            $retorno = $smart->fetch("base.tpl");
            $smart->clearAllAssign();

            return $retorno;

        } catch (\Exception $e) {
            $this->error = "Smarty Template Error: {$e->getMessage()}";
        }

        return "";
    }

    /**
     * Retorna dados padrão para passar para templates
     * @return array
     */
    private function getVariablesDefault(): array
    {
        list($color, $background) = $this->getColorTheme();
        return [
            "assunto" => $this->assunto,
            "mensagem" => $this->mensagem,
            "destinatarioEmail" => $this->destinatarioEmail[0]['address']['email'],
            "destinatarioNome" => $this->destinatarioNome,
            "remetenteEmail" => $this->remetenteEmail,
            "remetenteNome" => $this->remetenteNome,
            "sitename" => defined('SITENAME') ? SITENAME : "",
            "home" => defined('HOME') ? HOME : "",
            "sitedesc" => defined('SITEDESC') ? SITEDESC : "",
            "sitesub" => defined('SITESUB') ? SITESUB : "",
            "logo" => defined('LOGO') ? HOME . LOGO : "",
            "favicon" => defined('FAVICON') ? HOME . FAVICON : "",
            "date" => date('d/m/Y H:i', strtotime('now')),
            "theme" => $color,
            "themeBackground" => $background
        ];
    }

    /**
     * Retorna um nome a partir do email
     * @param string $email
     * @return string
     */
    private function prepareNameFromEmail(string $email): string
    {
        return ucwords(str_replace(['.', '_'], ' ', explode('@', $email)[0]));
    }

    private function getColorTheme()
    {
        if (file_exists(PATH_HOME . "public/assets/theme.min.css")) {
            $theme = file_get_contents(PATH_HOME . "public/assets/theme.min.css");
            if (preg_match('/\.theme{/i', $theme)) {
                $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"];
    }
}


<?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: InputPicker.php 3984 2011-04-28 02:54:31Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Easy\Element\InputText;

/**
 * InputPicker class is element for input picker
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class InputPicker extends InputText
{

    public $valuePicker;
    public $pickerMap;
    public $updateForm;

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    public function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        // if no class name, add default class name. i.e. NewRecord => ObjName.NewRecord
        $this->valuePicker = isset($xmlArr["ATTRIBUTES"]["VALUEPICKER"]) ? $xmlArr["ATTRIBUTES"]["VALUEPICKER"] : null;
        $this->valuePicker = $this->prefixPackage($this->valuePicker);
        $this->pickerMap = isset($xmlArr["ATTRIBUTES"]["PICKERMAP"]) ? $xmlArr["ATTRIBUTES"]["PICKERMAP"] : null;
        $this->updateForm = isset($xmlArr["ATTRIBUTES"]["UPDATEFORM"]) ? $xmlArr["ATTRIBUTES"]["UPDATEFORM"] : "N";
    }

    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $this->defaultValueRename = "N";
        $this->enabled = 'N';
        $sHTML = parent::render();

        // sample picker call CallFunction('easy.f_AttendeeListChild.LoadPicker(view,form,elem)','Prop_Window');
        if ($this->valuePicker != null) {
            $function = $this->formName . ".LoadPicker($this->valuePicker,$this->objectName)";
            $sHTML .= " <input type=button onClick=\"Openbizx.CallFunction('$function');\" value=\"...\" style='width:20px;' />";
        }

        return $sHTML;
    }

    public function getEvents()
    {
        $events = parent::getEvents();
        $events['onclick'] .= "Openbizx.CallFunction('" . $this->formName . ".LoadPicker($this->valuePicker,$this->objectName)')";
        return $events;
    }

    public function matchRemoteMethod($method)
    {
        return ($method == "loadpicker");
    }

}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Core;

/**
 * Localization class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class Localization
{
    /**
     * @var array
     */
    protected $files = [];

    /**
     * @var array
     */
    protected $lines = [];

    /**
     * @var string
     */
    protected $default_language;

    /**
     * @param string $default_language
     */
    public function __construct($default_language = 'en')
    {
        $this->default_language = $default_language;
    }

    //TODO: добавить обработку массивов в $file
    //TODO: добавить обработку абсолютных путей в $file
    /**
     * @param string $file
     * @param string $module
     * @param string $language
     * @param boolean $overwrite
     *
     * @throws \RuntimeException
     *
     * @return boolean
     */
    public function load($file, $module = 'application', $language = null, $overwrite = false)
    {
        if (!$overwrite && isset($this->files[$module][$language][$file])) {
            return $this;
        }

        $module = strtolower($module);
        switch ($module) {
            //TODO: ucfirst($module) for more than 1 word?
            case 'core':
                $file_path = dirname(__DIR__) . '/' . ucfirst($module) . '/localization/' . $language . '/' . $file . '.php';
                $default_file_path = dirname(__DIR__) . '/' . ucfirst($module) . '/localization/' . $this->default_language . '/' . $file . '.php';
                break;
            case 'application':
                $file_path = APPLICATION_PATH . 'localization/' . $language . '/' . $file . '.php';
                $default_file_path = APPLICATION_PATH . 'localization/' . $this->default_language . '/' . $file . '.php';
                break;
            default:
                $file_path = dirname(__DIR__) . '/Modules/' . ucfirst($module) . '/localization/' . $language . '/' . $file . '.php';
                $default_file_path = dirname(__DIR__) . '/Modules/' . ucfirst($module) . '/localization/' . $this->default_language . '/' . $file . '.php';
        }

        if (file_exists($file_path)) {
            if (!isset($this->lines[$language])) {
                $this->lines[$language] = [];
            }

            //TODO: correct include_once
            $lines = include $file_path;
            $this->lines[$language] = array_merge($this->lines[$language], $lines);

            return $language;
        } elseif (file_exists($default_file_path)) {
            if (!isset($this->lines[$this->default_language])) {
                $this->lines[$this->default_language] = [];
            }

            $lines = include $default_file_path;
            $this->lines[$this->default_language] = array_merge($this->lines[$this->default_language], $lines);

            return $this->default_language;
        } else {
            throw new \RuntimeException('Don`t find language file');
        }
    }

    /**
     * @param string $line_name
     * @param string $language
     * @param array $params
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    public function get($line_name, $language = null, array $params = [])
    {
        $params_temp = [];
        foreach ($params as $param_name => $param) {
            $params_temp[':' . $param_name . ':'] = $param;
        }
        unset($param);

        if (isset($this->lines[$language][$line_name])) {
            return strtr($this->lines[$language][$line_name], $params_temp);
        } elseif (isset($this->lines[$this->default_language][$line_name])) {
            return strtr($this->lines[$this->default_language][$line_name], $params_temp);
        } else {
            throw new \RuntimeException('Don`t find language line');
        }
    }
}


<?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.service
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: reportService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Service;

use Openbizx\Object\MetaObject;
use Openbizx\Helpers\TemplateHelper;

/**
 * reportService class is the plug-in service of generate report for BizDataobj
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class reportService extends MetaObject
{
    public $targetReportPath; // = "D:\\Tomcat5\\webapps\\birt-viewer\\report\\";
    public $rptTemplate; // = "dataobj.rptdesign.tpl";
    public $birtViewer; // = "http://localhost:8080/birt-viewer";

    /**
     * Initialize reportService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->targetReportPath = isset($xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["TARGETREPORTPATH"]) ? $xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["TARGETREPORTPATH"] : null;
        $this->rptTemplate = isset($xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["REPORTTEMPLATE"]) ? $xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["REPORTTEMPLATE"] : null;
        $this->birtViewer = isset($xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["BIRTVIEWER"]) ? $xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["BIRTVIEWER"] : null;
    }

    /**
     * render the report output
     *
     * @param string $objName object name which is the bizform name
     * @return void
     */
    public function render($objName)
    {
        // get the current UI bizobj
        $bizform = Openbizx::getObject($objName);    // get the existing bizform object
        $bizobj = $bizform->getDataObj();

        $h=opendir($this->targetReportPath);
        if (!$h)
        {
            echo "cannot read dir ".$this->targetReportPath;
            exit;
        }
        // create a tmp csv file for hold the data, then feed csv file to report engine
        $uid = $this->getUniqueString();
        $tmpfname = $this->targetReportPath . $uid . ".csv";
        //echo "csv file is at $tmpfname.
";
        $fp = fopen($tmpfname, 'w');

        $keyList = $bizform->recordRow->GetSortControlKeys();
        $fieldNames = array();
        foreach($keyList as $key)
        {
            $fieldNames[] = $bizform->GetControl($key)->bizFieldName;
        }
        fputcsv($fp, $fieldNames);

        $recList = $bizobj->directFetch();
        foreach ($recList as $recArray)
        {
            unset($fieldValues);
            $fieldValues = array();
            $line = "";
            foreach($keyList as $key)
            {
                $fieldValues[] = $recArray[$bizform->GetControl($key)->bizFieldName];
            }
            fputcsv($fp, $fieldValues);
        }

        fclose($fp);

        $i = 0;
        foreach($keyList as $key)
        {
            $rpt_fields[$i]["name"] = $bizform->GetControl($key)->bizFieldName;
            $rpt_fields[$i]["type"] = $bizobj->getField($rpt_fields[$i]["name"])->type;
            $i++;
        }

        // dataobj.rptdesign.tpl
        // $rpt_data_dir, $rpt_title, $rpt_csv_file, $rpt_fields[](name,type)
        $smarty = TemplateHelper::getSmartyTemplate();
        $smarty->assign("rpt_data_dir", $this->targetReportPath);
        $smarty->assign("rpt_title", $bizform->title);
        $smarty->assign("rpt_csv_file", basename($tmpfname));
        $smarty->assign("rpt_fields", $rpt_fields);
        $reportContent = $smarty->fetch($this->rptTemplate);

        $tmpRptDsgn = $this->targetReportPath . $uid . ".rptdesign";
        //echo "temp rpt design file is at $tmpRptDsgn.
";
        $fp = fopen($tmpRptDsgn, 'w');
        fwrite($fp, $reportContent);
        fclose($fp);

        ob_clean();
        $designFileName = $uid . ".rptdesign";
        $content = "
";
        $content .= "Reports can be viewed as ";
        $content .= "
birtViewer."/run?__report=report\\$designFileName' target='__blank'>HTML report
";
        $content .= "
birtViewer."/run?__report=report\\$designFileName&__format=pdf' target='__blank'>PDF report
";
        $content .= "
birtViewer."/frameset?__report=report\\$designFileName' target='__blank'>Interactive report
";
        $content .= "
";

        echo $content;
        exit;
    }

    /**
     * Clear files on specified directory
     *
     * @param string $dir
     * @param number $seconds
     */
    public function cleanFiles($dir, $seconds)
    {
        //Delete temporary files
        $currentTime = time();
        $dirHandle = opendir($dir);
        while($file = readdir($dirHandle))
        {
            $path=$dir.'/'.$file;
            if($currentTime - filemtime($path) > $seconds)
                unlink($path);
        }
        closedir($dirHandle);
    }

    /**
     * Get unique string by time and MD5
     *
     * @return string
     */
    public function getUniqueString()
    {
        $mdy = date("mdy");
        $hms = date("His");
        $rightnow = $mdy.$hms;

        return md5($rightnow);
    }
}


<?php

namespace Askedio\Laravelcp\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Str;

trait HasRoleAndPermission
{
    /**
     * Property for caching roles.
     *
     * @var \Illuminate\Database\Eloquent\Collection|null
     */
    protected $roles;

    /**
     * Property for caching permissions.
     *
     * @var \Illuminate\Database\Eloquent\Collection|null
     */
    protected $permissions;

    /**
     * User belongs to many roles.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(config('rbac.models.role'))->withTimestamps()->withPivot('granted');
    }

    /**
     * Get only Granted Roles
     */
    public function grantedRoles() {
        return $this->roles()->wherePivot('granted', true);
    }

    /**
     * Get only Denied Roles
     */
    public function deniedRoles() {
        return $this->roles()->wherePivot('granted', false);
    }

    /**
     * User belongs to many permissions.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function userPermissions()
    {
        return $this->belongsToMany(config('rbac.models.permission'))->withTimestamps()->withPivot('granted');
    }

    /**
     * Get only Granted Permissions
     */
    public function grantedPermissions() {
        return $this->userPermissions()->wherePivot('granted', true);
    }

    /**
     * Get only Denied Permissions
     */
    public function deniedPermissions() {
        return $this->userPermissions()->wherePivot('granted', false);
    }

    /**
     * Get all roles as collection.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getRoles()
    {
        if(!$this->roles){
            $this->roles = $this->grantedRoles()->get();

            $deniedRoles = $this->deniedRoles()->get();
            foreach($deniedRoles as $role)
                $deniedRoles = $deniedRoles->merge($role->descendants());

            foreach($this->roles as $role)
                if(!$deniedRoles->contains($role))
                    $this->roles = $this->roles->merge($role->descendants());

            $this->roles = $this->roles->filter(function($role) use ($deniedRoles){
                return !$deniedRoles->contains($role);
            });
        }
        return  $this->roles;
    }

    /**
     * Get all permissions from roles.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function rolePermissions()
    {

        $permissions = new Collection();
        foreach ($this->getRoles() as $role)
            $permissions = $permissions->merge($role->permissions);
        return $permissions;
    }

    /**
     * Get all permissions as collection.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getPermissions()
    {
        if(!$this->permissions){
            $rolePermissions = $this->rolePermissions();
            $userPermissions = $this->grantedPermissions()->get();

            $permissions = $rolePermissions->merge($userPermissions);
            $deniedPermissions =$this->deniedPermissions()->get();

            $this->permissions = $permissions->filter(function($permission) use ($deniedPermissions)
            {
                return !$deniedPermissions->contains($permission);
            });
        }
        return $this->permissions;
    }
    /**
     * Check if the user has a role or roles.
     *
     * @param int|string|array $role
     * @param bool $all
     * @return bool
     */
    public function is($role, $all = false)
    {
        if ($this->isPretendEnabled()) {
            return $this->pretend('is');
        }

        return $this->{$this->getMethodName('is', $all)}($this->getArrayFrom($role));
    }

    /**
     * Check if the user has at least one role.
     *
     * @param array $roles
     * @return bool
     */
    protected function isOne(array $roles)
    {
        foreach ($roles as $role) {
            if ($this->hasRole($role)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if the user has all roles.
     *
     * @param array $roles
     * @return bool
     */
    protected function isAll(array $roles)
    {
        foreach ($roles as $role) {
            if (!$this->hasRole($role)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check if the user has role.
     *
     * @param int|string $role
     * @return bool
     */
    protected function hasRole($role)
    {
        return $this->getRoles()->contains(function ($key, $value) use ($role) {
            return $role == $value->id || Str::is($role, $value->slug);
        });
    }

    /**
     * Check if the user has a permission or permissions.
     *
     * @param int|string|array $permission
     * @param bool $all
     * @return bool
     */
    public function can($permission, $all = false)
    {
        if ($this->isPretendEnabled()) {
            return $this->pretend('can');
        }

        return $this->{$this->getMethodName('can', $all)}($this->getArrayFrom($permission));
    }

    /**
     * Check if the user has at least one permission.
     *
     * @param array $permissions
     * @return bool
     */
    protected function canOne(array $permissions)
    {
        foreach ($permissions as $permission) {
            if ($this->hasPermission($permission)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if the user has all permissions.
     *
     * @param array $permissions
     * @return bool
     */
    protected function canAll(array $permissions)
    {
        foreach ($permissions as $permission) {
            if (!$this->hasPermission($permission)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check if the user has a permission.
     *
     * @param int|string $permission
     * @return bool
     */
    protected function hasPermission($permission)
    {
        return $this->getPermissions()->contains(function ($key, $value) use ($permission) {
            return $permission == $value->id || Str::is($permission, $value->slug);
        });
    }

    /**
     * Check if the user is allowed to manipulate with entity.
     *
     * @param string $providedPermission
     * @param \Illuminate\Database\Eloquent\Model $entity
     * @param bool $owner
     * @param string $ownerColumn
     * @return bool
     */
    public function allowed($providedPermission, Model $entity, $owner = true, $ownerColumn = 'user_id')
    {
        if ($this->isPretendEnabled()) {
            return $this->pretend('allowed');
        }

        if ($owner === true && $entity->{$ownerColumn} == $this->id) {
            return true;
        }

        return $this->isAllowed($providedPermission, $entity);
    }

    /**
     * Check if the user is allowed to manipulate with provided entity.
     *
     * @param string $providedPermission
     * @param \Illuminate\Database\Eloquent\Model $entity
     * @return bool
     */
    protected function isAllowed($providedPermission, Model $entity)
    {
        foreach ($this->getPermissions() as $permission) {
            if ($permission->model != '' && get_class($entity) == $permission->model
                && ($permission->id == $providedPermission || $permission->slug === $providedPermission)
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Attach role to a user.
     *
     * @param int|\Askedio\Laravelcp\Models\Role $role
     * @param bool $granted
     * @return bool|null
     */
    public function attachRole($role, $granted = TRUE)
    {
        if($granted)
            return (!$this->grantedRoles()->get()->contains($role)) ? $this->roles()->attach($role, array('granted' => TRUE)) : true;
        else
            return (!$this->deniedRoles()->get()->contains($role)) ? $this->roles()->attach($role, array('granted' => FALSE)) : true;
    }

    /**
     * Detach role from a user.
     *
     * @param int|\Askedio\Laravelcp\Models\Role $role
     * @return int
     */
    public function detachRole($role)
    {
        return $this->roles()->detach($role);
    }

    /**
     * Detach all roles from a user.
     *
     * @return int
     */
    public function detachAllRoles()
    {
        return $this->roles()->detach();
    }

    /**
     * Attach permission to a user.
     *
     * @param int|\Askedio\Laravelcp\Models\Permission $permission
     * @param bool $granted
     * @return bool|null
     */
    public function attachPermission($permission, $granted = true)
    {
        if($granted)
            return (!$this->grantedPermissions()->get()->contains($permission)) ? $this->userPermissions()->attach($permission, array('granted' => TRUE)) : true;
        else
            return (!$this->deniedPermissions()->get()->contains($permission)) ? $this->userPermissions()->attach($permission, array('granted' => FALSE)) : true;

    }

    /**
     * Detach permission from a user.
     *
     * @param int|\Askedio\Laravelcp\Models\Permission $permission
     * @return int
     */
    public function detachPermission($permission)
    {
        return $this->userPermissions()->detach($permission);
    }

    /**
     * Detach all permissions from a user.
     *
     * @return int
     */
    public function detachAllPermissions()
    {
        return $this->userPermissions()->detach();
    }

    /**
     * Check if pretend option is enabled.
     *
     * @return bool
     */
    private function isPretendEnabled()
    {
        return (bool) config('roles.pretend.enabled');
    }

    /**
     * Allows to pretend or simulate package behavior.
     *
     * @param string $option
     * @return bool
     */
    private function pretend($option)
    {
        return (bool) config('roles.pretend.options.' . $option);
    }

    /**
     * Get method name.
     *
     * @param string $methodName
     * @param bool $all
     * @return string
     */
    private function getMethodName($methodName, $all)
    {
        return ((bool) $all) ? $methodName . 'All' : $methodName . 'One';
    }

    /**
     * Get an array from argument.
     *
     * @param int|string|array $argument
     * @return array
     */
    private function getArrayFrom($argument)
    {
        return (!is_array($argument)) ? preg_split('/ ?[,|] ?/', $argument) : $argument;
    }

    /**
     * Handle dynamic method calls.
     *
     * @param string $method
     * @param array $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        if (starts_with($method, 'is')) {
            return $this->is(snake_case(substr($method, 2), config('roles.separator')));
        } elseif (starts_with($method, 'can')) {
            return $this->can(snake_case(substr($method, 3), config('roles.separator')));
        } elseif (starts_with($method, 'allowed')) {
            return $this->allowed(snake_case(substr($method, 7), config('roles.separator')), $parameters[0], (isset($parameters[1])) ? $parameters[1] : true, (isset($parameters[2])) ? $parameters[2] : 'user_id');
        }

        return parent::__call($method, $parameters);
    }
}


<?php

namespace Kitpages\UtilBundle\Service;

/**
 * @example
 * $hash = $tool->getHash($userId, $userName, $reference, array(toto));
 * if ($tool->checkHash($hash, $userId, $userName, $reference, array(toto)) ) {
 *     // do something
 * }
 */
class Hash
{
    /** @var null|string secret passphrase */
    protected $secret = null;

    /**
     * @param string $secret secret pass phrase used as salt for encoding
     */
    public function __construct(
        $secret
    )
    {
        $secret = preg_replace("/[^a-zA-Z0-9]/","x",$secret);
        $this->secret = $secret;
    }

    /**
     * return a hash for a list of params
     * @param mixed variable length param list
     */
    public function getHash()
    {
        $paramString = $this->getParamString(func_get_args());
        $encrypted = crypt($paramString, '$2a$07$'.$this->secret.'$');
        //echo "encrypted=$encrypted ; paramString=$paramString";
        return $encrypted;
    }

    /**
     * @param $hash
     * @param mixed variable length param list
     * @return bool
     */
    public function checkHash()
    {
        $args = func_get_args();
        $hash = array_shift($args);
        $paramString = $this->getParamString($args);
        if ( crypt($paramString, $hash) === $hash ) {
            return true;
        }
        return false;
    }

    protected function getParamString($args)
    {
        $paramList = array();
        foreach ($args as $arg) {
            if (!is_array($arg)) {
                $argTab = array($arg);
            }
            else {
                $argTab = $arg;
            }
            foreach ($argTab as $arg) {
                if (!$arg) {
                    $arg = "empty";
                }
                $arg = (string)$arg;
                $paramList[] = $arg;
            }
        }
        return implode("-", $paramList);
    }
}


<?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.service
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: accessService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

/* configuration
<PluginService ...>
   <access-constraint>
     <view-collection>
       <view name="view1">
         <role name="admin"/>
         <role name="member"/>
       </view>
       <view name="reg_expr"/>
     </view-collection>
   </access-constraint>
</PluginService ...>
*/

namespace Openbizx\Service;

use Openbizx\Object\MetaIterator;

/**
 * accessService class is the plug-in service of handling role based view access control
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class accessService
{
    private $_configFile = "accessService.xml";
    private $_restrictedViewList;

    /**
     * Initialize accessService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        $viewCollection = $xmlArr["PLUGINSERVICE"]["ACCESS-CONSTRAINT"]["VIEW-COLLECTION"];
        $this->_restrictedViewList = new MetaIterator($xmlArr["PLUGINSERVICE"]["ACCESS-CONSTRAINT"]["VIEW-COLLECTION"]["VIEW"],"RestrictedView");
    }

    /**
     * Allow view access
     *
     * @param string $viewName
     * @param <type> $role
     * @return boolean
     */
    public function allowViewAccess($viewName, $role=null)
    {
        if (!$role)
            $role = "";

        $view = $this->getMatchView($viewName);
        if (!$view)
            return true;

        $roleList = $view->getRoleList();
        if (!$roleList)
            return true;
        if ($roleList->get($role))
            return true;

        return false;
    }

    /**
     * Get match view
     *
     * @param string $viewName
     * @return WebPage|null
     */
    protected function getMatchView($viewName)
    {
        /* @var $viewObj WebPage */
        $viewObj = $this->_restrictedViewList->get($viewName);
        if ($viewObj)
            return $viewObj;
        foreach ($this->_restrictedViewList as $view => $viewObj)
        {
            $preg_view = "/".$view."/";
            if (preg_match($preg_view, $viewName))
            {
                return $viewObj;
            }
        }
        return null;
    }
}

/**
 * RestrictedView class
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class RestrictedView
{
    /**
     * Name of view
     *
     * @var string
     */
    public $objectName;

    /**
     * List of role
     *
     * @var MetaIterator
     */
    private $_roleList;

    /**
     * Initialize RestrictedView with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    public function __construct($xmlArr)
    {
        $this->objectName = $xmlArr["ATTRIBUTES"]["NAME"];
        $this->_roleList = new MetaIterator($xmlArr["ROLE"],"RestrictedRole");
    }

    /**
     * Get view name
     *
     * @return string the view name
     */
    public function getViewName()
    {
        return $this->objectName;
    }

    /**
     * Get list of role
     *
     * @return MetaIterator
     */
    public function getRoleList()
    {
        return $this->_roleList;
    }
}

/**
 * RestrictedRole class
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class RestrictedRole
{
    /**
     * Role name
     *
     * @var string
     */
    public $objectName;

    /**
     * Initialize RestrictedView with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    public function __construct($xmlArr)
    {
        $this->objectName = $xmlArr["ATTRIBUTES"]["NAME"];
    }

    /**
     * Get role name
     *
     * @return string
     */
    public function getRoleName()
    {
        return $this->objectName;
    }
}
?>


<?php

namespace Environaut\Export\Formatter;

use Environaut\Report\IReport;
use Environaut\Export\Formatter\BaseFormatter;

/**
 * Writes all or specific groups of settings as a PHP file that may be included.
 */
class PhpSettingsWriter extends BaseFormatter
{
    /**
     * Writes all or specific groups of settings as a PHP file and
     * returns a message with some information about that.
     *
     * @param IReport $report report to take results (and settings) from
     *
     * @return string messages for CLI output
     */
    public function format(IReport $report)
    {
        $output = '';
        $params = $this->getParameters();

        $file = $params->get('location', 'environaut-config.php');
        $groups = $params->get('groups');
        $nested = $params->get('nested', true);

        if (is_writable($file)) {
            $output .= '<comment>Overwriting</comment> ';
        } else {
            $output .= 'Writing ';
        }

        if (empty($groups)) {
            $output .= 'all groups ';
        } else {
            $output .= 'group(s) "' . implode(', ', $groups) . '" ';
        }

        $output .= 'to file "<comment>' . $file . '</comment>"...';

        $default_template = <<<EOT
<?php return %settings\$s;
EOT;

        $template = $params->get('template', $default_template);

        $all_settings = $report->getSettingsAsArray($groups);

        $grouped_settings = array();
        foreach ($all_settings as $setting) {
            if ($nested === true) {
                $grouped_settings[$setting['group']][$setting['name']] = $setting['value'];
            } else {
                $grouped_settings[$setting['name']] = $setting['value'];
            }
        }

        $content = XmlSettingsWriter::vksprintf($template, array('settings' => var_export($grouped_settings, true)));

        $ok = file_put_contents($file, $content, LOCK_EX);

        if ($ok !== false) {
            $output .= '<info>ok</info>.';
        } else {
            $output .= '<error>FAILED</error>.';
        }

        return $output;
    }
}


<?php

namespace Nameless\Modules\Assets;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;

/**
 * Base AdminController controller class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class AssetsCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('assets:compile')
            ->setDescription('Compiled assets')
            ->addOption('package', 'p', InputOption::VALUE_REQUIRED, 'Compile package by name');;
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return null
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Start compiling assets: ' . date('Y-m-d H:i:s'));

        /** @var \Nameless\Core\Application $app */
        $app = $this->getApplication();
        /** @var \Nameless\Core\Container $app */
        $container = $app->getContainer();

        $container['environment'] = 'test';

        $assets     = $container['assets'];
        $dispatcher = $container['assets.dispatcher'];

        $altPackage = $input->getOption('package');
        if ($altPackage) {
            $this->compilePackage($altPackage, $assets['packages'][$altPackage], $assets, $dispatcher, $output);
        } else {
            foreach ($assets['packages'] as $package => $libs) {
                $this->compilePackage($package, $libs, $assets, $dispatcher, $output);
            }
        }

        $output->writeln("End compiling assets.\n");

        return null;
    }

    /**
     * @param string           $package
     * @param array            $libs
     * @param array            $assets
     * @param AssetsDispatcher $dispatcher
     * @param OutputInterface  $output
     */
    protected function compilePackage($package, $libs, $assets, $dispatcher, $output)
    {
        $css_package = [];
        $js_package  = [];

        $output->writeln("\tPackage: " . $package);

        foreach ($libs as $lib) {
            if (isset($assets['libs'][$lib]['css'])) {
                $output->writeln("\t\tAdded file: " . $assets['libs'][$lib]['css']);
                $css_package[] = $assets['libs'][$lib]['css'];
            }
            if (isset($assets['libs'][$lib]['less'])) {
                $output->writeln("\t\tAdded file: " . $assets['libs'][$lib]['less']);
                $css_package[] = $assets['libs'][$lib]['less'];
            }
            if (isset($assets['libs'][$lib]['js'])) {
                $output->writeln("\t\tAdded file: " . $assets['libs'][$lib]['js']);
                $js_package[] = $assets['libs'][$lib]['js'];
            }
        }

        $dispatcher->getAssets($package, $css_package);
        $dispatcher->getAssets($package, $js_package);
    }
}


<?php

namespace Environaut\Config\Reader\Dom;

/**
 * Environaut DOM document implementation with convenience wrapper methods
 * that by default use the Environaut configuration namespace for queries.
 */
class DomDocument extends \DOMDocument
{
    /**
     * Default namespace of Environaut configuration files.
     */
    const NAMESPACE_ENVIRONAUT_1_0 = 'http://mivesto.de/environaut/config/1.0';

    /**
     * Default namespace prefix for Environaut configuration files.
     */
    const NAMESPACE_PREFIX = 'ec';

    /**
     * @var \DOMXpath xpath instance for this document
     */
    protected $xpath = null;

    /**
     * @var string default URI used as namespace for the document
     */
    protected $default_namespace_uri;

    /**
     * @var string default prefix for the default namespace of this document
     */
    protected $default_namespace_prefix;

    /**
     * @var array map of DOM classes and our implementations of them
     */
    protected $class_map = array(
        'DOMAttr' => 'Environaut\Config\Reader\Dom\DomAttribute',
        'DOMDocument' => 'Environaut\Config\Reader\Dom\DomDocument',
        'DOMElement' => 'Environaut\Config\Reader\Dom\DomElement'
    );

    /**
     * Creates a new DomDocument instance.
     *
     * @param string $version
     * @param string $encoding
     */
    public function __construct($version = "1.0", $encoding = "UTF-8")
    {
        parent::__construct($version, $encoding);

        foreach ($this->class_map as $dom_class => $environaut_class) {
            $this->registerNodeClass($dom_class, $environaut_class);
        }

        $this->xpath = new \DOMXPath($this);
    }

    /**
     * Loads XML from a file and registers the Environaut configuration
     * namespace if the XML document is an Environaut configuration file.
     *
     * @param string $filename xml file to load
     * @param int $options libXml flags to use for loading (like LIBXML_NOCDATA etc.)
     *
     * @return bool true on success; false on error
     *
     * @throws \DOMException in case of errors loading the document from the given file
     */
    public function load($filename, $options = 0)
    {
        $user_error_handling = $this->enableErrorHandling();

        $success = parent::load($filename, $options);

        $this->handleErrors(
            'Loading the document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the mentioned errors.',
            $user_error_handling
        );

        $this->refreshXpath();

        return $success;
    }

    /**
     * Loads XML from a string and registers the Environaut configuration
     * namespace if the XML document is an Environaut configuration file.
     *
     * @param string $source xml string to load
     * @param int $options libXml flags to use for loading (like LIBXML_NOCDATA etc.)
     *
     * @return bool true on success; false on error
     *
     * @throws \DOMException in case of errors loading the document from the given string
     */
    public function loadXml($source, $options = 0)
    {
        $user_error_handling = $this->enableErrorHandling();

        $success = parent::loadXML($source, $options);

        $this->handleErrors(
            'Loading the document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the mentioned errors.',
            $user_error_handling
        );

        $this->refreshXpath();

        return $success;
    }

    /**
     * Validates the current document according to the given schema file.
     *
     * @param string $filename path to the schema file
     *
     * @return bool true on success
     *
     * @throws \DomException in case of validation errors or non-readable file
     */
    public function schemaValidate($filename)
    {
        if (!is_readable($filename)) {
            throw new \DOMException("Schema file is not readable: $filename");
        }

        $user_error_handling = $this->enableErrorHandling();

        $success = parent::schemaValidate($filename);

        $this->handleErrors(
            'Validating the document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the mentioned errors or use another schema file.',
            $user_error_handling
        );

        return $success;
    }

    /**
     * Validates the current document according to the given schema file content.
     *
     * @param string $source content of a schema file
     *
     * @return bool true on success
     *
     * @throws \DomException in case of validation errors or empty schema
     */
    public function schemaValidateSource($source)
    {
        if (empty($source)) {
            throw new \DOMException('Schema is empty.');
        }

        $user_error_handling = $this->enableErrorHandling();

        $success = parent::schemaValidateSource($source);

        $this->handleErrors(
            'Validating the document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the mentioned errors or use another schema.',
            $user_error_handling
        );

        return $success;
    }

    /**
     * Substitutes XIncludes present in the current document.
     *
     * @param int $options libXml flags to use for loading (like LIBXML_NOCDATA etc.)
     *
     * @return int number of XIncludes or false if no xincludes were found
     *
     * @throws \DOMException in case of errors xincluding content
     */
    public function xinclude($options = 0)
    {
        $user_error_handling = $this->enableErrorHandling();

        $number_of_xincludes = parent::xinclude($options);

        $this->handleErrors(
            'Resolving XInclude directives in the current document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the XInclude directives according to the mentioned errors.',
            $user_error_handling
        );

        return $number_of_xincludes;
    }

    /**
     * Returns the xpath instance that handles this document.
     *
     * @return \DOMXpath instance
     */
    public function getXpath()
    {
        return $this->xpath;
    }

    /**
     * Returns the nodeValue of the child element with the given name.
     *
     * @param string $element_name name of child element
     * @param \DomElement $reference_element reference element for child node iteration, default to documentElement
     *
     * @return mixed nodeValue or null if Environaut element with that name does not exist
     *
     * @throws \InvalidArgumentException if name is empty
     */
    public function getElementValue($element_name, $reference_element = null)
    {
        $element_name = trim($element_name);
        if (empty($element_name)) {
            throw new \InvalidArgumentException('Element name must not be empty.');
        }

        if (null === $reference_element) {
            $reference_element = $this->documentElement;
        }

        if ($this->isEnvironautDocument()) {
            foreach ($reference_element->childNodes as $node) {
                if ($node->nodeType == XML_ELEMENT_NODE &&
                    $node->localName == $element_name &&
                    $node->namespaceURI == $this->documentElement->namespaceURI
                ) {
                    return $node->nodeValue;
                }
            }
        }

        return null;
    }

    /**
     * Returns the DomElement with the given name.
     *
     * @param string $name of the element to get
     *
     * @return DomElement of that name or null if does not exist in the Environaut namespace
     */
    public function getElement($name)
    {
        if ($this->isEnvironautDocument()) {
            foreach ($this->documentElement->childNodes as $node) {
                if ($node->nodeType == XML_ELEMENT_NODE &&
                    $node->localName == $name &&
                    $node->namespaceURI == $this->documentElement->namespaceURI
                ) {
                    return $node;
                }
            }
        }

        return null;
    }

    /**
     * Set the default namespace that should be used when accessing elements via
     * convenience methods and bind it to the internal xpath instance.
     *
     * @param string $prefix default prefix to use
     * @param string $uri namespace URI
     */
    public function setDefaultNamespace($prefix = self::NAMESPACE_PREFIX, $uri = self::NAMESPACE_ENVIRONAUT_1_0)
    {
        $this->default_namespace_uri = $uri;
        $this->default_namespace_prefix = $prefix;

        $this->xpath->registerNamespace($prefix, $uri);
    }

    /**
     * Returns the default namespace URI used by Environaut.
     *
     * @return string default namespace URI
     */
    public function getDefaultNamespaceUri()
    {
        return $this->default_namespace_uri;
    }

    /**
     * Returns the default namespace prefix used by Environaut
     *
     * @return string default namespace prefix
     */
    public function getDefaultNamespacePrefix()
    {
        return $this->default_namespace_prefix;
    }

    /**
     * Returns whether the current document is an Environaut configuration file.
     *
     * @return bool true if it's an Environaut document; false otherwise
     */
    public function isEnvironautDocument()
    {
        return self::isEnvironautConfigurationDocument($this);
    }

    /**
     * Registers the default Environaut namespace on the internal xpath
     * instance of the given DomDocument instance.
     *
     * @param DOMDocument $doc document instance
     */
    public static function registerEnvironautNamespace(DOMDocument $doc)
    {
        $doc->getXpath()->registerNamespace(self::NAMESPACE_PREFIX, self::NAMESPACE_ENVIRONAUT_1_0);
    }

    /**
     * Returns whether the given document instance is an Environaut configuration file.
     *
     * @param DOMDocument $doc document to check
     *
     * @return bool true if it's an Environaut document; false otherwise
     */
    public static function isEnvironautConfigurationDocument(DOMDocument $doc)
    {
        return (
            $doc->documentElement &&
            $doc->documentElement->localName === 'environaut' &&
            $doc->documentElement->namespaceURI === self::NAMESPACE_ENVIRONAUT_1_0
        );
    }

    /**
     * Re-instantiates the internal xpath instance and then
     * registers the Environaut config namespace if necessary.
     */
    protected function refreshXpath()
    {
        unset($this->xpath);

        $this->xpath = new \DOMXPath($this);

        if ($this->isEnvironautDocument()) {
            $this->setDefaultNamespace(self::NAMESPACE_PREFIX, self::NAMESPACE_ENVIRONAUT_1_0);
        }
    }

    /**
     * Disables libXml errors to let us handle errors by ourselves.
     *
     * @return bool whether or not the internal error handling was enabled before
     */
    protected function enableErrorHandling()
    {
        $user_error_handling = libxml_use_internal_errors(true);
        libxml_clear_errors();
        return $user_error_handling;
    }

    /**
     * Evaluates the last libXml operation and throws an exception
     * with a verbose multiline error message as text.
     *
     * @param string $msg_prefix prefix for the error message of the exception
     * @param string $msg_suffix suffix for the error message of the exception
     * @param bool $user_error_handling
     *
     * @throws \DOMException when libXml errors occurred
     */
    protected function handleErrors($msg_prefix = '', $msg_suffix = '', $user_error_handling = false)
    {
        if (libxml_get_last_error() !== false) {
            $errors = libxml_get_errors();
            libxml_clear_errors();
            libxml_use_internal_errors($user_error_handling);

            throw new \DOMException(
                $msg_prefix .
                $this->getErrorMessage($errors) .
                $msg_suffix
            );
        }

        libxml_use_internal_errors($user_error_handling);
    }

    /**
     * Returns a formatted error message from the given libXml errors.
     *
     * @param array $errors array of \LibXMLError instances
     *
     * @return string formatted error message
     */
    protected function getErrorMessage(array $errors)
    {
        $error_message = '';

        foreach ($errors as $error) {
            $error_message .= $this->parseError($error) . PHP_EOL . PHP_EOL;
        }

        return $error_message;
    }

    /**
     * Formats the given libXml error as a multiline string.
     *
     * @param \LibXMLError $error error to get as formatted string
     *
     * @return string formatted error message
     */
    protected function parseError(\LibXMLError $error)
    {
        $msg = '';
        switch ($error->level) {
            case LIBXML_ERR_WARNING:
                $msg .= 'Warning ' . $error->code . ': ';
                break;
            case LIBXML_ERR_FATAL:
                $msg .= 'Fatal error: ' . $error->code . ': ';
                break;
            case LIBXML_ERR_ERROR:
            default:
                $msg .= 'Error ' . $error->code . ': ';
                break;
        }

        $msg .= trim($error->message) . PHP_EOL .
                '  Line: ' . $error->line . PHP_EOL .
                'Column: ' . $error->column;

        if ($error->file) {
            $msg .= PHP_EOL . '  File: ' . $error->file;
        }

        return $msg;
    }
}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Modules\Validation;

/**
 * Validator class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class Validator
{
    /**
     * Config rule: no_empty
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function noEmpty($value)
    {
        if (!$value && '0' !== $value && 0 !== $value) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: number
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function number($value)
    {
        if ($value && !preg_match('!^[\p{Nd}]+$!iu', $value)) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: decimal
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function decimal($value)
    {
        if ($value && !preg_match('!^[\p{Nd}\., ]+$!iu', $value)) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: alpha
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function alpha($value)
    {
        if ($value && !preg_match('!^[\p{L} ]+$!iu', $value)) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: alpha_ext
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function alphaExt($value)
    {
        if ($value && !preg_match('!^[\p{L}\p{P}\p{Nd} ]+$!iu', $value)) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: email_simple
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function emailSimple($value)
    {
        if ($value && !preg_match('!^[^@]*@[^@]*$!iu', $value)) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: email
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function email($value)
    {
        if ($value && !preg_match(
            '!
                ^[a-zA-Z0-9][-_+\.a-zA-Z0-9]*                      # имя почты (может включать .-+_)
                @                                    # разделитель
                [\p{L}\p{Nd}][-\p{L}\p{Nd}]*         # домменое имя без зоны (любое кол-во поддоменов)
                ([\.][\p{L}\p{Nd}][-\p{L}\p{Nd}]*)?$ # доменная зона
            !xiu',
            $value
        )) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: phone
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function phone($value)
    {
        if ($value && !preg_match('!^[\p{Nd}+\(\) ]+$!iu', $value)) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: url
     *
     * @param string $value
     *
     * @return boolean
     */
    protected function url($value)
    {
        if ($value && !preg_match(
                '!^(http://|https://){0,1}(www\.){0,1}([-\p{L}\p{Nd}_]{2,}){1,}\.[\p{L}\p{Nd}]{2,4}[-\p{L}\p{Nd}_+&/=?\.%]{1,}!iu',
                $value
            )
        ) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: length
     *
     * @param string  $value
     * @param integer $rule
     *
     * @return boolean
     */
    protected function length($value, $rule)
    {
        if (mb_strlen($value, 'UTF-8') !== $rule) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: min_length
     *
     * @param string  $value
     * @param integer $rule
     *
     * @return boolean
     */
    protected function minLength($value, $rule)
    {
        if (mb_strlen($value, 'UTF-8') < $rule) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: max_length
     *
     * @param string  $value
     * @param integer $rule
     *
     * @return boolean
     */
    protected function maxLength($value, $rule)
    {
        if (mb_strlen($value, 'UTF-8') > $rule) {
            return false;
        }
        return true;
    }

    /**
     * Config rule: equal_field
     *
     * @param string $value
     * @param string $rule
     *
     * @return boolean
     */
    protected function equalField($value, $rule)
    {
        if ($value !== $rule) {
            return false;
        }
        return true;
    }

    /**
     * @param string         $rule          Config rule: no_empty|number|decimal|alpha|alpha_ext|email_simple|email|phone|url|length|min_length|max_length|equal_field
     * @param mixed          $value
     * @param integer|string $rule_extended
     *
     * @throws \InvalidArgumentException
     *
     * @return boolean
     */
    protected function checkRule($rule, $value, $rule_extended = null)
    {
        switch ($rule) {
            case 'no_empty':
                return $this->noEmpty($value);
            case 'number':
                return $this->number($value);
            case 'decimal':
                return $this->decimal($value);
            case 'alpha':
                return $this->alpha($value);
            case 'alpha_ext':
                return $this->alphaExt($value);
            case 'email_simple':
                return $this->emailSimple($value);
            case 'email':
                return $this->email($value);
            case 'phone':
                return $this->phone($value);
            case 'url':
                return $this->url($value);
            case 'length':
                return $this->length($value, (integer)$rule_extended);
            case 'min_length':
                return $this->minLength($value, (integer)$rule_extended);
            case 'max_length':
                return $this->maxLength($value, (integer)$rule_extended);
            case 'equal_field':
                return $this->equalField($value, $rule_extended);
            default:
                throw new \InvalidArgumentException('Invalid validation rule');
        }
    }

    /**
     * @param string $value
     * @param array  $rules
     *
     * @throws \InvalidArgumentException
     *
     * @return array
     */
    public function validate($value, array $rules)
    {
        $errors = [];
        $value  = trim($value);

        foreach ($rules as $rule) {
            list($rule_normalized, $rule_extended) = [$rule, null];
            if (is_array($rule)) {
                list($rule_normalized, $rule_extended) = $rule;
            }

            if (!$this->checkRule($rule_normalized, $value, $rule_extended)) {
                $errors[] = $rule_normalized;
            }
        }

        return $errors;
    }
}


<?php
namespace DdvPhp\DdvUtil\String;
use \DdvPhp\DdvUtil\Arrays\Compare;
/**
 * Class Cors
 *
 * Wrapper around PHPMailer
 *
 * @package \DdvPhp\DdvUtil\String\Conversion
 */
class Conversion
{

  /**
   * 把数组中所有驼峰的key转小写下滑杠
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function humpToUnderlineByIndexArray ($array = array()){
    if (is_array($array)&&Compare::isIndexArray($array)) {
      foreach ($array as $key => $value) {
        $array[$key] = self::humpToUnderlineByIndexArray($value);
      }
      return $array;
    }else{
      return self::humpToUnderlineByArray($array);
    }
  }
  /**
   * 把数组中所有小写下滑杠的key转驼峰
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function underlineToHumpByIndexArray ($array = array()){
    if (is_array($array)&&Compare::isIndexArray($array)) {
      foreach ($array as $key => $value) {
        $array[$key] = self::underlineToHumpByIndexArray($value);
      }
      return $array;
    }else{
      return self::underlineToHumpByArray($array);
    }
  }
  /**
   * 把数组中所有key的首字符转换为大写
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function ucfirstByIndexArray ($array = array()){
    if (is_array($array)&&Compare::isIndexArray($array)) {
      foreach ($array as $key => $value) {
        $array[$key] = self::ucfirstByIndexArray($value);
      }
      return $array;
    }else{
      return self::ucfirstByArray($array);
    }
  }
  /**
   * 把数组中所有key的首字符转换为小写
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function lcfirstByIndexArray ($array = array()){
    if (is_array($array)&&Compare::isIndexArray($array)) {
      foreach ($array as $key => $value) {
        $array[$key] = self::lcfirstByIndexArray($value);
      }
      return $array;
    }else{
      return self::lcfirstByArray($array);
    }
  }
  /**
   * 把数组中所有的key的首字符转换为大写
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function ucfirstByArray($array = array()){

      foreach ($array as $key => $value) {
          $keyt = self::ucfirst($key);
          if ($keyt!==$key){
              unset($array[$key]);
              $array[$keyt] = $value;
          }
      }
      return $array;
  }
  /**
   * 把数组中所有的key的首字符转换为小写
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function lcfirstByArray($array = array()){

      foreach ($array as $key => $value) {
          $keyt = self::lcfirst($key);
          if ($keyt!==$key){
              unset($array[$key]);
              $array[$keyt] = $value;
          }
      }
      return $array;
  }
  /**
   * 把数组中所有驼峰的key转小写下滑杠
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function humpToUnderlineByArray ($array = array()){
    foreach ($array as $key => $value) {
      $keyt = self::humpToUnderline($key);
      if ($keyt!==$key){
        unset($array[$key]);
        $array[$keyt] = $value;
      }
    }
    return $array;
  }
  /**
   * 把数组中所有小写下滑杠转驼峰
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function underlineToHumpByArray ($array = array()){
    foreach ($array as $key => $value) {
      $keyt = self::underlineToHump($key);
        if ($keyt!==$key){
          unset($array[$key]);
          $array[$keyt] = $value;
        }
    }
    return $array;
  }
  /**
   * 把数组中所有小写中杠转驼峰
   * @param array $array [数组]
   * @return array  [请求数组]
   */
  public static function middleLineToHumpByArray ($array = array()){
    foreach ($array as $key => $value) {
      $keyt = self::middleLineToUpperCase($key);
      if ($keyt!==$key){
        unset($array[$key]);
        $array[$keyt] = $value;
      }
    }
    return $array;
  }
  /**
  * 首字符转换为大写：
  * @param string $str [需要转换的字符串]
  * @return string  [转换后的字符串]
  */
  public static function ucfirst ($str){
    return ucfirst($str);
  }
  /**
  * 首字符转换为小写：
  * @param string $str [需要转换的字符串]
  * @return string  [转换后的字符串]
  */
  public static function lcfirst ($str){
    return lcfirst($str);
  }
  /**
  * 驼峰转小写下滑杠
  * @param string $str [需要转换的字符串]
  * @return string  [转换后的字符串]
  */
  public static function humpToUnderline ($str){
    return preg_replace_callback(
      '([A-Z])',
      function ($matches) {
        return '_'.strtolower($matches[0]);
      },
      $str
    );
  }
  /**
  * 小写下滑杠转驼峰
  * @param string $str [需要转换的字符串]
  * @return string  [转换后的字符串]
  */
  public static function underlineToHump ($str = ''){
    return preg_replace_callback(
      '(\_\w)',
      function ($matches) {
        return strtoupper(substr($matches[0], 1));
      },
      $str
    );
  }
  /**
  * 小写中杠转驼峰
  * @param string $str [需要转换的字符串]
  * @return string  [转换后的字符串]
  */
  public static function middleLineToHump ($str = ''){
    return preg_replace_callback(
      '(\-\w)',
      function ($matches) {
        return strtoupper(substr($matches[0], 1));
      },
      $str
    );
  }
  public static function middleLineToUpperCaseByArray ($array = array()){
    return self::middleLineToHumpByArray($array);
  }
  public static function underlineToUpperCaseByArray ($array = array()){
    return self::underlineToHumpByArray($array);
  }
  public static function upperCaseToUnderlineByArray ($array = array()){
    return self::humpToUnderlineByArray($array);
  }  public static function upperCaseToUnderline ($str){
      return self::humpToUnderline($str);
  }
  public static function underlineToUpperCase ($str = ''){
      return self::underlineToHump($str);
  }
  public static function middleLineToUpperCase ($str = ''){
    return self::middleLineToHump($str);
  }
}


<?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: RawData.php 3437 2011-03-08 16:40:19Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;
use Openbizx\Easy\Element\Element;

/**
 * RawData class is element for render raw data
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class RawData extends Element
{

    public $fieldName;
    public $label;
    public $text;
    public $link;
    public $unSerialize;

    /**
     * Read metadata info from metadata array and store to class variable
     *
     * @param array $xmlArr metadata array
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->fieldName = isset($xmlArr["ATTRIBUTES"]["FIELDNAME"]) ? $xmlArr["ATTRIBUTES"]["FIELDNAME"] : null;
        $this->label = isset($xmlArr["ATTRIBUTES"]["LABEL"]) ? $xmlArr["ATTRIBUTES"]["LABEL"] : null;
        $this->text = isset($xmlArr["ATTRIBUTES"]["TEXT"]) ? $xmlArr["ATTRIBUTES"]["TEXT"] : null;
        $this->link = isset($xmlArr["ATTRIBUTES"]["LINK"]) ? $xmlArr["ATTRIBUTES"]["LINK"] : null;
        $this->unSerialize = isset($xmlArr["ATTRIBUTES"]["UNSERIALIZE"]) ? $xmlArr["ATTRIBUTES"]["UNSERIALIZE"] : null;
    }

    /**
     * Get link of element
     *
     * @return string
     */
    protected function getLink()
    {
        if ($this->link == null) {
            return null;
        }
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->link, $formobj);
    }

    /**
     * Render label, just return elemen label
     *
     * @return string HTML text
     */
    public function renderLabel()
    {
        return $this->label;
    }

    /**
     * Get text of element
     *
     * @return string
     */
    protected function getText()
    {
        if ($this->text == null)
            return null;
        $formObj = $this->getFormObj();
        return Expression::evaluateExpression($this->text, $formObj);
    }

    /**
     * Render, draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $value = $this->text ? $this->getText() : $this->value;
        if ($value === null || $value == "")
            return $value;

        if ($this->unSerialize == "Y") {
            $value = unserialize($value);
        }

        if ($this->translatable == 'Y') {
            if (is_array($value)) {
                foreach ($value as $key => $value) {
                    $value[$key] = $value = $this->translateString($value);
                }
            } else {
                $value = $this->translateString($value);
            }
        }
        return $value;
    }

}

?>


<?php
/**
 * OAuth 2.0 Auth code grant
 *
 */

namespace OAuth2\Server\Grant;

use OAuth2\Server\Entity\AccessTokenEntity;
use OAuth2\Server\Entity\AuthCodeEntity;
use OAuth2\Server\Entity\ClientEntity;
use OAuth2\Server\Entity\RefreshTokenEntity;
use OAuth2\Server\Entity\SessionEntity;
use OAuth2\Server\Exception;
use OAuth2\Server\Util\SecureKey;

/**
 * Auth code grant class
 */
class AuthCodeGrant extends AbstractGrant
{
    /**
     * Grant identifier
     *
     * @var string
     */
    protected $identifier = 'authorization_code';

    /**
     * Response type
     *
     * @var string
     */
    protected $responseType = 'code';

    /**
     * AuthServer instance
     *
     * @var \OAuth2\Server\AuthorizationServer
     */
    protected $server = null;

    /**
     * Access token expires in override
     *
     * @var int
     */
    protected $accessTokenTTL = null;

    /**
     * The TTL of the auth token
     *
     * @var integer
     */
    protected $authTokenTTL = 600;

    /**
     * Override the default access token expire time
     *
     * @param int $authTokenTTL
     *
     * @return void
     */
    public function setAuthTokenTTL($authTokenTTL)
    {
        $this->authTokenTTL = $authTokenTTL;
    }

    /**
     * Check authorize parameters
     *
     * @return array Authorize request parameters
     *
     * @throws
     */
    public function checkAuthorizeParams()
    {
        // Get required params
        $clientId = $this->server->getRequestHandler()->getParam('client_id');
        if (is_null($clientId)) {
            throw new Exception\InvalidRequestException('client_id');
        }

        $redirectUri = $this->server->getRequestHandler()->getParam('redirect_uri');
        if (is_null($redirectUri)) {
            throw new Exception\InvalidRequestException('redirect_uri');
        }

        // Validate client ID and redirect URI
        $client = $this->server->getClientStorage()->get(
            $clientId,
            null,
            $redirectUri,
            $this->getIdentifier()
        );

        if (($client instanceof ClientEntity) === false) {
            throw new Exception\InvalidClientException();
        }

        $state = $this->server->getRequestHandler()->getParam('state');
        if ($this->server->stateParamRequired() === true && is_null($state)) {
            throw new Exception\InvalidRequestException('state', $redirectUri);
        }

        $responseType = $this->server->getRequestHandler()->getParam('response_type');
        if (is_null($responseType)) {
            throw new Exception\InvalidRequestException('response_type', $redirectUri);
        }

        // Ensure response type is one that is recognised
        if (!in_array($responseType, $this->server->getResponseTypes())) {
            throw new Exception\UnsupportedResponseTypeException($responseType, $redirectUri);
        }

        // Validate any scopes that are in the request
        $scopeParam = $this->server->getRequestHandler()->getParam('scope');
        $scopes = $this->validateScopes($scopeParam, $client, $redirectUri);

        return array(
            'client'        => $client,
            'redirect_uri'  => $redirectUri,
            'state'         => $state,
            'response_type' => $responseType,
            'scopes'        => $scopes
		);
    }

    /**
     * Parse a new authorize request
     *
     * @param string $type       The session owner's type
     * @param string $typeId     The session owner's ID
     * @param array  $authParams The authorize request $_GET parameters
     *
     * @return string An authorisation code
     */
    public function newAuthorizeRequest($type, $typeId, $authParams = [])
    {
        // Create a new session
        $session = new SessionEntity($this->server);
        $session->setOwner($type, $typeId);
        $session->associateClient($authParams['client']);

        // Create a new auth code
        $authCode = new AuthCodeEntity($this->server);
        $authCode->setId();
        $authCode->setRedirectUri($authParams['redirect_uri']);
        $authCode->setExpireTime(time() + $this->authTokenTTL);

        foreach ($authParams['scopes'] as $scope) {
            $authCode->associateScope($scope);
            $session->associateScope($scope);
        }

        $session->save();
        $authCode->setSession($session);
        $authCode->save();

        return $authCode->generateRedirectUri($authParams['state']);
    }

    /**
     * Complete the auth code grant
     *
     * @return array
     *
     * @throws
     */
    public function completeFlow(ClientEntity $client)
    {
        // Validate the auth code
        $authCode = $this->server->getRequestHandler()->getParam('code');
        if (is_null($authCode)) {
            throw new Exception\InvalidRequestException('code');
        }

        $code = $this->server->getAuthCodeStorage()->get($authCode);
        if (($code instanceof AuthCodeEntity) === false) {
            throw new Exception\InvalidRequestException('code');
        }

        // Ensure the auth code hasn't expired
        if ($code->isExpired() === true) {
            throw new Exception\InvalidRequestException('code');
        }

        // Check redirect URI presented matches redirect URI originally used in authorize request
        if ($code->getRedirectUri() !== $client->getRedirectUri()) {
            throw new Exception\InvalidRequestException('redirect_uri');
        }

        $session = $code->getSession();
        $session->associateClient($client);

        $authCodeScopes = $code->getScopes();

        // Generate the access token
        $accessToken = new AccessTokenEntity($this->server);
        $accessToken->setId();
        $accessToken->setExpireTime($this->getAccessTokenTTL() + time());

        foreach ($authCodeScopes as $authCodeScope) {
            $session->associateScope($authCodeScope);
        }

        foreach ($session->getScopes() as $scope) {
            $accessToken->associateScope($scope);
        }

        $this->server->getTokenType()->setSession($session);
        $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
        $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());

        // Associate a refresh token if set
        if ($this->server->hasGrantType('refresh_token')) {
            $refreshToken = new RefreshTokenEntity($this->server);
            $refreshToken->setId();
            $refreshToken->setExpireTime($this->server->getGrantType('refresh_token')->getRefreshTokenTTL() + time());
            $this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId());
        }

        // Expire the auth code
        $code->expire();

        // Save all the things
        $accessToken->setSession($session);
        $accessToken->save();

        if (isset($refreshToken) && $this->server->hasGrantType('refresh_token')) {
            $refreshToken->setAccessToken($accessToken);
            $refreshToken->save();
        }

        return $this->server->getTokenType()->generateResponse();
    }
}


<?php

namespace Modules\Menu\Entities;

use Baum\Node as Model;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Modules\Menu\Contracts\MenuItemInterface as MenuItemContract;
use Modules\Menu\Traits\MenuItemTrait;
use Vain\Packages\Translator\TranslatableTrait;

class Menu extends Model implements MenuItemContract
{
    use MenuItemTrait, TranslatableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'menu';

    /**
     * @var array
     */
    protected $fillable = ['type', 'target', 'visible', 'parameters', 'published_at', 'concealed_at'];

    /**
     * @var array
     */
    protected $dates = ['published_at', 'concealed_at', 'created_at', 'deleted_at'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function contents()
    {
        return $this->hasMany(MenuContent::class);
    }

    /**
     * @param Builder $query
     *
     * @return mixed
     */
    public function scopeVisible($query)
    {
        return $query->where(function ($query) {

            $query->where('visible', true);

            $query->where(function ($query) {
                $query->where('published_at', '<=', Carbon::now())
                    ->orWhere('published_at', null);
            });

            $query->where(function ($query) {
                $query->where('concealed_at', '>=', Carbon::now())
                    ->orWhere('concealed_at', null);
            });
        });
    }

    /**
     * @param $value
     *
     * @return bool
     */
    public function getVisibleAttribute($value)
    {
        if ($value) {
            // if we are willing to show the item we consider time boundaries if there are any
            if ($this->published_at instanceof Carbon) {
                // if the publish date is in the past we can
                // savely show the menu entry
                $value = $this->published_at->isPast();
            }

            if ($value && $this->concealed_at instanceof Carbon) {
                // if the visibility before is true and the conceal date
                // is in the future we can show the menu entry
                $value = $this->concealed_at->isFuture();
            }
        }

        return $value;
    }

    /**
     * fix optional empty dates.
     *
     * @param $value
     */
    public function setPublishedAtAttribute($value)
    {
        $this->attributes['published_at'] = !empty($value)
            ? $value
            : null;
    }

    /**
     * fix optional empty dates.
     *
     * @param $value
     */
    public function setConcealedAtAttribute($value)
    {
        $this->attributes['concealed_at'] = !empty($value)
            ? $value
            : null;
    }

    /**
     * Form aggregation used to display the name of the element
     * by also visualizing its depth.
     *
     * @return string
     */
    public function getDepthTitleAttribute()
    {
        return str_repeat('-', $this->depth).' '.$this->content->title;
    }
}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Modules\Auth;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\RouteCollection;

/**
 * User class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class User
{
    /**
     * @var Session
     */
    private $session;

    /**
     * @var array
     */
    private $routes;

    /**
     * @var array
     */
    private $access;

    const USER_ID     = 'user_id';
    const USER_NAME   = 'user_name';
    const USER_GROUPS = 'user_groups';

    /**
     * @param Session $session
     * @param RouteCollection $routes
     * @param array $access
     */
    public function __construct(Session $session, RouteCollection $routes, array $access)
    {
        $this->session = $session;
        $this->routes  = $routes;
        $this->access  = $access;
    }

    /**
     * @param Auth $auth
     * @param integer $duration
     *
     * @return Response|void
     */
    public function login(Auth $auth, $duration = 0 /*, Response $response = NULL, $duration = 0*/)
    {
        $user_groups = serialize($auth->getUserGroups());
        $user_id     = $auth->getUserId();
        $user_name   = $auth->getUserName();

        $this->session->migrate(false, $duration);

        $this->session->set(self::USER_ID, $user_id);
        $this->session->set(self::USER_NAME, $user_name);
        $this->session->set(self::USER_GROUPS, $user_groups);
    }

    /**
     * @param boolean $destroy
     *
     * @return boolean
     */
    public function logout($destroy = false)
    {
        if ($destroy === true) {
            $this->session->invalidate();
        } else {
            $this->session->remove(self::USER_ID);
            $this->session->remove(self::USER_NAME);
            $this->session->remove(self::USER_GROUPS);

            $this->session->migrate();
        }

        return !$this->isLogin();
    }

    /**
     * @param integer|null $default
     *
     * @return integer|null
     */
    public function getUserId($default = null)
    {
        return (integer)$this->session->get(self::USER_ID, $default);
    }

    /**
     * @param string|null $default
     *
     * @return string|null
     */
    public function getUserName($default = null)
    {
        return $this->session->get(self::USER_NAME, $default);
    }

    /**
     * @param array $default
     *
     * @return array
     */
    public function getUserGroups(array $default = [])
    {
        return unserialize($this->session->get(self::USER_GROUPS, serialize($default)));
    }

    /**
     * @return boolean
     */
    public function isLogin()
    {
        return ($this->getUserName() !== null);
    }

    /**
     * @param string $route
     *
     * @return boolean
     */
    public function getAccessByRoute($route)
    {
        $defaults = $this->routes->get($route)->getDefaults();
        return $this->getAccessByController($defaults['_controller']);
    }

    /**
     * @param string $controller
     *
     * @return boolean
     */
    public function getAccessByController($controller)
    {
        $access = false;
        list($controller, $action) = explode('::', $controller);

        $groups = $this->getUserGroups();

        // если в настройках нет контроллера - разрешен
        if (!isset($this->access[$controller])) {
            $access = true;
        } else {
            // если в настройках нет действия - разрешен
            if (!isset($this->access[$controller][$action])) {
                $access = true;
            } else {
                foreach ($this->access[$controller][$action] as $action_access) {
                    if (in_array($action_access, $groups)) {
                        $access = true;
                    }
                }
            }
        }
        return $access;
    }
}