<?php

/**
 * Copyright (c) 2010-2017 Romain Cottard
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Eureka\Component\Dependency;

/**
 * Container class.
 *
 * @author Romain Cottard
 */
class Container implements ContainerInterface
{
    /**
     * @var Container $instance
     */
    private static $instance = null;

    /**
     * @var \SplObjectStorage List of instances saved
     */
    protected $instances = array();

    /**
     * Container constructor.
     */
    protected function __construct()
    {
        $this->instances = array();
    }

    /**
     * Singleton getter.
     *
     * @return Container
     */
    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Get instance for given key.
     *
     * @param  string $key Key name to retrieve the instance
     * @return mixed
     * @throws \LogicException
     */
    public function get($key)
    {
        if (!isset($this->instances[$key])) {
            throw new \LogicException('No instance for given key! (key: ' . $key . ')');
        }

        return $this->instances[$key];
    }

    /**
     * Get all data.
     *
     * @return array
     */
    public function getAll()
    {
        return $this->instances;
    }

    /**
     * Attach new instance of any class to this container.
     *
     * @param  string $key Key name to retrieve the instance
     * @param  object $instance Instance to attach
     * @param  string $type Type of object
     * @return self
     * @throws \LogicException
     */
    public function attach($key, $instance, $type = self::OBJECT)
    {
        switch ($type) {
            case self::OBJECT:
            case self::CACHE:
                if (!is_object($instance)) {
                    throw new \LogicException('Instance is not an object!');
                }
                break;
            case self::DATABASE:
                if (!($instance instanceof \PDO)) {
                    throw new \LogicException();
                }
                break;
        }

        if (isset($this->instances[$key])) {
            return $this;
        }

        $this->instances[$key] = $instance;

        return $this;
    }

    /**
     * Detach Instance from container.
     * Implicit destruct the instance.
     *
     * @param  string $key Key name to retrieve the instance
     * @return self
     */
    public function detach($key)
    {
        if (isset($this->instances[$key])) {
            unset($this->instances[$key]);
        }

        return $this;
    }

    /**
     * Get database instance
     *
     * @param  string $config Database config name
     * @return \PDO
     * @throws \LogicException
     */
    public function getDatabase($config)
    {
        return $this->get($config);
    }

    /**
     * Get cache instance
     *
     * @param  string $config Cache config name
     * @return \Eureka\Component\Cache\CacheWrapperAbstract
     * @throws \LogicException
     */
    public function getCache($config)
    {
        return $this->get($config);
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\DependencyInjection\Compiler;

use Ruwork\RunetIdBundle\Basket\Factory\BasketFactory;
use Ruwork\RunetIdBundle\Basket\Handler\HandlerInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

final class AddBasketHandlersPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if (!$container->has(BasketFactory::class)) {
            return;
        }

        $tagged = $container->findTaggedServiceIds('ruwork_runet_id.basket_handler', true);
        $references = [];

        foreach ($tagged as $id => $attributes) {
            $class = $container->getDefinition($id)->getClass();

            if (!is_subclass_of($class, HandlerInterface::class)) {
                throw new \LogicException(sprintf('Basket handler "%s" must implement "%s".', $class, HandlerInterface::class));
            }

            $references[$class] = new Reference($id);
        }

        $container
            ->findDefinition(BasketFactory::class)
            ->setArgument('$handlers', ServiceLocatorTagPass::register($container, $references));
    }
}


<?php

namespace TaskQueue;

use TaskQueue\Invoker\InvokerInterface;

class TaskQueue implements TaskQueueInterface
{
    /**
     * @var array
     */
    private $tasks = [];

    /**
     * Add callbacks or \Closure into task queueing stack.
     *
     * @param InvokerInterface $invoker
     * @param array $taskArgs The callback or Closure arguments.
     * @return TaskQueueInterface
     */
    public function add(InvokerInterface $invoker, $taskArgs = [])
    {
        $taskArgs = (is_array($taskArgs) ? $taskArgs : array_slice(func_get_args(), 1));

        array_unshift($this->tasks, compact('invoker', 'taskArgs'));

        return $this;
    }

    /**
     * Invoke all of pending task in the task queueing stack.
     *
     * @return void
     */
    public function run()
    {
        while ($eachTasks = array_shift($this->tasks)) {
            $eachTasks['invoker']->invokeWithArgs($eachTasks['taskArgs']);
        }
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Component\Form;

use ItePHP\Validator\TextValidator;

/**
 * FormBuilder field
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class SelectField extends FormField{

    /**
     * @var mixed[]
     */
	private $collection=[];

    /**
     * @var int
     */
	private $data=null;

    /**
     * {@inheritdoc}
     */
	public function __construct($options){
		if(isset($options['collection'])){
			$this->collection=$options['collection'];
			unset($options['collection']);
		}

		if(!isset($options['validator'])){
			$this->setValidator(new TextValidator());
		}

		parent::__construct($options);
	}

	/**
	 * Get collection data (options value)
	 *
	 * @return mixed[] - eg:
	 * [
	 * 	[
	 * 		'value'=>'{string}'
	 * 		,'label'=>'{string}'
	 * 	]
	 * 	,...
	 * ]
	 */
	public function getCollection(){
		return $this->collection;
	}

	/**
	 * Set collection data (options value)
	 *
	 * @param mixed[] $collection - eg:
	 * [
	 * 	[
	 * 		'value'=>'{string}'
	 * 		,'label'=>'{string}'
	 * 	]
	 * 	,...
	 * ]
	 */
	public function setCollection($collection){
		$this->collection=$collection;
	}

	/**
	 * Set html tag multiple
	 *
	 * @param bool $flag - value of tag multiple
	 */
	public function setMultiple($flag){
		$this->setTag('multiple',$flag);
	}

	/**
	 * Get html tag multiple
	 *
	 * @return bool
	 */
	public function isMultiple(){
		$tags=$this->getTags();
		return (isset($tags['multiple']) && $tags['multiple']);
	}

    /**
     * {@inheritdoc}
     */
	public function render(){
		$template=$this->labelRender();
		$template.=$this->componentRender();
		return $template;
	}

    /**
     * {@inheritdoc}
     */
	public function labelRender(){
		return '<label for="'.$this->getId().'">'.htmlspecialchars($this->getLabel()).'</label>';
	}

    /**
     * {@inheritdoc}
     */
	public function setData($value){
		$this->data=$value;
	}

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

    /**
     * {@inheritdoc}
     */
	public function clearData(){
		return $this->data=null;
	}

    /**
     * {@inheritdoc}
     */
	public function componentRender(){
		$template='<select ';
		foreach($this->getTags() as $kTag=>$tag){
			if($tag!=''){
				if($kTag=='name' && $this->isMultiple()){
					$tag.='[]';
				}

				$template.=$kTag.'="'.htmlspecialchars($tag).'" ';

			}
		}

		$template.='>';
		$values=(is_array($this->getData())?$this->getData():[$this->getData()]);
		foreach($this->collection as $option){
			$template.='<option value="'.htmlspecialchars($option['value']).'" '.(in_array($option['value'], $values)?'selected':'').'>'.htmlspecialchars($option['label']).'</option>';
		}

		$template.='</select>';
		return $template;
	}
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class DothivContentfulExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config        = $this->processConfiguration($configuration, $configs);
        $container->setParameter('dothiv_contentful.web_path', $config['web_path']);
        $container->setParameter('dothiv_contentful.local_path', $config['local_path']);
        $container->setParameter('dothiv_contentful.webhook', $config['webhook']);
        $container->setParameter('dothiv_contentful.thumbnails', $config['thumbnails']);
        $container->setParameter('dothiv_contentful.default_locale', $config['default_locale']);
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
        $loader->load('listener.yml');
        $loader->load('persistence.yml');
        $loader->load('controllers.yml');
    }

