<?php

/*
 * This file is part of questocat/console-color package.
 *
 * (c) questocat <zhengchaopu@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Questocat\ConsoleColor;

class StdOut implements OutputInterface
{
    /**
     * {@inheritdoc}
     */
    public function write($content, $newline = true)
    {
        if ($newline) {
            $content .= PHP_EOL;
        }

        fwrite(STDOUT, $content);
    }
}


<?php
namespace KayStrobach\Menu\ViewHelpers\Security;

/* *
 * This script belongs to the TYPO3 Flow package "Neos.FluidAdaptor".           *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 * of the License, or (at your option) any later version.                 *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use		Neos\Flow\Annotations as Flow,
	Neos\Flow\Security\Authorization\AccessDecisionManagerInterface,
	Neos\Flow\Security\Exception\AccessDeniedException,
	Neos\FluidAdaptor\Core\ViewHelper\AbstractConditionViewHelper,
	Neos\Flow\Aop\JoinPoint;
use Neos\Flow\Security\Authorization\Privilege\Method\MethodPrivilegeSubject;

/**
 * This view helper implements an IfAccesOnControllersAction / else condition.
 *
 * = Examples =
 *
 *
 * <f:security.ifAccesOnControllersAction>
 *   This is being shown in case you have access to the given action
 * < /f:security.ifAccesOnControllersAction>
 *
 *
 * Everything inside the <f:security.ifAccesOnControllersAction> tag is being displayed if you have access to the given action.
 *
 *
 * <f:security.ifAccesOnControllersAction action="myAction" controller="MyController" subpackage="Some\Subpackage">
 *   <f:then>
 *     This is being shown in case you have access.
 *   < /f:then>
 *   <f:else>
 *     This is being displayed in case you do not have access.
 *   < /f:else>
 * < /f:security.ifAccesOnControllersAction>
 *
 *
 * Everything inside the "then" tag is displayed if you have access.
 * Otherwise, everything inside the "else"-tag is displayed.
 *
 * @api
 */
class IfAccesOnControllersActionViewHelper extends AbstractConditionViewHelper {

	/**
	 * @Flow\Inject
	 * @var \Neos\Flow\Security\Authorization\PrivilegeManagerInterface
	 */
	protected $privilegeManager;

	/**
	 * @Flow\Inject
	 * @var \Neos\Flow\Mvc\Routing\RouterInterface
	 */
	protected $router;

	/**
	 * @var \Neos\Flow\Mvc\ActionRequest
	 */
	protected $request;

	/**
	 * Initializes the view helper before invoking the render method.
	 *
	 * Override this method to solve tasks before the view helper content is rendered.
	 *
	 * @return void
	 */
	public function initialize() {
		parent::initialize();
		$this->request = $this->controllerContext->getRequest();
	}

	/**
	 * renders <f:then> child if access to the given resource is allowed, otherwise renders <f:else> child.
	 *
	 * @param null $package
	 * @param null $subpackage
	 * @param null $controller
	 * @param $action
	 * @internal param string $resource Policy resource
	 * @return string the rendered string
	 * @api
	 */
	public function render($action, $package = NULL, $subpackage = NULL, $controller = NULL) {
		if ($package === NULL) {
			$package = $this->request->getControllerPackageKey();
		}
		if (($package === NULL) && ($subpackage === NULL)) {
			$subpackage = $this->request->getControllerSubpackageKey();
		}
		if ($controller === NULL) {
			$controller = $this->request->getControllerName();
		}

		if ($this->hasAccessToAction($package, $subpackage, $controller, $action)) {
			return $this->renderThenChild();
		}
		return $this->renderElseChild();
	}

	/**
	 * Check if we currently have access to the given resource
	 *
	 * @param $packageKey
	 * @param $subpackageKey
	 * @param $controllerName
	 * @param $actionName
	 * @return boolean TRUE if we currently have access to the given action
	 */
	protected function hasAccessToAction($packageKey, $subpackageKey, $controllerName, $actionName) {
		$actionControllerName = $this->router->getControllerObjectName($packageKey, $subpackageKey, $controllerName);

		try {
			return $this->privilegeManager->isGranted(
					'Neos\Flow\Security\Authorization\Privilege\Method\MethodPrivilege',
					new MethodPrivilegeSubject(
							new JoinPoint(
									NULL,
									$actionControllerName,
									$actionName . 'Action',
									array()
							)
					)
			);
		} catch(AccessDeniedException $e) {
			return FALSE;
		}
	}

}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Controller;

use JMS\SecurityExtraBundle\Annotation\Secure;
use Orkestra\Bundle\ApplicationBundle\Controller\Controller;
use Orkestra\Bundle\ApplicationBundle\Entity\Group;
use Orkestra\Bundle\ApplicationBundle\Form\GroupType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * Group controller.
 *
 * @Route("/group")
 */
class GroupController extends Controller
{
    /**
     * Lists all Group entities.
     *
     * @Route("s/", name="orkestra_groups")
     * @Template()
     * @Secure(roles="ROLE_GROUP_READ")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('OrkestraApplicationBundle:Group')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Finds and displays a Group entity.
     *
     * @Route("/{id}/show", name="orkestra_group_show")
     * @Template()
     * @Secure(roles="ROLE_GROUP_READ")
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $group = $em->getRepository('Orkestra\Bundle\ApplicationBundle\Entity\Group')->find($id);

        if (!$group) {
            throw $this->createNotFoundException('Unable to locate Group');
        }

        return array(
            'group' => $group,
        );
    }

    /**
     * Displays a form to create a new Group entity.
     *
     * @Route("/new", name="orkestra_group_new")
     * @Template()
     * @Secure(roles="ROLE_GROUP_WRITE")
     */
    public function newAction()
    {
        $group = new Group();
        $form = $this->createForm(GroupType::class, $group);

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

    /**
     * Creates a new Group entity.
     *
     * @Route("/create", name="orkestra_group_create")
     * @Method("post")
     * @Template("OrkestraApplicationBundle:Group:new.html.twig")
     * @Secure(roles="ROLE_GROUP_WRITE")
     */
    public function createAction()
    {
        $group = new Group();

        $form = $this->createForm(GroupType::class, $group);
        $form->bindRequest($this->getRequest());

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($group);
            $em->flush();

            $this->get('session')->getFlashBag()->set('success', 'The group has been created.');

            return $this->redirect($this->generateUrl('orkestra_group_show', array('id' => $group->getId())));

        }

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

    /**
     * Displays a form to edit an existing Group entity.
     *
     * @Route("/{id}/edit", name="orkestra_group_edit")
     * @Template()
     * @Secure(roles="ROLE_GROUP_WRITE")
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $group = $em->getRepository('Orkestra\Bundle\ApplicationBundle\Entity\Group')->find($id);

        if (!$group) {
            throw $this->createNotFoundException('Unable to locate Group');
        }

        $form = $this->createForm(GroupType::class, $group);

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

    /**
     * Edits an existing Group entity.
     *
     * @Route("/{id}/update", name="orkestra_group_update")
     * @Method("post")
     * @Template("OrkestraApplicationBundle:Group:edit.html.twig")
     * @Secure(roles="ROLE_GROUP_WRITE")
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $group = $em->getRepository('Orkestra\Bundle\ApplicationBundle\Entity\Group')->find($id);

        if (!$group) {
            throw $this->createNotFoundException('Unable to locate Group');
        }

        $form = $this->createForm(GroupType::class, $group);

        $form->bindRequest($this->getRequest());

        if ($form->isValid()) {
            $em->persist($group);
            $em->flush();

            $this->get('session')->getFlashBag()->set('success', 'Your changes have been saved.');

            return $this->redirect($this->generateUrl('orkestra_group_show', array('id' => $id)));
        }

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


<?php

/**
 * This file is part of Vegas package
 *
 * How to use Atom class:
 *
 *
 * @author Adrian Malik <adrian.malik.89@gmail.com>
 * @copyright Amsterdam Standard Sp. Z o.o.
 * @homepage https://bitbucket.org/amsdard/vegas-phalcon
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vegas\Utils;

use Vegas\Utils\Path\Exception\InvalidPathException;

final class Path
{
    /**
     * Returns root path of the project (/var/www/vegas)
     *
     * @return string
     */
    public static final function getRootPath()
    {
        return APP_ROOT;
    }

    /**
     * Returns path to the public directory (/var/www/vegas/public)
     *
     * @return string
     */
    public static final function getPublicPath()
    {
        return self::getRootPath() . '/public';
    }

    /**
     * Returns path to the library directory (/var/www/vegas/lib)
     *
     * @return string
     */
    public static final function getLibPath()
    {
        return self::getRootPath() . '/lib';
    }

    /**
     * Returns path to the application directory (/var/www/vegas/app)
     *
     * @return string
     */
    public static final function getAppPath()
    {
        return self::getRootPath() . '/app';
    }

    /**
     * Returns path to the config directory (/var/www/vegas/config)
     *
     * @return string
     */
    public static final function getConfigPath()
    {
        return self::getRootPath() . '/config';
    }

    /**
     * Returns path to the temporary directory (/var/www/vegas/temp)
     *
     * @return string
     */
    public static final function getTempPath()
    {
        return self::getRootPath() . '/temp';
    }

    /**
     * Returns path to the tests directory (/var/www/vegas/tests)
     *
     * @return string
     */
    public static final function getTestsPath()
    {
        return self::getRootPath() . '/tests';
    }

    /**
     * Returns relative path of the absolute path. When you pass $absolutePath='/var/www/vegas/config'  then the result
     * should be '/config'
     *
     * @param string $absolutePath
     * @throws InvalidPathException
     * @return mixed|string
     */
    public static final function getRelativePath($absolutePath)
    {
        if (!is_string($absolutePath)) {
            throw new InvalidPathException();
        }

        $pattern = array(self::getRootPath(), DIRECTORY_SEPARATOR, '//');
        $replacement = array('', '/', '/');

        $raltivePath = str_replace($pattern, $replacement, $absolutePath);

        if(substr($raltivePath, 0, 1) != '/') {
            $raltivePath = '/' . $raltivePath;
        }

        return str_replace('/public', '', $raltivePath);
    }

    /**
     * Returns the name of directory where file is located
     *
     * @param string $path
     * @throws InvalidPathException
     * @return string
     */
    public static final function getFileDirectory($path)
    {
        if (!is_string($path)) {
            throw new InvalidPathException();
        }

        $directoryName = dirname($path);

        return $directoryName;
    }
}


<?php

// **************************** \\
// ***** ADMIN CONTROLLER ***** \\
// **************************** \\

namespace App\Controller;

use Pam\Controller\Controller;
use Pam\Model\ModelFactory;
use Pam\Helper\Session;

use App\Helper\User;

/** ***************************************\
* All control actions to the administration
*/
class AdminController extends Controller
{

