<?php
namespace wapmorgan\SystemDaemon;

use wapmorgan\SystemDaemon\Loggers\TerminalLogger;
use wapmorgan\SystemDaemon\Utilities\WindowsFork;
use Exception;

class AbstractDaemon
{
    const DEFAULT_PID_FILE = '{tmp}/daemon-{name}.pid';
    const DEFAULT_LOCK_FILE = '{tmp}/daemon-{name}.lock';
    const DEFAULT_LOG_FILE = '/var/log/daemon-{name}.log';

    /**
     * Daemon types
     */
    const NORMAL = 1;
    const TICKABLE = 2;

    /**
     * Log targets
     */
    const SYSLOG = 1;
    const FILES = 2;
    const FILES_DEBUG = 3;
    const TERMINAL = 4;

    /**
     * Log message levels
     */
    const ERROR = 'error';
    const WARNING = 'warning';
    const NOTICE = 'notice';
    const INFO = 'info';
    const DEBUG = 'debug';

    /**
     * @var string Short name of this daemon.
     * Used for generating pid and lock files for this daemon.
     */
    public $name;

    /**
     * @var string Full name of this daemon.
     * Used to show in managment console.
     */
    public $fullname;

    /**
     * @var string Daemons group.
     * Used to manage all daemons within a group.
     */
    public $group = 'default';

    /**
     * Settings:
     * @var boolean $usePidFile Should be or should not be used pid files for this daemon.
     * @var boolean $useLockFile Should be or should not be used lock files for this daemon.
     */
    public $usePidFile = true;
    public $useLockFile = true;

    /**
     * @var string The location of pid file for this daemon.
     * By default used AbstractDaemon::DEFAULT_PID_FILE template
     */
    public $pidFile;

    /**
     * @var string The location of lock file for this daemon.
     * By default used AbstractDaemon::DEFAULT_LOCK_FILE template
     */
    public $lockFile;

    /**
     * @var integer Stragery of daemon.
     */
    protected $strategy;

    /**
     * @var float Tick time for tickable daemon
     */
    protected $tickTime = null;

    /**
     * @var boolean Flag used as an indicator of running
     */
    protected $ticking = true;

    /**
     * @var boolean Flag used as an indicator of running
     */
    protected $running = true;

    /**
     * @var null|Loggers\* Logger of daemon.
     * If null, no logs will be collected.
     */
    protected $logger;

    /**
     * Builds a daemon.
     * @param integer $strategy
     * @param integer $tickTime Time between ticks. Valueable only if ticking strategy used.
     */
    public function __construct($strategy = self::NORMAL, $tickTime = null)
    {
        if ($strategy === self::TICKABLE) {
            $this->strategy = self::TICKABLE;
            if (!is_numeric($tickTime) || $tickTime === 0)
                throw new Exception('Tick time should be positive integer!');
            $this->tickTime = $tickTime;
        } else
            $this->strategy = self::NORMAL;

        $this->pidFile = static::DEFAULT_PID_FILE;
        $this->lockFile = static::DEFAULT_LOCK_FILE;
    }

    /**
     * Sets logger for daemon.
     * @param integer $log
     */
    public function setLogger($log = self::SYSLOG)
    {
        if ($log === self::FILES || $log === self::FILES_DEBUG) {
            $log_file = strtr(static::DEFAULT_LOG_FILE, [
                '{name}' => $this->name,
            ]);
            $this->logger = new Loggers\FilesLogger($log_file);
        } else if ($log === self::TERMINAL) {
            $this->logger = new Loggers\TerminalLogger();
        } else
            $this->logger = new Loggers\SyslogLogger();
        return $this;
    }

    /**
     * Starts daemon.
     * @return integer Process ID of daemon.
     */
    public function start()
    {
        $this->ensureNotLocked();
        $pid = $this->fork();

        // return pid
        if ($pid > 0)
            return $pid;

        declare(ticks=1);

        $this->lock();
        $this->registerSignalHandlers();
        if ($this->strategy === self::NORMAL)
            $this->onStart();
        else
            $this->startTicking();
        $this->unlock();
        exit(0);
    }

    /**
     * Returns status about a daemon.
     * Notice: if lock files are not used, this method alwats returns false.
     * @return boolean|array Returns false if daemon is not running
     */
    public function getStatus()
    {
        if (!$this->useLockFile)
            return false;

        $lock_file = strtr($this->lockFile, [
            '{tmp}' => sys_get_temp_dir(),
            '{name}' => $this->name,
        ]);

        if (!file_exists($lock_file))
            return false;

        if (!is_readable($lock_file))
            throw new Exception('Lock file can not be read ('.$lock_file.'). Is daemon launched by root?');

        $lock_data = json_decode(file_get_contents($lock_file));

        // corrupted lock data, delete lock
        if (!is_object($lock_data)) {
            if (!unlink($lock_file))
                throw new Exception('Can not delete messed lock file ('.$lock_file.').');
            return false;
        }

        // check if daemon is still running
        if (!is_dir('/proc/'.$lock_data->pid)) {
            if (!unlink($lock_file))
                throw new Exception('Can not delete invalid lock file ('.$lock_file.').');
            return false;
        }

        return $lock_data;
    }

    /**
     * Stops daemon.
     * @return null|boolean True if daemon is stopped. Null if it was not running.
     */
    public function stop()
    {
        $lock_data = $this->getStatus();
        if ($lock_data === false)
            return null;

        return posix_kill($lock_data->pid, SIGTERM);
    }

    /**
     * Kills daemon.
     * @return null|boolean True if daemon is stopped. Null if it was not running.
     */
    public function kill()
    {
        $lock_data = $this->getStatus();
        if ($lock_data === false)
            return null;

        return posix_kill($lock_data->pid, SIGKILL);
    }

    protected function ensureNotLocked()
    {
        if (!$this->useLockFile)
            return true;

        $lock_file = strtr($this->lockFile, [
            '{tmp}' => sys_get_temp_dir(),
            '{name}' => $this->name,
        ]);

        if (!file_exists($lock_file))
            return true;

        if (!is_readable($lock_file))
            throw new Exception('Lock file can not be read ('.$lock_file.'). Is daemon launched by root?');

        $lock_data = json_decode(file_get_contents($lock_file));

        // corrupted lock data, delete lock
        if (!is_object($lock_data)) {
            if (!unlink($lock_file))
                throw new Exception('Can not delete messed lock file ('.$lock_file.').');
        }

        // check if daemon is still running
        if (!is_dir('/proc/'.$lock_data->pid)) {
            if (!unlink($lock_file))
                throw new Exception('Can not delete invalid lock file ('.$lock_file.').');

            return true;
        }

        throw new Exception('Daemon is still running (PID '.$lock_data->pid.').');
    }

    protected function fork()
    {
        if (function_exists('pcntl_fork')) {
            $result_pid = pcntl_fork();

            // failure
            if ($result_pid === -1) {
                throw new Exception('Can\'t fork. Check system settings.');
            }

            return $result_pid;
        }

        throw new Exception('Unable to fork.');
    }

    protected function lock()
    {
        if (!$this->useLockFile)
            return true;

        $lock_file = strtr($this->lockFile, [
            '{tmp}' => sys_get_temp_dir(),
            '{name}' => $this->name,
        ]);

        $lock_data = [
            'pid' => getmypid(),
            'uid' => getmyuid(),
            'gid' => getmygid(),
            'group' => $this->group,
        ];

        if (!file_put_contents($lock_file, json_encode($lock_data)))
            throw new Exception('Can\'t write lock file. Do you have sufficient permissions?');

        return true;
    }

    protected function unlock()
    {
        if (!$this->useLockFile)
            return true;

        $lock_file = strtr($this->lockFile, [
            '{tmp}' => sys_get_temp_dir(),
            '{name}' => $this->name,
        ]);

        if (file_exists($lock_file)) {
            if (!unlink($lock_file))
                throw new Exception('Can not delete lock file ('.$lock_file.').');
        }

        return true;
    }

    protected function registerSignalHandlers()
    {
        pcntl_signal(SIGTERM, [$this, 'onSigTerm']);
        pcntl_signal(SIGUSR1, [$this, 'onSigUsr1']);
        pcntl_signal(SIGUSR2, [$this, 'onSigUsr2']);
    }

    public function onSigTerm()
    {
        if ($this->strategy === self::TICKABLE)
            $this->ticking = false;
        else
            $this->handleStop();
    }

    public function onSigUsr1()
    {
        $this->log(self::INFO, 'Received SIGUSR1 signal. Reimplement '.get_class($this).'::onSigUsr1() method to change this behavior.');
    }