    /**
     * Allow an extension to prepend the extension configurations.
     *
     * @param ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container)
    {
        $cacheConfig    = array();
        $doctrineConfig = array();

        $cacheConfig['providers']['contentful_api_cache'] = array(
            'namespace'   => 'contentful_api',
            'type'        => 'file_system',
            'file_system' => array(
                'directory' => '%kernel.root_dir%/cache/contentful'
            )
        );
        $cacheConfig['providers']['contentful_lastmodified_cache'] = array(
            'namespace'   => 'contentful_lastmodified_cache',
            'type'        => 'file_system',
            'file_system' => array(
                'directory' => '%kernel.root_dir%/cache/contentful'
            )
        );
        $container->prependExtensionConfig('doctrine_cache', $cacheConfig);

        $doctrineConfig['orm']['mappings']['contentful_bundle'] = array(
            'type'   => 'annotation',
            'alias'  => 'ContentfulBundle',
            'dir'    => __DIR__ . '/../Item',
            'prefix' => 'Dothiv\Bundle\ContentfulBundle\Item'
        );
        $container->prependExtensionConfig('doctrine', $doctrineConfig);
    }
}


<?php

class GD_Resize
{
    // Fonction pour redimensionner une image
    public static function run($source, $destination, $width, $height = "")
    {
        // Get the image's MIME
        $mime = exif_imagetype($source);

        // Check if the MIME is supported
        switch ($mime) {
            case IMAGETYPE_JPEG :
                $source = imagecreatefromjpeg($source);
                break;

            case IMAGETYPE_PNG :
                $source = imagecreatefrompng($source);
                break;

            case IMAGETYPE_GIF :
                $source = imagecreatefromgif($source);
                break;

            default :
                return; // No support
        }

        // Get the width and height of the source
        $width_src = imagesx($source);
        $height_src = imagesy($source);

        // Initialize the height and width of image destination
        $width_dest = 0;
        $height_dest= 0;

        // If the height is not provided, keep the proportions
        if (!$height) {
            // Get the ratio
            $ratio = ($width * 100) / $width_src;

            // Need resize ?
            if ($ratio>100) {
                imagejpeg($source, $destination, 70);
                imagedestroy($source);

                return;
            }

            // height and width of image resized
            $width_dest = $width;
            $height_dest = $height_src * $ratio/100;

        } else {
            if ($height_src >= $width_src) {
                $height_dest = ($height_src * $width ) / $width_src;
                $width_dest = $width;
            } elseif ($height_src < $width_src) {
                $width_dest = ($width_src * $height ) / $height_src;
                $height_dest = $height;
            }

        }

        // Build the image resized
        $emptyPicture = imagecreatetruecolor($width, ($height)?$height:$height_dest);
        imagecopyresampled($emptyPicture, $source, 0, 0, 0, 0, $width_dest, $height_dest, $width_src, $height_src);

        // Save image
        imagejpeg($emptyPicture, $destination, 70);

        // Destruct tmp images
        imagedestroy($source);
        imagedestroy($emptyPicture);

        return;
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\Forecast\Compress;

use Praxigento\BonusBase\Repo\Query\Period\Calcs\GetLast\ByCalcTypeCode\Builder as QBCalcGetLast;
use Praxigento\BonusHybrid\Config as Cfg;

/**
 * Get plain downline for forecast calculation and all customers with none-zero PV.
 */
class GetPlainData
    implements \Praxigento\Core\Api\App\Service\Process
{
    const IN_PERIOD = 'period';
    /** \Praxigento\BonusHybrid\Repo\Data\Downline[] */
    const OUT_DWNL = 'downline';
    /** Array [$custId => $pv] */
    const OUT_PV = 'pv';
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\BonusBase\Repo\Query\Period\Calcs\GetLast\ByCalcTypeCode\Builder */
    private $qbCalcGetLast;

    public function __construct(
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusBase\Repo\Query\Period\Calcs\GetLast\ByCalcTypeCode\Builder $qbCalcGetLast,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod
    )
    {
        $this->daoBonDwnl = $daoBonDwnl;
        $this->qbCalcGetLast = $qbCalcGetLast;
        $this->hlpPeriod = $hlpPeriod;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        $period = $ctx->get(self::IN_PERIOD);
        /* prepare result vars */
        $result = new \Praxigento\Core\Data();
        $outPv = [];
        /**
         * perform processing
         */
        $calcIdPlain = $this->getPlainCalcId($period);
        /** @var \Praxigento\BonusHybrid\Repo\Data\Downline[] $downline */
        $downline = $this->daoBonDwnl->getByCalcId($calcIdPlain);
        foreach ($downline as $item) {
            $custId = $item->getCustomerRef();
            $pv = $item->getPv();
            if (abs($pv) > Cfg::DEF_ZERO) {
                $outPv[$custId] = $pv;
            }

        }
        /* put result data into output */
        $result->set(self::OUT_PV, $outPv);
        $result->set(self::OUT_DWNL, $downline);
        return $result;
    }

    /**
     * Get ID for the last complete forecast plain calculation.
     *
     * @param string $period YYYYMM
     * @return int
     */
    private function getPlainCalcId($period)
    {
        if ($period) {
            $dsMax = $this->hlpPeriod->getPeriodLastDate($period);
        } else {
            $dsMax = Cfg::DEF_MAX_DATESTAMP;
        }
        /* prepare query */
        $query = $this->qbCalcGetLast->build();
        $bind = [
            QBCalcGetLast::BND_CODE => Cfg::CODE_TYPE_CALC_FORECAST_PLAIN,
            QBCalcGetLast::BND_DATE => $dsMax,
            QBCalcGetLast::BND_STATE => Cfg::CALC_STATE_COMPLETE
        ];

        /* fetch & parse data */
        $conn = $query->getConnection();
        $rs = $conn->fetchRow($query, $bind);
        $result = $rs[QBCalcGetLast::A_CALC_ID];
        return $result;
    }

}


<?php

namespace Dhii\Data\Container;

use Psr\Container\ContainerInterface as BaseContainerInterface;
use Exception as RootException;
use InvalidArgumentException;

/**
 * Functionality for retrieval of a container.
 *
 * @since [*next-version*]
 */
trait ContainerAwareTrait
{
    /**
     * The container.
     *
     * @since [*next-version*]
     *
     * @var BaseContainerInterface|null
     */
    protected $container;

    /**
     * Retrieves the container associated with this instance.
     *
     * @since [*next-version*]
     *
     * @return BaseContainerInterface|null The container, if any.
     */
    protected function _getContainer()
    {
        return $this->container;
    }

    /**
     * Associates a container with this instance.
     *
     * @since [*next-version*]
     *
     * @param BaseContainerInterface|null $container The container.
     *
     * @throws InvalidArgumentException If not a valid container.
     */
    protected function _setContainer($container)
    {
        if (!is_null($container) && !($container instanceof BaseContainerInterface)) {
            throw $this->_createInvalidArgumentException($this->__('Not a valid container'), 0, null, $container);
        }

        $this->container = $container;

        return $this;
    }

    /**
     * Creates a new  Invalid Argument exception.
     *
     * @since [*next-version*]
     *
     * @param string        $message  The error message.
     * @param int           $code     The error code.
     * @param RootException $previous The inner exception for chaining, if any.
     * @param mixed         $argument The invalid argument, if any.
     *
     * @return InvalidArgumentException The new exception.
     */
    abstract protected function _createInvalidArgumentException(
            $message = '',
            $code = 0,
            RootException $previous = null,
            $argument = null
    );

    /**
     * Translates a string, and replaces placeholders.
     *
     * @since [*next-version*]
     * @see sprintf()
     *
     * @param string $string  The format string to translate.
     * @param array  $args    Placeholder values to replace in the string.
     * @param mixed  $context The context for translation.
     *
     * @return string The translated string.
     */
    abstract protected function __($string, $args = [], $context = null);
}


<?php
/**
 * A class containing all pake tasks related to the build process
 *
 * @author    G. Giunta
 * @copyright (C) G. Giunta 2013-2014
 * @license   code licensed under the GNU GPL 2.0: see README file
 */

namespace eZExtBuilder;

use pakeException;
use pakeFinder;
use pakeGit;
use pakeSubversion;

class BuildTasks extends Builder
{
    /**
     * Downloads the extension from its source repository, removes files not to be built
     * (the list of files to be removed is in part hardcoded and in part specified in
     * the configuration file).
     * Options: skip-init, skip-init-fetch, skip-init-clean
     *
     * @todo add a dependency on a check-updates task that updates script itself?
     * @todo split this in two tasks and avoid this unsightly mess of options?
     */
    static function run_init( $task=null, $args=array(), $cliopts=array() )
    {
        $skip_init = @$cliopts['skip-init'];
        $skip_init_fetch = @$cliopts['skip-init-fetch'] || $skip_init;
        $skip_init_clean = @$cliopts['skip-init-clean'] || $skip_init;

        if ( ! $skip_init )
        {
            $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
            pake_mkdirs( self::getBuildDir( $opts ) );

            $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];

            if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
                throw new PakeException( "Source code locked by another process" );
        }

        if ( ! $skip_init_fetch )
        {
            if ( @$opts['svn']['url'] != '' )
            {
                pake_echo( "Fetching code from SVN repository {$opts['svn']['url']}" );
                pakeSubversion::checkout( $opts['svn']['url'], $destdir );
                /// @todo test that we got at least one file
                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
                {
                    sleep( 3 );
                }
            }
            else if ( @$opts['git']['url'] != '' )
            {
                pake_echo( "Fetching code from GIT repository {$opts['git']['url']}" );
                pakeGit::clone_repository( $opts['git']['url'], $destdir );
                if ( @$opts['git']['branch'] != '' )
                {
                    /// @todo test checking out a specific branch
                    pakeGit::checkout_repo( $destdir, $opts['git']['branch'] );
                    /// @todo test that we got at least one file
                }
                if ( strtoupper( substr( PHP_OS, 0, 3) ) === 'WIN' )
                {
                    sleep( 3 );
                }
            }
            else if ( @$opts['file']['url'] != '' )
            {
                pake_echo( "Fetching code from local repository {$opts['file']['url']}" );
                /// @todo (!important) exclude stuff we know we're going to delete immediately afterwards
                $files = pakeFinder::type( 'any' )->relative()->in( $opts['file']['url'] );
                if ( count( $files ) == 0 )
                {
                    SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
                    throw new pakeException( "Empty source repo option: no files found in {$opts['file']['url']}" );
                }

                pake_mirror( $files, $opts['file']['url'], $destdir );
            }
            else
            {
                SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
                throw new pakeException( "Missing source repo option: either svn:url, git:url or file:url" );
            }
        }

        // remove files
        if ( ! $skip_init_clean )
        {
            // known files/dirs not to be packed / md5'ed
            /// @todo !important shall we make this configurable?
            /// @bug 'build' & 'dist' we should probably take from options
            $files = array( 'ant/', 'build.xml', '**/.svn', '.git/', 'build/', 'dist/', 'composer.phar', 'composer.lock', '.idea/', 'vendor/' );
            // hack! when packing ourself, we need to keep this stuff
            if ( $opts['extension']['name'] != 'ezextensionbuilder' )
            {
                $files = array_merge( $files, array( 'pake/', 'pakefile.php', '**/.gitignore' ) );
            }
            // files from user configuration
            $files = array_merge( $files, $opts['files']['to_exclude'] );

            /// we figured a way to allow user to specify both:
            ///       files in a specific subdir
            ///       files to be removed globally (ie. from any subdir)
            //pakeFinder::type( 'any' )->name( $files )->in( $destdir );
            $files = self::pake_antpattern( $files, $destdir );
            foreach( $files as $key => $file )
            {
                if ( is_dir( $file ) )
                {
                    pake_remove_dir( $file );
                    unset( $files[$key] );
                }
            }
            pake_remove( $files, '' );
        }

