<?php

/**
 * Helpful string class.
 */
class Benri_Util_String
{
    /**
     * Returns given string as a dash_erized word.
     *
     * @param string $str String to dasherize
     * @param string $replacement Replacement to be used as "dash"
     * @return string The dash_erized form of the given `$str`
     */
    public static function dasherize($str, $replacement = '_')
    {
        return preg_replace_callback(
            '/([A-Z0-9-\s]+)/',
            function ($match) use ($replacement) {
                return $replacement . strtolower($match[1]);
            }, lcfirst($str)
        );
    }

    /**
     * @param string $string The string to slugfy
     * @param string $replacement Replacement to be used as the slug separator
     * @return string The slugy'd form of the given `$str`
     */
    public static function slugfy($string, $replacement = '-')
    {
        $string = static::removeponctuation(trim($string));
        $string = static::accentremove($string);

        return strtolower(preg_replace('/[^\w]+/', $replacement, $string));
    }

    /**
     * Returns given string as a camelCased word.
     *
     * @param string $str
     * @param bool $ucfirst wheter to uppercase the first character
     * @return string
     */
    public static function camelize($str, $ucfirst = false)
    {
        $replace = str_replace(
            ' ',
            '',
            ucwords(str_replace(['_', '-'], ' ', strtolower($str)))
        );

        if (!$ucfirst) {
            return lcfirst($replace);
        }

        return $replace;
    }

    /**
     * Quotes the string so that it can be used as Javascript string constants
     * for example.
     *
     * @param string $value The value to escape
     * @return string
     */
    public static function escape($value)
    {
        return strtr(
            $value,
            [
                "\r" => '\\r',
                "\n" => '\\n',
                "\'" => '\\\'',
                "\t" => '\\t',
                '/'  => '\\/',
                '"'  => '\\\\\'',
                '\\' => '\\\\\\',
            ]
        );
    }

    /**
     * Replace all ponctuation from the given string.
     *
     * @param string $str
     * @param string $replacement Replacement to apply
     * @return string
     */
    public static function removeponctuation($str, $replacement = '')
    {
        return preg_replace(
            '@(\xBB|\xAB|!|\xA1|%|,|:|;|\(|\)|\&|\'|"|\.|-|\/|\?|\\\)@',
            $replacement,
            $str
        );
    }

    /**
     * Translate characters to match \w regex.
     *
     * @param string $string to translate
     * @return string
     */
    public static function accentremove($str)
    {
        return str_replace(
            [
                'Á', 'á', 'à', 'À', 'â', 'Â', 'ä', 'Ä', 'ã', 'Ã', 'å', 'Å', 'ð',
                'é', 'É', 'È', 'è', 'Ê', 'ê', 'Ë', 'ë', 'í', 'Í', 'ì', 'Ì', 'î',
                'Î', 'ï', 'Ï', 'ñ', 'Ñ', 'ó', 'Ó', 'Ò', 'ò', 'Ô', 'ô', 'Ö', 'ö',
                'õ', 'Õ', 'Ú', 'ú', 'ù', 'Ù', 'û', 'Û', 'ü', 'Ü', 'ý', 'Ý', 'ÿ',
                'Ç', 'ç',
            ],

            [
                'A', 'a', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'o',
                'e', 'E', 'E', 'e', 'E', 'e', 'E', 'e', 'i', 'I', 'i', 'I', 'i',
                'I', 'i', 'I', 'n', 'N', 'o', 'O', 'O', 'o', 'O', 'o', 'O', 'o',
                'o', 'O', 'U', 'u', 'u', 'U', 'u', 'U', 'u', 'U', 'y', 'Y', 'y',
                'C', 'c',
            ],

            $str
        );
    }

    /**
     * Returns a random string with the given length and given string of
     * allowed characters.
     *
     * @param int $length The length of the random string
     * @param string $allowedChars Allowed chars
     * @return string
     */
    public static function random(
        $length         = 8,
        $allowedChars   = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXY346789'
    ) {
        $return     = '';
        $hashLength = strlen($allowedChars) - 1;

        for (;$length > 0; --$length) {
            $return .= $allowedChars{rand(0, $hashLength)};
        }

        return str_shuffle($return);
    }

    /**
     * Creates a password hash.
     *
     * @param string $raw The password in raw format
     * @return string Returns the hashed password, or `null` on failure
     */
    public static function password($raw)
    {
        return password_hash($raw, PASSWORD_BCRYPT);
    }

    /**
     * Verifies if the given (raw) password matches a hash.
     *
     * @param string $raw The password in raw format
     * @param string $hash A hash created by Benri_Util_String::password()
     * @return bool `true` if the password and hash match, or `false`
     *  otherwise
     */
    public static function verifyPassword($raw, $hash)
    {
        return password_verify($raw, $hash);
    }
}


<?php

namespace Encore\Events;

use Sabre\Event\EventEmitterInterface;

class Dispatcher implements DispatcherInterface
{
    protected $event;

    /**
     * Construct the object and assign properties from injected objects
     *
     * @param EventEmitterInterface $event
     */
    public function __construct(EventEmitterInterface $event)
    {
        $this->event = $event;
    }

    /**
     * Subscribe to an event.
     *
     * @param string $event
     * @param callable $callback
     * @param int $priority
     * @return void
     */
    public function listen($event, callable $callback, $priority = 100)
    {
        $this->event->on($event, $callback, $priority);
    }

    /**
     * Subscribe to an event exactly once.
     *
     * @param string $event
     * @param callable $callback
     * @param int $priority
     * @return void
     */
    public function once($event, callable $callback, $priority = 100)
    {
        $this->event->once($event, $callback, $priority);
    }

    /**
     * Emits an event.
     *
     * This method will return true if 0 or more listeners were succesfully
     * handled. false is returned if one of the events broke the event chain.
     *
     * @param string $event
     * @param array $arguments
     * @return bool
     */
    public function fire($event, array $arguments = [])
    {
        return $this->event->emit($event, $arguments);
    }

    /**
     * Returns the list of listeners for an event.
     *
     * The list is returned as an array. Every item is another array with 2
     * elements: priority and the callback.
     *
     * The array is returned by reference, and can therefore be used to
     * manipulate the list of events.
     *
     * @param string $event
     * @return array
     */
    public function listeners($event)
    {
        return $this->event->listeners($event);
    }

    /**
     * Removes a specific listener from an event.
     *
     * @param string $event
     * @param callable $listener
     * @return void
     */
    public function forgetListener($event, callable $listener)
    {
        $this->event->removeListener($event, $listener);
    }

