<?php

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

namespace Mmf\Routing;

/**
 * Description of RoutingResolver
 *
 * @author Jepi Humet
 */
class RoutingResolver extends RoutingResolverAbstract {

    /**
     * @return RoutingRuleAbstract
     * @throws \RoutingException
     */
    public function resolve() {
        $completeRoute = $this->communication->route();
        $fragmentedRoute = explode('?',$completeRoute);
        $routeWithoutGetParams = $fragmentedRoute[0];

        /* @var $rule RoutingRuleAbstract */
        foreach ($this->listOfRules as $rule) {
            if ($this->matchRule($routeWithoutGetParams, $rule)) {
                return $rule;
            }
        }

        throw new RoutingException("There is no rule resolving this route",
        1600);
    }

    /**
     * Arranges all changes based on rule and returns a real Regex, not an URL format
     * (based on routing rules), and a list of input params.
     *
     * @param RoutingRuleAbstract $rule
     * @return list(string regex, array<string> inputs)
     */
    private function getRegexProperties(RoutingRuleAbstract $rule) {
        $requiredMatches = array();
        $ruleRegex = $rule->getRegularExpression();

        preg_match_all($this->requiredInputPattern, $ruleRegex, $requiredMatches);
        $pathRequiredVars = $requiredMatches[0];
        preg_match_all($this->catchAllInputPattern, $ruleRegex, $requiredMatches);
        $pathCatchAllVars = $requiredMatches[0];

        $urlRegexRequired = str_replace($pathRequiredVars,
                "([" . $this->allowedInputValues . "]+)", $ruleRegex);
        $urlRegex = str_replace($pathCatchAllVars, "(.*)", $urlRegexRequired);

        $urlRegexReplaced = str_replace("/", "\/", $urlRegex);
        $finalUrlRegex = "/^" . $urlRegexReplaced . "?$/";

        $inputsRequired = str_replace(":", "", $pathRequiredVars);
        $inputsCatchAll = str_replace("*", "", $pathCatchAllVars);

        return array($finalUrlRegex, array_merge(array(), $inputsRequired,
                    $inputsCatchAll));
    }

    /**
     * Check if route matches with rule depending on regular expression which
     * defines them.
     * @param string $route
     * @param RoutingRuleAbstract $rule
     * @return bool true if rule matches with route or false if not
     */
    private function matchRule($route, RoutingRuleAbstract &$rule) {
        list($regex, $inputs) = $this->getRegexProperties($rule);

        $matches = array();
        preg_match($regex, $route, $matches);
        if (count($matches) > 0) {
            //Substract the first element of the array, which is the complete URL
            array_splice($matches, 0, 1);
            for ($i = 0; $i < count($inputs); $i++) {
                $key = $inputs[$i];
                $value = $matches[$i];
                $rule->getInput()->setInput($key, $value);
            }
            return true;
        }
        return false;
    }

}


<?php

namespace Kitpages\CmsBundle\Entity;

use JMS\Serializer\Annotation as JMS;

/**
 * Kitpages\CmsBundle\Entity\Page
 */
class Page
{
    /**
     * @var string $slug
     */
    /** @JMS\Groups({"complet"})
     *  @JMS\Type("string")
     */
    private $slug;

    /**
     * @var string $pageType
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("string")
     */
    private $pageType;

    /**
     * @var string $layout
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("string")
     */
    private $layout;

    /**
     * @var boolean $isPublished
     */
    /** @JMS\Groups({"publish"})
     *  @JMS\Type("boolean")
     */
    private $isPublished = false;

    /**
     * @var array $data
     */
    /** @JMS\Groups({"base"})
     */
    private $data;

     /**
     * @var integer $id
     */
    /** @JMS\Groups({"complet", "page_id"})
     *  @JMS\Type("integer")
     */
    private $id;

    /**
     * Set slug
     *
     * @param string $slug
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;
    }

    /**
     * Get slug
     *
     * @return string $slug
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set pageType
     *
     * @param string $pageType
     */
    public function setPageType($pageType)
    {
        $this->pageType = $pageType;
    }

    /**
     * Get pageType
     *
     * @return string $pageType
     */
    public function getPageType()
    {
        return $this->pageType;
    }

    /**
     * Set layout
     *
     * @param string $layout
     */
    public function setLayout($layout)
    {
        $this->layout = $layout;
    }

    /**
     * Get layout
     *
     * @return string $layout
     */
    public function getLayout()
    {
        return $this->layout;
    }

    /**
     * Set isPublished
     *
     * @param boolean $isPublished
     */
    public function setIsPublished($isPublished)
    {
        $this->isPublished = $isPublished;
    }

    /**
     * Get isPublished
     *
     * @return boolean $isPublished
     */
    public function getIsPublished()
    {
        return $this->isPublished;
    }

    /**
     * Set data
     *
     * @param array $data
     */
    public function setData($data)
    {
        $this->data = $data;
    }

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

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @var datetime $realUpdatedAt
     */
    /** @JMS\Groups({"complet"})
     *  @JMS\Type("DateTime")
     */
    private $realUpdatedAt;

    /**
     * @var datetime $publishedAt
     */
    /** @JMS\Groups({"publish"})
     *  @JMS\Type("DateTime")
     */
    private $publishedAt;

    /**
     * @var datetime $unpublishedAt
     */
    /** @JMS\Groups({"publish"})
     *  @JMS\Type("DateTime")
     */
    private $unpublishedAt;

    /**
     * @var datetime $createdAt
     */
    /** @JMS\Groups({"complet"})
     *  @JMS\Type("DateTime")
     */
    private $createdAt;

    /**
     * @var datetime $updatedAt
     */
    /** @JMS\Groups({"complet"})
     *  @JMS\Type("DateTime")
     */
    private $updatedAt;