    public function onSigUsr2()
    {
        $this->log(self::INFO, 'Received SIGUSR2 signal. Reimplement '.get_class($this).'::onSigUsr2() method to change this behavior.');
    }

    protected function handleStop()
    {
        $this->log(self::INFO, 'This is a informing message when calling handleStop() method on normal daemon. Reimplement '.get_class($this).'::handleStop() method to change this behavior.');
        $this->running = false;
    }

    protected function onStart()
    {
        while ($this->running) {
            $this->log(self::INFO, 'This is a informing message. Reimplement '.get_class($this).'::onStart() method to do real work.');
            sleep(2);
        }
    }

    protected function startTicking()
    {
        while ($this->ticking) {
            $this->onTick();
            sleep($this->tickTime);
        }
    }

    protected function onTick()
    {
        $this->log(self::INFO, 'This is a informing message. Reimplement '.get_class($this).'::onTick() method to do real work.');
    }

    protected function log($level, $message)
    {
        if ($this->logger !== null)
            $this->logger->log($level, $message);
    }
}


<?php

/*
 * This file is part of the Active Collab DatabaseObject project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseObject;

use ActiveCollab\ContainerAccess\ContainerAccessInterface;
use ActiveCollab\ContainerAccess\ContainerAccessInterface\Implementation as ContainerAccessInterfaceImplementation;
use ActiveCollab\DatabaseConnection\ConnectionInterface;
use ActiveCollab\DatabaseConnection\Result\Result;
use Doctrine\Common\Inflector\Inflector;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;

/**
 * @package ActiveCollab\DatabaseObject
 */
class Finder implements FinderInterface, ContainerAccessInterface
{
    use ContainerAccessInterfaceImplementation;

    /**
     * @var ConnectionInterface
     */
    private $connection;

    /**
     * @var PoolInterface
     */
    private $pool;

    /**
     * @var LoggerInterface
     */
    private $log;

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

    /**
     * @var string[]
     */
    private $where = [];

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

    /**
     * @var int|null
     */
    private $offset;

    /**
     * @var int|null
     */
    private $limit;

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

    /**
     * @param PoolInterface        $pool
     * @param ConnectionInterface  $connection
     * @param LoggerInterface|null $log
     * @param string               $type
     */
    public function __construct(ConnectionInterface $connection, PoolInterface $pool, LoggerInterface &$log = null, $type)
    {
        $this->connection = $connection;
        $this->pool = $pool;
        $this->log = $log;
        $this->type = $type;
        $this->order_by = $this->pool->getEscapedTypeOrderBy($type);
    }

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

    // ---------------------------------------------------
    //  Configuration
    // ---------------------------------------------------

    /**
     * Set finder  .
     *
     * @param string $pattern
     * @param  mixed  ...$arguments
     * @return $this
     */
    public function &where($pattern, ...$arguments)
    {
        if (!is_string($pattern)) {
            throw new InvalidArgumentException('Conditions pattern needs to be string');
        }

        $conditions_to_prepare = [$pattern];

        if (!empty($arguments)) {
            $conditions_to_prepare = array_merge($conditions_to_prepare, $arguments);
        }

        $this->where[] = $this->connection->prepareConditions($conditions_to_prepare);

        return $this;
    }

    /**
     * Return where part of the query.
     */
    public function getWhere()
    {
        switch (count($this->where)) {
            case 0:
                return '';
            case 1:
                return $this->where[0];
            default:
                return implode(' AND ', array_map(function ($condition) {
                    return "($condition)";
                }, $this->where));
        }
    }

    /**
     * @param  string $order_by
     * @return $this
     */
    public function &orderBy($order_by)
    {
        $this->order_by = $order_by;

        return $this;
    }

    /**
     * @param  int   $offset
     * @param  int   $limit
     * @return $this
     */
    public function &limit($offset, $limit)
    {
        $this->offset = $offset;
        $this->limit = $limit;

        return $this;
    }

    /**
     * @param  string $type
     * @param  string $field_name
     * @return $this
     */
    public function &join($type, $field_name = null)
    {
        return $this->joinTable($this->pool->getTypeTable($type), $field_name);
    }

    /**
     * @param  string $table_name
     * @param  string $field_name
     * @return $this
     */
    public function &joinTable($table_name, $field_name = null)
    {
        $join_table = $this->connection->escapeTableName($table_name);
        $join_field = $this->connection->escapeFieldName($field_name ? $field_name : $this->getJoinFieldNameFromType());

        $this->join = "LEFT JOIN $join_table ON {$this->getEscapedTableName()}.`id` = $join_table.$join_field";

        return $this;
    }

    /**
     * @return string
     */
    private function getJoinFieldNameFromType()
    {
        if (($pos = strrpos($this->getType(), '\\')) === false) {
            $type = $this->getType();
        } else {
            $type = substr($this->getType(), $pos + 1);
        }

        return Inflector::tableize($type) . '_id';
    }

    // ---------------------------------------------------
    //  Execution
    // ---------------------------------------------------

    /**
     * Return number of records that match the given criteria.
     *
     * @return int
     */
    public function count()
    {
        $table_name = $this->getEscapedTableName();

        $sql = "SELECT COUNT($table_name.`id`) AS 'row_count' FROM $table_name";

        if ($this->join) {
            $sql .= " $this->join";
        }

        if ($where = $this->getWhere()) {
            $sql .= " WHERE $where";
        }

        return $this->connection->executeFirstCell($sql);
    }

    /**
     * Return all records that match the given criteria.
     *
     * @return Result|object[]|null
     */
    public function all()
    {
        return $this->execute();
    }

    /**
     * Return first record that matches the given criteria.
     *
     * @return object|null
     */
    public function first()
    {
        if ($this->offset === null) {
            $this->offset = 0;
        }

        $this->limit = 1;

        if ($result = $this->execute()) {
            return $result[0];
        }

        return null;
    }

    /**
     * Return array of ID-s that match the given criteria.
     *
     * @return int[]
     */
    public function ids()
    {
        $ids = $this->connection->executeFirstColumn($this->getSelectIdsSql());

        return empty($ids) ? [] : $ids;
    }

    /**
     * Prepare SQL and load one or more records.
     *
     * @return mixed
     */
    public function execute()
    {
        $select_sql = $this->getSelectSql();

        if ($this->loadByTypeField()) {
            $return_by = ConnectionInterface::RETURN_OBJECT_BY_FIELD;
            $return_by_value = 'type';
        } else {
            $return_by = ConnectionInterface::RETURN_OBJECT_BY_CLASS;
            $return_by_value = $this->type;
        }

        if ($this->hasContainer()) {
            return $this->connection->advancedExecute($select_sql, null, ConnectionInterface::LOAD_ALL_ROWS, $return_by, $return_by_value, [&$this->connection, &$this->pool, &$this->log], $this->getContainer());
        } else {
            return $this->connection->advancedExecute($select_sql, null, ConnectionInterface::LOAD_ALL_ROWS, $return_by, $return_by_value, [&$this->connection, &$this->pool, &$this->log]);
        }
    }

    // ---------------------------------------------------
    //  Utilities
    // ---------------------------------------------------

    /**
     * @var bool
     */
    private $load_by_type_field;

    /**
     * Check if we should load by type field or by type class.
     *
     * @return bool
     */
    private function loadByTypeField()
    {
        if ($this->load_by_type_field === null) {
            $this->load_by_type_field = in_array('type', $this->pool->getTypeFields($this->type));
        }

        return $this->load_by_type_field;
    }

    /**
     * Prepare select one or more rows query.
     *
     * @return string
     */
    private function getSelectSql()
    {
        return $this->getSelectFieldsSql($this->pool->getEscapedTypeFields($this->type));
    }

    /**
     * Return select ID-s SQL.
     *
     * @return string
     */
    private function getSelectIdsSql()
    {
        return $this->getSelectFieldsSql($this->getEscapedTableName() . '.`id`');
    }

    /**
     * Construct SELECT query for the given fields based on set criteria.
     *
     * @param  string $escaped_field_names
     * @return string
     */
    private function getSelectFieldsSql($escaped_field_names)
    {
        $result = "SELECT $escaped_field_names FROM " . $this->getEscapedTableName();

        if ($this->join) {
            $result .= " $this->join";
        }

        if ($where = $this->getWhere()) {
            $result .= " WHERE $where";
        }

        if ($this->order_by) {
            $result .= " ORDER BY $this->order_by";
        }

        if ($this->offset !== null && $this->limit !== null) {
            $result .= " LIMIT $this->offset, $this->limit";
        }

        return $result;
    }

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

