<?php namespace ForeverPHP\Cache;

use ForeverPHP\Core\Facades\Settings;

/**
 * Permite el trabajo con Cache con diferentes motores.
 *
 * @author  Daniel Nuñez S. <dnunez@emarva.com>
 * @since   Version 0.4.0
 */

/*
 given a URL, try finding that page in the cache
if the page is in the cache:
    return the cached page
else:
    generate the page
    save the generated page in the cache (for next time)
    return the generated page
 */

/*
OJO: no va por url

¿Como se almacenan los templates?

    inicio.html.cache -> fonde inicio es el nombre del template

    Uso:
        Cache::set($tamplate . '.html', $render);

¿Como se almacenan los resultados de las consultas?

    mi_resultado_consulta.cache -> mi_resultado_consulta lo define el usuario
    o el ORM (tentacles)

    Uso:
        Cache::set('mi_resultado_consulta', $data);

        Nota: Los resultados se deberian guardar en formato JSon para una mejor
              comprension.

Cache::get: antes de devolver el objeto del cache debe verificar si ha expirado.

Cache::set: antes de guardar el objeto en el cache debe verificar que no se
            exceda el limite maximo de entidades.
*/

class Cache {
    /**
     * Indica si el cache esta activo.
     *
     * @var boolean
     */
    private $cacheEnabled;

    /**
     * El tipo de motor a utilizar.
     *
     * @var string
     */
    private $engine;

    /**
     * Ubicación del cache, solo algunos motores usan esta opción.
     *
     * @var string
     */
    private $location;

    /**
     * Tiempo de refresco del cache, esta representado en segundos.
     *
     * @var int
     */
    private $timeout;

    /**
     * Numero máximo de entradas en cache.
     *
     * @var int
     */
    private $maxEntries;

    /**
     * Contiene la instancia del motor de cache.
     *
     * @var mixed
     */
    private $cacheEngine;

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

    private function __construct() {
        $this->cacheEnabled = false;
    }

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

        return static::$instance;
    }

    /**
     * Carga una vez el motor de cache y la
     * configuración del cache.
     *
     * @return void
     */
    private function load() {
        // Verifico si el cache esta activo
        if (Settings::get('cacheEnabled')) {
            $this->cacheEnabled = true;
        }

        // Sigue cargando el motor de cache, solo su esta activo
        if ($this->cacheEnabled) {
            $cacheSettings = Settings::get('cache');

            // Se almacenan los ítems de configuración del cache
            $this->engine = $cacheSettings['engine'];
            $this->location = $cacheSettings['location'];
            $this->timeout = $cacheSettings['timeout'];
            $this->maxEntries = $cacheSettings['maxEntries'];

            // Se crea la instancia del motor según la configuración
            if ($this->engine === 'filecache') {
                $this->cacheEngine = new \ForeverPHP\Cache\FileCache($this->location);
            }
        }
    }

    /**
     * Valida si la entrada existe en el cache.
     *
     * @param  string $key
     * @return boolean
     */
    public function exists($key) {
        if ($this->cacheEnabled) {
            return $this->cacheEngine->exists($key);
        }

        return false;
    }

    /**
     * Almacena una entrada en el cache.
     *
     * @param string $key
     * @param string $value
     */
    public function set($key, $value) {
        if ($this->cacheEnabled) {
            $this->cacheEngine->set($key, $value);
        }
    }

    public function get($key) {
        // NO DISPONIBLE POR AHORA, YA QUE SE ESTAN HACIENDO PRUEBAS CON EL CACHE
    }

    public function remove($key) {
        // NO DISPONIBLE POR AHORA, YA QUE SE ESTAN HACIENDO PRUEBAS CON EL CACHE
    }
}


<?php

/*
 * Copyright (c) 2013, Flaming Code
 *
 */

namespace FlamingBase\Stdlib;

/**
 * ImageTool
 *
 * Uses GD2
 *
 * @author Flemming Andersen <flemming@flamingcode.com>
 * @copyright (c) 2013, Flaming Code
 * @link https://github.com/FlamingCode/FlamingBase for the canonical source repository
 * @license http://opensource.org/licenses/MIT MIT
 */
class ImageTool
{
	const IMG_QUALITY = 100;
	const MIRROR_HORIZONTAL = 1;
	const MIRROR_VERTICAL = 2;
	const MIRROR_BOTH = 3;

	/**
	 * Converts image to jpeg and optionally saves it to a given path.
	 *
	 * @param String $inputImg
	 * @param String $savePath
	 * @param int $quality
	 * @param array $exifData
	 * @return Boolean|ImageResource
	 */
	public static function convert2Jpeg($inputImg, $savePath = null, $quality = null, array $exifData = null)
	{
		$retval = false;
		$img = self::imgCreate($inputImg);
		$imgSize = self::size($img);
		$jpegImg = imagecreatetruecolor($imgSize[0], $imgSize[1]);
		imagecopy($jpegImg, $img, 0, 0, 0, 0, $imgSize[0], $imgSize[1]);

		if (null === $quality)
			$quality = self::IMG_QUALITY;

		if (null !== $exifData && array_key_exists('Orientation', $exifData)) {
			$ort = $exifData['Orientation'];
			switch ($ort) {
				default:
				case 1: // nothing
					break;

				case 2: // horizontal flip
					$jpegImg = self::flipImage($jpegImg, 1);
					break;

				case 3: // 180 rotate left
					$jpegImg = self::rotateImage($jpegImg, 180);
					break;

				case 4: // vertical flip
					$jpegImg = self::flipImage($jpegImg, 2);
					break;

				case 5: // vertical flip + 90 rotate right
					$jpegImg = self::flipImage($jpegImg, 2);
					$jpegImg = self::rotateImage($jpegImg, 90);
					break;

				case 6: // 90 rotate right
					$jpegImg = self::rotateImage($jpegImg, 90);
					break;

				case 7: // horizontal flip + 90 rotate right
					$jpegImg = self::flipImage($jpegImg, 1);
					$jpegImg = self::rotateImage($jpegImg, 90);
					break;

				case 8:    // 90 rotate left
					$jpegImg = self::rotateImage($jpegImg, 270);
					break;
			}
		}

		if (null === $savePath)
			$retval = $jpegImg;
		else
			$retval = imagejpeg($jpegImg, $savePath, $quality);
		return $retval;
	}

	private static function imgCreate($imgStr)
	{
		if (is_string($imgStr)) {
			$tmp = explode('.', $imgStr);
			$ext = strtolower(end($tmp));

			$img = null;

			switch ($ext) {
				case 'png':
					$img = imagecreatefrompng($imgStr);
					break;
				case 'gif':
					$img = imagecreatefromgif($imgStr);
					break;
				case 'bmp':
					$img = imagecreatefromwbmp($imgStr);
					break;
				case 'jpg':
				case 'jpeg':
				default:
					$img = imagecreatefromjpeg($imgStr);
					break;
			}

			return $img;
		}
		return $imgStr;
	}

	private static function resize($origImg, $newSize, $mode = 'width')
	{
		if (is_string($origImg))
			$fullSize = self::imgCreate($origImg);
		else
			$fullSize = $origImg;

		$origWidth = imagesx($fullSize);
		$origHeight = imagesy($fullSize);

		switch ($mode) {
			case 'height':
				$newHeight = $newSize;
				$ratio = $origWidth / $origHeight;
				$newWidth = $ratio * $newHeight;
				break;
			case 'width':
			default:
				$newWidth = $newSize;
				$ratio = $origHeight / $origWidth;
				$newHeight = $ratio * $newWidth;
				break;
		}

		$resizedImg = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($resizedImg, $fullSize, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);

		if (is_string($origImg))
			imagedestroy($fullSize);

		return $resizedImg;
	}

	public static function resizeByWidthKeepRatio($origImg, $newWidth)
	{
		return self::resize($origImg, $newWidth, 'width');
	}

	public static function resizeByLongSide($origImg, $newSize)
	{
		$mode = 'width';
		$size = self::size($origImg);

		if ($size[1] > $size[0])
			$mode = 'height';

		return self::resize($origImg, $newSize, $mode);
	}

	public static function resizeByShortSide($origImg, $newSize)
	{
		$mode = 'width';
		$size = self::size($origImg);

		if ($size[1] < $size[0])
			$mode = 'height';

		return self::resize($origImg, $newSize, $mode);
	}

	public static function resizeToThumb($origImg, $newSize)
	{
		$resizedImg = self::resizeByShortSide($origImg, $newSize);

		$resizedSize = self::size($resizedImg);

		$xOffset = ($resizedSize[0] / 2) - ($newSize / 2);
		$yOffset = ($resizedSize[1] / 2) - ($newSize / 2);

		$thumb = imagecreatetruecolor($newSize, $newSize);

		imagecopy($thumb, $resizedImg, 0, 0, $xOffset, $yOffset, $newSize, $newSize);

		return $thumb;
	}

	/**
	 * Calculates the image size - width and height in px.
	 *
	 * @param mixed $img
	 * @return array
	 */
	public static function size($inputImg)
	{
		if (is_string($inputImg))
			$img = self::imgCreate($inputImg);
		else
			$img = $inputImg;

		$imgW = imagesx($img);
		$imgH = imagesy($img);

		if (is_string($inputImg))
			imagedestroy($img);

		return array($imgW, $imgH);
	}

	public static function rotateImage($img, $rotation)
	{
		$width = imagesx($img);
		$height = imagesy($img);
		switch ($rotation) {
			case 0:
			case 360:
				return $img;
				break;
			case 90:
				$newimg = @imagecreatetruecolor($height, $width);
				break;
			case 180:
				$newimg = @imagecreatetruecolor($width, $height);
				break;
			case 270:
				$newimg = @imagecreatetruecolor($height, $width);
				break;
		}
		if ($newimg) {
			for ($i = 0; $i < $width; $i++) {
				for ($j = 0; $j < $height; $j++) {
					$reference = imagecolorat($img, $i, $j);
					switch ($rotation) {
						case 90:
							if (!@imagesetpixel($newimg, ($height - 1) - $j, $i, $reference))
								return false;
							break;
						case 180:
							if (!@imagesetpixel($newimg, $width - $i, ($height - 1) - $j, $reference))
								return false;
							break;
						case 270:
							if (!@imagesetpixel($newimg, $j, $width - $i, $reference))
								return false;
							break;
					}
				}
			}
			return $newimg;
		}
		return false;
	}