    public function __construct()
    {
        $this->pageZoneList = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set realUpdatedAt
     *
     * @param datetime $realUpdatedAt
     */
    public function setRealUpdatedAt($realUpdatedAt)
    {
        $this->realUpdatedAt = $realUpdatedAt;
    }

    /**
     * Get realUpdatedAt
     *
     * @return datetime $realUpdatedAt
     */
    public function getRealUpdatedAt()
    {
        return $this->realUpdatedAt;
    }

    /**
     * Set publishedAt
     *
     * @param datetime $publishedAt
     */
    public function setPublishedAt($publishedAt)
    {
        $this->publishedAt = $publishedAt;
    }

    /**
     * Get publishedAt
     *
     * @return datetime $publishedAt
     */
    public function getPublishedAt()
    {
        return $this->publishedAt;
    }

    /**
     * Set unpublishedAt
     *
     * @param datetime $unpublishedAt
     */
    public function setUnpublishedAt($unpublishedAt)
    {
        $this->unpublishedAt = $unpublishedAt;
    }

    /**
     * Get unpublishedAt
     *
     * @return datetime $unpublishedAt
     */
    public function getUnpublishedAt()
    {
        return $this->unpublishedAt;
    }

    /**
     * Set createdAt
     *
     * @param datetime $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * Get createdAt
     *
     * @return datetime $createdAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param datetime $updatedAt
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }

    /**
     * Get updatedAt
     *
     * @return datetime $updatedAt
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
    /**
     * @var string $language
     */
    /** @JMS\Groups({"language"})
     *  @JMS\Type("string")
     */
    private $language;

    /**
     * Set language
     *
     * @param string $language
     */
    public function setLanguage($language)
    {
        $this->language = $language;
    }

    /**
     * Get language
     *
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * @var Kitpages\CmsBundle\Entity\PageZone
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("ArrayCollection<Kitpages\CmsBundle\Entity\PageZone>")
     */
    private $pageZoneList;

    /**
     * Add pageZoneList
     *
     * @param Kitpages\CmsBundle\Entity\PageZone $pageZoneList
     */
    public function addPageZoneList(\Kitpages\CmsBundle\Entity\PageZone $pageZoneList)
    {
        $this->pageZoneList[] = $pageZoneList;
    }

    /**
     * Get pageZoneList
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getPageZoneList()
    {
        return $this->pageZoneList;
    }
    /**
     * @var string $urlTitle
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("string")
     */
    private $urlTitle;

    /**
     * @var Kitpages\CmsBundle\Entity\PagePublish
     */
    /** @JMS\Groups({"publish"})
     *  @JMS\Type("Kitpages\CmsBundle\Entity\PagePublish")
     */
    private $pagePublish;

    /**
     * Set urlTitle
     *
     * @param string $urlTitle
     */
    public function setUrlTitle($urlTitle)
    {
        $this->urlTitle = $urlTitle;
    }

    /**
     * Get urlTitle
     *
     * @return string
     */
    public function getUrlTitle()
    {
        return $this->urlTitle;
    }

    /**
     * Set pagePublish
     *
     * @param Kitpages\CmsBundle\Entity\PagePublish $pagePublish
     */
    public function setPagePublish(\Kitpages\CmsBundle\Entity\PagePublish $pagePublish)
    {
        $this->pagePublish = $pagePublish;
    }

    /**
     * Get pagePublish
     *
     * @return Kitpages\CmsBundle\Entity\PagePublish
     */
    public function getPagePublish()
    {
        return $this->pagePublish;
    }
    /**
     * @var string $title
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("string")
     */
    private $title;

    /**
     * Set title
     *
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }
    /**
     * @var integer $left
     */
    /** @JMS\Groups({"tree"})
     *  @JMS\Type("integer")
     */
    private $left;

    /**
     * @var integer $right
     */
    /** @JMS\Groups({"tree"})
     *  @JMS\Type("integer")
     */
    private $right;

    /**
     * @var integer $root
     */
    /** @JMS\Groups({"tree"})
     *  @JMS\Type("integer")
     */
    private $root;

    /**
     * @var integer $level
     */
    /** @JMS\Groups({"tree"})
     *  @JMS\Type("integer")
     */
    private $level;

    /**
     * @var Kitpages\CmsBundle\Entity\Page
     */
    /** @JMS\Groups({"tree"})
     *  @JMS\Type("Kitpages\CmsBundle\Entity\Page")
     */
    private $parent;

    /**
     * Set left
     *
     * @param integer $left
     */
    public function setLeft($left)
    {
        $this->left = $left;
    }

    /**
     * Get left
     *
     * @return integer
     */
    public function getLeft()
    {
        return $this->left;
    }

    /**
     * Set right
     *
     * @param integer $right
     */
    public function setRight($right)
    {
        $this->right = $right;
    }

    /**
     * Get right
     *
     * @return integer
     */
    public function getRight()
    {
        return $this->right;
    }

    /**
     * Set root
     *
     * @param integer $root
     */
    public function setRoot($root)
    {
        $this->root = $root;
    }

    /**
     * Get root
     *
     * @return integer
     */
    public function getRoot()
    {
        return $this->root;
    }

    /**
     * Set level
     *
     * @param integer $level
     */
    public function setLevel($level)
    {
        $this->level = $level;
    }

    /**
     * Get level
     *
     * @return integer
     */
    public function getLevel()
    {
        return $this->level;
    }

    /**
     * Set parent
     *
     * @param Kitpages\CmsBundle\Entity\Page $parent
     */
    public function setParent(\Kitpages\CmsBundle\Entity\Page $parent)
    {
        $this->parent = $parent;
    }

    /**
     * Get parent
     *
     * @return Kitpages\CmsBundle\Entity\Page
     */
    public function getParent()
    {
        return $this->parent;
    }
    /**
     * @var string $linkUrl
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("string")
     */
    private $linkUrl;

    /**
     * Set linkUrl
     *
     * @param string $linkUrl
     */
    public function setLinkUrl($linkUrl)
    {
        $this->linkUrl = $linkUrl;
    }

    /**
     * Get linkUrl
     *
     * @return string
     */
    public function getLinkUrl()
    {
        return $this->linkUrl;
    }
    /**
     * @var Kitpages\CmsBundle\Entity\NavPublish
     */
    /** @JMS\Groups({"publish"})
     *  @JMS\Type("Kitpages\CmsBundle\Entity\NavPublish")
     */
    private $navPublish;

    /**
     * Set navPublish
     *
     * @param Kitpages\CmsBundle\Entity\NavPublish $navPublish
     */
    public function setNavPublish(\Kitpages\CmsBundle\Entity\NavPublish $navPublish)
    {
        $this->navPublish = $navPublish;
    }

    /**
     * Get navPublish
     *
     * @return Kitpages\CmsBundle\Entity\NavPublish
     */
    public function getNavPublish()
    {
        return $this->navPublish;
    }
    /**
     * @var string $menuTitle
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("string")
     */
    private $menuTitle;

    /**
     * Set menuTitle
     *
     * @param string $menuTitle
     */
    public function setMenuTitle($menuTitle)
    {
        $this->menuTitle = $menuTitle;
    }

    /**
     * Get menuTitle
     *
     * @return string
     */
    public function getMenuTitle()
    {
        return $this->menuTitle;
    }
    /**
     * @var boolean $isPendingDelete
     */
    /** @JMS\Groups({"complet"})
     *  @JMS\Type("boolean")
     */
    private $isPendingDelete = false;

    /**
     * Set isPendingDelete
     *
     * @param boolean $isPendingDelete
     */
    public function setIsPendingDelete($isPendingDelete)
    {
        $this->isPendingDelete = $isPendingDelete;
    }

    /**
     * Get isPendingDelete
     *
     * @return boolean
     */
    public function getIsPendingDelete()
    {
        return $this->isPendingDelete;
    }
    /**
     * @var boolean $isInNavigation
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("boolean")
     */
    private $isInNavigation = true;

    /**
     * Set isInNavigation
     *
     * @param boolean $isInNavigation
     */
    public function setIsInNavigation($isInNavigation)
    {
        $this->isInNavigation = $isInNavigation;
    }

    /**
     * Get isInNavigation
     *
     * @return boolean
     */
    public function getIsInNavigation()
    {
        return $this->isInNavigation;
    }

    public function defaultSlug(){
        $this->setSlug('page_'.$this->getId());
    }

    /**
     * @var string $forcedUrl
     */
    /** @JMS\Groups({"complet"})
     *  @JMS\Type("string")
     */
    private $forcedUrl;

    /**
     * Set forcedUrl
     *
     * @param string $forcedUrl
     */
    public function setForcedUrl($forcedUrl)
    {
        if (substr($forcedUrl, 0, 1) != '/' && $forcedUrl != null) {
            $forcedUrl = '/'.$forcedUrl;
        }
        $this->forcedUrl = $forcedUrl;
    }

    /**
     * Get forcedUrl
     *
     * @return string
     */
    public function getForcedUrl()
    {
        return $this->forcedUrl;
    }

    /**
     * Get hasChildren
     *
     * @return boolean
     */
    public function getHasChildren()
    {
        if (($this->right - $this->left) > 1) {
            return true;
        }else {
            return false;
        }
    }

    /**
     * Get list fields
     *
     * @return array
     */
    public function getDataPage()
    {
        return array(
            'title' => $this->getTitle(),
            'slug' => $this->getSlug(),
            'language' => $this->getLanguage(),
            'menu_title' => $this->getMenuTitle(),
            'is_in_navigation' => $this->getIsInNavigation(),
            'forced_url' => $this->getForcedUrl(),
            'left' => $this->getLeft(),
            'right' => $this->getRight(),
            'root' => $this->getRoot(),
            'level' => $this->getLevel(),
            'hasChildren' => $this->getHasChildren()
        );
    }

    /**
     * Tells if the the given page is this page.
     *
     * Useful when not hydrating all fields.
     *
     * @param Page $Page
     * @return Boolean
     */
    public function isPage(Page $page = null)
    {
        return null !== $page && $this->getId() === $page->getId();
    }

    /**
     * Add pageZoneList
     *
     * @param Kitpages\CmsBundle\Entity\PageZone $pageZoneList
     */
    public function addPageZone(\Kitpages\CmsBundle\Entity\PageZone $pageZoneList)
    {
        $this->pageZoneList[] = $pageZoneList;
    }

    public function __toString() {
        return '['.get_class($this).':'.$this->getId().':'.$this->getSlug().']';
    }

    /**
     * @var boolean $isLinkUrlFirstChild
     */
    /** @JMS\Groups({"base"})
     *  @JMS\Type("boolean")
     */
    private $isLinkUrlFirstChild;

    /**
     * Set isLinkUrlFirstChild
     *
     * @param boolean $isLinkUrlFirstChild
     */
    public function setIsLinkUrlFirstChild($isLinkUrlFirstChild)
    {
        $this->isLinkUrlFirstChild = $isLinkUrlFirstChild;
    }

    /**
     * Get isLinkUrlFirstChild
     *
     * @return boolean
     */
    public function getIsLinkUrlFirstChild()
    {
        return $this->isLinkUrlFirstChild;
    }

    public function prePersist()
    {
        // Add your code here
    }

    public function preUpdate()
    {
        // Add your code here
    }

    /** @JMS\Groups({"complet","children"})
     *  @JMS\Type("array<Kitpages\CmsBundle\Entity\Page>")
     */
    private $children;

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

    /**
     * @param mixed $children
     */
    public function setChildren($children)
    {
        $this->children = $children;
    }

    public function addChild(\Kitpages\CmsBundle\Entity\Page $page)
    {
        $this->children[] = $page;
    }

}


<?php

/**
 * This file is part of MetaModels/attribute_translatedcheckbox.
 *
 * (c) 2012-2019 The MetaModels team.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * This project is provided in good faith and hope to be usable by anyone.
 *
 * @package    MetaModels/attribute_translatedcheckbox
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2012-2019 The MetaModels team.
 * @license    https://github.com/MetaModels/attribute_translatedcheckbox/blob/master/LICENSE LGPL-3.0-or-later
 * @filesource
 */

namespace MetaModels\AttributeTranslatedCheckboxBundle\EventListener;

use ContaoCommunityAlliance\DcGeneral\DataDefinition\Palette\Condition\Property\PropertyFalseCondition;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Palette\Condition\Property\PropertyTrueCondition;
use MetaModels\AttributeTranslatedCheckboxBundle\Attribute\TranslatedCheckbox;
use MetaModels\Events\CreatePropertyConditionEvent;

/**
 * Class CreatePropertyConditionListener.
 */
class CreatePropertyConditionListener
{
    /**
     * Create property condition for the translated checkbox.
     *
     * @param CreatePropertyConditionEvent $event The property condition event.
     *
     * @return void
     */
    public function createCondition(CreatePropertyConditionEvent $event)
    {
        $meta = $event->getData();

        if ('conditionpropertyvalueis' !== $meta['type']) {
            return;
        }

        $metaModel = $event->getMetaModel();
        $attribute = $metaModel->getAttributeById($meta['attr_id']);
        if (!($attribute instanceof TranslatedCheckbox)) {
            return;
        }

        if ((bool) $meta['value']) {
            $event->setInstance(new PropertyTrueCondition($attribute->getColName()));
            return;
        }
        $event->setInstance(new PropertyFalseCondition($attribute->getColName()));
    }
}


<?php

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

namespace Mmf\Plugin;

/**
 * The PluginManager Load all the installed plugins, give a way to search
 * all the plugins in the filesystem, install and uninstall plugins.
 *
 * Description
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class PluginManager implements PluginManagerInterface {

    /**
     *
     * @var ParametersInterface
     */
    protected $parameters;

    /**
     *
     * @var AutoloaderInterface
     */
    protected $autoloader;

    /**
     *
     * @var EventManagerInterface
     */
    protected $eventManager;

    /**
     *
     * @var PluginLocatorInterface
     */
    protected $pluginLocator;