    /**
     * @return string
     */
    private function getEscapedTableName()
    {
        if (empty($this->escaped_table_name)) {
            $this->escaped_table_name = $this->pool->getTypeTable($this->type, true);
        }

        return $this->escaped_table_name;
    }

    // ---------------------------------------------------
    //  Access to dependencies
    // ---------------------------------------------------

    /**
     * @return ConnectionInterface
     */
    protected function getConnection()
    {
        return $this->connection;
    }

    /**
     * @return PoolInterface
     */
    protected function getPool()
    {
        return $this->pool;
    }

    /**
     * @return LoggerInterface|null
     */
    protected function getLog()
    {
        return $this->log;
    }
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Adapter;

use Antares\Acl\Contracts\ModulesAdapter as ModulesAdapterContract;

class ModulesAdapter implements ModulesAdapterContract
{

    /**
     * fetch modules list
     *
     * @return type
     */
    public function modules()
    {

        $memory        = app('antares.memory');
        $configuration = $memory->make('component');
        $extensions    = $configuration->get('extensions.active');
        $coreActions   = $configuration->get('acl_antares.actions');

        $data = [
            [
                'name'        => 'antares',
                'namespace'   => 'antares',
                'full_name'   => 'Core Platform',
                'description' => 'Application engine',
                'actions'     => $coreActions
            ]
        ];

        foreach ($extensions as $extension) {
            $named   = app('antares.extension')->getAvailableExtensions()->findByName($extension['fullname']);
            $name    = str_replace(['component-', 'module-'], '', $extension['name']);
            $actions = $configuration->get("acl_antares/{$name}.actions");
            $data[]  = array_merge([
                'name'        => $name,
                'full_name'   => $named->getFriendlyName(),
                'description' => strip_tags($named->getPackage()->getDescription())], [
                'actions'   => $actions,
                'namespace' => "antares/{$name}"
            ]);
        }

        return $data;
    }

    /**
     * find smashed resource
     *
     * @param String $name
     * @param String $resource
     * @param array $item
     * @param String $controller
     * @param array $return
     * @return array
     */
    protected function smashResource($name, $resource, $item, $controller, &$return)
    {
        $pattern = "{$name}::{$resource}::";
        if (starts_with($item, $pattern)) {
            $id                                               = $this->collector->id($item);
            $actionForm                                       = preg_replace("/{$pattern}/", '', $item);
            $smashed                                          = explode('::', $actionForm);
            return $return[$resource][$controller][$smashed[0]][$id] = $smashed[1];
        }
    }

}


<?php

namespace Mamikon\RoleManager;

use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use Mamikon\RoleManager\Models\Permissions;
use Mamikon\RoleManager\Models\Roles;

/**
 * Class RoleManager
 *
 * @category Laravel_Package
 * @package  Mamikon\RoleManager
 * @author   Mamikon Arakelyan <m.araqelyan@gmail.com>
 * @license  https://github.com/mamikon/role-manager/blob/master/LICENSE.md MIT
 * @link     https://github.com/mamikon/role-manager
 */
class RoleManager
{
    /**
     * Define all permission and make usable from laravel application
     *
     * @return bool
     */
    public function defineAllPermissions()
    {
        foreach ($this->getPermissions() as $permission) {

            Gate::define(
                $permission->name,
                function ($user, ...$arguments) use ($permission) {
                    foreach ($permission->roles as $role) {
                        if ($role->belongsToUser($user)) {
                            if (!empty($permission->class)
                                AND !empty($permission->method)
                                AND class_exists($permission->class)
                            ) {
                                $container = resolve($permission->class);
                                if (method_exists($container, $permission->method)) {
                                    array_unshift($arguments, $user);
                                    return
                                        call_user_func_array(
                                            [$container, $permission->method],
                                            $arguments
                                        );
                                } else {
                                    return false;
                                }
                            }
                            return true;
                        }
                    }
                    return false;
                }
            );
        }
        return false;
    }

    /**
     * Assign Role to user
     *
     * @param int|User         $user User Instance or user id
     * @param int|string|Roles $role Role Instance, role name, or role id
     *
     * @return bool
     */
    public function assignRole($user, $role)
    {
        if (is_int($user) and !$user = User::where('id', $user)->first()) {
            return false;
        }
        if (is_int($role) and !$role = Roles::where('id', $role)->first()) {
            return false;
        }
        if (is_string($role) and !$role = Roles::where('name', $role)->first()) {
            return false;
        }
        if (!($user instanceof User) or !($role instanceof Roles)) {
            return false;
        }
        return $role->assignToUser($user);
    }

    /**
     * Remove Role from user
     *
     * @param int|User         $user User Instance or user id
     * @param int|string|Roles $role Role Instance, role name, or role id
     *
     * @return bool
     */
    public function removeRole($user, $role)
    {
        if (is_int($user) and !$user = User::where('id', $user)->first()) {
            return false;
        }
        if (is_int($role) and !$role = Roles::where('id', $role)->first()) {
            return false;
        }
        if (is_string($role) and !$role = Roles::where('name', $role)->first()) {
            return false;
        }
        if (!($user instanceof User) or !($role instanceof Roles)) {
            return false;
        }
        $role->users()->detach($user->id);
        return true;
    }

    /**
     * Get All permissions
     *
     * @return array|\Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getPermissions()
    {
        if (Schema::hasTable(config('roleManager.permissionsTable'))) {
            return Permissions::with('roles')->get();
        }
        return [];
    }

}


<?php
/*
 * Copyright (c) Atsuhiro Kubo <kubo@iteman.jp>,
 * All rights reserved.
 *
 * This file is part of PHPMentorsPageflowerBundle.
 *
 * This program and the accompanying materials are made available under
 * the terms of the BSD 2-Clause License which accompanies this
 * distribution, and is available at http://opensource.org/licenses/BSD-2-Clause
 */

namespace PHPMentors\PageflowerBundle\EventListener;

use PHPMentors\PageflowerBundle\Controller\ReflectionConversationalControllerRepository;
use PHPMentors\PageflowerBundle\Conversation\Conversation;
use PHPMentors\PageflowerBundle\Conversation\ConversationContext;
use PHPMentors\PageflowerBundle\Conversation\ConversationContextAwareInterface;
use PHPMentors\PageflowerBundle\Conversation\ConversationRepository;
use PHPMentors\PageflowerBundle\Conversation\EndableConversationSpecification;
use PHPMentors\PageflowerBundle\Pageflow\Pageflow;
use PHPMentors\PageflowerBundle\Pageflow\PageflowRepository;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Util\SecureRandomInterface;

class ConversationListener implements ConversationContextAwareInterface
{
    /**
     * @var ConversationContext
     */
    private $conversationContext;

    /**
     * @var ConversationRepository
     */
    private $conversationRepository;

    /**
     * @var PageflowRepository
     */
    private $pageflowRepository;

    /**
     * @var ReflectionConversationalControllerRepository
     */
    private $reflectionConversationalControllerRepository;

    /**
     * @var SecureRandomInterface
     */
    private $secureRandom;

    /**
     * @var EndableConversationSpecification
     *
     * @since Property available since Release 1.1.0
     */
    private $endableConversationSpecification;

    /**
     * @param ConversationRepository                       $conversationRepository
     * @param PageflowRepository                           $pageflowRepository
     * @param ReflectionConversationalControllerRepository $reflectionConversationalControllerRepository
     * @param SecureRandomInterface                        $secureRandom
     * @param EndableConversationSpecification             $endableConversationSpecification
     */
    public function __construct(ConversationRepository $conversationRepository, PageflowRepository $pageflowRepository, ReflectionConversationalControllerRepository $reflectionConversationalControllerRepository, SecureRandomInterface $secureRandom = null, EndableConversationSpecification $endableConversationSpecification)
    {
        $this->conversationRepository = $conversationRepository;
        $this->pageflowRepository = $pageflowRepository;
        $this->reflectionConversationalControllerRepository = $reflectionConversationalControllerRepository;
        $this->secureRandom = $secureRandom;
        $this->endableConversationSpecification = $endableConversationSpecification;
    }

    /**
     * {@inheritdoc}
     */
    public function setConversationContext(ConversationContext $conversationContext)
    {
        $this->conversationContext = $conversationContext;
    }