    /**
     * Removes all listeners from the specified event.
     *
     * @param string $event
     * @return void
     */
    public function forget($event)
    {
        $this->event->removeAllListeners($event);
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Action\Block;

use RedKiteCms\Action\BaseAction;
use RedKiteCms\Content\BlockManager\BlockManagerAdd;
use RedKiteCms\Content\BlockManager\BlockManagerArchive;
use RedKiteCms\Content\BlockManager\BlockManagerEdit;
use Silex\Application;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ArchiveBlockAction defines the object assigned to archive a block when it is edited
 *
 * @package RedKiteCms\Action
 */
class ArchiveBlockAction extends BaseAction
{
    /**
     * {@inheritdoc}
     */
    public function execute(array $options, $username)
    {
        $data = $options["data"];
        $archiveOptions = array(
            'page' => $data['page'],
            'language' => $data['language'],
            'country' => $data['country'],
            'slot' => $data['slot'],
            'blockname' => $data['name'],
        );

        $blockManager = $this->app["red_kite_cms.blocks_manager_factory"]->create('archive');
        $blockManager->archive(
            $this->app["red_kite_cms.configuration_handler"]->siteDir(),
            $archiveOptions,
            $username,
            $data['data']
        );
    }
}


<?php namespace Versatile\Introspection;

use Versatile\Introspection\Contracts\PathIntrospector;
use Versatile\Query\Contracts\SyntaxParser;
use Versatile\Query\SyntaxParser as DefaultParser;
use BadMethodCallException;
use Illuminate\Database\Eloquent\Relations\Relation;
use UnexpectedValueException;
use ReflectionMethod;

class EloquentPathIntrospector implements PathIntrospector
{

    protected $parser;

    protected $cache = [];

    public function __construct(SyntaxParser $parser=null)
    {
        $parser = $parser ?: new DefaultParser;
        $this->parser = $parser;
    }

     /**
     * {@inheritdoc}
     *
     * @param string|object $rootObject The root object
     * @param string $path The path relative from root
     * @return string classname of class related by $path
     **/
    public function classOfPath($rootObject, $path)
    {

        $rootObject = $this->rootInstance($rootObject);
        $cacheId = $this->getCacheId($rootObject, $path);

        if (isset($this->cache[$cacheId])) {
            return $this->cache[$cacheId];
        }

        $parts = $this->parser->splitPath($path);

        $partCount = count($parts);
        $last = $partCount-1;

        $currentObject = $rootObject;

        for ($i=0; $i<$partCount; $i++) {

            $part = $parts[$i];

            $methodName = '';

            if (method_exists($currentObject, $part)) {
                $methodName = $part;
            } else {
                $camelMethod = camel_case($part);
                if(method_exists($currentObject, $camelMethod)){
                    $methodName = $camelMethod;
                }
            }

            if(!$methodName){
                continue;
            }

            $reflectionMethod = new ReflectionMethod($currentObject, $methodName);

            if ($reflectionMethod->isStatic() || !$reflectionMethod->isPublic() ||
                $reflectionMethod->isAbstract()) {
                continue;
            }

            $relation = $currentObject->{$methodName}();

            if ($relation instanceof Relation) {

                if (!$model = $relation->getQuery()->getModel()) {
                    continue;
                }

                if($i != $last){
                    $currentObject = $model;
                    continue;
                }

                $this->cache[$cacheId] = get_class($model);
                return $this->cache[$cacheId];
            }

        }

        throw new UnexpectedValueException("$path does not point to an relation");
    }

    protected function rootInstance($rootObject){
        if(!is_object($rootObject)){
            return new $rootObject;
        }
        return $rootObject;
    }

    protected function getCacheId($model, $path)
    {
        $modelId = get_class($model);
        return "$modelId|$path";
    }

}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Plugin;

use RedKiteCms\Configuration\ConfigurationHandler;
use Symfony\Component\Finder\Finder;

/**
 * Class PluginManager is the object assigned to handle the installed plugins
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Plugin
 */
class PluginManager
{
    /**
     * @type array
     */
    private $blocks = array();
    /**
     * @type array
     */
    private $themes = array();
    /**
     * @type array
     */
    private $core = array();
    /**
     * @type \RedKiteCms\Configuration\ConfigurationHandler
     */
    private $configurationHandler;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     */
    public function __construct(ConfigurationHandler $configurationHandler)
    {
        $this->configurationHandler = $configurationHandler;
    }

    /**
     * Returns core and blocks assets
     *
     * @return array
     */
    public function getAssets()
    {
        return array_merge($this->core, $this->blocks);
    }

    /**
     * Returns core plugins
     *
     * @return array
     */
    public function getCorePlugins()
    {
        return $this->core;
    }

    /**
     * Returns blocks plugins
     *
     * @return array
     */
    public function getBlockPlugins()
    {
        return $this->blocks;
    }

    /**
     * Returns block plugin by name
     *
     * @return array
     */
    public function getBlockPlugin($name)
    {
        if (!array_key_exists($name, $this->blocks)) {
            return null;
        }

        return $this->blocks[$name];
    }

    /**
     * Returns theme plugins
     *
     * @return array
     */
    public function getThemePlugins()
    {
        return $this->themes;
    }

    /**
     * Returns theme plugin by name
     *
     * @return array
     */
    public function getThemePlugin($name)
    {
        if (!array_key_exists($name, $this->themes)) {
            return null;
        }

        return $this->themes[$name];
    }

    /**
     * Returns the active theme plugin
     *
     * @return \RedKiteCms\Plugin\Plugin
     */
    public function getActiveTheme()
    {
        $themeName = $this->configurationHandler->theme();

        return $this->themes[$themeName];
    }

    /**
     * Boots the plugin manager
     *
     * @return $this
     */
    public function boot()
    {
        $pluginFolders = $this->configurationHandler->pluginFolders();
        $this->core = $this->findPlugins($this->configurationHandler->corePluginsDir() . "/Core");
        foreach ($pluginFolders as $pluginFolder) {
            $this->blocks += $this->findPlugins($pluginFolder . "/Block");
            $this->themes += $this->findPlugins($pluginFolder . "/Theme");
        }

        return $this;
    }

    /**
     * Installs the assets for all the handled plugins
     */
    public function installAssets()
    {
        $this->doInstallAssets($this->core);
        $this->doInstallAssets($this->blocks);
        $this->doInstallAssets($this->themes);
    }

    private function findPlugins($pluginsDir)
    {
        if (!is_dir($pluginsDir)) {
            return array();
        }

        $plugins = array();

        $rootDir = $this->configurationHandler->rootDir();
        $frameworkAbsoluteDir = $this->configurationHandler->frameworkAbsoluteDir();
        $finder = new Finder();
        $folders = $finder->directories()->depth(0)->in($pluginsDir);
        foreach ($folders as $folder) {
            $pluginName = basename($folder);
            $plugins[$pluginName] = new Plugin(
                $pluginName,
                basename($pluginsDir),
                $rootDir,
                $frameworkAbsoluteDir
            );
        }

        return $plugins;
    }

    private function doInstallAssets($plugins)
    {
        foreach ($plugins as $plugin) {
            $plugin->installAssets($this->configurationHandler->webDirname());
        }
    }
}


<?php namespace Tequilarapido\PHPSerialized;

class SerializedObject
{
    protected $serialized;

    public function __construct($string = '')
    {
        if (!empty($string)) {
            $this->setSerialized($string);
        }
    }

    public function setSerialized($serlialized)
    {
        $this->serialized = $serlialized;
    }

    /**
     * Check value to find if it was serialized.
     *
     * If $data is not an string, then returned value will always be false.
     * Serialized data is always a string.
     *
     * @since 2.0.5
     * @from wordpress / is_serialized function
     *       https://github.com/WordPress/WordPress/blob/5f0981788d7adbd25b71addbc415f700eb1c71b5/wp-includes/functions.php
     *
     * @param mixed $data Value to check to see if was serialized.
     * @return bool False if not serialized and true if it was.
     */
    public function isSerialized()
    {
        // if it isn't a string, it isn't serialized
        if (!is_string($this->serialized)) {
            return false;
        }
        $this->serialized = trim($this->serialized);
        if ('N;' == $this->serialized) {
            return true;
        }
        $length = strlen($this->serialized);
        if ($length < 4) {
            return false;
        }
        if (':' !== $this->serialized[1]) {
            return false;
        }
        $lastc = $this->serialized[$length - 1];
        if (';' !== $lastc && '}' !== $lastc) {
            return false;
        }
        $token = $this->serialized[0];
        switch ($token) {
            case 's' :
                if ('"' !== $this->serialized[$length - 2]) {
                    return false;
                }
            case 'a' :
            case 'O' :
                return (bool)preg_match("/^{$token}:[0-9]+:/s", $this->serialized);
            case 'b' :
            case 'i' :
            case 'd' :
                return (bool)preg_match("/^{$token}:[0-9.E-]+;\$/", $this->serialized);
        }
        return false;
    }

    public function unserialize($base64 = true)
    {
        $string = $this->serialized;

        if ($base64) {
            $string = base64_decode(base64_encode($string));
        }

        return @unserialize($string);
    }

}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Factory\Validator;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    Zend\Validator\Callback,
    Zend\Validator\ValidatorChain,
    Zend\Validator\ValidatorInterface,
    CmsUser\Options\ModuleOptions;

class AnswerVerifyValidatorFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return ValidatorInterface
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();
        /* @var $options ModuleOptions */
        $options = $services->get(ModuleOptions::class);

        $identity = null;
        if ($services->has($options->getAuthenticationService())) {
            /* @var $authService \Zend\Authentication\AuthenticationServiceInterface */
            $authService = $services->get($options->getAuthenticationService());

            if ($authService->hasIdentity()) {
                /* @var $identity \CmsUser\Mapping\UserInterface */
                $identity = $authService->getIdentity();
            }
        }

        $validatorChain = new ValidatorChain();

        $validatorChain->attachByName('Callback', [
            'messages' => [
                Callback::INVALID_VALUE => 'Your answer is wrong. '
                    . 'Please provide the correct answer',
            ],
            'callback' => function($value, $context = []) use ($identity)
            {
                if (isset($context['answer'])) {
                    return strtolower($context['answer']) === $value;
                } elseif ($identity) {
                    return $identity->getAnswer() === $value;
                }
                return false;
            },
        ], true);

        return $validatorChain;
    }
}


<?php

/*
 * This file is part of the Meta Reader package.
 *
 * (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Temp\MetaReader;

use Temp\ImageAnalyzer\ImageAnalyzer;
use Temp\MetaReader\Value\MetaValue;
use Temp\MetaReader\Value\ValueBag;

/**
 * Image analyzer reader.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class ImageAnalyzerReader implements ReaderInterface
{
    /**
     * @var ImageAnalyzer
     */
    private $analyzer;

    /**
     * @param ImageAnalyzer $analyzer
     */
    public function __construct(ImageAnalyzer $analyzer)
    {
        $this->analyzer = $analyzer;
    }

    /**
     * {@inheritdoc}
     */
    public function available()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($filename)
    {
        return $this->analyzer->supports($filename);
    }

    /**
     * {@inheritdoc}
     */
    public function read($filename)
    {
        $meta = new ValueBag();

        try {
            $imageInfo = $this->analyzer->analyze($filename);

            $meta
                ->set('image.width', new MetaValue($imageInfo->getWidth()))
                ->set('image.height', new MetaValue($imageInfo->getHeight()))
                ->set('image.format', new MetaValue($imageInfo->getFormat()))
                ->set('image.type', new MetaValue($imageInfo->getType()))
                ->set('image.colorspace', new MetaValue($imageInfo->getColorspace()))
                ->set('image.depth', new MetaValue($imageInfo->getDepth()));

            if ($imageInfo->getColors()) {
                $meta->set('image.colors', new MetaValue($imageInfo->getColors()));
            }
            if ($imageInfo->getQuality()) {
                $meta->set('image.quality', new MetaValue($imageInfo->getQuality()));
            }
            if ($imageInfo->getCompression()) {
                $meta->set('image.compression', new MetaValue($imageInfo->getCompression()));
            }
            if ($imageInfo->getResolution()) {
                $meta->set('image.resolution', new MetaValue($imageInfo->getResolution()));
            }
            if ($imageInfo->getUnits()) {
                $meta->set('image.units', new MetaValue($imageInfo->getUnits()));
            }
            if ($imageInfo->getProfiles()) {
                $meta->set('image.profiles', new MetaValue(implode(',', $imageInfo->getProfiles())));
            }
        } catch (\Exception $e) {
        }

        return $meta;
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\helpers;

/**
 * Html [[@doctodo class_description:cascade\components\helpers\Html]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Html extends \canis\helpers\Html
{
    /**
     * [[@doctodo method_description:prepareEditInPlace]].
     *
     * @param [[@doctodo param_type:htmlOptions]] $htmlOptions [[@doctodo param_description:htmlOptions]]
     * @param [[@doctodo param_type:model]]       $model       [[@doctodo param_description:model]]
     * @param [[@doctodo param_type:attribute]]   $attribute   [[@doctodo param_description:attribute]]
     * @param [[@doctodo param_type:relative]]    $relative    [[@doctodo param_description:relative]] [optional]
     *
     * @return [[@doctodo return_type:prepareEditInPlace]] [[@doctodo return_description:prepareEditInPlace]]
     */
    public static function prepareEditInPlace(&$htmlOptions, $model, $attribute, $relative = null)
    {
        $eip = ['data' => []];
        if (empty($model->primaryKey) || (isset($relative) && empty($relative->primaryKey))) {
            return false;
        }
        $eip['data']['object'] = $model->primaryKey;
        $eip['data']['attribute'] = $attribute;

        $eip['lastValue'] = $model->{$attribute};
        if (isset($relative)) {
            $eip['data']['relatedObject'] = $relative['primaryKey'];
        }
        $htmlOptions['data-edit-in-place'] = json_encode($eip);

        return true;
    }
}