    /**
     *
     * @var RoutingResolver
     */
    protected $routing;

    /**
     *
     * @var array
     */
    protected $pluginPaths;

    /**
     *
     * @var array (PluginInterface, ...)
     */
    public $pluginList = array();

    /**
     *
     * @param ParametersInterface $parameters
     * @param AutoloaderInterface $autoloader
     * @param EventManagerInterface $eventManager
     * @param PluginLocatorInterface $pluginLocator
     * @param RoutingResolver $routing
     */
    public function __construct(
        \Mmf\Parameter\ParametersInterface $parameters,
        \Mmf\Autoloader\AutoloaderInterface $autoloader,
        \Mmf\Event\EventManagerInterface $eventManager,
        PluginLocatorInterface $pluginLocator,
        \Mmf\Routing\RoutingResolver $routing
    ) {
        $this->parameters    = $parameters;
        $this->autoloader    = $autoloader;
        $this->eventManager  = $eventManager;
        $this->pluginLocator = $pluginLocator;
        $this->routing       = $routing;
        $this->pluginPaths   = $this->parameters->get('plugin')['pluginPaths'];
    }

    /**
     * Get the list of plugins installed and init them.
     *
     * @return false | array(PluginInterface)
     * @throws PluginException
     */
    public function initPluginInstalled() {
        try {
            foreach ($this->pluginPaths as $path) {
                //Get the installed plugins
                $newPluginInstalled = $this->pluginLocator->getInstalledPlugins($this->autoloader->getURLBase().$path);
                $listOfPluginsInstalled = $this->createPluginInstances($newPluginInstalled, true);
                foreach ($listOfPluginsInstalled as $newPlugin) {
                    $this->pluginList[] = $newPlugin['plugin'];
                }
            }
            return $this->pluginList;
        } catch (Exception $e) {
            throw new PluginException('Plugin Manager: Can not init all plugins. '
                    . 'Please find attach the error from the '
                    . 'initialization:'. $e->getMessage());
        }
    }

    /**
     * Return the list of all plugin available, installed and not installed.
     *
     * @return array PluginInterface
     * @throws PluginException
     */
    public function getPluginList() {
        $arrayPluginList = array();
        try {
            //Iterate over the plugins paths
            foreach ($this->pluginPaths as $path) {
                //Search new plugins
                $newPluginsDiscover = $this->pluginLocator->discoverPlugins($this->autoloader->getURLBase().$path);

                //Instantiate the plugins
                $listOfPluginsDiscover = $this->createPluginInstances($newPluginsDiscover);
                foreach ($listOfPluginsDiscover as $newPlugin) {
                    $arrayPluginList[] = array('plugin'=>$newPlugin['plugin'], 'enabled'=>$newPlugin['enabled']);
                }
            }
        } catch (\Exception $e) {
            throw new PluginException('Plugin Manager: Can not init all plugins. '
                    . 'Please find attach the error from the '
                    . 'initialization:'. $e->getMessage());
        }
        return (array)$arrayPluginList;
    }

    /**
     * Instantiate the plugins from pluginLocator and if is true the $init var,
     * it creates the plugin. The expected return value is a array of tuples
     * of plugin and if it's enabled or not.
     *
     * @param array      $plugins
     * @param bool|false $init
     *
     * @return array
     * @throws \PluginException
     */
    private function createPluginInstances($plugins, $init=false) {
        $pluginList = array();
        foreach ($plugins['pluginClasses'] as $key => $newPlugin) {
            //Load the concrete plugin directory
            $this->autoloader->addNewAutoloadPath($plugins['pluginDirectories'][$key], true);

            //Create new plugin instance

            if(class_exists($newPlugin)) {
                $newPluginInstantiation = new $newPlugin($this->parameters,
                                                        $this->autoloader,
                                                        $this->eventManager);
            } else {
                throw new PluginException('Plugin Manager: '
                        . 'Unable to instantiate the plugin with '
                        . 'name ('. $newPlugin. ') and path ('.
                        $plugins['pluginDirectories'][$key].')');
            }

            //Call Init function of the plugin
            if($init) {
                $newPluginInstantiation->init();
            }
            //Add the plugin instance into the plugin list
            $pluginList[] = ['plugin'=>$newPluginInstantiation,
                                  'enabled'=>$plugins['pluginEnabled'][$key]];
        }
        return $pluginList;
    }

    /**
     *
     * @param PluginInterface $plugin
     * @return bool
     * @throws PluginException
     */
    public function pluginInstall(PluginInterface $plugin) {
        try {
            $isPluginInstalled = $plugin->install();
        } catch(Exception $e) {
            throw new PluginException('Plugin Manager: cannot '
                    . 'install the plugin'. get_class($plugin));
        }

        return (bool)$isPluginInstalled;
    }

    /**
     *
     * @param PluginInterface $plugin
     * @return bool
     * @throws PluginException
     */
    public function pluginUninstall(PluginInterface $plugin) {
        try {
            $isPluginUninstalled = $plugin->uninstall();
        } catch(Exception $e) {
            throw new PluginException('Plugin Manager: cannot '
                    . 'uninstall the plugin'. get_class($plugin));
        }

        return (bool)$isPluginUninstalled;
    }
}


<?php
namespace Kitpages\CmsBundle\EventListener;

use Kitpages\CmsBundle\Entity\Page;
use Kitpages\CmsBundle\Entity\Site;
use Kitpages\CmsBundle\Entity\Zone;
use Kitpages\CmsBundle\Entity\Block;

use Kitpages\CmsBundle\Event\NavEvent;
use Kitpages\CmsBundle\KitpagesCmsEvents;

use Kitpages\UtilBundle\Service\Util;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\Event;
use Doctrine\Bundle\DoctrineBundle\Registry;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;

class DoctrineListener {

    ////
    // dependency injection
    ////
    protected $doctrine = null;
    protected $dispatcher = null;
    protected $util = null;

    public function __construct(
        Registry $doctrine,
        EventDispatcherInterface $dispatcher,
        Util $util
    )
    {
        $this->doctrine = $doctrine;
        $this->dispatcher = $dispatcher;
        $this->util = $util;
    }
    /**
     * @return EventDispatcher $dispatcher
     */
    public function getDispatcher() {
        return $this->dispatcher;
    }

    /**
     * @return Registry $doctrine
     */
    public function getDoctrine() {
        return $this->doctrine;
    }

    ////
    // doctrine events
    ////
    public function prePersist(LifecycleEventArgs $event)
    {
        $entity = $event->getEntity();
        if ($entity instanceof Block) {
            $entity->setSlug($this->util->urlPathEncode($entity->getSlug()));
            $slug = $entity->getSlug();
            if(empty($slug)) {
                $entity->setSlug('block_ID');
            }
        }
        if ($entity instanceof Zone) {
            $entity->setSlug($this->util->urlPathEncode($entity->getSlug()));
            $slug = $entity->getSlug();
            if(empty($slug)) {
                $entity->setSlug('zone_ID');
            }
        }
        if ($entity instanceof Page) {
            $entity->setUrlTitle($this->util->urlPathEncode($entity->getTitle()));
            $entity->setSlug($this->util->urlPathEncode($entity->getSlug()));
            $slug = $entity->getSlug();
            if(empty($slug)) {
                $entity->setSlug('page_ID');
            }
            if($entity->getIsInNavigation() == 1) {
                $this->unpublishNav();
            }
        }
    }
    public function postPersist(LifecycleEventArgs $event)
    {
        /* Event BLOCK */
        $entity = $event->getEntity();
        if ($event->getEntity() instanceof Block) {
            if($entity->getSlug() == 'block_ID') {
                $entity->defaultSlug();
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();
            }
        }
        if ($event->getEntity() instanceof Zone) {
            if($entity->getSlug() == 'zone_ID') {
                $entity->defaultSlug();
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();
            }
        }
        if ($event->getEntity() instanceof Page) {
            if($entity->getSlug() == 'page_ID') {
                $entity->defaultSlug();
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();
            }
        }

    }

    public function preUpdate(PreUpdateEventArgs $eventArgs)
    {
        $entity = $eventArgs->getEntity();

        /* Event BLOCK */
        if ($entity instanceof Block) {
            $entity->setSlug($this->util->urlPathEncode($entity->getSlug()));
            $slug = $entity->getSlug();
            if(empty($slug)) {
                $entity->defaultSlug();
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();
            }

        }

        /* Event Zone */
        if ($entity instanceof Zone) {
            $entity->setSlug($this->util->urlPathEncode($entity->getSlug()));
            $slug = $entity->getSlug();
            if(empty($slug)) {
                $entity->defaultSlug();
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();
            }

//            if (($eventArgs->hasChangedField('data')
//                || $eventArgs->hasChangedField('template'))
//                && $entity->getIsPublished() == 1
//            ) {
//                $entity->setIsPublished(false);
//                $entity->setUnpublishedAt(new \DateTime());
//                $uom->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
//            }

        }
        /* Event Page */
        if ($entity instanceof Page) {
            $entity->setUrlTitle($this->util->urlPathEncode($entity->getTitle()));
            $entity->setSlug($this->util->urlPathEncode($entity->getSlug()));
            $slug = $entity->getSlug();
            if(empty($slug)) {
                $entity->defaultSlug();
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();
            }

        }
        /* Event PAGE */
        if ($entity instanceof Page) {
            if($eventArgs->hasChangedField('isInNavigation')
                || (!$eventArgs->hasChangedField('isInNavigation') && $entity->getIsInNavigation() == 1 && $eventArgs->hasChangedField('menuTitle'))
                || (!$eventArgs->hasChangedField('isInNavigation') && $entity->getIsInNavigation() == 1 && $eventArgs->hasChangedField('parent'))) {
                $this->unpublishNav();
            }

        }

    }

