<?php

namespace TaylorNetwork\LaravelHelpers\Commands;

use Illuminate\Console\GeneratorCommand;

class HelperMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:helper';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new helper function';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Helper';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__ . '/stubs/helper.stub';
    }
    /**
     * Get the default namespace for the class.
     *
     * @param  string $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\\' . config('laravel_helpers.namespace', 'Helpers');
    }

    /**
     * Replace DummyHelper in stub
     *
     * @param string $name
     * @return mixed
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    protected function buildClass($name)
    {
        $stub = $this->files->get($this->getStub());

        return str_replace('DummyHelper', $this->getNameInput(), $stub);
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Manager;

use OpenOrchestra\ModelInterface\Manager\EntityDbMapperInterface;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Persisters\PersistenceBuilder;

/**
 * Class EntityDbMapper
 */
class EntityDbMapper implements EntityDbMapperInterface
{
    protected $documentManager;
    protected $documentClass;

    /**
     * @param DocumentManager $documentManager
     * @param string          $documentClass
     */
    public function __construct(DocumentManager $documentManager, $documentClass)
    {
        $this->documentManager = $documentManager;
        $this->documentClass = $documentClass;
    }

    /**
     * Take a embed document array representation to return entity
     *
     * @param array $data
     *
     * @return mixed
     */
    public function fromDbToEntity(array $data)
    {
        $hydratorFactory = $this->documentManager->getHydratorFactory();
        $documentClass = $this->documentClass;

        $document = new $documentClass();
        $hydratorFactory->hydrate($document, $data);

        return $document;
    }

    /**
     * Take a id to turn it into a embed document array representation
     *
     * @param mixed $document
     *
     * @return array
     */
    public function fromEntityToDb($document)
    {
        $unitOfWork = $this->documentManager->getUnitOfWork();
        $persistenceBuilder = new PersistenceBuilder($this->documentManager, $unitOfWork);
        $mapping = array (
            'targetDocument' => $this->documentClass,
        );

        return $persistenceBuilder->prepareEmbeddedDocumentValue($mapping, $document, true);
    }
}


<?php
/**
 * Documents module for HiPanel
 *
 * @link      https://hipanel.com/
 * @package   hipanel-module-document
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2016-2018, HiQDev (http://hiqdev.com/)
 */

namespace hipanel\modules\document\models;

use hipanel\base\ModelTrait;
use hipanel\behaviors\File as FileBehavior;
use hipanel\models\File;
use hipanel\modules\document\models\query\DocumentQuery;
use paulzi\jsonBehavior\JsonBehavior;
use paulzi\jsonBehavior\JsonValidator;
use Yii;

/**
 * Class Document represents document.
 *
 * @property int $id
 * @property string $title
 * @property string $description
 */
class Document extends \hipanel\base\Model
{
    use ModelTrait;

    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';
    const SCENARIO_DELETE = 'delete';

    /**
     * {@inheritdoc}
     */
    public static $i18nDictionary = 'hipanel:document';

    /**
     * @return array
     */
    public function behaviors()
    {
        return [
            [
                'class' => FileBehavior::class,
                'attribute' => 'attachment',
                'targetAttribute' => 'file_id',
                'scenarios' => ['create'],
            ],
            [
                'class' => JsonBehavior::class,
                'attributes' => ['data'],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'type_id', 'state_id', 'object_id', 'client_id', 'seller_id'], 'integer'],
            [['client', 'seller', 'title', 'description'], 'safe'],
            [['create_time', 'update_time'], 'safe'],
            [['type', 'state'], 'safe'],
            [['filename'], 'string'],

            [['client', 'attachment'], 'safe', 'on' => ['create']],
            [['type', 'title'], 'required', 'on' => ['create', 'update']],
            [['description', 'status_types'], 'safe', 'on' => ['create', 'update']],
            [['file_id'], 'integer', 'on' => ['create', 'update']],
            [
                ['validity_start', 'validity_end'],
                'safe',
                'on' => ['create', 'update'],
                'when' => function () {
                    return Yii::$app->user->can('document.update');
                },
            ],
            [
                ['validity_end'],
                'compare',
                'compareAttribute' => 'validity_start',
                'operator' => '>',
                'on' => ['create', 'update'],
                'enableClientValidation' => false,
                'when' => function () {
                    return Yii::$app->user->can('document.update');
                },
            ],
            [['id'], 'required', 'on' => ['update', 'delete']],
            [['data'], JsonValidator::class],
        ];
    }

    /**
     * @return mixed
     */
    public function attributeLabels()
    {
        return $this->mergeAttributeLabels([
            'type_id' => Yii::t('hipanel', 'Type'),
            'attachment' => Yii::t('hipanel:document', 'File'),
            'status_types' => Yii::t('hipanel:document', 'Statuses'),
        ]);
    }

    public function getFile()
    {
        return $this->hasOne(File::class, ['id' => 'file_id']);
    }

    public function getObject()
    {
        return $this->hasOne(DocumentObject::class, ['id' => 'object_id'])->via('file');
    }

    public function getStatuses()
    {
        return $this->hasMany(Status::class, ['object_id' => 'id']);
    }

    public function isVerified()
    {
        return in_array('verified', (array) $this->status_types, true);
    }

    /**
     * {@inheritdoc}
     * @return DocumentQuery
     */
    public static function find($options = [])
    {
        return new DocumentQuery(get_called_class(), [
            'options' => $options,
        ]);
    }

    public function getDisplayTitle()
    {
        return $this->title ?: Yii::t('hipanel:document', 'Untitled document');
    }
}


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

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Exclude;
use Symfony\Component\Yaml\Yaml;

/**
 * Class ExtendableCollectionBlock is the object assigned to handle a collection of extendable blocks
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Block
 */
abstract class ExtendableCollectionBlock extends ExtendableBlock
{
    /**
     * @Type("array")
     */
    private $children = array();

    /**
     * Constructor
     */
    public function __construct(array $children, array $tags = array())
    {
        $this->children = $children;
        $this->tags = $tags;
        if (null === $this->source) {
            $this->source = Yaml::dump($this->generateSourceFromChildren(), 100, 2);
        }

        parent::__construct();
    }

    /**
     * Generates the source from the block children
     *
     * @return array
     */
    protected function generateSourceFromChildren()
    {
        $i = 1;
        $children = array();
        foreach ($this->children as $child) {
            $childValue = Yaml::parse($child->getSource());
            if (is_array($childValue) && array_key_exists("type", $childValue)) {
                $childValue["type"] = $child->getType();
            }
            $children['item' . $i] = $childValue;
            $i++;
        }

        $source = array(
            "children" => $children,
        );

        if (!empty($this->tags)) {
            $source["tags"] = $this->tags;
        }
        $source["type"] = $this->type;

        return $source;
    }

    /**
     * Returns the block's children property
     *
     * @return array
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Sets the block's children property
     *
     * @param array $value
     */
    public function setChildren(array $value)
    {
        $this->children = $value;
    }
}


<?php
/**
 * User: jonathanbak
 * Date: 2017. 2. 1.
 */

namespace MySQLiLib;

abstract class DbAbstract implements DbInterface
{
    protected $connection = null;	//DB connect
    protected $result = null;	//query 결과
    protected $result_query = array(); //query 결과 의 쿼리

    /**
     * Dao constructor.
     * @param $host
     * @param $user
     * @param $password
     * @param $dbName
     */
    public function __construct( $host, $user, $password, $dbName )
    {
        $this->connection = $this->connect( $host, $user, $password, $dbName );
    }

    /**
     * SQL Injection 방어 mysql_real_escape_string 실행
     * @param array $params
     * @return array
     */
    public function arrayToRealEscape( $params = array() )
    {
        foreach($params as $k=> $value){
            $params[$k] = $this->realEscapeString($value);
        }
        return $params;
    }

    /**
     * get_magic_quotes_gpc 체크하여 addslashes
     * @param $value
     * @return string
     */
    public function realEscapeString( $value )
    {
        return get_magic_quotes_gpc()? $value : addslashes( $value );
    }

    /**
     * get_magic_quotes_gpc 체크하여 stripslashes
     * @param $value
     * @return string
     */
    public function unEscapeString( $value )
    {
        return get_magic_quotes_gpc()? $value : stripslashes( $value );
    }