	public static function flipImage($src, $type)
	{
		$imgsrc = imagecreatefromjpeg($src);
		$width = imagesx($imgsrc);
		$height = imagesy($imgsrc);
		$imgdest = imagecreatetruecolor($width, $height);

		for ($x = 0; $x < $width; $x++) {
			for ($y = 0; $y < $height; $y++) {
				if ($type == self::MIRROR_HORIZONTAL)
					imagecopy($imgdest, $imgsrc, $width - $x - 1, $y, $x, $y, 1, 1);
				if ($type == self::MIRROR_VERTICAL)
					imagecopy($imgdest, $imgsrc, $x, $height - $y - 1, $x, $y, 1, 1);
				if ($type == self::MIRROR_BOTH)
					imagecopy($imgdest, $imgsrc, $width - $x - 1, $height - $y - 1, $x, $y, 1, 1);
			}
		}

		return $imgdest;
	}
}


<?php namespace ForeverPHP\Database\SQLEngines;

use ForeverPHP\Core\Settings;

/**
 * Motor MSSQL(Microsoft SQL Server) permite trabajar con este motor de base
 * de datos.
 *
 * @author      Daniel Nuñez S. <dnunez@emarva.com>
 * @since       Version 0.4.0
 */
class MSSQLEngine extends SQLEngine implements SQLEngineInterface {
    public function connect() {
        $db = Settings::getInstance()->get('dbs');
        $db = $db[$this->dbSetting];

        $dbName = ($this->database != false) ? $this->database : $db['database'];

        $server = $db['server'] . ':' . $db['port'];

        // Me conecto a la base de datos
        $this->link = mssql_pconnect($server, $db['user'], $db['password']);

        if (!$this->link) {
            $this->error = mssql_get_last_message();
            return false;
        }

        if (!mssql_select_db($dbName, $this->link)) {
            $this->error = mssql_get_last_message();
            return false;
        }

        return true;
    }

    private function executeQuery() {
        $return = false;

        if ($this->queryType == 'other') {
            if (mssql_query($this->query, $this->link) === true) {
                $return = true;

                $this->error = mssql_get_last_message();
            }
        } else {
            if ($result = mssql_query($this->query, $this->link)) {
                // Conteo de registros
                if ($this->queryType == 'insert' ||
                    $this->queryType == 'update' ||
                    $this->queryType == 'delete') {
                    $this->numRows = mssql_rows_affected($this->link);

                    $return = true;
                } else {
                    $this->numRows = mssql_num_rows($result);
                    $fetchType = MSSQL_NUM;

                    if ($this->queryReturn == 'assoc') {
                        $fetchType = MSSQL_ASSOC;
                    } elseif ($this->queryReturn == 'both') {
                        $fetchType = MSSQL_BOTH;
                    }

                    $return = array();

                    while ($row = mssql_fetch_array($result, $fetchType)) {
                        array_push($return, $row);
                    }
                }

                $this->error = mssql_get_last_message();

                mssql_free_result($result);
            } else {
                $this->error = mssql_get_last_message();
            }
        }

        return $return;
    }

    /*
     * Como el conector MSSQL de PHP no cuenta con consultas con
     * parametros, se deben emular.
     */
    private function executeQueryWithParameters() {
        if (count($this->parameters) != 0) {
            $newQuery = '';
            $totalParams = substr_count($this->query, '?');
            $posParam = strpos($this->query, '?');

            // Valida si el numero de parametros coincide
            if ($totalParams != count($this->parameters)) {
                $this->error = 'Incorrect number of parameters in the query.';
                return false;
            }

            foreach ($this->parameters as $param => $paramContent) {
                $valueParam = '';

                if ($paramContent['type'] == 'i' || $paramContent['type'] == 'd') {
                    $valueParam = $paramContent['value'];
                } elseif ($paramContent['type'] == 's' || $paramContent['type'] == 'b') {
                    $valueParam = '\'' . $paramContent['value'] . '\'';
                }

                $newQuery = substr_replace($this->query, $valueParam, $posParam, 1);
                $posParam = strpos($newQuery, '?');
                $this->query = $newQuery;
            }
        }

        return $this->executeQuery();
    }

    public function execute() {
        if (count($this->parameters) == 0) {
            return $this->executeQuery();
        } else {
            return $this->executeQueryWithParameters();
        }
    }

    public function disconnect() {
        if ($this->link != null) {
            // Cierro la conexion
            if (!mssql_close($this->link)) {
                $this->error = mssql_get_last_message();
                return false;
            }

            $this->link = null;
        }
    }

    public function __destruct() {
        $this->disconnect();
    }
}


<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2018
 */

namespace Praxigento\BonusHybrid\Ui\DataProvider\Downline;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Ui\DataProvider\Downline\Grid\A\Repo\Query\GetCalcId as QGetId;
use Praxigento\BonusHybrid\Ui\DataProvider\Downline\Grid\A\Repo\Query\Grid as QGrid;
use Praxigento\BonusHybrid\Ui\DataProvider\Options\TreeType as OptionTreeType;
use Praxigento\Core\Api\Helper\Period as HPeriod;

/**
 * Data provider for Bonus Downline grid (with initial parameters for select).
 */
class Grid
    extends \Praxigento\Core\App\Ui\DataProvider\Grid\Base
{
    /**
     * See "Praxigento_BonusHybrid:view/adminhtml/web/js/form/provider/bonus_downline"
     */
    const REQ_PERIOD = 'period';
    const REQ_TREE_TYPE = 'type';

    /** @var  \Praxigento\Core\App\Ui\DataProvider\Grid\Query\IBuilder */
    private $gridQueryBuilder;
    /** @var \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\BonusHybrid\Ui\DataProvider\Downline\Grid\A\Repo\Query\GetCalcId */
    private $qGetId;

    public function __construct(
        $name,
        \Magento\Framework\Api\Search\SearchCriteriaBuilder $searchCriteriaBuilder,
        \Magento\Framework\App\RequestInterface $request,
        \Praxigento\BonusHybrid\Ui\DataProvider\Downline\Grid\A\Repo\Query\Grid $gridQueryBuilder,
        \Praxigento\BonusHybrid\Ui\DataProvider\Downline\Grid\A\Repo\Query\GetCalcId $qGetId,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        $primaryFieldName = 'primaryFieldName',
        $requestFieldName = 'requestFieldName',
        array $meta = [],
        array $data = []
    ) {
        parent::__construct(
            $name,
            $searchCriteriaBuilder,
            $request,
            $gridQueryBuilder,
            $primaryFieldName,
            $requestFieldName,
            $meta,
            $data
        );
        $this->gridQueryBuilder = $gridQueryBuilder;
        $this->qGetId = $qGetId;
        $this->hlpPeriod = $hlpPeriod;
    }

    /**
     * Extract and validate input parameters.
     *
     * @return array [$dsBegin, $treeType]
     */
    private function extractInput()
    {
        $params = $this->request->getParams();
        $period = $params[self::REQ_PERIOD] ?? '';
        if (empty($period)) {
            $period = $this->hlpPeriod->getPeriodCurrent(null, 0, HPeriod::TYPE_MONTH);
        } else {
            $period = $this->hlpPeriod->normalizePeriod($period, HPeriod::TYPE_MONTH);
        }
        $dsBegin = $this->hlpPeriod->getPeriodFirstDate($period);
        $treeType = $params[self::REQ_TREE_TYPE] ?? '';
        if ($treeType != OptionTreeType::VAL_PLAIN) {
            $treeType = OptionTreeType::VAL_COMPRESS; // 'compressed' by default
        }
        return [$dsBegin, $treeType];
    }

    /**
     * Analyze HTTP request, load data from DB to compose bind array with parameters for grid query.
     *
     * @return array
     */
    private function getBind()
    {
        [$dsBegin, $treeType] = $this->extractInput();
        $calcId = $this->getCalcId($dsBegin, $treeType);
        $bind = [
            QGrid::BND_CALC_ID => $calcId
        ];
        return $bind;
    }

    /**
     * Get calculation ID for given period & tree type.
     *
     * @param string $dsBegin YYYYMMDD period's begin datestamp
     * @param string $treeType [compressed|plain]
     * @return int
     */
    private function getCalcId($dsBegin, $treeType)
    {
        $codeRegular = $codeForecast = '';
        if ($treeType == OptionTreeType::VAL_PLAIN) {
            $codeRegular = Cfg::CODE_TYPE_CALC_PV_WRITE_OFF;
            $codeForecast = Cfg::CODE_TYPE_CALC_FORECAST_PLAIN;
        } elseif ($treeType == OptionTreeType::VAL_COMPRESS) {
            $codeRegular = Cfg::CODE_TYPE_CALC_COMPRESS_PHASE1;
            $codeForecast = Cfg::CODE_TYPE_CALC_FORECAST_PHASE1;
        }
        $query = $this->qGetId->build();
        $conn = $query->getConnection();
        $bind = [
            QGetId::BND_DS_BEGIN => $dsBegin,
            QGetId::BND_TYPE_CODE_REGULAR => $codeRegular,
            QGetId::BND_TYPE_CODE_FORECAST => $codeForecast
        ];
        $result = $conn->fetchOne($query, $bind);
        return $result;
    }

    public function getData()
    {
        /* get Web UI search criteria */
        $search = $this->getSearchCriteria();
        /* analyze request and compose bind variables array */
        $bind = $this->getBind();
        /* get build queries and fetch data for total count and items */
        $total = $this->gridQueryBuilder->getTotal($search, $bind);
        $items = $this->gridQueryBuilder->getItems($search, $bind);
        $result = [
            static::JSON_A_TOTAL_RECORDS => $total,
            static::JSON_A_ITEMS => $items
        ];
        return $result;
    }
}


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

namespace cascade\components\db\behaviors;

use cascade\components\types\Relationship;
use Yii;