    public function unpublishNav()
    {
        $event = new NavEvent();
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onNavPublish, $event);
        if (! $event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            $em->getRepository('KitpagesCmsBundle:Site')->set(Site::IS_NAV_PUBLISHED, 0);
//            $em->flush();
        }
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterNavPublish, $event);
    }
}


<?php
namespace Kitpages\CmsBundle\Model;

use Doctrine\ORM\EntityManager;
use Kitpages\CmsBundle\Controller\Context;

class ZoneService
{
    ////
    // dependency injection
    ////
    protected $dispatcher = null;
    protected $doctrine = null;
    protected $blockManager = null;
    protected $logger = null;

    public function __construct(
        EntityManager $em
    )
    {
        $this->em = $em;
    }

    ////
    // test
    ////
    public function isEmpty($slug, $viewMode)
    {
        $countBlock = $this->countBlock($slug, $viewMode);
        if($countBlock > 0) {
            return false;
        } else {
            return true;
        }

    }

    public function countBlock($slug, $viewMode)
    {
        $countBlock = 0;
        if ($viewMode == Context::VIEW_MODE_EDIT || $viewMode == Context::VIEW_MODE_PREVIEW) {
            $zone = $this->em->getRepository('KitpagesCmsBundle:Zone')->findOneBy(array('slug' => $slug));
            if ($zone != null) {
                $countBlock = $this->em
                    ->getRepository('KitpagesCmsBundle:Block')
                    ->getBlockCountByZone($zone);
            }
        } elseif ($viewMode == Context::VIEW_MODE_PROD) {
            $zonePublish = $this->em->getRepository('KitpagesCmsBundle:ZonePublish')->findOneBy(array('slug' => $slug));
            if ($zonePublish != null) {
                $data = $zonePublish->getData();
                if (isset($data['blockPublishList']) && is_array($data['blockPublishList']) && $data['blockPublishList'] != null ) {
                    // retrieve first template
                    $blockList = array_shift($data['blockPublishList']);
                    if (is_array($blockList)) {
                        $countBlock = count($blockList);
                    }
                }
            }
        }
        return $countBlock;
    }

}


<?php
namespace Mmf\View;

/**
 *
 */
class TwigView extends BasicViewAbstract {

    /**
     * String var with Twig instance
     * @var string
     */
    public $twig = '';

	/**
	 * [__construct description]
	 * @param \Mmf\Parameter\ParametersInterface $config [description]
	 */
    public function __construct(\Mmf\Parameter\ParametersInterface $config) {
        $this->config = $config;
        $this->viewsFolder = $this->config->get('URLBase') . $this->config->get('mvc')['viewFolder'];

        /**
         * Based on template engine selection load its custom component
         */
		$this->loadTwig();
    }

    /**
     * Prepare Twig to be use into views
     * @return Twig instance
     */
    public function loadTwig() {

        $loader = new \Twig_Loader_Filesystem(
            array (
                $this->viewsFolder
            )
        );

        // Set up environment
        $params = array(
            //'cache' => $this->viewsFolder . "cache",
        );

        $this->twig = new \Twig_Environment($loader, $params);
    }

    /**
     * [get description]
     * @param  [type] $path             [description]
     * @param  string $template         [description]
     * @param  array  $vars             [description]
     * @param  string $globalScriptVars [description]
     * @return [type]                   [description]
     */
    public function get($path, $template = '', $vars = array(), $globalScriptVars = '') {

        if ($template !== '') {
            $this->setTemplate($template);
        }

        //If exists vars to assign, we assing one by one.
        $viewVars = (count($vars) > 0) ? $vars : $this->viewVars;

        //Include the style if exists some style to include
        if (isset($this->styles)) {
            $vars['styles'] = $this->styles;
        }

        return $this->twig->render('html/'.$path, $viewVars);
    }

}


<?php

/**
 * This file is part of MetaModels/attribute_translatedcheckbox.
 *
 * (c) 2012-2019 The MetaModels team.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * This project is provided in good faith and hope to be usable by anyone.
 *
 * @package    MetaModels/attribute_translatedcheckbox
 * @author     Christian Schiffler <c.schiffler@cyberspectrum.de>
 * @author     Stefan Heimes <stefan_heimes@hotmail.com>
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @author     Sven Baumann <baumann.sv@gmail.com>
 * @copyright  2012-2019 The MetaModels team.
 * @license    https://github.com/MetaModels/attribute_translatedcheckbox/blob/master/LICENSE LGPL-3.0-or-later
 * @filesource
 */

namespace MetaModels\AttributeTranslatedCheckboxBundle\Attribute;

use MetaModels\Attribute\TranslatedReference;

/**
 * This is the MetaModelAttribute class for handling translated checkbox fields.
 */
class TranslatedCheckbox extends TranslatedReference
{
    /**
     * Private flag to lock filling of missing values in getTranslatedDataFor.
     *
     * @var bool
     */
    private $doNotFixValues = false;

    /**
     * Check if the attribute is a published field.
     *
     * @return bool
     */
    public function isPublishedField()
    {
        return $this->get('check_publish') == 1;
    }

    /**
     * {@inheritDoc}
     */
    public function getAttributeSettingNames()
    {
        return \array_merge(
            parent::getAttributeSettingNames(),
            [
                'mandatory',
                'check_publish',
                'filterable',
                'searchable',
                'submitOnChange'
            ]
        );
    }

    /**
     * {@inheritDoc}
     */
    protected function getValueTable()
    {
        return 'tl_metamodel_translatedcheckbox';
    }

    /**
     * {@inheritDoc}
     */
    public function getFieldDefinition($arrOverrides = [])
    {
        $arrFieldDef              = parent::getFieldDefinition($arrOverrides);
        $arrFieldDef['inputType'] = 'checkbox';

        return $arrFieldDef;
    }

    /**
     * {@inheritDoc}
     */
    public function getTranslatedDataFor($arrIds, $strLangCode)
    {
        $arrReturn = parent::getTranslatedDataFor($arrIds, $strLangCode);

        // Per definition:
        // - all values that are not contained are defaulting to false in the fallback language.
        // - all values in published not contained are defaulting to false.
        if ($this->isFixingOfValuesNeeded($arrReturn, $arrIds, $strLangCode)) {
            foreach (array_diff($arrIds, array_keys($arrReturn)) as $itemId) {
                $arrReturn[$itemId] = $this->widgetToValue(false, $itemId);
            }
        }

        return $arrReturn;
    }

    /**
     * Check if the passed values need to be fixed (filled up) with missing ids.
     *
     * @param array    $values   The retrieved values.
     *
     * @param string[] $idList   The list of ids.
     *
     * @param string   $langCode The language code.
     *
     * @return bool
     */
    private function isFixingOfValuesNeeded($values, $idList, $langCode)
    {
        if ($this->doNotFixValues) {
            return false;
        }

        if (\count($values) == \count($idList)) {
            return false;
        }

        return ($this->isPublishedField() || ($langCode == $this->getMetaModel()->getFallbackLanguage()));
    }
}


<?php
namespace Kitpages\CmsBundle\Model;

use JMS\Serializer\SerializationContext;
use Kitpages\CmsBundle\Entity\Page;
use Kitpages\CmsBundle\Entity\PageZone;
use Kitpages\CmsBundle\Entity\PagePublish;
use Kitpages\CmsBundle\Entity\Zone;
use Kitpages\CmsBundle\Entity\Block;
use Kitpages\CmsBundle\Entity\ZonePublish;
use Kitpages\CmsBundle\Entity\ZoneBlock;
use Kitpages\CmsBundle\Event\PageEvent;
use Kitpages\CmsBundle\Event\PagePublishEvent;
use Kitpages\CmsBundle\KitpagesCmsEvents;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\Event;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Validator\Constraint;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;

class PageManager
{
    ////
    // dependency injection
    ////
    protected $dispatcher = null;
    protected $doctrine = null;
    protected $zoneManager = null;
    protected $cmsFileManager = null;
    protected $logger = null;

    public function __construct(
        Registry $doctrine,
        EventDispatcherInterface $dispatcher,
        ZoneManager $zoneManager,
        CmsFileManager $cmsFileManager,
        $jmsSerializer,
        LoggerInterface $logger
    )
    {
        $this->dispatcher = $dispatcher;
        $this->doctrine = $doctrine;
        $this->zoneManager = $zoneManager;
        $this->cmsFileManager = $cmsFileManager;
        $this->jmsSerializer = $jmsSerializer;
        $this->logger = $logger;
    }

    /**
     * @return EventDispatcher $dispatcher
     */
    public function getDispatcher() {
        return $this->dispatcher;
    }

    /**
     * @return Registry $doctrine
     */
    public function getDoctrine() {
        return $this->doctrine;
    }

    /**
     * @return CmsFileManager $cmsFileManager
     */
    public function getCmsFileManager() {
        return $this->cmsFileManager;
    }

    /**
     * @return ZoneManager $zoneManager
     */
    public function getZoneManager() {
        return $this->zoneManager;
    }

    /**
     * @return LoggerInterface
     */
    public function getLogger()
    {
        return $this->logger;
    }

    ////
    // repo
    ////
    /**
     * @return Page $page
     */

    public function getChildrenPageBySlug($slug)
    {
        $em = $this->getDoctrine()->getManager();

        $children = $em->getRepository('KitpagesCmsBundle:Page')->children(
            $this->getPageBySlug($slug),
            true
        );

        return $children;
    }

//    public function getChildrenPageJsonBySlug($slug, array $optionExport)
//    {
//        $em = $this->getDoctrine()->getManager();
//
//        $children = $em->getRepository('KitpagesCmsBundle:Page')->children(
//            $this->getPageBySlug($slug),
//            true
//        );
//
//        $childrenJson = array();
//
//        foreach($children as $child) {
//            $childrenJson[] = $this->getPageJsonByPage($child, $optionExport);
//        }
//        return $childrenJson;
//    }