    /**
     * 배열의 각 값을 홑따옴표로 묶어서 돌려준다
     * @param array $arrayVal
     * @return array
     */
    public function intArrayQuote( $arrayVal = array() )
    {
        $tmpVal = array();
        foreach($arrayVal as $val){
            $tmpVal[] = "'".$this->realEscapeString($val)."'";
        }

        return $tmpVal;
    }

    /**
     * 키:값 배열을 쿼리문에 넣기좋게 만들어준다
     * @param array $params
     * @return array
     */
    public function parseArrayToQuery( $params = array() )
    {
        $tmpVal = array();
        foreach($params as $k => $val){
            if(preg_match('/^([0-9]+)$/i',$k,$tmpMatch)==false) $tmpVal[] = " `$k` = "." '".$this->realEscapeString($val)."'";
        }
        return $tmpVal;
    }

    /**
     * 쿼리에 ? 로 파라미터 넣기
     * @param $pattern
     * @param $searchValue
     * @return mixed|string
     */
    public function parseCondition( $pattern, $searchValue )
    {
        if(preg_match_all('/:([a-zA-Z0-9_-]+)/i',$pattern,$tmpMatches)){
            $findKeys = array_unique($tmpMatches[1]);
            foreach($findKeys as $column){
                if(isset($searchValue[$column])) $pattern = str_replace(":".$column,"'".$searchValue[$column]."'",$pattern);
                else $pattern = str_replace(":".$column,"''",$pattern);
            }
        }
        if(preg_match_all('/::([a-zA-Z0-9_-]+)/i',$pattern,$tmpMatches)){
            $findKeys = array_unique($tmpMatches[1]);
            foreach($findKeys as $column){
                if(isset($searchValue[$column])) $pattern = str_replace("::".$column,$searchValue[$column],$pattern);
                else $pattern = str_replace("::".$column,"''",$pattern);
            }
        }
        $pattern = str_replace("%","%%",$pattern);
        $pattern = str_replace("??","%s",$pattern);
        $conditions = str_replace("?","'%s'",$pattern);

        if(is_array($searchValue)) {
            $searchValue = $this->arrayToRealEscape($searchValue);
            $conditions = vsprintf($conditions, $searchValue);
        }else{
            $searchValue = $this->realEscapeString($searchValue);
            $conditions = sprintf($conditions, $searchValue);
        }

        return $conditions;
    }

}


<?php

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

/**
 * Page.php.
 *
 * @author    allen05ren <allen05ren@outlook.com>
 * @copyright 2016 overtrue <i@overtrue.me>
 *
 * @see       https://github.com/overtrue
 * @see       http://overtrue.me
 */

namespace EasyWeChat\ShakeAround;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class Page.
 */
class Page extends AbstractAPI
{
    const API_ADD = 'https://api.weixin.qq.com/shakearound/page/add';
    const API_UPDATE = 'https://api.weixin.qq.com/shakearound/page/update';
    const API_SEARCH = 'https://api.weixin.qq.com/shakearound/page/search';
    const API_DELETE = 'https://api.weixin.qq.com/shakearound/page/delete';
    const API_RELATION_SEARCH = 'https://api.weixin.qq.com/shakearound/relation/search';

    /**
     * Add a page.
     *
     * @param string $title
     * @param string $description
     * @param string $pageUrl
     * @param string $iconUrl
     * @param string $comment
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function add($title, $description, $pageUrl, $iconUrl, $comment = '')
    {
        $params = [
            'title' => $title,
            'description' => $description,
            'page_url' => $pageUrl,
            'icon_url' => $iconUrl,
        ];
        if ($comment !== '') {
            $params['comment'] = $comment;
        }

        return $this->parseJSON('json', [self::API_ADD, $params]);
    }

    /**
     * update a page info.
     *
     * @param int    $pageId
     * @param string $title
     * @param string $description
     * @param string $pageUrl
     * @param string $iconUrl
     * @param string $comment
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function update($pageId, $title, $description, $pageUrl, $iconUrl, $comment = '')
    {
        $params = [
            'page_id' => intval($pageId),
            'title' => $title,
            'description' => $description,
            'page_url' => $pageUrl,
            'icon_url' => $iconUrl,
        ];
        if ($comment !== '') {
            $params['comment'] = $comment;
        }

        return $this->parseJSON('json', [self::API_UPDATE, $params]);
    }

    /**
     * Fetch batch of pages by pageIds.
     *
     * @param array $pageIds
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function fetchByIds(array $pageIds)
    {
        $params = [
            'type' => 1,
            'page_ids' => $pageIds,
        ];

        return $this->parseJSON('json', [self::API_SEARCH, $params]);
    }

    /**
     * Pagination to fetch batch of pages.
     *
     * @param int $begin
     * @param int $count
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function pagination($begin, $count)
    {
        $params = [
            'type' => 2,
            'begin' => intval($begin),
            'count' => intval($count),
        ];

        return $this->parseJSON('json', [self::API_SEARCH, $params]);
    }

    /**
     * delete a page.
     *
     * @param int $pageId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($pageId)
    {
        $params = [
            'page_id' => intval($pageId),
        ];

        return $this->parseJSON('json', [self::API_DELETE, $params]);
    }
}


<?php

/**
 * Manage date
 *
 * @category  	lib
 * @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\lib;

use \DateTime as DateTime;

/**
 * This class manage the date
 *
 * @category  	lib
 * @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 Date
{
    /**
     * set name of image
     *
     * @access public
     * @param  int $iWeek number of week
     * @param  int $iYear year
     * @param string $sFormat
     * @return Date
     */
    public static function getWeek(int $iWeek, int $iYear, string $sFormat = "Y-m-d") : Date
    {
        $iFirstDayInYear = date("N",mktime(0, 0, 0, 1, 1, $iYear));

        if ($iFirstDayInYear < 5) { $iShift = -($iFirstDayInYear - 1) * 86400; } else { $iShift = (8 - $iFirstDayInYear) * 86400; }

        if ($iWeek > 1) { $iWeekInSeconds = ($iWeek-1) * 604800; } else { $iWeekInSeconds = 0; }

        $iTimestamp = mktime(0, 0, 0, 1, 1, $iYear) + $iWeekInSeconds + $iShift;
        $iTimestampLastDay = mktime(0, 0, 0, 1, 6, $iYear) + $iWeekInSeconds + $iShift + 604800;

        return array(date($sFormat, $iTimestamp), date($sFormat, $iTimestampLastDay));
    }

    /**
     * set name of image
     *
     * @access public
     * @return \Venus\lib\Date
     */
    public static function getActualWeek() : Date
    {
        return self::getWeek(date('W'), date('Y'));
    }

    /**
     * set name of image
     *
     * @access public
     * @param  string $sMonth number of week
     * @param  string $sLanguage language
     * @return \Venus\lib\Date
     */
    public static function getMonthInWord(string $sMonth, string $sLanguage = 'fr') : Date
    {
        if ($sLanguage == 'fr') {

            if ($sMonth == '01' || $sMonth == 1) { return 'Janvier'; }
            else if ($sMonth == '02' || $sMonth == 2) { return 'Février'; }
            else if ($sMonth == '03' || $sMonth == 3) { return 'Mars'; }
            else if ($sMonth == '04' || $sMonth == 4) { return 'Avril'; }
            else if ($sMonth == '05' || $sMonth == 5) { return 'Mai'; }
            else if ($sMonth == '06' || $sMonth == 6) { return 'Juin'; }
            else if ($sMonth == '07' || $sMonth == 7) { return 'Juillet'; }
            else if ($sMonth == '08' || $sMonth == 8) { return 'Août'; }
            else if ($sMonth == '09' || $sMonth == 9) { return 'Septembre'; }
            else if ($sMonth == 10) { return 'Octobre'; }
            else if ($sMonth == 11) { return 'Novembre'; }
            else if ($sMonth == 12) { return 'Décembre'; }
        }
    }