  /** *********************************************************************\
  * Reads all objects for CRUD actions from the database, then display them
  * @return mixed => the rendering of the view admin
  */
  public function IndexAction()
  {
    // Checks if the user is connected
    if (Session::islogged())
    {
      // Checks if the user is the administrator
      if (Session::userEmail() == User::adminEmail())
      {
        // Reads all articles, users & comments, then stores them
        $allArticles  = ModelFactory::get('Article')->list();
        $allComments  = ModelFactory::get('Comment')->list();
        $allUsers     = ModelFactory::get('User')   ->list();

        // Returns the rendering of the view admin with the user datas
        return $this->render('admin/admin.twig', [
          'allArticles'       => $allArticles,
          'allComments'       => $allComments,
          'allUsers'          => $allUsers
        ]);
      }
      else {
        // Creates a warning message to inform that only the admin can access to this page
        htmlspecialchars(Session::createAlert('Access reserved for the site administrator', 'warning'));

        // Redirects to the view home
        $this->redirect('home');
      }
    }
    else {
      // Creates a cancel message to ask to be connected
      htmlspecialchars(Session::createAlert('You must be logged in to access the administration', 'cancel'));

      // Redirects to the view loginUser
      $this->redirect('user!login');
    }
  }
}


<?php
namespace keenly\component\swoole;

use keenly\base\Singleton;

class table extends \swoole_table{

    use Singleton;

    const INT    = \swoole_table::TYPE_INT;
    const STRING = \swoole_table::TYPE_STRING;
    const FLOAT  = \swoole_table::TYPE_FLOAT;

    public function __construct($size = 1024){
        return parent::__construct($size);
    }

    /**
     * 检查是否存在key
     * @param $key
     * @return bool
     */
    function exist($key)
    {
        return  parent::exist($key);
    }

    /**
     * 获取key
     * @param $key
     * @return array
     */
    function get($key,$field = NULL)
    {
        return parent::get($key,$field);
    }

    /**
     * 设置key
     * @param       $key
     * @param array $array
     * @return bool
     */
    function set($key, array $array)
    {
        return parent::set($key,$array);
    }

    /**
     * 删除key
     * @param $key
     * @return bool
     */
    function del($key)
    {
        return parent::del($key);
    }

    /**
     * 原子自增操作，可用于整形或浮点型列
     * @param $key
     * @param $column
     * @param $incrby
     * @return bool
     */
    function incr($key, $column, $incrby = 1)
    {
       return parent::incr($key, $column, $incrby);
    }

    /**
     * 原子自减操作，可用于整形或浮点型列
     * @param $key
     * @param $column
     * @param $decrby
     */
    function decr($key, $column, $decrby = 1)
    {
        return parent::decr($key, $column, $decrby);
    }

    /**
     * 增加字段定义
     * @param     $name
     * @param     $type
     * @param int $len
     */
    function column($name, $type, $len = 4)
    {
        parent::column($name, $type, $len);
        return $this;
    }

    /**
     * 创建表，这里会申请操作系统内存
     * @return bool
     */
    function create()
    {
        return parent::create();
    }

    /**
     * 返回table中存在的条目数
     */
    function count(){
        return parent::count();
    }

}


<?php

namespace Slion;

/**
 * Description of Run
 *
 * @author andares
 */
class Run {
    /**
     *
     * @var string
     */
    private $_id;

    /**
     *
     * @var \Slim\App
     */
    private $_app = null;

    /**
     *
     * @var \Slim\Container
     */
    private $_container = null;

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

    /**
     *
     * @var Init[]
     */
    private $_extensions;

    /**
     *
     * @var string
     */
    private $_current_extension;

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

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

    /**
     *
     * @var []
     */
    private static $_imported = [];

    public function __construct() {
        $GLOBALS['run'] = $this;

        $this->_id = $this->genId();

        // 初始化imported
        foreach (explode(PATH_SEPARATOR, ini_get('include_path')) as $dir) {
            self::$_imported[$dir] = 1;
        }
    }

    /**
     *
     * @return string
     */
    private function genId(): string {
        $generator = new Utils\IdGenerator;
        $generator->algo = 'fnv1a32';
        return $generator->prepare(microtime())->hash_hmac('triss')
            ->gmp_strval()->get();
    }

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

    /**
     *
     * @param string $name
     * @return type
     */
    public function __get(string $name) {
        return $this->_container->has($name) ?
            $this->_container->get($name) : null;
    }

    /**
     *
     * @param string $name
     * @param mixed $value
     */
    public function __set(string $name, $value) {
        $this->_container[$name] = $value;
    }

    /**
     *
     * @return \Slim\App
     */
    public function app(): \Slim\App {
        return $this->_app;
    }

    /**
     *
     * @return \Slim\Container
     */
    public function container(): \Slim\Container {
        return $this->_container;
    }

    /**
     *
     * @return mixed
     */
    public function settings(string $key = null) {
        return $key ? ($this->_settings[$key] ?? null) : $this->_settings;
    }

    /**
     *
     * @param string $extension_name
     * @return string
     */
    public function root(string $extension_name): string {
        return $this->_extensions[$extension_name]['root'];
    }

    /**
     * 框架准备
     */
    public function ready(array $container) {
        // 构建自身
        $this->_app          = new \Slim\App($container);
        $this->_container    = $this->_app->getContainer();
        $this->_settings     = $this->_container->get('slion_settings');

        // 注册自动载入
        $this->registerAutoload();
    }

    /**
     * 添加一个扩展
     * @param string $name
     * @param string $root
     * @return self
     */
    public function add(string $name, string $root): self {
        $this->_current_extension            = $name;
        $this->_extensions[$name]['root']    = $root;
        return $this;
    }

    /**
     *
     * @param string $name
     * @return self
     */
    public function select(string $name): self {
        $this->_current_extension    = $name;
        return $this;
    }

    /**
     *
     * 设置引导
     *
     * @param int $seq
     * @param \Slion\callable $boot
     * @param string $info
     * @return \self
     */
    public function setup(int $seq, callable $boot, string $info = ''): self {
        $this->_extensions[$this->_current_extension]['boots'][$seq][] = $boot;
        $this->_bootstrappers[$seq][$this->_current_extension][]       = $info;
        return $this;
    }

    /**
     *
     * @return array
     */
    public function getBootstrappers() {
        return $this->_bootstrappers;
    }

    /**
     * 初始化环境并返回app
     * @return \Slim\App
     */
    public function __invoke() {
        ksort($this->_bootstrappers);
        foreach ($this->_bootstrappers as $seq => $list) {
            if (isset($this->_skips[$seq])) {
                continue;
            }
            foreach ($list as $extension_name => $info) {
                $extension = $this->_extensions[$extension_name];
                foreach ($extension['boots'][$seq] as $boot) {
                    $boot->call($this, $extension['root']);
                }
            }
        }

        return $this->_app;
    }

    /**
     * 跳过某些引导序列
     * @param int $seq
     */
    public function skip(int $seq) {
        $this->_skips[$seq] = 1;
    }

    /**
     * 注册自动载入
     */
    private function registerAutoload() {
        spl_autoload_register(function ($classname) {
            try {
                foreach (self::$_imported as $dir => $flag) {
                    $file = $dir . DIRECTORY_SEPARATOR .
                        \str_replace("\\", DIRECTORY_SEPARATOR, $classname) . ".php";
                    if (file_exists($file)) {
                        include $file;
                    }
                }
            } catch (\Throwable $exc) {
                error_log($exc->getMessage());
                error_log($exc->getCode());
                error_log($exc->getTraceAsString());
                return false;
            }
            if (class_exists($classname) || interface_exists($classname) ||
                trait_exists($classname)) {
                return true;
            }
            return false;
        });
    }

    /**
     * 导入库
     * @param string $dir
     * @return array
     */
    private function importLibrary(string $dir): array {
        if (!isset(self::$_imported[$dir])) {
            ini_set('include_path', $dir . PATH_SEPARATOR . ini_get('include_path'));
            self::$_imported[$dir] = 1;
        }
        return self::$_imported;
    }

    /**
     * php ini检测
     * @param array $setup_list
     * @param array $check_list
     * @throws \RuntimeException
     */
    private function phpIniReady(array $setup_list = [], array $check_list = []) {
        foreach ($setup_list as $name => $value) {
            ini_set($name, $value);
        }
        foreach ($check_list as $name => $value) {
            if (ini_get($name) != $value) {
                throw new \RuntimeException("PHP ini [$name] should be $value");
            }
        }
    }
}


<?php
namespace keenly;

trait common
{

    public static  $funMet = [
        'logs' =>'debuglogs'
    ];

    public static  function __callstatic($obj,$fun){
        $isObj = self::$funMet[$obj];
        self::$isObj($fun);
    }

    static function logs($arg, $logName = 'debug')
    {
        $url  ='../logs/' . $logName . '.log.' . date('Ymd');
        $fp = fopen($url, 'a');
        $traces = debug_backtrace();
        $logMsg = 'FILE:' . basename($traces[0]['file']) . PHP_EOL;
        $logMsg .= 'FUNC:' . $traces[1]['function'] . PHP_EOL;
        $logMsg .= 'LINE:' . $traces[0]['line'] . PHP_EOL;
        if (is_string($arg)) {
            $logMsg .= 'ARGS:' . $arg . PHP_EOL;
        } else {
            $logMsg .= 'ARGS:' . var_export($arg, true) . PHP_EOL;
        }
        $logMsg .= 'DATETIME:' . date('Y-m-d H:i:s') . PHP_EOL . PHP_EOL;
        fwrite($fp, $logMsg);
        fclose($fp);
    }

    public static function lectionClass($class,$classargs = null){
        $class = new \ReflectionClass($class);
        $args = empty($classargs)?$class->newInstanceArgs():$class->newInstanceArgs([$classargs]);
        return $args;
    }

    //Openssl Encryption
    public static function OpensslEncryption($plaintext,$key){
        $ivlen = openssl_cipher_iv_length($cipher="BF-CBC");//openssl_get_cipher_methods ()
        $iv = openssl_random_pseudo_bytes($ivlen);
        $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
        $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
        return  base64_encode($iv.$hmac.$ciphertext_raw);
    }