    public function getPageBySlug($slug)
    {
        $page = $this->doctrine->getManager()->getRepository('Kitpages\CmsBundle\Entity\Page')->findOneBy(array('slug' => $slug));
        return $page;
    }
    ////
    // actions
    ////

    public function getObjectBySerializeFormat($content, $format, $entity)
    {
        $page = $this->jmsSerializer->deserialize(
            $content,
            $entity,
            $format
        );
        return $page;
    }

    public function updatePageByOption(Page $page, $option)
    {
        if (isset($option['page_language'])) {
            $page->setLanguage($option['page_language']);
        }
    }

    public function getContentPageAndChildrenJsonBySlug($slug, array $optionExport)
    {
        $contentJsonRoot = $this->getContentPageJsonBySlug($slug, $optionExport);
        $pageRootJson = $this->getObjectBySerializeFormat($contentJsonRoot, 'json', 'Kitpages\CmsBundle\Entity\Page');

//        $pageRootJson->setChildren($this->getChildrenPageJsonBySlug($slug, $optionExport));

        return $this->getJson($pageRootJson, $optionExport);
    }

    public function getPageJsonByPage(Page $page, $optionExport)
    {
        $contentJson = $this->getJson($page, $optionExport);

        $pageJson = $this->getObjectBySerializeFormat($contentJson, 'json', 'Kitpages\CmsBundle\Entity\Page');
        return $pageJson;
    }

    public function getContentPageJsonBySlug($slug, array $optionExport)
    {
        $page = $this->getPageBySlug($slug);

        return $this->getJson($this->getPageJsonByPage($page, $optionExport), $optionExport);
    }

    public function getJson($page, array $optionExport)
    {
        $pageJson = $this->jmsSerializer->serialize(
            $page,
            'json',
            SerializationContext::create()->setGroups($optionExport)
        );
        return $pageJson;
    }

//    public function createNewPageByXml($xml)
//    {
//        return $this->getObjectBySerializeFormat($xml, 'xml');
//    }
//
//    public function getPageXmlBySlug($slug, array $optionExport)
//    {
//        $pageXml = $this->getPageXml($this->getPageBySlug($slug), $optionExport);
//        return $pageXml;
//    }
//
//    public function getPageXml(Page $page, array $optionExport)
//    {
//        $pageXml = $this->jmsSerializer->serialize(
//            $page,
//            'xml',
//            SerializationContext::create()->setGroups($optionExport)
//        );
//        return $pageXml;
//    }

    public function unpendingDelete(Page $page)
    {
        // throw on event
        $event = new PageEvent($page);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onPagePendingDelete, $event);

        // preventable action
        if (!$event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            $page->setIsPendingDelete(0);
            $em->flush();
        }
        // throw after event
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterPagePendingDelete, $event);
    }

    public function pendingDelete(Page $page)
    {
        // throw on event
        $event = new PageEvent($page);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onPagePendingDelete, $event);

        // preventable action
        if (!$event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            $page->setIsPendingDelete(1);
            $em->flush();
        }
        // throw after event
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterPagePendingDelete, $event);
    }

    public function delete(Page $page)
    {
        // throw on event
        $event = new PageEvent($page);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onPageDelete, $event);

        // preventable action
        if (!$event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            $zoneManager = $this->getZoneManager();
            foreach($em->getRepository('KitpagesCmsBundle:Zone')->findByPage($page) as $zone){
                $nbr = $em->getRepository('KitpagesCmsBundle:PageZone')->nbrPageZoneByZoneWithPageDiff($zone, $page);
                if ($nbr == 0) {
                    $zoneManager->delete($zone);
                }
            }
            $pageData=$page->getData();
            if (!isset($pageData['root'])) {
                $pageData['root'] = array();
            }
            $cmsFileManager = $this->cmsFileManager;
            $cmsFileManager->delete($pageData['root']);
            $em->remove($page);
            $em->flush();
        }
        // throw after event
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterPageDelete, $event);
    }

    public function publishPage(Page $page, array $listLayout, array $listRenderer, array $dataInheritanceList)
    {
        $event = new PageEvent($page, $listLayout);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onPagePublish, $event);
        $cmsFileManager = $this->getCmsFileManager();
        if (! $event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            if ($page->getIsPendingDelete()) {
                $pagePublish = $em->getRepository('KitpagesCmsBundle:PagePublish')->findByPage($page);
                $eventPublish = new PagePublishEvent($pagePublish);
                $this->getDispatcher()->dispatch(KitpagesCmsEvents::onModifyPagePublish, $eventPublish);
                if (!is_null($pagePublish)) {
                    $pagePublishData = $pagePublish->getData();
                    if (isset($pagePublishData['media'])) {
                        $cmsFileManager->unpublishFileList($pagePublishData['media']);
                    }
                    $em->remove($pagePublish);
                    $em->flush();
                }
                $this->delete($page);
            } else {
                // publish zone
                $em = $this->getDoctrine()->getManager();
                foreach($em->getRepository('KitpagesCmsBundle:Zone')->findByPage($page) as $zone){
                    $this->getZoneManager()->publish($zone, $listRenderer);
                }
                $em->flush();
                // remove old pagePublish
                $zonePublish = null;
                $pagePublish = $em->getRepository('KitpagesCmsBundle:PagePublish')->findByPage($page);

                $eventPublish = new PagePublishEvent($pagePublish);
                $this->getDispatcher()->dispatch(KitpagesCmsEvents::onModifyPagePublish, $eventPublish);
                if (!is_null($pagePublish)) {
                    $em->remove($pagePublish);
                    $em->flush();
                }

                $zoneList = array();
                // create page publish
                foreach($em->getRepository('KitpagesCmsBundle:Zone')->findByPage($page) as $zone){
                    $zoneList[] = $zone->getId();
                }

                $data['root'] = $em->getRepository('KitpagesCmsBundle:Page')->getDataWithInheritance($page, $dataInheritanceList);

                $cmsFileManager->publishDataMediaList($data['root']);
                $listMedia = $cmsFileManager->mediaList($data['root'], true);
                $data['media'] = $listMedia;

                $pagePublishNew = new PagePublish();
                $pagePublishNew->initByPage($page, $data);
                $pagePublishNew->setZoneList(array("zoneList"=>$zoneList));
                $page->setIsPublished(true);
                $page->setPagePublish($pagePublishNew);
                $em->flush();
                $eventPublish->setPagePublishNew($pagePublishNew);
            }
            $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterModifyPagePublish, $eventPublish);
        }
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterPagePublish, $event);
    }

    public function publish(Page $page, array $layoutList, array $listRenderer, array $dataInheritanceList, $childrenPublish)
    {

        $event = new PageEvent($page, $layoutList);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onMultiplePagePublish, $event);
        if ($childrenPublish) {
            $em = $this->getDoctrine()->getManager();
            $pageChildren = $em->getRepository('KitpagesCmsBundle:Page')->children($page, true);
            //$pageChildren = $em->getRepository('KitpagesCmsBundle:Page')->children($page, false, 'level', 'DESC');
            foreach($pageChildren as $pageChild) {
                //$this->publishPage($pageChild, $layoutList, $listRenderer, $dataInheritanceList);
                $this->publish($pageChild, $layoutList, $listRenderer, $dataInheritanceList, $childrenPublish);
            }
        }
        $this->publishPage($page, $layoutList, $listRenderer, $dataInheritanceList);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterMultiplePagePublish, $event);
    }

    public function afterModify($page, $oldPage)
    {
        if ($oldPage != $page) {
            $page->setRealUpdatedAt(new \DateTime());
            $em = $this->getDoctrine()->getManager();
            $em->flush();
            $this->unpublish($page);
            $event = new PageEvent($page);
            $event->setData('oldPageData', $oldPage->getData());
            $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterPageModify, $event);
        }
    }

    public function unpublish($page){
        $event = new PageEvent($page);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onPageUnpublish, $event);
        $em = $this->getDoctrine()->getManager();
        $page->setIsPublished(false);
        $em->flush();
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterPageUnpublish, $event);
    }

    public function createZoneInPage(Page $page, $locationInPage)
    {
        $em = $this->getDoctrine()->getManager();
        $zone = new Zone();
        $zone->setSlug('');
        $zone->setIsPublished(false);
        $em->persist($zone);
        $em->flush();
        $pageZone = new PageZone();
        $pageZone->setPage($page);
        $pageZone->setZone($zone);
        $pageZone->setLocationInPage($locationInPage);
        $em->persist($pageZone);
        $em->flush();
    }

    public function createNewPage(Page $page, $dataForm)
    {
        $page->setIsPublished(false);
        $em = $this->doctrine->getManager();

        $parent_id = $dataForm['parent_id'];
        $repositoryPage = $em->getRepository('KitpagesCmsBundle:Page');
        if (!empty($parent_id)) {
            $pageParent = $repositoryPage->find($parent_id);
            $page->setLanguage($pageParent->getLanguage());
            $page->setParent($pageParent);
        }
        $nextSiblingSlug = $dataForm['next_sibling_slug'];
        $prevSiblingSlug = $dataForm['prev_sibling_slug'];
        if($nextSiblingSlug != null) {
            $sibling = $repositoryPage->findOneBySlug($nextSiblingSlug);
            $repositoryPage->persistAsNextSiblingOf($page, $sibling);
        }elseif($prevSiblingSlug != null){
            $sibling = $repositoryPage->findOneBySlug($prevSiblingSlug);
            $repositoryPage->persistAsPrevSiblingOf($page, $sibling);
        }
        $em->persist($page);

        $em->flush();
    }

    ////
    // event listener
    ////
    public function afterZoneUnpublish(Event $event)
    {
        $zone = $event->getZone();
        $em = $this->getDoctrine()->getManager();
        foreach($em->getRepository('KitpagesCmsBundle:Page')->findByZone($zone) as $page) {
            $this->unpublish($page);
        }
    }

    ////
    //  Validator
    ////
    public function validateUniqueForceUrlPublish(Page $page, Constraint $constraint)
    {

        if ($page->getForcedUrl() == null) {
            return true;
        }

        $em = $this->getDoctrine()->getManager();
        $pagePublishConflictList = $em->getRepository('KitpagesCmsBundle:PagePublish')->findBy(array('forcedUrl' => $page->getForcedUrl()));
        // there is no conflictual user
        if (empty($pagePublishConflictList)) {
            return true;
        }

        foreach ($pagePublishConflictList as $pagePublishConflict) {
            if ($pagePublishConflict->getPage()->getId() != $page->getId()) {
                return false;
            }
        }

        return true;
    }

}


