<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ConnectionsBundle\Sync\Extractor;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\ORM\AbstractQuery;
use ONGR\ConnectionsBundle\Sync\ActionTypes;
use ONGR\ConnectionsBundle\Sync\DiffProvider\Item\AbstractDiffItem;
use ONGR\ConnectionsBundle\Sync\DiffProvider\Item\CreateDiffItem;
use ONGR\ConnectionsBundle\Sync\DiffProvider\Item\DeleteDiffItem;
use ONGR\ConnectionsBundle\Sync\DiffProvider\Item\UpdateDiffItem;
use ONGR\ConnectionsBundle\Sync\Extractor\Descriptor\ExtractionCollection;
use ONGR\ConnectionsBundle\Sync\Extractor\Descriptor\ExtractionDescriptorInterface;
use ONGR\ConnectionsBundle\Sync\JobTableFields;
use ONGR\ConnectionsBundle\Sync\SyncStorage\SyncStorageInterface;

/**
 * Extractor that joins entities for insertion to SyncStorage.
 */
class DoctrineExtractor extends AbstractExtractor implements ExtractorInterface
{
    /**
     * @var SyncStorageInterface
     */
    private $storage;

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

    /**
     * @var ExtractionCollection
     */
    private $extractionCollection;

    /**
     * {@inheritdoc}
     *
     * @throws \LogicException
     */
    public function extract(AbstractDiffItem $item)
    {
        $connection = $this->getConnection();
        $descriptors = $this->getExtractionCollection()->getDescriptors();
        $action = $this->resolveItemAction($item);
        /** @var ExtractionDescriptorInterface $descriptor */
        foreach ($descriptors as $descriptor) {
            $table = $descriptor->getTable();
            if ($table === $item->getCategory() && $action === $descriptor->getTriggerTypeAlias()) {
                if ($action === ActionTypes::UPDATE
                    && !$this->isTrackedFieldModified($item, $descriptor)
                ) {
                    continue;
                }
                $insertList = $descriptor->getSqlInsertList();
                $idField = $insertList[JobTableFields::ID]['value'];

                $idFieldName = str_replace(['OLD.', 'NEW.'], '', $idField);
                $itemRow = $item->getItem();

                $statements = $descriptor->getRelations();

                if (isset($insertList[JobTableFields::TYPE]['value'])) {
                    $itemId = $itemRow[$idFieldName];

                    $storage = $this->getStorageFacility();
                    $storage->save(
                        $action,
                        $insertList[JobTableFields::TYPE]['value'],
                        $itemId,
                        $item->getTimestamp(),
                        $this->getShopIds()
                    );
                } elseif (empty($statements)) {
                    throw new \LogicException(
                        'Missing relations or no document type set in descriptor "'
                        . $descriptor->getName() . '"'
                    );
                }

                foreach ($statements as $statement) {
                    $selectQuery = $statement->getSelectQuery();
                    $sql = $this->inlineContext($selectQuery, $itemRow);
                    $executed = $connection->executeQuery($sql);
                    $this->saveResult($item, $executed);
                }
            }
        }
    }

    /**
     * @throws \LogicException
     *
     * @return Connection
     */
    public function getConnection()
    {
        if ($this->connection === null) {
            throw new \LogicException('setConnection must be called before getConnection.');
        }

        return $this->connection;
    }

    /**
     * @param Connection $connection
     */
    public function setConnection($connection)
    {
        $this->connection = $connection;
    }

    /**
     * {@inheritdoc}
     */
    public function getStorageFacility()
    {
        return $this->storage;
    }

    /**
     * {@inheritdoc}
     */
    public function setStorageFacility(SyncStorageInterface $storage)
    {
        $this->storage = $storage;
    }

    /**
     * @return ExtractionCollection
     */
    public function getExtractionCollection()
    {
        return $this->extractionCollection;
    }

    /**
     * @param ExtractionCollection $extractionCollection
     */
    public function setExtractionCollection($extractionCollection)
    {
        $this->extractionCollection = $extractionCollection;
    }

    /**
     * Returns action letter depending on item class.
     *
     * @param AbstractDiffItem $item
     *
     * @return string
     * @throws \InvalidArgumentException
     */
    protected function resolveItemAction(AbstractDiffItem $item)
    {
        if ($item instanceof CreateDiffItem) {
            $action = ActionTypes::CREATE;

            return $action;
        } elseif ($item instanceof DeleteDiffItem) {
            $action = ActionTypes::DELETE;

            return $action;
        } elseif ($item instanceof UpdateDiffItem) {
            $action = ActionTypes::UPDATE;

            return $action;
        } else {
            throw new \InvalidArgumentException('Unsupported diff item type. Got: ' . get_class($item));
        }
    }

    /**
     * Replace context placeholders with actual row values.
     *
     * @param string $selectQuery
     * @param array  $itemRow
     *
     * @return string
     */
    protected function inlineContext($selectQuery, $itemRow)
    {
        $selectQuery = str_replace(['OLD.', 'NEW.'], '__ctx__', $selectQuery);
        $prefixedKeys = array_map(
            function ($key) {
                return '__ctx__' . $key;
            },
            array_keys($itemRow)
        );
        $connection = $this->getConnection();
        $escapedValues = array_map(
            function ($value) use ($connection) {
                return $connection->quote($value);
            },
            array_values($itemRow)
        );
        $sql = str_replace($prefixedKeys, $escapedValues, $selectQuery);

        return $sql;
    }

    /**
     * Save results to storage.
     *
     * @param AbstractDiffItem $item
     * @param Statement        $results
     * @param string           $action
     */
    protected function saveResult(AbstractDiffItem $item, Statement $results, $action = 'U')
    {
        $storage = $this->getStorageFacility();
        while ($row = $results->fetch(AbstractQuery::HYDRATE_ARRAY)) {
            $storage->save(
                $action,
                $row[JobTableFields::TYPE],
                $row[JobTableFields::ID],
                $item->getTimestamp(),
                $this->getShopIds()
            );
        }
    }

    /**
     * Checks whether any of tracked fields has been modified.
     *
     * @param AbstractDiffItem              $item
     * @param ExtractionDescriptorInterface $relation
     *
     * @return bool
     *
     * @throws \InvalidArgumentException
     */
    private function isTrackedFieldModified(AbstractDiffItem $item, ExtractionDescriptorInterface $relation)
    {
        if (!$item instanceof UpdateDiffItem) {
            throw new \InvalidArgumentException('Wrong diff item type. Got: ' . get_class($item));
        }

        $trackedFields = $relation->getUpdateFields();
        if (empty($trackedFields)) {
            return true;
        }

        $itemRow = $item->getItem();
        $oldItemRow = $item->getOldItem();

        foreach (array_keys($trackedFields) as $key) {
            if (array_key_exists($key, $itemRow) && $itemRow[$key] !== $oldItemRow[$key]) {
                return true;
            }
        }

        return false;
    }
}


<?php

namespace ONGR\ConnectionsBundle\EventListener;

use Doctrine\ORM\EntityManager;
use ONGR\ConnectionsBundle\Pipeline\Event\SourcePipelineEvent;
use ONGR\ConnectionsBundle\Sync\SyncStorage\SyncStorageInterface;
use ONGR\ConnectionsBundle\Sync\SyncStorageImportIterator;
use ONGR\ElasticsearchBundle\ORM\Manager;

/**
 * Class SyncExecuteSourceEventListener - creates iterator which provides modified entities.
 */
class SyncExecuteSourceEventListener extends AbstractImportSourceEventListener
{
    /**
     * @var SyncStorageInterface
     */
    private $syncStorage;

    /**
     * @var int
     */
    private $shopId = 1;

    /**
     * @var int
     */
    private $chunkSize = 1;

    /**
     * @var string
     */
    private $documentType = '';

    /**
     * @param EntityManager        $manager
     * @param string               $entityClass
     * @param Manager              $elasticsearchManager
     * @param string               $documentClass
     * @param SyncStorageInterface $syncStorage
     */
    public function __construct(
        EntityManager $manager = null,
        $entityClass = null,
        Manager $elasticsearchManager = null,
        $documentClass = null,
        $syncStorage = null
    ) {
        parent::__construct($manager, $entityClass, $elasticsearchManager, $documentClass);
        $this->syncStorage = $syncStorage;
    }

    /**
     * Gets iterator for all documents which need to be updated.
     *
     * @return SyncStorageImportIterator
     */
    public function getDocuments()
    {
        return new SyncStorageImportIterator(
            [
                'sync_storage' => $this->getSyncStorage(),
                'shop_id' => $this->getShopId(),
                'document_type' => $this->getDocumentType(),
            ],
            $this->getElasticsearchManager()->getRepository($this->getDocumentClass()),
            $this->getDoctrineManager(),
            $this->getEntityClass()
        );
    }

    /**
     * Gets data and adds source.
     *
     * @param SourcePipelineEvent $event
     */
    public function onSource(SourcePipelineEvent $event)
    {
        $event->addSource($this->getDocuments());
    }

    /**
     * @return int
     */
    public function getChunkSize()
    {
        return $this->chunkSize;
    }

    /**
     * @param int $chunkSize
     */
    public function setChunkSize($chunkSize)
    {
        $this->chunkSize = $chunkSize;
    }

    /**
     * @return int
     */
    public function getShopId()
    {
        return $this->shopId;
    }

    /**
     * @param int $shopId
     */
    public function setShopId($shopId)
    {
        $this->shopId = $shopId;
    }

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

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

    /**
     * @return SyncStorageInterface
     */
    public function getSyncStorage()
    {
        if ($this->syncStorage === null) {
            throw new \LogicException('Sync storage must be set before using \'getSyncStorage\'');
        }

        return $this->syncStorage;
    }

    /**
     * @param SyncStorageInterface $syncStorage
     *
     * @return $this
     */
    public function setSyncStorage($syncStorage)
    {
        $this->syncStorage = $syncStorage;

        return $this;
    }
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ConnectionsBundle\Command;

use Doctrine\DBAL\Connection;
use InvalidArgumentException;
use ONGR\ConnectionsBundle\Sync\StorageManager\StorageManagerInterface;
use ONGR\ConnectionsBundle\Sync\SyncStorage\SyncStorage;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Command which creates storage place for SyncStorage data.
 */
class SyncStorageCreateCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('ongr:sync:storage:create')
            ->setDescription('Creates storage place for SyncStorage')
            ->addArgument(
                'storage',
                InputArgument::REQUIRED,
                'Storage to use. Available: ' . SyncStorage::STORAGE_MYSQL
            )
            ->addOption(
                'shop-id',
                null,
                InputOption::VALUE_OPTIONAL,
                'Shop id (optional)'
            );
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $storage = $input->getArgument('storage');
        $shopId = $input->getOption('shop-id');