        if ( ! $skip_init )
        {
            // move package file where it has to be
            $file = pakeFinder::type( 'file' )->name( 'package.xml' )->maxdepth( 0 )->in( $destdir );
            if ( count( $file ) )
            {
                if ( $opts['create']['tarball'] || $opts['create']['zip'] )
                {
                    pake_rename( $destdir . '/package.xml', $destdir . '/../../package.xml' );
                }
                else
                {
                    pake_remove( $file, '' );
                }
            }

            SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
        }
    }

    /**
     * Builds the extension; options: --skip-init
     *
     * We rely on the pake dependency system to do the real stuff
     * (run pake -P to see tasks included in this one)
     */
    static function run_build( $task=null, $args=array(), $cliopts=array() )
    {
    }

    /**
     * Removes the build/ directory
     */
    static function run_clean( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        pake_remove_dir( $opts['build']['dir'] );

        SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
    }

    /**
     * Creates a tarball of the built extension.
     *
     * Depending on configuration options, different versions of the extenion tarball
     * are generated by this task: .tar.gz, .zip, .ezpkg
     */
    static function run_dist( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( $opts['create']['tarball'] || $opts['create']['zip'] || $opts['create']['ezpackage'] || $opts['create']['pearpackage'] )
        {
            if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_SH, $opts ) )
                throw new PakeException( "Source code locked by another process" );