<?php
/**
 * Web2All Table Object class
 *
 * This is base class for objects reflecting a database table. All
 * kinds of support methods will be made available.
 *
 * @author Merijn van den Kroonenberg
 * @copyright (c) Copyright 2007-2011 Web2All BV
 * @since 2007-08-20
 */
class Web2All_Table_ClassBuilder extends Web2All_Manager_Plugin {

  /**
   * ADODB database connection
   *
   * @var ADOConnection
   */
  protected $db;

  protected $implement_listable=false;

  protected $keeppropnames=false;

  protected $saveobject=false;

  protected $author='';

  /**
   * constructor
   *
   * @param Web2All_Manager_Main $web2all
   * @param ADOConnection $db
   */
  public function __construct(Web2All_Manager_Main $web2all,$db) {
    parent::__construct($web2all);

    $this->db=$db;

  }

  public function implementIListable()
  {
    $this->implement_listable=true;
  }

  /**
   * Do not remove prefix when creating property names
   *
   */
  public function keepPropertyNames()
  {
    $this->keeppropnames=true;
  }

  /**
   * extend SaveObject instead of Object
   *
   */
  public function extendSaveObject()
  {
    $this->saveobject=true;
  }

  /**
   * extend SaveObject instead of Object
   * @param string $author
   */
  public function setAuthor($author)
  {
    $this->author=$author;
  }

  /**
   * Returns a string with the class definition
   *
   * requires template 'tableclass.tpl.php'
   *
   * @param string $tablename
   * @param string $classname
   * @return string
   */
  public function generateClass($tablename,$classname=null)
  {
    $analyzer=$this->Web2All->Plugin->Web2All_Database_Conversion_Analyzer($this->db);

    $database=$analyzer->readDatabaseTables(null,array($tablename));

    $table=$database->getTable($tablename);

    if(!$table){
      return "table not found";
    }

    $columns=$table->getColumns();

    $indices=$table->getIndices();

    $hasprimary=false;
    $primary_index=null;
    foreach($indices as $index){
      if($index->primary){
        $primary_index=$index;
        $hasprimary=true;
      }
    }

    $obj_to_db_trans=array();
    $key_properties=array();
    $property_info=array();

    foreach($columns as $column){
      $fieldname=$column->name;
      if($this->keeppropnames){
        $propname=$fieldname;
      }else{
        list($dummy,$propname)=explode('_',$fieldname,2);
      }
      $obj_to_db_trans[$propname]=$fieldname;
      $property_info[$propname]=array('type' => $this->getTypeFromCode($column->type), 'description' => '');
      if($column->driverspecific){
        $extradesc='';
        if($column->driverspecific->comment){
          $extradesc.=$column->driverspecific->comment;
        }
        if($column->driverspecific->type==10){
          if($extradesc){
            $extradesc.="
   * ";
          }
          $extradesc.='Possible values: '.substr($column->driverspecific->extradata,4);
        }
        if($extradesc){
          $property_info[$propname]['description'].=$extradesc;
        }
      }

      // check if primary key
      if ($hasprimary) {
        foreach($primary_index->columns as $prim_col){
          if($prim_col->name==$fieldname){
            // yes! its part of primary key
            $key_properties[]=$propname;
          }
        }
      }
    }

    /*
    // for mssql it would be:  'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME="'.$tablename.'" AND TABLE_SCHEMA="'.$this->db->database.'"'
    // and the key information:'SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME="'.$tablename.'" AND TABLE_SCHEMA="'.$this->db->database.'"'
    $recordSet = $this->db->Execute('SHOW COLUMNS FROM `'.$tablename.'`',array());
    while (!$recordSet->EOF) {
      $colspec=$recordSet->FetchRow();
      $fieldname=$colspec['Field'];
      if($this->keeppropnames){
        $propname=$fieldname;
      }else{
        list($dummy,$propname)=explode('_',$fieldname,2);
      }
      $obj_to_db_trans[$propname]=$fieldname;
      if ($colspec['Key']=='PRI') {
        $key_properties[]=$propname;
      }
    }
    $recordSet->close();
    */

    if (is_null($classname)) {
      $classname=ucfirst($tablename);
    }

    $tpl=$this->Web2All->Plugin->Web2All_Template_Engine_Savant3();

    $tpl->assign('property_info',$property_info);

    $tpl->assign('obj_to_db_trans',$obj_to_db_trans);
    $tpl->assign('key_properties',$key_properties);
    $tpl->assign('tablename',$tablename);
    $tpl->assign('classname',$classname);
    $tpl->assign('author',$this->author);
    $tpl->assign('implement_listable',$this->implement_listable);
    $tpl->assign('extend_saveobject',$this->saveobject);
    $tpl->assign('date',date("Y-m-d"));

    $classstring="<?php\n".$tpl->fetch('tableclass.tpl.php')."\n?>";

    return $classstring;
  }

  public function getTypeFromCode($type){
    $normtype='';
    switch($type){
      case Web2All_Database_Structure_Column::TYPE_INT:
      case Web2All_Database_Structure_Column::TYPE_BIGINT:
      case Web2All_Database_Structure_Column::TYPE_NUMERIC:
        $normtype='int';
        break;
      case Web2All_Database_Structure_Column::TYPE_DOUBLE:
      case Web2All_Database_Structure_Column::TYPE_DECIMAL:
        $normtype='float';
        break;
      case Web2All_Database_Structure_Column::TYPE_VARCHAR:
      case Web2All_Database_Structure_Column::TYPE_TEXT:
        $normtype='string';
        break;
      case Web2All_Database_Structure_Column::TYPE_DATE:
        $normtype='string';
        break;
      case Web2All_Database_Structure_Column::TYPE_DATETIME:
        $normtype='string';
        break;
      case Web2All_Database_Structure_Column::TYPE_BLOB:
        $normtype='base64Binary';
        break;
      default:
        $normtype='mixed';
        break;
    }
    return $normtype;
  }

}

?>


<?php
namespace app\manage\exception;

use cms\View;
use think\Config;
use think\Request;
use think\Response;
use lookfeel\common\Format;
use think\exception\Handle;

class Http extends Handle
{

    /**
     * !CodeTemplates.overridecomment.nonjd!
     *
     * @see \think\exception\Handle::render()
     */
    public function render(\Exception $e)
    {
        // 父类处理
        if (Config::get('app_debug')) {
            return parent::render($e);
        }
        parent::render($e);

        try {
            $request = Request::instance();
            $msg = $e->getMessage();

            if ($request->isAjax()) {
                $data = Format::formatJump(0, $msg);
                $response = Response::create($data, 'json');
            } else {

                $view = new View();

                // 标题
                $view->assign('site_title', $msg);

                // 跳转
                $jump = Format::formatJump(0, $msg);
                $view->assign('jump', $jump);

                // 主题
                $view_path = dirname(__DIR__) . '/view/' . Config::get('manage_theme') . '/';
                $view->config('view_path', $view_path);

                $data = $view->fetch('common/jump');

                $response = Response::create($data);
            }
        } catch (\Exception $e) {
            return parent::render($e);
        }

        return $response;
    }
}


<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types = 1);

namespace Cawa\Session;

use Cawa\App\HttpFactory;
use Cawa\Core\DI;
use Cawa\Events\DispatcherFactory;
use Cawa\Events\TimerEvent;
use Cawa\Http\Cookie;
use Cawa\Session\SessionStorage\AbstractStorage;

class Session
{
    use HttpFactory;
    use DispatcherFactory;

    /**
     * @var AbstractStorage
     */
    private $storage;

    /**
     * SessionTrait constructor.
     */
    public function __construct()
    {
        // name
        $name = DI::config()->getIfExists('session/name') ?? 'SID';
        $this->setName($name);

        // storage
        $class = DI::config()->getIfExists('session/storage/class') ?? '\\Cawa\\Session\\SessionStorage\\FileStorage';
        $args = DI::config()->getIfExists('session/storage/arguments') ?? [];

        $this->storage = new $class(...$args);

        // disable internal session handler
        $callable = function () {
            // this exception will not be displayed, instead "FatalErrorException"
            // with "Error: session_start(): Failed to initialize storage module: user (path: /var/lib/php/sessions)"
            throw new \LogicException('Cannot used internal session in Сáша HttpApp');
        };
        session_set_save_handler($callable, $callable, $callable, $callable, $callable, $callable, $callable);
    }

    /**
     * @return bool
     */
    private function haveCookie() : bool
    {
        return !is_null(self::request()->getCookie($this->name));
    }

    /**
     *
     */
    public function init()
    {
        if (!self::$init) {
            $event = new TimerEvent('session.open');
            $this->storage->open();
            self::emit($event);

            if (self::request()->getCookie($this->name)) {
                $this->id = self::request()->getCookie($this->name)->getValue();
            }

            if (!$this->id) {
                $this->create();
            } else {
                $event = new TimerEvent('session.read');
                $readData = $this->storage->read($this->id);

                $maxDuration = $this->storage->getDuration();

                if ($readData === false) {
                    $this->create();
                } else {
                    list($this->data, $this->startTime, $this->accessTime, $length) = $readData;
                }

                if (isset($length)) {
                    $event->setData([
                        'length' => $length,
                        'startTime' => date('Y-m-d H:i:s', $this->startTime),
                        'accessTime' => date('Y-m-d H:i:s', $this->accessTime),
                    ]);
                }
                self::emit($event);

                if ($readData !== false && $this->accessTime + $maxDuration < time()) {
                    $this->storage->destroy($this->id);
                    $this->create();
                }
            }

            $this->addHeaders();

            self::dispatcher()->addListener('app.end', function () {
                $this->save();
            });

            self::$init = true;
        }
    }

    /**
     */
    private function create()
    {
        $this->id = md5(uniqid((string) rand(), true));
        $this->accessTime = null;
        $this->startTime = time();
        $this->data = [];
        self::response()->addCookie(new Cookie($this->name, $this->id));
    }

