<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

use OpenOrchestra\ModelBundle\Document\Node;
use OpenOrchestra\ModelBundle\Document\RouteDocument;
use OpenOrchestra\ModelInterface\Model\NodeInterface;
use OpenOrchestra\ModelInterface\DataFixtures\OrchestraFunctionalFixturesInterface;

/**
 * Class LoadDeletedSiteNodeData
 */
class LoadDeletedSiteNodeData extends AbstractFixture implements OrderedFixtureInterface, OrchestraFunctionalFixturesInterface
{
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $rootNodeFr = $this->generateRootNodeFr();
        $manager->persist($rootNodeFr);
        $this->generateRouteNode($manager, $rootNodeFr);

        $deletedNodeFr = $this->generateDeletedNodeFr();
        $manager->persist($deletedNodeFr);

        $manager->flush();
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 561;
    }

    /**
     * @param ObjectManager $manager
     * @param NodeInterface $node
     */
    protected function generateRouteNode(ObjectManager $manager, $node)
    {
        $site = $this->getReference('site3');

        foreach ($site->getAliases() as $key => $alias) {
            if ($alias->getLanguage() == $node->getLanguage()) {
                $route = new RouteDocument();
                $route->setName($key . '_' . $node->getId());
                $route->setHost($alias->getDomain());
                $scheme = $alias->getScheme();
                $route->setSchemes($scheme);
                $route->setLanguage($node->getLanguage());
                $route->setNodeId($node->getNodeId());
                $route->setSiteId($site->getSiteId());
                $route->setAliasId($key);

                $route->setPattern($node->getRoutePattern());
                $manager->persist($route);
            }
        }

    }

    /**
     * @return Node
     */
    protected function generateRootNodeFr()
    {
        $node = $this->getSitePageNode();
        $node->setNodeId(NodeInterface::ROOT_NODE_ID);
        $node->setStatus($this->getReference('status-draft'));
        $node->setDeleted(false);

        $node->setName("Site fermé");
        $node->setRoutePattern("site-ferme");
        $node->setLanguage("fr");
        $node->setCreatedBy('fake_admin');
        $node->setParentId('-');
        $node->setOrder(0);

        return $node;
    }

    /**
     * @return Node
     */
    protected function generateDeletedNodeFr()
    {
        $node = $this->getSitePageNode();
        $node->setNodeId('some-deleted-node-id');
        $node->setStatus($this->getReference('status-draft'));
        $node->setDeleted(true);

        $node->setName("Page supprimée");
        $node->setRoutePattern("page-supprimee");
        $node->setLanguage("fr");
        $node->setCreatedBy('fake_admin');
        $node->setParentId(NodeInterface::ROOT_NODE_ID);
        $node->setOrder(0);

        return $node;
    }

    /**
     * @return Node
     */
    protected function getSitePageNode()
    {
        $node = new Node();
        $node->setMaxAge(1000);
        $node->setNodeType('page');
        $node->setSiteId('3');
        $node->setPath('-');
        $node->setVersion('1');
        $node->setTemplate('home');

        return $node;
    }
}


<?php
/**
 * This file is part of Formular.
 *
 * (c) Philippe Gerber
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace bigwhoop\Formular\Template;

use bigwhoop\Formular\Filtering\EscaperInterface;
use Zend\Escaper\Escaper;

/**
 * @author Philippe Gerber <philippe@bigwhoop.ch>
 */
class Value
{
    /** @var string */
    private $key = '';

    /** @var mixed */
    private $value = null;

    /** @var EscaperInterface|null */
    private $escaper = null;

    /**
     * @param string $key
     * @param mixed $value
     */
    public function __construct($key, $value = null)
    {
        $this->key   = $key;
        $this->value = $value;
    }

    /**
     * @param EscaperInterface $escaper
     * @return $this
     */
    public function setEscaper(EscaperInterface $escaper)
    {
        $this->escaper = $escaper;
        return $this;
    }

    /**
     * @return EscaperInterface|null
     */
    public function getEscaper()
    {
        return $this->escaper;
    }

    /**
     * @param mixed $default
     * @return mixed
     */
    public function val($default = null)
    {
        if (empty($this->value)) {
            return $default;
        }
        return $this->value;
    }

    /**
     * Returns val() as an escaped string that can be used inside HTML tags.
     *
     * @param mixed $default
     * @param bool $escape
     * @return string
     */
    public function str($default = null, $escape = true)
    {
        $val = $this->val($default);
        if (is_scalar($val)) {
            $val = (string)$val;
        } else {
            $val = print_r($this->value, true);
        }
        return $escape && $this->escaper ? $this->escaper->escapeHtml($val) : $val;
    }

    /**
     * Returns val() as an escaped string that can be used inside HTML element attributes.
     *
     * @param mixed $default
     * @param bool $escape
     * @return string
     */
    public function attrVal($default = null, $escape = true)
    {
        $val = $this->str($default, false);
        return $escape && $this->escaper ? $this->escaper->escapeHtmlAttr($val) : $val;
    }

    /**
     * @param mixed $default
     * @param string|null $key
     * @return string
     */
    public function attr($default = null, $key = null)
    {
        $value = $this->attrVal($default);
        if (empty($value)) {
            return '';
        }
        return sprintf('%s="%s"', $key === null ? $this->key : $key, $value);
    }

    /**
     * @param mixed $default
     * @param string|null $key
     * @return string
     */
    public function prop($default = null, $key = null)
    {
        $value = $this->val($default);
        if (empty($value)) {
            return '';
        }
        return $key === null ? $this->key : $key;
    }

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

    /**
     * @param mixed $default
     * @return mixed
     */
    public function __invoke($default = null)
    {
        return $this->val($default);
    }
}


<?php

namespace Litecms\Forum\Http\Controllers;

use App\Http\Controllers\ResourceController as BaseController;
use Form;
use Litecms\Forum\Http\Requests\QuestionRequest;
use Litecms\Forum\Interfaces\QuestionRepositoryInterface;
use Litecms\Forum\Models\Question;

/**
 * Resource controller class for question.
 */
class QuestionResourceController extends BaseController
{

    /**
     * Initialize question resource controller.
     *
     * @param type QuestionRepositoryInterface $question
     *
     * @return null
     */
    public function __construct(QuestionRepositoryInterface $question)
    {
        parent::__construct();
        $this->repository = $question;
        $this->repository
            ->pushCriteria(\Litepie\Repository\Criteria\RequestCriteria::class)
            ->pushCriteria(\Litecms\Forum\Repositories\Criteria\QuestionResourceCriteria::class);
    }

    /**
     * Display a list of question.
     *
     * @return Response
     */
    public function index(QuestionRequest $request)
    {
        $view = $this->response->theme->listView();

        if ($this->response->typeIs('json')) {
            $function = camel_case('get-' . $view);
            return $this->repository
                ->setPresenter(\Litecms\Forum\Repositories\Presenter\QuestionPresenter::class)
                ->$function();
        }

        $user_id = user_id();
        $questions = $this->repository->questions($user_id);

        return $this->response->title(trans('forum::question.names'))
            ->view('forum::question.index', true)
            ->data(compact('questions', 'view'))
            ->output();
    }

    /**
     * Display question.
     *
     * @param Request $request
     * @param Model   $question
     *
     * @return Response
     */
    public function show(QuestionRequest $request, Question $question)
    {

        if ($question->exists) {
            $view = 'forum::question.show';
        } else {
            $view = 'forum::question.new';
        }

        return $this->response->title(trans('app.view') . ' ' . trans('forum::question.name'))
            ->data(compact('question'))
            ->view($view, true)
            ->output();
    }

    /**
     * Show the form for creating a new question.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function create(QuestionRequest $request)
    {

        $question = $this->repository->newInstance([]);
        return $this->response->title(trans('app.new') . ' ' . trans('forum::question.name'))
            ->view('forum::question.create', true)
            ->data(compact('question'))
            ->output();
    }

    /**
     * Create new question.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function store(QuestionRequest $request)
    {
        try {
            $attributes              = $request->all();
            $attributes['user_id']   = user_id();
            $attributes['user_type'] = user_type();
            $question                 = $this->repository->create($attributes);

            return $this->response->message(trans('messages.success.created', ['Module' => trans('forum::question.name')]))
                ->code(204)
                ->status('success')
                ->url(trans_url('discussion/' . $question->slug))
                ->redirect();
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('/forum/question'))
                ->redirect();
        }

    }

    /**
     * Show question for editing.
     *
     * @param Request $request
     * @param Model   $question
     *
     * @return Response
     */
    public function edit(QuestionRequest $request, Question $question)
    {
        return $this->response->title(trans('forum::question.name'))
            ->view('forum::public.question.newdiscussion')
            ->data(compact('question'))
            ->output();
    }

    /**
     * Update the question.
     *
     * @param Request $request
     * @param Model   $question
     *
     * @return Response
     */
    public function update(QuestionRequest $request, Question $question)
    {
        try {
            $request = $request->all();
            $attributes['title'] = $request['title'];
            $attributes['question'] = $request['question'];
            $attributes['category_id'] = $request['category_id'];
            $question->update($attributes);

                return redirect('/discussion/'.$request['slug']);
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('forum/question/' . $question->getRouteKey()))
                ->redirect();
        }

    }

    /**
     * Remove the question.
     *
     * @param Model   $question
     *
     * @return Response
     */
    public function destroy(QuestionRequest $request, Question $question)
    {
        try {

            $question->delete();
            return $this->response->message(trans('messages.success.deleted', ['Module' => trans('forum::question.name')]))
                ->code(202)
                ->status('success')
                ->url(guard_url('forum/question'))
                ->redirect();

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('forum/question/' . $question->getRouteKey()))
                ->redirect();
        }

    }

    /**
     * Remove multiple question.
     *
     * @param Model   $question
     *
     * @return Response
     */
    public function delete(QuestionRequest $request, $type)
    {
        try {
            $ids = hashids_decode($request->input('ids'));

            if ($type == 'purge') {
                $this->repository->purge($ids);
            } else {
                $this->repository->delete($ids);
            }

            return $this->response->message(trans('messages.success.deleted', ['Module' => trans('forum::question.name')]))
                ->status("success")
                ->code(202)
                ->url(guard_url('forum/question'))
                ->redirect();

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->status("error")
                ->code(400)
                ->url(guard_url('/forum/question'))
                ->redirect();
        }

    }

    /**
     * Restore deleted questions.
     *
     * @param Model   $question
     *
     * @return Response
     */
    public function restore(QuestionRequest $request)
    {
        try {
            $ids = hashids_decode($request->input('ids'));
            $this->repository->restore($ids);

            return $this->response->message(trans('messages.success.restore', ['Module' => trans('forum::question.name')]))
                ->status("success")
                ->code(202)
                ->url(guard_url('/forum/question'))
                ->redirect();

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->status("error")
                ->code(400)
                ->url(guard_url('/forum/question/'))
                ->redirect();
        }

    }

}