            pake_mkdirs( $opts['dist']['dir'] );
            $rootpath = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];

            if ( $opts['create']['tarball'] )
            {
                $target = $opts['dist']['dir'] . '/' . $opts['extension']['name'] . '-' . $opts['version']['alias'] . '.' . $opts['version']['release'] . '.tar.gz';
                self::archiveDir( $rootpath, $target );
            }

            if ( $opts['create']['zip'] )
            {
                $target = $opts['dist']['dir'] . '/' . $opts['extension']['name'] . '-' . $opts['version']['alias'] . '.' . $opts['version']['release'] . '.zip';
                self::archiveDir( $rootpath, $target );
            }

            if ( $opts['create']['ezpackage'] || $opts['create']['pearpackage'] )
            {
                $toppath = $opts['build']['dir'];

                // check if package.xml file is there
                $file = pakeFinder::type( 'file' )->name( 'package.xml' )->maxdepth( 0 )->in( $toppath );
                if ( !count( $file ) )
                {
                    pake_echo_error( "File 'package.xml' missing in build dir $rootpath. Cannot create package(s)" );
                    return;
                }

                // cleanup if extra files/dirs found
                $dirs = array();
                $dirs = pakeFinder::type( 'directory' )->not_name( array( 'documents', 'ezextension' ) )->maxdepth( 0 )->in( $toppath );
                $dirs = array_merge( $dirs, pakeFinder::type( 'directory' )->in( $toppath . '/documents' ) );
                $dirs = array_merge( $dirs, pakeFinder::type( 'directory' )->not_name( $opts['extension']['name'] )->maxdepth( 0 )->in( $toppath . '/ezextension' ) );
                $files = pakeFinder::type( 'file' )->not_name( 'package.xml' )->maxdepth( 0 )->in( $toppath );
                $files = array_merge( $files, pakeFinder::type( 'file' )->in( $toppath . '/documents' ) );
                $files = array_merge( $files, pakeFinder::type( 'file' )->not_name( 'extension-' . $opts['extension']['name']. '.xml' )->maxdepth( 0 )->in( $toppath . '/ezextension' ) );
                if ( count( $dirs ) || count( $files ) )
                {
                    pake_echo( "Extra files/dirs found in build dir. Must remove them to continue:\n  " . implode( "\n  ", $dirs ) . "  ". implode( "\n  ", $files ) );
                    $ok = pake_input( "Do you want to delete them? [y/n]", 'n' );
                    if ( $ok != 'y' )
                    {
                        return;
                    }
                    foreach( $files as $file )
                    {
                        pake_remove( $file, '' );
                    }
                    foreach( $dirs as $dir )
                    {
                        pake_remove_dir( $dir );
                    }
                }
                // prepare missing folders/files
                /// @todo we should not blindly copy LICENSE and README, but inspect actual package.xml file
                ///       and copy any files mentioned there
                pake_copy( $rootpath . '/' . $opts['files']['gnu_dir'] . '/LICENSE', $toppath . '/documents/LICENSE' );
                pake_copy( $rootpath . '/' . $opts['files']['gnu_dir'] . '/README', $toppath . '/documents/README' );
                $target = $opts['dist']['dir'] . '/' . $opts['extension']['name'] . '_extension.ezpkg';
                self::archiveDir( $toppath, $target, true );

                if ( $opts['create']['pearpackage'] )
                {
                    /// @todo ...
                    pake_echo_error( "PEAR package creation not yet implemented" );
                }
            }

            SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
        }
    }

    /**
     * Removes the dist/ directory
     */
    static function run_dist_clean( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        pake_remove_dir( $opts['dist']['dir'] );
    }

    /**
     * Builds dependent extensions
     *
     * @todo add locking support
     */
    static function run_build_dependencies( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        $current = $opts['extension']['name'];
        foreach( $opts['dependencies']['extensions'] as $ext => $source )
        {
            // avoid loops
            if ( $ext != $current )
            {
                // create a temporary config file to drive the init task
                // this could be done better in memory...
                foreach( $source as $type => $def )
                {
                    break;
                }
                $tempconf = array( 'extension' => array( 'name' => $ext ),  'version' => array( 'major' => 0, 'minor' => 0, 'release' => 0 ), $type => $def );
                $tempconffile = self::getOptionsDir() . "/options-tmp_$ext.yaml";
                pakeYaml::emitfile( $tempconf, $tempconffile );

                // download remote extension
                // nb: we can not run the init task here via invoke() because of already_invoked status,
                // so we use execute(). NB: this is fine as long as init has no prerequisites
                $task = pakeTask::get( 'init' );
                $task->execute( array( "tmp_$ext" ), array_merge( $cliopts, array( 'skip-init' => false, 'skip-init-fetch' => false, 'skip-init-clean' => true ) ) );

                // copy config file from ext dir to current config dir
                if ( is_file( self::getBuildDir( $opts ) . "/$ext/pake/options-$ext.yaml" ) )
                {
                    pake_copy( self::getBuildDir( $opts ) . "/$ext/pake/options-$ext.yaml", self::getOptionsDir() . "/options-$ext.yaml" );
                }
                else
                {
                    throw new pakeException( "Missing pake/options.yaml extension in dependent extension $ext" );
                }

                // finish the init-task
                $task->execute( array( "tmp_$ext" ), array_merge( $cliopts, array( 'skip-init' => false, 'skip-init-fetch' => true, 'skip-init-clean' => false ) ) );
                pake_remove( $tempconffile, '' );

                // and build it. Here again we cannot use 'invoke', but we know 'build' has prerequisites
                // so we execute them one by one
                $task = pakeTask::get( 'build' );
                foreach( $task->get_prerequisites() as $pretask )
                {
                    $pretask = pakeTask::get( $pretask );
                    $pretask->execute( array( $ext ), array_merge( $opts, array( 'skip-init' => true ) ) );
                }
                $task->execute( array( $ext ), array_merge( $opts, array( 'skip-init' => true ) ) );
            }
        }
    }

    /**
     * Creates a tarball of all extensions in the build/ directory
     *
     * @todo add locking support
     */
    static function run_fat_dist( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        pake_mkdirs( $opts['dist']['dir'] );
        $files = pakeFinder::type( 'any' )->in( self::getBuildDir( $opts ) );
        // get absolute path to build dir
        $rootpath =  pakeFinder::type( 'directory' )->name( $opts['extension']['name'] )->in( self::getBuildDir( $opts ) );
        $rootpath = dirname( $rootpath[0] );
        $target = $opts['dist']['dir'] . '/' . $opts['extension']['name'] . '-' . $opts['version']['alias'] . '.' . $opts['version']['release'] . '-bundle.tar';
        // we do not rely on this, not to depend on phar extension and also because it's slightly buggy if there are dots in archive file name
        //pakeArchive::createArchive( $files, $opts['build']['dir'], $target, true );
        $tar = ezcArchive::open( $target, ezcArchive::TAR );
        $tar->appendToCurrent( $files, $rootpath );
        $tar->close();
        $fp = fopen( 'compress.zlib://' . $target . '.gz', 'wb9' );
        /// @todo read file by small chunks to avoid memory exhaustion
        fwrite( $fp, file_get_contents( $target ) );
        fclose( $fp );
        unlink( $target );
        pake_echo_action( 'file+', $target . '.gz' );
    }

    /**
     * Builds the extension and generates the tarball
     *
     * We rely on the pake dependency system to do the real stuff
     * (run pake -P to see tasks included in this one)
     */
    static function run_all( $task=null, $args=array(), $cliopts=array() )
    {
    }

    /**
     * Removes the build/ and dist/ directories
     *
     * We rely on the pake dependency system to do the real stuff
     * (run pake -P to see tasks included in this one)
     */
    static function run_clean_all( $task=null, $args=array(), $cliopts=array() )
    {
    }

    /**
     * Updates the ezinfo.php and extension.xml files with the version number and
     * license tag from configuration.
     *
     * Uses a regular expression to search and replace the correct strings in ezinfo.php
     * Within the file, please note there is a limit of 25 spaces to avoid indenting
     * 3rd party lib version numbers, if you use more than 25 spaces the version number
     * and license string will not be updated correctly.
     * Also we set a limit of 1 replacement, to avoid fixing 3rd party lib versions.
     *
     * For the extension.xml file, max indentation is set to 8 chars.
     */
    static function run_update_ezinfo( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];

        $files = pakeFinder::type( 'file' )->name( 'ezinfo.php' )->maxdepth( 0 );

        /// @todo use a real php parser instead
        pake_replace_regexp( $files, $destdir, array(
                '/^([\s]{1,25}\x27Version\x27[\s]+=>[\s]+[\x27\x22])(.*)([\x27\x22],?\r?\n?)/m' => '${1}' . $opts['version']['alias'] . $opts['releasenr']['separator'] . $opts['version']['release'] . '$3',
                '/^([\s]{1,25}\x27License\x27[\s]+=>[\s]+[\x27\x22])(.*)([\x27\x22],?\r?\n?)/m' => '${1}' . $opts['version']['license'] . '$3' ),
            1 );

        $files = pakeFinder::type( 'file' )->maxdepth( 0 )->name( 'extension.xml' );
        /// @todo use a real xml parser instead
        pake_replace_regexp( $files, $destdir, array(
                '#^([\s]{1,8}<version>)([^<]*)(</version>\r?\n?)#m' => '${1}' . $opts['version']['alias'] . $opts['releasenr']['separator'] . $opts['version']['release'] . '$3',
                /// @bug we should use a better xml escaping here
                '#^([\s]{1,8}<license>)([^<]*)(</license>\r?\n?)#m' => '${1}' . htmlspecialchars( $opts['version']['license'] ) . '$3',
                '#^([\s]{1,8}<copyright>)Copyright \(C\) 1999-[\d]{4} eZ Systems AS(</copyright>\r?\n?)#m' => '${1}' . 'Copyright (C) 1999-' . strftime( '%Y' ). ' eZ Systems AS' . '$2' ),
            1 );

        SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
    }

    /**
     * Updates .php, .css and .js files replacing tokens found in the standard eZ Systems header comment
     *
     * Recognized tokens (in regexp form) are:
     * // SOFTWARE RELEASE: (.*)
     * Copyright (C) 1999-[\d]{4} eZ Systems AS
     * .*@version //autogentag//\r?\n?
     *
     * @todo use more tolerant comment tags (eg multiline comments)
     * @todo parse tpl files too?
     * @todo use other strings than these, since it's gonna be community extensions?
     */
    static function run_update_license_headers( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];
        $files = pakeFinder::type( 'file' )->name( array( '*.php', '*.css', '*.js' ) );
        pake_replace_regexp( $files, $destdir, array(
            '#// SOFTWARE RELEASE: (.*)#m' => '// SOFTWARE RELEASE: ' . $opts['version']['alias'] . $opts['releasenr']['separator'] . $opts['version']['release'],
            '/Copyright \(C\) 1999-[\d]{4} eZ Systems AS/m' => 'Copyright (C) 1999-' . strftime( '%Y' ). ' eZ Systems AS',
            '#(.*@version )//autogentag//(\r?\n?)#m' => '${1}' . $opts['version']['alias'] . $opts['releasenr']['separator'] . $opts['version']['release'] . '$2' ) );

        SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
    }

    /**
     * Updates all files specified in user configuration,
     * replacing the tokens [EXTENSION_VERSION], [EXTENSION_PUBLISH_VERSION] and [EXTENSION_LICENSE]
     */
    static function run_update_extra_files( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];
        $extrafiles = $opts['files']['to_parse'];
        //$files = pakeFinder::type( 'file' )->name( $extrafiles )->in( $destdir );
        /// @todo shall we make sure we only retrieve files, not directories?
        $files = self::pake_antpattern( $extrafiles, $destdir );
        $tokens = array(
            'EXTENSION_VERSION' => $opts['version']['alias'] . $opts['releasenr']['separator'] . $opts['version']['release'],
            'EXTENSION_LICENSE' => $opts['version']['license'] );
        if ( @$opts['ezp']['version']['major'] )
        {
            $tokens['EXTENSION_PUBLISH_VERSION'] = $opts['ezp']['version']['major'] . '.' . $opts['ezp']['version']['minor'] . '.' . $opts['ezp']['version']['release'];
        }
        pake_replace_tokens( $files, $destdir, '[', ']', $tokens );

        SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
    }

    /**
     * Generates the documentation of the extension, if created in RST format in the doc/ folder, plus optionally
     * API docs via doxygen; options: --doxygen=/path/to/doxygen
     *
     * Builds an html file of all doc/*.rst files, and removes the source, then, if
     * configured in the options file, uses doxygen to create html documentation of
     * php source code in doc/api. The location of the doxygen binary can be specified
     * via a configuration option
     *
     * @todo allow config file to specify doc dir
     * @todo use local doxygen file if found, instead of std one
     * @todo create api doc from php files using phpdoc too
     *       example cli cmd: ${phpdocinstall}phpdoc -t ${phpdocdir}/html -ti 'eZ Publish' -pp -s -d lib/ezdb/classes,lib/ezdbschema/classes,lib/ezdiff/classes,lib/ezfile/classes,lib/ezi18n/classes,lib/ezimage/classes,lib/ezlocale/classes,lib/ezmath/classes,lib/ezpdf/classes,lib/ezsession/classes,lib/ezsoap/classes,lib/eztemplate/classes,lib/ezutils/classes,lib/ezxml/classes,kernel/classes,kernel/private/classes,kernel/common,cronjobs,update/common/scripts > ${phpdocdir}/generate.log
     */
    static function run_generate_documentation( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];
        $docdir = $destdir . '/doc';
        $files = pakeFinder::type( 'file' )->name( '*.rst' )->in( $docdir );
        foreach ( $files as $i => $file )
        {
            $dst = substr( $file, 0, -3 ) . 'html';
            $document = new ezcDocumentRst();
            $document->loadFile( $file );
            $docbook = $document->getAsXhtml();
            file_put_contents( $dst, $docbook->save() );
            pake_echo_action( 'file+', $dst );
            pake_remove( $file, '' );
        }

        /*
        * A few extension have Makefiles to generate documentation
        * We remove them as well as the original .rst files
        * NB: this is not done anymore since version 0.1. Use files.to_exclude option instead
        */
        //pake_remove( pakeFinder::type( 'file' )->name( 'Makefile' )->in( $destdir ), '' );

        // doxygen
        if ( $opts['create']['doxygen_doc'] )
        {
            pake_mkdirs( $docdir . '/api' );
            $doxygen = self::getTool( 'doxygen', $opts );
            $doxyfile = $destdir . '/doxyfile';
            pake_copy( self::getResourceDir() . '/doxyfile_master', $doxyfile, array( 'override' => true ) );
            file_put_contents( $doxyfile,
                "\nPROJECT_NAME = " . $opts['extension']['name'] .
                "\nPROJECT_NUMBER = " . $opts['version']['alias'] . $opts['releasenr']['separator'] . $opts['version']['release'] .
                "\nOUTPUT_DIRECTORY = " . $docdir . '/api' .
                "\nINPUT = " . $destdir .
                "\nEXCLUDE = " . $destdir . '/settings' .
                "\nSTRIP_FROM_PATH = " . $destdir, FILE_APPEND );
            $out = pake_sh( $doxygen . ' ' . escapeshellarg( $doxyfile ) );
            pake_remove( $doxyfile, '' );
            // cleanup leftover files, just in case dot tool is not found
            $files = pakeFinder::type( 'file' )->name( array( '*.dot', '*.md5', '*.map', 'installdox' ) )->in( $docdir . '/api' );
            pake_remove( $files, '' );
        }

        SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
    }

    /**
     * Creates a share/filelist.md5 file, with the checksum of all files in the build.
     *
     * This task is only run if in the configuration file md5 creation is specified.
     */
    static function run_generate_md5sums( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( $opts['create']['filelist_md5'] )
        {
            if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
                throw new PakeException( "Source code locked by another process" );

            $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];
            // make sure we do not add to checksum file the file itself
            @unlink( $destdir . '/share/filelist.md5'  );
            $files = pakeFinder::type( 'file' )->in( $destdir );
            $out = array();
            $rootpath =  pakeFinder::type( 'directory' )->name( $opts['extension']['name'] )->in( self::getBuildDir( $opts ) );
            foreach( $files as $file )
            {
                $out[] = md5_file( $file ) . '  ' . ltrim( str_replace( array( $rootpath[0], '\\' ), array( '', '/' ), $file ), '/' );
            }
            pake_mkdirs( $destdir . '/share' );
            file_put_contents( $destdir . '/share/filelist.md5', implode( "\n", $out ) );
            pake_echo_action('file+', $destdir . '/share/filelist.md5' );

            SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
        }
    }

    /**
     * Generates the xml file listing all the files in the extension that is used as
     * part of an eZ Package description.
     *
     * This task is only run if in the configuration file package creation is specified.
     */
    static function run_generate_package_filelist( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( $opts['create']['ezpackage'] || $opts['create']['pearpackage'] )
        {
            if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
                throw new PakeException( "Source code locked by another process" );

            $doc = new DOMDocument( '1.0', 'utf-8' );
            $doc->formatOutput = true;

            $packageRoot = $doc->createElement( 'extension' );
            $packageRoot->setAttribute( 'name', $opts['extension']['name'] );

            $rootpath =  pakeFinder::type( 'directory' )->name( $opts['extension']['name'] )->in( self::getBuildDir( $opts ) );
            $dirs =  pakeFinder::type( 'directory' )->in( self::getBuildDir( $opts ) . '/' . $opts['extension']['name'] );
            foreach( $dirs as $dir )
            {
                $name = basename( $dir );
                $path = dirname( $dir );
                $path = str_replace( array( $rootpath[0], '\\' ), array( '', '/' ), $path );
                $fileNode = $doc->createElement( 'file' );
                $fileNode->setAttribute( 'name', $name );
                if ( $path )
                    $fileNode->setAttribute( 'path', $path );
                $fileNode->setAttribute( 'type', 'dir' );
                $packageRoot->appendChild( $fileNode );
            }
            $files =  pakeFinder::type( 'file' )->in( self::getBuildDir( $opts ) . '/' . $opts['extension']['name'] );
            foreach( $files as $file )
            {
                //$dir = ;
                $name = basename( $file );
                $path = dirname( $file );
                $path = str_replace( array( $rootpath[0], '\\' ), array( '', '/' ), $path );
                $fileNode = $doc->createElement( 'file' );
                $fileNode->setAttribute( 'name', $name );
                if ( $path )
                    $fileNode->setAttribute( 'path', $path );
                $fileNode->setAttribute( 'md5sum', md5_file( $file ) );
                $packageRoot->appendChild( $fileNode );
            }
            $doc->appendChild( $packageRoot );

            $doc->save( self::getBuildDir( $opts ) . '/extension-' . $opts['extension']['name'] . '.xml' );
            pake_echo_action( 'file+', self::getBuildDir( $opts ) . '/extension-' . $opts['extension']['name'] . '.xml' );

            SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
        }
    }

    /**
     * Runs all code compliance checks.
     *
     * We rely on the pake dependency system to do the real stuff
     * (run pake -P to see tasks included in this one)
     */
    static function run_code_checks( $task=null, $args=array(), $cliopts=array() )
    {
    }

    /**
     * Checks if a schema.sql file is present for any supported database (or none at all)
     *
     * The accepted directory structure is:
     *
     * myextension
     * |___share
     * |   |___db_schema.dba
     * |   `___db_data.dba
     * `__ sql
     *     |__ mysql
     *     |   |__ cleandata.sql
     *     |   `__ schema.sql
     *     |__ oracle
     *     |   |__ cleandata.sql
     *     |   `__ schema.sql
     *     `__ postgresql
     *         |__ cleandata.sql
     *         `__ schema.sql
     *
     * NB: there are NOT a lot of extensions currently following this schema.
     * Alternative used are: sql/mysql/mysql.sql, sql/mysql/random.sql
     */
    static function run_check_sql_files( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_SH, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];

        $schemafile = $opts['files']['sql_files']['db_schema'];
        $schemafiles = array( 'share' => 'db_schema.dba', 'sql/mysql' => $schemafile, 'sql/oracle' => $schemafile, 'sql/postgresql' => $schemafile );
        if ( $schemafile == '$db.sql' )
        {
            $schemafiles = array( 'share' => 'db_schema.dba', 'sql/mysql' => 'mysql.sql', 'sql/oracle' => 'oracle.sql', 'sql/postgresql' => 'postgresql.sql' );
        }
        $count = 0;
        foreach( $schemafiles as $dir => $file )
        {
            $files = pakeFinder::type( 'file' )->name( $file )->maxdepth( 0 )->in( $destdir . "/$dir" );
            if ( count( $files ) )
            {
                if ( filesize( $files[0] ) == 0 )
                {
                    SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
                    throw new pakeException( "Sql schema file {$files[0]} is empty. Please fix" );
                }
                $count++;
            }

        }
        if ( $count > 0 && $count < 4 )
        {
            SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
            throw new pakeException( "Found some sql schema files but not all of them. Please fix" );
        }

        $datafile = $opts['files']['sql_files']['db_data'];
        $datafiles = array( 'share' => 'db_data.dba', 'sql/mysql' => $datafile, 'sql/oracle' => $datafile, 'sql/postgresql' => $datafile );
        if ( $datafile == '$db.sql' )
        {
            $datafiles = array( 'share' => 'db_data.dba', 'sql/mysql' => 'mysql.sql', 'sql/oracle' => 'oracle.sql', 'sql/postgresql' => 'postgresql.sql' );
        }
        $count = 0;
        foreach( $datafiles as $dir => $file )
        {
            $files = pakeFinder::type( 'file' )->name( $file )->maxdepth( 0 )->in( $destdir . "/$dir" );
            if ( count( $files ) )
            {
                if ( filesize( $files[0] ) == 0 )
                {
                    SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
                    throw new pakeException( "Sql data file {$files[0]} is empty. Please fix" );
                }
                $count++;
            }
        }
        if ( $count > 0 && $count < 4 )
        {
            SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
            throw new pakeException( "Found some sql data files but not all of them. Please fix" );
        }

        SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
    }

    /**
     * Checks for presence of files README and LICENSE, by default in extension root
     * directory - but a config parameter is allowed to specify their location
     */
    static function run_check_gnu_files( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_SH, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];
        if ( $opts['files']['gnu_dir'] )
        {
            $destdir .= '/' . $opts['files']['gnu_dir'];
        }
        $files = pakeFinder::type( 'file' )->name( array( 'README', 'LICENSE' ) )->maxdepth( 0 )->in( $destdir );
        if ( count( $files ) != 2 )
        {
            SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
            throw new pakeException( "README and/or LICENSE files missing. Please fix" );
        }

        SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
    }

    /**
     * Checks for validity all template files - needs a working eZP install somewhere to get the tpl syntax checker script;
     * use config options to specify the path to php executable if needed, as well as the path to an
     * eZPublish installation
     */
    static function run_check_templates( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_SH, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];
        $files = pakeFinder::type( 'file' )->name( array( '*.tpl' ) )->maxdepth( 0 )->in( $destdir );
        if ( count( $files ) )
        {
            $php = self::getTool( 'php', $opts );
            if ( strpos( pake_sh( $php . " -v" ), 'PHP' ) === false )
            {
                SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
                throw new pakeException( "$php does not seem to be a valid php executable" );
            }

            $ezp = @$opts['ezublish']['install_dir_LS'];
            if ( $ezp == '' )
            {
                // assume we're running inside an eZ installation
                $ezp = '../..';
            }
            if ( !file_exists( $ezp . '/bin/php/eztemplatecheck.php' ) )
            {
                SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
                throw new pakeException( "$ezp does not seem to be a valid eZ Publish install" );
            }

            // get absolute path to build dir
            $rootpath =  pakeFinder::type( 'directory' )->name( $opts['extension']['name'] )->in( self::getBuildDir( $opts ) );
            $rootpath = dirname( $rootpath[0] );
            $out = pake_sh( "cd " . escapeshellarg( $ezp ) . " && " . escapeshellarg( $php ) . " bin/php/eztemplatecheck.php " . escapeshellarg( $rootpath ) );
            if ( strpos( $out, 'Some templates did not validate' ) !== false )
            {
                SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
                throw new pakeException( $out );
            }
        }

        SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
    }

    /**
     * Checks for validity all php files; use config options to specify the path to php executable if needed
     */
    static function run_check_php_files( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_SH, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = self::getBuildDir( $opts ) . '/' . $opts['extension']['name'];
        $files = pakeFinder::type( 'file' )->name( array( '*.php' ) )->in( $destdir );
        if ( count( $files ) )
        {
            $php = self::getTool( 'php', $opts );
            if ( strpos( pake_sh( $php . " -v" ), 'PHP' ) === false )
            {
                SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
                throw new pakeException( "$php does not seem to be a valid php executable" );
            }

            foreach ( pakeFinder::type( 'file' )->name( array( '*.php' ) )->in( $destdir ) as $file )
            {
                if ( strpos( pake_sh( $php . " -l " . escapeshellarg( $file ) ), 'No syntax errors detected' ) === false )
                {
                    SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
                    throw new pakeException( "$file does not seem to be a valid php file" );
                }
            }
        }

        SharedLock::release( $opts['extension']['name'], LOCK_SH, $opts );
    }

    /**
     * Updates information in package.xml file used by packaged extensions
     */
    static function run_update_package_xml( $task=null, $args=array(), $cliopts=array() )
    {
        /// @todo replace hostname, build time

        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        if ( !SharedLock::acquire( $opts['extension']['name'], LOCK_EX, $opts ) )
            throw new PakeException( "Source code locked by another process" );

        $destdir = $opts['build']['dir'];
        $files = pakeFinder::type( 'file' )->name( 'package.xml' )->maxdepth( 0 );
        if ( count( $files ) == 1 )
        {
            // original format
            pake_replace_regexp( $files, $destdir, array(
                // <name>xxx</name>
                '#^( *\074name\076)(.*)(\074/name\076\r?\n?)$#m' => '${1}' . $opts['extension']['name'] . '_extension' . '$3',
                // <version>xxx</version>
                '#^( *\074version\076)(.*)(\074/version\076\r?\n?)$#m' => '${1}' . $opts['ezp']['version']['major'] . '.' . $opts['ezp']['version']['minor'] . '.' . $opts['ezp']['version']['release'] . '$3',
                // <named-version>xxx</named-version>
                '#^( *\074named-version\076)(.*)(\074/named-version\076\r?\n?)$#m' => '${1}' . $opts['ezp']['version']['major'] . '.' . $opts['ezp']['version']['minor'] . '$3',
                // <package version="zzzz"
                //'#^( *\074package +version=")(.*)("\r?\n?)$#m' => '${1}' . $opts['version']['major'] . '.' . $opts['version']['minor'] . $opts['releasenr']['separator'] . $opts['version']['release'] . '$3',
                // <number>xxxx</number>
                '#^( *\074number\076)(.*)(\074/number\076\r?\n?)$#m' => '${1}' . $opts['version']['alias'] . '$3',
                // <release>yyy</release>
                '#^( *\074release\076)(.*)(\074/release\076\r?\n?)$#m' => '${1}' . $opts['version']['release'] . '$3',

                '#^( *\074timestamp\076)(.*)(\074/timestamp\076\r?\n?)$#m' => '${1}' . time() . '$3',
                '#^( *\074host\076)(.*)(\074/host\076\r?\n?)$#m' => '${1}' . gethostname() . '$3',
                '#^( *\074licence\076)(.*)(\074/licence\076\r?\n?)$#m' => '${1}' . $opts['version']['license'] . '$3',
            ) );
            // replacing a token based on its value instead of its location (text immediately before and after,
            // as done above) has a disadvantage: we cannot execute the substitution many
            // times on the same text, as the 1st substitution will remove the token's
            // value. This means we have to reinit the build to get a 100% updated
            // package file. Unfortunately hunting for xml attributes not based on
            // token values needs a real xml parser, simplistic regexps are not enough...
            pake_replace_tokens( $files, $destdir, '{', '}', array(
                '$name' => $opts['extension']['name'],
                '$version' => $opts['version']['alias'],
                '$ezp_version' => $opts['ezp']['version']['major'] . '.' . $opts['ezp']['version']['minor'] . '.' . $opts['ezp']['version']['release']
            ) );
        }

        SharedLock::release( $opts['extension']['name'], LOCK_EX, $opts );
    }

    /**
     * Generates a sample package.xml to allow creation of packaged extension
     *
     * NB: that file is to be completed by hand
     */
    static function run_generate_sample_package_xml( $task=null, $args=array(), $cliopts=array() )
    {
        pake_copy( self::getResourceDir() . '/package_master.xml', 'package.xml' );
        // tokens not replaced here are replaced at build time
        // tokens in square brackets are supposed to be edited by the developer
        $tokens = array(
            '$summary' => '[Summary]',
            '$description' => '[Description]',
            '$vendor' => '',
            '$maintainers' => '',
            '$documents' => '',
            '$changelog' => '',
            '$simple-files' => '',
            '$state' => '[State]',
            '$requires' => ''
        );
        //$files = pakeFinder::type( 'file' )->name( 'package.xml' )->maxdepth( 0 )->in( '.' );
        pake_replace_tokens( 'package.xml', '.', '{', '}', $tokens );
        pake_echo ( "File package.xml generated. Please replace all tokens in square brackets in it (but do not replace values in curly brackets) then commit it to sources in the top dir of the extension" );
    }

}