    /**
     * set name of image
     *
     * @access public
     * @param  mixed $sDay number of day
     * @param  string $sLanguage language
     * @return \Venus\lib\Date
     */
    public static function getDayInWord(string $sDay, string $sLanguage = 'fr') : Date
    {
        if ($sLanguage == 'fr') {

            if ($sDay == 0) { return 'dimanche'; }
            else if ($sDay == 1) { return 'lundi'; }
            else if ($sDay == 2) { return 'mardi'; }
            else if ($sDay == 3) { return 'mercredi'; }
            else if ($sDay == 4) { return 'jeudi'; }
            else if ($sDay == 5) { return 'vendredi'; }
            else if ($sDay == 6) { return 'samedi'; }
        }
    }

    /**
     * get age by date
     *
     * @access public
     * @param string $sBirthday
     * @return int
     */
    public static function getAgeByDate(string $sBirthday) : int
    {
        list($iYear, $iMonth, $iDay) = preg_split('/[-.]/', $sBirthday);

        $aToday = array();
        $aToday['mois'] = date('n');
        $aToday['jour'] = date('j');
        $aToday['annee'] = date('Y');

        $iYears = $aToday['annee'] - $iYear;

        if ($aToday['mois'] <= $iMonth) {

            if ($iMonth == $aToday['mois']) {

                if ($iDay > $aToday['jour']) { $iYears--; }
            }
            else {

                $iYears--;
            }
        }

        return $iYears;
    }

    /**
     * set name of image
     *
     * @access public
     * @param  int $iWeek number of week
     * @param  int $iYear year
     * @param string $sFormat
     * @return array|Date
     */
    public static function getMiddleWeek(int $iWeek, int $iYear, string $sFormat = "Y-m-d") : array
    {
        $iFirstDayInYear = date("N",mktime(0, 0, 0, 1, 1, $iYear));

        if ($iFirstDayInYear < 5) { $iShift = -($iFirstDayInYear - 1) * 86400; }
        else { $iShift = (8 - $iFirstDayInYear) * 86400; }

        if ($iWeek > 1) { $iWeekInSeconds = ($iWeek-1) * 604800; }
        else { $iWeekInSeconds = 0; }

        if (date('N') > 2) {

            $iTimestamp = mktime(0, 0, 0, 1, 1, $iYear) + $iWeekInSeconds + $iShift + 172800;
            $iTimestampLastDay = $iTimestamp + 604800;
        }
        else {

            $iTimestamp = mktime(0, 0, 0, 1, 1, $iYear) + $iWeekInSeconds + $iShift - 432000;
            $iTimestampLastDay = $iTimestamp + 604800;
        }

        $aDates = array(date($sFormat, $iTimestamp), date($sFormat, $iTimestampLastDay));

        if (preg_replace('/^([0-9]+)-[0-9]+-[0-9]+$/', '$1', $aDates[0]) != date('Y')) {

            $aDates[0] = preg_replace('/^[0-9]+(-[0-9]+-[0-9]+)$/', date('Y').'$1', $aDates[0]);
            $aDates[1] = preg_replace('/^[0-9]+(-[0-9]+-[0-9]+)$/', (date('Y')+1).'$1', $aDates[1]);
        }

        return $aDates;
    }

    /**
     * set name of image
     *
     * @access public
     * @return array
     */
    public static function getActualMiddleWeek() : array
    {
        return self::getMiddleWeek(date('W'), date('Y'));
    }

    /**
     * get time of kind "X hour ago"
     *
     * @access public
     * @param  string $sDateTime datetime to convert
     * @param  string $sLanguage language
     * @return string
     */
    public static function getTimeAgoInString(string $sDateTime, string $sLanguage = 'fr') : string
    {
        if ($sLanguage == 'fr') {

            $sStartReturn = 'Il y a';
            $sEndReturn = '';
            $sMinutes = 'minute(s) ';
            $sHours = 'heure(s) ';
            $sDays = 'jour(s) ';
            $sMonths = 'mois ';
            $sYears = 'années ';
        } else {
            $sStartReturn = 'Ago';
            $sEndReturn = '';
            $sMinutes = 'minute(s) ';
            $sHours = 'hour(s) ';
            $sDays = 'day(s) ';
            $sMonths = 'month ';
            $sYears = 'years ';
        }

        $oDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $sDateTime);
        $iTimeStamp = time() - $oDateTime->getTimestamp();

        if ($iTimeStamp < 3600) { return $sStartReturn.' '.(int)($iTimeStamp/60).' '.$sMinutes.$sEndReturn; }
        if ($iTimeStamp < 86400) { return $sStartReturn.' '.(int)($iTimeStamp/3600).' '.$sHours.$sEndReturn; }
        if ($iTimeStamp < 2592000) { return $sStartReturn.' '.(int)($iTimeStamp/86400).' '.$sDays.$sEndReturn; }
        if ($iTimeStamp < 31536000) { return $sStartReturn.' '.(int)($iTimeStamp/2592000).' '.$sMonths.$sEndReturn; }
        else { return $sStartReturn.' '.(int)($iTimeStamp/31536000).' '.$sYears.$sEndReturn; }
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\Value;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusBase\Repo\Data\Calculation as ECalc;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;

class Tv
    implements \Praxigento\Core\Api\App\Service\Process
{

    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Value\Tv\Calc */
    private $subCalc;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Calc\Value\Tv\Calc $subCalc
    ) {
        $this->logger = $logger;
        $this->daoCalc = $daoCalc;
        $this->daoBonDwnl = $daoBonDwnl;
        $this->servPeriodGet = $servPeriodGet;
        $this->subCalc = $subCalc;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        $this->logger->info("TV calculation is started.");
        /**
         * perform processing
         */
        /**
         * Get dependent calculation data
         *
         * @var ECalc $compressCalc
         * @var ECalc $tvCalc
         *
         */
        list($compressCalc, $tvCalc) = $this->getCalcData();
        $compressCalcId = $compressCalc->getId();
        $tvCalcId = $tvCalc->getId();
        /* load compressed downlines for period */
        $dwnlCompress = $this->daoBonDwnl->getByCalcId($compressCalcId);
        /* populate downline with TV data */
        $dwnlUpdated = $this->subCalc->exec($dwnlCompress);
        /* save updates into repo */
        $this->updateTv($dwnlUpdated);
        /* mark this calculation complete */
        $this->daoCalc->markComplete($tvCalcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("TV calculation is completed.");
    }

    /**
     * Get data for periods/calculations.
     *
     * @return array [$compressCalc, $tvCalc]
     * @throws \Exception
     */
    private function getCalcData()
    {
        /**
         * Get period & calc data.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_COMPRESS_PHASE1);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_VALUE_TV);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var ECalc $compressCalc */
        $compressCalc = $resp->getBaseCalcData();
        /** @var ECalc $tvCalc */
        $tvCalc = $resp->getDepCalcData();
        /**
         * Compose result.
         */
        $result = [$compressCalc, $tvCalc];
        return $result;
    }

    /**
     * Update downline tree with calculated TV values.
     *
     * @param EBonDwnl[] $dwnl
     */
    private function updateTv($dwnl)
    {
        $entity = new  EBonDwnl();
        /** @var EBonDwnl $one */
        foreach ($dwnl as $one) {
            $tv = $one->getTv();
            $calcId = $one->getCalculationRef();
            $custId = $one->getCustomerRef();
            $entity->setTv($tv);
            $id = [
                EBonDwnl::A_CALC_REF => $calcId,
                EBonDwnl::A_CUST_REF => $custId
            ];
            $this->daoBonDwnl->updateById($id, $entity);
        }
    }

}


<?php
namespace eMacros\Runtime\Collection;

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

class ArrayPush implements Applicable {
	/**
	 * Pushes the given parameter onto the end of an array
	 * Usage: (Array::push _arr 20 10)
	 * Returns: int
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		$nargs = count($arguments);
		if ($nargs == 0) throw new \BadFunctionCallException("ArrayPush: No target specified.");
		elseif ($nargs == 1) throw new \BadFunctionCallException("ArrayPush: No values specified.");
		$target = $arguments[0];
		if (!($target instanceof Symbol))
			throw new \InvalidArgumentException(sprintf("ArrayPush: Expected symbol as first argument but %s was found instead.", substr(strtolower(strstr(get_class($arguments[0]), '\\')), 1)));
		$ref = $target->symbol;

		if (is_array($scope->symbols[$ref]) || $scope->symbols[$ref] instanceof \ArrayObject) {
			$args = [];
			$it = $arguments->getIterator();
			$it->rewind();
			for ($it->next(); $it->valid(); $it->next())
				$args[] = $it->current()->evaluate($scope);

			if (is_array($scope->symbols[$ref])) {
				foreach ($args as $arg)
					array_push($scope->symbols[$ref], $arg);
			}
			else {
				$arr = $scope->symbols[$ref]->getArrayCopy();
				foreach ($args as $arg)
					array_push($arr, $arg);
				$scope->symbols[$ref]->exchangeArray($arr);
			}

			return count($scope->symbols[$ref]);
		}

		throw new \InvalidArgumentException(sprintf("ArrayPush: Expected array as first argument but %s was found instead.", gettype($scope->symbols[$ref])));
	}
}
?>


<?php

namespace Weew\Container;

use Weew\Container\Definitions\AliasDefinition;
use Weew\Container\Definitions\ClassDefinition;
use Weew\Container\Definitions\InterfaceDefinition;
use Weew\Container\Definitions\ValueDefinition;
use Weew\Container\Definitions\WildcardDefinition;
use Weew\Container\Exceptions\MissingDefinitionIdentifierException;
use Weew\Container\Exceptions\MissingDefinitionValueException;

class Registry {
    /**
     * @var IDefinition[]
     */
    protected $definitions = [];