<?php

/*
 * Chill is a software for social workers
 *
 * Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
 * <http://www.champs-libres.coop>, <info@champs-libres.coop>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Chill\CustomFieldsBundle\Templating\Twig;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Chill\CustomFieldsBundle\Entity\CustomField;

/**
 * Add the following Twig Extension :
 * * chill_custom_fields_group_widget : to render the value of a custom field
 * *   group
 *
 * @author Julien Fastré <julien.fastre@champs-libres.coop>
 * @author Marc Ducobu <marc.ducobu@champs-libres.coop>
 */
class CustomFieldsGroupRenderingTwig extends \Twig_Extension implements ContainerAwareInterface
{

    /** @var Container $container The container */
    private $container;

    /** @var array $defaultParams The default parameters */
    private $defaultParams = array(
        'layout' => 'ChillCustomFieldsBundle:CustomFieldsGroup:render.html.twig',
        'show_empty' => True
    );

    /**
     *
     * @param boolean $showEmptyValues whether the empty values must be rendered
     */
    public function __construct($showEmptyValues)
    {
        $this->defaultParams['show_empty'] = $showEmptyValues;
    }

    /*
     * (non-PHPdoc)
     * @see \Symfony\Component\DependencyInjection\ContainerAwareInterface::setContainer()
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /*
     * (non-PHPdoc)
     * @see Twig_Extension::getFunctions()
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('chill_custom_fields_group_widget', array(
                $this,
                'renderWidget'
            ), array(
                'is_safe' => array(
                    'html'
                )
            )),
        ];
    }

    /* (non-PHPdoc)
     * @see Twig_ExtensionInterface::getName()
     */
    public function getName()
    {
        return 'chill_custom_fields_group_rendering';
    }

    /**
     * Twig extension that is used to render the value of a custom field group.
     *
     * The presentation of the value  is influenced by the document type.
     *
     * @param array $fields The array raw, as stored in the db
     * @param CustomFieldsGroud $customFielsGroup The custom field group
     * @param string $documentType The type of the document (csv, html)
     * @param array $params The parameters for rendering :
     *  - layout : allow to choose a different layout by default :
     *             ChillCustomFieldsBundle:CustomFieldsGroup:render.html.twig
     *  - show_empty : force show empty field
     * @return string HTML representation of the custom field group value, as described in
     * the CustomFieldInterface. Is HTML safe
     */
    public function renderWidget(array $fields, $customFielsGroup, $documentType='html', array $params = array())
    {
        $resolvedParams = array_merge($this->defaultParams, $params);

        return $this->container->get('templating')
            ->render($resolvedParams['layout'], array(
            	'cFGroup' => $customFielsGroup,
            	'cFData' => $fields,
                'show_empty' => $resolvedParams['show_empty']));
    }
}


<?php

declare(strict_types = 1);

namespace OctoLab\Kilex\ServiceProvider;

use Doctrine\DBAL\DriverManager;
use OctoLab\Common\Doctrine\Util\ConfigResolver;

/**
 * @author Kamil Samigullin <kamil@samigullin.info>
 */
class DoctrineServiceProvider
{
    /**
     * @param \Pimple $app
     *
     * @throws \InvalidArgumentException
     *
     * @api
     */
    public function setup(\Pimple $app)
    {
        $config = $app['config'];
        \assert('$config instanceof \OctoLab\Common\Config\SimpleConfig');
        ConfigResolver::resolve($config['doctrine:dbal']);
        $app['connections'] = $app::share(function () use ($config) : \Pimple {
            $connections = new \Pimple();
            foreach ($config['doctrine:dbal:connections'] as $id => $params) {
                assert('is_string($id)');
                $connections[$id] = DriverManager::getConnection($params);
            }
            return $connections;
        });
        $app['connection'] = $app::share(function (\Pimple $app) use ($config) : \Doctrine\DBAL\Connection {
            $ids = $app['connections']->keys();
            $default = $config['doctrine:dbal:default_connection'] ?: current($ids);
            return $app['connections'][$default];
        });
    }
}


<?php

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

namespace Temp\MetaReader;

use PHPExiftool\Driver\Metadata\Metadata;
use PHPExiftool\Driver\Value\ValueInterface;
use PHPExiftool\FileEntity;
use PHPExiftool\Reader;
use Temp\MetaReader\Value\MetaValue;
use Temp\MetaReader\Value\ValueBag;

/**
 * Exiftool reader.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class ExiftoolReader implements ReaderInterface
{
    /**
     * @var Reader
     */
    private $reader;

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

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

    /**
     * {@inheritdoc}
     */
    public function supports($filename)
    {
        try {
            $fileEntity = $this->reader->reset()->files($filename)->first();
        } catch (\Exception $e) {
            return false;
        }

        return $fileEntity instanceof FileEntity;
    }

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

        try {
            $fileEntity = $this->reader->reset()->files($filename)->first();
        } catch (\Exception $e) {
            return $meta;
        }

        if ($fileEntity->getMetadatas()->containsKey('File:ImageWidth')) {
            $meta->set(
                'image.width',
                new MetaValue((int) $fileEntity->getMetadatas()->get('File:ImageWidth')->getValue()->asString())
            );
        } elseif ($fileEntity->getMetadatas()->containsKey('PNG:ImageWidth')) {
            $meta->set(
                'image.width',
                new MetaValue((int) $fileEntity->getMetadatas()->get('PNG:ImageWidth')->getValue()->asString())
            );
        }

        if ($fileEntity->getMetadatas()->containsKey('File:ImageHeight')) {
            $meta->set(
                'image.height',
                new MetaValue((int) $fileEntity->getMetadatas()->get('File:ImageHeight')->getValue()->asString())
            );
        } elseif ($fileEntity->getMetadatas()->containsKey('PNG:ImageHeight')) {
            $meta->set(
                'image.height',
                new MetaValue((int) $fileEntity->getMetadatas()->get('PNG:ImageHeight')->getValue()->asString())
            );
        }

        foreach ($fileEntity->getMetadatas() as $metadata) {
            /* @var $metadata Metadata */

            if (ValueInterface::TYPE_BINARY === $metadata->getValue()->getType()) {
                continue;
            }

            $groupName = ($metadata->getTag()->getGroupName());
            $name = ($metadata->getTag()->getName());
            $value = (string) $metadata->getValue();
            if ($groupName === 'System' || !ctype_print($value)) {
                continue;
            }

            $path = "$groupName.$name";
            $meta->set($path, new MetaValue($value));
        }

        return $meta;
    }
}


<?php

namespace Colorium\Stateful;

abstract class Flash extends Session
{

	/** @var string */
	protected static $root = '__FLASH__';

	/**
	 * Consume value in session
	 *
	 * @param string $key
	 * @param mixed $fallback
	 *
	 * @return mixed
	 */
	public static function get($key, $fallback = null)
	{
		$message = static::provider()->get($key, $fallback);
		static::provider()->drop($key);
		return $message;
	}

}


<?php

namespace BetaBuddy\ApiClient;

/**
 * BetaBuddy Api Client Sample
 */
class ApiClient
{
    protected $apiUrl;
    protected $betaId;
    protected $secret;
    protected $hashingAlgorithm = 'sha1';

    /**
     * Constructor
     *
     * @param type $apiUrl Url to the BetaBuddy API (no trailing slash)
     * @param type $betaId Your Beta Id
     * @param type $secret Your Secret
     */
    public function __construct($apiUrl, $betaId, $secret)
    {
        $this->apiUrl = $apiUrl;
        $this->betaId = $betaId;
        $this->secret = $secret;
    }

    /**
     * Sign up a user for a chance to participate in the beta.
     *
     * @param string $moniker Something to uniquely identify the user, usually an email address.
     * @return type
     */
    public function SignupUser($moniker, $mailer_id = null)
    {
        $endpoint = '/user/signup';
        $postdata = array("moniker" => $moniker, "mailer_id" => $mailer_id);
        return $this->executePostRequest($endpoint, $postdata);
    }

    public function GetUserByMoniker($moniker)
    {
        $moniker = urlencode($moniker);
        $endpoint = '/user/get_by_moniker/'.$moniker;
        return $this->executeGetRequest($endpoint);
    }

    public function GetUserById($id)
    {
        $endpoint = '/user/get_by_id/'.$id;
        return $this->executeGetRequest($endpoint);
    }

    public function GetUsers($page=1, $pageSize=25)
    {
        $endpoint = '/user/list/'.$page.'/'.$pageSize;
        return $this->executeGetRequest($endpoint);
    }

    public function InviteByMoniker($moniker)
    {
        $endpoint = '/invite';
        $postdata = array("moniker" => $moniker);
        return $this->executePostRequest($endpoint, $postdata);
    }

    public function InviteById($id)
    {
        $endpoint = '/invite';
        $postdata = array("id" => $id);
        return $this->executePostRequest($endpoint, $postdata);
    }

    public function ActivateByMoniker($moniker, $token)
    {
        $endpoint = '/activate';
        $postdata = array("moniker" => $moniker, "token" => $token);
        return $this->executePostRequest($endpoint, $postdata);
    }

    public function ActivateById($id, $token)
    {
        $endpoint = '/activate';
        $postdata = array("id" => $id, "token" => $token);
        return $this->executePostRequest($endpoint, $postdata);
    }

    protected function executePostRequest($endpoint, array $postdata)
    {
        $curl = $this->getCurlHandle($endpoint);

        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);

        $curl_response = curl_exec($curl);
        curl_close($curl);