<?php
namespace eMacros\Runtime\Arithmetic;

use eMacros\Runtime\GenericFunction;

class Modulus extends GenericFunction {
	/**
	 * Caculates the modulus between 2 values
	 * Usage: (mod -1 5)
	 * Returns: number
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
    public function execute(array $arguments) {
    	if (empty($arguments)) throw new \BadFunctionCallException("Modulus: No arguments found.");
    	if (!isset($arguments[1])) throw new \BadFunctionCallException("Modulus: At least 2 arguments are required");
        return $arguments[0] % $arguments[1];
    }
}


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

namespace RedKiteCms\Action;

use Silex\Application;

/**
 * This object is assigned to build an Action object to execute a specific action.
 *
 * An action could be adding a block or edit a page and so on.
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Action
 */
class FactoryAction
{
    private $app;

    /**
     * Constructor
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Creates an action object
     *
     * @param $entity
     * @param $action
     * @return null|\RedKiteCms\Action\ActionInterface
     */
    public function create($entity, $action)
    {
        $type = ucfirst($entity);
        $actionName = ucfirst($action);
        $class = sprintf('RedKiteCms\Action\%s\%s%sAction', $type, $actionName, $type);

        if (!class_exists($class)) {
            return null;
        }

        $reflectionClass = new \ReflectionClass($class);

        return $reflectionClass->newInstance($this->app);
    }
}


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

namespace RedKiteCms\Plugin;

use RedKiteCms\Exception\General\LogicException;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Class Plugin is the object assigned to handle a generic plugin
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Plugin
 */
class Plugin
{
    /**
     * @type string
     */
    private $name;
    /**
     * @type string
     */
    private $rootDir;
    /**
     * @type string
     */
    private $frameworkAbsoluteDir;
    /**
     * @type string
     */
    private $pluginDir;
    /**
     * @type array
     */
    private $information;