    //openssl decrypt
    public static function OpensslDecrypt($ciphertext,$key){
        $c = base64_decode($ciphertext);
        $ivlen = openssl_cipher_iv_length($cipher="BF-CBC");
        $iv = substr($c, 0, $ivlen);
        $hmac = substr($c, $ivlen, $sha2len=32);
        $ciphertext_raw = substr($c, $ivlen+$sha2len);
        $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
        $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
        if (hash_equals($hmac, $calcmac))//PHP 5.6+
        {
            return $original_plaintext;
        }
    }

    /**
     * session decrypt AES 256
     *
     * @param data $edata
     * @param string $password
     * @return decrypted data
     */
    function decrypt($data, $password) {
        $data = base64_decode($data);
        $salt = substr($data, 0, 16);
        $ct = substr($data, 16);
        $rounds = 3; // depends on key length
        $data00 = $password.$salt;
        $hash = array();
        $hash[0] = hash('sha256', $data00, true);
        $result = $hash[0];
        for ($i = 1; $i < $rounds; $i++) {
            $hash[$i] = hash('sha256', $hash[$i - 1].$data00, true);
            $result .= $hash[$i];
        }
        $key = substr($result, 0, 32);
        $iv  = substr($result, 32,16);

        return openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv);
    }

    /**
     * session crypt AES 256
     *
     * @param data $data
     * @param string $password
     * @return base64 encrypted data
     */
    function encrypt($data, $password) {
        // Set a random salt
        $salt = openssl_random_pseudo_bytes(16);
        $salted = '';
        $dx = '';
        while (strlen($salted) < 48) {
            $dx = hash('sha256', $dx.$password.$salt, true);
            $salted .= $dx;
        }

        $key = substr($salted, 0, 32);
        $iv  = substr($salted, 32,16);

        $encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv);
        return base64_encode($salt . $encrypted_data);
    }

}

?>


<?php

namespace keenly\component\swoole\Process;

use swoole_process as SwooleProcess;

/**
 * The process
 */
class Processpool
{
    /**
     * @var SwooleProcess
     */
    private $process;

    /**
     * Process constructor.
     *
     * @param SwooleProcess  $process
     */
    public function __construct(SwooleProcess $process)
    {
        $this->process = $process;
    }

    /**
     * Start process
     *
     * @return mixed Create a successful PID to return to the child process, create a failure to return to false
     */
    public function start()
    {
        return $this->process->start();
    }

    /**
     * Set the name of process
     *
     * @param string $name
     */
    public function name(string $name)
    {

            $this->process->name($name);

    }

    /**
     * Execute an external program
     *
     * @param string $execfile
     * @param array  $args
     *
     * @return bool
     */
    public function exec(string $execfile, array $args): bool
    {
        return $this->process->exec($execfile, $args);
    }

    /**
     * Write data into pipe
     *
     * @param string $data
     *
     * @return int
     */
    public function write(string $data): int
    {
        return $this->process->write($data);
    }

    /**
     * Read data from pipe
     *
     * @param int $bufferSize
     *
     * @return bool|string
     */
    public function read(int $bufferSize = 8192)
    {
        return $this->process->read($bufferSize);
    }

    /**
     * Sett the timeout of the pipe read or write
     *
     * @param float $timeout
     */
    public function setTimeout(double $timeout)
    {
        $this->process->setTimeout($timeout);
    }

    /**
     * Enable message queuing as interprocess communication
     *
     * @param int $msgkey
     * @param int $mode
     */
    public function useQueue(int $msgkey = 0, int $mode = 2)
    {
        $this->process->useQueue($msgkey, $mode);
    }

    /**
     * Show the message queue status
     *
     * @return array
     */
    public function statQueue(): array
    {
        return $this->process->statQueue();
    }

    /**
     * Remove message queue
     */
    public function freeQueue()
    {
        $this->process->freeQueue();
    }

    /**
     * Send data to the message queue
     *
     * @param string $data
     *
     * @return bool
     */
    public function push(string $data): bool
    {
        return $this->process->push($data);
    }

    /**
     * Get data from message queue
     *
     * @param int $maxSize
     *
     * @return string
     */
    public function pop(int $maxSize = 8192): string
    {
        return $this->process->pop($maxSize);
    }

    /**
     * Close the pipe
     *
     * @param int $which
     *
     * @return bool
     */
    public function close(int $which = 0): bool
    {
        return $this->process->close($which);
    }

    /**
     * Exit child process
     *
     * @param int $status
     *
     * @return int
     */
    public function exit(int $status = 0): int
    {
        return $this->process->exit($status);
    }

    /**
     * @param int $pid
     * @param int $signo
     *
     * @return bool
     */
    public static function kill(int $pid, int $signo = SIGTERM): bool
    {
        return SwooleProcess::kill($pid, $signo);
    }

    /**
     * @param bool $blocking
     *
     * @return array|bool
     */
    public static function wait(bool $blocking = true)
    {
        return SwooleProcess::wait($blocking);
    }

    /**
     * @param bool $nochdir
     * @param bool $noclose
     *
     */
    public static function daemon(bool $nochdir = false, bool $noclose = false)
    {
        SwooleProcess::daemon($nochdir, $noclose);
    }

    /**
     * @param int      $signo
     * @param callable $callback
     */
    public static function signal(int $signo, callable $callback)
    {
        SwooleProcess::signal($signo, $callback);
    }

    /**
     * @param int $intervalUsec
     * @param int $type
     *
     * @return bool
     */
    public static function alarm(int $intervalUsec, int $type = 0): bool
    {
        return SwooleProcess::alarm($intervalUsec, $type);
    }

    /**
     * @param array $cpuSet
     *
     * @return bool
     */
    public static function setaffinity(array $cpuSet): bool
    {
        return SwooleProcess::setaffinity($cpuSet);
    }

    /**
     * @return \Swoole\Process
     */
    public function getProcess(): SwooleProcess
    {
        return $this->process;
    }
}


<?php

namespace Slion;
use Slim\Container;

/**
 * Description of Console
 *
 * 提供几种注册指令的方案：
 * 1、map()，给目录和命名空间，搜索该目录以及其下Commands目录中的所有继承Commands的类
 * 2、add()，直接注册一个对象
 *
 * @author andares
 */
class Console {
    /**
     *
     * @var Container
     */
    protected $container;

    protected $name = '';

    protected $default_domain = '';

    protected $style = null;

    /**
     *
     * @var Console\Command[]
     */
    protected $commands = [];

    protected $base;

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

    public function __construct(Container $container, string $name = '') {
        $this->container = $container;
        $name && $this->name = $name;
    }

    public function __invoke(array $argv): string {
        $this->base = array_shift($argv);
        if (!$argv) {
            $this->makeHelp();
            return '';
        }

        $domain = array_shift($argv);
        $action = $argv ? array_shift($argv) : '';
        if (!$action) {
            // 处理帮助
            $this->makeHelp($domain);
            return '';
        }

        // 执行
        return $this->callCommand($domain, $argv);
    }

    protected function makeHelp(string $domain = '') {
        // 域指令的帮助功能
        if ($domain) {
            $command = $this->commands[$domain] ??
                ($this->commands["$this->default_domain.$domain"] ?? null);
            /* @var $command Console\Command */
            if ($command) {
                $help_text = $command->getHelp();
                if ($help_text) {
                    $this->ec($help_text);
                    $this->ec();
                }
            }
        } else {
            $this->ec(">>> Welcome to use Chord <<<", 'clear');
            $this->ec();
        }

        // 固定内容
        $this->ec("- example: $this->base <domain> <action> [<arguments>..]");
        $this->ec();
        $this->ec('- commands list:');

        // 输出指令列表
        $prefix = str_repeat(' ', 3) . $this->base;
        if ($domain) {
            $list = $this->getActionHelpList($domain);
            $this->printActionHelpList($prefix, $list);

            if (!$list) {
                throw new \DomainException(
                    tr('console/errors', 'domain_not_found', $domain));
            }
        } else {
            $this->printActionHelpList($prefix, $this->getActionHelpList());
        }
    }

    public function __get($name) {
        return $this->container->get($name);
    }

    protected function callCommand(string $domain, string $action, array $argv): string {
        // 域指令
        $cmd    = $this->commands[$domain] ?? null;
        if (!$cmd) {
            // 检查默认
            $domain = "$this->default_domain.$domain";
            $cmd    = $this->commands[$domain] ?? null;
            if (!$cmd) {
                throw new \BadFunctionCallException(
                    tr('console/errors', 'cmd_not_found', $domain));
            }
        }
        return $cmd($action, $argv);
    }

    public function getActionHelpList(...$white_list): array {
        $result = [];
        if ($white_list) {
            foreach ($white_list as $domain) {
                if (isset($this->commands[$domain])) {
                    foreach ($this->commands[$domain]->getActions() as $action => $arguments) {
                        $result[$domain] = "$action $arguments";
                    }
                }
                if (isset($this->commands["$this->default_domain.$domain"])) {
                    $default_domain = "$this->default_domain.$domain";
                    foreach ($this->commands[$default_domain]
                        ->getActions() as $action => $arguments) {
                        $result[$default_domain] = "$action $arguments";
                    }
                }

                $node = $domain;
                foreach ($this->getActionHelpListByNode($node) as $domain => $help) {
                    $result[$domain] = $help;
                }
            }
        } else {
            foreach ($this->commands as $domain => $command) {
                foreach ($command->getActions() as $action => $arguments) {
                    $result[$domain] = "$action $arguments";
                }
            }
        }
        return $result;
    }

    private function getActionHelpListByNode(string $node): \Generator {
        if (isset($this->index[$node])) {
            foreach ($this->index[$node] as $domain) {
                foreach ($this->commands[$domain]->getActions() as $action => $arguments) {
                    yield $domain => "$action $arguments";
                }
            }
        }
        if (isset($this->index["$this->default_domain.$node"])) {
            $default_node = "$this->default_domain.$node";
            foreach ($this->index[$default_node] as $domain) {
                foreach ($this->commands[$domain]->getActions() as $action => $arguments) {
                    yield $domain => "$action $arguments";
                }
            }
        }
    }

    public function printActionHelpList(string $prefix, array $list) {
        $current = '';
        foreach ($list as $domain => $line) {
            // 给默认域加可选
            $domain = $this->wrapDefaultDomain($domain);
            if ($current != $domain) {
                $this->ec();
                $current = $domain;
            }

            $this->ec("$prefix $domain $line");
        }
        $this->ec();
    }