<?php

namespace Kitpages\CmsBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Configuration processer.
 * Parses/validates the extension configuration and sets default values.
 *
 * @author Philippe Le Van (@plv)
 */
class Configuration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree.
     *
     * @return TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('kitpages_cms');

        $this->addBlockSection($rootNode);
        $this->addPageSection($rootNode);
        $this->addOtherSection($rootNode);

        return $treeBuilder;
    }

    /**
     * Parses the kitpages_cms.block config section
     * Example for yaml driver:
     * kitpages_cms:
     *     block:
     *         template:
     *             template_list: {standard: \Kitpages\CmsBundle\Form\TemplateStandardType}
     *
     * @param ArrayNodeDefinition $node
     * @return void
     */
    private function addBlockSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('block')
                    ->addDefaultsIfNotSet()
                    ->children()

                        ->arrayNode('template')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->arrayNode('template_list')
                                    ->useAttributeAsKey('template_slug')
                                        ->prototype('array')
                                        ->children()
                                            ->scalarNode('service')
                                            ->end()
                                            ->scalarNode('class')
                                            ->end()
                                            ->scalarNode('name')
                                                ->cannotBeEmpty()
                                            ->end()
                                            ->scalarNode('twig')
                                                ->cannotBeEmpty()
                                            ->end()
                                        ->end()
                                    ->end()

//                                    ->addDefaultsIfNotSet()
//                                    ->children()
//                                        ->arrayNode('standard')
//                                            ->addDefaultsIfNotSet()
//                                            ->children()
//                                                ->scalarNode('class')
//                                                    ->defaultValue('\Kitpages\CmsBundle\Form\BlockTemplateEditStandardType')
//                                                    ->cannotBeEmpty()
//                                                ->end()
//                                                ->scalarNode('name')
//                                                    ->defaultValue('Standard')
//                                                    ->cannotBeEmpty()
//                                                ->end()
//                                                ->scalarNode('twig')
//                                                    ->defaultValue('KitpagesCmsBundle:Block:edit.html.twig')
//                                                    ->cannotBeEmpty()
//                                                ->end()
//                                            ->end()
//                                        ->end()
//                                    ->end()
                                ->end()
                            ->end()
                        ->end()

                        ->arrayNode('renderer')
                            ->useAttributeAsKey('template_slug')
                                ->prototype('array')

                                    ->useAttributeAsKey('renderer_slug')
                                        ->prototype('array')
                                        ->children()
                                            ->scalarNode('type')
                                                ->cannotBeEmpty()
                                            ->end()
                                            ->scalarNode('twig')
                                            ->end()
                                        ->end()
                                    ->end()

                                ->end()
                            ->end()
//                            ->addDefaultsIfNotSet()
//                            ->children()
//                                ->arrayNode('standard')
//                                    ->addDefaultsIfNotSet()
//                                    ->children()
//                                        ->arrayNode('default')
//                                            ->addDefaultsIfNotSet()
//                                            ->children()
//                                                ->scalarNode('type')
//                                                    ->defaultValue('twig')
//                                                    ->cannotBeEmpty()
//                                                ->end()
//                                                ->scalarNode('twig')
//                                                    ->defaultValue('KitpagesCmsBundle:Block:block-render-standard-default.html.twig')
//                                                ->end()
//                                            ->end()
//                                        ->end()
//                                    ->end()
//                                ->end()
//                            ->end()
                        ->end()

                    ->end()
                ->end()
            ->end();
    }

    /**
     * Parses the kitpages_cms.block config section
     * Example for yaml driver:
     * kitpages_cms:
     *     block:
     *         template:
     *             template_list: {standard: \Kitpages\CmsBundle\Form\TemplateStandardType}
     *
     * @param ArrayNodeDefinition $node
     * @return void
     */
    private function addPageSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('page')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('renderer_twig_main')
                            ->defaultValue('KitpagesCmsBundle:Page:layout.html.twig')
                        ->end()
                        ->arrayNode('data_inheritance_list')
                            ->defaultValue(array())
                            ->prototype('scalar')->end()
                        ->end()
                        ->scalarNode('data_inheritance_form_service')
                        ->end()
                        ->scalarNode('data_inheritance_form_class')
                        ->end()
                        ->scalarNode('data_inheritance_form_twig')
                        ->end()
                        ->arrayNode('layout_list')
                            ->useAttributeAsKey('layout')
                            ->prototype('array')
                                ->addDefaultsIfNotSet()
                                ->children()
                                    ->scalarNode('renderer_twig')
                                        ->cannotBeEmpty()
                                    ->end()
                                    ->scalarNode('data_form_service')
                                    ->end()
                                    ->scalarNode('data_form_class')
                                    ->end()
                                    ->scalarNode('data_form_twig')
                                        ->cannotBeEmpty()
                                    ->end()
                                    ->arrayNode('zone_list')
                                        ->useAttributeAsKey('location_in_page')
                                            ->prototype('array')
                                            ->children()
                                                ->scalarNode('renderer')
                                                    ->cannotBeEmpty()
                                                ->end()
                                                ->arrayNode('authorized_block_template_list')
                                                    ->isRequired()
                                                    ->requiresAtLeastOneElement()
                                                    ->beforeNormalization()
                                                        ->ifTrue(function($v){ return !is_array($v); })
                                                        ->then(function($v){ return array($v); })
                                                    ->end()
                                                    ->prototype('scalar')->end()
                                                ->end()
                                            ->end()
                                        ->end()
                                    ->end()
                                ->end()
                            ->end()
                        ->end()

                        ->scalarNode('default_twig')
                            ->cannotBeEmpty()
                        ->end()
                        ->scalarNode('bootstrap')
                            ->defaultValue(false)
                        ->end()
                    ->end()
                ->end()
            ->end();
    }

    /**
     * Parses the kitpages_cms others sections
     * Example for yaml driver:
     * kitpages_cms:
     *     target_parameter: 'cms_target'
     *
     * @param ArrayNodeDefinition $node
     * @return void
     */
    private function addOtherSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->scalarNode('target_parameter')
                    ->defaultValue(null)
                ->end()
                ->scalarNode('view_mode_default')
                    ->defaultValue('VIEW_MODE_PROD')
                ->end()
                ->scalarNode('export_dir')
                    ->defaultValue('%kernel.root_dir%/data/kitpagesCmsBundle/export')
                ->end()
            ->end();
    }
}


<?php

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

namespace Mmf\Auth;

/**
 * The AuthInterface
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class AuthAPI extends Auth {

    /**
     * Logic of authentication.
     *
     * @return void
     */
    public function authenticate() {
        if ($this->token != "") {
            $userInfo = $this->checkIfTokenIsValidAndUpdateTheExpireDate();
        } else { //Is a guess user.
            $userInfo = ['username' => 'guest', 'name' => 'guest', 'id_user' => 1];
        }

        $this->setUsername($userInfo['username']);
        $this->setRoleName($userInfo['name']);
        $this->setUserId($userInfo['id_user']);
        $this->setDefaultLanguage($userInfo['id_user']);
    }

    /**
     * Set the default language for this user.
     *
     * @param int $userId
     */
    private function setDefaultLanguage($userId) {
        if ($this->language !== null) {
            $languageModel = new \Mmf\Language\LanguageModel($this->connection);
            $userLanguageProperties = $languageModel->getUserLanguage($userId);
            if ($userLanguageProperties !== false) {
                $this->language->setLocale($userLanguageProperties['code']);
            }
        }
    }

    /**
     * Check if token is valid, if not throws and error.
     *
     * @throws MmfAuthException
     */
    private function checkIfTokenIsValidAndUpdateTheExpireDate() {
        $userInfo = $this->authModel->getRoleAndUserFromToken($this->token);
        if ($userInfo === false) {
            throw new AuthException('The token is not valid', 2000);
        }
        if ($userInfo['expire'] !== null &&
                $userInfo['expire'] < $userInfo['db_date']) {
            throw new AuthException('The token expires', 2001);
        }
        if ($userInfo['expire'] !== null) {
            $futureExpiredate = date('Y-m-d H:i:s',
                    strtotime($userInfo['db_date']) + $this->config->get('auth')['sessionTimeLife']
                    * 60);
            $this->authModel->updateExpireDate($this->token, $futureExpiredate);
        }
        return $userInfo;
    }

}


<?php

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

namespace Mmf\IO;

/**
 * The ResponseJson format the response into the JSON format.
 *
 * @author Jepi Humet
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 */
class ResponseJson implements ResponseInterface {

    /**
     * It gets the return array and it encapsulates into the json_encode. The
     * right way of json structure is, array(success=>1|0 responseData=>
     * result of the controller action or error message). The return data will be
     * encode into the utf8.
     *
     * @param mixed $response
     * @return string
     */
    public function formatResponse($response) {
        //$utf8Response = $this->utf8Encode($response);
        $returnResponse = array('success'=>true, 'responseData'=>$response);
        $this->sendHeaders('Content-Type: application/json');
        echo json_encode($returnResponse);
        return json_encode($returnResponse);
    }