    /**
     * @param FilterControllerEvent $event
     *
     * @throws \UnexpectedValueException
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) {
            $controllerName = $event->getRequest()->attributes->get('_controller');
            $pageflowId = substr($controllerName, 0, strpos($controllerName, ':'));
            $pageflow = $this->pageflowRepository->findByPageflowId($pageflowId);
            if ($pageflow !== null) {
                list($conversationalController, $action) = $event->getController();

                $this->conversationRepository->setConversationCollection($event->getRequest()->getSession()->getConversationBag());

                if ($event->getRequest()->request->has($this->conversationContext->getConversationParameterName())) {
                    $conversationId = $event->getRequest()->request->get($this->conversationContext->getConversationParameterName());
                } elseif ($event->getRequest()->query->has($this->conversationContext->getConversationParameterName())) {
                    $conversationId = $event->getRequest()->query->get($this->conversationContext->getConversationParameterName());
                }

                if (isset($conversationId)) {
                    $conversation = $this->conversationRepository->findByConversationId($conversationId);
                }

                if (!isset($conversation)) {
                    $conversation = $this->createConversation($pageflow);
                    $conversation->start();

                    $reflectionConversationalController = $this->reflectionConversationalControllerRepository->findByClass(get_class($conversationalController));
                    if ($reflectionConversationalController === null) {
                        throw new \UnexpectedValueException(sprintf(
                            'ReflectionConversationalController object for controller "%s" is not found.',
                            get_class($conversationalController)
                        ));
                    }

                    foreach ($reflectionConversationalController->getInitMethods() as $initMethod) {
                        /* @var $initMethod \ReflectionMethod */
                        if (is_callable(array($conversationalController, $initMethod->getName()))) {
                            $initMethod->invoke($conversationalController);
                        } else {
                            throw new \UnexpectedValueException(sprintf(
                                'Init method "%s" for pageflow "%s" is not callable.',
                                get_class($conversationalController).'::'.$initMethod->getName(),
                                $pageflow->getPageflowId()
                            ));
                        }
                    }

                    $this->conversationRepository->add($conversation);
                }

                $conversation->increaseStepCount();

                if (!isset($reflectionConversationalController)) {
                    $reflectionConversationalController = $this->reflectionConversationalControllerRepository->findByClass(get_class($conversationalController));
                    if ($reflectionConversationalController === null) {
                        throw new \UnexpectedValueException(sprintf(
                            'ReflectionConversationalController object for controller "%s" is not found.',
                            get_class($conversationalController)
                        ));
                    }
                }

                if (!in_array($conversation->getCurrentPage()->getPageId(), $reflectionConversationalController->getAcceptablePages($action))) {
                    throw new AccessDeniedHttpException(sprintf(
                        'Controller "%s" should be accessed when the current page is one of [ %s ], the actual page is "%s".',
                        get_class($conversationalController).'::'.$action,
                        implode(', ', $reflectionConversationalController->getAcceptablePages($action)),
                        $conversation->getCurrentPage()->getPageId()
                    ));
                }

                foreach ($reflectionConversationalController->getStatefulProperties() as $statefulProperty) {
                    /* @var $statefulProperty \ReflectionProperty */
                    if ($conversation->attributes->has($statefulProperty->getName())) {
                        if (!$statefulProperty->isPublic()) {
                            $statefulProperty->setAccessible(true);
                        }

                        $statefulProperty->setValue($conversationalController, $conversation->attributes->get($statefulProperty->getName()));

                        if (!$statefulProperty->isPublic()) {
                            $statefulProperty->setAccessible(false);
                        }
                    }
                }