        // Do not convert null value to integer, because null value is fully acceptable for required method.
        if ($shopId !== null) {
            $shopId = (int)$shopId;
        }

        switch ($storage) {
            case SyncStorage::STORAGE_MYSQL:
                /** @var Connection $connection */
                $connection = $this->getContainer()->get('doctrine.dbal.default_connection');
                /** @var StorageManagerInterface $storageManager */
                $storageManager = $this->getContainer()
                    ->get('ongr_connections.sync.storage_manager.mysql_storage_manager');
                break;
            default:
                throw new InvalidArgumentException('Storage "' . $storage . '" is not implemented yet.');
        }

        $result = $storageManager->createStorage($shopId, $connection);

        if ($result === null) {
            $output->writeln('<info>Storage for ' . $storage . ' already exists.</info>');
        } elseif ($result === true) {
            $output->writeln('<info>Storage successfully created for ' . $storage . '.</info>');
        } else {
            $output->writeln('<error>Failed to create storage for ' . $storage . '.</error>');
        }
    }
}


<?php

/**
 * Unauthorized copying or dissemination of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 *
 * @author    Jorge Torres <jorge.torres@wondeotec.com>
 * @copyright Copyright (C) Wondeotec SA - All Rights Reserved
 * @license   LICENSE.txt
 */

namespace EB\SDK\Webhook;

/**
 * Set of functions to help you on Emailbidding webhook creations
 */
class PayloadFactory
{
    /**
     * Creates a new Emailbidding webhook payload of hard bounce type
     *
     * @param string $recipientEmailAddress
     * @param string $recipientExternalId
     * @param string $listExternalId
     * @param string $ipAddress
     *
     * @return Payload
     */
    public static function createHardBounce(
        $recipientEmailAddress,
        $listExternalId,
        $recipientExternalId = null,
        $ipAddress = '127.0.0.1'
    ) {
        if ($recipientExternalId == null) {
            $recipientExternalId = rand(1, 99999);
        }

        return (new Payload())->setIpAddress($ipAddress)
            ->setAction(Type::HARD_BOUNCE)
            ->setCampaignId(rand(1, 99999))
            ->setListExternalId($listExternalId)
            ->setReason(Type::REASON_SYSTEM_AUTOMATIC)
            ->setRecipientEmailAddress($recipientEmailAddress)
            ->setHash(md5($recipientEmailAddress))
            ->setRecipientExternalId($recipientExternalId)
            ->setTriggerDate(new \DateTime())
            ->setType(Type::HARD_BOUNCE);
    }

    /**
     * Creates a new Emailbidding webhook payload of soft bounce type
     *
     * @param string $recipientEmailAddress
     * @param string $recipientExternalId
     * @param string $listExternalId
     * @param string $ipAddress
     *
     * @return Payload
     */
    public static function createSoftBounce(
        $recipientEmailAddress,
        $listExternalId,
        $recipientExternalId = null,
        $ipAddress = '127.0.0.1'
    ) {
        if ($recipientExternalId == null) {
            $recipientExternalId = rand(1, 99999);
        }

        return (new Payload())->setIpAddress($ipAddress)
            ->setAction(Type::SOFT_BOUNCE)
            ->setCampaignId(rand(1, 99999))
            ->setListExternalId($listExternalId)
            ->setReason(Type::REASON_SYSTEM_AUTOMATIC)
            ->setRecipientEmailAddress($recipientEmailAddress)
            ->setHash(md5($recipientEmailAddress))
            ->setRecipientExternalId($recipientExternalId)
            ->setTriggerDate(new \DateTime())
            ->setType(Type::SOFT_BOUNCE);
    }

    /**
     * Creates a new Emailbidding webhook payload of spam complaint type
     *
     * @param string $recipientEmailAddress
     * @param string $recipientExternalId
     * @param string $listExternalId
     * @param string $ipAddress
     *
     * @return Payload
     */
    public static function createSpamComplaint(
        $recipientEmailAddress,
        $listExternalId,
        $recipientExternalId = null,
        $ipAddress = '127.0.0.1'
    ) {
        if ($recipientExternalId == null) {
            $recipientExternalId = rand(1, 99999);
        }

        return (new Payload())->setIpAddress($ipAddress)
            ->setAction(Type::SPAM_COMPLAINT)
            ->setCampaignId(rand(1, 99999))
            ->setListExternalId($listExternalId)
            ->setReason(Type::REASON_USER_REQUEST)
            ->setRecipientEmailAddress($recipientEmailAddress)
            ->setHash(md5($recipientEmailAddress))
            ->setRecipientExternalId($recipientExternalId)
            ->setTriggerDate(new \DateTime())
            ->setType(Type::SPAM_COMPLAINT);
    }

    /**
     * Creates a new Emailbidding webhook payload of unsubscription type
     *
     * @param string $recipientEmailAddress
     * @param string $recipientExternalId
     * @param string $listExternalId
     * @param string $ipAddress
     *
     * @return Payload
     */
    public static function createUnsubscription(
        $recipientEmailAddress,
        $listExternalId,
        $recipientExternalId = null,
        $ipAddress = '127.0.0.1'
    ) {
        if ($recipientExternalId == null) {
            $recipientExternalId = rand(1, 99999);
        }

        return (new Payload())->setIpAddress($ipAddress)
            ->setAction(Type::UNSUBSCRIPTION)
            ->setCampaignId(rand(1, 99999))
            ->setListExternalId($listExternalId)
            ->setReason(Type::REASON_USER_REQUEST)
            ->setRecipientEmailAddress($recipientEmailAddress)
            ->setHash(md5($recipientEmailAddress))
            ->setRecipientExternalId($recipientExternalId)
            ->setTriggerDate(new \DateTime())
            ->setType(Type::UNSUBSCRIPTION);
    }

    /**
     * Creates a new Emailbidding webhook payload of click type
     *
     * @param string $recipientEmailAddress
     * @param string $recipientExternalId
     * @param string $listExternalId
     * @param string $ipAddress
     *
     * @return Payload
     */
    public static function createClick(
        $recipientEmailAddress,
        $listExternalId,
        $recipientExternalId = null,
        $ipAddress = '127.0.0.1'
    ) {
        if ($recipientExternalId == null) {
            $recipientExternalId = rand(1, 99999);
        }

        return (new Payload())->setIpAddress($ipAddress)
            ->setAction(Type::CLICK)
            ->setCampaignId(rand(1, 99999))
            ->setListExternalId($listExternalId)
            ->setReason(Type::REASON_USER_REQUEST)
            ->setRecipientEmailAddress($recipientEmailAddress)
            ->setHash(md5($recipientEmailAddress))
            ->setRecipientExternalId($recipientExternalId)
            ->setTriggerDate(new \DateTime())
            ->setType(Type::CLICK);
    }

    /**
     * Creates a new Emailbidding webhook payload of open type
     *
     * @param string $recipientEmailAddress
     * @param string $recipientExternalId
     * @param string $listExternalId
     * @param string $ipAddress
     *
     * @return Payload
     */
    public static function createOpen(
        $recipientEmailAddress,
        $listExternalId,
        $recipientExternalId = null,
        $ipAddress = '127.0.0.1'
    ) {
        if ($recipientExternalId == null) {
            $recipientExternalId = rand(1, 99999);
        }

        return (new Payload())->setIpAddress($ipAddress)
            ->setAction(Type::OPEN)
            ->setCampaignId(rand(1, 99999))
            ->setListExternalId($listExternalId)
            ->setReason(Type::REASON_USER_REQUEST)
            ->setRecipientEmailAddress($recipientEmailAddress)
            ->setHash(md5($recipientEmailAddress))
            ->setRecipientExternalId($recipientExternalId)
            ->setTriggerDate(new \DateTime())
            ->setType(Type::OPEN);
    }
}


<?php namespace Cerbero\Auth\Jobs;

use Cerbero\Auth\Exceptions\DisplayException;
use Cerbero\Auth\Repositories\UserRepositoryInterface;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Hashing\Hasher;

class ResetJob implements SelfHandling {

	/**
	 * @author	Andrea Marco Sartori
	 * @var		string	$password	Password input.
	 */
	public $password;

	/**
	 * @author	Andrea Marco Sartori
	 * @var		string	$token	Reset token.
	 */
	public $token;

	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct($password, $token)
	{
		$this->password = $password;

		$this->token = $token;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle(UserRepositoryInterface $users, Hasher $hasher)
	{
		if( ! $user = $users->findByResetToken($this->token))
		{
			throw new DisplayException('auth::reset.error');
		}

		$users->resetPassword($user, $hasher->make($this->password));
	}

}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ConnectionsBundle\Sync\DiffProvider\Binlog;

use Doctrine\DBAL\Connection;
use ONGR\ConnectionsBundle\Sync\DiffProvider\Item\DiffItemFactory;

/**
 * Decorator for binary logs which changes column indexes to names.
 */
class BinlogDecorator implements \Iterator
{
    /**
     * @var string Base name of the bin logs.
     */
    private $baseName;

    /**
     * @var string Directory of the bin logs.
     */
    private $directory;

    /**
     * @var array Mapping from ordinal field position to associative for all tables.
     */
    private $mappings = [];

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

    /**
     * @var string Connection to be used.
     */
    private $connectionName = 'default';

    /**
     * @var BinlogParser
     */
    private $binlogParser;

    /**
     * @param Connection    $connection
     * @param string        $dir
     * @param string        $baseName
     * @param \DateTime|int $from
     * @param int           $startType
     * @param string        $connectionName
     */
    public function __construct(Connection $connection, $dir, $baseName, $from, $startType, $connectionName = 'default')
    {
        $this->connection = $connection;
        $this->connectionName = $connectionName;
        $this->directory = $dir;
        $this->baseName = $baseName;
        $this->binlogParser = new BinlogParser($this->directory, $this->baseName, $from, $startType);
    }

    /**
     * Returns table mapping from ordinal field position to associative for all tables.
     *
     * @param string $table
     *
     * @return array|bool
     * @throws \UnderflowException
     */
    protected function getTableMapping($table)
    {
        if (array_key_exists($table, $this->mappings)) {
            return $this->mappings[$table];
        }

        $mapping = $this->retrieveMapping($table);

        if (empty($mapping)) {
            throw new \UnderflowException("Table with name {$table} not found.");
        }

        $this->mappings[$table] = $mapping;

        return $mapping;
    }