    /**
     * @param $id
     * @param null $value
     *
     * @return IDefinition
     */
    public function createDefinition($id, $value = null) {
        list($id, $value) = $this->getIdAndValueFromCreateDefinitionArgs(
            func_get_args(), $id, $value
        );

        $definition = $this->delegateDefinitionCreation($id, $value);
        $this->addDefinition($definition);

        return $definition;
    }

    /**
     * @param array $args
     * @param $id
     * @param $value
     *
     * @return array
     */
    protected function getIdAndValueFromCreateDefinitionArgs(array $args, $id, $value) {
        if (count($args) > 2) {
            array_shift($args);
            $value = $args;
        }

        if ( ! is_array($id) && $value === null) {
            $value = $id;

            if (is_object($id)) {
                $id = get_class($id);
            }
        }

        return [$id, $value];
    }

    /**
     * @param $id
     * @param $value
     *
     * @return IDefinition
     * @throws MissingDefinitionIdentifierException
     * @throws MissingDefinitionValueException
     */
    protected function delegateDefinitionCreation($id, $value) {
        if (is_array($id)) {
            $definition = $this->createDefinitionWithAliases($id, $value);
        } else if ($this->isRegexPattern($id)) {
            $definition = new WildcardDefinition($id, $value);
        } else if (class_exists($id)) {
            $definition = new ClassDefinition($id, $value);
        } else if (interface_exists($id)) {
            $definition = new InterfaceDefinition($id, $value);
        } else {
            $definition = new ValueDefinition($id, $value);
        }

        return $definition;
    }

    /**
     * @param $id
     *
     * @return bool
     */
    public function hasDefinition($id) {
        return $this->getDefinition($id) !== null;
    }

    /**
     * @param $id
     */
    public function removeDefinition($id) {
        $index = $this->getDefinitionIndex($id);

        if ($index !== null) {
            $definition = $this->definitions[$index];

            if ($definition instanceof IDefinition &&
                ! $definition instanceof WildcardDefinition) {
                array_remove($this->definitions, $index);
            }
        }
    }

    /**
     * @param array $ids
     * @param $value
     *
     * @return IDefinition
     * @throws MissingDefinitionIdentifierException
     * @throws MissingDefinitionValueException
     */
    protected function createDefinitionWithAliases(array $ids, $value) {
        if ($value == null) {
            throw new MissingDefinitionValueException(
                s('Trying to register a class with alias without a value. Received %s.', json_encode($ids))
            );
        } else if (count($ids) == 0) {
            throw new MissingDefinitionIdentifierException(
                'Trying to create a definition without an identifier.'
            );
        }

        $definition = null;

        foreach ($ids as $id) {
            if ( ! $definition instanceof IDefinition) {
                $definition = $this->createDefinition($id, $value);
            } else {
                $alias = $this->createAliasDefinition($definition, $id);
                $definition->addAlias($alias);
                $this->addDefinition($alias);
            }
        }

        return $definition;
    }

    /**
     * @param IDefinition $definition
     * @param $id
     *
     * @return AliasDefinition
     */
    protected function createAliasDefinition(IDefinition $definition, $id) {
        return new AliasDefinition($id, $definition);
    }

    /**
     * @param $id
     *
     * @return IDefinition
     */
    public function getDefinition($id) {
        foreach ($this->definitions as $definition) {
            if ($definition instanceof WildcardDefinition) {
                if ($this->matchRegexPattern($id, $definition->getId())) {
                    return $definition;
                }
            } else if ($definition->getId() == $id) {
                if ($definition instanceof AliasDefinition) {
                    return $definition->getValue();
                }

                return $definition;
            }
        }

        return null;
    }

    /**
     * @param $id
     *
     * @return int|null|string
     */
    public function getDefinitionIndex($id) {
        $definition = $this->getDefinition($id);

        foreach ($this->definitions as $index => $item) {
            if ($item === $definition) {
                return $index;
            }
        }
    }

    /**
     * @param IDefinition $definition
     */
    public function addDefinition(IDefinition $definition) {
        $this->removeDefinition($definition->getId());
        array_unshift($this->definitions, $definition);
    }

    /**
     * @param $string
     *
     * @return bool
     */
    protected function isRegexPattern($string) {
        return str_starts_with($string, '/') &&
            str_ends_with($string, '/') ||
            str_starts_with($string, '#') &&
            str_ends_with($string, '#');
    }

    /**
     * @param $string
     * @param $pattern
     *
     * @return bool
     */
    protected function matchRegexPattern($string, $pattern) {
        return preg_match($pattern, $string) == 1;
    }
}


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

namespace Controller\ElFinder;

use RedKiteCms\Rendering\Controller\ElFinder\ElFinderController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to render the ElFinder media library
 * to manage generic files
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\ElFinder
 */
class ElFinderFilesController extends ElFinderController
{
    /**
     * Show ElFinder for files action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function filesAction(Request $request, Application $app)
    {
        $options = array(
            "connector" => $app["red_kite_cms.elfinder_files_connector"],
        );

        return parent::show($options);
    }
}


<?php
/*
 * jQuery File Upload Plugin PHP Class 6.4.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

namespace AdminBundle\Service;

use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Router;
use Symfony\Component\HttpFoundation\Request;
use CoreBundle\Entity\Image as ProductImage;
use BlogBundle\Entity\Image as PostImage;
use Symfony\Component\HttpFoundation\RequestStack;
/**
 * Class UploadHandler
 *
 * Forked from https://github.com/blueimp/jQuery-File-Upload
 * The constructor and the post method are the only customized methods from the original.
 * The post method only customizes the $fileName variable.
 * Everything else is like the original, but with coding standard errors fixed.
 */
class UploadHandler
{
    private $entityManager;

    protected $options;

    protected $request;

    // PHP File Upload error message codes:
    // http://php.net/manual/en/features.file-upload.errors.php
    protected $error_messages = array(
        1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3 => 'The uploaded file was only partially uploaded',
        4 => 'No file was uploaded',
        6 => 'Missing a temporary folder',
        7 => 'Failed to write file to disk',
        8 => 'A PHP extension stopped the file upload',
        'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
        'max_file_size' => 'File is too big',
        'min_file_size' => 'File is too small',
        'accept_file_types' => 'Filetype not allowed',
        'max_number_of_files' => 'Maximum number of files exceeded',
        'max_width' => 'Image exceeds maximum width',
        'min_width' => 'Image requires a minimum width',
        'max_height' => 'Image exceeds maximum height',
        'min_height' => 'Image requires a minimum height'
    );