    protected function wrapDefaultDomain($domain) {
        return preg_replace("/^($this->default_domain\.)(.*)$/", '[$1]$2', $domain);
    }

    public function setDefaultDomain(string $domain) {
        $this->default_domain = $domain;
    }

    public function getStyle() {
        if (!$this->style) {
            $this->style = new Console\Style;
        }
        return $this->style;
    }

    public function map(string $dir, string $space) {
        $search = [
            $space              => $dir,
            "$space\\Commands"  => $dir . DIRECTORY_SEPARATOR . 'Commands',
        ];

        foreach ($search as $space => $dir) {
            if (!file_exists($dir)) {
                continue;
            }

            $it = new \RecursiveDirectoryIterator($dir);
            foreach ($it as $file) {
                /* @var $file \SplFileInfo */
                if ($file->isDir()) {
                    continue;
                }
                if ($file->getExtension() != 'php') {
                    continue;
                }

                $class  = $space . '\\' . $file->getBasename('.php');
                if (!class_exists($class)) {
                    continue;
                }

                $refl   = new \ReflectionClass($class);
                if ($refl->isAbstract()) {
                    continue;
                }
                if ($this->isCommand($refl)) {
                    $this->add(new $class($this));
                }
            }
        }
    }

    private function isCommand(\ReflectionClass $refl) {
        $parent = $refl->getParentClass();
        if (!$parent) {
            return false;
        }
        if ($parent->getName() == (__NAMESPACE__ . '\\Console\\Command')) {
            return true;
        }
        return $this->isCommand($parent);
    }

    /**
     * 添加一个命令。
     *
     * 如果在同一域下重复添加，后者不会生效。
     *
     * @param \Slion\Console\Command $command
     */
    public function add(Console\Command $command) {
        $domain = $command->getDomain();
        if (!$domain || isset($this->commands[$domain])) {
            return;
        }
        $this->commands[$domain] = $command;

        $this->buildCommandsIndex($command);
    }

    private function buildCommandsIndex(Console\Command $command) {
        $domain = $command->getDomain();
        $path   = [];
        foreach (explode('.', $domain) as $node) {
            $path[]  = $node;
            $key     = implode('.', $path);
            $domain != $key && $this->index[$key][] = $domain;
        }
    }

    public function ec(string $words = '', $level = 'info', Console\Style $style = null) {
        !$style && $style = $this->getStyle();
        echo $style->$level($words), PHP_EOL;
    }
}


<?php

// ****************************** \\
// ***** COMMENT CONTROLLER ***** \\
// ****************************** \\

namespace App\Controller;

use Pam\Controller\Controller;
use Pam\Model\ModelFactory;
use Pam\Helper\Session;

/** *********************************\
* All control actions to the comments
*/
class CommentController extends Controller
{

  /** ********************\
   * Creates a new comment
   */
  public function CreateAction()
  {
    // Checks if the user is connected
    if (Session::islogged())
    {
      // Creates the $data array to store the new comment
      $data['article_id']   = $_GET['id'];
      $data['content']      = $_POST['content'];
      $data['created_date'] = $_POST['date'];
      $data['user_id']      = $_SESSION['user']['id'];

      // Creates the comment
      ModelFactory::get('Comment')->create($data);

      // Creates a valid message to confirm the creation of a new comment
      htmlspecialchars(Session::createAlert('New comment created successfully !', 'valid'));

      // Redirects to the view readArticle
      $this->redirect('article!read', ['id' => $_GET['id']]);
    }
    else {
      // Creates a fail message to ask to be connected
      htmlspecialchars(Session::createAlert('You must be logged in to add a comment...', 'cancel'));
    }
    // Redirects to the view loginUser
    $this->redirect('user!login');
  }

  /** ****************\
   * Deletes a comment
   */
  public function DeleteAction()
  {
    // Gets the comment id, then stores it
    $id = $_GET['id'];

    // Deletes the selected comment
    ModelFactory::get('Comment')->delete($id);

    // Creates a delete message to confirm the removal of the selected comment
    htmlspecialchars(Session::createAlert('Comment permanently deleted !', 'delete'));

    // Redirects to the view admin
    $this->redirect('admin');
  }
}


<?php
namespace KayStrobach\Menu;

/*                                                                        *
 * This script belongs to the TYPO3 Flow package "Fluid".                 *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 * of the License, or (at your option) any later version.                 *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use Neos\Flow\Package\Package as BasePackage;

/**
 * The Fluid Package
 *
 */
class Package extends BasePackage {

	/**
	 * @var boolean
	 */
	protected $protected = TRUE;

	/**
	 * Invokes custom PHP code directly after the package manager has been initialized.
	 *
	 * @param \Neos\Flow\Core\Bootstrap $bootstrap The current bootstrap
	 * @return void
	 */
	public function boot(\Neos\Flow\Core\Bootstrap $bootstrap) {
		//register Configuration Type Menu
		$dispatcher = $bootstrap->getSignalSlotDispatcher();
		$dispatcher->connect('Neos\Flow\Configuration\ConfigurationManager', 'configurationManagerReady',
			function ($configurationManager) {
				$configurationManager->registerConfigurationType('Menus');
			}
		);
	}
}

?>


<?php
/**
 * Created by PhpStorm.
 * User: inhere
 * Date: 2017/7/2
 * Time: 下午1:50
 */

namespace Toolkit\Pool\Raw;

use Toolkit\Pool\FactoryInterface;
use Toolkit\Pool\SPLQueuePool;

/**
 * Class ResourcePool2
 * - 通过设置的资源工厂类实现资源的创建和销毁
 *
 * $pool = new ResourcePool([
 *  'maxSize' => 50,
 * ]);
 *
 * $pool->initPool();
 *
 * @package Toolkit\Pool\Raw
 */
class Resource2Pool extends SPLQueuePool
{
    /**
     * @var FactoryInterface
     */
    private $factory;

    /**
     * 等待并返回可用资源
     * @return bool|mixed
     */
    protected function wait()
    {
        $timer = 0;
        $timeout = $this->getMaxWait();
        $interval = 50;
        $uSleep = $interval * 1000;

        while ($timer <= $timeout) {
            // 等到了可用的空闲资源
            if ($res = $this->getFreeQueue()->pop()) {
                return $res;
            }

            $timer += $interval;
            usleep($uSleep);
        }

        return false;
    }

    /**
     * release pool
     */
    public function clear()
    {
        $this->factory = null;

        parent::clear();
    }

    /**
     * @return FactoryInterface
     */
    public function getFactory()
    {
        return $this->factory;
    }

    /**
     * @param FactoryInterface $factory
     * @return $this
     */
    public function setFactory(FactoryInterface $factory)
    {
        $this->factory = $factory;

        // 预准备资源
        $this->prepare($this->getInitSize());

        return $this;
    }

    /**
     * 创建新的资源实例
     * @return mixed
     */
    public function create()
    {
        return $this->factory->create();
    }

    /**
     * 销毁资源实例
     * @param $resource
     * @return void
     */
    public function destroy($resource)
    {
        $this->factory->destroy($resource);
    }

    /**
     * 验证资源(eg. db connection)有效性
     * @param mixed $obj
     * @return bool
     */
    protected function validate($obj): bool
    {
        // TODO: Implement validate() method.
    }
}


<?php

// *************************** \\
// ***** USER CONTROLLER ***** \\
// *************************** \\

namespace App\Controller;

use Pam\Controller\Controller;
use Pam\Model\ModelFactory;
use Pam\Helper\Session;

/** ********************************
* All control actions to the gallery
*/
class UserController extends Controller
{

  /** *******************************************************\
  * Checks if the user is registred & if his password matches
  * Then connects him if it's alright
  * Otherwise, display the login form
  * @return mixed => the rendering of the login form page
  */
  public function LoginAction()
  {
    // Checks if the form has been completed
    if (!empty($_POST))
    {
      // Search the user in the DB
      $user = ModelFactory::get('User')->read($_POST['email'], 'email');

      // Checks if the password is correct
      if (password_verify($_POST['pass'], $user['pass']))
      {
        // Creates the user session
        Session::createSession(
          $user['id'],
          $user['first_name'],
          $user['image'],
          $user['email']
        );
        // Creates a custom message to welcome the user
        htmlspecialchars(Session::createAlert('Successful authentication, welcome ' . $user['first_name'] .' !', 'special'));

        // Redirects to the view home
        $this->redirect('home');
      }
      else {
        // Creates an authentification fail message
        htmlspecialchars(Session::createAlert('Failed authentication !', 'cancel'));
      }
    }
    // Returns the rendering of the view loginUser
    return $this->render('user/loginUser.twig');
  }

  /** ****************************\
  * Destroys the session to logout
  */
  public function LogoutAction()
  {
    // Destroys the user session
    Session::destroySession();

    // Redirects to the view home
    $this->redirect('home');
  }

  /** ****************\
  * Creates a new user
  * @return mixed => the rendering of the view createUser
  */
  public function CreateAction()
  {
    // Checks if the form has been completed
    if (!empty($_POST))
    {
      // Search the user in the DB
      $user = ModelFactory::get('User')->read($_POST['email'], 'email');

      // Checks if the user exists already
      if (empty($user) == false)
      {
        // Creates a fail message to inform that an existing account uses this email address
        htmlspecialchars(Session::createAlert('There is already a user account with this email address'));
      }
      // Uploads the image & gets back the file name
      $data['image'] = $this->upload('img/user');

      // Hashes the user password
      $data['pass'] = password_hash($_POST['pass'], PASSWORD_DEFAULT);

      // Creates the $data array to store the new user
      $data['first_name']   = $_POST['first_name'];
      $data['last_name']    = $_POST['last_name'];
      $data['zipcode']      = $_POST['zipcode'];
      $data['country']      = $_POST['country'];
      $data['email']        = $_POST['email'];
      $data['created_date'] = $_POST['date'];
      $data['updated_date'] = $_POST['date'];

      // Creates a new user
      ModelFactory::get('User')->create($data);

      // Creates a valid message to confirm the creation of a new user
      htmlspecialchars(Session::createAlert('New user created successfully !', 'valid'));

      // Redirects to the view home
      $this->redirect('home');
    }
    else {
      // Returns the rendering of the view createUser with the empty fields
      return $this->render('user/createUser.twig');
    }
  }