    /**
     * Retrieves mapping from database.
     *
     * @param string $table
     *
     * @return array|bool
     */
    protected function retrieveMapping($table)
    {
        $result = $this->connection->fetchAll(
            'SELECT
               COLUMN_NAME,
               ORDINAL_POSITION
             FROM
               INFORMATION_SCHEMA.COLUMNS
             WHERE TABLE_NAME = ?',
            [$table]
        );

        if (empty($result)) {
            return false;
        }

        $columns = [];

        foreach ($result as $column) {
            $columns[$column['ORDINAL_POSITION']] = $column['COLUMN_NAME'];
        }

        return $columns;
    }

    /**
     * Applies associative mapping to numbered columns.
     *
     * @param array      $params
     * @param array|bool $mapping
     *
     * @return array
     */
    public function applyMapping($params, $mapping)
    {
        $newParams = [];

        foreach ($params as $key => $value) {
            $newParams[$mapping[$key]] = $value;
        }

        return $newParams;
    }

    /**
     * {@inheritdoc}
     */
    public function current()
    {
        $buffer = $this->binlogParser->current();
        $type = $buffer[BinlogParser::PARAM_QUERY]['type'];

        $diffItem = DiffItemFactory::create($type);
        $diffItem->setTimestamp($buffer[BinlogParser::PARAM_DATE]);
        $diffItem->setDiffId($buffer[BinlogParser::PARAM_POSITION]);
        $diffItem->setCategory($buffer[BinlogParser::PARAM_QUERY]['table']);
        $mapping = $this->getTableMapping($diffItem->getCategory());

        if (isset($buffer[BinlogParser::PARAM_QUERY]['where'])) {
            $diffItem->setWhereParams(
                $this->applyMapping(
                    $buffer[BinlogParser::PARAM_QUERY]['where'],
                    $mapping
                )
            );
        }

        if (isset($buffer[BinlogParser::PARAM_QUERY]['set'])) {
            $diffItem->setSetParams(
                $this->applyMapping(
                    $buffer[BinlogParser::PARAM_QUERY]['set'],
                    $mapping
                )
            );
        }

        return $diffItem;
    }

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        $this->binlogParser->next();
    }

    /**
     * {@inheritdoc}
     */
    public function key()
    {
        return $this->binlogParser->key();
    }

    /**
     * {@inheritdoc}
     */
    public function valid()
    {
        return $this->binlogParser->valid();
    }

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        $this->binlogParser->rewind();
    }
}


<?php namespace Cerbero\Auth\Pipes\Recover;

use Cerbero\Auth\Pipes\AbstractPipe;
use Cerbero\Auth\Repositories\UserRepositoryInterface;

class Store extends AbstractPipe {

	/**
	 * Run after the handled job.
	 *
	 * @param	Cerbero\Auth\Repositories\UserRepositoryInterface	$user
	 * @param	mixed	$handled
	 * @param	Cerbero\Auth\Jobs\RecoverJob	$job
	 * @return	mixed
	 */
	public function after(UserRepositoryInterface $user, $handled, $job)
	{
		$user->assignResetToken($handled, $job->email);
	}

}


<?php

namespace Webcore\Validation\Rules;

use Webcore\Validation\AbstractRuleTrait;

trait Base64Trait
{
    use AbstractRuleTrait;

    /**
     * Allowed characters: A-Z, a-z, 0-9, +, /, =
     *
     * @param $value
     */
    private function validateBase64($value)
    {
        $isNotValid = base64_decode($value, true) === false;
        if ($isNotValid) {
            $this->throwInvalidArgumentMustBe("valid base_64");
        }
    }
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ConnectionsBundle\Import;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\PDOConnection;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use PDO;
use LogicException;

/**
 * Helper class for getting unbuffered queries.
 */
class UnbufferedConnectionHelper
{
    /**
     * Closes connection if open, opens a unbuffered connection.
     *
     * @param Connection $connection
     *
     * @throws InvalidArgumentException
     */
    public static function unbufferConnection(Connection $connection)
    {
        /** @var PDOConnection $wrappedConnection */
        $wrappedConnection = $connection->getWrappedConnection();

        if (!$wrappedConnection instanceof PDOConnection) {
            throw new InvalidArgumentException('unbufferConection can only be used with pdo_mysql Doctrine driver.');
        }

        if ($wrappedConnection->getAttribute(PDO::ATTR_DRIVER_NAME) != 'mysql') {
            throw new InvalidArgumentException(
                'unbufferConection can only be used with PDO mysql driver, got "' .
                $wrappedConnection->getAttribute(PDO::ATTR_DRIVER_NAME) . '" instead.'
            );
        }

        if ($connection->isConnected()) {
            $connection->close();
        }

        $connection->getWrappedConnection()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
        $connection->connect();
    }
}


<?php

namespace Scaleplan\Helpers;

use Scaleplan\Helpers\Exceptions\FileReturnedException;
use Scaleplan\Helpers\Exceptions\FileSaveException;
use Scaleplan\Helpers\Exceptions\FileUploadException;
use Scaleplan\Helpers\Exceptions\FileValidationException;

/**
 * Хэлпер манипуляций над файлами
 *
 * Class FileHelper
 *
 * @package Scaleplan\Helpers
 */
class FileHelper
{
    /**
     * Максимальный размер загружаемых файлов (в мегабатах)
     */
    public const FILE_UPLOAD_MAX_SIZE = 300;

    public const FREAD_DEFAULT_LENGTH = 1024;

    public const FILES_DIRECTORY_PATH = '/files';

    public const FILE_LOCATIONS_FILE_PATH = 'paths';

    /**
     * Сохранить массив в csv-файл
     *
     * @param array $data - массив данных
     * @param string $filePath - путь к директории файла
     * @param string $fileName - имя файла для сохраниения
     *
     * @throws FileReturnedException
     */
    public static function returnASCSVFile(array $data, string $filePath, string $fileName = 'tmp.csv'): void
    {
        $fileName = $filePath . '/' . $fileName;

        static::returnFile($fileName);

        $fp = fopen($fileName, 'wb');
        //fputs($fp, '\xEF\xBB\xBF');
        foreach ($data as $fields) {
            fputcsv($fp, $fields);
        }

        fclose($fp);

        static::returnFile($fileName);

        throw new FileReturnedException();
    }

    /**
     * Вернуть файл пользователю
     *
     * @param string $filePath - путь к файлу
     */
    public static function returnFile(string $filePath): void
    {
        if (file_exists($filePath)) {
            // сбрасываем буфер вывода PHP, чтобы избежать переполнения памяти выделенной под скрипт
            // если этого не сделать файл будет читаться в память полностью!
            if (ob_get_level()) {
                ob_end_clean();
            }
            // заставляем браузер показать окно сохранения файла
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($filePath));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($filePath));
            // читаем файл и отправляем его пользователю
            if ($fd = fopen($filePath, 'rb')) {
                while (!feof($fd)) {
                    print fread($fd, static::FREAD_DEFAULT_LENGTH);
                }

                fclose($fd);
            }

            exit;
        }
    }

    /**
     * Функция загрузки массива файлов на сервер
     *
     * @param array $files - массив файлов, которые прислала форма и мета-информация о них
     *
     * @return array
     *
     * @throws Exceptions\HelperException
     * @throws FileUploadException
     */
    public static function saveFiles(array $files): array
    {
        $saveFile = static function (array &$file, string &$uploadPath, int &$index = -1): ?array
        {
            if ($index >= 0) {
                $fn = &$file['name'][$index];
                $tn = &$file['tmp_name'][$index];
                $fe = &$file['error'][$index];
            } else {
                $fn = &$file['name'];
                $tn = &$file['tmp_name'];
                $fe = &$file['error'];
            }

            switch ($fe) {
                case UPLOAD_ERR_OK:
                    break;

                case UPLOAD_ERR_NO_FILE:
                    return null;

                case UPLOAD_ERR_INI_SIZE:
                    throw new FileSaveException(
                        'Размер принятого файла превысил максимально допустимый '
                        . 'размер, который задан директивой upload_max_filesize конфигурационного файла php.ini',
                        413
                    );

                case UPLOAD_ERR_FORM_SIZE:
                    throw new FileSaveException('Размер загружаемого файла превысил значение MAX_FILE_SIZE, '
                    . 'указанное в HTML-форме', 413);

                case UPLOAD_ERR_PARTIAL:
                    throw new FileSaveException('Загружаемый файл был получен только частично', 400);

                case UPLOAD_ERR_NO_TMP_DIR:
                    throw new FileSaveException('Отсутствует временная папка', 500);

                case UPLOAD_ERR_CANT_WRITE:
                    throw new FileSaveException('Не удалось записать файл на диск', 500);

                case UPLOAD_ERR_EXTENSION:
                    throw new FileSaveException('PHP-расширение остановило загрузку файла', 500);
            }

            $nameArray = explode('.', $fn);
            $ext = strtolower(end($nameArray));
            $newName = preg_replace(
                '/[\s,\/:;\?!*&^%#@$|<>~`]/',
                '',
                str_replace(
                    ' ',
                    '_',
                    str_replace($ext, '', $fn) . microtime(true)
                )
            );

            $fileMaxSizeMb = (int)(get_env('FILE_UPLOAD_MAX_SIZE') ?? static::FILE_UPLOAD_MAX_SIZE);

            if (!is_uploaded_file($tn)) {
                unlink($tn);
                throw new FileSaveException('Не удалось записать файл на диск', 500);
            }

            if (filesize($tn) > (1048576 * (int) $fileMaxSizeMb)) {
                unlink($tn);
                throw new FileSaveException(
                    "Размер загружаемого файла не может быть больше значения $fileMaxSizeMb мегабайт).", 413
                );
            }

            if (!($validExt = static::validateFileMimeType($tn))) {
                unlink($tn);
                throw new FileSaveException('Неподдерживаемый тип файла', 415);
            }

            if ($validExt !== $ext) {
                $ext = $validExt;
            }

            $newName = "$newName.$ext";
            $path = $uploadPath . $newName;
            if (!move_uploaded_file($tn, $path)) {
                throw new FileSaveException("Файл $fn не был корректно сохранен", 500);
            }

            $path = strtr($path, [$_SERVER['DOCUMENT_ROOT'] => '', static::getFilesDirectoryPath() => '']);
            return ['name' => $fn, 'path' => $path];
        };

        $result = [];
        foreach ($files as $field => &$file) {
            $filePath = static::getFilePath($field);
            $uploadPath = $_SERVER['DOCUMENT_ROOT'] . $filePath . '/';
            if (\is_array($file['name'])) {
                foreach ($file['name'] as $index => &$fn) {
                    if ($moveFile = $saveFile($file, $uploadPath, $index)) {
                        $result[$field][] = $moveFile;
                    }
                }

                unset($fn);
            } elseif ($moveFile = $saveFile($file, $uploadPath)) {
                $result[$field][0] = $moveFile;
            }
        }

        unset($file);
        return $result;
    }

    /**
     * @return string
     */
    public static function getFilesDirectoryPath() : string
    {
        return get_env('FILES_DIRECTORY_PATH') ?? static::FILES_DIRECTORY_PATH;
    }

    /**
     * @return string
     */
    public static function getLocationsFilePath() : string
    {
        return get_env('FILE_LOCATIONS_FILE_PATH') ?? static::FILE_LOCATIONS_FILE_PATH;
    }

    /**
     * Проверка расширения файла на возможность загрузки
     *
     * @param $extName - расширение файла
     *
     * @return bool
     *
     * @throws Exceptions\HelperException
     */
    public static function validateFileExt(string &$extName): bool
    {
        if (empty(Helper::getConf('exts')[strtolower($extName)])) {
            return false;
        }

        return true;
    }

    /**
     * Проверка mime-типа файла
     *
     * @param string $filePath - путь к файлу
     *
     * @return null|string
     *
     * @throws Exceptions\HelperException
     * @throws FileValidationException
     */
    public static function validateFileMimeType(string &$filePath): ?string
    {
        if (!file_exists($filePath)) {
            throw new FileValidationException("Файл $filePath не существует");
        }

        if (empty($validExt = Helper::getConf('mimes')[mime_content_type($filePath)])) {
            return null;
        }

        return $validExt;
    }

    /**
     * Возвращает путь к директории с заданным видом файлов
     *
     * @param string $fileKind - вид файлов
     *
     * @return string
     *
     * @throws Exceptions\HelperException
     * @throws FileUploadException
     */
    public static function getFilePath(string $fileKind): string
    {
        $locations = Helper::getConf(static::getLocationsFilePath());
        if (!\is_array($locations) || empty($locations[$fileKind])) {
            throw new FileUploadException("Для поля $fileKind не задан путь сохранения");
        }

        return $locations[$fileKind];
    }

    /**
     * Найти все файлы в каталоге, включая вложенные директории
     *
     * @param string $dirPath - путь к каталогу
     *
     * @return array
     */
    public static function getRecursivePaths(string $dirPath) : array
    {
        if (!\is_dir($dirPath)) {
            return [];
        }

        $dirPath = rtrim($dirPath, '/\ ');
        $paths = \scandir($dirPath, SCANDIR_SORT_NONE);
        unset($paths[0], $paths[1]);
        $result = [];

        foreach ($paths as $path) {
            $path = "$dirPath/$path";
            if (!\is_dir($path)) {
                $result[] = $path;
                continue;
            }

            $result += array_map(static function ($item) use ($path) {
                return "$path/$item";
            }, static::getRecursivePaths($path));
        }

        return $result;
    }
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ConnectionsBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use ONGR\ConnectionsBundle\Service\PairStorage;