    /**
     * Class constructor
     *
     * @param string        $rootDir       Symfony root dir
     * @param string        $type          Image type
     * @param Router        $router        Symfony router
     * @param Request       $request       Symfony request
     * @param EntityManager $entityManager Entity Manager
     * @param array|null    $options       Options to merge
     * @param bool          $initialize    Initialize flag
     * @param array|null    $errorMessages Error messages
     */
    public function __construct($rootDir, Router $router, RequestStack $requestStack, EntityManager $entityManager, $options = null, $initialize = true, $errorMessages = null)
    {
        $this->entityManager = $entityManager;
        $this->request = $requestStack->getCurrentRequest();
        $this->options = array(
            'script_url' => $router->generate($this->request->get('route'), array(
                        'id' => $this->request->get('id'),
                        'slug' => $this->request->get('slug'),
                        'type' => $this->request->get('type'),
                        'route' => $this->request->get('route'),
                        'entity' => $this->request->get('entity'),
                        'image_entity' => $this->request->get('image_entity')
                    ), true),
            'type' => $this->request->get('type'),
            'upload_dir' => $rootDir.'/../web/uploads/images/'.$this->request->get('type').'/'.$this->request->get('id').'/',
            'upload_url' => $this->get_full_url().'/uploads/images/'.$this->request->get('type').'/'.$this->request->get('id').'/',
            'entity_id' => $this->request->get('id'),
            'entity_slug' => $this->request->get('slug'),
            'entity_path' => $this->request->get('entity'),
            'entity_image_path' => $this->request->get('image_entity'),
            'user_dirs' => false,
            'mkdir_mode' => 0755,
            'param_name' => 'files',
            // Set the following option to 'POST', if your server does not support
            // DELETE requests. This is a parameter sent to the client:
            'delete_type' => 'DELETE',
            'access_control_allow_origin' => '*',
            'access_control_allow_credentials' => false,
            'access_control_allow_methods' => array(
                'OPTIONS',
                'HEAD',
                'GET',
                'POST',
                'PUT',
                'PATCH',
                'DELETE'
            ),
            'access_control_allow_headers' => array(
                'Content-Type',
                'Content-Range',
                'Content-Disposition'
            ),
            // Enable to provide file downloads via GET requests to the PHP script:
            'download_via_php' => false,
            // Defines which files can be displayed inline when downloaded:
            'inline_file_types' => '/\.(gif|jpe?g|png)$/i',
            // Defines which files (based on their names) are accepted for upload:
            'accept_file_types' => '/.+$/i',
            // The php.ini settings upload_max_filesize and post_max_size
            // take precedence over the following max_file_size setting:
            'max_file_size' => null,
            'min_file_size' => 1,
            // The maximum number of files for the upload directory:
            'max_number_of_files' => null,
            // Image resolution restrictions:
            'max_width' => null,
            'max_height' => null,
            'min_width' => 1,
            'min_height' => 1,
            // Set the following option to false to enable resumable uploads:
            'discard_aborted_uploads' => true,
            // Set to true to rotate images based on EXIF meta data, if available:
            'orient_image' => false,
            'image_versions' => array(
                // Uncomment the following version to restrict the size of
                // uploaded images:
                /*
                '' => array(
                    'max_width' => 1920,
                    'max_height' => 1200,
                    'jpeg_quality' => 95
                ),
                */
                // Uncomment the following to create medium sized images:
                /*
                'medium' => array(
                    'max_width' => 800,
                    'max_height' => 600,
                    'jpeg_quality' => 80
                ),
                */
                'thumbnail' => array(
                    // Uncomment the following to force the max
                    // dimensions and e.g. create square thumbnails:
                    //'crop' => true,
                    'max_width' => 200,
                    'max_height' => 200
                )
            )
        );
        if ($options) {
            $this->options = array_merge($this->options, $options);
        }
        if ($errorMessages) {
            $this->error_messages = array_merge($this->error_messages, $errorMessages);
        }
        if ($initialize) {
            $this->initialize();
        }
    }

    protected function initialize()
    {
        switch ($this->get_server_var('REQUEST_METHOD')) {
            case 'OPTIONS':
            case 'HEAD':
                $this->head();
                break;
            case 'GET':
                $this->get();
                break;
            case 'PATCH':
            case 'PUT':
            case 'POST':
                $this->post();
                break;
            case 'DELETE':
                $this->delete();
                break;
            default:
                $this->header('HTTP/1.1 405 Method Not Allowed');
        }
    }