        return $curl_response;
    }

    protected function executeGetRequest($endpoint)
    {
        $curl = $this->getCurlHandle($endpoint);

        $curl_response = curl_exec($curl);
        curl_close($curl);

        return $curl_response;
    }

    protected function getCurlHandle($endpoint)
    {
        $timestamp = microtime(true);
        $url = $this->buildUrl($endpoint, $timestamp );
        $customHeader = $this->getCustomHeaderArray($url, $timestamp);

        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT ,0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 400); //timeout in seconds
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER ,false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $customHeader);

        return $curl;
    }

    protected function getCustomHeaderArray($url, $timestamp)
    {
        $hash = $this->getHash($url);
        return array(
                'BetaBuddy-Microtime: '.$timestamp,
                'BetaBuddy-Hash: '.$hash
                );
    }

    protected function buildUrl($endpoint, $timestamp)
    {
        return $this->apiUrl.'/api/'.$this->betaId.'/'.$timestamp.$endpoint;
    }

    protected function getHash($url)
    {
        return hash_hmac($this->hashingAlgorithm, $url, $this->secret);
    }

}


<?php

namespace Colorium\Stateful;

use Colorium\Stateful\Contract\ProviderInterface;

abstract class Auth
{

    /** @var ProviderInterface */
    protected static $provider;

    /** @var \Closure */
    protected static $factory;

    /** @var object */
    protected static $user;

    /** @var string */
    protected static $root = '__AUTH__';

    /**
     * Load session provider
     *
     * @param ProviderInterface $provider
     * @return ProviderInterface
     */
    public static function provider(ProviderInterface $provider = null)
    {
        if($provider) {
            static::$provider = $provider;
        }
        elseif(!static::$provider) {
            static::$provider = new Provider\Native(static::$root);
        }

        return static::$provider;
    }

    /**
     * Set user factory
     *
     * @param \Closure $factory
     */
    public static function factory(\Closure $factory)
    {
        static::$factory = $factory;
    }

    /**
     * Get validity
     *
     * @return bool
     */
    public static function valid()
    {
        return static::provider()->get('valid', false);
    }

    /**
     * Get user rank
     *
     * @return int
     */
    public static function rank()
    {
        return static::provider()->get('rank', 0);
    }

    /**
     * Get user object
     *
     * @return object
     */
    public static function user()
    {
        if(!static::$user and static::$factory) {
            $id = static::provider()->get('id');
            static::$user = call_user_func(static::$factory, $id);
        }

        return static::$user;
    }

    /**
     * Log user in session
     *
     * @param int $rank
     * @param string $id
     * @return object
     */
    public static function login($rank = 1, $id = null)
    {
        static::provider()->set('valid', true);
        static::provider()->set('rank', $rank);
        static::provider()->set('id', $id);

        return static::user();
    }

    /**
     * Log user out of session
     */
    public static function logout()
    {
        static::provider()->drop('valid');
        static::provider()->drop('rank');
        static::provider()->drop('id');
    }

}


<?php

namespace Gaufrette\Core\Filesystem;

use Gaufrette\Core\Adapter;
use Gaufrette\Core\Adapter\CanListKeys;
use Gaufrette\Core\File;
use Gaufrette\Core\File\FileFactory;
use Gaufrette\Core\File\FileFactory\LazyFileFactory;
use Gaufrette\Core\Filesystem;
use Gaufrette\Core\Operator;
use Gaufrette\Core\Operator\CanLoad;
use Gaufrette\Core\Operator\CanSave;

/**
 * A filesystem abstraction.
 */
class DefaultFilesystem implements Filesystem
{
    /**
     * @type FileFactory
     */
    private $factory;

    /**
     * @type Adapter
     */
    private $adapter;

    /**
     * @type Operator[]
     */
    private $operators;

    /**
     * @param Adapter     $adapter
     * @param FileFactory $factory
     */
    public function __construct(Adapter $adapter, FileFactory $factory = null)
    {
        $this->operators = array();
        $this->adapter   = $adapter;
        $this->factory   = null !== $factory ? $factory : new LazyFileFactory($this);
    }

    /**
     * {@inheritdoc}
     */
    public function addOperator(Operator $operator)
    {
        $this->operators[] = $operator;
    }

    /**
     * {@inheritdoc}
     */
    public function getFiles($prefix = '')
    {
        $files = array();

        if ($this->adapter instanceof CanListKeys) {
            foreach ($this->adapter->listKeys($prefix) as $key) {
                $files[$key] = $this->factory->create($key, $this);
            }
        }

        return $files;
    }

    /**
     * {@inheritdoc}
     */
    public function get($file)
    {
        if (false === $file instanceof File) {
            $file = $this->factory->create($file);
        }

        foreach ($this->operators as $operator) {
            if (false === $operator instanceof CanLoad || false === $operator->supports($file, $this->adapter)) {
                continue;
            }

            $operator->load($file, $this->adapter);
        }

        return $file;
    }