  /** ************\
  * Updates a user
  * @return mixed => the rendering of the view updateUser
  */
  public function UpdateAction()
  {
    // Gets the article id, then stores it
    $id = $_GET['id'];

    // Checks if the form has been completed
    if (!empty($_POST))
    {
      // Checks if a new file has been uploaded
      if (!empty($_FILES['file']['name']))
      {
        // Uploads the user image, then stores it
        $data['image'] = $this->upload('img/user');
      }
      // Hashes the user password
      $data['pass'] = password_hash($_POST['pass'], PASSWORD_DEFAULT);

      // Retrieves form data, then stores the user
      $data['first_name']   = $_POST['first_name'];
      $data['last_name']    = $_POST['last_name'];
      $data['zipcode']      = $_POST['zipcode'];
      $data['country']      = $_POST['country'];
      $data['email']        = $_POST['email'];
      $data['updated_date'] = $_POST['date'];

      // Updates the selected user
      ModelFactory::get('User')->update($id, $data);

      // Creates an info message to confirm the update of the selected user
      htmlspecialchars(Session::createAlert('Successful modification of the selected user !', 'info'));

      // Redirects to the view home
      $this->redirect('home');
    }
    // Reads the selected user, then stores it
    $user = ModelFactory::get('User')->read($id);

    // Returns the rendering of the view updateUser with the current user
    return $this->render('user/updateUser.twig', ['user' => $user]);
  }

  /** ************\
  * Deletes a user
  */
  public function DeleteAction()
  {
    // Gets the user id, then stores it
    $id = $_GET['id'];

    // Deletes the selected user
    ModelFactory::get('User')->delete($id);

    // Creates a delete message to confirm the removal of the selected user
    htmlspecialchars(Session::createAlert('User permanently deleted !'));

    // Redirects to the view home
    $this->redirect('home');
  }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle;

use Doctrine\DBAL\Types\Type;
use Orkestra\Bundle\ApplicationBundle\DependencyInjection\Compiler\ModifyServiceDefinitionsPass;
use Orkestra\Bundle\ApplicationBundle\DependencyInjection\Compiler\RegisterFormTypesPass;
use Orkestra\Bundle\ApplicationBundle\DependencyInjection\Compiler\RegisterWorkersPass;
use Orkestra\Common\DbalType\EncryptedStringType;
use Orkestra\Common\Type\Date;
use Orkestra\Common\Type\DateTime;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class OrkestraApplicationBundle extends Bundle
{
    const VERSION = '1.0.0-DEV';

    /**
     * {@inheritDoc}
     */
    public function boot()
    {
        Type::overrideType('datetime', 'Orkestra\Common\DbalType\DateTimeType');
        Type::overrideType('date',     'Orkestra\Common\DbalType\DateType');
        Type::overrideType('time',     'Orkestra\Common\DbalType\TimeType');

        if (!Type::hasType('encrypted_string')) {
            Type::addType('encrypted_string', 'Orkestra\Common\DbalType\EncryptedStringType');
        } elseif (!(Type::getType('encrypted_string') instanceof EncryptedStringType)) {
            throw new \UnexpectedValueException('Type encrypted_string must be instance of Orkestra\Common\DbalType\EncryptedStringType');
        }

        $encryptedStringType = Type::getType('encrypted_string');
        $encryptedStringType->setKey($this->container->getParameter('secret'));

        // Set up date related settings
        $defaultTimezone = new \DateTimeZone(date_default_timezone_get());
        DateTime::setServerTimezone($defaultTimezone);
        DateTime::setUserTimezone($defaultTimezone);
        DateTime::setDefaultFormat('Y-m-d H:i:s');
        Date::setDefaultFormat('Y-m-d');
    }

    /**
     * {@inheritDoc}
     */
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new ModifyServiceDefinitionsPass());
        $container->addCompilerPass(new RegisterFormTypesPass());
        $container->addCompilerPass(new RegisterWorkersPass());
    }
}


<?php
declare (strict_types = 1);

namespace GrottoPress\WordPress;

use GrottoPress\Getter\GetterTrait;
use WP_Post;

class Breadcrumbs
{
    use GetterTrait;

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

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

    /**
     * @var string $before Text to prepend to breadcrumbs.
     */
    protected $before;

    /**
     * @var string $after Text to append to breadcrumbs.
     */
    protected $after;

    /**
     * @var array
     */
    protected $links;

    /**
     * @var Page
     */
    private $page;

    public function __construct(Page $page, array $args = [])
    {
        $this->page = $page;

        $this->setAttributes($args);
        $this->sanitizeAttributes();

        $this->collectLinks();
    }

    protected function getLinks()
    {
        return $this->links;
    }

    public function render(): string
    {
        $trail = '';

        if (\is_rtl()) {
            $trail .= $this->renderRTL();
        } else {
            $trail .= $this->renderLTR();
        }

        $trail .= '';

        return $trail;
    }

    /**
     * The breadcrumbs trail for right-to-left languages.
     */
    protected function renderRTL(): string
    {
        $trail = '';

        if ($this->after) {
            $trail .= ''.$this->after.' ';
        }

        $trail .= \join(
            ' '.$this->delimiter.' ',
            \array_reverse($this->links)
        );

        if ($this->before) {
            $trail .= ' '.$this->before.'';
        }

        return $trail;
    }

    /**
     * The breadcrumbs trail for left-to-right languages.
     */
    protected function renderLTR(): string
    {
        $trail = '';

        if ($this->before) {
            $trail .= ''.$this->before.' ';
        }

        $trail .= \join(
            ' '.$this->delimiter.' ',
            $this->links
        );

        if ($this->after) {
            $trail .= ' '.$this->after.'';
        }

        return $trail;
    }

    protected function collectLinks()
    {
        if (!$this->page->is('front_page')) {
            $this->addHomeLink();
        }

        $this_page = $this->page->type();

        foreach ($this_page as $page) {
            $add_links = 'add_'.$page.'_links';

            if (\is_callable([$this, $add_links])) {
                $this->$add_links();
                break;
            }
        }

        if ($this->page->is('paged') && !$this->page->is('404')) {
            $this->addPageNumberLink();
        }

        /**
         * @filter grotto_wp_breadcrumbs_links
         *
         * @var array $this->links Breadcrub links for current page.
         */
        $this->links = (array)\apply_filters(
            'grotto_wp_breadcrumbs_links',
            $this->links,
            $this_page
        );
    }

    /**
     * Called if $page === 'front_page'
     */
    protected function add_front_page_links()
    {
        $this->links[] = $this->currentLink($this->homeLabel, \home_url('/'));
    }

    /**
     * Called if $page === 'home'
     */
    protected function add_home_links()
    {
        if ($this->page->is('front_page')) {
            $this->add_front_page_links();
        } else {
            $home = \get_option('page_for_posts');
            $title = \get_the_title($home);
            $url = (\get_permalink($home) ?: '');

            $this->links[] = $this->currentLink($title, $url);
        }
    }

    /**
     * Called if $page === 'category'
     */
    protected function add_category_links()
    {
        $cat_id = \absint(\get_query_var('cat'));
        $cat = \get_category($cat_id);
        $cat_parent_id = \absint($cat->parent);

        $cat_links = [];

        if ($cat_parent_id) {
            while ($cat_parent_id) {
                $cat_parent = \get_category($cat_parent_id);
                $cat_links[] = $this->makeLink(
                    $cat_parent->name,
                    \get_category_link(\absint($cat_parent->term_id))
                );
                $cat_parent_id = \absint($cat_parent->parent);
            }

            $this->links = \array_merge(
                $this->links,
                \array_reverse($cat_links)
            );
        }

        $this->links[] = $this->currentLink(
            $cat->name,
            \get_category_link($cat_id)
        );
    }

    /**
     * Called if $page === 'date'
     */
    protected function add_date_links()
    {
        $year = \get_query_var('year', (int)\date('Y'));
        $month = \get_query_var('monthnum', 1);
        $day = \get_query_var('day', 1);

        $timestamp = \strtotime("{$year}-{$month}-{$day}");

        $year_args = ["{$year}", \get_year_link($year)];
        $month_args = [
            \date('M Y', $timestamp),
            \get_month_link($year, $month)
        ];
        $day_args = [
            \date('d M Y', $timestamp),
            \get_day_link($year, $month, $day)
        ];

        if ($this->page->is('year')) {
            $this->links[] = $this->currentLink(...$year_args);
        } else {
            $this->links[] = $this->makeLink(...$year_args);
        }

        if ($this->page->is('month')) {
            $this->links[] = $this->currentLink(...$month_args);
        }

        if ($this->page->is('day')) {
            $this->links[] = $this->makeLink(...$month_args);
            $this->links[] = $this->currentLink(...$day_args);
        }
    }

    /**
     * Called if $page === 'search'
     */
    protected function add_search_links()
    {
        $this->links[] = $this->currentLink(
            '“'.\get_search_query().'”',
            \get_search_link(\get_search_query())
        );
    }

    /**
     * Called if $page === 'tag'
     */
    protected function add_tag_links()
    {
        $tag_id = \get_query_var('tag_id');
        $tag_label = (\single_tag_title('', false) ?: '');

        $this->links[] = $this->currentLink($tag_label, \get_tag_link($tag_id));
    }

    /**
     * Called if $page === 'author'
     */
    protected function add_author_links()
    {
        $author_id = \get_query_var('author');
        $author_name = \get_the_author_meta('display_name', $author_id);

        $this->links[] = $this->currentLink(
            $author_name,
            \get_author_posts_url($author_id)
        );
    }

    /**
     * Called if $page === '404'
     */
    protected function add_404_links()
    {
        $this->links[] = $this->currentLink(
            \esc_html__('Error 404', 'grotto-wp-breadcrumbs')
        );
    }

    /**
     * Called if $page === 'post_type_archive'
     */
    protected function add_post_type_archive_links()
    {
        $post_type = \get_query_var('post_type');
        $post_type_link = (\get_post_type_archive_link($post_type) ?: '');
        $post_type_label = \post_type_archive_title('', false);

        $this->links[] = $this->currentLink($post_type_label, $post_type_link);
    }

    /**
     * Called if $page === 'tax'
     */
    protected function add_tax_links()
    {
        $tax_slug = \get_query_var('taxonomy');
        $term_slug = \get_query_var('term');
        $term = \get_term_by('slug', $term_slug, $tax_slug);
        $term_id = \absint($term->term_id);
        $term_parent_id = \absint($term->parent);

        $tax_links = [];

        if ($term_parent_id) {
            while ($term_parent_id) {
                $term_parent = \get_term_by(
                    'id',
                    $term_parent_id,
                    $term->taxonomy
                );
                $tax_links[] = $this->makeLink(
                    $term_parent->name,
                    $this->getTermLink(
                        \absint($term_parent->term_id),
                        $term->taxonomy
                    )
                );
                $term_parent_id = \absint($term_parent->parent);
            }

            $this->links = \array_merge(
                $this->links,
                \array_reverse($tax_links)
            );
        }

        $this->links[] = $this->currentLink(
            $term->name,
            $this->getTermLink($term_id, $tax_slug)
        );
    }