/**
 * PrimaryRelation [[@doctodo class_description:cascade\components\db\behaviors\PrimaryRelation]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class PrimaryRelation extends \canis\db\behaviors\PrimaryRelation
{
    /**
     * @var [[@doctodo var_type:_relationship]] [[@doctodo var_description:_relationship]]
     */
    protected $_relationship;

    /**
     * @inheritdoc
     */
    public function handlePrimary($role)
    {
        if (!parent::handlePrimary($role)) {
            return false;
        }
        if (!isset(Yii::$app->collectors['types'])) {
            return false;
        }
        if (empty($this->relationship)) {
            return false;
        }

        return $this->relationship->handlePrimary !== false;
    }

    /**
     * Get relationship.
     *
     * @return [[@doctodo return_type:getRelationship]] [[@doctodo return_description:getRelationship]]
     */
    public function getRelationship()
    {
        if (is_null($this->_relationship)) {
            $parentObject = $this->owner->getParentObject(false);
            $childObject = $this->owner->getChildObject(false);
            if ($parentObject && $childObject) {
                if (empty($parentObject->objectTypeItem) || empty($childObject->objectTypeItem)) {
                    return false;
                }
                $this->_relationship = Relationship::getOne($parentObject->objectTypeItem, $childObject->objectTypeItem);
            }
        }

        return $this->_relationship;
    }

    /**
     * Set relationship.
     *
     * @param cascade\components\types\Relationship $value [[@doctodo param_description:value]]
     */
    public function setRelationship(Relationship $value)
    {
        $this->_relationship = $value;
    }
}


<?php
namespace core\manage\logic;

use cms\Logic;
use cms\Upload;
use think\Config;
use lookfeel\common\Format;
use lookfeel\file\FileInfo;

class FileLogic extends Logic
{

    /**
     * 获取文件
     *
     * @param string $hash
     * @return string
     */
    public function getFile($hash)
    {
        $map = array(
            'file_hash' => $hash
        );
        $file = $this->model->field('file_url')
            ->where($map)
            ->find();
        return $file ? $file['file_url'] : null;
    }

    /**
     * 保存文件
     *
     * @param unknown $hash
     * @param unknown $url
     * @param string $type
     * @param number $size
     * @return number
     */
    public function addFile($hash, $url, $type = '', $size = 0)
    {
        // 后缀
        $arr = explode('.', $url);
        $ext = end($arr);

        // 类型
        $type || $type = $this->getUploadDriver()->getFileType($ext);

        // 大小
        $size || $size = FileInfo::getFileSize($url);

        $data = array(
            'file_hash' => $hash,
            'file_type' => $type,
            'file_ext' => $ext,
            'file_size' => $size,
            'file_url' => $url,
            'create_time' => time()
        );
        return $this->model->insert($data);
    }

    /**
     * 删除文件
     *
     * @param number $file_id
     * @return array
     */
    public function delFile($file_id)
    {
        $file = $this->model->get($file_id);
        if (empty($file)) {
            return Format::formatResult(0, '文件不存在');
        }

        // 删除记录
        $this->model->del($file_id);

        // 删除文件
        $upload_driver = $this->getUploadDriver();
        return $upload_driver->deleteFile($file['file_url']);
    }

    /**
     * 上传类型选择
     *
     * @return array
     */
    public function getUploadTypeSelect()
    {
        $upload_type = $this->getUploadDriver()->getUploadType();
        $upload_type_select = [];
        foreach ($upload_type as $co => $vo) {
            $upload_type_select[] = [
                'name' => $co,
                'value' => $co
            ];
        }
        return $upload_type_select;
    }

    /**
     * 上传驱动
     *
     * @return \app\common\driver\Upload
     */
    public function getUploadDriver()
    {
        if (empty($this->upload_driver)) {
            $upload_driver = Config::get('upload_driver');
            if ($upload_driver == Upload::TYPE_LOCAL) {
                $option = Config::get('upload_local');
            } else {
                $option = Config::get('upload_upyun');
            }
            $this->upload_driver = Upload::create($option, $upload_driver);

            // 检查文件
            $this->upload_driver->onCheck = function ($data) {
                return FileLogic::instance()->getFile($data['hash']);
            };

            // 上传成功
            $this->upload_driver->onSuccess = function ($data) {
                FileLogic::instance()->addFile($data['hash'], $data['url'], $data['type'], FileInfo::getFileSize($data['path']));
            };
        }
        return $this->upload_driver;
    }
}


<?php

/*
 * Chill is a software for social workers
 *
 * Copyright (C) 2014, Champs Libres Cooperative SCRLFS, <http://www.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\PersonBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes;
use Chill\MainBundle\Entity\Address;

/**
 * Load people into database
 *
 * @author Julien Fastré <julien arobase fastre point info>
 * @author Marc Ducobu <marc@champs-libres.coop>
 */
class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{

    use \Symfony\Component\DependencyInjection\ContainerAwareTrait;

    protected $faker;

    public function __construct()
    {
        $this->faker = \Faker\Factory::create('fr_FR');
    }

    public function prepare()
    {
        //prepare days, month, years
        $y = 1950;
        do {
            $this->years[] = $y;
            $y = $y +1;
        } while ($y >= 1990);

        $m = 1;
        do {
            $this->month[] = $m;
            $m = $m +1;
        } while ($m >= 12);

        $d = 1;
        do {
            $this->day[] = $d;
            $d = $d + 1;
        } while ($d <= 28);
    }

    public function getOrder()
    {
        return 10000;
    }

    public function load(ObjectManager $manager)
    {
        $this->loadRandPeople($manager);
        $this->loadExpectedPeople($manager);

        $manager->flush();
    }

    public function loadExpectedPeople(ObjectManager $manager)
    {
        echo "loading expected people...\n";

        foreach ($this->peoples as $person) {
            $this->addAPerson($this->fillWithDefault($person), $manager);
        }
    }

    public function loadRandPeople(ObjectManager $manager)
    {
        echo "loading rand people...\n";

        $this->prepare();

        $chooseLastNameOrTri = array('tri', 'tri', 'name', 'tri');

        $i = 0;

        do {
            $i++;

            $sex = $this->genders[array_rand($this->genders)];

            if ($chooseLastNameOrTri[array_rand($chooseLastNameOrTri)] === 'tri' ) {
                $length = rand(2, 3);
                $lastName = '';
                for ($j = 0; $j <= $length; $j++) {
                    $lastName .= $this->lastNamesTrigrams[array_rand($this->lastNamesTrigrams)];
                }
                $lastName = ucfirst($lastName);
            } else {
                $lastName = $this->lastNames[array_rand($this->lastNames)];
            }

            if ($sex === Person::MALE_GENDER) {
                $firstName = $this->firstNamesMale[array_rand($this->firstNamesMale)];
            } else {
                $firstName = $this->firstNamesFemale[array_rand($this->firstNamesFemale)];
            }

            // add an address on 80% of the created people
            if (rand(0,100) < 80) {
                $address = $this->getRandomAddress();
                // on 30% of those person, add multiple addresses
                if (rand(0,10) < 4) {
                    $address = array(
                       $address,
                       $this->getRandomAddress()
                    );
                }
            } else {
                $address = null;
            }

            $person = array(
                'FirstName' => $firstName,
                'LastName' => $lastName,
                'Gender' => $sex,
                'Nationality' => (rand(0,100) > 50) ? NULL: 'BE',
                'center' => (rand(0,1) == 0) ? 'centerA': 'centerB',
                'Address' => $address,
                'maritalStatus' => $this->maritalStatusRef[array_rand($this->maritalStatusRef)]
            );

            $this->addAPerson($this->fillWithDefault($person), $manager);

        } while ($i <= 100);
    }

    /**
     * fill a person array with default value
     *
     * @param string[] $specific
     */
    private function fillWithDefault(array $specific)
    {
        return array_merge(array(
                'Birthdate' => "1960-10-12",
                'PlaceOfBirth' => "Ottignies Louvain-La-Neuve",
                'Gender' => Person::MALE_GENDER,
                'Email' => "Email d'un ami: roger@tt.com",
                'CountryOfBirth' => 'BE',
                'Nationality' => 'BE',
                'CFData' => array(),
                'Address' => null
            ), $specific);
    }

    /**
     * create a new person from array data
     *
     * @param array $person
     * @param ObjectManager $manager
     * @throws \Exception
     */
    private function addAPerson(array $person, ObjectManager $manager)
    {
        $p = new Person();

        foreach ($person as $key => $value) {
            switch ($key) {
                case 'CountryOfBirth':
                case 'Nationality':
                    $value = $this->getCountry($value);
                    break;
                case 'Birthdate':
                    $value = new \DateTime($value);
                    break;
                case 'center':
                case 'maritalStatus':
                    $value = $this->getReference($value);
                    break;
            }

            //try to add the data using the setSomething function,
            // if not possible, fallback to addSomething function
            if (method_exists($p, 'set'.$key)) {
                call_user_func(array($p, 'set'.$key), $value);
            } elseif (method_exists($p, 'add'.$key)) {
                // if we have a "addSomething", we may have multiple items to add
                // so, we set the value in an array if it is not an array, and
                // will call the function addSomething multiple times
                if (!is_array($value)) {
                    $value = array($value);
                }

                foreach($value as $v) {
                    if ($v !== NULL) {
                        call_user_func(array($p, 'add'.$key), $v);
                    }
                }

            }
        }

        $manager->persist($p);
        echo "add person'".$p->__toString()."'\n";
    }