    protected function get_full_url()
    {
        $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';

        return
            ($https ? 'https://' : 'http://').
            (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
            (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
            ($https && $_SERVER['SERVER_PORT'] === 443 ||
            $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
            substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
    }

    protected function get_user_id()
    {
        @session_start();

        return session_id();
    }

    protected function get_user_path()
    {
        if ($this->options['user_dirs']) {
            return $this->get_user_id().'/';
        }

        return '';
    }

    protected function get_upload_path($fileName = null, $version = null)
    {
        $fileName = $fileName ? $fileName : '';
        $versionPath = empty($version) ? '' : $version.'/';

        return $this->options['upload_dir'].$this->get_user_path()
            .$versionPath.$fileName;
    }

    protected function get_query_separator($url)
    {
        return strpos($url, '?') === false ? '?' : '&';
    }

    protected function get_download_url($fileName, $version = null)
    {
        if ($this->options['download_via_php']) {
            $url = $this->options['script_url']
                .$this->get_query_separator($this->options['script_url'])
                .'file='.rawurlencode($fileName);
            if ($version) {
                $url .= '&version='.rawurlencode($version);
            }

            return $url.'&download=1';
        }
        $versionPath = empty($version) ? '' : rawurlencode($version).'/';

        return $this->options['upload_url'].$this->get_user_path()
            .$versionPath.rawurlencode($fileName);
    }

    protected function set_file_delete_properties($file)
    {
        $file->deleteUrl = $this->options['script_url']
            .$this->get_query_separator($this->options['script_url'])
            .'file='.rawurlencode($file->name);
        $file->deleteType = $this->options['delete_type'];
        if ($file->deleteType !== 'DELETE') {
            $file->deleteUrl .= '&_method=DELETE';
        }
        if ($this->options['access_control_allow_credentials']) {
            $file->delete_with_credentials = true;
        }
    }

    // Fix for overflowing signed 32 bit integers,
    // works for sizes up to 2^32-1 bytes (4 GiB - 1):
    protected function fix_integer_overflow($size)
    {
        if ($size < 0) {
            $size += 2.0 * (PHP_INT_MAX + 1);
        }

        return $size;
    }

    protected function get_file_size($filePath, $clearStatCache = false)
    {
        if ($clearStatCache) {
            clearstatcache(true, $filePath);
        }

        return $this->fix_integer_overflow(filesize($filePath));
    }

    protected function is_valid_file_object($fileName)
    {
        $filePath = $this->get_upload_path($fileName);
        if (is_file($filePath) && $fileName[0] !== '.') {
            return true;
        }

        return false;
    }

    protected function get_file_object($fileName)
    {

        if ($this->is_valid_file_object($fileName)) {

            $qb = $this->entityManager->getRepository($this->options['entity_image_path'])
                    ->createQueryBuilder('i');
            $image = $qb->where($qb->expr()->like('i.path', ':path'))
                ->setParameter('path','%'.$fileName.'%')
                ->getQuery()
                ->getOneOrNullResult();

            if(!$image instanceof \CoreBundle\Entity\Image && !$image instanceof \BlogBundle\Entity\Image){
                return null;
            }

            $file = new \stdClass();
            $file->title = $image->getTitle();
            $file->alt = $image->getAlt();
            $file->name = $fileName;
            $file->size = $this->get_file_size(
                $this->get_upload_path($fileName)
            );
            $file->url = $this->get_download_url($file->name);
            foreach ($this->options['image_versions'] as $version => $options) {
                if (!empty($version)) {
                    if (is_file($this->get_upload_path($fileName, $version))) {
                        $file->{$version.'_url'} = $this->get_download_url(
                            $file->name,
                            $version
                        );
                    }
                }
            }
            $this->set_file_delete_properties($file);

            return $file;
        }

        return null;
    }

    protected function get_file_objects($iterationMethod = 'get_file_object')
    {

        $uploadDir = $this->get_upload_path();

        if (!is_dir($uploadDir)) {
            return array();
        }
        $returnValues = array_values(array_filter(array_map(
            array($this, $iterationMethod),
            scandir($uploadDir)
        )));

        return $returnValues;
    }

    protected function count_file_objects()
    {
        return count($this->get_file_objects('is_valid_file_object'));
    }

    protected function create_scaled_image($fileName, $version, $options)
    {
        $filePath = $this->get_upload_path($fileName);
        if (!empty($version)) {
            $versionDir = $this->get_upload_path(null, $version);
            if (!is_dir($versionDir)) {
                mkdir($versionDir, $this->options['mkdir_mode'], true);
            }
            $newFilePath = $versionDir.'/'.$fileName;
        } else {
            $newFilePath = $filePath;
        }
        if (!function_exists('getimagesize')) {
            error_log('Function not found: getimagesize');

            return false;
        }
        list($imgWidth, $imgHeight) = @getimagesize($filePath);
        if (!$imgWidth || !$imgHeight) {
            return false;
        }
        $maxWidth = $options['max_width'];
        $maxHeight = $options['max_height'];
        $scale = min(
            $maxWidth / $imgWidth,
            $maxHeight / $imgHeight
        );
        if ($scale >= 1) {
            if ($filePath !== $newFilePath) {
                return copy($filePath, $newFilePath);
            }

            return true;
        }
        if (!function_exists('imagecreatetruecolor')) {
            error_log('Function not found: imagecreatetruecolor');

            return false;
        }
        if (empty($options['crop'])) {
            $newWidth = $imgWidth * $scale;
            $newHeight = $imgHeight * $scale;
            $dstX = 0;
            $dstY = 0;
            $newImg = @imagecreatetruecolor($newWidth, $newHeight);
        } else {
            if (($imgWidth / $imgHeight) >= ($maxWidth / $maxHeight)) {
                $newWidth = $imgWidth / ($imgHeight / $maxHeight);
                $newHeight = $maxHeight;
            } else {
                $newWidth = $maxWidth;
                $newHeight = $imgHeight / ($imgWidth / $maxWidth);
            }
            $dstX = 0 - ($newWidth - $maxWidth) / 2;
            $dstY = 0 - ($newHeight - $maxHeight) / 2;
            $newImg = @imagecreatetruecolor($maxWidth, $maxHeight);
        }
        switch (strtolower(substr(strrchr($fileName, '.'), 1))) {
            case 'jpg':
            case 'jpeg':
                $srcImg = @imagecreatefromjpeg($filePath);
                $writeImage = 'imagejpeg';
                $imageQuality = isset($options['jpeg_quality']) ?
                    $options['jpeg_quality'] : 75;
                break;
            case 'gif':
                @imagecolortransparent($newImg, @imagecolorallocate($newImg, 0, 0, 0));
                $srcImg = @imagecreatefromgif($filePath);
                $writeImage = 'imagegif';
                $imageQuality = null;
                break;
            case 'png':
                @imagecolortransparent($newImg, @imagecolorallocate($newImg, 0, 0, 0));
                @imagealphablending($newImg, false);
                @imagesavealpha($newImg, true);
                $srcImg = @imagecreatefrompng($filePath);
                $writeImage = 'imagepng';
                $imageQuality = isset($options['png_quality']) ?
                    $options['png_quality'] : 9;
                break;
            default:
                $srcImg = null;
        }
        $success = $srcImg && @imagecopyresampled(
            $newImg,
            $srcImg,
            $dstX,
            $dstY,
            0,
            0,
            $newWidth,
            $newHeight,
            $imgWidth,
            $imgHeight
        ) && $writeImage($newImg, $newFilePath, $imageQuality);
        // Free up memory (imagedestroy does not delete files):
        @imagedestroy($srcImg);
        @imagedestroy($newImg);

        return $success;
    }

    protected function get_error_message($error)
    {
        return array_key_exists($error, $this->errorMessages) ?
            $this->errorMessages[$error] : $error;
    }

    /**
     * @param string $val
     *
     * @return float
     */
    public function get_config_bytes($val)
    {
        $val = trim($val);
        $last = strtolower($val[strlen($val)-1]);
        switch($last) {
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }

        return $this->fix_integer_overflow($val);
    }

    protected function validate($uploadedFile, $file, $error, $index)
    {
        if ($error) {
            $file->error = $this->get_error_message($error);

            return false;
        }
        $contentLength = $this->fix_integer_overflow(intval(
            $this->get_server_var('CONTENT_LENGTH')
        ));
        $postMaxSize = $this->get_config_bytes(ini_get('post_max_size'));
        if ($postMaxSize && ($contentLength > $postMaxSize)) {
            $file->error = $this->get_error_message('post_max_size');

            return false;
        }
        if (!preg_match($this->options['accept_file_types'], $file->name)) {
            $file->error = $this->get_error_message('accept_file_types');

            return false;
        }
        if ($uploadedFile && is_uploaded_file($uploadedFile)) {
            $fileSize = $this->get_file_size($uploadedFile);
        } else {
            $fileSize = $contentLength;
        }
        if ($this->options['max_file_size'] && (
            $fileSize > $this->options['max_file_size'] ||
                $file->size > $this->options['max_file_size'])
        ) {
            $file->error = $this->get_error_message('max_file_size');

            return false;
        }
        if ($this->options['min_file_size'] &&
            $fileSize < $this->options['min_file_size']) {
            $file->error = $this->get_error_message('min_file_size');

            return false;
        }
        if (is_int($this->options['max_number_of_files']) && (
            $this->count_file_objects() >= $this->options['max_number_of_files'])
        ) {
            $file->error = $this->get_error_message('max_number_of_files');

            return false;
        }
        list($imgWidth, $imgHeight) = @getimagesize($uploadedFile);
        if (is_int($imgWidth)) {
            if ($this->options['max_width'] && $imgWidth > $this->options['max_width']) {
                $file->error = $this->get_error_message('max_width');

                return false;
            }
            if ($this->options['max_height'] && $imgHeight > $this->options['max_height']) {
                $file->error = $this->get_error_message('max_height');

                return false;
            }
            if ($this->options['min_width'] && $imgWidth < $this->options['min_width']) {
                $file->error = $this->get_error_message('min_width');

                return false;
            }
            if ($this->options['min_height'] && $imgHeight < $this->options['min_height']) {
                $file->error = $this->get_error_message('min_height');

                return false;
            }
        }

        return true;
    }

    protected function upcount_name_callback($matches)
    {
        $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
        $ext = isset($matches[2]) ? $matches[2] : '';

        return ' ('.$index.')'.$ext;
    }

    protected function upcount_name($name)
    {
        return preg_replace_callback(
            '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
            array($this, 'upcount_name_callback'),
            $name,
            1
        );
    }

    protected function get_unique_filename($name, $type, $index, $contentRange)
    {
        while (is_dir($this->get_upload_path($name))) {
            $name = $this->upcount_name($name);
        }
        // Keep an existing filename if this is part of a chunked upload:
        $uploadedBytes = $this->fix_integer_overflow(intval($contentRange[1]));
        while (is_file($this->get_upload_path($name))) {
            if ($uploadedBytes === $this->get_file_size(
                $this->get_upload_path($name))) {
                break;
            }
            $name = $this->upcount_name($name);
        }

        return $name;
    }

    protected function trim_file_name($name, $type, $index, $contentRange)
    {
        // Remove path information and dots around the filename, to prevent uploading
        // into different directories or replacing hidden system files.
        // Also remove control characters and spaces (\x00..\x20) around the filename:
        $name = trim(basename(stripslashes($name)), ".\x00..\x20");
        // Use a timestamp for empty filenames:
        if (!$name) {
            $name = str_replace('.', '-', microtime(true));
        }
        // Add missing file extension for known image types:
        if (strpos($name, '.') === false &&
            preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
            $name .= '.'.$matches[1];
        }

        return $name;
    }

    protected function get_file_name($name, $type, $index, $contentRange)
    {
        return $this->get_unique_filename(
            $this->trim_file_name($name, $type, $index, $contentRange),
            $type,
            $index,
            $contentRange
        );
    }

    protected function handle_form_data($file, $index)
    {
        // Handle form data, e.g. $_REQUEST['description'][$index]
    }

    protected function orient_image($filePath)
    {
        if (!function_exists('exif_read_data')) {
            return false;
        }
        $exif = @exif_read_data($filePath);
        if ($exif === false) {
            return false;
        }
        $orientation = intval(@$exif['Orientation']);
        if (!in_array($orientation, array(3, 6, 8))) {
            return false;
        }
        $image = @imagecreatefromjpeg($filePath);
        switch ($orientation) {
            case 3:
                $image = @imagerotate($image, 180, 0);
                break;
            case 6:
                $image = @imagerotate($image, 270, 0);
                break;
            case 8:
                $image = @imagerotate($image, 90, 0);
                break;
            default:
                return false;
        }
        $success = imagejpeg($image, $filePath);
        // Free up memory (imagedestroy does not delete files):
        @imagedestroy($image);

        return $success;
    }

    protected function handle_image_file($filePath, $file)
    {
        if ($this->options['orient_image']) {
            $this->orient_image($filePath);
        }
        $failedVersions = array();
        foreach ($this->options['image_versions'] as $version => $options) {
            if ($this->create_scaled_image($file->name, $version, $options)) {
                if (!empty($version)) {
                    $file->{$version.'_url'} = $this->get_download_url(
                        $file->name,
                        $version
                    );
                } else {
                    $file->size = $this->get_file_size($filePath, true);
                }
            } else {
                $failedVersions[] = $version;
            }
        }
        switch (count($failedVersions)) {
            case 0:
                break;
            case 1:
                $file->error = 'Failed to create scaled version: '
                    .$failedVersions[0];
                break;
            default:
                $file->error = 'Failed to create scaled versions: '
                    .implode($failedVersions, ', ');
        }
    }

    protected function handle_file_upload($uploadedFile, $name, $size, $type, $error,
                                          $index = null, $contentRange = null)
    {
        $file = new \stdClass();
        $file->name = $this->get_file_name($name, $type, $index, $contentRange);
        $file->size = $this->fix_integer_overflow(intval($size));
        $file->type = $type;
        if ($this->validate($uploadedFile, $file, $error, $index)) {
            $this->handle_form_data($file, $index);
            $uploadDir = $this->get_upload_path();
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, $this->options['mkdir_mode'], true);
            }
            $filePath = $this->get_upload_path($file->name);
            $appendFile = $contentRange && is_file($filePath) &&
                $file->size > $this->get_file_size($filePath);
            if ($uploadedFile && is_uploaded_file($uploadedFile)) {
                // multipart/formdata uploads (POST method uploads)
                if ($appendFile) {
                    file_put_contents(
                        $filePath,
                        fopen($uploadedFile, 'r'),
                        FILE_APPEND
                    );
                } else {
                    move_uploaded_file($uploadedFile, $filePath);
                }
            } else {
                // Non-multipart uploads (PUT method support)
                file_put_contents(
                    $filePath,
                    fopen('php://input', 'r'),
                    $appendFile ? FILE_APPEND : 0
                );
            }
            $fileSize = $this->get_file_size($filePath, $appendFile);
            if ($fileSize === $file->size) {
                $file->url = $this->get_download_url($file->name);
                list($imgWidth, $imgHeight) = @getimagesize($filePath);
                if (is_int($imgWidth)) {
                    $this->handle_image_file($filePath, $file);
                }
            } else {
                $file->size = $fileSize;
                if (!$contentRange && $this->options['discard_aborted_uploads']) {
                    unlink($filePath);
                    $file->error = 'abort';
                }
            }
            $this->set_file_delete_properties($file);
        }

        return $file;
    }

    protected function readfile($filePath)
    {
        return readfile($filePath);
    }

    protected function body($str)
    {
        echo $str;
    }

    protected function header($str)
    {
        header($str);
    }

    protected function get_server_var($id)
    {
        return isset($_SERVER[$id]) ? $_SERVER[$id] : '';
    }

    protected function generate_response($content, $printResponse = true)
    {
        if ($printResponse) {
            $json = json_encode($content);
            $redirect = isset($_REQUEST['redirect']) ?
                stripslashes($_REQUEST['redirect']) : null;
            if ($redirect) {
                $this->header('Location: '.sprintf($redirect, rawurlencode($json)));

                return;
            }
            $this->head();
            if ($this->get_server_var('HTTP_CONTENT_RANGE')) {
                $files = isset($content[$this->options['param_name']]) ?
                    $content[$this->options['param_name']] : null;
                if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) {
                    $this->header('Range: 0-'.(
                        $this->fix_integer_overflow(intval($files[0]->size)) - 1
                    ));
                }
            }
            $this->body($json);
        }

        return $content;
    }