    /**
     * Called if $page === 'singular'
     */
    protected function add_singular_links()
    {
        if (($post = \get_post())->post_parent) {
            $parent_id = $post->post_parent;

            $single_links = [];

            while ($parent_id) {
                $parent = \get_post($parent_id);
                $single_links[] = $this->makeLink(
                    \get_the_title($parent->ID),
                    (\get_permalink($parent->ID) ?: '')
                );
                $parent_id = $parent->post_parent;
            }

            $this->links = \array_merge(
                $this->links,
                \array_reverse($single_links)
            );
        } elseif (!\is_post_type_hierarchical($post->post_type)) {
            if ($term = $this->getFirstTerm($post)) {
                $single_links = [];
                $term_id = \absint($term->term_id);

                while ($term_id) {
                    $term = \get_term_by('id', $term_id, $term->taxonomy);
                    $single_links[] = $this->makeLink(
                        $term->name,
                        $this->getTermLink(
                            \absint($term->term_id),
                            $term->taxonomy
                        )
                    );
                    $term_id = \absint($term->parent);
                }

                $this->links = \array_merge(
                    $this->links,
                    \array_reverse($single_links)
                );
            } elseif ('post' !== $post->post_type
                || ($page_for_posts = \get_option('page_for_posts'))
                // NB: 'post' archive is the same as frontpage unless page_for_posts is set
            ) { // Add post type archive link
                $post_type_object = \get_post_type_object($post->post_type);

                $label = (
                    'post' === $post->post_type && $page_for_posts
                    ? \get_the_title($page_for_posts)
                    : $post_type_object->labels->name
                );

                if (($post_type_link =
                    \get_post_type_archive_link($post->post_type))
                ) {
                    $this->links[] = $this->makeLink($label, $post_type_link);
                }
            }
        }

        $this->links[] = $this->currentLink(
            \get_the_title($post->ID),
            (\get_permalink($post->ID) ?: '')
        );
    }

    /**
     * Get post's first term
     */
    protected function getFirstTerm(WP_Post $post)
    {
        $taxonomies = $this->getTaxonomies($post->post_type);

        foreach ($taxonomies as $taxonomy) {
            $post_terms = \get_the_terms($post, $taxonomy);

            if (!$post_terms || \is_wp_error($post_terms)) {
                continue;
            }

            return $post_terms[0];
        }
    }

    /**
     * Get all hierarchical taxonomies
     */
    protected function getTaxonomies(string $post_type): array
    {
        $return = [];

        $taxes = \get_object_taxonomies($post_type, 'objects');

        foreach ($taxes as $tax_slug => $tax_object) {
            if (\is_taxonomy_hierarchical($tax_slug)) {
                $return[] = $tax_slug;
            }
        }

        return $return;
    }

    protected function addHomeLink()
    {
        $this->links[] = $this->makeLink($this->homeLabel, \home_url('/'));
    }

    protected function addPageNumberLink()
    {
        $this->links[] = $this->makeLink(\sprintf(
            \esc_html__('Page %d', 'grotto-wp-breadcrumbs'),
            $this->page->number()
        ));
    }

    protected function currentLink(
        string $title = '',
        string $url = ''
    ): string {
        if ($this->page->is('paged')) {
            return $this->makeLink($title, $url);
        }

        return $this->makeLink($title);
    }

    protected function makeLink(string $title, string $url = ''): string
    {
        $link = '';

        if ($url) {
            $link .= '';
        }

        $link .= ''.\sanitize_text_field($title).'';

        if ($url) {
            $link .= '';
        }

        return $link;
    }

    private function setAttributes(array $args)
    {
        if (!($vars = \get_object_vars($this))) {
            return;
        }

        unset($vars['links']);
        unset($vars['page']);

        foreach ($vars as $key => $value) {
            $this->$key = $args[$key] ?? null;
        }
    }

    private function sanitizeAttributes()
    {
        $this->homeLabel = $this->homeLabel ?
            \sanitize_text_field($this->homeLabel) :
            \esc_html__('Home', 'grotto-wp-breadcrumbs');
        $this->delimiter = $this->delimiter ?
            \esc_attr($this->delimiter) :
            $this->defaultDelimiter();
        $this->after = \sanitize_text_field($this->after);
        $this->before = \sanitize_text_field($this->before);

        $this->links = [];
    }

    private function defaultDelimiter(): string
    {
        return (\is_rtl() ? '/' : '\\');
    }