    /**
     * Creata a random address
     *
     * @return Address
     */
    private function getRandomAddress()
    {
        return (new Address())
                      ->setStreetAddress1($this->faker->streetAddress)
                      ->setStreetAddress2(
                            rand(0,9) > 5 ? $this->faker->streetAddress : ''
                            )
                      ->setPostcode($this->getReference(
                                LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)]
                            ))
                      ->setValidFrom($this->faker->dateTimeBetween('-5 years'))
              ;
    }

    private function getCountry($countryCode)
    {
        if ($countryCode === NULL) {
            return NULL;
        }
        return $this->container->get('doctrine.orm.entity_manager')
              ->getRepository('ChillMainBundle:Country')
              ->findOneByCountryCode($countryCode);
    }

    private $maritalStatusRef = ['ms_single', 'ms_married', 'ms_widow', 'ms_separat',
        'ms_divorce', 'ms_legalco', 'ms_unknown'];

    private $firstNamesMale = array("Jean", "Mohamed", "Alfred", "Robert",
        "Compère", "Jean-de-Dieu",
        "Charles", "Pierre", "Luc", "Mathieu", "Alain", "Etienne", "Eric",
        "Corentin", "Gaston", "Spirou", "Fantasio", "Mahmadou", "Mohamidou",
        "Vursuv" );
    private $firstNamesFemale = array("Svedana", "Sevlatina","Irène", "Marcelle",
        "Corentine", "Alfonsine","Caroline","Solange","Gostine", "Fatoumata",
        "Groseille", "Chana", "Oxana", "Ivana");

    private $lastNames = array("Diallo", "Bah", "Gaillot");
    private $lastNamesTrigrams = array("fas", "tré", "hu", 'blart', 'van', 'der', 'lin', 'den',
        'ta', 'mi', 'gna', 'bol', 'sac', 'ré', 'jo', 'du', 'pont', 'cas', 'tor', 'rob', 'al',
        'ma', 'gone', 'car',"fu", "ka", "lot", "no", "va", "du", "bu", "su",
        "lo", 'to', "cho", "car", 'mo','zu', 'qi', 'mu');

    private $genders = array(Person::MALE_GENDER, Person::FEMALE_GENDER);

    private $years = array();

    private $month = array();

    private $day = array();

    private $peoples = array(
        array(
            'FirstName' => "Depardieu",
            'LastName' => "Gérard",
            'Birthdate' => "1948-12-27",
            'PlaceOfBirth' => "Châteauroux",
            'Gender' => Person::MALE_GENDER,
            'CountryOfBirth' => 'FR',
            'Nationality' => 'RU',
            'center' => 'centerA',
            'maritalStatus' => 'ms_divorce'
        ),
       array(
          //to have a person with same firstname as Gérard Depardieu
            'FirstName' => "Depardieu",
            'LastName' => "Jean",
            'Birthdate' => "1960-10-12",
            'CountryOfBirth' => 'FR',
            'Nationality' => 'FR',
            'center' => 'centerA',
            'maritalStatus' => 'ms_divorce'
        ),
       array(
          //to have a person with same birthdate of Gérard Depardieu
          'FirstName' => 'Van Snick',
          'LastName' => 'Bart',
          'Birthdate' => '1948-12-27',
          'center' => 'centerA',
          'maritalStatus' => 'ms_legalco'
       ),
       array(
          //to have a woman with Depardieu as FirstName
          'FirstName' => 'Depardieu',
          'LastName' => 'Charline',
          'Gender' => Person::FEMALE_GENDER,
          'center' => 'centerA',
          'maritalStatus' => 'ms_legalco'
       ),
       array(
          //to have a special character in lastName
          'FirstName' => 'Manço',
          'LastName' => 'Étienne',
          'center' => 'centerA',
          'maritalStatus' => 'ms_unknown'
       )
    );
}


<?php
namespace Ecompassaro\Login;

use Ecompassaro\Autenticacao\Autenticacao;
use Ecompassaro\Autenticacao\Manager as AutenticacaoManager;
use Ecompassaro\Notificacao\Notificacao;
use Ecompassaro\Notificacao\NotificacoesContainerTrait;
use Zend\Authentication\AuthenticationService;
use Ecompassaro\Acesso\ViewModel as AcessoViewModel;
use Ecompassaro\Acesso\Acesso;

/**
 * Gerador da estrutura da página de login
 */
class ViewModel extends AcessoViewModel
{
    use NotificacoesContainerTrait;

    const MENSAGEM_ERRO_LOGIN_INVALIDO = 'Usuario ou senha inválidos.';

    private $authenticationService;
    private $autenticacaoManager;
    private $form;

    /**
     * Injeta dependências
     * @param \Acesso\Acesso
     * @param \AutenticacaoManager $autenticacaoManager
     * @param LoginForm $form
     */
    public function __construct(Acesso $acesso, AuthenticationService $authenticationService, AutenticacaoManager $autenticacaoManager, Form $form)
    {
        parent::__construct($acesso);
        $this->authenticationService = $authenticationService;
        $this->autenticacaoManager = $autenticacaoManager;
        $this->form = $form;
        $this->variables['formulario'] = $form;
    }

    /**
     * Adiciona Mensagem de erro
     * @return LoginViewModel
     */
    private function addMensagemErro()
    {
       return $this->addNotificacao(new Notificacao(Notificacao::TIPO_ERRO, self::MENSAGEM_ERRO_LOGIN_INVALIDO));
    }

    /**
     * Obtem o formulário de login
     * @return LoginForm
     */
    public function getFormulario($routeRedirect = null)
    {
        return $this->form->setRouteRedirect($routeRedirect);
    }

    /**
     * Verifica se existe um login com o usuário e senha informados
     * Se não existir além de retornar false seta uma mensagem de erro no atributo
     * da classe.
     * @param string $usuario
     * @param string $senha
     * @return boolean
     */
    public function validaLogin($dados)
    {
        $this->getFormulario()->setData($dados);

        if ($this->getFormulario()->isValid()) {
            $autenticacao = new Autenticacao();
            $autenticacao->exchangeArray($this->getFormulario()->getData());

            $resultadoAutenticacao = $this->autenticacaoManager->autenticar($autenticacao);

            if (!$resultadoAutenticacao->isValid()) {
                $this->addMensagemErro();
                return false;
            }

            return true;
        }

        return false;
    }

    public function limparAutenticacao()
    {
        $this->authenticationService->clearIdentity();
    }
}


<?php

/**
 * Contains an individual row of a Benri_Db_Table object.
 *
 * This is a class that contains an individual row of a Benri_Db_Table object.
 * When you run a query against a Table class, the result is returned in a set
 * of Benri_Db_Table_Row objects. You can also use this object to create new
 * rows and add them to the database table.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.db.table.row.html Zend_Db_Table_Row
 */
class Benri_Db_Table_Row extends Zend_Db_Table_Row
{
    /**
     * This means a required resource does not exist.
     */
    const ERR_MISSING         = 'missing';

    /**
     * This means a required field on a resource has not been set.
     */
    const ERR_MISSING_FIELD   = 'missing_field';

    /**
     * This means the formatting of a field is invalid. The documentation for
     * that resource should be able to give you more specific information.
     */
    const ERR_INVALID         = 'invalid';

    /**
     * This means another resource has the same value as this field. This can
     * happen in resources that must have some unique key (such as Label or
     * Locale names).
     */
    const ERR_ALREADY_EXISTS  = 'already_exists';

    /**
     * This means an uncommon error.
     */
    const ERR_UNCATEGORIZED   = 'uncategorized';

    /**
     * For the cases this model is set as read only.
     */
    const ERR_READ_ONLY       = 'read only';

    /**
     * For the rare case an exception occurred and we couldn't recover.
     */
    const ERR_UNKNOWN         = 'unknown';

    /**
     * Hold the errors while saving this object.
     *
     * @var array
     */
    private $_errors = [];

    /**
     * Returns the errors found while saving this object.
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->_errors;
    }

    /**
     * Returns true if the given column was modified since this object was
     * loaded from the database.
     *
     * @param string $column
     * @return bool
     */
    public function isDirty($column)
    {
        return array_key_exists($column, $this->_modifiedFields);
    }

    /**
     * Returns true if this is a new record on the database.
     *
     * @return bool
     */
    public function isNewRecord()
    {
        return empty($this->_cleanData);
    }

    /**
     * @param $input
     * @return Benri_Db_Table_Row
     */
    public function normalizeInput($input)
    {
        foreach ($input as $column => $value) {
            if ($this->offsetExists($column)) {
                $this->__set($column, $value);
            }
        }

        return $this;
    }

    /**
     * Reset the value to the given column to its defaults.
     *
     * @param string $column
     */
    final public function reset($column)
    {
        if ($this->isDirty($column)) {
            $this->_data[$column] = $this->_cleanData[$column];
            unset($this->_modifiedFields[$column]);
        }
    }

    /**
     * Saves the properties to the database.
     *
     * This performs an intelligent insert/update, and reloads the properties
     * with fresh data from the table on success.
     *
     * @return mixed The primary key value(s), as an associative array if the
     *  key is compound, or a scalar if the key is single-column
     */
    final public function save()
    {
        $this->checkReadOnly();

        /*
         * Allows pre-save logic to be applied to any row.
         *
         * Zend_Db_Table_Row only uses to do it on _insert OR _update,
         * here we can use the very same rules to be applied in both methods.
         */
        $this->_save();

        if (count($this->_errors)) {
            throw new Zend_Db_Table_Row_Exception('This row contain errors.');
        }

        foreach ($this->_data as $column => &$value) {
            if ($value instanceof DateTime) {
                // Should replace with Benri_Util_DateTime.
                if (!($value instanceof Benri_Util_DateTime)) {
                    $value = new Benri_Util_DateTime($value->format('U'));
                }

                $value->setFormat('Y-m-d H:i:s');
            }
        }

        if ($this->isNewRecord()) {
            if ($this->offsetExists('created_at')) {
                $this->created_at = new Benri_Util_DateTime();
                $this->created_at->setFormat('Y-m-d H:i:s');
            }
        }

        if ($this->offsetExists('updated_at')) {
            $this->updated_at = new Benri_Util_DateTime();
            $this->updated_at->setFormat('Y-m-d H:i:s');
        }

        /// Saves the properties to the database
        parent::save();

        /// Run post-SAVE logic
        $this->_postSave();

        /// chain
        return $this;
    }

    /**
     * Convert this object to a JSON string.
     *
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->toArray(), JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
    }

    /**
     * @return mixed The primary key value(s), as an associative array if the
     *  key is compound, or a scalar if the key is single-column
     */
    final protected function _doInsert()
    {
        /// A read-only row cannot be saved.
        $this->checkReadOnly();

        /// Run pre-INSERT logic
        $this->_insert();

        if (count($this->_errors)) {
            throw new Zend_Db_Table_Row_Exception('This row contain errors.');
        }

        return parent::_doInsert();
    }

    /**
     * @return mixed The primary key value(s), as an associative array if the
     *  key is compound, or a scalar if the key is single-column
     */
    final protected function _doUpdate()
    {
        /// A read-only row cannot be saved.
        $this->checkReadOnly();

        /// Run pre-UPDATE logic
        $this->_update();

        if (count($this->_errors)) {
            throw new Zend_Db_Table_Row_Exception('This row contain errors.');
        }

        return parent::_doUpdate();
    }

    /**
     * Allows post-save logic to be applied to row.
     *
     * @throws Zend_Db_Table_Row_Exception
     */
    protected function _postSave()
    {
    }

    /**
     * All error objects have field and code properties so that your client
     * can tell what the problem is.
     *
     * If resources have custom validation errors, they should be documented
     * with the resource.
     *
     * @param string $field The erroneous field or column
     * @param string $code One of the ERR_* codes contants
     * @param string $title A title for this error
     * @param string $message A friendly message
     * @return Benri_Db_Table_Row
     */
    protected function _pushError($field, $code, $title, $message = '')
    {
        $this->_errors[] = [
            'field'     => $field,
            'message'   => $message,
            'code'      => $code,
            'title'     => $title,
        ];

        return $this;
    }