    protected function get_version_param()
    {
        return isset($_GET['version']) ? basename(stripslashes($_GET['version'])) : null;
    }

    protected function get_file_name_param()
    {
        return isset($_GET['file']) ? basename(stripslashes($_GET['file'])) : null;
    }

    protected function get_file_type($filePath)
    {
        switch (strtolower(pathinfo($filePath, PATHINFO_EXTENSION))) {
            case 'jpeg':
            case 'jpg':
                return 'image/jpeg';
            case 'png':
                return 'image/png';
            case 'gif':
                return 'image/gif';
            default:
                return '';
        }
    }

    protected function download()
    {
        if (!$this->options['download_via_php']) {
            $this->header('HTTP/1.1 403 Forbidden');

            return;
        }
        $fileName = $this->get_file_name_param();
        if ($this->is_valid_file_object($fileName)) {
            $filePath = $this->get_upload_path($fileName, $this->get_version_param());
            if (is_file($filePath)) {
                if (!preg_match($this->options['inline_file_types'], $fileName)) {
                    $this->header('Content-Description: File Transfer');
                    $this->header('Content-Type: application/octet-stream');
                    $this->header('Content-Disposition: attachment; filename="'.$fileName.'"');
                    $this->header('Content-Transfer-Encoding: binary');
                } else {
                    // Prevent Internet Explorer from MIME-sniffing the content-type:
                    $this->header('X-Content-Type-Options: nosniff');
                    $this->header('Content-Type: '.$this->get_file_type($filePath));
                    $this->header('Content-Disposition: inline; filename="'.$fileName.'"');
                }
                $this->header('Content-Length: '.$this->get_file_size($filePath));
                $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($filePath)));
                $this->readfile($filePath);
            }
        }
    }