                $this->conversationContext->setConversation($conversation);
                $this->conversationContext->setConversationalController($conversationalController);
                $this->conversationContext->setReflectionConversationalController($reflectionConversationalController);
            }
        }
    }

    /**
     * @param FilterResponseEvent $event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) {
            $conversation = $this->conversationContext->getConversation();
            if ($conversation !== null) {
                if ($this->endableConversationSpecification->isSatisfiedBy($conversation)) {
                    $conversation->end();
                    $this->conversationRepository->remove($conversation);

                    $conversationalController = $this->conversationContext->getConversationalController();
                    $reflectionConversationalController = $this->conversationContext->getReflectionConversationalController();
                    if ($conversationalController !== null && $reflectionConversationalController !== null) {
                        foreach ($reflectionConversationalController->getStatefulProperties() as $statefulProperty) { /* @var $statefulProperty \ReflectionProperty */
                            if ($conversation->attributes->has($statefulProperty->getName())) {
                                $conversation->attributes->remove($statefulProperty->getName());
                            }
                        }
                    }
                } else {
                    if ($conversation->getCurrentPage()->isEndPage()) {
                        $conversation->logStepCountOnEndPage();
                    }

                    $conversationalController = $this->conversationContext->getConversationalController();
                    $reflectionConversationalController = $this->conversationContext->getReflectionConversationalController();
                    if ($conversationalController !== null && $reflectionConversationalController !== null) {
                        foreach ($reflectionConversationalController->getStatefulProperties() as $statefulProperty) { /* @var $statefulProperty \ReflectionProperty */
                            if (!$statefulProperty->isPublic()) {
                                $statefulProperty->setAccessible(true);
                            }

                            $conversation->attributes->set($statefulProperty->getName(), $statefulProperty->getValue($conversationalController));

                            if (!$statefulProperty->isPublic()) {
                                $statefulProperty->setAccessible(false);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @param Pageflow $pageflow
     *
     * @return Conversation
     */
    private function createConversation(Pageflow $pageflow)
    {
        return new Conversation($this->generateConversationId(), $this->createPageflow($pageflow));
    }

    /**
     * @param Pageflow $pageflow
     *
     * @return Pageflow
     */
    private function createPageflow(Pageflow $pageflow)
    {
        return unserialize(serialize($pageflow));
    }

    /**
     * @return string
     */
    private function generateConversationId()
    {
        return sha1($this->secureRandom === null ? random_bytes(24) : $this->secureRandom->nextBytes(24));
    }
}


<?php
/*
 * Copyright (c) Atsuhiro Kubo <kubo@iteman.jp>,
 * All rights reserved.
 *
 * This file is part of PHPMentorsPageflowerBundle.
 *
 * This program and the accompanying materials are made available under
 * the terms of the BSD 2-Clause License which accompanies this
 * distribution, and is available at http://opensource.org/licenses/BSD-2-Clause
 */

namespace PHPMentors\PageflowerBundle\DependencyInjection\Compiler;

use PHPMentors\PageflowerBundle\Generator\PageflowDefinitionGenerator;
use PHPMentors\PageflowerBundle\Generator\ReflectionConversationalControllerDefinitionGenerator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class GeneratePageflowDefinitionsPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        foreach ($container->findTaggedServiceIds('phpmentors_pageflower.pageflow') as $controllerServiceId => $attribute) {
            $controllerClass = new \ReflectionClass($container->getParameterBag()->resolveValue($container->getDefinition($controllerServiceId)->getClass()));
            if (!$controllerClass->implementsInterface('PHPMentors\PageflowerBundle\Controller\ConversationalControllerInterface')) {
                throw new \LogicException(sprintf(
                    'The controller "%s" must implement "%s".',
                    $controllerClass->getName(),
                    'PHPMentors\PageflowerBundle\Controller\ConversationalControllerInterface'
                ));
            }

            $pages = array();
            $pageflowDefinitionGenerator = new PageflowDefinitionGenerator($container, $controllerClass, $controllerServiceId, $container->get('annotation_reader'), $pages);
            $pageflowDefinitionGenerator->generate();

            $reflectionConversationalControllerDefinitionGenerator = new ReflectionConversationalControllerDefinitionGenerator($container, $controllerClass, $controllerServiceId, $container->get('annotation_reader'), $pages);
            $reflectionConversationalControllerDefinitionGenerator->generate();
        }
    }
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Processor;

use Antares\Acl\Http\Presenters\Role as RolePresenter;
use Antares\Contracts\Foundation\Foundation;
use Antares\Acl\Contracts\ModulesAdapter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;
use Antares\Model\Role as Eloquent;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use Antares\Model\Action;
use Antares\Support\Str;
use Exception;

class Role extends Processor
{

    /**
     * control scripts config container
     *
     * @var array
     */
    protected $config;

    /**
     * memory provider
     *
     * @var \Antares\Form\Provider\Provider
     */
    protected $collector;

    /**
     * Setup a new processor instance.
     *
     * @param  \Antares\Acl\Http\Presenters\Role  $presenter
     * @param  \Antares\Contracts\Foundation\Foundation  $foundation
     */
    public function __construct(RolePresenter $presenter, Foundation $foundation)
    {
        $this->presenter  = $presenter;
        $this->foundation = $foundation;
        $this->model      = $foundation->make('antares.role');
    }

    /**
     * view list action
     *
     * @return \Illuminate\Http\Response|\Illuminate\View\View
     */
    public function index()
    {
        return $this->presenter->table();
    }

    /**
     * View create a role page.
     *
     * @param  object  $listener
     *
     * @return mixed
     */
    public function create($listener)
    {

        $eloquent = $this->model;
        $form     = $this->presenter->form($eloquent);
        return $listener->createSucceed(compact('eloquent', 'form'));
    }

    /**
     * View edit a role page.
     *
     * @param  object  $listener
     * @param  string|int  $id
     *
     * @return mixed
     */
    public function edit($listener, $id)
    {
        $eloquent = $this->model->findOrFail($id);
        $data     = $this->presenter->edit($eloquent);
        return $listener->editSucceed($data);
    }

    /**
     * Store a role.
     *
     * @param  object  $listener
     * @param  array   $input
     *
     * @return mixed
     */
    public function store($listener, array $input)
    {
        $role = $this->model;
        $form = $this->presenter->form($role);
        if (!$form->isValid()) {
            return $listener->storeValidationFailed($form->getMessageBag());
        }
        try {
            $this->saving($role, $input, 'create');
        } catch (Exception $e) {
            Log::warning($e);
            return $listener->storeFailed(['error' => $e->getMessage()]);
        }
        return $listener->storeSucceed($role);
    }

    /**
     * Update a role.
     *
     * @param  object  $listener
     * @param  array   $input
     * @param  int     $id
     *
     * @return mixed
     */
    public function update($listener, array $input, $id)
    {

        if ((int) $id !== (int) $input['id']) {
            return $listener->userVerificationFailed();
        }
        $role = $this->model->findOrFail($id);
        $form = $this->presenter->form($role);
        if (!$form->isValid()) {
            return $listener->updateValidationFailed($form->getMessageBag(), $id);
        }

        try {
            $this->saving($role, $input, 'update');
        } catch (Exception $e) {

            Log::warning($e);
            return $listener->updateFailed(['error' => $e->getMessage()]);
        }

        return $listener->updateSucceed();
    }

    /**
     * Delete a role.
     *
     * @param  object  $listener
     * @param  string|int  $id
     *
     * @return mixed
     */
    public function destroy($listener, $id)
    {
        $role = $this->model->findOrFail($id);
        try {
            if ($role->users->count() > 0) {
                throw new Exception('Unable to delete group with assigned users.');
            }
            DB::transaction(function () use ($role) {
                $role->delete();
            });
        } catch (Exception $e) {
            Log::warning($e);
            return $listener->destroyFailed(['error' => $e->getMessage()]);
        }

        return $listener->destroySucceed($role);
    }

    /**
     * Save the role.
     *
     * @param  \Antares\Model\Role  $role
     * @param  array  $input
     * @param  string  $type
     *
     * @return bool
     */
    protected function saving(Eloquent $role, $input = [], $type = 'create')
    {
        $beforeEvent = ($type === 'create' ? 'creating' : 'updating');
        $afterEvent  = ($type === 'create' ? 'created' : 'updated');

        $name = $input['name'];
        $role->fill([
            'name'        => snake_case($name, '-'),
            'full_name'   => $name,
            'area'        => array_get($input, 'area'),
            'description' => $input['description']
        ]);
        if (!$role->exists && isset($input['roles'])) {
            $role->parent_id = $input['roles'];
        }
        $this->fireEvent($beforeEvent, [$role]);
        $this->fireEvent('saving', [$role]);
        DB::transaction(function() use($role, $input) {
            $role->save();
            $this->import($input, $role);
        });
        $this->fireEvent($afterEvent, [$role]);
        $this->fireEvent('saved', [$role]);

        return true;
    }

    /**
     * import permissions when copy
     *
     * @param array $input
     * @param Model $role
     */
    protected function import(array $input, Model $role)
    {
        if (isset($input['import']) && !is_null($from = $input['roles'])) {
            $permission = $this->foundation->make('antares.auth.permission');

            $permissions = $permission->where('role_id', $from)->get();

            $permissions->each(function(Model $model) use($permission, $role) {
                $attributes = $model->getAttributes();
                $insert     = array_except($attributes, ['id', 'role_id']) + ['role_id' => $role->id];
                $permission->newInstance($insert)->save();
            });
        }
        return true;
    }

    /**
     * Fire Event related to eloquent process.
     *
     * @param  string  $type
     * @param  array   $parameters
     *
     * @return void
     */
    protected function fireEvent($type, array $parameters = [])
    {
        Event::fire("antares.control.{$type}: roles", $parameters);
    }

    /**
     * Acl rules form
     *
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function acl($id)
    {
        $eloquent = $this->model->findOrFail($id);
        return $this->presenter->acl($eloquent);
    }

    /**
     * Modules structure as tree
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function tree($id)
    {
        $eloquent  = $this->model->findOrFail($id);
        $instances = app('antares.acl')->all();
        $return    = [
            'name'    => 'Root',
            'open'    => true,
            'checked' => false,
        ];
        $modules   = app(ModulesAdapter::class)->modules();
        foreach ($modules as $module) {
            $item        = [
                'saveName'      => array_get($module, 'full_name', '---'),
                'name'          => array_get($module, 'full_name', '---'),
                'indeterminate' => false,
                'checked'       => false,
                'open'          => true,
            ];
            if (!is_null($description = array_get($module, 'description'))) {
                array_set($item, 'description', $description);
            }
            $actions = array_get($module, 'actions', []);
            if (empty($actions) or ! isset($instances[$module['namespace']])) {
                continue;
            }
            $children = [];
            $checked  = true;
            $keys     = array_keys($actions);

            $actionsWithoutCategories = Action::query()->whereIn('id', $keys)->whereNull('category_id')->get();

            foreach ($actionsWithoutCategories as $action) {
                $checked    = $instances[$module['namespace']]->check($eloquent->name, $action->name);
                $key        = array_search($action->name, $actions);
                $children[] = [
                    'saveName'      => "acl[{$id}][{$key}]",
                    'name'          => Str::humanize($action->name),
                    'indeterminate' => false,
                    'checked'       => $checked,
                    'value'         => $action->name,
                    'description'   => $action->description
                ];
                if (!$checked) {
                    $checked = false;
                }
            }
            $actionsWithCategories = \Antares\Model\ActionCategories::query()->with(['actions' => function($query) use($keys) {
                            $query->whereIn('id', $keys);
                        }])->get();

            foreach ($actionsWithCategories as $category) {
                if ($category->actions->isEmpty()) {
                    continue;
                }
                $subchildren = [];
                foreach ($category->actions as $action) {
                    $checked       = $instances[$module['namespace']]->check($eloquent->name, $action->name);
                    $key           = array_search($action->name, $actions);
                    $subchildren[] = [
                        'saveName'      => "acl[{$id}][{$key}]",
                        'name'          => Str::humanize($action->name),
                        'indeterminate' => false,
                        'checked'       => $checked,
                        'value'         => $action->name,
                        'description'   => $action->description
                    ];
                }
                $children[] = [
                    'name'          => $category->name,
                    'saveName'      => "acl_category_" . $category->id,
                    'indeterminate' => false,
                    'checked'       => true,
                    'children'      => $subchildren,
                    'open'          => true
                ];
            }

            $item['checked'] = $checked;

            $item['children']     = $children;
            $return['children'][] = $item;
        }
        return new JsonResponse(['tree' => $return]);
    }

}


<?php

namespace Adback\ApiClient\Driver;

/**
 * Class SqlScriptCache
 */
abstract class SqlScriptCache
{
    const ADBACK_ANALYTICS_SCRIPT = 'adback_analytics_script';
    const ADBACK_ANALYTICS_URL = 'adback_analytics_url';
    const ADBACK_ANALYTICS_CODE = 'adback_analytics_code';
    const ADBACK_MESSAGE_SCRIPT = 'adback_message_script';
    const ADBACK_MESSAGE_URL = 'adback_message_url';
    const ADBACK_MESSAGE_CODE = 'adback_message_code';
    const ADBACK_AUTOPROMO_BANNER_SCRIPT = 'adback_autopromo_banner_script';
    const ADBACK_AUTOPROMO_BANNER_URL = 'adback_autopromo_banner_url';
    const ADBACK_AUTOPROMO_BANNER_CODE = 'adback_autopromo_banner_code';
    const ADBACK_PRODUCT_SCRIPT = 'adback_product_script';
    const ADBACK_PRODUCT_URL = 'adback_product_url';
    const ADBACK_PRODUCT_CODE = 'adback_product_code';
    const ADBACK_IAB_BANNER_SCRIPT = 'adback_iab_banner_script';
    const ADBACK_IAB_BANNER_CODE = 'adback_iab_banner_code';
    const ADBACK_IAB_BANNER_URL = 'adback_iab_banner_url';

    /**
     * @return bool
     */
    public function isAnalyticsConfigured()
    {
        return null != $this->get(self::ADBACK_ANALYTICS_SCRIPT);
    }

    /**
     * @param string $domain
     */
    public function setAnalyticsUrl($domain)
    {
        $this->set(self::ADBACK_ANALYTICS_URL, $domain);
    }

    /**
     * @return string
     */
    public function getAnalyticsUrl()
    {
        return $this->get(self::ADBACK_ANALYTICS_URL);
    }

    /**
     * @param string $script
     */
    public function setAnalyticsScript($script)
    {
        $this->set(self::ADBACK_ANALYTICS_SCRIPT, $script);
    }

    /**
     * @return string
     */
    public function getAnalyticsScript()
    {
        return $this->get(self::ADBACK_ANALYTICS_SCRIPT);
    }

    /**
     * @param string $code
     */
    public function setAnalyticsCode($code)
    {
        $this->set(self::ADBACK_ANALYTICS_CODE, $code);
    }

    /**
     * @return string
     */
    public function getAnalyticsCode()
    {
        return $this->get(self::ADBACK_ANALYTICS_CODE);
    }

    /**
     * @return bool
     */
    public function isMessageConfigured()
    {
        return null != $this->get(self::ADBACK_MESSAGE_SCRIPT);
    }

    /**
     * @param string $domain
     */
    public function setMessageUrl($domain)
    {
        $this->set(self::ADBACK_MESSAGE_URL, $domain);
    }

    /**
     * @return string
     */
    public function getMessageUrl()
    {
        return $this->get(self::ADBACK_MESSAGE_URL);
    }

    /**
     * @param string $script
     */
    public function setMessageScript($script)
    {
        $this->set(self::ADBACK_MESSAGE_SCRIPT, $script);
    }

    /**
     * @return string
     */
    public function getMessageScript()
    {
        return $this->get(self::ADBACK_MESSAGE_SCRIPT);
    }

    /**
     * @param string $code
     */
    public function setMessageCode($code)
    {
        $this->set(self::ADBACK_MESSAGE_CODE, $code);
    }

    /**
     * @return string
     */
    public function getMessageCode()
    {
        return $this->get(self::ADBACK_MESSAGE_CODE);
    }

    /**
     * @return bool
     */
    public function isAutopromoBannerConfigured()
    {
        return null != $this->get(self::ADBACK_AUTOPROMO_BANNER_SCRIPT);
    }

    /**
     * @param string $domain
     */
    public function setAutopromoBannerUrl($domain)
    {
        $this->set(self::ADBACK_AUTOPROMO_BANNER_URL, $domain);
    }

    /**
     * @return string
     */
    public function getAutopromoBannerUrl()
    {
        return $this->get(self::ADBACK_AUTOPROMO_BANNER_URL);
    }

    /**
     * @param string $script
     */
    public function setAutopromoBannerScript($script)
    {
        $this->set(self::ADBACK_AUTOPROMO_BANNER_SCRIPT, $script);
    }

    /**
     * @return string
     */
    public function getAutopromoBannerScript()
    {
        return $this->get(self::ADBACK_AUTOPROMO_BANNER_SCRIPT);
    }

    /**
     * @param string $code
     */
    public function setAutopromoBannerCode($code)
    {
        $this->set(self::ADBACK_AUTOPROMO_BANNER_CODE, $code);
    }

    /**
     * @return string
     */
    public function getAutopromoBannerCode()
    {
        return $this->get(self::ADBACK_AUTOPROMO_BANNER_CODE);
    }

    /**
     * @return bool
     */
    public function isIabBannerConfigured()
    {
        return null != $this->get(self::ADBACK_IAB_BANNER_SCRIPT);
    }

    /**
     * @param string $script
     */
    public function setIabBannerScript($script)
    {
        $this->set(self::ADBACK_IAB_BANNER_SCRIPT, $script);
    }

    /**
     * @return string
     */
    public function getIabBannerScript()
    {
        return $this->get(self::ADBACK_IAB_BANNER_SCRIPT);
    }

    /**
     * @param string $code
     */
    public function setIabBannerCode($code)
    {
        $this->set(self::ADBACK_IAB_BANNER_CODE, $code);
    }

    /**
     * @return string
     */
    public function getIabBannerCode()
    {
        return $this->get(self::ADBACK_IAB_BANNER_CODE);
    }

    /**
     * @param string $domain
     */
    public function setIabBannerUrl($domain)
    {
        $this->set(self::ADBACK_IAB_BANNER_URL, $domain);
    }

    /**
     * @return string
     */
    public function getIabBannerUrl()
    {
        return $this->get(self::ADBACK_IAB_BANNER_URL);
    }

    /**
     * @return bool
     */
    public function isProductConfigured()
    {
        return null != $this->get(self::ADBACK_PRODUCT_SCRIPT);
    }

    /**
     * @param string $domain
     */
    public function setProductUrl($domain)
    {
        $this->set(self::ADBACK_PRODUCT_URL, $domain);
    }

    /**
     * @return string
     */
    public function getProductUrl()
    {
        return $this->get(self::ADBACK_PRODUCT_URL);
    }

    /**
     * @param string $script
     */
    public function setProductScript($script)
    {
        $this->set(self::ADBACK_PRODUCT_SCRIPT, $script);
    }

    /**
     * @return string
     */
    public function getProductScript()
    {
        return $this->get(self::ADBACK_PRODUCT_SCRIPT);
    }

    /**
     * @param string $code
     */
    public function setProductCode($code)
    {
        $this->set(self::ADBACK_PRODUCT_CODE, $code);
    }

    /**
     * @return string
     */
    public function getProductCode()
    {
        return $this->get(self::ADBACK_PRODUCT_CODE);
    }

    /**
     * Clear analytics data
     */
    public function clearAnalyticsData()
    {
        $this->clear(self::ADBACK_ANALYTICS_SCRIPT);
        $this->clear(self::ADBACK_ANALYTICS_URL);
        $this->clear(self::ADBACK_ANALYTICS_CODE);
    }

    /**
     * Clear message data
     */
    public function clearMessageData()
    {
        $this->clear(self::ADBACK_MESSAGE_SCRIPT);
        $this->clear(self::ADBACK_MESSAGE_URL);
        $this->clear(self::ADBACK_MESSAGE_CODE);
    }

    /**
     * Clear autopromo banner data
     */
    public function clearAutopromoBannerData()
    {
        $this->clear(self::ADBACK_AUTOPROMO_BANNER_SCRIPT);
        $this->clear(self::ADBACK_AUTOPROMO_BANNER_URL);
        $this->clear(self::ADBACK_AUTOPROMO_BANNER_CODE);
    }

    /**
     * Clear autopromo banner data
     */
    public function clearProductData()
    {
        $this->clear(self::ADBACK_PRODUCT_SCRIPT);
        $this->clear(self::ADBACK_PRODUCT_URL);
        $this->clear(self::ADBACK_PRODUCT_CODE);
    }

    /**
     * Clear autopromo banner data
     */
    public function clearIabBannerData()
    {
        $this->clear(self::ADBACK_IAB_BANNER_SCRIPT);
        $this->clear(self::ADBACK_IAB_BANNER_CODE);
    }

    /**
     * @param string $key
     *
     * @return string|null
     */
    abstract protected function get($key);

    /**
     * @param string $key
     * @param string $value
     */
    abstract protected function set($key, $value);

    /**
     * @param string $key
     */
    abstract protected function clear($key);
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Http\Handlers;

use Antares\Foundation\Http\Composers\LeftPane;

class ModulesPane extends LeftPane
{

    /**
     * @var ModulesPane
     */
    private static $oInstance = false;

    /**
     * @return ModulesPane
     */
    public static function getInstance()
    {
        if (self::$oInstance == false) {
            self::$oInstance = new self();
        }
        return self::$oInstance;
    }

    /**
     * make resource instance of left pane
     */
    public function make()
    {
        $extensions = app('antares.memory')->make('component')->get('extensions.active');
        $data       = [
            [
                'name'      => 'core_platform',
                'full_name' => 'Core Platform',
                'handles'   => handles('antares::acl/acl')
            ]
        ];
        foreach ($extensions as $extension) {
            $name = $extension['name'];
            if ($name == 'control') {
                continue;
            }
            $data[] = array_merge($extension, ['handles' => handles('antares::acl/acl', ['name' => "antares/{$name}"])]);
        }
        $this->widget->make('pane.left')->add('modules')->content(view("antares/acl::partial._modules", ['data' => $data]));
    }

}


<?php
/*
 * This file is part of the prooph/ProophEventStoreModule.
 * (c) Alexander Miertsch <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 02.06.14 - 22:05
 */

namespace ProophEventStoreModule\Factory;

use Codeliner\ArrayReader\ArrayReader;
use Prooph\EventStore\Configuration\Configuration;
use Prooph\EventStore\Configuration\Exception\ConfigurationException;
use Prooph\EventStore\EventStore;
use Prooph\EventStore\Feature\FeatureManager;
use Zend\ServiceManager\Config;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Class EventStoreFactory
 *
 * @package src\ProophEventStoreModule\Service
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
class EventStoreFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @throws \Prooph\EventStore\Configuration\Exception\ConfigurationException
     * @return EventStore
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get("configuration");

        if (! isset($config['prooph.event_store'])) {
            throw ConfigurationException::configurationError("Missing key prooph.event_store in application configuration");
        }

        $config = $config['prooph.event_store'];

        if (! isset($config['adapter'])) {
            throw ConfigurationException::configurationError("Missing adapter configuration in prooph.event_store configuration");
        }

        $adapterConfig = $config['adapter'];

        $configReader = new ArrayReader($adapterConfig);

        $adapterType    = $configReader->stringValue("type");
        $adapterOptions = $configReader->arrayValue("options");

        if ( $adapterType == 'Prooph\EventStore\Adapter\Zf2\Zf2EventStoreAdapter'
            && isset($adapterOptions['zend_db_adapter'])
            && is_string($adapterOptions['zend_db_adapter'])) {
            $config['adapter']['options']['zend_db_adapter'] = $serviceLocator->get($adapterOptions['zend_db_adapter']);
        }

        $featureManagerConfig = null;

        if (isset($config['feature_manager'])) {
            $featureManagerConfig = new Config($config['feature_manager']);
            unset($config['feature_manager']);
        }

        $esConfiguration = new Configuration($config);

        $featureManager = new FeatureManager($featureManagerConfig);

        $featureManager->setServiceLocator($serviceLocator);

        $esConfiguration->setFeatureManager($featureManager);

        return new EventStore($esConfiguration);
    }
}


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePermissionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(
            config('roleManager.permissionsTable'),
            function (Blueprint $table) {
                $table->increments('id');
                $table->char('name', 255)->unique();
                $table->text('description')->nullable();
                $table->text('class')->nullable();
                $table->text('method')->nullable();
                $table->timestamps();
            }
        );
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(config('roleManager.permissionsTable'));
    }
}