    /**
     * Allows pre-save logic to be applied to row.
     *
     * @throws Zend_Db_Table_Row_Exception
     */
    protected function _save()
    {
    }

    /**
     * Constructor.
     *
     * Supported params for $config are:-
     * - table       = class name or object of type Zend_Db_Table_Abstract
     * - data        = values of columns in this row.
     *
     * @param array $config OPTIONAL Array of user-specified config options
     * @throws Zend_Db_Table_Row_Exception
     */
    final public function __construct(array $config = [])
    {
        if (isset($config['table']) && $config['table'] instanceof Zend_Db_Table_Abstract) {
            $this->_table      = $config['table'];
            $this->_tableClass = get_class($this->_table);
        } elseif ($this->_tableClass !== null) {
            $this->_table = $this->_getTableFromString($this->_tableClass);
        }

        if (isset($config['data'])) {
            if (!is_array($config['data'])) {
                throw new Zend_Db_Table_Row_Exception('Data must be an array.');
            }

            $this->setFromArray($this->_data = $config['data']);
            $this->_modifiedFields = [];
        }

        if (isset($config['stored']) && true === $config['stored']) {
            $this->_cleanData = $this->_data;
        }

        if (isset($config['readOnly']) && true === $config['readOnly']) {
            $this->setReadOnly(true);
        }

        // Retrieve primary keys from table schema
        if (($table = $this->_getTable())) {
            $info           = $table->info();
            $this->_primary = (array) $info['primary'];
        }

        $this->init();
    }

    /**
     * Returns the column/value data as an array.
     *
     * @return array
     */
    public function toArray()
    {
        $data = (array) $this->_data;

        foreach ($data as $column => $value) {
            $data[$column] = $this->__get($column);
        }

        return $data;
    }

    /**
     * Retrieve a row field value.
     *
     * @param string The user-specified column name.
     * @return mixed The corresponding column value.
     * @throws Zend_Db_Table_Row_Exception if the $columnName is not a column
     *      in the row.
     * @internal
     */
    public function __get($columnName)
    {
        $getter = Benri_Util_String::camelize($columnName, true);

        if (method_exists($this, $getter = "get{$getter}")) {
            return call_user_func_array([$this, $getter], []);
        }

        return parent::__get($columnName);
    }

    /**
     * Set a row field value.
     *
     * @internal
     */
    public function __set($columnName, $value)
    {
        $setter = Benri_Util_String::camelize($columnName, true);

        if (method_exists($this, $setter = "set{$setter}")) {
            $value = call_user_func_array([$this, $setter], [$value]);
        }

        return parent::__set($columnName, $value);
    }

    /**
     * Check if this model is set as a read-only model.
     *
     * @return bool
     */
    private function checkReadOnly()
    {
        if (true === $this->_readOnly) {
            $this->_pushError(
                '',
                self::ERR_READ_ONLY,
                'This row has been marked read-only'
            );

            return false;
        }

        return true;
    }
}


<?php
namespace HtSettingsModule\Service;

use HtSettingsModule\Mapper\SettingsMapperInterface;
use HtSettingsModule\Options\ModuleOptionsInterface;

class SettingsProvider implements SettingsProviderInterface, CacheManagerAwareInterface
{
    /**
     * @var SettingsMapperInterface
     */
    protected $settingsMapper;

    /**
     * @var ModuleOptionsInterface
     */
    protected $options;

    /**
     * @var NamespaceHydratorProviderInerface
     */
    protected $namespaceHydratorProvider;

    use CacheManagerAwareTrait;

    /**
     * Constructor
     *
     * @param ModuleOptionsInterface            $options
     * @param SettingsMapperInterface           $settingsMapper
     * @param NamespaceHydratorProviderInerface $namespaceHydratorProvider
     */
    public function __construct(
        ModuleOptionsInterface $options,
        SettingsMapperInterface $settingsMapper,
        NamespaceHydratorProviderInerface $namespaceHydratorProvider
    )
    {
        $this->options = $options;
        $this->settingsMapper = $settingsMapper;
        $this->namespaceHydratorProvider = $namespaceHydratorProvider;
    }

    /**
     * {@inheritDoc}
     */
    public function getSettings($namespace)
    {
        if ($this->getCacheOptions()->isEnabled()) {
            if ($this->cacheManager->settingsExists($namespace)) {
                return $this->cacheManager->get($namespace);
            }
            $settings = $this->getSettingsFromRealSource($namespace);
            $this->cacheManager->create($namespace, $settings);

            return $settings;
        }

        return $this->getSettingsFromRealSource($namespace);
    }

    /**
     * {@inheritDoc}
     */
    public function getSettingsArray($namespace)
    {
        $resultSet = $this->settingsMapper->findByNamespace($namespace);
        $arraySettings = [];
        foreach ($resultSet as $parameter) {
            $arraySettings[$parameter->getName()] = $parameter->getValue();
        }

        return $arraySettings;
    }

    /**
     * Gets settings from real source, most probably from database
     *
     * @param  string $namespace
     * @return object
     */
    protected function getSettingsFromRealSource($namespace)
    {
        $arraySettings = $this->getSettingsArray($namespace);
        $namespaceOptions = $this->options->getNamespaceOptions($namespace);
        $entity = clone($namespaceOptions->getEntityPrototype());
        if (!empty($arraySettings)) {
            $hydrator = $this->namespaceHydratorProvider->getHydrator($namespace);
            $entity = $hydrator->hydrate($arraySettings, $entity);
        }

        return $entity;
    }

    /**
     * Gets cacheOptions
     *
     * @return \HtSettingsModule\Options\CacheOptionsInterface
     */
    public function getCacheOptions()
    {
        return $this->options->getCacheOptions();
    }
}


<?php
namespace Devedge\XmlRpc\Server;

class XmlRpcBuilder extends \Devedge\XmlRpc\Common\XmlRpcBuilder
{
    /**
     * creates a xml-rpc fault
     *
     * @param int $code
     * @param string $message
     * @return string
     */
    public static function createFault($code, $message)
    {
        $response = new \SimpleXMLElement("<methodResponse></methodResponse>");
        $struct = $response->addChild("fault")->addChild("value")->addChild("struct");

        $member = $struct->addChild("member");
        $member->addChild("name", "faultCode");
        $member->addChild("value")->addChild("int", $code);

        $member = $struct->addChild("member");
        $member->addChild("name", "faultString");
        $member->addChild("value", $message);

        return $response->asXML();
    }

    /**
     * @param mixed $data
     * @return string
     * @throws \Exception
     */
    public static function createResponse($data)
    {
        $response = new \SimpleXMLElement("<methodResponse></methodResponse>");
        $params = $response->addChild("params");
        $param = $params->addChild("param");
        $value = $param->addChild("value");
        $dataElement = static::typeByGuess($data);
        $value->addChild($dataElement->getName());
        $value->{$dataElement->getName()} = $dataElement;

        return $response->asXML();
    }
}


<?php
namespace eMacros\Runtime\Symbol;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;
use eMacros\Environment\Environment;
use eMacros\Symbol;

class SymbolSet implements Applicable {
	/**
	 * Defines a symbol value
	 * Usage: (sym "value") (sym "counter" 0)
	 * Returns: NULL
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (count($arguments) == 0) throw new \BadFunctionCallException("SymbolSet: No parameters found.");
		$ref = $arguments[0]->evaluate($scope);
		if (!is_string($ref) || empty($ref)) throw new \InvalidArgumentException("SymbolSet: Symbol must be specified as a non-empty string.");
		Symbol::validateSymbol($ref);
		$value = (count($arguments) > 1) ? $arguments[1]->evaluate($scope) : null;
		$scope->symbols[$ref] = $value;
	}
}
?>


<?php

/**
 * Controller to test
 *
 * @category  	src
 * @package   	src\Demo\Controller
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */

namespace Venus\src\Demo\Controller;

use \Venus\src\Demo\common\Controller as Controller;

/**
 * Controller to test
 *
 * @category  	src
 * @package   	src\Demo\Controller
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */

class Home extends Controller {

	/**
	 * Constructor
	 *
	 * @access public
	 * @return object
	 */

	public function __construct() {

		parent::__construct();
	}

	/**
	 * the main page
	 *
	 * @access public
	 * @return void
	 */

	public function show() {

		$response = new \Venus\lib\Response();

		$response->setContent('
Hello world!
');
		$response->setStatusCode(\Venus\lib\Response::HTTP_OK);
		$response->headers->set('Content-Type', 'text/html');
		$response->send();
	}
}


<?php

namespace nadir2\core;

/**
 * This is the class of abstract web-controller. Despite the fact that no one method
 * declared as abstract, the 'abstract' modifier is set a specially to exclude the
 * possibility of creating an instance of the class.
 * @author Leonid Selikhov
 */
abstract class AbstractWebCtrl extends AbstractCtrl
{
    /** @var \nadir2\core\Request The request object. */
    protected $request = null;

    /** @var \nadir2\core\View The view object. */
    protected $view = null;

    /** @var \nadir2\core\Layout The layout object. */
    protected $layout = null;

    /**
     * The constructor assigns object with request object and possibly with
     * the view object (full or partial).
     * @param \nadir2\core\Request $request The request object.
     * @param \nadir2\core\AbstractView|null $view The view object.
     */
    public function __construct(Request $request, AbstractView $view = null)
    {
        $this->request = $request;
        if ($view instanceof View) {
            $this->view = $view;
        } elseif ($view instanceof Layout) {
            $this->layout = $view;
            $this->view   = $this->layout->view;
        }
    }

    /**
     * It returns the object of assigned request.
     * @return \nadir2\core\Request|null.
     */
    public function getRequest(): ?Request
    {
        return $this->request;
    }

    /**
     * It returns the object of associated view.
     * @return \nadir2\core\View|null.
     */
    protected function getView(): ?View
    {
        return $this->view;
    }

    /**
     * It's used for binding the controller with a view (both with the default
     * and with corresponding another controller).
     * @param string $ctrlName The controller name.
     * @param string $actionName The action name (without prefix action).
     * @return void.
     */
    protected function setView(string $ctrlName, string $actionName): void
    {
        $this->view = ViewFactory::createView($actionName, $ctrlName);
        if (!is_null($this->layout)) {
            $this->layout->view = $this->view;
        }
    }

    /**
     * It returns the object of associated layout.
     * @return \nadir2\core\Layout|null.
     */
    protected function getLayout(): ?Layout
    {
        return $this->layout;
    }