    protected function send_content_type_header()
    {
        $this->header('Vary: Accept');
        if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) {
            $this->header('Content-type: application/json');
        } else {
            $this->header('Content-type: text/plain');
        }
    }

    protected function send_access_control_headers()
    {
        $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']);
        $this->header('Access-Control-Allow-Credentials: '
            .($this->options['access_control_allow_credentials'] ? 'true' : 'false'));
        $this->header('Access-Control-Allow-Methods: '
            .implode(', ', $this->options['access_control_allow_methods']));
        $this->header('Access-Control-Allow-Headers: '
            .implode(', ', $this->options['access_control_allow_headers']));
    }

    /**
     * Head method
     */
    public function head()
    {
        $this->header('Pragma: no-cache');
        $this->header('Cache-Control: no-store, no-cache, must-revalidate');
        $this->header('Content-Disposition: inline; filename="files.json"');
        // Prevent Internet Explorer from MIME-sniffing the content-type:
        $this->header('X-Content-Type-Options: nosniff');
        if ($this->options['access_control_allow_origin']) {
            $this->send_access_control_headers();
        }
        $this->send_content_type_header();
    }

    /**
     * Get method
     *
     * @param bool $printResponse
     *
     * @return array
     */
    public function get($printResponse = true)
    {

        if ($printResponse && isset($_GET['download'])) {

            return $this->download();
        }

        $fileName = $this->get_file_name_param();

        if ($fileName) {
            $response = array(
                substr($this->options['param_name'], 0, -1) => $this->get_file_object($fileName)
            );
        } else {
            $response = array(
                $this->options['param_name'] => $this->get_file_objects()
            );
        }

        return $this->generate_response($response, $printResponse);
    }

    /**
     * Post method
     *
     * @param bool $printResponse
     *
     * @throws NotFoundHttpException
     * @return mixed
     */
    public function post($printResponse = true)
    {
        if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
            return $this->delete($printResponse);
        }
        $upload = isset($_FILES[$this->options['param_name']]) ?
            $_FILES[$this->options['param_name']] : null;
        // Parse the Content-Disposition header, if available:
        /*$fileName = $this->get_server_var('HTTP_CONTENT_DISPOSITION') ?
            rawurldecode(preg_replace(
                '/(^[^"]+")|("$)/',
                '',
                $this->get_server_var('HTTP_CONTENT_DISPOSITION')
            )) : null;*/
        $fileName = $this->options['entity_slug'].'-'.md5(uniqid());
        // Parse the Content-Range header, which has the following form:
        // Content-Range: bytes 0-524287/2000000
        $contentRange = $this->get_server_var('HTTP_CONTENT_RANGE') ?
            preg_split('/[^0-9]+/', $this->get_server_var('HTTP_CONTENT_RANGE')) : null;
        $size =  $contentRange ? $contentRange[3] : null;
        $files = array();
        if ($upload && is_array($upload['tmp_name'])) {

            /** @var Product $entity */
            $entity = $this->entityManager->getRepository($this->options['entity_path'])->find($this->options['entity_id']);

            if (!$entity) {
                throw new NotFoundHttpException('Unable to find entity.');
            }

            // param_name is an array identifier like "files[]",
            // $_FILES is a multi-dimensional array:
            foreach ($upload['tmp_name'] as $index => $value) {
                $files[] = $this->handle_file_upload(
                    $upload['tmp_name'][$index],
                    $fileName ? $fileName : $upload['name'][$index],
                    $size ? $size : $upload['size'][$index],
                    $upload['type'][$index],
                    $upload['error'][$index],
                    $index,
                    $contentRange
                );

                // save the file name in the database
                /** @var Image $image */
                if($this->options['entity_path'] == 'BlogBundle:Post') {
                    $image = new PostImage();
                }elseif($this->options['entity_path'] == 'CatalogueBundle:Product'){
                    $image = new ProductImage();
                }
                $image->setPath('/uploads/images/'.$this->options['type'].'/'.$entity->getId().'/'.$files[$index]->name);
                $this->entityManager->persist($image);

                $entity->addImage($image);

                //add crop center thumbmail image
                // '260'=>array('w'=>260,'h'=>123),
                // '160'=>array('w'=>160,'h'=>100),
                // '104'=>array('w'=>104,'h'=>56),
                // '142'=>array('w'=>142,'h'=>88)
                //create source image
                if(isset($upload['type'][0]) && isset($upload['name'][0])){
                    $extension = $upload['type'][0];
                    $arr=array();
                    if($extension=='image/jpeg') {
                        $source = imagecreatefromjpeg($this->options['upload_dir'].$files[$index]->name);
                        if(preg_match('/\.jpeg/', $files[$index]->name)) $arr = explode('.jpeg', $files[$index]->name);
                        if(preg_match('/\.jpg/', $files[$index]->name)) $arr = explode('.jpg', $files[$index]->name);
                        $img_name = $arr[0];
                    }else if($extension=='image/gif') {
                        $source = imagecreatefromgif($this->options['upload_dir'].$files[$index]->name);
                        if(preg_match('/\.gif/', $files[$index]->name)) $arr = explode('.gif', $files[$index]->name);
                        $img_name = $arr[0];
                    }else if($extension=='image/png') {
                        $source = imagecreatefrompng($this->options['upload_dir'].$files[$index]->name);
                        if(preg_match('/\.png/', $files[$index]->name)) $arr = explode('.png', $files[$index]->name);
                        $img_name = $arr[0];
                    }
                    $this->resizeImage($source, $img_name.'_400', 400, 250);
                    $this->resizeImage($source, $img_name.'_380', 380, 180);
                    $this->resizeImage($source, $img_name.'_260', 260, 123);
                    $this->resizeImage($source, $img_name.'_142', 142, 88);

                }
            }

            $this->entityManager->persist($entity);
            $this->entityManager->flush();
        } else {
            // param_name is a single object identifier like "file",
            // $_FILES is a one-dimensional array:
            $files[] = $this->handle_file_upload(
                isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
                $fileName ? $fileName : (isset($upload['name']) ?
                    $upload['name'] : null),
                $size ? $size : (isset($upload['size']) ?
                    $upload['size'] : $this->get_server_var('CONTENT_LENGTH')),
                isset($upload['type']) ?
                $upload['type'] : $this->get_server_var('CONTENT_TYPE'),
                isset($upload['error']) ? $upload['error'] : null,
                null,
                $contentRange
            );
        }

        return $this->generate_response(
            array($this->options['param_name'] => $files),
            $printResponse
        );
    }

    /**
     * Delete method
     *
     * @param bool $printResponse
     *
     * @throws NotFoundHttpException
     * @return mixed
     */
    public function delete($printResponse = true)
    {
        $fileName = $this->get_file_name_param();
        $filePath = $this->get_upload_path($fileName);

        /** @var Image $entity */
        $qb = $this->entityManager->getRepository($this->options['entity_image_path'])
                    ->createQueryBuilder('i');
        $image = $qb->where($qb->expr()->like('i.path', ':path'))
            ->setParameter('path','%'.$fileName.'%')
            ->getQuery()
            ->getOneOrNullResult();

        /** @var Product $entity */
        $entity = $this->entityManager->getRepository($this->options['entity_path'])->find($this->options['entity_id']);

        if (!$image) {
            throw new NotFoundHttpException('Unable to find Image entity.');
        }
        if (!$entity) {
            throw new NotFoundHttpException('Unable to find Product entity.');
        }

        //this line reutn true when all is false ...&&
        $success = is_file($filePath) && $fileName[0] !== '.' && unlink($filePath);

        if ($success) {
            foreach ($this->options['image_versions'] as $version => $options) {

                if (!empty($version)) {
                    $file = $this->get_upload_path($fileName, $version);
                    if (is_file($file)) {
                        unlink($file);
                    }
                }
                // remove the file name from the database
                $entity->removeImage($image);
                $this->entityManager->remove($image);
            }

            $this->entityManager->persist($entity);
            $this->entityManager->flush();
        }

        return $this->generate_response(array('success' => $success), $printResponse);
    }

    public function resizeImage($source, $name, $newImageWidth, $newImageHeight) {
        //imagen vertical u horizontal
        $width  = imagesx($source);
        $height = imagesy($source);

        if($newImageWidth==null){
          $ratio = $newImageHeight / $height;
          $newImageWidth = round($width * $ratio);
        }

        if($newImageHeight==null){
          $ratio = $newImageWidth / $width;
          $newImageHeight = round($height * $ratio);
        }

        $source_ratio=$width/$height;
        $new_ratio=$newImageWidth/$newImageHeight;

        //imagen horizontal ajustar al alto
        if($new_ratio<$source_ratio){
          $ratio = $newImageHeight / $height;
          $width_aux = round($width * $ratio);
          $height_aux = $newImageHeight;
        }else{//imagen vertical ajustar al ancho
          $ratio = $newImageWidth / $width;
          $height_aux = round($height * $ratio);
          $width_aux = $newImageWidth;
        }

        $newImage = imagecreatetruecolor($width_aux,$height_aux);
        imagecopyresampled($newImage,$source,0,0,0,0,$width_aux,$height_aux,$width,$height);
        //imagedestroy($source);

        //recortar al centro
        if($width_aux==$newImageWidth && $height_aux==$newImageHeight){
          $newImage2=$newImage;
        }else{

          $centreX = ceil($width_aux / 2);
          $centreY = ceil($height_aux / 2);

          $cropWidth  = $newImageWidth;
          $cropHeight = $newImageHeight;
          $cropWidthHalf  = ceil($cropWidth / 2); // could hard-code this but I'm keeping it flexible
          $cropHeightHalf = ceil($cropHeight / 2);

          $x1 = max(0, $centreX - $cropWidthHalf);
          $y1 = max(0, $centreY - $cropHeightHalf);

          $x2 = min($width, $centreX + $cropWidthHalf);
          $y2 = min($height, $centreY + $cropHeightHalf);

          $newImage2 = imagecreatetruecolor($cropWidth,$cropHeight);
          //echo 'recorta '.$cropWidth.' '.$cropHeight.' '.$x1.' '.$y1.' '.$x2.' '.$y2.' '.$newImageWidth.' '.$newImageHeight;
          imagecopy($newImage2, $newImage, 0, 0, $x1, $y1, $newImageWidth, $newImageHeight);

        }
        //save image
        imagejpeg($newImage2, $this->options['upload_dir'].'/thumbnail/'.$name.'.jpg',90);

        return $newImage2;

    }

}