    /**
     * It gets the return array and it encapsulates into the json_encode. The
     * right way of json structure is, array(success=>1|0 responseData=>
     * result of the controller action or error message). The return data will be
     * encode into the utf8.
     *
     * @param mixed $response
     * @return string
     */
    public function formatResponseBad($response) {
        //$utf8Response = $this->utf8Encode($response);
        $returnResponse = array('success'=>false, 'responseData'=>$response);
        $this->sendHeaders('Content-Type: application/json');
        echo json_encode($returnResponse);
        return json_encode($returnResponse);
    }

    /**
     * Send headers if is possible.
     *
     * @param string $header
     * @return boolean
     */
    private function sendHeaders($header) {
        if(!headers_sent()) {
            header($header);
            return true;
        }
        return false;
    }

}


<?php

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

namespace Mmf\View;

/**
 * The BasicViewInterface is the mvc component in charge of making the views,
 * and do all the stuff relation with that.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
abstract class BasicViewAbstract implements BasicViewInterface {

    /**
     * Configuration object.
     *
     * @var ParametersInterface
     */
    public $config;

    /**
     * List of vars that we will include into the view.
     *
     * @var array
     */
    public $viewVars = array();

    /**
     * String var with the name of template to be use.
     *
     * @var string
     */
    public $template = null;

    /**
     * String var with the root path of the view folder.
     *
     * @var string
     */
    public $viewsFolder = '';

    /**
     * String var with the styles path.
     *
     * @var string
     */
    public $styles = '';

    /**
     * String var with the scripts path.
     *
     * @var string
     */
    public $scripts = '';

    /**
     * The view content.
     *
     * @var string
     */
    public $contentView = '';

    /**
     * Script vars to include in the JS.
     *
     * @var string
     */
    public $scriptVars = '';

    /**
     *
     * @param \Mmf\Parameter\ParametersInterface $config
     */
    public function __construct(\Mmf\Parameter\ParametersInterface $config) {
        $this->config = $config;
        $this->viewsFolder = $this->config->get('URLBase') . $this->config->get('mvc')['viewFolder'];
    }

    /**
     * Include Vars to the view.
     *
     * @param string $name
     * @param mixed $value
     */
    public function addVar($name, $value) {
        $this->viewVars[$name] = $value;
    }

    /**
     * Get the view render as string.
     *
     * @param string $name path name to the view.
     * @param string $template name of the template used for this view in case
     * to be the last one to be output.
     * @param mixed $vars vars to include into the view.
     * @param mixed $globalScriptVars global scripts included in the view.
     * @return BasicViewInterface
     */
    public function get($name, $template = '', $vars = array(), $globalScriptVars = '') {
        if ($template !== '') {
            $this->setTemplate($template);
        }
        //Creation the full path of the view
        $path = $this->viewsFolder . '/html/' . $name;
        //If exists vars to assign, we assing one by one.
        $viewVars = (count($vars) > 0) ? $vars : $this->viewVars;

        //Include the style if exists some style to include
        if (isset($this->styles)) {
            $vars['styles'] = $this->styles;
        }

        //Finalmente, incluimos la plantilla con las variables de los scripts.
        $this->contentView = $this->getFileContent($path, $viewVars) . $globalScriptVars;
        return $this;
    }

    /**
     * Add a global JS variable to the view
     *
     * @param mixed $vars array(variable_name => value, ...) or simply the
     * variable name. If $value happens to be a number (or something else you
     * don't want to "json_encode()", set $encode = FALSE
     * @param string $value
     * @param bool $encode = TRUE. If we don't want to encode some variable,
     * it is mandatory to add them one by one, under the pattern
     * addJsVar( $varName, $varValue, FALSE )
     * @note remember that if $foo is a string, then json_encode($var) === $var
     */
    public function addJsVar($vars, $value, $encode = false) {
        if (is_array($vars)) {
            foreach ($vars as $key => $value) {
                // if JSONencode it's enable then is because it doesn't want json_encode.
                $this->addJsVar($key, $value);
            }
        } else { // apply the logic
            $this->scriptVars = $this->scriptVars . "var $vars = " . ($encode ? json_encode($value) : $value) . ";";
        }
    }

    /**
     * Add Script into the cue of Script vars.
     *
     * @param string $jsfile
     * @param bool $min
     * @param string $type
     */
    public function addScript($jsfile, $min = FALSE, $type = 'text/javascript') {
        //Check if we must minified the style
        $minTag = "<script type='$type' src='min/?f=" . $this->asset($jsfile, TRUE) . "' ></script>";
        $maxTag = "<script type='$type' src='" . $this->asset($jsfile, TRUE) . "' ></script>";

        //TODO: min files
        $includeTag = $maxTag;

        $minPos = strpos($this->scripts, $minTag);
        $maxPos = strpos($this->scripts, $maxTag);

        if ($minPos === FALSE && $maxPos === FALSE) {  // Si no esta, concatenamos
            $this->scripts .= $includeTag;
        }
    }

    /**
     * Add Style into the cue of style vars.
     *
     * @param string $cssfile
     * @param bool $min
     */
    public function addStyles($cssfile, $min = FALSE) {
        //Check if we must minified the style
        $minTag = "<link href='min/?f=" . $this->asset($cssfile, TRUE) . "' rel='stylesheet' type='text/css'/>";
        $maxTag = "<link href='" . $this->asset($cssfile, TRUE) . "' rel='stylesheet' type='text/css'/>";

        //TODO: min styles
        $includeTag = $maxTag;

        $minPos = strpos($this->styles, $minTag);
        $maxPos = strpos($this->styles, $maxTag);

        //If it doesn't exist, we concat with the actual styles
        if ($minPos === FALSE && $maxPos === FALSE) {
            $value = $this->styles . $includeTag;
            $this->styles = $value;
        }
    }

    /**
     * Set the template to use for the returned view.
     *
     * @param string $template
     */
    public function setTemplate($template) {
        $this->template = $template;
    }

    /**
     * Get the content of the view with the template vars replace it.
     *
     * @param string $path
     * @param array  $vars
     *
     * @return string
     */
    protected function getFileContent($path, $vars = array()) {

        //If there is vars to assign.
        if (is_array($vars)) {
            foreach ($vars as $key => $value) {
                /* @var $value BasicViewInterface */
                //If is a view, get the content of the view.
                if (is_object($value) && is_a($value, '\Mmf\View\BasicViewInterface')) {
                    $$key = $value->getContentView();
                } else {
                    $$key = $value;
                }
            }
        }
        ob_start();
        /** @noinspection PhpIncludeInspection */
        include($path);
        $output = ob_get_clean();
        return $output;
    }

    /**
     * Get the view content but included into a template.
     *
     * @return string
     * @throws Exception
     */
    public function getContentWithTemplate() {
        $vars = $this->viewVars;
        //If there is vars to assign.
        if (is_array($vars)) {
            foreach ($vars as $key => $value) {
                /* @var $value BasicViewInterface */
                //If is a view, get the content of the view.
                if (is_object($value) && is_a($value, '\Mmf\View\BasicViewInterface')) {
                    $$key = $value->getContentView();
                } else {
                    $$key = $value;
                }
            }
        }

        $content = $this->getContentView();
        if ($this->template == "") {
            $output = $content;
        } else {
            $scripts = '';
            if (strlen($this->scriptVars) > 0) {
                $scripts = "<script>/* Global Vars */".$this->scriptVars."</script>";
            }
            $styles = $this->getAllCss();
            $scripts .= $this->getAllScripts();
            ob_start();
            $path = $this->viewsFolder . '/template/' . $this->template;

            if (file_exists($path)) {
                /** @noinspection PhpIncludeInspection */
                include ($path);
            } else {
                $output = ob_get_clean();
                throw new \Exception('Template does not exists', 1502);
            }

            $output = ob_get_clean();
        }
        return $output;
    }

    /**
     * Get all the scripts, included the default scripts defined in the config
     * file.
     *
     * @return string with the dinamic and default scripts
     */
    public function getAllScripts() {
        $return = '';
        foreach ($this->config->get('mvc')['defaultScripts'] as $script) {
            //If the script includes the // is for example http or https absolute route
            if (strpos($script, '//') !== FALSE) {
                $return .= '<script type="text/javascript" src="' . $script . '"></script>';
            } else {
                $return .= '<script type="text/javascript" src="' . $this->asset($script, TRUE) . '"></script>';
            }
        }
        $return .= $this->scripts;
        return $return;
    }

    /**
     * Get all the styles.
     * file.
     *
     * @return string with the dinamic and default scripts
     */
    public function getAllCss() {
        $return = '';
        foreach ($this->config->get('mvc')['defaultCSS'] as $script) {
            //If the script includes the // is for example http or https absolute route
            if (strpos($script, '//') !== FALSE) {
                $return .= "<link href='" . $script . "' rel='stylesheet' type='text/css'/>";
            } else {
                $return .= "<link href='" . $this->asset($script, TRUE) . "' rel='stylesheet' type='text/css'/>";
            }
        }
        $return .= $this->styles;
        return $return;
    }

    /**
     * Return or Echo the install folder.
     *
     * @param string $path path from install path
     * @param bool $return (return=FALSE) if it's true, the result is returned.
     * @return string | void
     */
    public function asset($path = "/", $return = FALSE) {
        $installFolder = $this->config->get('mvc')['installFolder'];
        if (!$return) {
            echo $installFolder . $path;
        }
        return $installFolder . $path;
    }

    /**
     * Return the content view of the view.
     *
     * @return string contentView
     */
    public function getContentView() {
        return $this->contentView;
    }

}


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

namespace Mmf\ACL;

use Mmf\Auth\AuthInterface;
use Mmf\Model\ConnectionInterface;
use Mmf\Language\LanguageInterface;
use Mmf\Routing\RoutingRuleAbstract;