    /**
     * It assosiates the controller with the layout.
     * @param string $layoutName The layout name.
     * @return void
     * @throws \nadir2\core\Exception It's thrown if the layout doesn't contain
     * a view.
     */
    protected function setLayout(string $layoutName): void
    {
        if (is_null($this->view)) {
            throw new Exception("It's unable to set Layout without View.");
        }
        $this->layout = ViewFactory::createLayout($layoutName, $this->view);
    }

    /**
     * It renders the page both full (layout with view) and partial (view only).
     * @return void
     * @throws \nadir2\core\Exception It's thrown if the view is empty.
     */
    protected function render(): void
    {
        if (!is_null($this->layout)) {
            $this->layout->render();
        } elseif (!is_null($this->view)) {
            $this->partialRender();
        } else {
            throw new Exception("It's unable to render with empty View.");
        }
    }

    /**
     * The method provides partial rendering (view without layout).
     * @return void
     */
    protected function partialRender(): void
    {
        $this->view->render();
    }

    /**
     * It renders the page with JSON-formatted data.
     * @param mixed $data The input data.
     * @return void
     */
    protected function renderJson($data): void
    {
        echo json_encode($data, \JSON_UNESCAPED_UNICODE);
    }

    /**
     * The method redirects to the URL, which passed as param. The HTTP-code is
     * 302 as default. The method unconditional completes the script execution,
     * the code after it will not be executed.
     * @param string $uri
     * @param bool $isPermanent The flag of permanent redirect.
     * @return void
     */
    protected function redirect(string $uri, bool $isPermanent = false): void
    {
        $nCode = $isPermanent ? 301 : 302;
        Headers::getInstance()
            ->addByHttpCode($nCode)
            ->add('Location: '.$uri)
            ->run();
        exit;
    }
}


<?php

namespace nadir2\core;

/**
 * The class provides the centralized access to the parameters of input request.
 * @author Leonid Selikhov
 */
class Request
{
    /** @var array It contains the raw request body. */
    private $rawBody = null;

    /**
     * The constructor inits the private properties of the object.
     * @return self.
     */
    public function __construct()
    {
        $this->rawBody = @file_get_contents('php://input');
    }

    /**
     * The method returns the server parameter value by the key. It's wrapper over
     * the filter_input() function.
     * @param string $name Name of a variable to get.
     * @param int $filter
     * @param mixed $options Associative array of options or bitwise disjunction
     * of flags. If filter accepts options, flags can be provided in "flags"
     * field of array.
     * @return mixed Value of the requested variable on success, false if the filter
     * fails, or null if the variable is not set.
     */
    public function getServerParam(
        string $name,
        int $filter = \FILTER_DEFAULT,
        $options = null
    ) {
        // Can be useful if FastCGI has strange side-effects with unexpected null
        // values when using INPUT_SERVER and INPUT_ENV with this function.
        //return isset($_SERVER[$name]) ? filter_var($_SERVER[$name], $filter, $options)
        //    : null;
        return filter_input(\INPUT_SERVER, $name, $filter, $options);
    }

    /**
     * The method returns the raw body of the request as string, which was gotten
     * from the input stream.
     * @return string|null.
     */
    public function getRawBody(): ?string
    {
        return $this->rawBody;
    }

    /**
     * The method returns the parameter value of request by the passed key. It's
     * wrapper over the filter_var() function.
     * @param string $name Name of a variable to get.
     * @param int $filter
     * @param mixed $options Associative array of options or bitwise disjunction
     * of flags. If filter accepts options, flags can be provided in "flags"
     * field of array.
     * @return mixed Value of the requested variable on success, false if the filter
     * fails, or null if the variable is not set.
     */
    public function getParam(
        string $name,
        int $filter = \FILTER_DEFAULT,
        $options = null
    ) {
        // Can be useful when INPUT_REQUEST is implemented for the filter_input()
        // function.
        //return filter_input(\INPUT_REQUEST, $name, $filter, $options);
        return isset($_REQUEST[$name]) ? filter_var($_REQUEST[$name], $filter, $options)
            : null;
    }

    /**
     * It returns the request HTTP-method.
     * @return string|null
     */
    public function getMethod(): ?string
    {
        return $this->getServerParam('REQUEST_METHOD', \FILTER_SANITIZE_STRING);
    }

    /**
     * It returns the array of request headers.
     * @return string[]
     */
    public function getAllHeaders()
    {
        return getallheaders();
    }

    /**
     * It returns the header by passed name. The search is case-insensitive.
     * @param string $name
     * @return string|null
     */
    public function getHeader(string $name): ?string
    {
        $name = strtolower($name);
        foreach ($this->getAllHeaders() as $key => $value) {
            if (strtolower($key) === $name) {
                return $value;
            }
        }
        return null;
    }

    /**
     * It returns cookie value by name if it exists and matches predefined filter.
     * @param string $name Cookie name.
     * @return string|false|null
     */
    public function getCookie(string $name)
    {
        return filter_input(\INPUT_COOKIE, $name, \FILTER_SANITIZE_STRING);
    }

    /**
     * The method returns the associated array of cookies.
     * @return mixed[]|null
     */
    public function getAllCookies(): ?array
    {
        return filter_input_array(\INPUT_COOKIE, array_combine(
            array_keys($_COOKIE),
            array_fill(0, count($_COOKIE), \FILTER_SANITIZE_STRING)
        ));
    }

    /**
     * It returns the URL path of the request.
     * @return string|null
     */
    public function getUrlPath(): ?string
    {
        $uri = $this->getServerParam('REQUEST_URI', \FILTER_SANITIZE_URL);
        if (!is_null($uri)) {
            return parse_url($uri, \PHP_URL_PATH);
        }
        return null;
    }

    /**
     * It checks if the request is an ajax request.
     * @return boolean.
     */
    public function isAjax(): bool
    {
        $param = $this->getServerParam('HTTP_X_REQUESTED_WITH', \FILTER_SANITIZE_STRING);
        return !is_null($param) && strtolower($param) === 'xmlhttprequest';
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\Reminder\Marker;

use Doctrine\DBAL\Connection;

final class DatabaseMarker implements MarkerInterface
{
    private $connection;
    private $table;

    public function __construct(Connection $connection, string $table)
    {
        $this->connection = $connection;
        $this->table = $table;
    }

    /**
     * {@inheritdoc}
     */
    public function isMarked(string $id): bool
    {
        $count = $this->connection
            ->createQueryBuilder()
            ->select('count(marker)')
            ->from($this->table, 'marker')
            ->where('marker.id = :id')
            ->setParameter('id', $id)
            ->execute()
            ->fetchColumn();

        return $count > 0;
    }

    /**
     * {@inheritdoc}
     */
    public function mark(string $id): void
    {
        $this->connection
            ->createQueryBuilder()
            ->insert($this->table)
            ->setValue('id', ':id')
            ->setParameter('id', $id)
            ->execute();
    }

    /**
     * {@inheritdoc}
     */
    public function unmark(string $id): void
    {
        $this->connection
            ->createQueryBuilder()
            ->delete($this->table, 'marker')
            ->where('marker.id = :id')
            ->setParameter('id', $id)
            ->execute();
    }
}


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

namespace cascade\models;

use Yii;

/**
 * DataInterface is the model class for table "data_interface".
 *
 * @property string $id
 * @property string $name
 * @property string $system_id
 * @property string $last_sync
 * @property string $created
 * @property string $modified
 * @property Registry $id
 * @property DataInterfaceLog[] $dataInterfaceLogs
 * @property KeyTranslation[] $keyTranslations
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DataInterface extends \cascade\components\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function isAccessControlled()
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'data_interface';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'Registry' => [
                'class' => 'canis\db\behaviors\Registry',
            ],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['system_id'], 'required'],
            [['last_sync', 'created', 'modified'], 'safe'],
            [['id'], 'string', 'max' => 36],
            [['name', 'system_id'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'system_id' => 'System ID',
            'last_sync' => 'Last Sync',
            'created' => 'Created',
            'modified' => 'Modified',
        ];
    }

    /**
     * Get id.
     *
     * @return \yii\db\ActiveRelation
     */
    public function getId()
    {
        return $this->hasOne(Registry::className(), ['id' => 'id']);
    }

    /**
     * Get data interface logs.
     *
     * @return \yii\db\ActiveRelation
     */
    public function getDataInterfaceLogs()
    {
        return $this->hasMany(DataInterfaceLog::className(), ['data_interface_id' => 'id']);
    }

    /**
     * Get last data interface log.
     *
     * @return [[@doctodo return_type:getLastDataInterfaceLog]] [[@doctodo return_description:getLastDataInterfaceLog]]
     */
    public function getLastDataInterfaceLog()
    {
        return DataInterfaceLog::find()->where(['data_interface_id' => $this->primaryKey])->orderBy(['created' => SORT_DESC])->one();
    }

    /**
     * Get key translations.
     *
     * @return \yii\db\ActiveRelation
     */
    public function getKeyTranslations()
    {
        return $this->hasMany(DataInterface::className(), ['data_interface_id' => 'id']);
    }

    /**
     * @inheritdoc
     */
    public function getPackage($urlAction = 'view')
    {
        $p = parent::getPackage($urlAction);
        $p['type'] = 'Interface';
        if ($this->hasIcon()) {
            $p['icon'] = $this->getIcon();
        }

        return $p;
    }

    /**
     * Get data interface item.
     *
     * @return [[@doctodo return_type:getDataInterfaceItem]] [[@doctodo return_description:getDataInterfaceItem]]
     */
    public function getDataInterfaceItem()
    {
        return Yii::$app->collectors['dataInterfaces']->getByPk($this->primaryKey);
    }

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

    /**
     * @inheritdoc
     */
    public function getIcon()
    {
        return [
            'class' => 'fa fa-arrows-h',
        ];
    }

    /**
     * [[@doctodo method_description:estimateDuration]].
     *
     * @return [[@doctodo return_type:estimateDuration]] [[@doctodo return_description:estimateDuration]]
     */
    public function estimateDuration()
    {
        $durations = [];
        $logs = DataInterfaceLog::find()->where(['data_interface_id' => $this->primaryKey, 'status' => 'success'])->all();
        foreach ($logs as $log) {
            if (empty($log->ended) || empty($log->started)) {
                continue;
            }
            $durations[] = strtotime($log->ended) - strtotime($log->started);
        }
        if (empty($durations)) {
            return false;
        }
        $average = array_sum($durations) / count($durations);
        $max = max($durations);

        return $average;

        return ($average + $max) / 2;
    }

    /**
     * Get related log query.
     *
     * @return [[@doctodo return_type:getRelatedLogQuery]] [[@doctodo return_description:getRelatedLogQuery]]
     */
    public function getRelatedLogQuery()
    {
        return DataInterfaceLog::find()->where(['data_interface_id' => $this->primaryKey]);
    }
}


<?php
namespace FelixOnline\Base;

trait ControllerCookiesTrait
{
    private function getCookie(
        $cookie,
        \Psr\Http\Message\ServerRequestInterface $request
    ) {
        return \Dflydev\FigCookies\FigRequestCookies::get($request, $cookie);
    }