    protected function getTermLink(int $id, string $tax = ''): string
    {
        $str = \get_term_link($id, $tax);

        if (\is_wp_error($str)) {
            return '';
        }

        return $str;
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Manager;

use Orkestra\Bundle\ApplicationBundle\Entity\File;

class FileManager
{
    /**
     * @var string
     */
    protected $basePath;

    /**
     * Constructor
     *
     * @param string $basePath
     */
    public function __construct($basePath)
    {
        $this->basePath = $basePath;
    }

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

    /**
     * @return string
     */
    public function getBasePath()
    {
        return $this->basePath;
    }

    /**
     * @param resource $gdResource  A GD image resource
     * @param string $path          The path (no filename) to save the image
     * @param string $filename      The filename to save the image as
     *
     * @throws \RuntimeException
     * @return \Orkestra\Bundle\ApplicationBundle\Entity\File
     */
    public function saveImageToPng($gdResource, $path = null, $filename = null)
    {
        if (null === $path) {
            $path = $this->basePath;
        }

        $this->ensureDirectoryExists($path);

        if (null === $filename) {
            $filename = md5(uniqid('imagepng', true)) . '.png';
        }

        $fullPath = $path . '/' . $filename;
        $result = imagepng($gdResource, $fullPath, 5);

        if (!$result) {
            throw new \RuntimeException(sprintf('Could not save image to %s', $fullPath));
        }

        $file = new File($fullPath, $filename, 'image/png', filesize($fullPath));

        return $file;
    }

    /**
     * Attempts to create the given directory, throwing an exception if unable to
     *
     * @param string $path
     *
     * @return string            $path
     * @throws \RuntimeException
     */
    private function ensureDirectoryExists($path)
    {
        if (!is_dir($path)) {
            if (!mkdir($path, 0777, true)) {
                throw new \RuntimeException(sprintf('Could not create directory "%s"', $path));
            }
        }

        return $path;
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Model;

use Doctrine\Common\Persistence\ObjectManager;

/**
 * A resulting set of new or updated entities
 *
 * This class is useful when creating a group of entities without a single
 * entry point, or to allow for explicit control of persisting without using
 * cascade operations.
 */
class EntityOperationResult implements \Iterator, \ArrayAccess, \Countable
{
    /**
     * @var object The root entity, usually the main one created during the operation
     */
    public $root;

    /**
     * @var array
     */
    private $entities = array();

    /**
     * Add an entity to this result
     *
     * @param object $entity
     */
    public function addEntity($entity)
    {
        $this->entities[] = $entity;
    }

    /**
     * Persist all stored entities with the given ObjectManager
     *
     * @param ObjectManager $manager
     */
    public function persist(ObjectManager $manager)
    {
        foreach ($this->entities as $entity) {
            $manager->persist($entity);
        }

        if ($this->root) {
            $manager->persist($this->root);
        }
    }

    /**
     * @param mixed $offset
     *
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($this->entities[$offset]);
    }

    /**
     * @param mixed $offset
     *
     * @return mixed|null
     */
    public function offsetGet($offset)
    {
        return $this->offsetExists($offset) ? $this->entities[$offset] : null;
    }

    /**
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        $this->entities[$offset] = $value;
    }

    /**
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->entities[$offset]);
    }

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

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

    /**
     * @return mixed|void
     */
    public function key()
    {
        return key($this->entities);
    }

    /**
     * @return bool
     */
    public function valid()
    {
        return $this->offsetExists(key($this->entities));
    }

    /**
     * @return void
     */
    public function rewind()
    {
        reset($this->entities);
    }

    /**
     * @return int
     */
    public function count()
    {
        return count($this->entities) + (null !== $this->root ? 1 : 0);
    }
}


<?php
namespace Crayon;

use const Crayon\{RED, GREEN, BLUE, YELLOW, MAGENTA, CYAN};

/**
 * Class Font
 *
 * A string representation class which contains all formatting information
 * that'll be used when rendering the string.
 *
 * @package Crayon
 */
class Font
{
    /**
     * @var string
     */
    const BOLD = "\e[1m";

    /**
     * @var string
     */
    const ITALIC = "\e[3m";

    /**
     * @var string
     */
    const UNDERLINE = "\e[4m";

    /**
     * @var string
     */
    const RESET = "\e[0m";

    /**
     * the text to be formatted
     * @var string|null
     */
    private $text;

    /**
     * boolean value to indicate if the text shall be rendered bold
     * @var bool
     */
    private $bold = false;

    /**
     * boolean value to indicate if the text shall be rendered italic
     * @var bool
     */
    private $italic = false;

    /**
     * boolean value to indicate if the text shall be rendered underlined
     * @var bool
     */
    private $underline = false;

    /**
     * may contain the color format string if available
     * @var string|null
     */
    private $color;

    /**
     * sets the information that the color should be applied as background
     * @var bool
     */
    private $background = false;

    /**
     * Font constructor.
     * @param string $text
     */
    public function __construct(string $text)
    {
        $this->text = $text;
    }

    /**
     * function to set text bold
     * @return Font
     */
    public function bold(): Font
    {
        $this->bold = true;
        return $this;
    }

    /**
     * function to set text italic
     * @return Font
     */
    public function italic(): Font
    {
        $this->italic = true;
        return $this;
    }

    /**
     * function to set text underlined
     * @return Font
     */
    public function underline(): Font
    {
        $this->underline = true;
        return $this;
    }

    /**
     * function to color the text red
     * @return Font
     */
    public function red(): Font
    {
        return $this->color(RED);
    }

    /**
     * function to color the text green
     * @return Font
     */
    public function green(): Font
    {
        return $this->color(GREEN);
    }

    /**
     * function to color the text yellow
     * @return Font
     */
    public function yellow(): Font
    {
        return $this->color(YELLOW);
    }

    /**
     * function to color the text blue
     * @return Font
     */
    public function blue(): Font
    {
        return $this->color(BLUE);
    }

    /**
     * function to color the magenta
     * @return Font
     */
    public function magenta(): Font
    {
        return $this->color(MAGENTA);
    }

    /**
     * function to color the text cyan
     * @return Font
     */
    public function cyan(): Font
    {
        return $this->color(CYAN);
    }

    /**
     * function to set color as background
     * @return Font
     */
    public function background(): Font
    {
        if ($this->color !== null) {
            $this->turnToBackground();
        }

        $this->background = true;
        return $this;
    }

    /**
     * function to prepare and render the text with set font options
     * @return string
     */
    public function __toString()
    {
        $reset = self::RESET;

        $font_color = $this->color ?? '';
        $is_bold = $this->bold ? self::BOLD : '';
        $is_italic = $this->italic ? self::ITALIC : '';
        $is_underline = $this->underline ? self::UNDERLINE : '';

        return "{$font_color}{$is_bold}{$is_italic}{$is_underline}{$this->text}{$reset}";
    }

    /**
     * function to set color to a string
     * @param string $color
     * @return Font
     */
    private function color(string $color): Font
    {
        $this->color = $color;

        if ($this->background) {
            $this->turnToBackground();
        }

        return $this;
    }

    /**
     * function to convert color to background color
     */
    private function turnToBackground()
    {
        $this->color = preg_replace_callback('/\\e\[(?<color>\d+)m/', function ($matches) {
            $new_color = $matches['color'] + 10;
            return "\e[{$new_color}m";
        }, $this->color);
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Helper;

use Orkestra\Bundle\ApplicationBundle\Entity\HashedEntity;
use Orkestra\Bundle\ApplicationBundle\Model\UserInterface;

class PasswordHelper
{
    /**
     * @var HashedEntityHelper
     */
    private $hashedEntityHelper;

    /**
     * @var EmailHelperInterface
     */
    private $emailHelper;

    /**
     * Constructor
     *
     * @param EmailHelperInterface $emailHelper
     * @param HashedEntityHelper   $hashedEntityHelper
     */
    public function __construct(
        EmailHelperInterface $emailHelper,
        HashedEntityHelper $hashedEntityHelper
    ) {
        $this->emailHelper = $emailHelper;
        $this->hashedEntityHelper = $hashedEntityHelper;
    }

    /**
     * Looks up a user with the given hash
     *
     * @param string $hash
     * @param string $className
     * @return null|HashedEntity
     */
    public function lookup($hash, $className = 'Orkestra\Bundle\ApplicationBundle\Entity\User')
    {
        try {
            return $this->hashedEntityHelper->lookup($hash, $className);

        } catch (\RuntimeException $e) {
            return null;
        }
    }

    /**
     * Sends password reset message to the user
     *
     * @param User $user
     * @param      $subject
     *
     * @return HashedEntity
     */
    public function sendPasswordResetEmail(UserInterface $user, $subject = 'Password reset request')
    {
        $hashedEntity = $this->createHash($user);
        $this->emailHelper->createAndSendMessageFromTemplate(
            'OrkestraApplicationBundle:Email:setPassword.html.twig',
            array(
                'user' => $user,
                'hash' => $hashedEntity->getHash()
            ),
            $subject,
            $user->getEmail()
        );

        return $hashedEntity;
    }

    /**
     * @param User $user
     * @return HashedEntity
     */
    private function createHash(UserInterface $user)
    {
        $hashedEntity = $this->hashedEntityHelper->create($user, new \DateTime('+1 day'));

        return $hashedEntity;
    }
}


<?php

namespace Sco\Tree\Traits;

use ArrayAccess;
use BadMethodCallException;
use Illuminate\Support\Collection;
use InvalidArgumentException;

trait TreeTrait
{
    private $allNodes = null;

    /**
     * 数据主ID名.
     *
     * @return string
     */
    protected function getTreeNodeIdName()
    {
        return property_exists($this, 'treeNodeIdName') ? $this->treeNodeIdName : 'id';
    }

    /**
     * 数据父ID名.
     *
     * @return string
     */
    protected function getTreeNodeParentIdName()
    {
        return property_exists($this, 'treeNodeParentIdName') ? $this->treeNodeParentIdName
                                                              : 'parent_id';
    }

    protected function getTreeSpacer()
    {
        return property_exists($this, 'treeSpacer') ? $this->treeSpacer : '   ';
    }

    protected function getTreeFirstIcon()
    {
        return property_exists($this, 'treeFirstIcon') ? $this->treeFirstIcon
                                                       : '   │ ';
    }

    protected function getTreeMiddleIcon()
    {
        return property_exists($this, 'treeMiddleIcon') ? $this->treeMiddleIcon
                                                        : '   ├─ ';
    }

    protected function getTreeLastIcon()
    {
        return property_exists($this, 'treeLastIcon') ? $this->treeLastIcon
                                                      : '   └─ ';
    }

    /**
     * 获取待格式树结构的节点数据.
     *
     * @return mixed
     */
    final protected function getAllNodes()
    {
        if ($this->allNodes) {
            return $this->allNodes;
        }

        if (!method_exists($this, 'getTreeAllNodes')) {
            throw new BadMethodCallException('Method [getTreeAllNodes] does not exist.');
        }

        $data = $this->getTreeAllNodes(); // 由use的class来实现

        if (!$data instanceof ArrayAccess) {
            throw new InvalidArgumentException('tree data must be a collection');
        }
        // 重置键值
        $this->allNodes = collect([]);
        foreach ($data as $item) {
            $this->allNodes->put($item->{$this->getTreeNodeIdName()}, $item);
        }

        return $this->allNodes;
    }

    /**
     * 设置 所有节点.
     *
     * @param \Illuminate\Support\Collection $nodes
     */
    public function setAllNodes(Collection $nodes)
    {
        $this->allNodes = $nodes;
    }

    /**
     * 获取子级（仅子代一级）.
     *
     * @param mixed $parentId
     *
     * @return array
     */
    public function getSubLevel($parentId)
    {
        $data = $this->getAllNodes();

        $childList = collect([]);
        foreach ($data as $val) {
            if ($val->{$this->getTreeNodeParentIdName()} == $parentId) {
                $childList->put($val->{$this->getTreeNodeIdName()}, $val);
            }
        }

        return $childList;
    }

    /**
     * 获取指定节点的所有后代.
     *
     * @param mixed  $parentId
     * @param int    $depth
     * @param string $adds
     *
     * @return \Illuminate\Support\Collection
     */
    public function getDescendants($parentId, $depth = 0, $adds = '')
    {
        static $array;
        if (!$array instanceof ArrayAccess || $depth == 0) {
            $array = collect([]);
        }
        $number = 1;
        $child = $this->getSubLevel($parentId);
        if ($child) {
            $nextDepth = $depth + 1;
            $total = $child->count();
            foreach ($child as $val) {
                $j = $k = '';
                if ($number == $total) {
                    $j .= $this->getTreeLastIcon();
                    $k = $this->getTreeSpacer();
                } else {
                    $j .= $this->getTreeMiddleIcon();
                    $k = $adds ? $this->getTreeFirstIcon() : '';
                }

                $val->spacer = $adds ? ($adds.$j) : '';

                $val->depth = $depth;
                $array->put($val->{$this->getTreeNodeIdName()}, $val);
                $this->getDescendants(
                    $val->{$this->getTreeNodeIdName()},
                    $nextDepth,
                    $adds.$k.$this->getTreeSpacer()
                );
                ++$number;
            }
        }

        return $array;
    }

    /**
     * 获取指定节点的所有后代（分层级）.
     *
     * @param mixed $id
     *
     * @return \Illuminate\Support\Collection
     */
    public function getLayerOfDescendants($id)
    {
        $child = $this->getSubLevel($id);
        $data = collect([]);
        if ($child) {
            foreach ($child as $val) {
                $val->child = $this->getLayerOfDescendants($val->{$this->getTreeNodeIdName()});
                $data->put($val->{$this->getTreeNodeIdName()}, $val);
            }
        }

        return $data;
    }

    /**
     * 获取指定id的数据.
     *
     * @param mixed $id
     *
     * @return mixed
     */
    public function getSelf($id)
    {
        $data = $this->getAllNodes();

        return $data->get($id);
    }

    /**
     * 获取父一级节点.
     *
     * @param mixed $id
     *
     * @return mixed
     */
    public function getParent($id)
    {
        $node = $this->getSelf($id);
        if ($node) {
            $parentId = $node->{$this->getTreeNodeParentIdName()};

            return $this->getSelf($parentId);
        }
    }

    /**
     * 获取节点的所有祖先.
     *
     * @param int $id
     * @param int $depth
     *
     * @return array
     */
    public function getAncestors($id, $depth = 0)
    {
        static $array;
        if (!$array instanceof ArrayAccess || $depth == 0) {
            $array = collect([]);
        }
        $parent = $this->getParent($id);
        if ($parent) {
            $nextDepth = $depth + 1;
            $array->prepend($parent);   // 添加到开头
            $this->getAncestors($parent->{$this->getTreeNodeIdName()}, $nextDepth);
        }

        return $array;
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Adds useful functionality to Twig
 *
 * @author Tyler Sommer <sommertm@gmail.com>
 */
class OrkestraExtension extends \Twig_Extension
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;

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

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

    /**
     * @var \Symfony\Component\HttpFoundation\Request
     */
    private $request;

    /**
     * @return array
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('current_controller', array($this, 'getController')),
            new \Twig_SimpleFunction('current_action', array($this, 'getAction')),
            new \Twig_SimpleFunction('is_currently_on', array($this, 'isCurrentlyOn')),
            new \Twig_SimpleFunction('is_current_route', array($this, 'isCurrentRoute')),
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'orkestra_extension';
    }

    /**
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     */
    public function setContainer(ContainerInterface $container)
    {
        $this->container = $container;
        if ($this->container->has('request_stack')) {
            $this->request = $this->container->get('request_stack')->getCurrentRequest();
        }
    }

    /**
     * Returns true if the user is currently on the given controller(s)
     *
     * @param string|array $controllers
     *
     * @return bool
     */
    public function isCurrentlyOn($controllers)
    {
        $controllers = is_array($controllers) ? $controllers : array($controllers);

        foreach ($controllers as $controller) {
            if ($this->getController() == $controller) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns true if the given route matches the current route
     *
     * @param string $route
     *
     * @return bool
     */
    public function isCurrentRoute($route)
    {
        return $route === $this->getCurrentRequest()->get('_route');
    }

    /**
     * @return string
     */
    public function getController()
    {
        // TODO Check if request is the same as it was so that the controller gets changed
        if (!$this->controller) {
            $pattern = "#Controller\\\([a-zA-Z\\\\]*)Controller#";
            $matches = array();
            preg_match($pattern, $this->getCurrentRequest()->get('_controller'), $matches);

            $this->controller = isset($matches[1]) ? $matches[1] : null;
        }

        return $this->controller;
    }

    /**
     * @return string
     */
    public function getAction()
    {
        if (!$this->action) {
            $pattern = "#::([a-zA-Z]*)Action#";
            $matches = array();
            preg_match($pattern, $this->getCurrentRequest()->get('_controller'), $matches);

            $this->action = isset($matches[1]) ? $matches[1] : null;
        }

        return $this->action;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Request
     */
    protected function getCurrentRequest()
    {
        if (!$this->request) {
            if ($this->container->has('request_stack')) {
                $this->request = $this->container->get('request_stack')->getCurrentRequest();
            } else {
                throw new \RuntimeException('Unable to get "request" service');
            }
        }

        return $this->request;
    }
}


<?php
/**
 * @license MIT
 */
namespace Pivasic\Bundle\Template;

use Pivasic\Bundle\Template\Exception\FileNotFoundException;

/**
 * Class Native
 * @package Pivasic\Bundle\Template
 */
class Native
{
    /**
     * @param string $packageRoot
     * @param string $language
     * @param bool $cache
     */
    public function __construct(string $packageRoot, string $language = '', bool $cache = true)
    {
        $this->packageRoot = rtrim($packageRoot, '/');
        $this->language = $language;
        $this->cache = $cache;
        $this->isRouteView = false;
        $this->title = '';
    }

    /**
     * Create content from template and data.
     *
     * @param string $name
     * @param array $data
     * @return string
     * @throws FileNotFoundException
     * @throws \RuntimeException
     */
    public function getContent(string $name, array $data = []): string
    {
        $cacheName = $name;
        if ('' == $name) {
            $this->isRouteView = true;

            $stack = debug_backtrace();
            foreach ($stack as $item) {
                if (false !== stripos($item['file'], DIRECTORY_SEPARATOR . 'Route' . DIRECTORY_SEPARATOR)) {
                    $cacheName = pathinfo($item['file'], PATHINFO_DIRNAME) . '/' . $name;
                    $cacheName = explode('Route' . DIRECTORY_SEPARATOR, $cacheName)[1];
                    $cacheName = 'route_' . str_replace(['/', '\\'], '_', $cacheName);
                    break;
                }
            }
        }
        $cacheName .= '_' . $this->language . '.html.php';
        $path = $this->packageRoot . '/view/_cache/' . str_replace('/', '_', $cacheName);

        $exist = file_exists($path);
        if (!$this->cache || !$exist) {
            $code = $this->compile($name . '/view.html.php', true, true, true);

            $code = preg_replace(['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'], ['>', '<', '\\1'], $code);

            if ($exist) {
                $fh = fopen($path, 'r+b');
            } else {
                $fh = fopen($path, 'wb');
            }
            if (flock($fh, LOCK_EX)) {
                ftruncate($fh, 0);
                fwrite($fh, $code);
                flock($fh, LOCK_UN);
            }
            fclose($fh);
        }

        $fh = fopen($path, 'rb');
        if (flock($fh, LOCK_SH)) {
            $html = self::renderTemplate($path, $data);

            flock($fh, LOCK_UN);
            fclose($fh);

            return $html;
        }

        throw new \RuntimeException('Can\'t render template');
    }

    /**
     * Create solid template.
     *
     * @param string $name
     * @param bool $processLang
     * @param bool $processInclude
     * @param bool $processExtends
     * @return string
     * @throws FileNotFoundException
     */
    private function compile(string $name, bool $processLang, bool $processInclude, bool $processExtends): string
    {
        if ($this->isRouteView) {
            $this->isRouteView = false;
            $path = '';
            $stack = debug_backtrace();
            foreach ($stack as $item) {
                if (false !== stripos($item['file'], DIRECTORY_SEPARATOR . 'Route' . DIRECTORY_SEPARATOR)) {
                    $path = pathinfo($item['file'], PATHINFO_DIRNAME) . '/view.html.php';
                    if ($processLang) {
                        $storagePath = str_replace('view.html.php', '_lang/' . $this->language . '.php', $path);
                    }
                    break;
                }
            }
        } else {
            $path = $this->packageRoot . '/view/' . $name;
            if ($processLang) {
                $storagePath = str_replace('view.html.php', '', $path) . '_lang/' . $this->language . '.php';
            }
        }

        if (file_exists($path)) {
            ob_start();
            readfile($path);
            $code = ob_get_clean();
        } else {
            throw new FileNotFoundException($path);
        }

        if ($processLang && file_exists($storagePath)) {
            $storage = include $storagePath;
            if ('' == $this->title) {
                $this->title = $storage['title'] ?? '';
            }
            preg_match_all('/<!-- lang (.*) -->/', $code, $matchList);
            if (isset($matchList[1])) {
                foreach ($matchList[1] as $key => $index) {
                    $name = explode('>', $index);
                    $default = trim($name[1] ?? '');
                    $name = trim($name[0]);
                    if (!empty($matchList[0][$key]) && false !== strpos($code, $matchList[0][$key])) {
                        $code = str_replace($matchList[0][$key], $storage[$name] ?? $default, $code);
                    }
                }
            }
        } else {
            preg_match_all('/<!-- lang (.*) -->/', $code, $matchList);
            if (isset($matchList[1])) {
                foreach ($matchList[1] as $key => $index) {
                    $name = explode('>', $index);
                    $default = trim($name[1] ?? '');
                    $name = trim($name[0]);
                    if (!empty($matchList[0][$key]) && false !== strpos($code, $matchList[0][$key])) {
                        $code = str_replace($matchList[0][$key], $this->$name ?? $default, $code);
                    }
                }
            }
        }

        if ($processInclude) {
            preg_match_all('/<!-- include (.*) -->/', $code, $matchList);
            if (isset($matchList[1])) {
                foreach ($matchList[1] as $key => $template) {
                    if (!empty($matchList[0][$key]) && false !== strpos($code, $matchList[0][$key])) {
                        $template = trim($template);
                        $code = str_replace($matchList[0][$key], $this->compile($template . '/view.html.php', true, true, false), $code);
                    }
                }
            }
        }

        if ($processExtends) {
            preg_match_all('/<!-- extends (.*) -->/', $code, $matchList);
            if (isset($matchList[1][0])) {
                $template = trim($matchList[1][0]);
                $parentHtml = $this->compile($template . '/view.html.php', true, true, false);

                $code = str_replace($matchList[0][0], '', $code);
                $parentHtml = str_replace('<!-- section -->', $code, $parentHtml);
                $code = $parentHtml;
            }
        }

        return $code;
    }

    /**
     * Safe include. Used for scope isolation.
     *
     * @param string $__file__  File to include
     * @param array  $data      Data passed to template
     * @return string
     */
    private static function renderTemplate(string $__file__, array $data): string
    {
        ob_start();
        extract($data);
        include $__file__;
        return ob_get_clean();
    }

    private $packageRoot;
    private $language;
    private $cache;
    private $isRouteView;

    private $title;
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Controller\Auth;

use Doctrine\ORM\EntityNotFoundException;
use Orkestra\Bundle\ApplicationBundle\Controller\Controller;
use Orkestra\Bundle\ApplicationBundle\Http\JsonErrorResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\HttpFoundation\Request;

/**
 * @Route
 */
class PasswordSetController extends Controller
{
    const CURRENT_USER_ID_KEY = '__orkestra_set_password_user_id';

    /**
     * Displays a form to request a reset
     *
     * @Route("/set-password/{hash}", name="orkestra_password_set_new")
     * @Template
     */
    public function newAction(Request $request, $hash)
    {
        $passwordHelper = $this->get('orkestra.application.helper.password');
        $hashedEntityHelper = $this->get('orkestra.application.helper.hashed_entity');
        $hashedEntity = $passwordHelper->lookup($hash);
        if (!$hashedEntity) {
            throw new EntityNotFoundException();
        }
        $user = $hashedEntity->getReferencedObject();
        $hashedEntityHelper->invalidate($hashedEntity);

        $em = $this->getDoctrine()->getManager();
        $em->persist($hashedEntity);
        $em->flush();

        if ($user) {
            $request->getSession()->set(PasswordSetController::CURRENT_USER_ID_KEY, $user->getId());
            $form = $this->getSetPasswordForm();

            return array(
                'form' => $form->createView()
            );
        } else {
            throw $this->createNotFoundException('No user was found.');
        }

    }

    /**
     * Resets a user's password and emails them the temporary password
     *
     * @Route("/set-password", name="orkestra_password_set_create", defaults={"_format"="json"})
     * @Method("POST")
     */
    public function createAction(Request $request)
    {
        $form = $this->getSetPasswordForm();
        $form->bind($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('Orkestra\Bundle\ApplicationBundle\Entity\User')->find($request->getSession()->get(PasswordSetController::CURRENT_USER_ID_KEY));

            if ($user) {
                $password = $form->get('password')->getData();
                $factory = $this->get('security.encoder_factory');
                $encoder = $factory->getEncoder($user);
                $user->setPassword($encoder->encodePassword($password, $user->getSalt()));

                $em->persist($user);
                $em->flush();
                $this->get('session')->getFlashBag()->set('success', 'Your password has been set.');

                return $this->redirect($this->generateUrl('login'));
            }
        }

        return new JsonErrorResponse('The passwords provided do not match.');
    }

    private function getSetPasswordForm()
    {
        return $this->createFormBuilder()
            ->add('password', RepeatedType::class, array(
                'type'        => PasswordType::class,
                'first_name'  => 'password',
                'second_name' => 'confirm'
            ))
            ->getForm();
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Security\Authentication;

use Orkestra\Bundle\ApplicationBundle\Http\JsonErrorResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;

/**
 * Supports the client side JsonResponse API
 */
class AuthenticationFailureHandler extends DefaultAuthenticationFailureHandler
{
    /**
     * {@inheritDoc}
     */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if (($request->get('_format') == 'json'
            || 0 < strpos($request->headers->get('accept'), 'application/json')
            || 0 < strpos($request->headers->get('accept'), 'text/javascript'))
        ) {
            return new JsonErrorResponse('Authentication failed. Please try again.');
        }

        return parent::onAuthenticationFailure($request, $exception);
    }
}