/**
 * The ACL is the class for all Access Control List, available
 * for Mamaframework.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class ACL implements ACLInterface {

    /**
     *
     * @var \Mmf\Auth\AuthInterface
     */
    private $auth;

    /**
     *
     * @var \Mmf\Model\ConnectionInterface
     */
    private $connection;

    /**
     *
     * @var \Mmf\Language\LanguageInterface
     */
    private $language;

    /**
     *
     * @var ACLModel
     */
    private $aclModel;

    /**
     * Id role for the user.
     *
     * @var int
     */
    private $roleId = NULL;

    /**
     * Id role for the user.
     *
     * @var int
     */
    private $roleName = NULL;

    /**
     * Roles given from database.
     *
     * @var array
     */
    private $rolesChain = NULL;

    /**
     * Roles adatped from database to normal form.
     *
     * @var array
     */
    private $access = NULL;

    /**
     * Get the Session and Request Interfaces need to capture the user and
     * determine if is allowed or not.
     *
     * @param \Mmf\Auth\AuthInterface              $auth
     * @param \MmfConnectionInterface | null $connection
     * @param \MmfLanguageInterface   | null $language
     */
    public function __construct(AuthInterface $auth,
            ConnectionInterface $connection = null,
            LanguageInterface $language = null) {
        $this->auth = $auth;
        $this->connection = $connection;
        $this->language = $language;
        $this->aclModel = new ACLModel($connection);
        $this->forceRole($this->auth->getRoleName());
    }

    /**
     * Main Function, used to check if the request have autorization to access
     * into the controller and action required.
     *
     * @param \MmfRoutingRuleAbstract $routingRule
     * @return bool TRUE if the user is allow to execute the routing rule or
     * FALSE if the user is not allowed.
     */
    public function isAllowed(RoutingRuleAbstract $routingRule) {
        $controller = $routingRule->getController();
        if (substr($controller, -10) == "Controller") {
            $controller = substr($controller,0, -10);
        }

        //$function = new \ReflectionClass($routingRule->getController() . 'Controller');
        /*
        var_dump($function->inNamespace());
        var_dump($function->getName());
        var_dump($function->getNamespaceName());
        var_dump($function->getShortName());
         */
        //$controller = str_ireplace("Controller", "", $function->getShortName());

        $action = $routingRule->getAction();
        $access = $this->getAccess();
        $allowed = FALSE;
        if (array_key_exists($controller, $access)) {
            foreach ($access[$controller] as $rule) {
                if ($rule == "*") {
                    $allowed = TRUE;
                } else {
                    if ($allowed) { //After general acceptation like * can be an exception
                        $negation = FALSE;
                        if ($rule[0] == "!") {
                            $negation = TRUE;
                            $rule = substr($rule, 1);
                        }

                        if ($negation) { //By the moment is allowed but maybe there is an exception rule
                            if ($rule == $action) {
                                $allowed = FALSE;
                            }
                        }
                    } else {
                        if ($rule == $action) {
                            $allowed = TRUE;
                        }
                    }
                }
            }
        }
        return $allowed;
    }

    private function forceRole($name = "guest") {
        $role = $this->aclModel->getConcreteRole($name);
        if ($role === false) {
            throw new ACLException("Role name doesn't exist in database", 1700);
        }
        $this->roleId = $role['id_role'];
        $this->roleName = $role['name'];
    }

    /**
     * Return a normal access array.
     *
     * @return array
     */
    private function getAccess() {
        if (is_null($this->access)) {
            $chain = $this->getRolesChain();
            $tmpAccess = array();

            foreach ($chain as $role) {
                $arrAccess = $this->aclModel->getAccessForARole($role['id_role']);
                foreach ($arrAccess as $accessItem) {
                    $tmpAccess[$accessItem['controller']] = explode("|",
                            $accessItem['rules']);
                }
            }
            $this->access = $tmpAccess;
            return $this->access;
        } else {
            return $this->access;
        }
    }

    /**
     * Get the list of roles chain. For example, if admin have user as parent
     * role, it returns the admin and user role.
     *
     * @return array
     */
    private function getRolesChain() {
        if (is_null($this->rolesChain)) {
            $chain = array();
            $role = $this->aclModel->getRoleById($this->roleId);
            while ($role != FALSE) {
                $chain[] = $role;
                $currId = $role['id_parent'];
                $role = $this->aclModel->getRoleById($currId);
            }

            $this->rolesChain = array_reverse($chain);
        }
        return $this->rolesChain;
    }

}


<?php

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

namespace Mmf\Language;

use \Mmf\Model\MySQLModelAbstract;
/**
 * The LanguageModel, check the default user language.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class LanguageModel extends MySQLModelAbstract{

    /**
     * Return the user language properties.
     *
     * @param int $userId
     * @return boolean
     */
    public function getUserLanguage($userId) {
        $sql = 'SELECT language.id_language,
                       language.name,
                       language.code,
                       language.default
                FROM user
                INNER JOIN language ON language.id_language = user.id_language
                WHERE user.id_user=\''.$userId.'\'';

        $language = $this->select($sql);
        if (count($language)>0) {
            return $language[0];
        } else {
            return false;
        }
    }
}


<?php

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

namespace Mmf\Language;

/**
 * The Translator is the interface used for all the classes that want to
 * implement the logic of the translation in PHP.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class Translator implements TranslatorInterface  {

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

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

    /**
     * @var array
     */
    protected $translations;

    /**
     * Construct.
     *
     * @param string $locale The locale
     * @param string $translatePath The path to the translation scripts
     */
    public function __construct($locale, $translatePath) {
        $this->translatePath = $translatePath;
        $this->setLocale($locale); //Set the default locale
        $this->getTranslation($locale); //Get the translation of the default
    }

    /**
     * Translates the given message.
     *
     * @param string      $id         The message id (may also be an object that can be cast to string)
     * @param array       $parameters An array of parameters for the message
     * @param string|null $locale     The locale or null to use the default
     *
     * @throws \InvalidArgumentException If the locale contains invalid characters
     *
     * @return string The translated string
     */
    public function translate($id, array $parameters = array(), $locale = null) {
        if (null === $locale) {
            $locale = $this->getLocale();
        } else {
            $this->assertValidLocale($locale);
        }
        //Get the translations
        $translations = $this->getTranslation($locale);

        //Calculate the translation and replace the parameters
        return strtr($this->getTranslationForId($id, $translations), $parameters);
    }

    /**
     * Translates the given choice message by choosing a translation according to a number.
     *
     * @param string      $id         The message id (may also be an object that can be cast to string)
     * @param int         $number     The number to use to find the indice of the message
     * @param array       $parameters An array of parameters for the message
     * @param string|null $locale     The locale or null to use the default
     *
     * @throws \InvalidArgumentException If the locale contains invalid characters
     *
     * @return string The translated string
     */
    public function translateChoice($id, $number, array $parameters = array(), $locale = null) {
        if (null === $locale) {
            $locale = $this->getLocale();
        } else {
            $this->assertValidLocale($locale);
        }
        //Get the translations
        $translations = $this->getTranslation($locale);

        //Calculate the translation and replace the parameters
        return strtr($this->getTranslationForId($id, $translations, $number), $parameters);
    }

    /**
     * Sets the current locale.
     *
     * @param string $locale The locale
     *
     * @throws \InvalidArgumentException If the locale contains invalid characters
     */
    public function setLocale($locale) {
        $this->assertValidLocale($locale);
        $this->locale = $locale;

    }

    /**
     * Returns the current locale.
     *
     * @return string The locale
     */
    public function getLocale() {
        return $this->locale;
    }

    /**
     * Returns the list of translations.
     *
     * @param string $locale
     * @return array|null
     */
    public function getTranslation($locale) {
        if (!isset($this->translations[$locale])) {
            $this->translations[$locale] = $this->getFileTranslations($locale, $this->translatePath);
        }
        return $this->translations[$locale];
    }

    /**
     * Asserts that the locale is valid, throws an Exception if not.
     *
     * @param string $locale Locale to tests
     *
     * @throws \InvalidArgumentException If the locale contains invalid characters
     */
    protected function assertValidLocale($locale) {
        if (1 !== preg_match('/^[a-z]{3,3}$/i', $locale)) {
            throw new \InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
        }
    }

    /**
     * Get the translation array.
     *
     * @param string $locale
     * @param string $translatePath
     *
     * @throws \InvalidArgumentException
     *
     * @returns array of translations
     */
    protected function getFileTranslations($locale, $translatePath) {
        $fileToInclude = $translatePath.$locale.'.php';
        if (file_exists($fileToInclude)) {
            /** @noinspection PhpIncludeInspection */
            require $fileToInclude;
            return $translation;
        }  else {
            throw new \InvalidArgumentException('Invalid path file');
        }
    }

    /**
     * Get the translation.
     *
     * @param string  $id
     * @param array   $translationArray
     * @param int     $number
     *
     * @throws TranslateException
     *
     * @return string translation
     */
    protected function getTranslationForId($id, $translationArray, $number = 0) {
        $translation = '';
        if(isset($translationArray[$id])) { //Id all join
            $translation = $this->getBasicTranslationForId($translationArray[$id], $number);
        } else { //Id separataly
            $arrayOfIds = explode(' ', $id);
            $constructTranslateArray = $translationArray;
            foreach ($arrayOfIds as $subId) {
                if(!isset($constructTranslateArray[$subId])) {
                    throw new TranslateException('Translation id not exists.('.$id.')');
                }
                $constructTranslateArray = $constructTranslateArray[$subId];

            }
            $translation = $this->getBasicTranslationForId($constructTranslateArray, $number);
        }
        //Return the string translate with the parameters include into the placeholders
        return $translation;
    }

    /**
     * Calculate the basic translation.
     *
     * @param mixed  $translationId
     * @param int     $number
     *
     * @throws TranslateException
     *
     * @return string
     */
    private function getBasicTranslationForId($translationId, $number) {
        if(is_array($translationId) //Is array and we get the translate given for number array
            && isset($translationId[$number])
            && is_string($translationId[$number])) {
             $translation = $translationId[$number];
         } else if (is_string($translationId)) { //Is string directly
             $translation = $translationId;
         }
         return $translation;
    }
}