    private function setCookie(
        \DFlydev\FigCookies\SetCookie $cookie,
        \Psr\Http\Message\ResponseInterface $response
    ) {
        return \Dflydev\FigCookies\FigResponseCookies::set(
            $response,
            $cookie
        );
    }

    // Remove from response, not remove from browser
    private function removeCookie(
        $cookie,
        \Psr\Http\Message\ResponseInterface $response
    ) {
        return \Dflydev\FigCookies\FigResponseCookies::remove(
            $response,
            $cookie
        );
    }

    private function expireCookie(
        $cookie,
        \Psr\Http\Message\ResponseInterface $response,
        $domain = null,
        $path = null
    ) {
        $setCookie = \Dflydev\FigCookies\SetCookie::createExpired($cookie);

        if ($domain) {
            $setCookie = $setCookie->withDomain($domain);
        }

        if ($path) {
            $setCookie = $setCookie->withPath($path);
        }

        return $this->setCookie($setCookie, $response);
    }

    private function modifyCookie(
        \DFlydev\FigCookies\SetCookie $cookie,
        \Psr\Http\Message\ResponseInterface $response
    ) {
        return \Dflydev\FigCookies\FigResponseCookies::modify(
            $response,
            $cookie->getName(),
            function ($cookie) {
                return $cookie;
            }
        );
    }
}


<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2018
 */

namespace Praxigento\BonusHybrid\Service\United;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Last\Request as ACalcLastRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Last\Response as ACalcLastResponse;
use Praxigento\BonusBase\Repo\Data\Period as EPeriod;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Service\Calc\Forecast\Plain as APlain;
use Praxigento\BonusHybrid\Service\United\Forecast\Request as ARequest;
use Praxigento\BonusHybrid\Service\United\Forecast\Response as AResponse;
use Praxigento\Core\Api\Helper\Period as HPeriod;

/**
 * Aggregated service to perform all activities related to forecast bonus calculation (create calculation,
 * rebuild downline and balances, etc.).
 */
class Forecast
{
    /** @var \Praxigento\BonusBase\Repo\Dao\Period */
    private $daoPeriod;
    /** @var \Praxigento\BonusBase\Repo\Dao\Type\Calc */
    private $daoTypeCalc;
    /** @var \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Forecast\Compress */
    private $servCalcCompress;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Last */
    private $servCalcGetLast;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Forecast\Plain */
    private $servCalcPlain;
    /** @var \Praxigento\Downline\Api\Service\Snap\Calc */
    private $servSnapCalc;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\BonusBase\Repo\Dao\Period $daoPeriod,
        \Praxigento\BonusBase\Repo\Dao\Type\Calc $daoTypeCalc,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\Downline\Api\Service\Snap\Calc $servSnapCalc,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Last $servCalcGetLast,
        \Praxigento\BonusHybrid\Service\Calc\Forecast\Plain $servCalcPlain,
        \Praxigento\BonusHybrid\Service\Calc\Forecast\Compress $servCalcCompress
    ) {
        $this->logger = $logger;
        $this->daoPeriod = $daoPeriod;
        $this->daoTypeCalc = $daoTypeCalc;
        $this->hlpPeriod = $hlpPeriod;
        $this->servSnapCalc = $servSnapCalc;
        $this->servCalcGetLast = $servCalcGetLast;
        $this->servCalcPlain = $servCalcPlain;
        $this->servCalcCompress = $servCalcCompress;
    }

    private function calcPeriods()
    {
        $req = new ACalcLastRequest();
        $req->setCalcTypeCode(Cfg::CODE_TYPE_CALC_PV_WRITE_OFF);
        /** @var ACalcLastResponse $resp */
        $resp = $this->servCalcGetLast->exec($req);
        $period = $resp->getPeriod();
        $dsEnd = $period->getDstampEnd();
        $periodNext = $this->hlpPeriod->getPeriodNext($dsEnd, HPeriod::TYPE_MONTH);
        /* compare last calculated period with current period */
        $periodPrev = null;
        $periodCurrent = $this->hlpPeriod->getPeriodCurrent(null, 0, HPeriod::TYPE_MONTH);
        /* period after the last calculated is not equal to current period - we need to calc both */
        if ($periodNext != $periodCurrent) {
            $periodPrev = $periodNext;
        }

        return [$periodPrev, $periodCurrent];
    }

    private function cleanForecastCalcs()
    {
        $typeIdPlain = $this->daoTypeCalc->getIdByCode(Cfg::CODE_TYPE_CALC_FORECAST_PLAIN);
        $typeIdCompress = $this->daoTypeCalc->getIdByCode(Cfg::CODE_TYPE_CALC_FORECAST_PHASE1);
        $byPlain = EPeriod::A_CALC_TYPE_ID . '=' . (int)$typeIdPlain;
        $byCompress = EPeriod::A_CALC_TYPE_ID . '=' . (int)$typeIdCompress;
        $where = "($byPlain) OR ($byCompress)";
        $this->daoPeriod->delete($where);
    }

    /**
     * @param ARequest $request
     * @return AResponse
     * @throws \Exception
     */
    public function exec($request)
    {
        /** define local working data */
        assert($request instanceof ARequest);

        /* perform the main processing */
        $this->logger->info("Aggregated activity to perform forecast calculation is started.");
        $this->logger->info("Rebuild downline snaps for the last days.");
        $this->rebuildDwnlSnaps();
        /* should we calculate one or two periods? */
        list($periodPrev, $periodCurr) = $this->calcPeriods();
        $this->logger->info("Clean up all forecast calculations data.");
        $this->cleanForecastCalcs();
        /* if previous period is not closed yet */
        if ($periodPrev) {
            $this->logger->info("Perform calculation for period '$periodPrev' (previous).");
            $ctx = new \Praxigento\Core\Data();
            $ctx->set(APlain::CTX_IN_PERIOD, $periodPrev);
            /* ... then perform forecast calculations */
            $this->servCalcPlain->exec($ctx);
            $this->servCalcCompress->exec($ctx);
        }
        /* calculation for current period */
        $this->logger->info("Perform calculation for period '$periodCurr' (current).");
        $ctx = new \Praxigento\Core\Data();
        $ctx->set(APlain::CTX_IN_PERIOD, $periodCurr);
        /* ... then perform forecast calculations */
        $this->servCalcPlain->exec($ctx);
        $this->servCalcCompress->exec($ctx);

        /** compose result */
        $this->logger->info("Aggregated activity to perform forecast calculation is completed.");
        $result = new AResponse();
        return $result;
    }

    /**
     * MOBI-1026: re-build downline snaps before calculations.
     *
     * Clean up downline tree snaps for the last 2 days then rebuild it.
     * The last day of the snap would contain incomplete information.
     *
     * TODO: remove it after the last day of the snap will be processed correctly.
     */
    private function rebuildDwnlSnaps()
    {
        $req = new \Praxigento\Downline\Api\Service\Snap\Calc\Request();
        $this->servSnapCalc->exec($req);
    }
}


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

namespace cascade\components\dataInterface;

use Yii;

/**
 * DataItem [[@doctodo class_description:cascade\components\dataInterface\DataItem]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class DataItem extends \canis\base\Component
{
    /**
     * @var [[@doctodo var_type:dataSource]] [[@doctodo var_description:dataSource]]
     */
    public $dataSource;
    /**
     * @var [[@doctodo var_type:isForeign]] [[@doctodo var_description:isForeign]]
     */
    public $isForeign = true;

    /**
     * @var [[@doctodo var_type:localModelError]] [[@doctodo var_description:localModelError]]
     */
    public $localModelError = false;
    /**
     * @var [[@doctodo var_type:foreignModelError]] [[@doctodo var_description:foreignModelError]]
     */
    public $foreignModelError = false;

    /**
     * @var [[@doctodo var_type:_pairedDataItem]] [[@doctodo var_description:_pairedDataItem]]
     */
    protected $_pairedDataItem;
    /**
     * @var [[@doctodo var_type:_handledDataItem]] [[@doctodo var_description:_handledDataItem]]
     */
    protected $_handledDataItem = false;
    /**
     * @var [[@doctodo var_type:_foreignObject]] [[@doctodo var_description:_foreignObject]]
     */
    protected $_foreignObject;
    /**
     * @var [[@doctodo var_type:foreignPrimaryKey]] [[@doctodo var_description:foreignPrimaryKey]]
     */
    public $foreignPrimaryKey;

    /**
     * @var [[@doctodo var_type:_localObject]] [[@doctodo var_description:_localObject]]
     */
    protected $_localObject;
    /**
     * @var [[@doctodo var_type:localPrimaryKey]] [[@doctodo var_description:localPrimaryKey]]
     */
    public $localPrimaryKey;

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

    const EVENT_LOAD_FOREIGN_OBJECT = 0x01;
    const EVENT_LOAD_LOCAL_OBJECT = 0x02;

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

    /**
     * [[@doctodo method_description:searchLocalObject]].
     *
     * @param [[@doctodo param_type:event]] $event [[@doctodo param_description:event]]
     *
     * @return [[@doctodo return_type:searchLocalObject]] [[@doctodo return_description:searchLocalObject]]
     */
    protected function searchLocalObject($event)
    {
        if (isset($this->foreignObject) && !isset($this->_localObject) && isset($this->dataSource->search)) {
            if (($localObject = $this->dataSource->search->searchLocal($this)) && !empty($localObject)) {
                $this->localObject = $localObject;
            }

            if ($localObject === false) {
                $this->localModelError = true;
            }
        }

        return true;
    }

    /**
     * [[@doctodo method_description:clean]].
     */
    public function clean()
    {
        if (isset($this->foreignObject)) {
            $this->foreignPrimaryKey = $this->foreignObject->primaryKey;
            $this->foreignObject = null;
        }
        if (isset($this->localObject)) {
            $this->localPrimaryKey = $this->localObject->primaryKey;
            $this->localObject = null;
        }
        Yii::getLogger()->flush();
    }