    /**
     * Constructor
     *
     * @param string $pluginName
     * @param string $rootDir
     * @param string $type
     */
    public function __construct($pluginName, $type, $rootDir, $frameworkAbsoluteDir)
    {
        $this->name = $pluginName;
        $this->rootDir = $rootDir;
        $this->frameworkAbsoluteDir = $frameworkAbsoluteDir;
        $this->pluginDir = $this->getBaseDir($type, $this->name);
        $this->filesystem = new Filesystem();
        $this->parseConfiguration();
    }

    /**
     * Returns the plugin name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns the plugin directory
     *
     * @return string
     */
    public function getPluginDir()
    {
        return $this->pluginDir;
    }

    /**
     * Returns true when the plugin is translated
     *
     * @return bool
     */
    public function isTranslated()
    {
        return is_dir($this->pluginDir . '/Resources/translations');
    }

    /**
     * Returns the plugin information
     *
     * @return array
     */
    public function getInformation()
    {
        return $this->information;
    }

    /**
     * Returns true when the plugin is a core plugin
     *
     * @return bool
     */
    public function isCore()
    {
        return (bool)strpos($this->pluginDir, $this->frameworkAbsoluteDir . '/plugins');
    }

    /**
     * Returns true when the plugin has a toolbar
     *
     * @return bool
     */
    public function hasToolbar()
    {
        $fileSkeleton = '/Resources/views/Editor/Toolbar/_toolbar_%s_buttons.html.twig';
        return file_exists($this->pluginDir . sprintf($fileSkeleton, 'left')) || file_exists($this->pluginDir . sprintf($fileSkeleton, 'right'));
    }

    /**
     * Returns true when the plugin has the screenshot
     *
     * @return bool
     */
    public function hasScreenshot()
    {
        return file_exists($this->pluginDir . '/Resources/public/screenshot.jpg');
    }

    /**
     * Magic method to return single plugin information
     *
     * @param string $name
     * @param $arguments
     *
     * @return null|string
     */
    public function __call($name, $arguments)
    {
        if (!array_key_exists($name, $this->information)) {
            return null;
        }

        return $this->information[$name];
    }

    /**
     * Installs plugin assets
     *
     * @param string $targetFolder
     * @param bool $force
     */
    public function installAssets($targetFolder = "web", $force = false)
    {
        $sourceDir = $this->pluginDir . '/Resources/public';
        $targetDir = $this->rootDir . '/' . $targetFolder . '/plugins/' . strtolower($this->name);
        if (is_dir($targetDir) && !$force) {
            return;
        }

        $this->filesystem->symlink($sourceDir, $targetDir, true);
    }

    private function getBaseDir($type, $name)
    {
        $paths = array(
            sprintf('%s/%s/plugins/RedKiteCms/%s/%s', $this->rootDir, $this->frameworkAbsoluteDir, $type, $name),
            sprintf('%s/vendor/redkite-labs/redkitecms-plugins/RedKiteCms/%s/%s', $this->rootDir, $type, $name),
            sprintf('%s/app/plugins/RedKiteCms/%s/%s', $this->rootDir, $type, $name),
        );

        return FilesystemTools::cascade($paths);
    }

    private function parseConfiguration()
    {
        $informationFile = $this->pluginDir . '/plugin.json';
        if (!file_exists($informationFile)) {
            throw new LogicException(sprintf('You must define a plugin.json file for the %s plugin.', $this->name));
        }

        $information = json_decode(FilesystemTools::readFile($informationFile), true);
        if (null === $information) {
            throw new LogicException(sprintf('The %s plugin is empty.', $this->name));
        }

        $this->information = array();
        foreach ($information as $key => $param) {
            $tokens = explode('-', $key);
            $method = "get";
            foreach ($tokens as $token) {
                $method .= ucfirst($token);
            }
            $this->information[$method] = $param;
        }
    }
}


<?php

Web2All_Manager_Main::loadClass('Web2All_Table_SQLOperation');
include_once(__DIR__ . '/ObjectTrait.php');

/**
 * Web2All Table Object class
 *
 * This is base class for objects reflecting a database table. All
 * kinds of support methods will be made available.
 *
 * @author Merijn van den Kroonenberg
 * @copyright (c) Copyright 2007-2017 Web2All BV
 * @since 2007-08-20
 */
abstract class Web2All_Table_Object extends Web2All_Manager_Plugin {
  use Web2All_Table_ObjectTrait;

  /**
   * constructor
   *
   * @param Web2All_Manager_Main $web2all
   * @param ADOConnection $db
   */
  public function __construct(Web2All_Manager_Main $web2all,$db)
  {
    parent::__construct($web2all);

    $this->initTableObject($db);
  }

  /**
   * This is called after successful load of the object from table
   *
   * Can be used to override debugging output
   */
  protected function onSuccessLoad()
  {
    if ($this->Web2All->DebugLevel>Web2All_Manager_Main::DEBUGLEVEL_MEDIUM) {
      $this->Web2All->debugLog('Web2All_Table_Object::loadFromTable(): loaded: '.$this->asDebugString());
    }
  }

  /**
   * outputs all properties of the object
   *
   */
  public function debugDump()
  {
    $this->Web2All->debugLog($this->asDebugString());
  }

}

?>


<?php

namespace AdminBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class AdminExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        //admin menu
        $configs = $this->addMenuItemsByBundles($container, $config);
        $container->setParameter('core.admin_menus', $configs);

        //company menu
        if(isset($config['company_menus']))
        $container->setParameter('core.company_menus', $config['company_menus']);