/**
 * Command which sets/gets sync run-time parameters.
 */
class SyncParametersCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('ongr:sync:provide:parameter')
            ->setDescription('Sets or gets parameter value for sync.')
            ->addArgument(
                'parameter',
                InputArgument::REQUIRED,
                'Parameter name'
            )
            ->addOption(
                'set',
                null,
                InputOption::VALUE_REQUIRED,
                'Use --set="<new value>" to set new parameter value'
            );
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $parameter = $input->getArgument('parameter');
        $set = $input->getOption('set');

        /** @var PairStorage $pairStorage */
        $pairStorage = $this->getContainer()->get('ongr_connections.pair_storage');

        if (isset($parameter) & !empty($parameter)) {
            $setValue = $pairStorage->get($parameter);

            $output->writeln(
                "Parameter `$parameter`: " .
                ($setValue === null ? 'has no value.' : var_export($setValue, true))
            );

            if ($set) {
                $pairStorage->set($parameter, $set);
                $output->writeln('New value written: ' . var_export($set, true));
            } else {
                $output->writeln('If you want to write new value, use --set="<new value>" option.');
            }
        }
    }
}


<?php

namespace Data\Type;

use InvalidArgumentException;

abstract class Number extends Type
{
    /**
     * Negation. Product is always FloatType.
     *
     * @return FloatType
     */
    public function neg()
    {
        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType($this->value * -1);
    }

    /**
     * Addition. Product is always FloatType.
     *
     * @param  mixed $value
     * @return FloatType
     */
    public function add($value)
    {
        $value = Cast::Float($value);

        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType($this->value + $value);
    }

    /**
     * Subtraction. Product is always FloatType.
     *
     * @param  mixed $value
     * @return FloatType
     */
    public function sub($value)
    {
        $value = Cast::Float($value);

        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType($this->value - $value);
    }

    /**
     * Multiplication. Product is always FloatType.
     *
     * @param  mixed $value
     * @return FloatType
     */
    public function mul($value)
    {
        $value = Cast::Float($value);

        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType($this->value * $value);
    }

    /**
     * Division. Product is always FloatType.
     *
     * @param  mixed $value
     * @return FloatType
     */
    public function div($value)
    {
        $value = Cast::Float($value);

        if ($value == 0) {
            throw new InvalidArgumentException('Division by zero');
        }

        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType($this->value / $value);
    }

    /**
     * Modulus. Product is always FloatType.
     *
     * @param  mixed $value
     * @return FloatType
     */
    public function mod($value)
    {
        $value = Cast::Float($value);

        if ($value == 0) {
            throw new InvalidArgumentException('Division by zero');
        }

        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType($this->value % $value);
    }

    /**
     * Exponentiation. Product is always FloatType.
     *
     * @param  mixed $value
     * @return FloatType
     */
    public function exp($value)
    {
        $value = Cast::Float($value);

        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType(pow($this->value, $value));
    }

    /**
     * Alias of exp
     * @see exp
     */
    public function pow($value)
    {
        return $this->exp($value);
    }

    /**
     * Square root. Product is always FloatType.
     *
     * @return FloatType
     */
    public function sqrt()
    {
        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType(sqrt($this->value));
    }

    /**
     * Nth root. Product is always FloatType.
     *
     * @return FloatType
     */
    public function root($value)
    {
        $value = Cast::Float($value);

        if ($this->value === null) {
            return new FloatType($this->value);
        }

        return new FloatType(pow($this->value, 1 / $value));
    }

    /**
     * Equal
     *
     * @param  mixed $value
     * @return bool
     */
    public function eq($value)
    {
        $value = Cast::_Float($value);

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

        return false;
    }

    /**
     * Not equal
     *
     * @param  mixed $value
     * @return bool
     */
    public function ne($value)
    {
        $value = Cast::_Float($value);

        if ($this->value !== $value) {
            return true;
        }

        return false;
    }

    /**
     * Greater than
     *
     * @param  mixed $value
     * @return bool
     */
    public function gt($value)
    {
        $value = Cast::Float($value);

        if ($this->value !== null && $this->value > $value) {
            return true;
        }

        return false;
    }

    /**
     * Greater than or equal
     *
     * @param  mixed $value
     * @return bool
     */
    public function gte($value)
    {
        $value = Cast::Float($value);

        if ($this->value !== null && $this->value >= $value) {
            return true;
        }

        return false;
    }

    /**
     * Less than
     *
     * @param  mixed $value
     * @return bool
     */
    public function lt($value)
    {
        $value = Cast::Float($value);

        if ($this->value !== null && $this->value < $value) {
            return true;
        }

        return false;
    }

    /**
     * Less than or equal
     *
     * @param  mixed $value
     * @return bool
     */
    public function lte($value)
    {
        $value = Cast::Float($value);

        if ($this->value !== null && $this->value <= $value) {
            return true;
        }

        return false;
    }
}


<?php

namespace Asoc\Dadatata\Filter\ImageMagick;

use Asoc\Dadatata\Exception\ProcessingFailedException;
use Asoc\Dadatata\Filter\BaseMagickFilter;
use Asoc\Dadatata\Filter\DocumentImageOptions;
use Asoc\Dadatata\Filter\OptionsInterface;
use Asoc\Dadatata\Model\ThingInterface;

class PdfRender extends BaseMagickFilter
{
    public function canHandle(ThingInterface $thing)
    {
        return $thing->getMime() === 'application/pdf';
    }

    /**
     * @param ThingInterface                        $thing
     * @param string                                $sourcePath
     * @param OptionsInterface|DocumentImageOptions $options
     *
     * @throws \Asoc\Dadatata\Exception\ProcessingFailedException
     * @return array
     */
    public function process(ThingInterface $thing, $sourcePath, OptionsInterface $options = null)
    {
        $tmpPath = tempnam(sys_get_temp_dir(), 'Dadatata');

        $options = $this->defaults->merge($options);

        $pb = $this->getConvertProcess();
        $pb->add('-quality')->add($options->getQuality());

        // so the output resolution won't be crap
        $pb->add('-density')->add(150);

        // should fix resulting image in being black
        $pb->add('-background')->add('white');
        $pb->add('-alpha')->add('remove');

        $width  = $options->getWidth();
        $height = $options->getHeight();
        $pb->add('-resize')->add(sprintf('%dx%d', $width, $height));

        $pages = $options->getPages();
        if ($pages === 'all') {
            $pb->add(sprintf('%s', $sourcePath));
        } else {
            $pages = intval($pages);
            $pb->add(sprintf('%s[%s]', $sourcePath, $pages));
        }

        $pb->add(sprintf('%s:%s', $options->getFormat(), $tmpPath));

        $process = $pb->getProcess();
        $code    = $process->run();

        if ($code !== 0) {
            throw ProcessingFailedException::create(
                'Failed to render PDF as image',
                $code,
                $process->getOutput(),
                $process->getErrorOutput()
            );
        }

        $tmpPaths = [];
        if ($pages === 'all') {
            for ($i = 0, $n = $pages; $i < $n; $i++) {
                $tmpPaths[] = sprintf('%s-%d', $tmpPath, $i);
            }
        } else {
            $tmpPaths[] = $tmpPath;
        }

        return $tmpPaths;
    }
}


<?php

namespace Peyote;