    /**
     * add expiration headers to avoid caching.
     */
    private function addHeaders()
    {
        self::response()->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); // HTTP 1.1
        self::response()->addHeader('Pragma', 'no-cache'); // HTTP 1.0
        self::response()->addHeader('Expires', '-1'); // Proxies
    }

    /**
     * is the session is init and data loaded.
     *
     * @var bool
     */
    protected static $init = false;

    /**
     * @return bool
     */
    public function isStarted() : bool
    {
        return self::$init;
    }

    /**
     * is the data have changed.
     *
     * @var bool
     */
    private $changed = false;

    /**
     * The session id.
     *
     * @var string
     */
    private $id;

    /**
     * @return string
     */
    public function getId() : string
    {
        return $this->id;
    }

    /**
     * The name of the session cookie.
     *
     * @var string
     */
    private $name;

    /**
     * Gets the name of the cookie.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     *
     * @return $this|self
     */
    public function setName(string $name) : self
    {
        // from PHP source code
        if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
            throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
        }

        if (empty($name)) {
            throw new \InvalidArgumentException('The cookie name cannot be empty.');
        }

        $this->name = $name;

        return $this;
    }

    /**
     * @var int
     */
    protected $startTime;

    /**
     * @return int
     */
    public function getStartTime() : int
    {
        return $this->startTime;
    }

    /**
     * @var int
     */
    protected $accessTime;

    /**
     * @return int
     */
    public function getAccessTime() : int
    {
        return $this->accessTime;
    }

    /**
     * @var array
     */
    private $data = [];

    /**
     * @return array
     */
    public function getData() : array
    {
        if (self::$init == false) {
            $this->init();
        }

        return $this->data;
    }

    /**
     * @param string $name
     *
     * @return mixed
     */
    public function get(string $name)
    {
        if (!$this->haveCookie()) {
            return null;
        }

        if (self::$init == false) {
            $this->init();
        }

        return isset($this->data[$name]) ? $this->data[$name] : null;
    }

    /**
     * @param string $name
     *
     * @return mixed
     */
    public function getFlush(string $name)
    {
        if (!$this->haveCookie()) {
            return null;
        }

        $return = $this->get($name);
        $this->remove($name);

        return $return;
    }

    /**
     * @param string $name
     * @param $value
     *
     * @return $this|self
     */
    public function set(string $name, $value) : self
    {
        if (self::$init == false) {
            $this->init();
        }

        if (array_key_exists($name, $this->data) && $this->data[$name] === $value) {
            return $this;
        }

        $this->changed = true;

        $this->data[$name] = $value;

        return $this;
    }

    /**
     * @param string $name
     * @param $value
     *
     * @return $this|self
     */
    public function push(string $name, $value) : self
    {
        $data = $this->get($name) ?: [];
        $data[] = $value;

        return $this->set($name, $data);
    }

    /**
     * @param string $name
     * @param $value
     *
     * @return $this|self
     */
    public function merge(string $name, $value) : self
    {
        $data = $this->get($name) ?: [];

        return $this->set($name, array_merge($data, $value));
    }

    /**
     * @param string $name
     *
     * @return $this|self
     */
    public function remove(string $name) : self
    {
        if (self::$init == false) {
            $this->init();
        }

        if (!isset($this->data[$name])) {
            return $this;
        }

        $this->changed = true;

        unset($this->data[$name]);

        return $this;
    }

    /**
     * @return bool
     */
    public function destroy() : bool
    {
        if (self::$init == false) {
            $this->init();
        }

        $event = new TimerEvent('session.destroy');

        self::$init = false;

        $return = $this->storage->destroy($this->id);
        self::response()->clearCookie(new Cookie($this->name));

        self::emit($event);

        return $return;
    }

    /**
     * @param string $name
     *
     * @return bool
     */
    public function exist(string $name) : bool
    {
        if (self::$init == false) {
            $this->init();
        }

        return isset($this->data[$name]) ? true : false;
    }

    /**
     * @return bool
     */
    public function save() : bool
    {
        if (!self::$init) {
            return true;
        }

        if (!$this->accessTime) {
            $this->accessTime = time();
        }

        $ttl = DI::config()->getIfExists('session/refreshTtl') ?? 60;

        if (!$this->changed && $this->accessTime + $ttl < time()) {
            $this->accessTime = time();

            $event = new TimerEvent('session.touch');
            $return = $this->storage->touch($this->id, $this->data, $this->startTime, $this->accessTime);
        } elseif ($this->changed) {
            $this->accessTime = time();

            $event = new TimerEvent('session.write');
            $return = $this->storage->write($this->id, $this->data, $this->startTime, $this->accessTime);
        } else {
            return true;
        }

        $event->setData(['length' => $return]);
        self::emit($event);

        return $return === false ? false : true;
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */
namespace RedKiteCms\Rendering\Controller\Page;

/**
 * Class ApprovePageController is the object assigned to approve a page contribution
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\Seo
 */
abstract class ApprovePageController extends BasePageController
{
    /**
     * Implements the action to approve the page contribution
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function approve(array $options)
    {
        $pageName = $options["request"]->get('pageName');
        $seoData = $options["request"]->get('seo-data');
        $json = $options["page_manager"]
            ->contributor($options["username"])
            ->approve($pageName, $seoData["language"]);

        return $this->buildJSonResponse($json);
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Form\DataTransformer;

use OpenOrchestra\ModelInterface\Model\EmbedStatusInterface;
use OpenOrchestra\ModelInterface\Model\StatusInterface;
use OpenOrchestra\ModelInterface\Repository\StatusRepositoryInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

/**
 * Class EmbedStatusToStatusTransformer
 */
class EmbedStatusToStatusTransformer implements DataTransformerInterface
{
    protected $statusRepositoy;
    protected $embedStatusClass;

    /**
     * @param StatusRepositoryInterface $statusRepository
     * @param string                    $embedStatusClass
     */
    public function __construct(StatusRepositoryInterface $statusRepository, $embedStatusClass)
    {
        $this->statusRepositoy = $statusRepository;
        $this->embedStatusClass = $embedStatusClass;
    }

    /**
     * @param EmbedStatusInterface $value
     *
     * @return StatusInterface
     *
     * @throws TransformationFailedException When the transformation fails.
     */
    public function transform($value)
    {
        if ($value instanceof EmbedStatusInterface) {
            return $this->statusRepositoy->find($value->getId());
        }

        return '';
    }

    /**
     * @param StatusInterface $value
     *
     * @return EmbedStatusInterface
     *
     * @throws TransformationFailedException When the transformation fails.
     */
    public function reverseTransform($value)
    {
        if ($value === null) {
            return null;
        }

        $embedStatusClass = $this->embedStatusClass;

        return $embedStatusClass::createFromStatus($value);
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Component\Form;

/**
 * Support for uploaded file.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class FileUploaded{

	/**
	 * File name.
	 *
	 * @var string $name
	 */
	private $name;

	/**
	 * File name in tmp dir.
	 *
	 * @var string $tmpName
	 */
	private $tmpName;

	/**
	 * Error code
	 *
	 * @var int $error
	 */
	private $error;

	/**
	 * File size in bytes.
	 *
	 * @var int $size
	 */
	private $size;

	/**
	 * Mime type file.
	 *
	 * @var string $extension
	 */
	private $extension;

	/**
	 * Constructor.
	 *
	 * @param mixed[] $data
	 */
	public function __construct($data){
		$this->name=$data['name'];
		$this->tmpName=$data['tmp_name'];
		$this->error=$data['error'];
		$this->size=$data['size'];

		if($this->tmpName){
			$fileInfo = new \finfo(FILEINFO_MIME);
			$this->extension=$fileInfo->buffer(file_get_contents($this->tmpName));
		}

	}

	/**
	 * Save uploaded file to destiny dir
	 *
	 * @param string $path path dir to save file
	 * @param string $name file name if is empty then set name on origin name
	 * @throws FileFailSavedException
	 */
	public function save($path,$name=null){
		if(!file_exists($path)){
			mkdir($path,0777,true);
		}

		$destinationPath=rtrim($path, '/');
		if($name){
			$destinationPath.='/'.$name;
		}
		else{
			$destinationPath.='/'.$this->name;
		}

		if(!copy($this->tmpName, $destinationPath)){
			//detect error reason
			$reason='Unknown';
			if(!file_exists($path)){
				$reason='Path "'.$path.'" not exists.';
			}
			else if(!is_writeable($path))
				$reason='Path "'.$path.'" required permission to write.';

			throw new FileFailSavedException($reason);
		}
	}

	/**
	 * Return true if is has error on uploaded, else return false.
	 *
	 * @return boolean
	 * @since 0.12.0
	 */
	public function isError(){
		return $this->error!='0';
	}

	/**
	 * Return error message if fail uploaded.
	 *
	 * @return string
	 * @since 0.12.0
	 */
	public function getError(){
		return $this->error;
	}

	/**
	 * Get origin file name.
	 *
	 * @return string
	 * @since 0.12.0
	 */
	public function getName(){
		return $this->name;
	}

	/**
	 * Get file size in bytes.
	 *
	 * @return int
	 * @since 0.17.0
	 */
	public function getSize(){
		return $this->size;
	}

	/**
	 * Get file extension (mime/type).
	 *
	 * @return string
	 * @since 0.17.0
	 */
	public function getExtension(){
		return $this->extension;
	}
}


<?php

namespace mtoolkit\cache\mysql;

use mtoolkit\cache\MCacheItem;
use mtoolkit\cache\MCacheManager;
use mtoolkit\core\MDataType;

/**
 * Class MMySQLCacheManager
 *
 * @package mtoolkit\cache\mysql
 */
class MMySQLCacheManager extends MCacheManager
{
    const MYSQL_DATE_FORMAT = 'Y-m-d H:i:s';

    private static $CREATE_TABLE = '
        CREATE TABLE IF NOT EXISTS %s(
            `key` VARCHAR(200) NOT NULL,
            `value` TEXT,
            `inserted` DATETIME,
            `ttl` int(11),
            `end_validation` DATETIME,
            PRIMARY KEY (`key`)
        )
    ';

    /**
     * @var string
     */
    private static $UPSERT = '
        INSERT INTO %s(
          `key`, `value`, `inserted`, `ttl`, `end_validation`
        )
        VALUES (
          ?,
          ?,
          NOW(),
          ?,
          DATE_ADD(NOW(), INTERVAL ? SECOND)
        )
        ON DUPLICATE KEY UPDATE
          `value`=?,
          `inserted`=NOW(),
          `ttl`=?,
          `end_validation`=DATE_ADD(NOW(), INTERVAL ? SECOND)
    ';

    /**
     * @var string
     */
    private static $DELETE = '
      DELETE FROM %s
      WHERE ( `key`=? OR ? is null )
    ';

    /**
     * @var string
     */
    private static $SELECT = '
        SELECT *
        FROM %s
        WHERE `end_validation` > NOW()
    ';

    /**
     * @var string
     */
    private $tableName = null;

    /**
     * @var \PDO
     */
    private $pdoConnection = null;

    /**
     * MPDOCacheManager constructor.
     *
     * @param array $option Must contains an item called 'db' containing an {@link \PDO} object and an item called
     *     'table' containing the table name of the database to use to store the cache item.
     * @throws \Exception
     */
    public function __construct( array $option )
    {
        parent::__construct( $option );

        if( isset( $option['db'] ) === false || isset( $option['table'] ) === false )
        {
            throw new \Exception( 'Mandatory options are not set!' );
        }

        $this->setPdoConnection( $option['db'] );
        $this->setTableName( $option['table'] );
    }

    /**
     * Create the cache table on the database.
     *
     * @return bool
     */
    public function createTable()
    {
        $stmt = $this->pdoConnection->prepare( sprintf( self::$CREATE_TABLE, $this->tableName ) );

        return $stmt->execute();
    }

    /**
     * @param array $keys
     * @return MCacheItem[]
     */
    public function getItems( array $keys )
    {
        $select = self::$SELECT;

        if( is_null( $keys ) === false && count( $keys ) > 0 )
        {
            $keyClause = ' AND `key` IN (%s) ';
            $keysString = '\'' . implode( '\', \'', $keys ) . '\'';
            $select .= sprintf( $keyClause, $keysString );
        }

        $stmt = $this->pdoConnection->prepare( sprintf( $select, $this->tableName ) );
        $result = $stmt->execute();

        if( $result === false )
        {
            return array();
        }

        $result = $stmt->fetchAll( \PDO::FETCH_ASSOC );

        $items = array();
        foreach( $result as $row )
        {
            $i = new MCacheItem();
            $i->setValue( $row['value'] )
                ->setTtl( (int)$row['ttl'] )
                ->setKey( $row['key'] );

            $items[] = $i;
        }

        return $items;
    }

    /**
     * @param array $keys
     */
    public function deleteItems( array $keys )
    {
        array_map(
            function ( $key )
            {
                $i=1;
                $stmt = $this->pdoConnection->prepare( sprintf( self::$DELETE, $this->tableName ) );
                $stmt->bindParam( $i++, $key, \PDO::PARAM_STR );
                $stmt->bindParam( $i, $key, \PDO::PARAM_STR );

                return $stmt->execute();
            },
            $keys
        );
    }

    /**
     * @param MCacheItem $item
     * @return bool
     */
    public function addItem( MCacheItem $item )
    {
        $i=0;
        $stmt = $this->pdoConnection->prepare( sprintf( self::$UPSERT, $this->tableName ) );
        $stmt->bindParam( ++$i, $item->getKey(), \PDO::PARAM_STR );
        $stmt->bindParam( ++$i, $item->getValue(), \PDO::PARAM_STR );
        $stmt->bindParam( ++$i, $item->getTtl(), \PDO::PARAM_INT );
        $stmt->bindParam( ++$i, $item->getTtl(), \PDO::PARAM_INT );
        $stmt->bindParam( ++$i, $item->getValue(), \PDO::PARAM_STR );
        $stmt->bindParam( ++$i, $item->getTtl(), \PDO::PARAM_INT );
        $stmt->bindParam( ++$i, $item->getTtl(), \PDO::PARAM_INT );

        return $stmt->execute();
    }

    /**
     * @param string $tableName
     * @return MMySQLCacheManager
     */
    private function setTableName( $tableName )
    {
        MDataType::mustBe( MDataType::STRING );
        $this->tableName = $tableName;

        return $this;
    }

    /**
     * @param \PDO $pdoConnection
     * @return MMySQLCacheManager
     */
    private function setPdoConnection( \PDO $pdoConnection )
    {
        $this->pdoConnection = $pdoConnection;

        return $this;
    }

    /**
     * @return void
     */
    public function flush( )
    {
        $this->deleteItems( null );
    }
}


<?php
namespace core\manage\logic;

use cms\Logic;

class MemberGroupLogic extends Logic
{

    /**
     * 群组菜单
     *
     * @param number $group_id
     * @return array
     */
    public function getGroupMenu($group_id)
    {
        $map = [
            'id' => $group_id
        ];
        $group = $this->model->field('group_menus')
            ->where($map)
            ->find();
        if ($group && $group['group_menus']) {
            return explode(',', $group['group_menus']);
        }
        return [];
    }

    /**
     * 群组下拉选择
     *
     * @return array
     */
    public function getGroupSelect()
    {
        $group_list = $this->model->select();
        $group_select = [];
        foreach ($group_list as $vo) {
            $group_select[] = [
                'name' => $vo['group_name'],
                'value' => $vo['id']
            ];
        }
        return $group_select;
    }

    /**
     * 群组状态
     *
     * @return array
     */
    public function groupStatus()
    {
        return [
            [
                'name' => '启用',
                'value' => 1
            ],
            [
                'name' => '禁用',
                'value' => 0
            ]
        ];
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Factory\Form\Element;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Form\Element\Birthday,
    CmsUser\Options\ModuleOptionsInterface,
    CmsUser\Options\ModuleOptions;

class BirthdayElementFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return Birthday
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();
        return $this->configureElement(new Birthday('birthday'), $services);
    }

    /**
     * @param Birthday $element
     * @param ServiceLocatorInterface $services
     * @return Birthday
     */
    protected function configureElement(Birthday $element, ServiceLocatorInterface $services)
    {
        /* @var $options ModuleOptionsInterface */
        $options = $services->get(ModuleOptions::class);

        $year = (new \DateTime('now'))->format('Y');
        $element->setOptions([
            'label'                 => 'When were you born?',
            'create_empty_option'   => true,
            'min_year'              => $year - 100,
            'max_year'              => $year - 18,
            'day_attributes' => [
                'required' => true,
            ],
            'month_attributes' => [
                'required' => true,
            ],
            'year_attributes' => [
                'required' => true,
            ],
        ]);

        return $element;
    }
}


<?php

namespace BlogBundle\Controller;

use Doctrine\ORM\Query;
use BlogBundle\Entity\Tag;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use BlogBundle\Form\TagType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

/**
 * Tag controller.
 *
 * @Route("/admin/post/tag")
 */
class TagController extends Controller
{
    /**
     * Lists all Tag entities.
     *
     * @return array
     *
     * @Route("/")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * Returns a list of Tag entities in JSON format.
     *
     * @return JsonResponse
     *
     * @Route("/list.{_format}", requirements={ "_format" = "json" }, defaults={ "_format" = "json" })
     * @Method("GET")
     */
    public function listJsonAction()
    {
        $em = $this->getDoctrine()->getManager();

        /** @var \Kitchenit\AdminBundle\Services\DataTables\JsonList $jsonList */
        $jsonList = $this->get('json_list');
        $jsonList->setRepository($em->getRepository('BlogBundle:Tag'));

        $response = $jsonList->get();

        return new JsonResponse($response);
    }

    /**
     * Creates a new Tag entity.
     *
     * @Route("/new")
     * @Method({"GET", "POST"})
     * @Template()
     */
    public function newAction(Request $request)
    {
        $tag = new Tag();
        $form = $this->createForm('BlogBundle\Form\TagType', $tag);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($tag);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', 'post.tag.created');

            return $this->redirectToRoute('blog_tag_index');
        }

        return array(
            'entuty' => $tag,
            'form' => $form->createView(),
        );
    }

    /**
     * Finds and displays a Tag entity.
     *
     * @Route("/{id}")
     * @Method("GET")
     * @Template()
     */
    public function showAction(Tag $tag)
    {
        $deleteForm = $this->createDeleteForm($tag);

        return array(
            'entity' => $tag,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Tag entity.
     *
     * @Route("/{id}/edit")
     * @Method({"GET", "POST"})
     * @Template()
     */
    public function editAction(Request $request, Tag $tag)
    {
        $deleteForm = $this->createDeleteForm($tag);
        $editForm = $this->createForm('BlogBundle\Form\TagType', $tag);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($tag);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', 'post.tag.edited');

            return $this->redirectToRoute('blog_tag_index');
        }

        return array(
            'entity' => $tag,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Tag entity.
     *
     * @Route("/{id}")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Tag $tag)
    {
        $form = $this->createDeleteForm($tag);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($tag);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', 'post.tag.deleted');
        }

        return $this->redirectToRoute('blog_tag_index');
    }

    /**
     * Creates a form to delete a Tag entity.
     *
     * @param Tag $tag The Tag entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Tag $tag)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('blog_tag_delete', array('id' => $tag->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /**
     * Sorts a list of features.
     *
     * @param Request $request
     * @param int     $tagId
     *
     * @throws NotFoundHttpException
     * @return array|Response
     *
     * @Route("/sort")
     * @Method({"GET", "POST"})
     * @Template
     */
    public function sortAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        if ($request->isXmlHttpRequest()) {
            $this->get('admin_manager')->sort('BlogBundle:Tag', $request->get('values'));

            return new Response(0, 200);
        }

        $tags = $em->getRepository('BlogBundle:Tag')->findBy(
            array('parentTag' => NULL),
            array('order' => 'asc')
        );

        return array(
            'tags' => $tags
        );
    }
}


<?php
/**
 * Jaeger
 *
 * @copyright	Copyright (c) 2015-2016, mithra62
 * @link		http://jaeger-app.com
 * @version		1.0
 * @filesource 	./Db/Mysqli.php
 */

namespace JaegerApp\Db;

use voku\db\DB as vDb;

/**
 * Jaeger - MySQLi Database Object
 *
 * Wrapper for the MySQLi database interface
 *
 * @package Database
 * @author Eric Lamb <eric@mithra62.com>
 */
class Mysqli implements DbInterface
{
    /**
     * The primary table we're working with
     * @var string
     */
    protected $table = null;

    /**
     * Any filtering for a WHERE SQL clause
     * @var mixed
     */
    protected $where = false;

    /**
     * The database connection credentials
     * @var array
     */
    protected $credentials = array();

    /**
     * The database object we're piggybacking on
     * @var \voku\db\DB
     */
    protected $db = null;

    /**
     * Changes the databse connection to use a new database
     * @param string $db_name
     */
    public function setDbName($db_name)
    {
        @mysqli_select_db($this->getDb()->getLink(), $db_name);
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::select()
     */
    public function select($table, $where = '1=1')
    {
        $this->table = $table;
        $this->where = $where;
        return $this;
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::get()
     */
    public function get()
    {
        $data = $this->getDb()->select($this->table, $this->where);
        return $data->fetchAllArray();

    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::query()
     */
    public function query($sql = '', $return = false)
    {
        $data = $this->getDb()->query($sql, $return);
        if( $data instanceof \voku\db\Result )
        {
            return $data->fetchAllArray();
        }
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::getTableStatus()
     */
    public function getTableStatus()
    {
        $tables = $this->query("SHOW TABLE STATUS", true);
        return $tables;
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::getCreateTable()
     */
    public function getCreateTable($table, $if_not_exists = false)
    {
        $sql = sprintf('SHOW CREATE TABLE `%s` ;', $table);
        $statement = $this->query($sql, true);
        $string = false;
        if (! empty($statement['0']['Create Table'])) {
            $string = $statement['0']['Create Table'];
        }

        if ($if_not_exists) {
            $replace = substr($string, 0, 12);
            if ($replace == 'CREATE TABLE') {
                $string = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS ', $string);
            }
        }

        return $string;
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::clear()
     */
    public function clear()
    {
        $this->table = null;
        $this->where = null;
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::totalRows()
     */
    public function totalRows($table)
    {
        $sql = sprintf('SELECT COUNT(*) AS count FROM `%s`', $table);
        $statement = $this->query($sql, true);
        if ($statement) {
            if (isset($statement['0']['count'])) {
                return $statement['0']['count'];
            }
        }

        return '0';
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::getColumnns()
     */
    public function getColumns($table)
    {
        $sql = sprintf('SHOW COLUMNS FROM `%s`', $table);
        $statement = $this->query($sql, true);
        if ($statement) {
            return $statement;
        }
        return array();
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::escape()
     */
    public function escape($string)
    {
        return $this->getDb()->escape($string);
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::getAllTables()
     */
    public function getAllTables()
    {
        return $this->getDb()->getAllTables();
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::insert()
     */
    public function insert($table, array $data = array())
    {
        return $this->getDb()->insert($table, $data);
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::update()
     */
    public function update($table, $data, $where)
    {
        return $this->getDb()->update($table, $data, $where);
    }

    /**
     *
     * @param array $credentials
     * @return \JaegerApp\Db\Mysqli
     */
    public function setCredentials(array $credentials)
    {
        $this->credentials = $credentials;
        return $this;
    }

    /**
     * (non-PHPdoc)
     * @see \JaegerApp\Db\DbInterface::getDb()
     */
    public function getDb($force = false)
    {
        if (is_null($this->db)) {

            $this->db = vDb::getInstance($this->credentials['host'], $this->credentials['user'], $this->credentials['password'], $this->credentials['database']);
        }

        return $this->db;
    }
}


<?php

namespace Monolyth\Booby;

use Generator;

class Flash
{
    private $msg;
    private $options;
    private $index;

    private static $store = [];

    /**
     * @param string $msg
     * @param array $options
     * @return void
     */
    public function __construct(string $msg, array $options = [])
    {
        $this->msg = $msg;
        $this->options = $options;
        $this->index = spl_object_hash($this);
    }

    /**
     * @param string $name
     * @return mixed The value of the option, or null if not found.
     */
    public function __get(string $name)
    {
        if (isset($this->options[$name])) {
            return $this->options[$name];
        }
        return null;
    }

    /**
     * @param string $name
     * @return bool
     */
    public function __isset(string $name) : bool
    {
        return isset($this->options[$name]);
    }

    /**
     * @return string
     */
    public function __toString() : string
    {
        $msg = $this->msg;
        unset(self::$store[$this->index]);
        return $msg;
    }

    /**
     * @param string $msg
     * @param array $options
     * @return Monolyth\Booby\Flash
     */
    public static function me(string $msg, array $options = []) : Flash
    {
        self::init();
        $msg = new static($msg, $options);
        self::$store[spl_object_hash($msg)] = $msg;
        return $msg;
    }

    /**
     * Get messages one by one.
     *
     * @return Generator
     */
    public static function each() : Generator
    {
        self::init();
        foreach (self::$store as $msg) {
            yield $msg;
        }
    }

    /**
     * Get all current messages.
     *
     * @return array
     */
    public static function all() : array
    {
        self::init();
        return self::$store;
    }

    /**
     * Flush all messages (i.e., discard regardless of whether they were
     * shown to the user).
     *
     * @return void
     */
    public static function flush() : void
    {
        self::init();
        self::$store = [];
        $_SESSION['Booby'] = [];
    }

    /**
     * Helper to check if we were initialized.
     *
     * @return void
     */
    private static function init() : void
    {
        static $inited = false;
        if (!$inited) {
            if (!isset($_SESSION['Booby']) || !$_SESSION['Booby']) {
                $_SESSION['Booby'] = [];
            }
            self::$store =& $_SESSION['Booby'];
            $inited = true;
        }
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license
 */

namespace cascade\commands;

use canis\caching\Cacher;
use Yii;
use yii\helpers\Console;
use yii\helpers\FileHelper;

/**
 * ToolsController runs various commands for Cascade.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class ToolsController extends \canis\console\Controller
{
    /**
     * Flush the cache.
     *
     * @param string $category flush a particular category from cache [optional]
     */
    public function actionFlush($category = null)
    {
        if (is_null($category)) {
            $category = $this->prompt("Category (blank for all): ");
        }
        if (empty($category)) {
            $category = 'all';
        } else {
            $category = ['category', $category];
        }
        Cacher::invalidateGroup($category);
        $this->out("Done!");
    }

    /**
     * Fix the code formatting throughout Cascade and its related libraries.
     */
    public function actionFixProject()
    {
        $dirs = [
            Yii::getAlias('@cascade'),
            Yii::getAlias('@canis'),
            Yii::getAlias('@cascade/modules/core'),
            Yii::getAlias('@psesd/cascade'),
            Yii::getAlias('@canis/deferred'),
            Yii::getAlias('@canis/notification'),
        ];
        $customStart = microtime(true);
        Console::stdout("Running custom fixes..." . PHP_EOL);
        foreach ($dirs as $dir) {
            $dirStart = microtime(true);
            $changed = 0;
            Console::stdout("\t" . $dir . "...");
            $files = FileHelper::findFiles($dir, ['only' => ['*.php'], 'recursive' => true]);
            Console::stdout("found " . count($files) . " files...");
            foreach ($files as $file) {
                if ($this->fixFile($file)) {
                    $changed++;
                }
            }
            Console::stdout("changed {$changed} files in " . round(microtime(true)-$dirStart, 1) . "s!" . PHP_EOL);
        }
        Console::stdout("done in " . round(microtime(true)-$customStart, 1) . "s!" . PHP_EOL . PHP_EOL);

        $phpcsStart = microtime(true);
        Console::stdout("Running style fixes..." . PHP_EOL);
        foreach ($dirs as $dir) {
            $dirStart = microtime(true);
            $changed = 0;
            Console::stdout("\t" . $dir . "...");
            $configFiles = [];
            $configFiles[] = $dir . DIRECTORY_SEPARATOR . '.php_cs';
            $configFiles[] = dirname($dir) . DIRECTORY_SEPARATOR . '.php_cs';
            $configFiles[] = dirname(dirname($dir)) . DIRECTORY_SEPARATOR . '.php_cs';
            $foundConfig = false;
            foreach ($configFiles as $configFile) {
                if (file_exists($configFile)) {
                    $foundConfig = $configFile;
                    break;
                }
            }
            if (!$foundConfig) {
                Console::stdout("skipped!" . PHP_EOL);
                continue;
            }
            $phpcsBinary = Yii::getAlias('@vendor/bin/php-cs-fixer');
            if (!file_exists($phpcsBinary)) {
                Console::stdout("no php-cs-fixer binary!" . PHP_EOL);
                continue;
            }

            $command = [];
            $command[] = PHP_BINARY;
            $command[] = $phpcsBinary;
            $command[] = '--no-interaction';
            $command[] = '--config-file=' . $foundConfig;
            // $command[] = '--quiet';
            $command[] = 'fix';

            exec(implode(' ', $command), $output, $exitCode);
            Console::stdout("done in " . round(microtime(true)-$dirStart, 1) . "s!" . PHP_EOL);
        }
        Console::stdout("done in " . round(microtime(true)-$phpcsStart, 1) . "s!" . PHP_EOL . PHP_EOL);
    }

    /**
     * Run a series of fixes on a file's code formatting.
     *
     * @param string $file file name of the file being checked
     *
     * @return bool if the file was changed
     */
    public function fixFile($file)
    {
        $contents = preg_split("/\\r\\n|\\r|\\n/", file_get_contents($file));
        $changed = false;
        if ($this->fixFileSlashes($file, $contents)) {
            $changed = true;
        }
        // if ($this->fixDocBlockPlaceholder($file, $contents)) {
        //     $changed = true;
        // }
        if ($changed) {
            file_put_contents($file, implode("\n", $contents));
        }

        return $changed;
    }

    /**
     * Removes the old @doctodo.
     *
     * @param string     $file     file name of the file being checked
     * @param array $contents array of the file contents
     *
     * @return bool if the file was changed
     */
    public function fixDocBlockPlaceholder($file, &$contents)
    {
        $changed = false;
        foreach ($contents as $lineNumber => $line) {
            $line = trim($line);
            if (substr($line, 0, 1) === '*' || substr($line, 0, 1) === '/') {
                if (strpos($line, '@doctodo write class description') !== false) {
                    unset($contents[$lineNumber]);
                    $changed = true;
                }
            }
        }

        return $changed;
    }

    /**
     * Fixes slashes inside namespace strings.
     *
     * @param string     $file     file name of the file being fixed
     * @param array $contents array of the file contents
     *
     * @return bool if the file changed
     */
    public function fixFileSlashes($file, &$contents)
    {
        $changed = false;
        foreach ($contents as $lineNumber => $line) {
            if (preg_match('/(psesd|canis|cascade)\\\\\\\/', $line) === 1) {
                $fixedLine = preg_replace('/\\\\\\\/', '\\', $line);
                if ($fixedLine !== $line) {
                    $contents[$lineNumber] = $fixedLine;
                    $changed = true;
                }
            }
        }

        return $changed;
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Broadcast.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Broadcast;

use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Core\Exceptions\HttpException;

/**
 * Class Broadcast.
 */
class Broadcast extends AbstractAPI
{
    const API_SEND_BY_GROUP = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall';
    const API_SEND_BY_OPENID = 'https://api.weixin.qq.com/cgi-bin/message/mass/send';
    const API_DELETE = 'https://api.weixin.qq.com/cgi-bin/message/mass/delete';
    const API_PREVIEW = 'https://api.weixin.qq.com/cgi-bin/message/mass/preview';
    const API_GET = 'http://api.weixin.qq.com/cgi-bin/message/mass/get';

    const PREVIEW_BY_OPENID = 'touser';
    const PREVIEW_BY_NAME = 'towxname';

    const MSG_TYPE_TEXT = 'text'; // 文本
    const MSG_TYPE_NEWS = 'news'; // 图文
    const MSG_TYPE_VOICE = 'voice'; // 语音
    const MSG_TYPE_IMAGE = 'image'; // 图片
    const MSG_TYPE_VIDEO = 'video'; // 视频
    const MSG_TYPE_CARD = 'card'; // 卡券

    /**
     * Send a message.
     *
     * @param string $msgType message type
     * @param mixed  $message message
     * @param mixed  $to
     *
     * @return mixed
     */
    public function send($msgType, $message, $to = null)
    {
        $message = (new MessageBuilder())->msgType($msgType)->message($message)->to($to)->build();

        $api = is_array($to) ? self::API_SEND_BY_OPENID : self::API_SEND_BY_GROUP;

        return $this->post($api, $message);
    }

    /**
     * Send a text message.
     *
     * @param mixed $message message
     * @param mixed $to
     *
     * @return mixed
     */
    public function sendText($message, $to = null)
    {
        return $this->send(self::MSG_TYPE_TEXT, $message, $to);
    }

    /**
     * Send a news message.
     *
     * @param mixed $message message
     * @param mixed $to
     *
     * @return mixed
     */
    public function sendNews($message, $to = null)
    {
        return $this->send(self::MSG_TYPE_NEWS, $message, $to);
    }

    /**
     * Send a voice message.
     *
     * @param mixed $message message
     * @param mixed $to
     *
     * @return mixed
     */
    public function sendVoice($message, $to = null)
    {
        return $this->send(self::MSG_TYPE_VOICE, $message, $to);
    }

    /**
     * Send a image message.
     *
     * @param mixed $message message
     * @param mixed $to
     *
     * @return mixed
     */
    public function sendImage($message, $to = null)
    {
        return $this->send(self::MSG_TYPE_IMAGE, $message, $to);
    }

    /**
     * Send a video message.
     *
     * @param mixed $message message
     * @param mixed $to
     *
     * @return mixed
     */
    public function sendVideo($message, $to = null)
    {
        return $this->send(self::MSG_TYPE_VIDEO, $message, $to);
    }

    /**
     * Send a card message.
     *
     * @param mixed $message message
     * @param mixed $to
     *
     * @return mixed
     */
    public function sendCard($message, $to = null)
    {
        return $this->send(self::MSG_TYPE_CARD, $message, $to);
    }

    /**
     * Preview a message.
     *
     * @param string $msgType message type
     * @param mixed  $message message
     * @param string $to
     * @param string $by
     *
     * @return mixed
     */
    public function preview($msgType, $message, $to, $by = self::PREVIEW_BY_OPENID)
    {
        $message = (new MessageBuilder())->msgType($msgType)->message($message)->to($to)->buildPreview($by);

        return $this->post(self::API_PREVIEW, $message);
    }

    /**
     * Preview a text message.
     *
     * @param mixed  $message message
     * @param string $to
     * @param string $by
     *
     * @return mixed
     */
    public function previewText($message, $to, $by = self::PREVIEW_BY_OPENID)
    {
        return $this->preview(self::MSG_TYPE_TEXT, $message, $to, $by);
    }

    /**
     * Preview a news message.
     *
     * @param mixed  $message message
     * @param string $to
     * @param string $by
     *
     * @return mixed
     */
    public function previewNews($message, $to, $by = self::PREVIEW_BY_OPENID)
    {
        return $this->preview(self::MSG_TYPE_NEWS, $message, $to, $by);
    }

    /**
     * Preview a voice message.
     *
     * @param mixed  $message message
     * @param string $to
     * @param string $by
     *
     * @return mixed
     */
    public function previewVoice($message, $to, $by = self::PREVIEW_BY_OPENID)
    {
        return $this->preview(self::MSG_TYPE_VOICE, $message, $to, $by);
    }

    /**
     * Preview a image message.
     *
     * @param mixed  $message message
     * @param string $to
     * @param string $by
     *
     * @return mixed
     */
    public function previewImage($message, $to, $by = self::PREVIEW_BY_OPENID)
    {
        return $this->preview(self::MSG_TYPE_IMAGE, $message, $to, $by);
    }

    /**
     * Preview a video message.
     *
     * @param mixed  $message message
     * @param string $to
     * @param string $by
     *
     * @return mixed
     */
    public function previewVideo($message, $to, $by = self::PREVIEW_BY_OPENID)
    {
        return $this->preview(self::MSG_TYPE_VIDEO, $message, $to, $by);
    }

    /**
     * Preview a card message.
     *
     * @param mixed  $message message
     * @param string $to
     * @param string $by
     *
     * @return mixed
     */
    public function previewCard($message, $to, $by = self::PREVIEW_BY_OPENID)
    {
        return $this->preview(self::MSG_TYPE_CARD, $message, $to, $by);
    }

    /**
     * Preview a message by name.
     *
     * @param string $msgType message type
     * @param mixed  $message message
     * @param $to
     *
     * @return mixed
     */
    public function previewByName($msgType, $message, $to)
    {
        return $this->preview($msgType, $message, $to, self::PREVIEW_BY_NAME);
    }

    /**
     * Preview a text message by name.
     *
     * @param mixed $message message
     * @param $to
     *
     * @return mixed
     */
    public function previewTextByName($message, $to)
    {
        return $this->preview(self::MSG_TYPE_TEXT, $message, $to, self::PREVIEW_BY_NAME);
    }

    /**
     * Preview a news message by name.
     *
     * @param mixed $message message
     * @param $to
     *
     * @return mixed
     */
    public function previewNewsByName($message, $to)
    {
        return $this->preview(self::MSG_TYPE_NEWS, $message, $to, self::PREVIEW_BY_NAME);
    }

    /**
     * Preview a voice message by name.
     *
     * @param mixed $message message
     * @param $to
     *
     * @return mixed
     */
    public function previewVoiceByName($message, $to)
    {
        return $this->preview(self::MSG_TYPE_VOICE, $message, $to, self::PREVIEW_BY_NAME);
    }

    /**
     * Preview a image message by name.
     *
     * @param mixed $message message
     * @param $to
     *
     * @return mixed
     */
    public function previewImageByName($message, $to)
    {
        return $this->preview(self::MSG_TYPE_IMAGE, $message, $to, self::PREVIEW_BY_NAME);
    }

    /**
     * Preview a video message by name.
     *
     * @param mixed $message message
     * @param $to
     *
     * @return mixed
     */
    public function previewVideoByName($message, $to)
    {
        return $this->preview(self::MSG_TYPE_VIDEO, $message, $to, self::PREVIEW_BY_NAME);
    }

    /**
     * Preview a card message by name.
     *
     * @param mixed $message message
     * @param $to
     *
     * @return mixed
     */
    public function previewCardByName($message, $to)
    {
        return $this->preview(self::MSG_TYPE_CARD, $message, $to, self::PREVIEW_BY_NAME);
    }

    /**
     * Delete a broadcast.
     *
     * @param string $msgId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($msgId)
    {
        $options = [
            'msg_id' => $msgId,
        ];

        return $this->post(self::API_DELETE, $options);
    }

    /**
     * Get a broadcast status.
     *
     * @param string $msgId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function status($msgId)
    {
        $options = [
            'msg_id' => $msgId,
        ];

        return $this->post(self::API_GET, $options);
    }

    /**
     * post request.
     *
     * @param string       $url
     * @param array|string $options
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws HttpException
     */
    private function post($url, $options)
    {
        return $this->parseJSON('json', [$url, $options]);
    }
}


<?php
/**
 * Created by Marcin.
 * Date: 22.10.2017
 * Time: 22:15
 */

namespace mrcnpdlk\Monolog\Handler;

use mrcnpdlk\Monolog\Helper;

class ErrorLogHandler extends \Monolog\Handler\ErrorLogHandler
{
    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        parent::write($record);

        if (isset($record['message_orig'])) {
            error_log(Helper::logSuffix($record['message_orig']), $this->messageType);
        }
    }
}


<?php

/*
 * This file is part of the YepsuaGeneratorBundle.
 *
 * (c) Omar Yepez <omar.yepez@yepsua.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Yepsua\GeneratorBundle\UI;

use \YsGridForm as GridForm;
use \YsUIConstant as UIConstant;
use \YsJsFunction as JsFunction;
use \YsGridNavigator as GridNavigator;
use \YsGridConstants as GridConstants;
use \YsGridCustomButton as GridCustomButton;
use \YsGridFilterToolbar as GridFilterToolbar;
use \YsGridField as GridField;
use \YsJQueryBuilder as JQueryBuilder;
use \YsJQuery as JQuery;
use \YsJQueryConstant as JQueryConstant;

use \Yepsua\CommonsBundle\IO\ObjectUtil;

JQuery::useComponent(JQueryConstant::COMPONENT_JQGRID);

/**
 * Generates a Grid to show the data.
 * @author Omar Yepez <omar.yepez@yepsua.com>
 */
class Grid extends \YsGrid{

  private $translator;
  private $entityName;
  public static $ID_SUFFIX = "Grid";
  public static $RC_PREFIX = "rc";
  public static $CRUD_TRANSLATION_DOMAIN = "richcrud";
  public static $TRANSLATION_DOMAIN = "messages";

  public static $ROW_LIST_ALL = "-1";

  private $hasAddButton = true;
  private $hasEditButton = true;
  private $hasDeleteButton = true;
  private $hasShowButton = true;
  private $hasFilterButton = true;
  private $hasSearchButton = true;
  private $hasRefreshButton = true;
  private $translatorDomain;
  private $translatorProperties;
  private $translatorLocale;
  private $entityManager;

  public function __construct($entityName, $caption = null, $gridHtmlProperties = null) {
    $this->setMultiboxOnly(true);
    $this->setSortname(sprintf('%s.id',$entityName));
    $gridId = $entityName . self::$ID_SUFFIX;
    $this->setEntityName(ucfirst($entityName));
    $this->setTranslatorProperties(array());
    parent::__construct($gridId, $caption, $gridHtmlProperties);
    $this->hideFilterToolbar();
  }

  public function hideFilterToolbar(){
      $this->addPostSintax(sprintf("%s('.ui-search-toolbar').hide()",  JQueryBuilder::$jqueryVar));
  }

  /**
   * @deprecated
   */
  public function get($withCRUDButton = false){
    $this->createView($withCRUDButton);
  }

  public function createView($withCRUDButton = false){
    $this->_getNavigator();
    if($withCRUDButton){
        $this->addCRUDButtons();
    }
    $this->configureNavigator();
    $this->configure();
  }

  public function _getNavigator(){
    return ($this->getNavigator() !== null)
           ? $this->getNavigator()
           : new GridNavigator();
  }

  public function addCRUDButtons(){
    $navigator = $this->_getNavigator();
    if($this->hasAddButton()){
      // Button -> New entity
      $button = new GridCustomButton();
      $button->setCaption('');
      $button->setButtonIcon(UIConstant::ICON_PLUS);
      $button->setTitle($this->translator->trans('grid.btn.new.title'));
      $button->setOnClickButton(
        new JsFunction(sprintf("%s%s%s()",self::$RC_PREFIX, "New", $this->getEntityName()))
      );
      $navigator->addCustomButton($button);
    }

    if($this->hasEditButton()){
      // Button -> Edit entity
      $button = new GridCustomButton();
      $button->setCaption('');
      $button->setButtonIcon(UIConstant::ICON_PENCIL);
      $button->setTitle($this->translator->trans('grid.btn.edit.title'));
      $button->setOnClickButton(
        new JsFunction(sprintf("%s%s%s()",self::$RC_PREFIX, "Edit", $this->getEntityName()))
      );
      $navigator->addCustomButton($button);
    }

    if($this->hasDeleteButton()){
      // Button -> Delete entity
      $button = new GridCustomButton();
      $button->setCaption('');
      $button->setButtonIcon(UIConstant::ICON_CLOSE);
      $button->setTitle($this->translator->trans("grid.btn.delete.title"));
      $button->setOnClickButton(
        new JsFunction(sprintf("%s%s%s()",self::$RC_PREFIX, "Delete", $this->getEntityName()))
      );
      $navigator->addCustomButton($button);
    }

    // Button -> Show entity
    $button = new GridCustomButton();
    $button->setCaption('');
    $button->setButtonIcon(UIConstant::ICON_DOCUMENT);
    $button->setTitle($this->translator->trans("grid.btn.show.title"));
    $button->setOnClickButton(
      new JsFunction(sprintf("%s%s%s()",self::$RC_PREFIX, "Show", $this->getEntityName()))
    );
    $navigator->addCustomButton($button);
    $this->setNavigator($navigator);
  }

  protected function configureNavigator(){
    $navigator = $this->_getNavigator();

    // No Buttons
    $navigator->noDefaultButtons();

    if($this->hasFilterButton()){
      // Filter -> Button
      $button = new GridCustomButton();
      $button->setCaption($this->translator->trans("grid.btn.filter"));
      $button->setButtonIcon(UIConstant::ICON_PIN_S);
      $button->setTitle($this->translator->trans("grid.btn.filter.title"));
      $button->setOnClickButton(
        new JsFunction(sprintf("$('#%s')[0].toggleToolbar()",$this->getGridId()))
      );
      $navigator->addCustomButton($button);
    }

    if($this->hasSearchButton()){
      // Search -> Button
      $searchForm = new GridForm();
      $searchForm->setMultipleSearch(true);
      $navigator->setSearchForm($searchForm);
    }
    if($this->hasRefreshButton()){
      // Refresh -> Button
      $navigator->setRefresh(true);
      $this->setNavigator($navigator);
    }
  }

  public function configure(){
    $this->setWidth("100%");
    $this->setHeight('auto');
    $this->setDataType(GridConstants::DATA_TYPE_JSON);
    $this->setRowList(array(10,50,100, Grid::$ROW_LIST_ALL));
    $this->setLoadComplete(new \YsJsFunction(sprintf('$("option[value=%1$s]").text("%2$s");', static::$ROW_LIST_ALL, $this->getTranslator()->trans("grid.cbo.rownum.all"))));
    $this->setViewRecords(true);

    $filterToolBar = new GridFilterToolbar();
    $filterToolBar->setStringResult(true);
    $filterToolBar->setSearchOnEnter(true);
    $filterToolBar->setToggleToolbar(true);
    $this->setFilterToolbar($filterToolBar);

    $this->setMultiselect(true);
    $this->setRowNumbers(true);
  }

  /**
   * The Symfony2 tranlator
   * @return \Symfony\Component\Translation\Translator
   */
  public function getTranslator() {
    return $this->translator;
  }

  /**
   * The Symfony2 tranlator
   * @param \Symfony\Component\Translation\Translator $translator
   */
  public function setTranslator($translator, $translatorDomain = null, $translatorLocale = null) {
    $this->translator = $translator;
    $this->setTranslatorDomain($translatorDomain);
    $this->setTranslatorLocale($translatorLocale);
    $this->setCaption($this->translate($this->getCaption()));
  }

  private function translate($value){
    return $this->getTranslator()->trans($value, $this->getTranslatorProperties() , $this->getTranslatorDomain());
  }

  public function getEntityName() {
    return $this->entityName;
  }

  public function setEntityName($entityName) {
    $this->entityName = $entityName;
  }

  public function hasAddButton() {
    return $this->hasAddButton;
  }

  public function setHasAddButton($hasAddButton) {
    $this->hasAddButton = $hasAddButton;
  }

  public function hasEditButton() {
    return $this->hasEditButton;
  }

  public function setHasEditButton($hasEditButton) {
    $this->hasEditButton = $hasEditButton;
  }

  public function hasDeleteButton() {
    return $this->hasDeleteButton;
  }

  public function setHasDeleteButton($hasDeleteButton) {
    $this->hasDeleteButton = $hasDeleteButton;
  }

  public function hasShowButton() {
    return $this->hasShowButton;
  }

  public function setHasShowButton($hasShowButton) {
    $this->hasShowButton = $hasShowButton;
  }

  public function hasFilterButton() {
    return $this->hasFilterButton;
  }

  public function setHasFilterButton($hasFilterButton) {
    $this->hasFilterButton = $hasFilterButton;
  }

  public function hasSearchButton() {
    return $this->hasSearchButton;
  }

  public function setHasSearchButton($hasSearchButton) {
    $this->hasSearchButton = $hasSearchButton;
  }

  public function hasRefreshButton() {
    return $this->hasRefreshButton;
  }

  public function setHasRefreshButton($hasRefreshButton) {
    $this->hasRefreshButton = $hasRefreshButton;
  }

  public function noWriteActions(){
    $this->setHasDeleteButton(false);
    $this->setHasEditButton(false);
    $this->setHasAddButton(false);
  }

  public function addGridField(GridField $gridFields) {
    $gridFields->setColName($this->translate($gridFields->getColName()));
    parent::addGridField($gridFields);
  }

  public function setArrayGridField($gridFields) {;
    if(is_array($gridFields)){
      foreach ($gridFields as $key => $value) {
        $field = new GridField($key, null);
        if(is_array($value)){
          if( isset($value['title']) ){
            $field->setColName($value['title']);
          }
          foreach ($value as $_key => $_value) {
            $field[$_key] = $_value;
          }
        }else{
          $field->setColName($value);
        }
        if(isset($value['association'])){
          $searchPattern = isset($value['searchPattern']) ? $value['searchPattern'] : ";%KEY%:%VALUE%";
          $searchType = isset($value['searchType']) ? $value['searchType'] : GridConstants::EDIT_TYPE_SELECT;
          $field->setSearchOptions(array(
            'value' => ':' . ObjectUtil::entityToKeyValue(
              $this->getEntityManager()->getRepository($value['association'])->findAll(), $searchPattern
            )
          ));
          $field->setSType($searchType);

        }
        $this->addGridField($field);
      }
    }
  }

  public function getTranslatorDomain() {
    return $this->translatorDomain;
  }

  public function setTranslatorDomain($translatorDomain) {
    if($translatorDomain !== null){
      $this->translatorDomain = $translatorDomain;
    }
  }

  public function getTranslatorProperties() {
    return $this->translatorProperties;
  }

  public function setTranslatorProperties($translatorProperties) {
    $this->translatorProperties = $translatorProperties;
  }

  public function getTranslatorLocale() {
    return $this->translatorLocale;
  }

  public function setTranslatorLocale($translatorLocale) {
    if($translatorLocale !== null){
      $this->translatorLocale = $translatorLocale;
    }
  }

  public function getEntityManager() {
    return $this->entityManager;
  }

  public function setEntityManager($entityManager) {
    $this->entityManager = $entityManager;
  }

  public function renewNavigator(){
      $this->setNavigator(new \YsGridNavigator());
  }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Structure;

use Pactum\ConfigBuilder;
use Pactum\ConfigBuilderObject;

/**
 * Structure for actions.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class ActionArgumentStructure implements Structure{

    /**
     * {@inheritdoc}
     */
	public function doConfig(ConfigBuilder $configBuilder){
        $configBuilder->getArray('action')->getValue()->addArray('argument',new ConfigBuilderObject())
            ->getValue()->addString('storage')
            ->addString('name')
            ->addString('pattern','')
            ->addString('validator','')
            ->addString('mapper','')
            ->addString('default','');//FIXME change to addMixedZ
	}
}