    /**
     * {@inheritdoc}
     */
    public function save(File $file)
    {
        foreach ($this->operators as $operator) {
            if (false === $operator instanceof CanSave || false === $operator->supports($file, $this->adapter)) {
                continue;
            }

            $operator->save($file, $this->adapter);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function exists($file)
    {
        if (false === $file instanceof File) {
            $file = $this->factory->create($file);
        }

        return $this->adapter->exists($file->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function delete(File $file)
    {
        $this->adapter->delete($file);

        return $this;
    }
}


<?php namespace ForeverPHP\Core;

/**
 * Permite administrar la configuracion del sistema y de las aplicaciones.
 *
 * @since       Version 1.0.0
 */
class Config {
    /**
     * Almacena todos los elementos de configuracion.
     *
     * @var array
     */
    private $settings;

    /**
     * Contiene la instancia singleton de Settings.
     *
     * @var \ForeverPHP\Core\Settings
     */
    private static $instance;

    private function __construct() {}

    /**
     * Obtiene o crea la instancia singleton de Settings.
     *
     * @return \ForeverPHP\Core\Settings
     */
    public static function getInstance() {
        if (is_null(static::$instance)) {
            static::$instance = new static();
            static::$instance->load();
        }

        return static::$instance;
    }

    /*
     * Carga una vez el archivo de configuracion
     */
    private function load() {
        $path = APPS_ROOT . DS . 'settings.php';

        if (!file_exists($path)) {
            exit('El archivo de configuración settings.php no existe.');
        }

        $this->settings = require $path;

        if (!is_array($this->settings)) {
            exit('El archivo de configuración no tiene el formato correcto.');
        }
    }

    /**
     * Valida si existe el item de configuracion
     *
     * @param  string $name Nombre del item.
     * @return boolean
     */
    public function exists($name) {
        if (array_key_exists($name, $this->settings)) {
            return true;
        }

        return false;
    }

    /**
     * Solo cambia la configuracion mientras el script este vivo
     *
     * @param string $name  Nombre del item.
     * @param mixed  $value Valor a asignar al item
     * @return boolean
     */
    public function set($name, $value = null) {
        if ($value == null) {
            return false;
        }

        $this->settings[$name] = $value;
    }

    /**
     * Obtiene un item de configuracion
     *
     * @param  string $item Nombre del item a obtener.
     * @return mixed        Retorna el valor del item.
     */
    public function get($name) {
        if ($this->exists($name)) {
            $value = $this->settings[$name];

            /*
             * NO VA: Si el valor a devolver es una matriz se debe retornar una
             * instancia de SubSettings para recorrer dicha matriz y asi
             * sucesivamente hasta recorrer toda la configuracion.
             */

            /*
             * Idea si se quiere llamar a una configuracion que esta en una matriz
             * dentro del settings.php
             *
             * podria haber dos opciones:
             *     1.- con secciones:
             *         Settings::get($name, $section);
             *
             *     2.- con separaciones por punto:
             *         Settings::get('db.default.port');
             */

            return $value;
        }

        return false;
    }

    /**
     * Abreviación para ver si se está en Debug true.
     *
     * @return boolean
     */
    public function inDebug() {
        return $this->get('debug');
    }
}


<?php

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

namespace FivePercent\Component\Error;

/**
 * Available list error codes
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com>
 */
class Errors
{
    /**
     * @var array|ErrorFactoryInterface[]
     */
    private $factories = [];

    /**
     * Construct
     *
     * @param array|ErrorFactoryInterface[] $factories
     */
    public function __construct(array $factories = [])
    {
        foreach ($factories as $factory) {
            $this->addFactory($factory);
        }
    }

    /**
     * Get errors
     *
     * @return array
     */
    public function getErrors()
    {
        $errors = [];

        foreach ($this->factories as $factory) {
            foreach ($factory->getErrors() as $code => $message) {
                $errors[$code] = $message;
            }
        }

        return $errors;
    }

    /**
     * Get exceptions
     *
     * @return array
     */
    public function getExceptions()
    {
        $exceptions = [];

        foreach ($this->factories as $factory) {
            foreach ($factory->getExceptions() as $exception => $code) {
                $exceptions[$exception] = $code;
            }
        }

        return $exceptions;
    }

    /**
     * Is has exception in storage
     *
     * @param \Exception $exception
     *
     * @return bool
     */
    public function hasException(\Exception $exception)
    {
        $class = get_class($exception);
        $exceptions = $this->getExceptions();

        return isset($exceptions[$class]);
    }

    /**
     * Get exception code
     *
     * @param \Exception $exception
     *
     * @return int
     *
     * @throws \RuntimeException
     */
    public function getExceptionCode(\Exception $exception)
    {
        $class = get_class($exception);
        $exceptions = $this->getExceptions();

        if (!isset($exceptions[$class])) {
            throw new \RuntimeException(sprintf(
                'Not exist exception "%s" in storage.',
                $class
            ));
        }

        return $exceptions[$class];
    }

    /**
     * Add error factory
     *
     * @param ErrorFactoryInterface $factory
     *
     * @return Errors
     */
    public function addFactory(ErrorFactoryInterface $factory)
    {
        $this->factories[get_class($factory)] = $factory;

        return $this;
    }

    /**
     * Get all factories
     *
     * @return array
     */
    public function getFactories()
    {
        return $this->factories;
    }

    /**
     * Get reserved codes
     *
     * @return array
     */
    public function getReservedCodes()
    {
        $reserved = [];

        /** @var ErrorFactoryInterface|string $factory */
        foreach ($this->factories as $factoryClass => $factory) {
            $reserved[$factoryClass] = $factory->getReservedDiapason();
        }

        return $reserved;
    }

    /**
     * Check reserved codes
     *
     * @throws \Exception
     */
    public function checkReservedCodes()
    {
        $reserved = $this->getReservedCodes();

        // First iterate: check all factory
        foreach ($reserved as $factoryClass => $reservedForFactory) {
            // Second iterate: check in each factory
            foreach ($reserved as $checkInFactory => $reservedInCheckFactory) {
                if ($checkInFactory == $factoryClass) {
                    continue;
                }

                if ($reservedInCheckFactory[0] >= $reservedForFactory[0] &&
                    $reservedInCheckFactory[0] <= $reservedForFactory[1]
                ) {
                    throw new \RuntimeException(sprintf(
                        'The reserved codes for factory "%s" [%d - %d] superimposed on "%s" factory [%d - %d].',
                        $checkInFactory,
                        $reservedInCheckFactory[0],
                        $reservedInCheckFactory[1],
                        $factoryClass,
                        $reservedForFactory[0],
                        $reservedForFactory[1]
                    ));
                }

                if ($reservedInCheckFactory[1] >= $reservedForFactory[0] &&
                    $reservedInCheckFactory[1] <= $reservedForFactory[1]
                ) {
                    throw new \RuntimeException(sprintf(
                        'The reserved codes for factory "%s" [%d - %d] superimposed on "%s" factory [%d - %d].',
                        $checkInFactory,
                        $reservedInCheckFactory[0],
                        $reservedInCheckFactory[1],
                        $factoryClass,
                        $reservedForFactory[0],
                        $reservedForFactory[1]
                    ));
                }
            }
        }
    }
}


<?php namespace Ordercloud\Cart\Entities;

use Ordercloud\Entities\Products\Product;
use Ordercloud\Entities\Products\ProductExtra;
use Ordercloud\Entities\Products\ProductExtraSet;

class CartItemExtra
{
    /** @var ProductExtraSet */
    private $extraSet;
    /** @var ProductExtra */
    private $extra;

    /**
     * @param $extraSet
     * @param $extra
     */
    public function __construct($extraSet, $extra)
    {
        $this->extraSet = $extraSet;
        $this->extra = $extra;
    }

    /**
     * @param array   $selectedExtras
     * @param Product $product
     *
     * @return array|static[]
     */
    public static function createFromArray(array $selectedExtras, Product $product) // TODO
    {
        $extras = [];

        foreach ($selectedExtras as $extra) {
            list($setId, $extraId) = explode('_', $extra);

            $extraSet = $product->getExtraSetByID($setId);

            $extras[] = new static($extraSet, $extraSet->getExtraByID($extraId));
        }

        return $extras;
    }

    /**
     * @return ProductExtraSet
     */
    public function getExtraSet()
    {
        return $this->extraSet;
    }

    /**
     * @return ProductExtra
     */
    public function getExtra()
    {
        return $this->extra;
    }
}


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

namespace cascade\components\types;

use cascade\components\web\ObjectViewEvent;
use cascade\models\Group;
use canis\base\exceptions\Exception;
use canis\base\exceptions\HttpException;
use canis\base\language\Noun;
use canis\security\Access;
use Yii;
use yii\base\Controller;

/**
 * Module [[@doctodo class_description:cascade\components\types\Module]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class Module extends \cascade\components\base\CollectorModule
{
    /**
     * @var [[@doctodo var_type:_title]] [[@doctodo var_description:_title]]
     */
    protected $_title;
    /**
     * @var [[@doctodo var_type:version]] [[@doctodo var_description:version]]
     */
    public $version = 1;

    /**
     * @var [[@doctodo var_type:objectSubInfo]] [[@doctodo var_description:objectSubInfo]]
     */
    public $objectSubInfo = [];
    /**
     * @var [[@doctodo var_type:icon]] [[@doctodo var_description:icon]]
     */
    public $icon = 'ic-icon-info';
    /**
     * @var [[@doctodo var_type:priority]] [[@doctodo var_description:priority]]
     */
    public $priority = 1000; //lower is better

    /**
     * @var [[@doctodo var_type:hasDashboard]] [[@doctodo var_description:hasDashboard]]
     */
    public $hasDashboard = true;
    /**
     * @var [[@doctodo var_type:uniparental]] [[@doctodo var_description:uniparental]]
     */
    public $uniparental = false;

    /**
     * @var [[@doctodo var_type:searchWeight]] [[@doctodo var_description:searchWeight]]
     */
    public $searchWeight = 1; // overall weight of item in search results
    /**
     * @var [[@doctodo var_type:childSearchWeight]] [[@doctodo var_description:childSearchWeight]]
     */
    public $childSearchWeight = false; // weight when a child of a searchable object
    /**
     * @var [[@doctodo var_type:parentSearchWeight]] [[@doctodo var_description:parentSearchWeight]]
     */
    public $parentSearchWeight = false; // weight when a parent of a searchable object

    /**
     * @var [[@doctodo var_type:enableApiAccess]] [[@doctodo var_description:enableApiAccess]]
     */
    public $enableApiAccess = true;

    /**
     * @var [[@doctodo var_type:sectionName]] [[@doctodo var_description:sectionName]]
     */
    public $sectionName;

    /**
     * @var [[@doctodo var_type:widgetNamespace]] [[@doctodo var_description:widgetNamespace]]
     */
    public $widgetNamespace;
    /**
     * @var [[@doctodo var_type:modelNamespace]] [[@doctodo var_description:modelNamespace]]
     */
    public $modelNamespace;

    /**
     * @var [[@doctodo var_type:formGeneratorClass]] [[@doctodo var_description:formGeneratorClass]]
     */
    public $formGeneratorClass = 'cascade\components\web\form\Generator';
    /**
     * @var [[@doctodo var_type:sectionItemClass]] [[@doctodo var_description:sectionItemClass]]
     */
    public $sectionItemClass = 'cascade\components\section\Item';
    /**
     * @var [[@doctodo var_type:sectionWidgetClass]] [[@doctodo var_description:sectionWidgetClass]]
     */
    public $sectionWidgetClass = 'cascade\components\web\widgets\section\Section';
    /**
     * @var [[@doctodo var_type:sectionSingleWidgetClass]] [[@doctodo var_description:sectionSingleWidgetClass]]
     */
    public $sectionSingleWidgetClass = 'cascade\components\web\widgets\section\SingleSection';
    /**
     * @var [[@doctodo var_type:fallbackDetailsWidgetClass]] [[@doctodo var_description:fallbackDetailsWidgetClass]]
     */
    public $fallbackDetailsWidgetClass = 'cascade\components\web\widgets\base\Details';

    /**
     * @var [[@doctodo var_type:_objectTypeModel]] [[@doctodo var_description:_objectTypeModel]]
     */
    protected $_objectTypeModel;

    const EVENT_RELATION_CHANGE = 'onRelationChange';
    const EVENT_RELATION_DELETE = 'onRelationDelete';
    const EVENT_VIEW_OBJECT = 'onViewObject';

    /**
     * @var [[@doctodo var_type:_disabledFields]] [[@doctodo var_description:_disabledFields]]
     */
    protected $_disabledFields;

    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->on(self::EVENT_VIEW_OBJECT, [$this, 'subactionHandle']);
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function always()
    {
        parent::always();
        if (isset($this->modelNamespace)) {
            Yii::$app->registerModelAlias(':' . $this->systemId, $this->modelNamespace);
        }
    }

    /**
     * @inheritdoc
     */
    public function getCollectorName()
    {
        return 'types';
    }

    /**
     * [[@doctodo method_description:onBeforeControllerAction]].
     *
     * @param unknown $controller
     * @param unknown $action
     *
     * @throws HttpException [[@doctodo exception_description:HttpException]]
     * @return unknown
     *
     */
    public function onBeforeControllerAction($controller, $action)
    {
        if (!isset($_SERVER['PASS_THRU']) or $_SERVER['PASS_THRU'] != md5(Yii::$app->params['salt'] . 'PASS')) {
            throw new HttpException(400, 'Invalid request!');
        }

        return parent::onBeforeControllerAction($event);
    }

    /**
     * @inheritdoc
     */
    public function onAfterInit($event)
    {
        if (!isset(Yii::$app->collectors['taxonomies']) || !Yii::$app->collectors['taxonomies']->registerMultiple($this, $this->taxonomies())) {
            throw new Exception('Could not register taxonmies for ' . $this->systemId . '!');
        }
        if (!isset(Yii::$app->collectors['widgets']) || !Yii::$app->collectors['widgets']->registerMultiple($this, $this->widgets())) {
            throw new Exception('Could not register widgets for ' . $this->systemId . '!');
        }
        // if (!isset(Yii::$app->collectors['roles']) || !Yii::$app->collectors['roles']->registerMultiple($this, $this->roles())) { throw new Exception('Could not register roles for '. $this->systemId .'!'); }
        // if (!isset(Yii::$app->collectors['tools']) || !Yii::$app->collectors['tools']->registerMultiple($this, $this->tools())) { throw new Exception('Could not register tools for '. $this->systemId .'!'); }
        // if (!isset(Yii::$app->collectors['reports']) || !Yii::$app->collectors['reports']->registerMultiple($this, $this->reports())) { throw new Exception('Could not register reports for '. $this->systemId .'!'); }
        return parent::onAfterInit($event);
    }

    /**
     * Get page meta.
     *
     * @return [[@doctodo return_type:getPageMeta]] [[@doctodo return_description:getPageMeta]]
     */
    public function getPageMeta()
    {
        $m = [];
        $m['id'] = $this->systemId;
        $m['icon'] = $this->icon;
        $m['hasDashboard'] = $this->hasDashboard;
        $m['title'] = $this->getTitle()->package;

        return $m;
    }

    /**
     * Get related type.
     *
     * @param [[@doctodo param_type:name]] $name [[@doctodo param_description:name]]
     *
     * @return [[@doctodo return_type:getRelatedType]] [[@doctodo return_description:getRelatedType]]
     */
    public function getRelatedType($name)
    {
        list($relationship, $role) = $this->getRelationship($name);
        if ($relationship) {
            return $relationship->roleType($role);
        }

        return false;
    }

    /**
     * Get relationship.
     *
     * @param [[@doctodo param_type:name]] $name [[@doctodo param_description:name]]
     *
     * @return [[@doctodo return_type:getRelationship]] [[@doctodo return_description:getRelationship]]
     */
    public function getRelationship($name)
    {
        $parts = explode(':', $name);
        $item = $this->collectorItem;
        if (count($parts) > 1) {
            if (in_array($parts[0], ['child', 'children', 'descendents'])) {
                if (isset($item->children[$parts[1]])) {
                    return [$item->children[$parts[1]], 'child'];
                }
            } else {
                if (isset($item->parents[$parts[1]])) {
                    return [$item->parents[$parts[1]], 'parent'];
                }
            }
        }

        return [false, false];
    }

    /**
     * [[@doctodo method_description:subactionHandle]].
     *
     * @param cascade\components\web\ObjectViewEvent $event [[@doctodo param_description:event]]
     *
     * @return [[@doctodo return_type:subactionHandle]] [[@doctodo return_description:subactionHandle]]
     */
    public function subactionHandle(ObjectViewEvent $event)
    {
        $subactions = $this->subactions();
        if (isset($subactions[$event->action])) {
            if (is_callable($subactions[$event->action])) {
                $event->handleWith($subactions[$event->action]);

                return;
            } elseif (isset($subactions[$event->action]['callback'])) {
                $always = !empty($subactions[$event->action]['always']);
                $event->handleWith($subactions[$event->action]['callback'], $always);
            }
        }

        return;
    }

    /**
     * [[@doctodo method_description:subactions]].
     *
     * @return [[@doctodo return_type:subactions]] [[@doctodo return_description:subactions]]
     */
    public function subactions()
    {
        return [];
    }

    /**
     * Set up.
     *
     * @return [[@doctodo return_type:setup]] [[@doctodo return_description:setup]]
     */
    public function setup()
    {
        $results = [true];
        if (!empty($this->primaryModel) && !empty($this->collectorItem->parents)) {
            $groups = ['top'];
            foreach ($groups as $groupName) {
                $group = Group::getBySystemName($groupName, false);
                if (empty($group)) {
                    continue;
                }
                if ($this->inheritParentAccess) {
                    $results[] = $this->objectTypeModel->parentAccess(null, $group);
                }
            }
        }

        return min($results);
    }

    /**
     * Get inherit parent access.
     *
     * @return [[@doctodo return_type:getInheritParentAccess]] [[@doctodo return_description:getInheritParentAccess]]
     */
    public function getInheritParentAccess()
    {
        return !$this->hasDashboard;
    }

    /**
     * [[@doctodo method_description:determineOwner]].
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     *
     * @return [[@doctodo return_type:determineOwner]] [[@doctodo return_description:determineOwner]]
     */
    public function determineOwner($object)
    {
        if (isset(Yii::$app->user)
            && !Yii::$app->user->isGuest
            && isset(Yii::$app->user->identity)
            ) {
            if (!empty(Yii::$app->user->identity->object_individual_id)) {
                return Yii::$app->user->identity->object_individual_id;
            } else {
                return false; //Yii::$app->user->id;
            }
        }

        return false;
    }

    /**
     * Get role help text.
     *
     * @param [[@doctodo param_type:roleItem]] $roleItem [[@doctodo param_description:roleItem]]
     * @param [[@doctodo param_type:object]]   $object   [[@doctodo param_description:object]] [optional]
     *
     * @return [[@doctodo return_type:getRoleHelpText]] [[@doctodo return_description:getRoleHelpText]]
     */
    public function getRoleHelpText($roleItem, $object = null)
    {
        switch ($roleItem->systemId) {
            case 'owner':
                return 'Able to manage access, delete, edit, and transfer ownership.';
            break;
            case 'manager':
                return 'Able to manage access, delete, and edit.';
            break;
            case 'editor':
                return 'Able to edit and archive.';
            break;
            case 'viewer':
                return 'Able to view content.';
            break;
            case 'browser':
                return 'Able to see name in lists, but cannot see content.';
            break;
        }

        return;
    }

    /**
     * [[@doctodo method_description:determineAccessLevel]].
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     * @param [[@doctodo param_type:role]]   $role   [[@doctodo param_description:role]]
     * @param [[@doctodo param_type:aro]]    $aro    [[@doctodo param_description:aro]] [optional]
     *
     * @return [[@doctodo return_type:determineAccessLevel]] [[@doctodo return_description:determineAccessLevel]]
     */
    public function determineAccessLevel($object, $role, $aro = null)
    {
        switch ($role) {
            case 'owner':
                return ['list' => Access::ACCESS_GRANTED, 'read' => Access::ACCESS_GRANTED, 'update' => Access::ACCESS_GRANTED, 'archive' => Access::ACCESS_GRANTED, 'delete' => Access::ACCESS_GRANTED, 'manageAccess' => Access::ACCESS_GRANTED, 'transfer' => Access::ACCESS_GRANTED];
            break;
            case 'manager':
                return ['list' => Access::ACCESS_GRANTED, 'read' => Access::ACCESS_GRANTED, 'update' => Access::ACCESS_GRANTED, 'archive' => Access::ACCESS_GRANTED, 'manageAccess' => Access::ACCESS_GRANTED];
            break;
            case 'editor':
                return ['list' => Access::ACCESS_GRANTED, 'read' => Access::ACCESS_GRANTED, 'update' => Access::ACCESS_GRANTED, 'archive' => Access::ACCESS_GRANTED];
            break;
            case 'viewer':
                return ['list' => Access::ACCESS_GRANTED, 'read' => Access::ACCESS_GRANTED];
            break;
            case 'browser':
                return ['list' => Access::ACCESS_GRANTED];
            break;
        }

        return false;
    }

    /**
     * Get action map.
     *
     * @param [[@doctodo param_type:controlledObject]] $controlledObject [[@doctodo param_description:controlledObject]] [optional]
     *
     * @return [[@doctodo return_type:getActionMap]] [[@doctodo return_description:getActionMap]]
     */
    public function getActionMap($controlledObject = null)
    {
        return [];
    }

    /**
     * Get primary as child.
     *
     * @param cascade\components\types\Module $parent [[@doctodo param_description:parent]]
     *
     * @return [[@doctodo return_type:getPrimaryAsChild]] [[@doctodo return_description:getPrimaryAsChild]]
     */
    public function getPrimaryAsChild(Module $parent)
    {
        return false;
    }

    /**
     * Get primary as parent.
     *
     * @param cascade\components\types\Module $child [[@doctodo param_description:child]]
     *
     * @return [[@doctodo return_type:getPrimaryAsParent]] [[@doctodo return_description:getPrimaryAsParent]]
     */
    public function getPrimaryAsParent(Module $child)
    {
        return false;
    }

    /**
     * Get disabled fields.
     *
     * @return [[@doctodo return_type:getDisabledFields]] [[@doctodo return_description:getDisabledFields]]
     */
    public function getDisabledFields()
    {
        if (is_null($this->_disabledFields)) {
            return [];
        }

        return $this->_disabledFields;
    }

    /**
     * Set disabled fields.
     *
     * @param [[@doctodo param_type:fields]] $fields [[@doctodo param_description:fields]]
     */
    public function setDisabledFields($fields)
    {
        $this->_disabledFields = $fields;
    }

    /**
     * Get primary model.
     *
     * @return [[@doctodo return_type:getPrimaryModel]] [[@doctodo return_description:getPrimaryModel]]
     */
    public function getPrimaryModel()
    {
        return $this->modelNamespace . '\\' . 'Object' . $this->systemId;
    }

    /**
     * @inheritdoc
     */
    public function getModuleType()
    {
        return 'Type';
    }

    /**
     * Get insert verb.
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     *
     * @return [[@doctodo return_type:getInsertVerb]] [[@doctodo return_description:getInsertVerb]]
     */
    public function getInsertVerb($object)
    {
        return;
    }

    /**
     * Get update verb.
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     *
     * @return [[@doctodo return_type:getUpdateVerb]] [[@doctodo return_description:getUpdateVerb]]
     */
    public function getUpdateVerb($object)
    {
        return;
    }
    /**
     * Get delete verb.
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     *
     * @return [[@doctodo return_type:getDeleteVerb]] [[@doctodo return_description:getDeleteVerb]]
     */
    public function getDeleteVerb($object)
    {
        return;
    }

    /**
     * [[@doctodo method_description:upgrade]].
     *
     * @param [[@doctodo param_type:from]] $from [[@doctodo param_description:from]]
     *
     * @return [[@doctodo return_type:upgrade]] [[@doctodo return_description:upgrade]]
     */
    public function upgrade($from)
    {
        return $this->setup();
    }

    /**
     * Get creator role.
     *
     * @return [[@doctodo return_type:getCreatorRole]] [[@doctodo return_description:getCreatorRole]]
     */
    public function getCreatorRole()
    {
        return [];
    }

    /**
     * Get role validation settings.
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]] [optional]
     *
     * @return [[@doctodo return_type:getRoleValidationSettings]] [[@doctodo return_description:getRoleValidationSettings]]
     */
    public function getRoleValidationSettings($object = null)
    {
        $settings = [];
        $settings['possibleRoles'] = $this->possibleRoles;

        return $settings;
    }

    /**
     * Get possible roles.
     *
     * @return [[@doctodo return_type:getPossibleRoles]] [[@doctodo return_description:getPossibleRoles]]
     */
    public function getPossibleRoles()
    {
        $roles = [];
        foreach (Yii::$app->collectors['roles']->getAll() as $roleItem) {
            $test = true;
            switch ($roleItem->systemId) {
                case 'owner':
                    $test = $this->isOwnable;
                break;
            }
            if ($test) {
                $roles[] = $roleItem->object->primaryKey;
            }
        }

        return $roles;
    }

    /**
     * Get required roles.
     *
     * @return [[@doctodo return_type:getRequiredRoles]] [[@doctodo return_description:getRequiredRoles]]
     */
    public function getRequiredRoles()
    {
        $roles = [];
        foreach (Yii::$app->collectors['roles']->getAll() as $roleItem) {
            $test = false;
            switch ($roleItem->systemId) {
                case 'owner':
                    $test = $this->isOwnable;
                break;
            }
            if ($test) {
                $roles[] = $roleItem->object->primaryKey;
            }
        }

        return $roles;
    }

    /**
     * Get initial role.
     *
     * @return [[@doctodo return_type:getInitialRole]] [[@doctodo return_description:getInitialRole]]
     */
    public function getInitialRole()
    {
        $roles = [];
        foreach (Yii::$app->collectors['roles']->getAll() as $roleItem) {
            $test = $roleItem->level < 400;
            if ($test) {
                $roles[] = $roleItem->object->primaryKey;
            }
        }

        return $roles;
    }

    /**
     * Get is ownable.
     *
     * @return [[@doctodo return_type:getIsOwnable]] [[@doctodo return_description:getIsOwnable]]
     */
    public function getIsOwnable()
    {
        return $this->dummyModel->getBehavior('Ownable') !== null && $this->dummyModel->getBehavior('Ownable')->isEnabled();
    }

    /**
     * Get owner object.
     *
     * @return [[@doctodo return_type:getOwnerObject]] [[@doctodo return_description:getOwnerObject]]
     */
    public function getOwnerObject()
    {
        return;
    }

    /**
     * Get owner.
     *
     * @return [[@doctodo return_type:getOwner]] [[@doctodo return_description:getOwner]]
     */
    public function getOwner()
    {
        if (!$this->isOwnable) {
            return;
        }
        $ownerObject = $this->getOwnerObject();
        if (is_object($ownerObject)) {
            return $ownerObject->primaryKey;
        }

        return $ownerObject;
    }

    /**
     * Get object type model.
     *
     * @return [[@doctodo return_type:getObjectTypeModel]] [[@doctodo return_description:getObjectTypeModel]]
     */
    public function getObjectTypeModel()
    {
        if (!isset($this->_objectTypeModel) && isset(Yii::$app->collectors['types']->tableRegistry[$this->systemId])) {
            $this->_objectTypeModel = Yii::$app->collectors['types']->tableRegistry[$this->systemId];
        }

        return $this->_objectTypeModel;
    }

    /**
     * Set object type model.
     *
     * @param [[@doctodo param_type:model]] $model [[@doctodo param_description:model]]
     */
    public function setObjectTypeModel($model)
    {
        $this->_objectTypeModel = $model;
    }
    /**
     * [[@doctodo method_description:search]].
     *
     * @param unknown $term
     * @param array   $params [[@doctodo param_description:params]] [optional]
     *
     * @return unknown
     */
    public function search($term, $params = [])
    {
        if (!$this->primaryModel) {
            return false;
        }

        $results = [];
        $modelClass = $this->primaryModel;

        return $modelClass::searchTerm($term, $params);
    }

    /**
     * Get object level.
     *
     * @return [[@doctodo return_type:getObjectLevel]] [[@doctodo return_description:getObjectLevel]]
     */
    public function getObjectLevel()
    {
        if ($this->isPrimaryType) {
            return 1;
        }
        $parents = $this->collectorItem->parents;
        if (!empty($parents)) {
            $maxLevel = 1;
            foreach ($parents as $rel) {
                if (get_class($rel->parent) === get_class($this)) {
                    continue;
                }
                $newLevel = $rel->parent->objectLevel + 1;
                if ($newLevel > $maxLevel) {
                    $maxLevel = $newLevel;
                }
            }

            return $maxLevel;
        }

        return 1;
    }
    /**
     * Get section.
     *
     * @param [[@doctodo param_type:parentWidget]] $parentWidget [[@doctodo param_description:parentWidget]] [optional]
     * @param unknown                              $settings     (optional)
     *
     * @return unknown
     */
    public function getSection($parentWidget = null, $settings = [])
    {
        $name = $this->systemId;
        $parent = false;
        $child = false;
        if (isset($settings['relationship']) && isset($settings['queryRole'])) {
            if ($settings['relationship']->companionRole($settings['queryRole']) === 'parent') {
                $parent = $settings['relationship']->parent;
            } else {
                $child = $settings['relationship']->child;
            }
        }
        if (($parent && $parent->systemId === $this->systemId) || ($child && $child->systemId === $this->systemId)) {
            $sectionId = $settings['relationship']->systemId . '-' . $this->systemId;
            $section = Yii::$app->collectors['sections']->getOne($sectionId);
            $section->title = '%%relationship%% %%type.' . $this->systemId . '.title.upperPlural%%';
            $section->icon = $this->icon;
            $section->systemId = $sectionId;
            if (empty($section->object)) {
                $sectionConfig = ['class' => $this->sectionSingleWidgetClass, 'section' => $section];
                $section->priority = $this->priority + 10000;
                $section->object = Yii::createObject($sectionConfig);
            }

            return $section;
        }
        $sectionClass = $this->sectionSingleWidgetClass;
        $sectionItemClass = $this->sectionItemClass;
        $newSectionTitle = '%%type.' . $this->systemId . '.title.upperPlural%%';
        $sectionId = $this->systemId;
        if (!is_null($this->sectionName)) {
            $sectionId = $sectionItemClass::generateSectionId($this->sectionName);
            if (Yii::$app->collectors['sections']->has($sectionId)) {
                return Yii::$app->collectors['sections']->getOne($sectionId);
            }
            $newSectionTitle = $this->sectionName;
            $sectionClass = $this->sectionWidgetClass;
        }
        $section = Yii::$app->collectors['sections']->getOne($sectionId);
        if (empty($section->object)) {
            $section->title = $newSectionTitle;
            $section->priority = $this->priority;
            $section->icon = $this->icon;
            $sectionConfig = ['class' => $sectionClass, 'section' => $section];
            $section->object = Yii::createObject($sectionConfig);
        }

        return $section;
    }

    /**
     * Get title.
     *
     * @return unknown
     */
    public function getTitle()
    {
        if (!is_object($this->_title)) {
            $this->_title = new Noun($this->_title);
        }

        return $this->_title;
    }

    /**
     * Set title.
     *
     * @param [[@doctodo param_type:title]] $title [[@doctodo param_description:title]]
     */
    public function setTitle($title)
    {
        $this->_title = $title;
    }

    /**
     * Get details widget.
     *
     * @param [[@doctodo param_type:objectModel]] $objectModel [[@doctodo param_description:objectModel]] [optional]
     *
     * @return [[@doctodo return_type:getDetailsWidget]] [[@doctodo return_description:getDetailsWidget]]
     */
    public function getDetailsWidget($objectModel = null)
    {
        if (is_null($objectModel) && isset(Yii::$app->request->object)) {
            $objectModel = Yii::$app->request->object;
        } elseif (is_null($objectModel)) {
            $objectModel = $this->dummyModel;
        }

        $detailsSection = $this->getDetailsSection();
        if ($detailsSection === false) {
            return false;
        }
        if ($detailsSection === true) {
            $detailsSection = '_self';
        }

        $detailsWidgetClass = self::classNamespace() . '\widgets\\' . 'Details';
        $widgetClass = $this->fallbackDetailsWidgetClass;

        @class_exists($detailsWidgetClass);
        if (class_exists($detailsWidgetClass, false)) {
            $widgetClass = $detailsWidgetClass;
        }
        $widget = ['class' => $widgetClass];
        $widget['owner'] = $this;
        $widgetItem = ['widget' => $widget, 'locations' => ['self'], 'priority' => 1];
        $widgetItem['section'] = Yii::$app->collectors['sections']->getOne($detailsSection);

        return $widgetItem;
    }

    /**
     * Get details section.
     *
     * @return [[@doctodo return_type:getDetailsSection]] [[@doctodo return_description:getDetailsSection]]
     */
    public function getDetailsSection()
    {
        return '_side';
    }

    /**
     * [[@doctodo method_description:widgets]].
     *
     * @return [[@doctodo return_type:widgets]] [[@doctodo return_description:widgets]]
     */
    public function widgets()
    {
        $widgets = [];

        $detailsWidget = $this->getDetailsWidget();
        if ($detailsWidget) {
            $id = '_' . $this->systemId . 'Details';
            $widgets[$id] = $detailsWidget;
        }

        $detailListClassName = self::classNamespace() . '\widgets\\' . 'DetailList';
        $simpleListClassName = self::classNamespace() . '\widgets\\' . 'SimpleLinkList';
        @class_exists($detailListClassName);
        @class_exists($simpleListClassName);

        $baseWidget = [];
        if ($this->module instanceof \cascade\components\section\Module) {
            $baseWidget['section'] = $this->module->collectorItem;
        }

        if (!$this->isChildless) {
            if (!class_exists($detailListClassName, false)) {
                $detailListClassName = false;
            }
            if (!class_exists($simpleListClassName, false)) {
                $simpleListClassName = false;
            }
            // needs widget for children and summary page
            if ($detailListClassName) {
                $childrenWidget = $baseWidget;
                $id = 'Parent' . $this->systemId . 'Browse';
                $childrenWidget['widget'] = [
                    'class' => $detailListClassName,
                    'icon' => $this->icon,
                    'title' => '%%relationship%% %%type.' . $this->systemId . '.title.upperPlural%%',
                ];
                $childrenWidget['locations'] = ['child_objects'];
                $childrenWidget['priority'] = $this->priority;
                $childrenWidget['section'] = Yii::$app->collectors['sections']->getOne('_parents');
                $widgets[$id] = $childrenWidget;
            } else {
                Yii::trace("Warning: There is no browse class for the child objects of {$this->systemId}");
            }
            if ($this->hasDashboard && $simpleListClassName) {
                $summaryWidget = $baseWidget;
                $id = $this->systemId . 'Summary';
                $summaryWidget['widget'] = [
                    'class' => $simpleListClassName,
                    'icon' => $this->icon,
                    'title' => '%%type.' . $this->systemId . '.title.upperPlural%%',
                ];
                $summaryWidget['locations'] = ['front'];
                $summaryWidget['priority'] = $this->priority;
                $widgets[$id] = $summaryWidget;
            } else {
                Yii::trace("Warning: There is no summary class for {$this->systemId}");
            }
        } else {
            if (!class_exists($detailListClassName, false)) {
                $detailListClassName = false;
            }
            // needs widget for parents
        }
        if ($detailListClassName) {
            $parentsWidget = $baseWidget;
            $id = 'Children' . $this->systemId . 'Browse';
            $parentsWidget['widget'] = [
                    'class' => $detailListClassName,
                    'icon' => $this->icon,
                    'title' => '%%relationship%% %%type.' . $this->systemId . '.title.upperPlural%%',
                ];
            $parentsWidget['locations'] = ['parent_objects'];
            $parentsWidget['priority'] = $this->priority + 1;
            $widgets[$id] = $parentsWidget;
        } else {
            Yii::trace("Warning: There is no browse class for the parent objects of {$this->systemId}");
        }

        return $widgets;
    }

    /**
     * [[@doctodo method_description:loadFieldLink]].
     *
     * @param [[@doctodo param_type:field]]  $field     [[@doctodo param_description:field]]
     * @param [[@doctodo param_type:object]] $object    [[@doctodo param_description:object]]
     * @param boolean                        $typeMatch [[@doctodo param_description:typeMatch]] [optional]
     */
    public function loadFieldLink($field, $object, $typeMatch = true)
    {
        if ($this->hasDashboard) {
            $field->url = ['/object/view', $object->id];
            if (!$typeMatch) {
                // what is being displayed isn't the same type as what is being linked to. put helper title.
                //		example: linking to an Individual from one of their phone numbers
                $field->linkOptions['title'] = $object->descriptor;
            }
        }
    }

    /**
     * [[@doctodo method_description:taxonomies]].
     *
     * @return unknown
     */
    public function taxonomies()
    {
        return [];
    }

    /**
     * [[@doctodo method_description:roles]].
     *
     * @return unknown
     */
    public function roles()
    {
        return [];
    }

    /**
     * [[@doctodo method_description:dependencies]].
     *
     * @return unknown
     */
    public function dependencies()
    {
        return [];
    }

    /**
     * [[@doctodo method_description:parents]].
     *
     * @return unknown
     */
    public function parents()
    {
        return [];
    }

    /**
     * Settings for.
     *
     * @return unknown
     */
    public function parentSettings()
    {
        return [
            'title' => false,
            'allow' => 1, // 0/false = no; 1 = only 1; 2 = 1 or more
            'showDescriptor' => false,
        ];
    }

    /**
     * [[@doctodo method_description:childrenSettings]].
     *
     * @return unknown
     */
    public function childrenSettings()
    {
        return [
            'allow' => 2,  // 0/false = no; 1 = only 1; 2 = 1 or more
        ];
    }

    /**
     * [[@doctodo method_description:children]].
     *
     * @return unknown
     */
    public function children()
    {
        return [];
    }

    /**
     * Get dummy model.
     *
     * @return [[@doctodo return_type:getDummyModel]] [[@doctodo return_description:getDummyModel]]
     */
    public function getDummyModel()
    {
        if (!$this->primaryModel) {
            return false;
        }
        $model = $this->primaryModel;

        return new $model();
    }

    /**
     * Get is childless.
     *
     * @return [[@doctodo return_type:getIsChildless]] [[@doctodo return_description:getIsChildless]]
     */
    public function getIsChildless()
    {
        if (empty($this->collectorItem) || empty($this->collectorItem->children)) {
            return true;
        }

        return false;
    }

    /**
     * Get model.
     *
     * @param [[@doctodo param_type:primaryModel]] $primaryModel [[@doctodo param_description:primaryModel]] [optional]
     * @param boolean                              $input        [[@doctodo param_description:input]] [optional]
     *
     * @return unknown
     */
    public function getModel($primaryModel = null, $input = false)
    {
        if (is_null($primaryModel)) {
            $primaryModel = $this->primaryModel;
            if (isset($input['id'])) {
                $primaryModel = $primaryModel::get($input['id']);
                if (empty($primaryModel)) {
                    return false;
                }
            } else {
                $primaryModel = new $primaryModel();
            }
        }
        $primaryModel->tabularId = false;

        if ($input && $input['_moduleHandler']) {
            $moduleHandler = $input['_moduleHandler'];
            $primaryModel->_moduleHandler = $moduleHandler;
            unset($input['_moduleHandler']);
            $primaryModel->setAttributes($input);
        } else {
            $primaryModel->loadDefaultValues();
        }

        return $primaryModel;
    }

    /**
     * Get form.
     *
     * @param boolean $primaryModel [[@doctodo param_description:primaryModel]] [optional]
     * @param array   $settings     [[@doctodo param_description:settings]] [optional]
     *
     * @return unknown
     */
    public function getForm($primaryModel = false, $settings = [])
    {
        if (!$primaryModel) {
            return false;
        }
        $formSegments = [$this->getFormSegment($primaryModel, $settings)];
        $config = ['class' => $this->formGeneratorClass, 'models' => $primaryModel->collectModels(), 'items' => $formSegments];

        return Yii::createObject($config);
    }

    /**
     * Get form segment.
     *
     * @param [[@doctodo param_type:primaryModel]] $primaryModel [[@doctodo param_description:primaryModel]] [optional]
     * @param array                                $settings     [[@doctodo param_description:settings]] [optional]
     *
     * @return [[@doctodo return_type:getFormSegment]] [[@doctodo return_description:getFormSegment]]
     */
    public function getFormSegment($primaryModel = null, $settings = [])
    {
        if (empty($primaryModel)) {
            return false;
        }

        return $primaryModel->form($settings);
    }
}


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

namespace cascade\components\web\form\fields;

use cascade\components\db\fields\Base as DbBaseField;

/**
 * FieldTypeDetector [[@doctodo class_description:cascade\components\web\form\fields\FieldTypeDetector]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class FieldTypeDetector extends \canis\base\object
{
    /**
     * [[@doctodo method_description:detect]].
     *
     * @param cascade\components\db\fields\Base $field [[@doctodo param_description:field]]
     *
     * @return [[@doctodo return_type:detect]] [[@doctodo return_description:detect]]
     */
    public static function detect(DbBaseField $field)
    {
        if (!$field->human) {
            return 'hidden';
        } else {
            $fieldType = $type = 'text';
            $dbMap = ['date' => 'date'];

            $fieldSchema = $field->fieldSchema;
            if ($fieldSchema->dbType === 'tinyint(1)') {
                return 'boolean';
            }
            if ($field->multiline) {
                return 'textarea';
            } elseif ($fieldSchema->type === 'boolean') {
                return 'boolean';
            } elseif (isset($dbMap[$fieldSchema->dbType])) {
                return $dbMap[$fieldSchema->dbType];
            }

            return 'text';
        }
    }
}


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

namespace CmsUser\Factory\Validator;

use Zend\Filter\StringToLower,
    Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    Zend\Validator\Callback,
    Zend\Validator\ValidatorInterface,
    CmsUser\Options\InputFilterOptionsInterface,
    CmsUser\Options\ModuleOptions;

class NoEmailExistsValidatorFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return ValidatorInterface
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();
        /* @var $options InputFilterOptionsInterface */
        $options = $services->get(ModuleOptions::class);
        /* @var $userMapper \CmsUser\Persistence\UserMapperInterface */
        $userMapper = $services->get('MapperManager')->get($options->getUserEntityClass());

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

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

        return $serviceLocator->get('Callback', [
            'messages' => [
                Callback::INVALID_VALUE => 'An user with this email already exists',
            ],
            'callback' => function ($value) use ($userMapper, $identity)
            {
                if ($identity) {
                    $filter = new StringToLower(['encoding' => 'UTF-8']);
                    if ($filter->filter($identity->getEmail()) === $filter->filter($value)) {
                        return true;
                    }
                }

                return !$userMapper->findOneByEmail($value);
            },
            'break_chain_on_failure' => true,
        ]);
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\PvWriteOff\A;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\BonusHybrid\Service\Calc\PvWriteOff\A\SaveDownline\A\Repo\Query\GetSnap as QGetSnap;
use Praxigento\Downline\Repo\Data\Snap as ESnap;

/**
 * Process PV Write Offs and calculate PV/TV/OV values for plain downline tree.
 */
class SaveDownline
{
    /** @var \Praxigento\Accounting\Repo\Dao\Account */
    private $daoAcc;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoDwnl;
    /** @var \Praxigento\Core\Api\App\Repo\Generic */
    private $daoGeneric;
    /** @var \Praxigento\BonusBase\Repo\Dao\Rank */
    private $daoRanks;
    /** @var \Praxigento\Downline\Api\Helper\Config */
    private $hlpCfgDwnl;
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpDwnlTree;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Z\Helper\GetDownlinePlainPrev */
    private $hlpGetDwnlPlainPrev;
    /** @var  \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Z\Helper\GetCustomersIds */
    private $hlpSignUpDebitCust;
    /** @var \Praxigento\BonusHybrid\Service\Calc\PvWriteOff\A\SaveDownline\A\Repo\Query\GetSnap */
    private $qDwnlSnap;

    public function __construct(
        \Praxigento\Core\Api\App\Repo\Generic $daoGeneric,
        \Praxigento\Accounting\Repo\Dao\Account $daoAcc,
        \Praxigento\BonusBase\Repo\Dao\Rank $daoRank,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoDwnl,
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme,
        \Praxigento\BonusHybrid\Service\Calc\Z\Helper\GetCustomersIds $hlpSignUpDebitCust,
        \Praxigento\Downline\Api\Helper\Tree $hlpDwnlTree,
        \Praxigento\Downline\Api\Helper\Config $hlpCfgDwnl,
        \Praxigento\BonusHybrid\Service\Calc\Z\Helper\GetDownlinePlainPrev $hlpGetDwnlPlainPrev,
        \Praxigento\BonusHybrid\Service\Calc\PvWriteOff\A\SaveDownline\A\Repo\Query\GetSnap $qDwnlSnap
    ) {
        $this->daoGeneric = $daoGeneric;
        $this->daoAcc = $daoAcc;
        $this->daoRanks = $daoRank;
        $this->daoDwnl = $daoDwnl;
        $this->hlpScheme = $hlpScheme;
        $this->hlpSignUpDebitCust = $hlpSignUpDebitCust;
        $this->hlpDwnlTree = $hlpDwnlTree;
        $this->hlpCfgDwnl = $hlpCfgDwnl;
        $this->hlpGetDwnlPlainPrev = $hlpGetDwnlPlainPrev;
        $this->qDwnlSnap = $qDwnlSnap;
    }

    public function exec($calcId, $periodEnd, $updates)
    {
        /* load accounts map */
        $mapAccs = $this->loadCustomersAccounts();
        /* get 'Sign Up Volume Debit' customers and customers with forced qualification */
        $signupDebitCustomers = $this->hlpSignUpDebitCust->exec();
        $forcedQualCustomers = $this->prepareForcedQualification();
        /* load customers downline tree and map by depth in descending order */
        $tree = $this->loadDownline($periodEnd);
        $mapByDepth = $this->hlpDwnlTree->mapByTreeDepthDesc(
            $tree,
            QGetSnap::A_CUST_ID,
            QGetSnap::A_DEPTH
        );
        /* default & unqualified ranks IDs */
        $mapRanks = $this->mapDefRanksByCustId();
        $rankIdUnranked = $this->daoRanks->getIdByCode(Cfg::RANK_UNRANKED);
        /* plain tree with unq. months info */
        $mapPlainPrev = $this->hlpGetDwnlPlainPrev->exec($periodEnd);

        /* create registries for collected data */
        $regDwnl = [];
        $regTeam = [];      // custId => [teamCustId, ...]
        $reqQual = [];      // custId => true|false
        /* PV to be transited through unqualified children (sum for all unqual. children of custId) */
        $reqJumps = [];     // custId=> pv
        /* scan downline tree from the lowest level up to the top */
        foreach ($mapByDepth as $level => $customers) {
            /* process all customers from one level of the downline tree */
            foreach ($customers as $custId) {
                $custData = $tree[$custId];
                $custParentId = $custData->get(QGetSnap::A_PARENT_ID);
                $custDepth = $custData->get(QGetSnap::A_DEPTH);
                $custPath = $custData->get(QGetSnap::A_PATH);
                $custScheme = $this->hlpScheme->getSchemeByCustomer($custData);
                /* register current customer in the parent's team */
                if (!isset($regTeam[$custParentId])) $regTeam[$custParentId] = [];
                $regTeam[$custParentId][] = $custId;
                /* get PV for current customer */
                /* TODO: should we add 'Sign Up Debit' PV here ??? */
                $custPv = $this->getPv($custId, $mapAccs, $updates, $signupDebitCustomers);
                /* get customer qualification */
                $isQualifedByPvDef = ($custScheme == Cfg::SCHEMA_DEFAULT)
                    && ($custPv > (Cfg::PV_QUALIFICATION_LEVEL_DEF - Cfg::DEF_ZERO));
                $isQualifedByPvEu = ($custScheme == Cfg::SCHEMA_EU)
                    && ($custPv > (Cfg::PV_QUALIFICATION_LEVEL_EU - Cfg::DEF_ZERO));
                $isForced = isset($forcedQualCustomers[$custScheme][$custId]);
                $isCustQualified = $isQualifedByPvDef || $isQualifedByPvEu || $isForced;
                $reqQual[$custId] = $isCustQualified;

                /* jump unqualif. children's PV if customer is not qualified itself */
                if (!$isCustQualified && isset($reqJumps[$custId])) {
                    $reqJumps[$custParentId] = $reqJumps[$custId];
                    unset($reqJumps[$custId]);
                }

                /* register customer in downline registry with initial values for TV/OV (own PV)*/
                $dwnlData = new EBonDwnl();
                $dwnlData->setCalculationRef($calcId);
                $dwnlData->setCustomerRef($custId);
                $dwnlData->setOv(0);
                $dwnlData->setParentRef($custParentId);
                $dwnlData->setDepth($custDepth);
                $dwnlData->setPath($custPath);
                $dwnlData->setPv($custPv);
                if (isset($mapPlainPrev[$custId])) {
                    /** @var EBonDwnl $prevItem */
                    $prevItem = $mapPlainPrev[$custId];
                    $unqMonths = $prevItem->getUnqMonths() + 1;
                } else {
                    $unqMonths = 1;
                }
                /* use default rank for customer group (unranked or distributor) if qualified */
                /* (rank will be set by compression calculation) */
                $rankId = $mapRanks[$custId];
                if (!$isCustQualified) {
                    $rankId = $rankIdUnranked;
                } else {
                    $unqMonths = 0;
                }
                $dwnlData->setRankRef($rankId);
                $dwnlData->setUnqMonths($unqMonths);
                $dwnlData->setTv(0);
                $regDwnl[$custId] = $dwnlData;

                /* walk trough the team and add children OV to the customer OV */
                $team = $regTeam[$custId] ?? [];
                $custTv = $custPv;  // TV = (PV.own + SUM(PV.team)
                $custOv = ($isCustQualified) ? $custPv : 0;  // OV = (PV.own + SUM(OV.team)
                foreach ($team as $childId) {
                    /* all children should be registered before */
                    /** @var EBonDwnl $childData */
                    $childData = $regDwnl[$childId];
                    $childPv = $childData->getPv();
                    $childOv = $childData->getOv();
                    $isChildQualified = $reqQual[$childId];

                    if (!$isCustQualified && !$isChildQualified) {
                        /* PV of the unqualified children should jump through unqualified customers */
                        if ($childPv) {
                            if (isset($reqJumps[$custParentId])) {
                                $reqJumps[$custParentId] += $childPv;
                            } else {
                                $reqJumps[$custParentId] = $childPv;
                            }
                        }
                        /* ... but OV should be assigned to customer (unqualif. child's PV are not in his OV) */
                        $custOv += $childOv;
                    } else {
                        /* add child's PV & OV to customer's TV & OV */
                        $custTv += $childPv;
                        $custOv += $childOv;
                        if (!$isChildQualified) $custOv += $childPv; // PV for unqualified children are not in his OV.
                    }
                }
                /* update customer TV & OV */
                /** @var EBonDwnl $custUpdate */
                $custUpdate = $regDwnl[$custId];
                $updateTv = $custUpdate->getTv();
                $updateOv = $custUpdate->getOv();
                $custUpdate->setTv($updateTv + $custTv);
                $custUpdate->setOv($updateOv + $custOv);
                /* add jumped PV of the unqualified children */
                if (isset($reqJumps[$custId])) {
                    $jumpOv = $reqJumps[$custId];
                    $updateOv = $custUpdate->getOv();
                    $custUpdate->setOv($updateOv + $jumpOv);
                    unset($reqJumps[$custId]);
                }
            }
        }
        /* save data into downline registry */
        foreach ($regDwnl as $item) {
            $this->daoDwnl->create($item);
        }
    }

    /**
     * Get PV for customer (real PV from 'PV Write Off' calculation adjusted for 'Sign Up Debit' customers).
     */
    private function getPv($custId, $mapAccs, $updates, $signupDebitCustomers)
    {
        $result = 0;
        if (isset($mapAccs[$custId])) {
            $account = $mapAccs[$custId];
            $accId = $account->getId();
            $result = (isset($updates[$accId])) ? $updates[$accId] : 0;
        }
        /* correct PV for 'Sign Up Debit' customers */
        $isSignUpDebit = in_array($custId, $signupDebitCustomers);
        if ($isSignUpDebit) {
            $result += \Praxigento\BonusHybrid\Config::SIGNUP_DEBIT_PV;
        }
        return $result;
    }

    /**
     * Load accounts by asset type code and map its using $customerId as a key.
     *
     * @return \Praxigento\Accounting\Repo\Data\Account[]
     */
    private function loadCustomersAccounts()
    {
        $mapAccs = $this->daoAcc->getAllByAssetTypeCode(Cfg::CODE_TYPE_ASSET_PV);
        $result = [];
        foreach ($mapAccs as $one) {
            $custId = $one->getCustomerId();
            $result[$custId] = $one;
        }
        return $result;
    }

    private function loadDownline($periodEnd)
    {
        $result = [];
        $query = $this->qDwnlSnap->build();
        $conn = $query->getConnection();
        $bind = [
            QGetSnap::BND_ON_DATE => $periodEnd
        ];
        $rows = $conn->fetchAll($query, $bind);
        foreach ($rows as $one) {
            $item = new ESnap($one);
            $custId = $item->getCustomerRef();
            $result[$custId] = $item;
        }
        return $result;
    }

    /**
     * @return array [custId => rankId]
     */
    private function mapDefRanksByCustId()
    {
        $result = [];
        /* unqual. customer's group ID & rank */
        $groupIdUnqual = $this->hlpCfgDwnl->getDowngradeGroupUnqual();
        $rankIdUnranked = $this->daoRanks->getIdByCode(Cfg::RANK_UNRANKED);
        $rankIdDefault = $this->daoRanks->getIdByCode(Cfg::RANK_DISTRIBUTOR);

        /* get all customers & map ranks by groups */
        $entity = Cfg::ENTITY_MAGE_CUSTOMER;
        $cols = [
            Cfg::E_CUSTOMER_A_ENTITY_ID,
            Cfg::E_CUSTOMER_A_GROUP_ID
        ];
        $all = $this->daoGeneric->getEntities($entity, $cols);
        foreach ($all as $one) {
            $custId = $one[Cfg::E_CUSTOMER_A_ENTITY_ID];
            $groupId = $one[Cfg::E_CUSTOMER_A_GROUP_ID];
            $rankId = ($groupId == $groupIdUnqual) ? $rankIdUnranked : $rankIdDefault;
            $result[$custId] = $rankId;
        }
        return $result;
    }

    /**
     * @return array [schema => [custId, ...], ...]
     */
    private function prepareForcedQualification()
    {
        $result = [
            Cfg::SCHEMA_DEFAULT => [],
            Cfg::SCHEMA_EU => []
        ];
        $customers = $this->hlpScheme->getForcedQualificationCustomers();
        foreach ($customers as $custId => $item) {
            if (isset($item[Cfg::SCHEMA_DEFAULT])) $result[Cfg::SCHEMA_DEFAULT][] = $custId;
            if (isset($item[Cfg::SCHEMA_EU])) $result[Cfg::SCHEMA_EU][] = $custId;
        }
        return $result;
    }
}