/**
 * Building an INSERT query.
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Insert extends \Peyote\Query
{
	/**
	 * @var array  A list of columns to insert
	 */
	private $columns = array();

	/**
	 * @var array  A list of values to insert
	 */
	private $values = array();

	/**
	 * Specify the columns to insert.
	 *
	 * @param  array $columns  The columns
	 * @return \Peyote\Insert
	 */
	public function columns(array $columns)
	{
		$this->columns = $columns;
		return $this;
	}

	/**
	 * The values to add to the insert statement.
	 *
	 * @param  array $values  The column values
	 * @return \Peyote\Insert
	 */
	public function values(array $values)
	{
		$this->values[] = $values;
		return $this;
	}

	/**
	 * Compiles the query into raw SQL
	 *
	 * @return  string
	 */
	public function compile()
	{
		$sql = array("INSERT INTO");
		$sql[] = $this->table;
		$sql[] = "(".join(', ', $this->columns).")";
		$sql[] = "VALUES";

		$values = array();
		foreach ($this->values as $row)
		{
			$placeholders = array_fill(0, count($row), "?");
			$values[] = "(".join(", ", $placeholders).")";
			$this->params = array_merge($this->params, $row);
		}

		$sql[] = join(', ', $values);

		return join(' ', $sql);
	}

}


<?php

declare(strict_types=1);

namespace Wtf\ORM;

use Pimple\Container;
use Pimple\ServiceProviderInterface;

class Provider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Container $container): void
    {
        $container['medoo'] = $this->setMedoo($container);
        $container['entity'] = $this->setEntityLoader($container);
    }

    /**
     * Set Medoo into container.
     *
     * @param Container $container
     *
     * @return callable
     */
    protected function setMedoo(Container $container): callable
    {
        return function ($container) {
            $config = $container['config']('medoo');

            return new \Medoo\Medoo($config);
        };
    }

    /**
     * Set entity() function into container.
     *
     * @param Container $container
     *
     * @return callable
     */
    protected function setEntityLoader(Container $container): callable
    {
        return $container->protect(function (string $name) use ($container) {
            $parts = \explode('_', $name);
            $class = $container['config']('medoo.namespace');
            foreach ($parts as $part) {
                $class .= \ucfirst($part);
            }
            if (!$container->has('entity_'.$class)) {
                $container['entity_'.$class] = $container->factory(function ($container) use ($class) {
                    return new $class($container);
                });
            }

            return $container['entity_'.$class];
        });
    }
}


<?php
/**
 * AnimeDb package.
 *
 * @author    Peter Gribanov <info@peter-gribanov.ru>
 * @copyright Copyright (c) 2014, Peter Gribanov
 * @license   http://opensource.org/licenses/MIT
 */

namespace AnimeDb\Bundle\CacheTimeKeeperBundle\Command;

use AnimeDb\Bundle\CacheTimeKeeperBundle\Service\Keeper;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ResetCommand extends Command
{
    /**
     * @var Keeper
     */
    protected $keeper;

    /**
     * @param Keeper $keeper
     */
    public function __construct(Keeper $keeper)
    {
        $this->keeper = $keeper;
        parent::__construct();
    }

    protected function configure()
    {
        $this
            ->setName('cache:reset-cache-time-keeper')
            ->setDescription('Reset last update date of the project')
            ->setHelp('Command only reset date of update. Not remove data from the storage.');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return int|null
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->keeper->set(Keeper::LAST_UPDATE_KEY, new \DateTime());
        $output->writeln('Reset last update date of the project is complete.');
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yangguanghui\extFinal\components;

use yangguanghui\extFinal\Generator;
use yii\helpers\Json;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ActiveField extends \yii\widgets\ActiveField
{
    /**
     * @var Generator
     */
    public $model;

    /**
     * @inheritdoc
     */
    public function init()
    {
        $stickyAttributes = $this->model->stickyAttributes();
        if (in_array($this->attribute, $stickyAttributes)) {
            $this->sticky();
        }
        $hints = $this->model->hints();
        if (isset($hints[$this->attribute])) {
            $this->hint($hints[$this->attribute]);
        }
        $autoCompleteData = $this->model->autoCompleteData();
        if (isset($autoCompleteData[$this->attribute])) {
            if (is_callable($autoCompleteData[$this->attribute])) {
                $this->autoComplete(call_user_func($autoCompleteData[$this->attribute]));
            } else {
                $this->autoComplete($autoCompleteData[$this->attribute]);
            }
        }
    }

    /**
     * Makes field remember its value between page reloads
     * @return $this the field object itself
     */
    public function sticky()
    {
        $this->options['class'] .= ' sticky';

        return $this;
    }

    /**
     * Makes field auto completable
     * @param array $data auto complete data (array of callables or scalars)
     * @return $this the field object itself
     */
    public function autoComplete($data)
    {
        static $counter = 0;
        $this->inputOptions['class'] .= ' typeahead typeahead-' . (++$counter);
        foreach ($data as &$item) {
            $item = ['word' => $item];
        }
        $this->form->getView()->registerJs("yii.gii.autocomplete($counter, " . Json::htmlEncode($data) . ");");

        return $this;
    }
}


<?php
/**
 * Copyright WideFocus. See LICENSE.txt.
 * https://www.widefocus.net
 */

namespace WideFocus\Parameters;

/**
 * Sets parameters on subjects.
 */
class ParameterSetter implements ParameterSetterInterface
{
    /**
     * Set parameters on a subject.
     *
     * @param mixed                 $subject
     * @param ParameterBagInterface $parameters
     *
     * @return void
     *
     * @throws InvalidSubjectException When the subject is not an object.
     */
    public function setParameters($subject, ParameterBagInterface $parameters)
    {
        if (!is_object($subject)) {
            throw new InvalidSubjectException($subject);
        }

        if ($subject instanceof ParameterBagAwareInterface) {
            $subject->setParameters($parameters);
        } else {
            foreach ($parameters as $key => $value) {
                $this->setParameter($subject, $key, $value);
            }
        }
    }

    /**
     * Set a parameter on a subject.
     *
     * @param mixed  $subject
     * @param string $key
     * @param mixed  $value
     *
     * @return void
     */
    private function setParameter($subject, string $key, $value)
    {
        $setter = 'set' . $this->snakeToCamelCase($key);
        if (is_callable([$subject, $setter])) {
            call_user_func([$subject, $setter], $value);
        }
    }

    /**
     * Convert a string to camel case.
     *
     * @param string $value
     *
     * @return string
     */
    private function snakeToCamelCase(string $value): string
    {
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $value)));
    }
}


<?php declare(strict_types=1);

namespace Onion\Framework\Console\Factory;

use Onion\Framework\Console\Buffer;
use Onion\Framework\Console\Console;
use Onion\Framework\Dependency\Interfaces\FactoryInterface;
use Psr\Container\ContainerInterface as Container;

class ConsoleFactory implements FactoryInterface
{
    /**
     * Method that is called by the container, whenever a new
     * instance of the application is necessary. It is the only
     * method called when creating instances and thus, should
     * produce/return the fully configured object it is intended
     * to build.
     *
     * @param Container $container
     *
     * @return mixed
     */
    public function build(Container $container)
    {
        return new Console(
            new Buffer(
                $container->get('console.stream'),
                $container->has('console.autoFlush') ? $container->get('console.autoFlush') : true
            )
        );
    }
}


<?php
namespace Rzeka\DataHandlerBundle\Api;

use Rzeka\DataHandler\DataHandler;
use Rzeka\DataHandler\DataHandlerResult;
use Rzeka\DataHandlerBundle\Exception\InvalidJsonException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class ApiHandler
{
    /**
     * @param DataHandler $dataHandler
     */
    public function __construct(DataHandler $dataHandler)
    {
        $this->dataHandler = $dataHandler;
    }

    /**
     * @param Request $request
     * @param $data
     * @param array $options
     *
     * @return DataHandlerResult
     * @throws BadRequestHttpException
     */
    public function handle(Request $request, $data, array $options = []): DataHandlerResult
    {
        try {
            $requestData = $this->parseJsonData($request->getContent());

            return $this->dataHandler->handle($requestData, $data, $options);
        } catch (\OutOfBoundsException $e) {
            throw new BadRequestHttpException('Data hydration failed', $e);
        } catch (InvalidJsonException $e) {
            throw new BadRequestHttpException('JSON parsing failed', $e);
        }
    }

    /**
     * @param DataHandlerResult $result
     *
     * @return Response
     */
    public function getResponseFromResult(DataHandlerResult $result): Response
    {
        if ($result->isValid()) {
            return new Response('', Response::HTTP_NO_CONTENT);
        } else {
            return new JsonResponse(
                $result->getErrors(),
                Response::HTTP_UNPROCESSABLE_ENTITY
            );
        }
    }

    /**
     * @param string $jsonData
     *
     * @return array
     * @throws InvalidJsonException
     */
    public function parseJsonData(string $jsonData): array
    {
        $data = json_decode($jsonData, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new InvalidJsonException(sprintf(
                'Could not decode JSON: %s',
                json_last_error_msg()
            ));
        }

        return (array) $data;
    }
}


<?php

namespace Orchid\Log\Providers;

use Illuminate\Support\ServiceProvider;
use Orchid\Log\Contracts;
use Orchid\Log\Utilities;

class UtilitiesServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->registerLogLevels();
        $this->registerStyler();
        $this->registerLogMenu();
        $this->registerFilesystem();
        $this->registerFactory();
        $this->registerChecker();
    }

    /**
     * Register the log levels.
     */
    private function registerLogLevels()
    {
        $this->app->singleton(Contracts\Utilities\LogLevels::class, function ($app) {
            /**
             * @var \Illuminate\Config\Repository
             * @var \Illuminate\Translation\Translator $translator
             */
            $translator = $app['translator'];

            return new Utilities\LogLevels($translator, 'en');
        });

        $this->app->singleton('arcanedev.log-viewer.levels', Contracts\Utilities\LogLevels::class);
    }

    /**
     * Register the log styler.
     */
    private function registerStyler()
    {
        $this->app->singleton(Contracts\Utilities\LogStyler::class, Utilities\LogStyler::class);
        $this->app->singleton('arcanedev.log-viewer.styler', Contracts\Utilities\LogStyler::class);
    }

    /**
     * Register the log menu builder.
     */
    private function registerLogMenu()
    {
        $this->app->singleton(Contracts\Utilities\LogMenu::class, Utilities\LogMenu::class);
        $this->app->singleton('arcanedev.log-viewer.menu', Contracts\Utilities\LogMenu::class);
    }

    /**
     * Register the log filesystem.
     */
    private function registerFilesystem()
    {
        $this->app->singleton(Contracts\Utilities\Filesystem::class, function ($app) {
            /**
             * @var \Illuminate\Config\Repository
             * @var \Illuminate\Filesystem\Filesystem $files
             */
            $files = $app['files'];
            $filesystem = new Utilities\Filesystem($files, storage_path('logs'));

            $filesystem->setPattern(
                Utilities\Filesystem::PATTERN_PREFIX,
                Utilities\Filesystem::PATTERN_DATE,
                Utilities\Filesystem::PATTERN_EXTENSION
            );

            return $filesystem;
        });

        $this->app->singleton('arcanedev.log-viewer.filesystem', Contracts\Utilities\Filesystem::class);
    }

    /**
     * Register the log factory class.
     */
    private function registerFactory()
    {
        $this->app->singleton(Contracts\Utilities\Factory::class, Utilities\Factory::class);
        $this->app->singleton('arcanedev.log-viewer.factory', Contracts\Utilities\Factory::class);
    }

    /**
     * Register the log checker service.
     */
    private function registerChecker()
    {
        $this->app->singleton(Contracts\Utilities\LogChecker::class, Utilities\LogChecker::class);
        $this->app->singleton('arcanedev.log-viewer.checker', Contracts\Utilities\LogChecker::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            'arcanedev.log-viewer.levels',
            Contracts\Utilities\LogLevels::class,
            'arcanedev.log-viewer.styler',
            Contracts\Utilities\LogStyler::class,
            'arcanedev.log-viewer.menu',
            Contracts\Utilities\LogMenu::class,
            'arcanedev.log-viewer.filesystem',
            Contracts\Utilities\Filesystem::class,
            'arcanedev.log-viewer.factory',
            Contracts\Utilities\Factory::class,
            'arcanedev.log-viewer.checker',
            Contracts\Utilities\LogChecker::class,
        ];
    }
}


<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 */
namespace Peach\Markup;

/**
 * XML の仕様書で定義されている以下の EBNF に基づいて,
 * 要素名や属性名などのバリデーションを行います.
 *
 * <pre>
 * NameStartChar       ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] |
 *                         [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] |
 *                         [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
 * NameChar            ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
 * Name                ::= NameStartChar (NameChar)*
 * </pre>
 *
 * 参考文献: {@link http://www.w3.org/TR/REC-xml/ Extensible Markup Language (XML) 1.0 (Fifth Edition)}
 */
class NameValidator
{
    /**
     * このクラスはインスタンス化できません.
     */
    private function __construct() {}