        //google analytics
        if (isset($config['apis']['google_analytics']['options']['application_name'])) {
            $container->setParameter('google_analytics.application_name', $config['apis']['google_analytics']['options']['application_name']);
        }
        if (isset($config['apis']['google_analytics']['options']['oauth2_client_id'])) {
            $container->setParameter('google_analytics.oauth2_client_id', $config['apis']['google_analytics']['options']['oauth2_client_id']);
        }
        if (isset($config['apis']['google_analytics']['options']['oauth2_client_secret'])) {
            $container->setParameter('google_analytics.oauth2_client_secret', $config['apis']['google_analytics']['options']['oauth2_client_secret']);
        }
        if (isset($config['apis']['google_analytics']['options']['oauth2_redirect_uri'])) {
            $container->setParameter('google_analytics.oauth2_redirect_uri', $config['apis']['google_analytics']['options']['oauth2_redirect_uri']);
        }
        if (isset($config['apis']['google_analytics']['options']['developer_key'])) {
            $container->setParameter('google_analytics.developer_key', $config['apis']['google_analytics']['options']['developer_key']);
        }
        if (isset($config['apis']['google_analytics']['options']['site_name'])) {
            $container->setParameter('google_analytics.site_name', $config['apis']['google_analytics']['options']['site_name']);
        }

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

    }

    private function addMenuItemsByBundles($container, $config)
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (isset($bundles['CoreBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'dashboard' => array(
                        'icon_class' => 'fa fa-dashboard',
                        'label' => 'dashboard',
                        'options' => array(
                            'translations' => 'core_translation_index',
                            'parameters' => 'core_parameter_index',
                            'pages' => 'core_page_index'
                        )
                     ),
                    'users' => array(
                        'icon_class' => 'fa fa-users',
                        'label' => 'actor.plural',
                        'options' => array(
                            'actors' => 'core_actor_index',
                            'roles' => 'core_role_index',
                            )
                    ),
                ),
            ),$config);
        }
        if (isset($bundles['CoreExtraBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'dashboard' => array(
                        'icon_class' => 'fa fa-dashboard',
                        'label' => 'dashboard',
                        'options' => array(
                            'menuitems' => 'coreextra_menuitem_index',
                            'sliders' => 'coreextra_slider_index',
                            'design.font' => array(
                                'icon_class' => 'fa fa-paint-brush',
                                'label' => 'design.font',
                                'options' => array(
                                    'fontadds' => 'coreextra_font_index',
                                    'fontless' => 'coreextra_font_less',
                                )
                             ),
                        )
                     ),
                    'marketing' => array(
                        'icon_class' => 'fa fa-line-chart',
                        'label' => 'marketing',
                        'options' => array(
                            'reputation.onlie' => 'coreextra_visit_index',
                            'newsletter' => array(
                                'icon_class' => 'fa fa-envelope-o',
                                'label' => 'newsletter.plural',
                                'options' => array(
                                    'subscriptions' => 'coreextra_newsletter_subscription',
                                    'newsletters' => 'coreextra_newsletter_index',
                                    'shippings' => 'coreextra_newsletter_shipping',
                                ),
                            ),
                        ),
                    ),
                ),
            ),$config);
        }
        if (isset($bundles['AdminBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'dashboard' => array(
                        'options' => array(
                            'stats' => 'admin_default_dashboard',
                            'analytics' => 'admin_default_analytics'
                            )
                        )
                    )
                ),$config);
        }
        if (isset($bundles['BlogBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'blog' => array(
                        'icon_class' => 'fa fa-pencil-square-o',
                        'label' => 'blog.singular',
                        'options' => array(
                            'posts' => 'blog_post_index',
                            'postcategories' => 'blog_category_index',
                            'posttags' => 'blog_tag_index',
                            'postcomments' => 'blog_comment_index'
                        )
                    )
                )
            ),$config);
        }
        if (isset($bundles['EcommerceBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'ecommerce' => array(
                        'icon_class' => 'fa fa-shopping-cart ',
                        'label' => 'ecommerce',
                        'options' => array(
                            'catalogue' => array(
                                'options' => array(
                                    'products' => 'ecommerce_product_index',
                                    'categories' => 'ecommerce_category_index',
                                    'features' => 'ecommerce_feature_index',
                                    'attributes' => 'ecommerce_attribute_index',
                                    'brands' => 'ecommerce_brand_index',
                                    'models' => 'ecommerce_brandmodel_index',
                                )
                            ),
                            'sales' => array(
                                'options' => array(
                                    'transactions' => 'ecommerce_transaction_index',
                                    'invoices' => 'ecommerce_invoice_index',
                                    'taxes' => 'ecommerce_tax_index',
                                    'paymentserviceproviders' => 'ecommerce_paymentserviceprovider_index',
                                )
                            ),
                            'recurrings' => array(
                                'options' => array(
                                    'contracts' => 'ecommerce_contract_index',
                                    'plans' => 'ecommerce_plan_index',
                                )
                            )
                        )
                    ),
                    'marketing' => array(
                        'options' => array(
                            'advert' => array(
                                'icon_class' => 'fa fa-picture-o',
                                'label' => 'advert.plural',
                                'options' => array(
                                    'adverts' => 'ecommerce_advert_index',
                                    'advertslocated' => 'ecommerce_located_index',
                                )
                            )
                        )
                    ),
                )),$config);
        }
        if (isset($bundles['ElearningBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'elearning' => array(
                        'icon_class' => 'fa fa-graduation-cap',
                        'label' => 'elearning',
                        'options' => array(
                            'courses' => 'elearning_course_index',
                            'class' => 'elearning_classes_index',
                            'tests' => 'elearning_test_index',
                            )
                        )
                    )
                ),$config);
        }

        if (isset($bundles['PaymentBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'ecommerce' => array(
                        'icon_class' => 'fa fa-shopping-cart ',
                        'label' => 'ecommerce',
                        'options' => array(
                            'sales' => array(
                                'options' => array(
                                    'transactions' => 'payment_transaction_index',
                                    'invoices' => 'payment_invoice_index',
                                    //'taxes' => 'payment_tax_index',
                                    'paymentserviceproviders' => 'payment_paymentserviceprovider_index',
                                    'carts' => 'payment_cart_index'
                                )
                            ),
//                            'recurrings' => array(
//                                'options' => array(
//                                    'contracts' => 'ecommerce_contract_index',
//                                    'plans' => 'ecommerce_plan_index',
//                                )
//                            )
                        )
                    ),
                )),$config);
        }

        if (isset($bundles['CatalogueBundle'])) {
            $config = $this->arraymap(array(
                'admin_menus' => array(
                    'catalogue' => array(
                        'icon_class' => 'fa fa-book ',
                        'label' => 'catalogue',
                        'options' => array(
                            'products' => 'catalogue_product_index',
                            'cataloguecategories' => 'catalogue_category_index',
                            'features' => 'catalogue_feature_index',
                            'attributes' => 'catalogue_attribute_index',
                            'brands' => 'catalogue_brand_index',
                            'models' => 'catalogue_brandmodel_index',
                        )
                    ),
                )),$config);
        }

        return $config;
    }

    private function addCompanyMenuItems($container, $config)
    {
        $bundles = $container->getParameter('kernel.bundles');

        print_r($config);die();

        return $config;
    }

    private function arraymap($arr1, $arr2)
    {
        foreach ($arr1 as $key => $menu_item) {
            if(!array_key_exists($key, $arr2)){
                $arr2[$key] = $menu_item;
            }else{
                foreach ($menu_item as $key2 => $menu_item2) {
                    if(!array_key_exists($key2, $arr2[$key])){
                        $arr2[$key][$key2] = $menu_item2;
                    }else{
                        foreach ($menu_item2 as $key3 => $menu_item3) {
                            if(isset($arr2[$key][$key2][$key3]) && is_array($arr2[$key][$key2][$key3])){
                                $customOptions = $arr2[$key][$key2][$key3];
                                //if we need remove items put values as null
                                $arr2[$key][$key2][$key3] = $this->cleanOptionsNull($customOptions, $menu_item3);
                            }
                        }
                    }
                }
            }
        }
        return $arr2;
    }

    private function cleanOptionsNull($customOptions, $oldOptions)
    {
        foreach ($customOptions as $key => $value) {
            if(isset($oldOptions[$key])){
                if(count($value['options'])==0){
                    unset($customOptions[$key]);
                    unset($oldOptions[$key]);
                }
            }
        }
        $merge = array_merge($customOptions, $oldOptions);
        return $merge;
    }

}


<?php

namespace BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use BlogBundle\Model\CommentFront;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use BlogBundle\Entity\Comment;
use CoreBundle\CoreBundle\Entity\Actor;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use A2lix\I18nDoctrineBundle\Annotation\I18nDoctrine;
use DateTime;
use FontCatalogueBundle\Entity\User;

/**
* @Route("/blog")
* @Template()
*/
class BlogController extends Controller
{
    /**
     * @Route("/")
     * @Template()
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        if ($request->isXmlHttpRequest()) {
            $offset = $request->get('offset');
            $limit = $request->get('limit');
            $posts = $em->getRepository('BlogBundle:Post')->loadPosts($offset, $limit);
            return $this->render('BlogBundle:Blog/Block:more.post.html.twig', array(
                'posts'    => $posts,
                'position' => $offset
            ));
        } else {

            $categories = $em->getRepository('BlogBundle:Category')->findBy(array('parentCategory' => null ), array('order' => 'ASC'));
            $tags = $em->getRepository('BlogBundle:Tag')->findBy(array(), array('name' => 'ASC'));
            $total_items = $em->getRepository('BlogBundle:Post')->countTotal();

            return array(
                'categories' => $categories,
                'tags' => $tags,
                'total_items' => $total_items,
                'load_more_path' => $this->generateUrl('blog_blog_index')
            );
        }

    }

    /**
    * @Route("/share-counter")
    */
    public function shareCounterAction()
    {
    //        $data = $this->get('request')->request->all();
        $url = $this->get('request')->query->get('url');
        //$this->getRequest()->isXmlHttpRequest() &&
        if (isset($url)) {
            $returnValues = $this->get('blog_manager')->shareCounter($url);

            return new JsonResponse($returnValues);
        }

        return JsonResponse();
   }