    /**
     * Get id.
     *
     * @return [[@doctodo return_type:getId]] [[@doctodo return_description:getId]]
     */
    public function getId()
    {
        if ($this->isForeign) {
            if (isset($this->foreignPrimaryKey)) {
                return $this->foreignPrimaryKey;
            } elseif (isset($this->foreignObject)) {
                return $this->foreignObject->primaryKey;
            }
        } else {
            if (isset($this->localPrimaryKey)) {
                return $this->localPrimaryKey;
            } elseif (isset($this->localObject)) {
                return $this->localObject->primaryKey;
            }
        }
        if (isset($this->primaryObject)) {
            return $this->primaryObject->primaryKey;
        }

        return;
    }

    /**
     * [[@doctodo method_description:handle]].
     *
     * @param boolean $fromRelative   [[@doctodo param_description:fromRelative]] [optional]
     * @param array   $baseAttributes [[@doctodo param_description:baseAttributes]] [optional]
     *
     * @return [[@doctodo return_type:handle]] [[@doctodo return_description:handle]]
     */
    public function handle($fromRelative = false, $baseAttributes = [])
    {
        $this->baseAttributes = $baseAttributes;
        if ($this->handledDataItem) {
            if ($this->isForeign) {
                $object = $this->localObject;
            } else {
                $object = $this->foreignObject;
            }
            if (!empty($baseAttributes)) {
                foreach ($baseAttributes as $key => $value) {
                    $object->{$key} = $value;
                }
                if (!$object->save()) {
                    return false;
                }
            }

            return $object;
        }
        if ($fromRelative || !$this->dataSource->childOnly) {
            if (isset($baseAttributes['relationModels'][0]['parent_object_id'])) {
                $baseAttributes['indirectObject'] = $baseAttributes['relationModels'][0]['parent_object_id'];
            }
            if ($this->isForeign) {
                // handle local to foreign
                $result = $this->handler->handleForeign($baseAttributes);
            } else {
                $result = $this->handler->handleLocal($baseAttributes);
            }
        } else {
            $result = true;
        }
        if (is_null($result)) {
            $this->handledDataItem = true;
        } elseif ($result) {
            if (is_object($result)) {
                $this->handledDataItem = true;
            }
            if ($this->dataSource->postProcess) {
                call_user_func($this->dataSource->postProcess, $this);
            }

            return $result;
        }

        return false;
    }

    /**
     * Get ignore foreign object.
     *
     * @return [[@doctodo return_type:getIgnoreForeignObject]] [[@doctodo return_description:getIgnoreForeignObject]]
     */
    public function getIgnoreForeignObject()
    {
        return $this->testIgnore($this->foreignObject, $this->dataSource->ignoreForeign);
    }

    /**
     * Get ignore local object.
     *
     * @return [[@doctodo return_type:getIgnoreLocalObject]] [[@doctodo return_description:getIgnoreLocalObject]]
     */
    public function getIgnoreLocalObject()
    {
        return $this->testIgnore($this->localObject, $this->dataSource->ignoreLocal);
    }

    /**
     * [[@doctodo method_description:testIgnore]].
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     * @param [[@doctodo param_type:ignore]] $ignore [[@doctodo param_description:ignore]]
     *
     * @return [[@doctodo return_type:testIgnore]] [[@doctodo return_description:testIgnore]]
     */
    protected function testIgnore($object, $ignore)
    {
        if (!$object) {
            return true;
        }
        if ($ignore === true) {
            return true;
        } elseif (is_array($ignore)) {
            foreach ($ignore as $key => $value) {
                $objectValue = $object->{$key};
                if (is_object($value)) {
                    if ($value->test($objectValue)) {
                        return true;
                    }
                } elseif (is_array($value)) {
                    if (in_array($objectValue, $value)) {
                        return true;
                    }
                } else {
                    if ($objectValue === $value) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * [[@doctodo method_description:handleLocal]].
     *
     * @param array $baseAttributes [[@doctodo param_description:baseAttributes]] [optional]
     *
     * @return [[@doctodo return_type:handleLocal]] [[@doctodo return_description:handleLocal]]
     */
    protected function handleLocal($baseAttributes = [])
    {
        return false;
    }

    /**
     * [[@doctodo method_description:handleForeign]].
     *
     * @param array $baseAttributes [[@doctodo param_description:baseAttributes]] [optional]
     *
     * @return [[@doctodo return_type:handleForeign]] [[@doctodo return_description:handleForeign]]
     */
    protected function handleForeign($baseAttributes = [])
    {
        return false;
    }

    /**
     * Get handler.
     *
     * @return [[@doctodo return_type:getHandler]] [[@doctodo return_description:getHandler]]
     */
    public function getHandler()
    {
        if ($this->pairedDataItem) {
            if (!isset($this->primaryObject)) {
                return $this->pairedDataItem;
            } elseif (isset($this->companionObject)) {
                return static::getHandlingObject($this, $this->pairedDataItem);
            }
        }

        return $this;
    }

    /**
     * Get handling comparison.
     *
     * @return [[@doctodo return_type:getHandlingComparison]] [[@doctodo return_description:getHandlingComparison]]
     */
    public function getHandlingComparison()
    {
        return false;
    }

    /**
     * Get handling object.
     *
     * @param [[@doctodo param_type:a]] $a [[@doctodo param_description:a]]
     * @param [[@doctodo param_type:b]] $b [[@doctodo param_description:b]]
     *
     * @return [[@doctodo return_type:getHandlingObject]] [[@doctodo return_description:getHandlingObject]]
     */
    public static function getHandlingObject($a, $b)
    {
        $handlingA = $a->handlingComparison;
        $handlingB = $b->handlingComparison;

        if (!$handlingB) {
            return $a;
        }
        if ($handlingA !== false && $handlingB !== false) {
            if ($handlingA > $handlingB) {
                return $a;
            } else {
                return $b;
            }
        }

        return $a;
    }

    /**
     * Get primary object.
     *
     * @return [[@doctodo return_type:getPrimaryObject]] [[@doctodo return_description:getPrimaryObject]]
     */
    public function getPrimaryObject()
    {
        if ($this->isForeign) {
            return $this->foreignObject;
        } else {
            return $this->localObject;
        }
    }

    /**
     * Get companion object.
     *
     * @return [[@doctodo return_type:getCompanionObject]] [[@doctodo return_description:getCompanionObject]]
     */
    public function getCompanionObject()
    {
        if ($this->isForeign) {
            return $this->localObject;
        } else {
            return $this->foreignObject;
        }
    }

    /**
     * Set companion object.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     *
     * @return [[@doctodo return_type:setCompanionObject]] [[@doctodo return_description:setCompanionObject]]
     */
    public function setCompanionObject($value)
    {
        if ($this->isForeign) {
            return $this->localObject = $value;
        } else {
            return $this->foreignObject = $value;
        }
    }

    /**
     * Get companion.
     *
     * @return [[@doctodo return_type:getCompanionId]] [[@doctodo return_description:getCompanionId]]
     */
    public function getCompanionId()
    {
        if ($this->isForeign && isset($this->foreignPrimaryKey)) {
            return $this->foreignPrimaryKey;
        } elseif (!$this->isForeign && isset($this->localPrimaryKey)) {
            return $this->localPrimaryKey;
        }
        if (isset($this->companionObject)) {
            return $this->companionObject->primaryKey;
        }

        return;
    }

    /**
     * Set paired data item.
     *
     * @param cascade\components\dataInterface\DataItem $value [[@doctodo param_description:value]]
     */
    public function setPairedDataItem(DataItem $value)
    {
        $this->_pairedDataItem = $value;
        if (!isset($this->_localObject) && isset($value->localObject)) {
            $this->localObject = $value->localObject;
        }

        if (!isset($this->_foreignObject) && isset($value->foreignObject)) {
            $this->foreignObject = $value->foreignObject;
        }

        if ($value->handledDataItem) {
            $this->handledDataItem = $value->handledDataItem;
        }
    }

    /**
     * Get paired data item.
     *
     * @return [[@doctodo return_type:getPairedDataItem]] [[@doctodo return_description:getPairedDataItem]]
     */
    public function getPairedDataItem()
    {
        return $this->_pairedDataItem;
    }

    /**
     * Set handled data item.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     *
     * @return [[@doctodo return_type:setHandledDataItem]] [[@doctodo return_description:setHandledDataItem]]
     */
    public function setHandledDataItem($value)
    {
        if (isset($this->_pairedDataItem)) {
            $this->pairedDataItem->handledDataItem = $value;
        }
        if (!$this->_handledDataItem && $value) {
            $this->dataSource->reduceRemaining($this);
        }
        $this->clean();

        return $this->_handledDataItem = $value;
    }

    /**
     * Get handled data item.
     *
     * @return [[@doctodo return_type:getHandledDataItem]] [[@doctodo return_description:getHandledDataItem]]
     */
    public function getHandledDataItem()
    {
        return $this->_handledDataItem;
    }

    /**
     * Get foreign object.
     *
     * @return [[@doctodo return_type:getForeignObject]] [[@doctodo return_description:getForeignObject]]
     */
    public function getForeignObject()
    {
        if (is_null($this->_foreignObject)) {
            $this->trigger(self::EVENT_LOAD_FOREIGN_OBJECT);
        }

        return $this->_foreignObject;
    }

    /**
     * Set foreign object.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setForeignObject($value)
    {
        $this->_foreignObject = $value;
    }

    /**
     * Get local object.
     *
     * @return [[@doctodo return_type:getLocalObject]] [[@doctodo return_description:getLocalObject]]
     */
    public function getLocalObject()
    {
        if (is_null($this->_localObject)) {
            $this->trigger(self::EVENT_LOAD_LOCAL_OBJECT);
        }

        return $this->_localObject;
    }

    /**
     * Set local object.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setLocalObject($value)
    {
        $this->_localObject = $value;
    }

    /**
     * Get action.
     *
     * @return [[@doctodo return_type:getAction]] [[@doctodo return_description:getAction]]
     */
    public function getAction()
    {
        return $this->dataSource->action;
    }

    /**
     * Get module.
     *
     * @return [[@doctodo return_type:getModule]] [[@doctodo return_description:getModule]]
     */
    public function getModule()
    {
        return $this->dataSource->module;
    }
}