    /**
     * 指定された文字列が XML で定義されている Name のネーミングルールに合致するかどうか調べます.
     *
     * @param  string $name 検査対象の文字列
     * @return bool         指定された文字列が Name として妥当な場合のみ true
     */
    public static function validate($name)
    {
        if (self::validateFast($name)) {
            return true;
        }

        $utf8Codec  = new \Peach\DF\Utf8Codec();
        $codepoints = $utf8Codec->decode($name);
        if (!count($codepoints)) {
            return false;
        }
        $start = array_shift($codepoints);
        if (!self::validateNameStartChar($start)) {
            return false;
        }
        foreach ($codepoints as $c) {
            if (!self::validateNameChar($c)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 使用頻度の高い Name 文字列 (例えば HTML タグなど) について,
     * 簡易な正規表現を使って検査します.
     *
     * @param  string $name 検査対象の文字列
     * @return bool         "h1", "img" など, ASCII 文字から成る妥当な Name 文字列の場合のみ true
     */
    private static function validateFast($name)
    {
        $firstNameCharClass = "[a-zA-Z_:]";
        $nameCharClass      = "[a-zA-Z0-9_:\\.\\-]";
        $pattern            = "/\\A{$firstNameCharClass}{$nameCharClass}*\\z/";
        return (0 < preg_match($pattern, $name));
    }

    /**
     * 指定された Unicode 符号点が NameStartChar の範囲に適合するかどうかを調べます.
     *
     * @param  int $codepoint Unicode 符号点
     * @return bool           引数が NameStartChar である場合のみ true
     */
    private static function validateNameStartChar($codepoint)
    {
        // @codeCoverageIgnoreStart
        static $range = null;
        if ($range === null) {
            $first = new NameValidator_Range(0x61, 0x7A); // a-z
            $range = $first
                    ->add(0x41, 0x5A)->add(0x3A)->add(0x5F) // A-Z, ":", "_"
                    ->add(0xC0, 0xD6)->add(0xD8, 0xF6)->add(0xF8, 0x2FF)
                    ->add(0x370, 0x37D)->add(0x37F, 0x1FFF)->add(0x200C, 0x200D)
                    ->add(0x2070, 0x218F)->add(0x2C00, 0x2FEF)->add(0x3001, 0xD7FF)
                    ->add(0xF900, 0xFDCF)->add(0xFDF0, 0xFFFD)->add(0x10000, 0xEFFFF);
        }
        // @codeCoverageIgnoreEnd

        return $range->validate($codepoint);
    }

    /**
     * 指定された Unicode 符号点が NameChar の範囲に適合するかどうかを調べます.
     *
     * @param  int $codepoint Unicode 符号点
     * @return bool           引数が NameChar である場合のみ true
     */
    private static function validateNameChar($codepoint)
    {
        // @codeCoverageIgnoreStart
        static $range = null;
        if ($range === null) {
            $first = new NameValidator_Range(0x30, 0x39); // 0-9
            $range = $first
                    ->add(0x2D, 0x2E)->add(0xB7) // "-", ".", MIDDLE DOT
                    ->add(0x0300, 0x036F)->add(0x203F, 0x2040);
        }
        // @codeCoverageIgnoreEnd

        return self::validateNameStartChar($codepoint) || $range->validate($codepoint);
    }
}

/**
 * 指定された Unicode 符号点が, 特定の範囲内に存在するかどうかを確認します.
 * @ignore
 */
class NameValidator_Range
{
    /**
     * 範囲の最小値です.
     * @var int
     */
    private $min;

    /**
     * 範囲の最大値です.
     * @var int
     */
    private $max;

    /**
     * 検査対象の Unicode 符号点がこのオブジェクトの
     * $min と $max の範囲内になかった場合に使用される次の Range オブジェクトです.
     *
     * @var NameValidator_Range
     */
    private $next;

    /**
     * 指定された Unicode 符号点の範囲を持つ NameValidator_Range オブジェクトを構築します.
     *
     * @param int $min 範囲の最小値
     * @param int $max 範囲の最大値
     * @param NameValidator_Range $next 次の Range オブジェクト (add が使用します)
     * @codeCoverageIgnore
     */
    public function __construct($min, $max, NameValidator_Range $next = null)
    {
        $this->min  = $min;
        $this->max  = ($max === null) ? $min : $max;
        $this->next = $next;
    }

    /**
     * このオブジェクトを次の Range オブジェクトとして設定した新しい Range オブジェクトを返します.
     *
     * @param  int $min 範囲の最小値
     * @param  int $max 範囲の最大値 (単一の値を指定する場合は省略可)
     * @return NameValidator_Range
     * @codeCoverageIgnore
     */
    public function add($min, $max = null)
    {
        return new self($min, $max, $this);
    }

    /**
     * 指定された Unicode 符号点がこのオブジェクトが示す範囲内に存在するかどうか調べます.
     * 次の Range オブジェクトが設定されている場合, 再帰的に validate() を実行した結果を返します.
     *
     * @param  int  $codepoint Unicode 符号点
     * @return bool            引数が範囲内に存在する場合のみ true
     */
    public function validate($codepoint)
    {
        return
            ($this->min <= $codepoint && $codepoint <= $this->max) ||
            ($this->next !== null && $this->next->validate($codepoint));
    }
}


<?php

namespace Asoc\Dadatata\Filter\ImageMagick;

use Asoc\Dadatata\Exception\ProcessingFailedException;
use Asoc\Dadatata\Filter\BaseMagickFilter;
use Asoc\Dadatata\Filter\ImageOptions;
use Asoc\Dadatata\Filter\OptionsInterface;
use Asoc\Dadatata\Model\ImageInterface;
use Asoc\Dadatata\Model\ThingInterface;

class Thumbnail extends BaseMagickFilter
{
    /**
     * @param ThingInterface|ImageInterface $thing
     * @param string                        $sourcePath
     * @param OptionsInterface|ImageOptions $options
     *
     * @throws \Asoc\Dadatata\Exception\ProcessingFailedException
     * @return array Paths to generated files
     */
    public function process(ThingInterface $thing, $sourcePath, OptionsInterface $options = null)
    {
        $tmpPath = tempnam(sys_get_temp_dir(), 'Dadatata');

        $options = $this->defaults->merge($options);

        $pb = $this->getConvertProcess();
        $pb->add('-quality')->add($options->getQuality());

        $width  = $options->getWidth();
        $height = $options->getHeight();

        if ($thing->getWidth() > $width && $thing->getHeight() > $height) {
            if ($width === $height) {
                // square image
                // http://www.imagemagick.org/Usage/thumbnails/#cut
                $single  = sprintf('%dx%d', $width, $height);
                $doubled = sprintf('%dx%d', $width * 2, $height * 2);
                //$pb->add('-define')->add(sprintf('jpeg:size=%s', $doubled));
                $pb->add('-thumbnail')->add(sprintf('%s^', $single));
                $pb->add('-gravity')->add('center');
                $pb->add('-extent')->add($single);
            } else {
                $pb->add('-thumbnail')->add(sprintf('%dx%d', $width, $height));
            }
        }

        $pb->add(sprintf('%s[0]', $sourcePath));
        $pb->add(sprintf('%s:%s', $options->getFormat(), $tmpPath));

        $process = $pb->getProcess();
        $code    = $process->run();

        if ($code !== 0) {
            throw ProcessingFailedException::create(
                'Failed to create thumbnail',
                $code,
                $process->getOutput(),
                $process->getErrorOutput()
            );
        }

        return [$tmpPath];
    }
}


<?php

/*
 * This file is part of the Mamasu Framework package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Mmf\Event;

/**
 * The MmfEventManager is a class used to manage the event dispached and notify
 * the observer listen to that events.
 *
 * This class have the static method instance, used to get one instance of the
 * class.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */

class EventManager implements EventManagerInterface{

    /**
     * List of Observers
     * @var SplObjectStorage
     */
    private $_observers;

    /**
     * @var EventAbstract
     */
    public $event;

    public function __construct() {
        $this->_observers = new \SplObjectStorage();
    }

    /**
     * Add new observer to the list
     *
     * @param \SplObserver        $observer
     * @param string|null         $eventName
     * @param string|null         $function
     * @param mixed |null         $order
     */
    public function attach(\SplObserver $observer, $eventName = Null, $function = Null, $order = Null) {
        $newEventAttach = new \stdClass();
        $newEventAttach->observer  = $observer;
        $newEventAttach->function  = $function;
        $newEventAttach->eventName = $eventName;
        $newEventAttach->order     = $order;
        $this->_observers->attach($newEventAttach);
    }

    /**
     * Delete the observer from the list
     *
     * @param \SplObserver $observer
     */
    public function detach(\SplObserver $observer) {
        foreach ($this->_observers as $observerItem) {
            if ($observerItem->observer === $observer) {
                $this->_observers->detach($observerItem);
            }
        }
    }

    /**
     * Send a notification to the correct observer
     */
    public function notify() {
        $observersToNotify = array();

        //Check which observers must be update
        foreach ($this->_observers as $observer) {
            if ($this->checkIfObserverMustBeUpdate($observer)) {
                //Add the observers in array to be order for priority
                $observersToNotify[] = $observer;
            }
        }

        //Order the list of observers
        usort($observersToNotify, array($this,'orderObserversForPriority'));

        //Update the observers
        foreach ($observersToNotify as $observer) {
            try {
                $this->updateObserverState($observer);
            } catch (\Exception $e) {
                if ((int)$e->getCode()===600) { //Stop propagation
                    break 1;
                }
            }
        }

    }

    /**
     * Order The observers using the order integer value. Lower number is going
     * to execute first, in case of have the same order it goes first the first
     * observer assign to the event.
     *
     * @param stdClass $a
     * @param stdClass $b
     * @return int
     */
    private function orderObserversForPriority($a, $b) {
        if($a->order > $b->order) {
            return +1;
        } elseif ($a->order == $b->order) {
            return 0;
        }
        return -1;
    }

    /**
     * Returns if the observer must be update.
     *
     * @param StdClass $observer
     * @return boolean
     */
    private function checkIfObserverMustBeUpdate (\StdClass $observer) {
        if ($observer->eventName == $this->event->name) {
            return true;
        }
        return false;
    }

    /**
     * Update the correct observer match with the same name.
     *
     * @param StdClass $observer
     */
    private function updateObserverState(\StdClass $observer) {
        $this->event->function = $observer->function;
        $observerObject = $observer->observer;
        $observerObject->update($this);
    }

    /**
     * This method is used for other classes when they want to dispatch an
     * event. It requires and Event.
     *
     * @param EventAbstract $event
     * @return void
     */
    public function dispatch(EventAbstract $event) {
        $this->event = $event;
        $this->notify();
    }

}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Builder;

/**
 * ParameterTrait
 *
 * Dealing with positioned parameters
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     ParameterInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait ParameterTrait
{
    /**
     * store positioned parameters
     *
     * @var    array
     * @access protected
     * @staticvar
     */
    protected static $positioned_params = [];

    /**
     * builder-wide position count
     *
     * @var    int
     * @access protected
     * @staticvar
     */
    protected static $positioned_count  = 0;

    /**
     *{@inheritDoc}
     */
    public function generatePlaceholder($value)/*# : string */
    {
        $key = '__PH_' . ++self::$positioned_count . '__';
        self::$positioned_params[$key] = $value;
        return $key;
    }

    /**
     * {@inheritDoc}
     */
    public function getPlaceholderMapping()/*# : array */
    {
        return self::$positioned_params;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: seyfer
 * Date: 21.01.15
 * Time: 18:12
 */

namespace ZendMover\Command;

use ZendMover\MoverInterface;

/**
 * Class AbstractMoveCommand
 *
 * @package ZendMover\Command
 */
abstract class AbstractMoveCommand implements MoveCommandInterface
{
    /**
     * @var string
     */
    protected $fromDirectory = '';

    /**
     * @var string
     */
    protected $toDirectory = '';

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

    /**
     * @var bool
     */
    protected $usePathReplace = FALSE;

    /**
     * @var array
     */
    protected $pathReplaceParts
        = [
            "search"  => "",
            "replace" => "",
        ];

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

    /**
     * @var MoverInterface
     */
    protected $mover;

    /**
     * @param MoverInterface $mover
     */
    public function __construct(MoverInterface $mover)
    {
        $this->setMover($mover);
    }

    /**
     * @return bool
     */
    public function isUsePathReplace()
    {
        return $this->usePathReplace;
    }

    /**
     * @param $filePathFrom
     * @return mixed
     */
    public function replacePath($filePathFrom)
    {
        $filePathTo = str_replace(
            $this->pathReplaceParts['search'], $this->pathReplaceParts['replace'], $filePathFrom
        );

        return $filePathTo;
    }

    /**
     * @param $filePathFrom
     * @return mixed
     */
    public function replacePathBack($filePathFrom)
    {
        $filePathTo = str_replace(
            $this->pathReplaceParts['replace'], $this->pathReplaceParts['search'], $filePathFrom
        );

        return $filePathTo;
    }

    /**
     * @param boolean $usePathReplace
     * @return $this
     */
    public function setUsePathReplace($usePathReplace)
    {
        $this->usePathReplace = $usePathReplace;

        return $this;
    }

    /**
     * @param array $pathReplaceParts
     * @return $this
     */
    public function setPathReplaceParts($pathReplaceParts)
    {
        $this->pathReplaceParts = $pathReplaceParts;

        return $this;
    }

    /**
     * @return MoverInterface
     */
    public function getMover()
    {
        return $this->mover;
    }

    /**
     * @param MoverInterface $mover
     * @return $this
     */
    public function setMover(MoverInterface $mover)
    {
        $this->mover = $mover;

        return $this;
    }

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

    /**
     *
     * @param  \stdClass|Array $filesToMove
     * @return $this
     * @throws \RuntimeException
     */
    public function setFilesToMove($filesToMove)
    {
        if (is_object($filesToMove)) {
            if (method_exists($filesToMove, 'toArray')) {
                $filesToMove = $filesToMove->toArray();
            } else {
                throw new \RuntimeException(__METHOD__ . " need array as param");
            }
        }

        if (is_array($filesToMove)) {
            $this->filesToMove = $filesToMove;
        }

        return $this;
    }

    /**
     * @return $this
     */
    public function convertFilesToSpl()
    {
        if (!$this->filesToMove) {
            return null;
        }

        $converted = [];
        foreach ($this->filesToMove as $fileToMove) {
            if ($fileToMove instanceof \SplFileInfo) {
                $converted[] = $fileToMove;
            } else {
                $convertedFile = new \SplFileInfo($fileToMove);
                $converted[]   = $convertedFile;
            }
        }

        $this->filesToMove = $converted;

        return $this;
    }

    /**
     * @param \SplFileInfo $fileToMove
     * @return $this
     */
    public function addFileToMove(\SplFileInfo $fileToMove)
    {
        if (!$fileToMove->isFile()) {
            //            Debug::dump($fileToMove);

            throw new \RuntimeException(__METHOD__ . " added file not exist");
        }

        $this->filesToMove[] = $fileToMove;

        return $this;
    }

    private function emptyFileList()
    {
        $this->filesToMove = [];
    }

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

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

    /**
     * inspect file directory and set it
     *
     * @param $file
     * @return $this
     */
    public function setToDirectoryFromFile($file)
    {
        $fileDir = $this->getFilePath($file);

        $this->setToDirectory($fileDir);

        return $this;
    }

    /**
     * inspect file directory and set it
     *
     * @param $file
     * @return $this
     */
    public function setFromDirectoryFromFile($file)
    {
        $fileDir = $this->getFilePath($file);

        $this->setFromDirectory($fileDir);

        return $this;
    }

    /**
     * @param \SplFileInfo|string $file
     * @return string
     */
    protected function getFilePath($file)
    {
        if (!$file) {
            throw new \InvalidArgumentException(__METHOD__ . $file .
                                                " param invalid");
        }

        if (!$file instanceof \SplFileInfo) {
            $file = new \SplFileInfo($file);
        }

        $fileDir = $file->getPath();

        return $fileDir;
    }

    /**
     *
     * @param  $toDirectory
     * @return $this
     */
    public function setToDirectory($toDirectory)
    {
        if (!$toDirectory) {
            return null;
        }

        try {
            $this->checkIsDir($toDirectory);
        } catch (\Exception $e) {
            $this->prepareDir($toDirectory);
        }

        $this->checkIsWritable($toDirectory);

        $this->toDirectory = $toDirectory;

        return $this;
    }

    /**
     * @param $path
     * @throws \Exception
     */
    private function prepareDir($path)
    {
        if (!is_dir($path)) {
            if (!mkdir($path, 0777, true)) {
                throw new \Exception('Directory of ' . $path . ' was not created');
            }
        } else {
            if (substr(sprintf('%o', fileperms($path)), -4) != '0777') {
                if (!chmod($path, 0777)) {
                    throw new \Exception('Cannot change access to ' . $path);
                }
            }
        }
    }

    /**
     * @param  $fromDirectory
     * @return $this
     */
    public function setFromDirectory($fromDirectory)
    {
        if (!$fromDirectory) {
            return null;
        }

        $this->checkIsDir($fromDirectory);

        $this->fromDirectory = $fromDirectory;

        return $this;
    }

    /**
     * @param  $dir
     * @return boolean
     * @throws \InvalidArgumentException
     */
    protected function checkIsWritable($dir)
    {
        if (!is_writable($dir)) {
            throw new \InvalidArgumentException(__METHOD__ . " " . $dir .
                                                " is not writable");
        }

        return TRUE;
    }

    /**
     *
     * @param  $dir
     * @return boolean
     * @throws \InvalidArgumentException
     */
    protected function checkIsDir($dir)
    {
        if (!is_dir($dir)) {
            throw new \InvalidArgumentException(__METHOD__ . $dir .
                                                " not is dir");
        }

        return TRUE;
    }

    public function reverseFromToDirs()
    {
        $tmpFrom = $this->getFromDirectory();
        $this->setFromDirectory($this->getToDirectory());
        $this->setToDirectory($tmpFrom);
    }

    /**
     * default
     */
    public function execute()
    {
        $this->mover->iLikeToMoveItMoveIt($this);
    }

    /**
     * default
     */
    public function unexecute()
    {
        $this->mover->iLikeToMoveItMoveItBack();
    }

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

    /**
     * @param string $destinationFileName
     * @return $this
     */
    public function setDestinationFileName($destinationFileName)
    {
        $this->destinationFileName = $destinationFileName;

        return $this;
    }
}


<?php

namespace RickySu\Tagcache\Adapter;

use RickySu\Tagcache\TagcacheObj;
use RickySu\Tagcache\TagcacheTime;

abstract class TagcacheAdapter
{
    const TAG_PREFIX = 'Tagcache#Tag';
    const LOCK_PREFIX = 'Tagcache#Lock';
    const TAG_CLEAR_ALL = '__Tagcache__All';

    protected $Namespace = null;
    protected $Options = null;
    protected $hLock = array();

    public function __construct($NameSpace, $Options)
    {
        $this->Namespace = $NameSpace;
        $this->Options = $Options;
    }

    protected function buildKey($Key)
    {
        if ($this->Options['hashkey']) {
            return md5("{$this->Namespace}:$Key");
        }

        return "{$this->Namespace}:$Key";
    }

    protected function getLockFile($Key)
    {
        $LockFileDir = $this->Options['cache_dir'] . DIRECTORY_SEPARATOR . 'LCK';
        if (!file_exists($LockFileDir)) {
            mkdir($LockFileDir, 0777, true);
        }
        $KeyHash = md5($this->buildKey($Key));

        return $LockFileDir . DIRECTORY_SEPARATOR . "$KeyHash.lck";
        ;
    }

    public function getLock($Key, $LockExpire = 5)
    {
        $LockFile = $this->getLockFile($Key);
        @$Timestamp = (int) file_get_contents($LockFile);
        $hLock = fopen($LockFile, "w");
        if ($Timestamp + $LockExpire < time()) { //Old Lock File
            flock($hLock, LOCK_UN);
        }
        $StartTime = time();
        fwrite($hLock, $StartTime);
        while (!flock($hLock, LOCK_EX | LOCK_NB)) {
            usleep(rand(1, 500));
            if (time() - $StartTime > $LockExpire) { //Wait Lock Timeout
                flock($hLock, LOCK_UN);     //Steal Lock
                flock($hLock, LOCK_EX | LOCK_NB);
                break;
            }
        }
        $this->hLock[$LockFile] = $hLock;
    }

    public function releaseLock($Key)
    {
        $LockFile = $this->getLockFile($Key);
        if (!isset($this->hLock[$LockFile])) {
            $hLock = fopen($LockFile, "w");
        } else {
            $hLock = $this->hLock[$LockFile];
            unset($this->hLock[$LockFile]);
        }
        flock($hLock, LOCK_UN);
        fclose($hLock);
        unlink($LockFile);
    }

    /**
     * Store Cache
     * @param string $key
     * @param mixed  $var
     * @param array  $Tags
     * @param float  $expire
     */
    public function set($key, $var, $Tags = array(), $expire = null)
    {
        if ($expire) {
            $expire+=TagcacheTime::time();
        }
        if (is_array($Tags)) {
            array_push($Tags, self::TAG_CLEAR_ALL);
            foreach ($Tags as $Tag) {
                if ($this->getTagUpdateTimestamp($Tag) === false) {
                    $this->setRaw($this->buildKey(self::TAG_PREFIX . $Tag), TagcacheTime::time(), 0);
                }
            }
        }
        $Obj = new TagcacheObj($var, $Tags, $expire);

        return $this->setRaw($this->buildKey($key), $Obj, $expire);
    }

    /**
     * get cache
     * @param  string $key
     * @return mixed
     */
    public function get($key)
    {
        $Obj = $this->getRaw($this->buildKey($key));
        if ($Obj instanceof TagcacheObj) {
            $Data = $Obj->getVar($this);
            if ($Data === false) {
                $this->delete($key);
            }

            return $Data;
        }

        return $Obj;
    }

    /**
     * delete cache
     * @param  string $key
     * @return bool
     */
    public function delete($key)
    {
        return $this->deleteRaw($this->buildKey($key));
    }

    /**
     * tag delete
     * @param  string $Tag
     * @return bool
     */
    public function deleteTag($Tag)
    {
        return $this->deleteRaw($this->buildKey(self::TAG_PREFIX . $Tag));
    }

    /**
     * clear all cache
     * @return bool
     */
    public function clear()
    {
        return $this->deleteTag(self::TAG_CLEAR_ALL);
    }

    /**
     * get tag updated timestamp
     * @param  string $key
     * @return float
     */
    public function getTagUpdateTimestamp($tag)
    {
        return $this->getRaw($this->buildKey(self::TAG_PREFIX . $tag));
    }

    /**
     * get tags
     * @param  type    $key
     * @return boolean
     */
    public function getTags($key)
    {
        $Obj = $this->getRaw($this->buildKey($key));
        if ($Obj instanceof TagcacheObj) {
            return $Obj->getTags();
        }

        return array();
    }

    /**
     * increment a key
     * @param  type    $key
     * @param  type    $expire
     * @return boolean
     */
    public function inc($key, $expire = 0)
    {
        $this->getLock($key);
        $this->set($key,(int) $this->get($key)+1);
        $this->releaseLock($key);

        return true;
    }

    /**
     * decrement a key
     * @param  type    $key
     * @param  type    $expire
     * @return boolean
     */
    public function dec($key, $expire = 0)
    {
        $this->getLock($key);
        $this->set($key,(int) $this->get($key)-1);
        $this->releaseLock($key);

        return true;
    }

    abstract protected function getRaw($key);

    abstract protected function setRaw($key, $Obj, $expire);

    abstract protected function deleteRaw($key);
}


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\ProductBundle\Form\DataTransformer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\PropertyAccess\PropertyPathInterface;
use WellCommerce\Bundle\MediaBundle\Entity\MediaInterface;
use WellCommerce\Bundle\MediaBundle\Form\DataTransformer\MediaCollectionToArrayTransformer;
use WellCommerce\Bundle\ProductBundle\Entity\Product;
use WellCommerce\Bundle\ProductBundle\Entity\ProductInterface;
use WellCommerce\Bundle\ProductBundle\Entity\ProductPhoto;

/**
 * Class ProductPhotoCollectionToArrayTransformer
 *
 * @author Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductPhotoCollectionToArrayTransformer extends MediaCollectionToArrayTransformer
{
    /**
     * {@inheritdoc}
     */
    public function transform($modelData)
    {
        if (null === $modelData || !$modelData instanceof PersistentCollection) {
            return [];
        }

        $items = [];
        foreach ($modelData as $item) {
            if ($item->isMainPhoto() == 1) {
                $items['main_photo'] = $item->getPhoto()->getId();
            }
            $items['photos'][] = $item->getPhoto()->getId();
        }

        return $items;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($modelData, PropertyPathInterface $propertyPath, $values)
    {
        if (!$modelData instanceof ProductInterface) {
            throw new \InvalidArgumentException(sprintf('Wrong entity passed "%s"', get_class($modelData)));
        }

        if ($this->isPhotoCollectionUnModified($values)) {
            return false;
        }

        $previousCollection = $this->propertyAccessor->getValue($modelData, $propertyPath);
        $this->clearPreviousCollection($previousCollection);

        $collection = $this->createPhotosCollection($modelData, $values);

        if (0 === $collection->count()) {
            $modelData->setPhoto(null);
        }

        $this->propertyAccessor->setValue($modelData, $propertyPath, $collection);
    }

    /**
     * Checks whether photo collection was modified
     *
     * @param array $values
     *
     * @return bool
     */
    private function isPhotoCollectionUnModified($values)
    {
        return (isset($values['unmodified']) && (int)$values['unmodified'] === 1);
    }

    /**
     * Resets previous photo collection
     *
     * @param Collection $collection
     */
    protected function clearPreviousCollection(Collection $collection)
    {
        if ($collection->count()) {
            foreach ($collection as $item) {
                $collection->removeElement($item);
            }
        }
    }

    /**
     * Returns new photos collection
     *
     * @param Product $product
     * @param array   $values
     *
     * @return ArrayCollection
     */
    protected function createPhotosCollection(Product $product, $values)
    {
        $photos      = new ArrayCollection();
        $identifiers = $this->getMediaIdentifiers($values);
        $hierarchy   = 0;

        foreach ($identifiers as $id) {
            $media = $this->getMediaById($id);
            $photo = $this->getProductPhoto($media, $product, $values);
            $photo->setHierarchy($hierarchy++);
            if (!$photos->contains($photo)) {
                $photos->add($photo);
            }
        }

        return $photos;
    }

    /**
     * Fetch only media identifiers from an array
     *
     * @param array $values
     *
     * @return array
     */
    private function getMediaIdentifiers($values)
    {
        $identifiers = [];

        foreach ($values as $key => $id) {
            if (is_int($key)) {
                $identifiers[] = $id;
            }
        }

        return $identifiers;
    }

    /**
     * Returns media entity by its identifier
     *
     * @param int $id
     *
     * @return \WellCommerce\Bundle\MediaBundle\Entity\Media
     */
    protected function getMediaById($id)
    {
        return $this->getRepository()->find($id);
    }

    /**
     * Returns product photo model
     *
     * @param MediaInterface   $media
     * @param ProductInterface $modelData
     * @param array            $values
     *
     * @return ProductPhoto
     */
    protected function getProductPhoto(MediaInterface $media, ProductInterface $modelData, $values)
    {
        $mainPhoto    = $this->isMainPhoto($media, $values['main']);
        $productPhoto = new ProductPhoto();
        $productPhoto->setPhoto($media);
        $productPhoto->setMainPhoto($mainPhoto);
        $productPhoto->setProduct($modelData);

        if ($mainPhoto) {
            $modelData->setPhoto($media);
        }

        return $productPhoto;
    }

    /**
     * Checks whether photo was chosen as main product photo
     *
     * @param MediaInterface $photo
     * @param int            $mainId
     *
     * @return bool
     */
    private function isMainPhoto(MediaInterface $photo, $mainId)
    {
        return $photo->getId() === (int)$mainId;
    }
}


<?php
namespace Apatis\Transporter;

/**
 * Class TransportUtil
 * @package Apatis\Transporter
 */
class TransportUtil
{
    /**
     * @const string default user agent
     */
    const DEFAULT_USER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0';

    /**
     * Get generate User Agent
     *
     * @return string
     */
    public static function getBrowserUserAgentGenerated()
    {
        static $ua;
        if (isset($ua)) {
            return $ua;
        }

        $year  = abs(@date('Y'));
        if ($year <= 2017) {
            return $ua = self::DEFAULT_USER_AGENT;
        }

        $user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:[version].0) Gecko/20100101 Firefox/[version].0';
        $month      = abs(@date('m'));
        $version    = 51;
        $currentYear    = ($year-2017);
        $currentVersion = is_int($month/2) ? $month/2 : abs($month/2 + 0.5);
        $version   += $currentYear + $currentVersion;
        return $ua = str_replace('[version]', $version, $user_agent);
    }
}