<?php
/*
 * This file is part of the prooph/ProophEventStoreModule.
 * (c) Alexander Miertsch <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 03.09.14 - 21:58
 */

namespace ProophEventStoreModule\Factory;

use Prooph\EventStore\Stream\AggregateTypeStreamStrategy;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class AggregateTypeStreamStrategyFactory implements FactoryInterface
{

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $aggregateTypeStreamMap = array();

        if ($serviceLocator->has('configuration')) {
            $config = $serviceLocator->get('configuration');

            if (isset($config['prooph.event_store']) && isset($config['prooph.event_store']['aggregate_type_stream_map'])) {
                $aggregateTypeStreamMap = $config['prooph.event_store']['aggregate_type_stream_map'];
            }
        }

        return new AggregateTypeStreamStrategy($serviceLocator->get('prooph.event_store'), $aggregateTypeStreamMap);
    }
}


<?php

namespace Mamikon\RoleManager\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Mamikon\RoleManager\Models\Permissions;
use Mamikon\RoleManager\Models\Roles;
use Mamikon\RoleManager\Requests\RoleRequest;

/**
 * Class RoleController
 *
 * @category Laravel_Package
 * @package  Mamikon\RoleManager
 * @author   Mamikon Arakelyan <m.araqelyan@gmail.com>
 * @license  https://github.com/mamikon/role-manager/blob/master/LICENSE.md MIT
 * @link     https://github.com/mamikon/role-manager
 */