    /**
    * @Route("/feed")
    */
    public function feedAction()
    {
        $em = $this->getDoctrine()->getManager();
        $manager = $this->getDoctrine()->getManager();
        $core = $this->getParameter('core');

        $dql = "SELECT p, pTrans FROM BlogBundle:Post p JOIN p.translations pTrans ORDER BY p.created DESC";
        $entities = $manager
           ->createQuery($dql)
           ->getResult()
        ;

        $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
        $rssfeed .= '<rss version="2.0">';
        $rssfeed .= '<channel>';
        $rssfeed .= '<title>Font Catalogue RSS feed</title>';
        $rssfeed .= '<link>'.$this->get('twig.global')->getParameter('server_base_url').'</link>';
        $rssfeed .= '<description>This is an example Kundalini Woman RSS feed</description>';
        $rssfeed .= '<language>en-us</language>';
        $rssfeed .= '<copyright>Copyright (C) 2009 mywebsite.com</copyright>';

        foreach ($entities as $value) {
            $rssfeed .= '<item>';
            $rssfeed .= '<title>' . utf8_decode($value->getTitle()) . '</title>';
            $rssfeed .= '<description>' . utf8_decode($value->getDescription()) . '</description>';
            $rssfeed .= '<link>' . $this->get('twig.global')->getParameter('server_base_url').$this->generateUrl('blog_blog_show', array('slug' => $value->getSlug())) . '</link>';
            $rssfeed .= '<pubDate>' . $value->getCreated()->format("D, d M Y H:i:s O")  . '</pubDate>';
            $rssfeed .= '</item>';
        }

        $rssfeed .= '</channel>';
        $rssfeed .= '</rss>';

        $response = new Response($rssfeed);
        $response->headers->set('Content-Type', 'application/rss+xml');

        $response->setPublic();
        $response->setMaxAge(3600);
        $now = new DateTime();
        $response->setLastModified($now);

        return $response;

   }

    /**
     * @Route("/{slug}")
     * @Method("GET")
     * @Template()
     */
    public function showAction($slug)
    {
        $em = $this->getDoctrine()->getManager();

//        $entity = $em->getRepository('BlogBundle:Post')->findOneBy(array('slug' => $slug));
        $qb = $em->getRepository('BlogBundle:Post')->createQueryBuilder('p')
                ->join('p.translations', 't')
                ->where('t.slug = :slug')
                ->setParameter('slug', $slug)
                ->setMaxResults(1);
        $entity = $qb->getQuery()->getSingleResult();

        $categories = $em->getRepository('BlogBundle:Category')->findBy(array('parentCategory' => null ), array('order' => 'ASC'));
        $tags = $em->getRepository('BlogBundle:Tag')->findBy(array(), array('name' => 'ASC'));
        $comments = $em->getRepository('BlogBundle:Comment')->findBy(array('post' => $entity->getId(), 'active' => true));

        $related = $this->getRelatedPost($entity);

        $form = $this->createCommentForm(new CommentFront(), $entity);

        return array(
            'post'       => $entity,
            'comments'   => $comments,
            'categories' => $categories,
            'form'       => $form->createView(),
            'tags'       => $tags,
            'related'   =>  $related
        );

    }

    private function getRelatedPost($entity)
    {
        $categories = $entity->getCategories();
        $em = $this->getDoctrine()->getManager();
        $returnValues = array();

        foreach ($categories as $category) {
            $posts = $em->getRepository('BlogBundle:Post')->loadPostsCategory(0, 5, $category);
            foreach ($posts as $post) {
                if($entity->getId() != $post->getId())
                $returnValues[] = $post;
            }
        }
        return $returnValues;
    }

    /**
     * @Route("/category/{category}")
     * @Template("BlogBundle:Blog:list.html.twig")
     */
    public function categoryAction(Request $request, $category)
    {

        $em = $this->getDoctrine()->getManager();
        $categoryEntity = $em->getRepository('BlogBundle:Category')->findOneBySlug($category);

        if ($request->isXmlHttpRequest()) {

            $offset = $request->get('offset');
            $limit = $request->get('limit');
            $posts = $em->getRepository('BlogBundle:Post')->loadPostsCategory($offset, $limit, $categoryEntity);
            return $this->render('BlogBundle:Blog/Block:more.post.html.twig', array(
                'posts'    => $posts,
                'position' => $offset
            ));
        } else {
            $categories = $em->getRepository('BlogBundle:Category')->findBy(array('parentCategory' => null ), array('order' => 'ASC'));
            $tags = $em->getRepository('BlogBundle:Tag')->findBy(array(), array('name' => 'ASC'));
            $posts = $em->getRepository('BlogBundle:Post')->loadPostsCategory(0, 2, $categoryEntity);
            $total_items = $em->getRepository('BlogBundle:Post')->countTotal($categoryEntity->getId());

            return array(
                'category'   => $categoryEntity,
                'posts'      => $posts,
                'categories' => $categories,
                'total_items' => $total_items,
                'tags'       => $tags,
                'load_more_path' => $this->generateUrl('blog_blog_category', array('category'=>$categoryEntity->getSlug()))
            );
        }

    }

    /**
     * @Route("/tag/{tag}")
     * @Template("BlogBundle:Blog:list.html.twig")
     */
    public function tagAction(Request $request, $tag)
    {
        $em = $this->getDoctrine()->getManager();
        $tagEntity = $em->getRepository('BlogBundle:Tag')->findOneBySlug($tag);

        if ($request->isXmlHttpRequest()) {

            $offset = $request->get('offset');
            $limit = $request->get('limit');
            $posts = $em->getRepository('BlogBundle:Post')->loadPostsTag($offset, $limit, $tagEntity);
            return $this->render('BlogBundle:Blog/Block:more.post.html.twig', array(
                'posts'    => $posts,
                'position' => $offset
            ));
        } else {
            $tags = $em->getRepository('BlogBundle:Tag')->findBy(array(),array('id' => 'DESC'));
            $categories = $em->getRepository('BlogBundle:Category')->findBy(array(), array('name' => 'ASC'));
            $posts = $em->getRepository('BlogBundle:Post')->loadPostsTag(0, 2, $tagEntity);
            $total_items = $em->getRepository('BlogBundle:Post')->countTotal();

            return array(
                'tag'   => $tagEntity,
                'posts'      => $posts,
                'categories' => $categories,
                'total_items' => $total_items,
                'tags'       => $tags,
                'load_more_path' => $this->generateUrl('blog_blog_tag', array('tag'=>$tagEntity->getSlug()))
            );
        }
    }

    /**
     * @Route("/comment/")
     * @Method("POST")
     * @Template()
     */
    public function commentAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $comment = new Comment();

        try {
            $comment = $this->resolve($comment, $request);
            $this->get('session')->getFlashBag()->add('warning', 'comment.wait.for.validate');
        } catch (\Exception $exception) {
            // Write flash message
            print_r($exception->getMessage());die();
        }

        //save
        $em->persist($comment);
        $em->flush();

        return $this->redirect($this->get('core_manager')->getRefererPath($request));
    }
    /**
     * Creates a form to create a Post entity.
     *
     * @param Post $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCommentForm(CommentFront $model, $entity)
    {
        $form = $this->createForm('BlogBundle\Form\CommentFrontType', $model, array(
            'action' => $this->generateUrl('blog_blog_comment', array('post' => $entity->getId())),
            'method' => 'POST',
            'attr' => array('id' => 'comment-form','class' => 'comment-form')
        ));

        return $form;
    }

    /**
     * @param Comment $comment
     * @param Request $request
     *
     * @throws ItemResolvingException
     * @return CartItemInterface|void
     */
    public function resolve(Comment $comment, Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $postId = $request->query->get('post');
        $itemForm = $request->get('comment_front');

        if( $this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') ){
            $comment->setActor($this->container->get('security.token_storage')->getToken()->getUser());
        }else{
            //register user
            $actor = $this->createActor($itemForm);
            $comment->setActor($actor);
        }

        $postRepository = $em->getRepository('BlogBundle:Post');
        if (!$postId || !$post = $postRepository->find($postId)) {
            // no product id given, or product not found
            throw new \Exception('Requested post was not found');
        }

        // assign the product and quantity to the item
        $comment->setPost($post);
        $comment->setComment($itemForm['comment']);

        return $comment;
    }

    public function createActor($itemForm)
    {
        $em = $this->getDoctrine()->getManager();
        $uniqid = uniqid();
        $actor = new User();
        $actor->setUsername($itemForm['email']);
        $actor->setName($itemForm['name']);
        $actor->setEmail($itemForm['email']);

        //Encode pass
        $factory = $this->get('security.encoder_factory');
        $encoder = $factory->getEncoder($actor);
        $password = $encoder->encodePassword($uniqid, $actor->getSalt());
        $actor->setPassword($password);

        //Add ROLE
        $role = $em->getRepository('CoreBundle:Role')->findOneBy(array('role' => 'ROLE_USER'));
        $actor->addRole($role);

        $em->persist($actor);
        $em->flush();

        //$this->get('core.mailer')->sendRegisteredEmailMessage($actor);

        return $actor;
    }

    /**
     * @Route("/search/", name="blog_search")
     * @Route("/search/{search}")
     * @Template("BlogBundle:Blog:list.html.twig")
     */
    public function searchAction(Request $request, $search = null) {

        if ($request->getMethod() == 'POST') {
            $search = $request->request->get('search');
        }

        $em = $this->getDoctrine()->getManager();
        $posts = $em->getRepository('BlogBundle:Post')->findPost($search);

        return array(
            'search'     => $search,
            'posts'      => $posts,
        );
    }

}