class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('view_role');
        if (!empty($request->term)) {
            $term = trim($request->term);
            $roles = Roles::where('name', 'like', '%' . $term . '%')
                ->orWhere('description', 'like', '%' . $term . '%')
                ->paginate(config('roleManager.rolesPerPage'));

        } else {
            $roles = Roles::paginate(config('roleManager.rolesPerPage'));
        }
        return view('RoleManager::role.index', ['roles' => $roles]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create_role');

        return view(
            'RoleManager::role.create',
            ['permissions' => Permissions::all()]
        );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request|RoleRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(RoleRequest $request)
    {
        $this->authorize('create_role');

        $role = Roles::create($request->all());
        if (!empty($request->permission) AND is_array($request->permission)) {
            foreach ($request->permission as $permission) {
                $role->permissions()->attach($permission);
            }
        }
        $request->session()->flash('message', 'Role Successfully Created');
        return redirect()->route('RoleManager::role.edit', $role->id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Roles $role
     *
     * @return \Illuminate\Http\Response
     */
    public function edit(Roles $role)
    {
        $this->authorize('edit_role');

        $valueList = $role->permissions()->get()->pluck('id')->toArray();
        return view(
            'RoleManager::role.edit',
            ['role' => $role, 'permissions' => Permissions::all(),
                'valueList' => $valueList]
        );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request|RoleRequest $request
     * @param int                 $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(RoleRequest $request, $id)
    {
        $this->authorize('edit_role');

        $role = Roles::where('id', $id)->firstOrFail();
        $role->update($request->all());
        if (!empty($request->permission) AND is_array($request->permission)) {
            $role->permissions()->sync($request->permission);

        } else {
            $role->permissions()->detach();
        }
        $request->session()->flash('message', 'Role Updated Successfully');
        return redirect()->route('RoleManager::role.edit', $role->id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authorize('delete_role');

        Roles::where('id', $id)->delete();
        session()->flash('message', 'Role Deleted Successfully');
        session()->flash('message-status', 'alert-info');
        return redirect()->route('RoleManager::role.index');
    }
}


<?php

namespace Adback\ApiClient\Query;

use Adback\ApiClient\Client\Client;
use Adback\ApiClient\Driver\ScriptCacheInterface;

/**
 * Class FullScriptQuery
 */
class FullScriptQuery implements QueryInterface
{
    protected $cache;
    protected $token;
    protected $apiUrl;
    protected $client;
    protected $scriptUrl;

    /**
     * @param Client               $client
     * @param ScriptCacheInterface $cache
     * @param string               $token
     * @param string               $apiUrl
     * @param string               $scriptUrl
     */
    public function __construct(Client $client, ScriptCacheInterface $cache, $token, $apiUrl = 'https://www.adback.co/api', $scriptUrl = 'script/me/full')
    {
        $this->cache = $cache;
        $this->token = $token;
        $this->apiUrl = $apiUrl;
        $this->client = $client;
        $this->scriptUrl = $scriptUrl;
    }

    /**
     * Get the script info and store them
     */
    public function execute()
    {
        $url = sprintf('%s/%s?_format=json&access_token=%s',
            $this->apiUrl,
            $this->scriptUrl,
            $this->token
        );

        $response = $this->client->get($url);

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

        $fullScriptFacade = json_decode($response->getBody(), true);
        $types = [
            'analytics' => 'Analytics',
            'message' => 'Message',
            'product' => 'Product',
            'banner' => 'AutopromoBanner',
            'iab_banner' => 'IabBanner',
        ];

        foreach ($types as $type => $element) {
            if (array_key_exists($type, $fullScriptFacade['script_codes'])) {
                $scriptSetter = 'set' . $element . 'Script';
                $codeSetter = 'set'. $element . 'Code';
                $this->cache->$scriptSetter($fullScriptFacade['script_codes'][$type]['script_name']);
                $this->cache->$codeSetter($fullScriptFacade['script_codes'][$type]['code']);
            } else {
                $clearer = 'clear' . $element . 'Data';
                $this->cache->$clearer();
            }
        }
    }
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Http\Datatables;

use Antares\Acl\Http\Filter\GroupsFilter;
use Antares\Datatables\Services\DataTable;
use Antares\Support\Facades\Foundation;
use Illuminate\Support\Facades\DB;
use Antares\Model\User;

class Administrators extends DataTable
{

    /**
     * items per page
     *
     * @var mixed
     */
    public $perPage = 25;

    /**
     * container with filters
     *
     * @var array
     */
    protected $filters = [
        GroupsFilter::class
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        $builder = Foundation::make('antares.user')
                ->select(['tbl_users.id', 'tbl_users.firstname', 'tbl_users.lastname', 'tbl_users.email', 'tbl_users.created_at', 'tbl_users.status'])
                ->whereNull('tbl_users.deleted_at');
        if (config('antares/acl::allow_register_with_other_roles')) {
            $builder->administrators();
        } else {
            $builder->withoutGlobalScopes()->with('roles')->whereNotNull('tbl_users.id')->whereHas('roles', function ($query) {
                $query->whereIn('tbl_roles.id', user()->roles->pluck('id')->toArray());
            });
        }

        if (!request()->ajax()) {
            $builder->where('tbl_users.status', 1);
        } else {
            $columns = request('columns');
            $status  = null;
            array_walk($columns, function($item, $index ) use(&$status) {
                if (array_get($item, 'data') == 'status') {
                    $status = array_get($item, 'search.value');
                }
            });

            if ($status == "") {
                $builder->where('tbl_users.status', 1);
            }
        }

        return $builder;
    }

    /**
     * {@inheritdoc}
     */
    public function ajax()
    {
        $acl            = app('antares.acl')->make('antares/acl');
        $canUpdateUser  = $acl->can('user-update');
        $canDeleteUser  = $acl->can('user-delete');
        $canLoginAsUser = $acl->can('login-as-user');

        return $this->prepare()
                        ->filter(function($query) {
                            $request = app('request');
                            $keyword = array_get($request->get('search'), 'value');
                            if (is_null($keyword) or ! strlen($keyword)) {
                                return;
                            }
                            switch ($keyword) {
                                case 'active':
                                    $query->where('tbl_users.status', 1);
                                    break;
                                case 'archived':
                                    $query->where('tbl_users.status', 0);
                                    break;
                                default:
                                    $query
                                    ->leftJoin('tbl_user_role', 'tbl_users.id', '=', 'tbl_user_role.user_id')
                                    ->leftJoin('tbl_roles', 'tbl_user_role.role_id', '=', 'tbl_roles.id')
                                    ->whereRaw("(tbl_users.firstname like '%$keyword%'  or tbl_users.lastname like '%$keyword%' or tbl_users.email like '%$keyword%' or tbl_roles.full_name like '%$keyword%')");
                                    break;
                            }
                        })
                        ->filterColumn('status', function ($query, $keyword) {
                            if ($keyword == 'all') {
                                $query->whereIn('tbl_users.status', [0, 1]);
                            } else {
                                $query->where('tbl_users.status', $keyword);
                            }
                        })
                        ->editColumn('status', function ($model) {
                            return ((int) $model->status) ? 'ACTIVE' : 'Disabled';
                        })
                        ->editColumn('email', $this->getUserEmail($eloquent = null))
                        ->editColumn('role', $this->userRoles($eloquent = null))
                        ->editColumn('firstname', function($eloquent = null) {
                            return strlen($eloquent->firstname) <= 0 ? '---' : $eloquent->firstname;
                        })
                        ->editColumn('lastname', function($eloquent = null) {
                            return strlen($eloquent->lastname) <= 0 ? '---' : $eloquent->lastname;
                        })
                        ->editColumn('created_at', function ($model) {
                            return format_x_days($model->created_at);
                        })
                        ->addColumn('action', $this->getActionsColumn($canUpdateUser, $canDeleteUser, $canLoginAsUser))
                        ->make(true);
    }

    /**
     * {@inheritdoc}
     */
    public function html()
    {
        if (!app('antares.acl')->make('antares/acl')->can('roles-list')) {
            $this->filters = [];
        }
        return $this
                        ->setName('Administrators List')
                        ->addColumn(['data' => 'id', 'name' => 'id', 'title' => trans('antares/foundation::label.users.id')])
                        ->addColumn(['data' => 'firstname', 'name' => 'firstname', 'title' => trans('antares/foundation::label.users.firstname'), 'className' => 'bolded'])
                        ->addColumn(['data' => 'lastname', 'name' => 'lastname', 'title' => trans('antares/foundation::label.users.lastname'), 'className' => 'bolded'])
                        ->addColumn(['data' => 'email', 'name' => 'email', 'title' => trans('antares/foundation::label.users.email'), 'className' => 'bolded'])
                        ->addColumn(['data' => 'role', 'name' => 'role', 'title' => trans('antares/foundation::label.users.role')])
                        ->addColumn(['data' => 'created_at', 'name' => 'created_at', 'title' => trans('antares/foundation::label.users.created_at')])
                        ->addColumn(['data' => 'status', 'name' => 'status', 'title' => trans('antares/foundation::label.users.status')])
                        ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false])
                        ->setDeferedData()
                        ->addGroupSelect($this->statuses(), 6, 'all');
    }

    /**
     * Scopes roles by configuration
     *
     * @param \Illuminate\Database\Query\Builder $builder
     * @return \Illuminate\Database\Query\Builder
     */
    protected function scopeRoles(&$builder)
    {
        return (config('antares/acl::allow_register_with_other_roles')) ? $builder->administrators() :
                $builder->with('roles')->whereNotNull('tbl_users.id')->whereHas('roles', function ($query) {
                    $query->whereIn('tbl_roles.id', user()->roles->pluck('id')->toArray());
                });
    }

    /**
     * Creates select for statuses
     *
     * @return String
     */
    protected function statuses()
    {

        $statuses = User::withoutGlobalScopes()
                ->select([DB::raw('count(id) as counter'), 'status'])
                ->whereNull('tbl_users.deleted_at');
        $this->scopeRoles($statuses);
        $result   = $statuses->groupBy('status')->get()->pluck('counter', 'status')->toArray();
        return [
            'all' => trans('antares/foundation::messages.statuses.all'),
            0     => trans('antares/foundation::messages.statuses.disabled', ['count' => array_get($result, 0, 0)]),
            1     => trans('antares/foundation::messages.statuses.active', ['count' => array_get($result, 1, 0)])
        ];
    }

    /**
     * Get actions column for table builder.
     *
     * @return callable
     */
    protected function getActionsColumn($canUpdateUser, $canDeleteUser, $canLoginAsUser)
    {
        return function ($row) use($canUpdateUser, $canDeleteUser, $canLoginAsUser) {
            $html               = app('html');
            $this->tableActions = [];
            $user               = user();

            if ($canUpdateUser) {
                $url = ($user->id === $row->id) ? 'antares/foundation::/account' : "antares::acl/index/users/{$row->id}/edit";
                $this->addTableAction('edit', $row, $html->link(handles($url), trans('antares/foundation::label.edit'), ['data-icon' => 'edit']));
            }
            if (!is_null($user) && $user->id !== $row->id and $canDeleteUser) {
                $this->addTableAction('delete', $row, $html->create('li', $html->link(handles("antares::acl/index/users/{$row->id}/delete", ['csrf' => true]), trans('antares/foundation::label.delete'), [
                                    'class'            => 'triggerable confirm',
                                    'data-icon'        => 'delete',
                                    'data-title'       => trans("antares/acl::messages.users.delete.are_you_sure"),
                                    'data-description' => trans("antares/acl::messages.users.delete.deleteing_description", ["fullname" => $row->fullname])
                ])));
            }
            if (!is_null($user) && $user->id !== $row->id and $canLoginAsUser && $row->roles->pluck('name')->toArray() !== $user->roles->pluck('name')->toArray()) {

                $this->addTableAction('login_as', $row, $html->create('li', $html->link(handles("login/with/{$row->id}"), trans('antares/acl::label.login_as', ['fullname' => $row->fullname]), [
                                    'class'            => 'triggerable confirm',
                                    'data-icon'        => 'odnoklassniki',
                                    'data-title'       => trans("Are you sure?"),
                                    'data-description' => trans('antares/acl::label.login_as', ['fullname' => $row->fullname])
                ])));
            }
            if (empty($this->tableActions)) {
                return '';
            }
            $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $this->tableActions->toArray())))), ['class' => 'mass-actions-menu'])->get();
            return '' . $html->raw($section)->get();
        };
    }

    /**
     * Get email column for table builder.
     *
     * @return callable
     */
    protected function getUserEmail($row)
    {
        return function ($row) {
            return app('html')->create('span', e($row->email))->get();
        };
    }

    /**
     * Get user roles column for table builder.
     *
     * @return callable
     */
    protected function userRoles($row)
    {
        return function ($row) {

            $roles = $row->roles;
            $value = [];

            foreach ($roles as $role) {
                $value[] = app('html')->create('span', e($role->full_name), [
                    'class' => 'label-basic label-basic--info'
                ]);
            }
            return implode('', [app('html')->create('span', app('html')->raw(implode(' ', $value)), ['class' => 'meta']),]);
        };
    }

}