<?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     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\EventListener;

use ContaoCommunityAlliance\DcGeneral\Contao\DataDefinition\Definition\Contao2BackendViewDefinition;
use ContaoCommunityAlliance\DcGeneral\Contao\DataDefinition\Definition\Contao2BackendViewDefinitionInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Definition\View\CommandCollectionInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Definition\View\TranslatedToggleCommand;
use MetaModels\Attribute\IAttribute;
use MetaModels\AttributeTranslatedCheckboxBundle\Attribute\TranslatedCheckbox;
use MetaModels\DcGeneral\Events\MetaModel\BuildMetaModelOperationsEvent;

/**
 * This class creates the default instances for property conditions when generating input screens.
 */
class BuildMetaModelOperationsListener
{

    /**
     * Generate the toggle command information.
     *
     * @param CommandCollectionInterface $commands    The already existing commands.
     *
     * @param IAttribute                 $attribute   The attribute.
     *
     * @param string                     $commandName The name of the new command.
     *
     * @param string                     $class       The name of the CSS class for the command.
     *
     * @param string                     $language    The language name.
     *
     * @return void
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     * @SuppressWarnings(PHPMD.CamelCaseVariableName)
     */
    protected function generateToggleCommand($commands, $attribute, $commandName, $class, $language)
    {
        if (!$commands->hasCommandNamed($commandName)) {
            $toggle = new TranslatedToggleCommand();
            $toggle
                ->setLanguage($language)
                ->setToggleProperty($attribute->getColName())
                ->setName($commandName)
                ->setLabel($GLOBALS['TL_LANG']['MSC']['metamodelattribute_translatedcheckbox']['toggle'][0])
                ->setDescription(
                    \sprintf(
                        $GLOBALS['TL_LANG']['MSC']['metamodelattribute_translatedcheckbox']['toggle'][1],
                        $attribute->getName(),
                        $language
                    )
                );

            $extra          = $toggle->getExtra();
            $extra['icon']  = 'visible.svg';
            $extra['class'] = $class;

            if ($commands->hasCommandNamed('show')) {
                $info = $commands->getCommandNamed('show');
            } else {
                $info = null;
            }
            $commands->addCommand($toggle, $info);
        }
    }

    /**
     * Build a attribute toggle operation for all languages of the MetaModel.
     *
     * @param TranslatedCheckbox         $attribute The checkbox attribute.
     *
     * @param CommandCollectionInterface $commands  The already existing commands.
     *
     * @return void
     */
    protected function buildCommandsFor($attribute, $commands)
    {
        $activeLanguage = $attribute->getMetaModel()->getActiveLanguage();
        $commandName    = 'publishtranslatedcheckboxtoggle_' . $attribute->getColName();

        $this->generateToggleCommand(
            $commands,
            $attribute,
            $commandName . '_' . $activeLanguage,
            'contextmenu',
            $activeLanguage
        );

        foreach (\array_diff($attribute->getMetaModel()->getAvailableLanguages(), [$activeLanguage]) as $langCode) {
            $this->generateToggleCommand(
                $commands,
                $attribute,
                $commandName . '_' . $langCode,
                'edit-header',
                $langCode
            );
        }
    }

    /**
     * Create the property conditions.
     *
     * @param BuildMetaModelOperationsEvent $event The event.
     *
     * @return void
     *
     * @throws \RuntimeException When no MetaModel is attached to the event or any other important information could
     *                           not be retrieved.
     */
    public function handle(BuildMetaModelOperationsEvent $event)
    {
        foreach ($event->getMetaModel()->getAttributes() as $attribute) {
            if (($attribute instanceof TranslatedCheckbox) && ($attribute->get('check_publish') == 1)) {
                $container = $event->getContainer();
                if ($container->hasDefinition(Contao2BackendViewDefinitionInterface::NAME)) {
                    $view = $container->getDefinition(Contao2BackendViewDefinitionInterface::NAME);
                } else {
                    $view = new Contao2BackendViewDefinition();
                    $container->setDefinition(Contao2BackendViewDefinitionInterface::NAME, $view);
                }
                $this->buildCommandsFor($attribute, $view->getModelCommands());
            }
        }
    }
}


<?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\Controller;

use \Mmf\Routing\RoutingException;

/**
 * Is the controller in charge of instantiate all the controllers, init
 * the basic configuration and call the method of controller that will respond
 * to the request.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class FrontController {

    /**
     * @var \AutoloaderInterface
     */
    protected $autoload;

    /**
     * @var \ParametersInterface
     */
    protected $config;

    /**
     * @var PluginManagerInterface
     */
    protected $pluginManager;

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

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

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

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

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

    /**
     * @var ErrorController
     */
    protected $errorController;

    /**
     * @var RoutingResolverAbstract
     */
    protected $routingResolver;

    /**
     * @var RoutingRuleAbstract
     */
    protected $routingRule;

    /**
     * @var CommunicationInterface
     */
    protected $communication;

    /**
     * @var ACLInterface
     */
    protected $acl;

    /**
     * @var BasicViewInterface
     */
    protected $view;

    /**
     * @var LanguageInterface
     */
    protected $language;

    /**
     *
     * @var SessionFactory
     */
    protected $sessionFactory;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var ConnectionInterface
     */
    protected $connection;

    /**
     * @var AuthInterface
     */
    protected $auth;

    /**
     * @var BasicControllerAbstract
     */
    private $controller;

    /**
     * @var CoreInterface
     */
    private $core;
    public $executionErrors = 0;
    public $messageErrors = '';
    public $traceRouteErrors = '';

    public function __construct(
        \Mmf\Autoloader\AutoloaderInterface $autoload,
        \Mmf\Parameter\ParametersInterface $config,
        \Mmf\IO\CommunicationInterface $communication
    ) {
        $this->autoload = $autoload;
        $this->config = $config;
        $this->communication = $communication;
    }

    /**
     * Is the function to start the Framework. Is usually call in index .
     *
     * @throws Exception
     */
    public function main() {
        $this->config->set('URLBase', $this->autoload->getURLBase());

        $this->setAndAppLibraries(); //Load All library paths, not include in try because ErrorController is not present.
        $this->loadAppFilesystem(); //Include the app filesystem structure into the loader path.

        $this->errorController = $this->getLibraryInstance('mvc', 'errorClass'); //Create error controller.
        //TODO log
        try {

            return $this->createMVCAction(); //Load Event, Plugin, Language, Routing, Auth, ACL, View, and controllers.
        } catch (ControllerException $e) { //Catch the false response from controller, not catch the problem errors.
            return $this->routingRule->getOutput()->formatResponseBad(['errorCode' => $e->getCode(),
                        'errorMessage' => $e->getMessage()]);
        } catch (RoutingException $e) { //Catch the routing not resolve.
            $respAutoClass = $this->getLibraryInstance('io', 'respAutoClass', $this->config);
            /* @var $respAutoClass ResponseInterface */
            return $respAutoClass->formatResponseBad(['errorCode' => $e->getCode(),
                        'errorMessage' => 'The URL not match with any of our defined routes']);
            //TODO translate all the texts
        } catch (Exception $e) { //Catch the All other frameworks exceptions.
            $respAutoClass = $this->getLibraryInstance('io', 'respAutoClass', $this->config);
            /* @var $respAutoClass ResponseInterface */
            return $respAutoClass->formatResponseBad(['errorCode' => $e->getCode(),
                        'errorMessage' => $e->getMessage()]);
        } catch (\Exception $e) { //Catch not controlled errors
            $this->executionErrors = 1;
            $this->messageErrors = 'File:' . $e->getFile() . ' File line:' . $e->getLine() . ', Message:' . $e->getMessage() . ', Traceroute:' . $e->getTraceAsString();
            $this->traceRouteErrors = $e->getTrace();
            $this->errorController->displayError(500);

            $respAutoClass = $this->getLibraryInstance('io', 'respAutoClass', $this->config);
            /* @var $respAutoClass ResponseInterface */
            return $respAutoClass->formatResponseBad(['errorCode' => $e->getCode(),
                        'errorMessage' => 'Internal Server Error']);
        }
    }

    /**
     * @throws ControllerException
     * @throws Exception
     * @throws Exception
     *
     * @return mixed controller->action return
     */
    protected function createMVCAction() {
        //Start new session
        $this->sessionFactory = $this->getLibraryInstance('session', 'sessionClass');
        $this->session = $this->sessionFactory->createSession();

        //Activate Event if the library it's included
        $this->activateEvent();

        //Create connection
        //TODO check, how to get the none connection bd class
        $this->connection = $this->getLibraryInstance('mvc', 'connectionClass', $this->config);

        //Create the translate object and translate the route input.
        //TODO Create Language and translate URL CLASS
        $this->language = $this->getLibraryInstance('language', 'languageClass', $this->communication, $this->config, $this->connection);

        //Activate the communication
        //$this->communication   = $this->getLibraryInstance('io', 'chanelClass');
        //Activate Routing
        $this->routingResolver = $this->getLibraryInstance('routing', 'routingClass', $this->communication, $this->language);

        //Start plugin managment & load install plugins if the library it's included
        //$this->activatePlugin();
        //Dispatch Core read event in case of Event library is included
        //$this->dispatchCoreReady(array());
        //Create SEO class and redirect the http request if is need.
        //TODO Create SEO CLASS
        //Execute Resolution of route, if is no possible to resolve RoutingException is throw
        $this->executeResolveRoute();

        //Execute Auth system, if the user is not authenticate a ControllerException is throw
        $this->executeAuth();

        //Execute the ACL system, if the user is not allowed ControllerException is throw
        $this->executeACL();
        //Up view, create core, create controller and execute action
        return $this->prepareAndCreateControllerAction();
    }

    /**
     * This method will create the view, the core and controller and
     * execute the action.
     *
     * @return mixed controller->action return
     */
    protected function prepareAndCreateControllerAction() {
        //Create the view controller
        $this->view = $this->getLibraryInstance('mvc', 'viewClass', $this->config);

        //Create the controller with the core.
        $controller = $this->createCoreAndController(
                $this->routingRule->getController() . 'Controller',
                $this->eventManager,
                $this->routingRule->getInput(),
                $this->routingRule->getOutput(),
                $this->view,
                $this->language,
                $this->routingResolver,
                $this->errorController,
                $this->session,
                $this->connection,
                $this->auth
        );

        //Execute the controller action with the parameters.
        $actionReturn = $this->callClassAndMethodWithInputArguments($controller, $this->routingRule->getAction(), $this->routingRule->getInput());

        //Format the response
        return $this->routingRule->getOutput()->formatResponse($actionReturn);
    }

    /**
     * Execute the Access Control List, throws and ControllerException if is not allowed.
     *
     * @throws ControllerException
     */
    protected function executeACL() {
        //Create the ACL
        $this->acl = $this->getLibraryInstance('acl', 'aclClass', $this->auth, $this->connection, $this->language);
        $isAllowed = $this->acl->isAllowed($this->routingRule);

        //Check if is allow to create the controller and call the action
        if (!$isAllowed) {
            throw new ControllerException('User not allow to access', 1500);
        }
    }

    /**
     * Execute the Authentication system, throws and ControllerException if
     * the session is not longer valid.
     *
     * @throws ControllerException
     */
    protected function executeAuth() {
        //Create Auth controller
        $this->auth = $this->getLibraryInstance('auth', 'authClass', $this->session, $this->routingRule->getInput(), $this->connection, $this->config, $this->language);
    }

    /**
     * Resolve the route.
     *
     * @throws \RoutingException when no route is matching
     */
    protected function executeResolveRoute() {
        //Add bulk routes
        $routingIniFile = $this->autoload->getURLBase() . $this->config->get('routing')['bulkRoutePath'];
        $this->routingResolver->addBulkRoutes($routingIniFile);

        //Resolve route
        $this->routingRule = $this->routingResolver->resolve();
    }

    /**
     * Set the libraries from the config and set the structure from the config
     * file.
     */
    private function setAndAppLibraries() {
        //Get the  libraries and application libraries
        $this->appLibraries = $this->config->get('app')['paths'];

        //Get the Structure
        $this->Structure = $this->config->get('Structure')['filesystem'];

        //Set to Autoloader the internal Structure
        $this->autoload->setStructure($this->Structure);
    }

    /**
     * Load the App file system.
     */
    protected function loadAppFilesystem() {
        foreach ($this->appLibraries as $value) {
            $this->autoload->addNewMmfAutoloadPath($value);
        }
    }

    /**
     * Activate Event System if is configure.
     */
    private function activateEvent() {
        //Init Event Manager
        $this->eventManager = $this->getLibraryInstance('event', 'eventClass');
    }

    /**
     * Return the instance of the library class.
     *
     * @param string $libraryName
     * @param string $libraryClass
     *
     * @throws \InvalidArgumentException
     *
     * @return stdClass | null $libraryClass
     */
    private function getLibraryInstance($libraryName, $libraryClass) {
        $instance = null;
            $libraryClassName = $this->config->get($libraryName)[$libraryClass];
            if (class_exists($libraryClassName)) {
                if (count(func_get_args()) > 2) {
                    $arguments = array_slice(func_get_args(), 2, count(func_get_args()) - 2);
                    $ref = new \ReflectionClass($libraryClassName);
                    $instance = $ref->newInstanceArgs($arguments);
                    //$instance = new $libraryClassName(array_slice(func_get_args(), 2, count(func_get_args())-2));
                } else {
                    $instance = new $libraryClassName();
                }
                return $instance;
            } else {
                throw new \InvalidArgumentException('Invalid library class(' . $libraryClassName . ')');
            }
        throw new \InvalidArgumentException('We can not instantiate the library class (' . $libraryClassName . ')');
    }

    /**
     * Creates the Concret controller with the constructor parameters and
     *
     * @param                              $class
     * @param \PluginManagerInterface   $pluginManager
     * @param \EventManagerInterface    $eventManager
     * @param \RequestInterface         $request
     * @param \ResponseInterface        $response
     * @param \BasicViewInterface       $view
     * @param \LanguageInterface        $language
     * @param \RoutingResolverAbstract  $router
     * @param \ErrorControllerInterface $error
     * @param \SessionInterface         $session
     * @param \ConnectionInterface      $connection
     * @param \AuthInterface            $auth
     *
     * @return mixed
     * @throws \CoreException
     */
    public function createCoreAndController(
        $class,
        \Mmf\Event\EventManagerInterface $eventManager,
        \Mmf\IO\RequestInterface $request,
        \Mmf\IO\ResponseInterface $response,
        \Mmf\View\BasicViewInterface $view,
        \Mmf\Language\LanguageInterface $language,
        \Mmf\Routing\RoutingResolverAbstract $router,
        ErrorControllerInterface $error,
        \Mmf\Parameter\SessionInterface $session,
        \Mmf\Model\ConnectionInterface $connection,
        \Mmf\Auth\AuthInterface $auth
    ) {
        $coreClass = $this->config->get('mvc')['coreClass'];

        if (class_exists($class) && class_exists($coreClass)) {
            $this->core = new $coreClass(
                $this->autoload,
                $this->config,
                $eventManager,
                $request,
                $response,
                $view,
                $language,
                $router,
                $error,
                $session,
                $connection,
                $auth
            );

            $this->controller = new $class($this->core);
            return $this->controller;
        } else {
            $className = is_object($class) ? get_class($class) : $class;
            throw new \Mmf\Core\CoreException('Is not unable to create the controller'
            . ' (' . $className . '), check if the path is correct and if '
            . 'exists the controller or if The CoreClass is correct (' . $coreClass . ')');
        }
    }

    /**
     * Call a class and a method trying to pass the method recive in the request.
     * If the request doesn't have the parameters, it is set to false.
     *
     * @param string | object      $class to call the method
     * @param string               $method to be call
     * @param \RequestInterface $request
     *
     * @return mixed
     *
     * @throws \ControllerException
     * @throws \CoreException
     */
    public function callClassAndMethodWithInputArguments(
        $class,
        $method,
        \Mmf\IO\RequestInterface $request
    ) {
        $params = $this->getFunctionArguments($class, $method);

        $listOfParams = [];
        foreach ($params as $param) {
            $paramValue = $request->input($param['name']);
            if ($paramValue === null && $param['isOptional'] === false) {
                throw new ControllerException('The param ' . $param['name'] . ' is mandatory', 1501);
            } elseif ($paramValue === null && $param['isOptional'] === true) {
                $paramValue = $param['initialValue'];
            }
            $listOfParams[] = $paramValue;
        }
        if (!is_object($class)) {
            $class = new $class();
        }
        $returnOfAction = call_user_func_array(array($class, $method), $listOfParams);
        if ($returnOfAction !== false) {
            return $returnOfAction;
        } else {
            throw new \Mmf\Core\CoreException('FrontController::callClassAndMethodWithInputArguments'
            . ', Is not unable to call the action (' . $method . ') with '
            . 'the parameters(' . print_r($listOfParams, true) . '), the expected name of parameters are'
            . '(' . print_r($params, true) . ')');
        }
    }

    /**
     * This function returns the arguments of the method in class send it in the
     * parameters.
     *
     * @param string | object $class
     * @param string $method
     * @return array of parameters <'name', 'isOptional', 'initialValue'>
     */
    public function getFunctionArguments($class, $method) {

        $ReflectionMethod = new \ReflectionMethod($class, $method);

        $paramsArray = array();
        foreach ($ReflectionMethod->getParameters() as $param) {
            $auxParam = array('name' => $param->getName(), 'isOptional' => false, 'initialValue' => null);
            if ($param->isOptional()) {
                $auxParam['isOptional'] = true;
                $auxParam['initialValue'] = $param->getDefaultValue();
            }
            $paramsArray[] = $auxParam;
        }
        return $paramsArray;
    }

}


<?php

namespace Kitpages\CmsBundle\Model;

// external service
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\Event;

use Kitpages\FileBundle\Model\FileManager;
use Kitpages\CmsBundle\KitpagesCmsEvents;
use Kitpages\FileBundle\Entity\File;
use Kitpages\FileBundle\Entity\FileInterface;

class CmsFileManager {

    ////
    // dependency injection
    ////
    protected $dispatcher = null;
    protected $doctrine = null;
    protected $fileManager = null;
    protected $itemClassBlock = null;

    public function __construct(Registry $doctrine, EventDispatcherInterface $dispatcher, FileManager $fileManager) {
        $this->dispatcher = $dispatcher;
        $this->doctrine = $doctrine;
        $this->fileManager = $fileManager;
        $this->itemClassBlock = 'KitpagesCmsBundle:Block';
        $this->itemClassPage = 'KitpagesCmsBundle:Page';
    }

    /**
     * @return $fileManager
     */
    public function getFileManager() {
        return $this->fileManager;
    }

    /**
     * @return $itemClassPage
     */
    public function getItemClassPage() {
        return $this->itemClassPage;
    }

    /**
     * @return $itemClassBlock
     */
    public function getItemClassBlock() {
        return $this->itemClassBlock;
    }

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

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

    ////
    // action function
    ////

    public function publishDataMediaList($data) {
        $fileManager = $this->getFileManager();
        $em = $this->getDoctrine()->getManager();
        if (count($data)>0 ) {
            foreach($data as $field => $value) {
                if (substr($field, '0', '6') == 'media_') {
                    foreach($this->valueMedia($value) as $idMedia) {
                        $file = $em->getRepository('KitpagesFileBundle:File')->find($idMedia);
                        if ($file != null) {
                            $fileManager->publish($file);
                        }
                    }
                }
            }
        }
    }

    public function delete($data) {
        $fileManager = $this->getFileManager();
        $em = $this->getDoctrine()->getManager();
        if (count($data)>0 ) {
            foreach($data as $field => $value) {
                if (substr($field, '0', '6') == 'media_') {
                    foreach($this->valueMedia($value) as $indexMedia => $idMedia) {
                        $file = $em->getRepository('KitpagesFileBundle:File')->find($idMedia);
                        if ($file != null) {
                            $fileManager->delete($file);
                        }
                    }
                }
            }
        }
    }

    public function unpublishFileList($mediaList)
    {
        $em = $this->getDoctrine()->getManager();
        $repositoryFileBundle = $em->getRepository('KitpagesFileBundle:File');
        $fileManager = $this->getFileManager();
        foreach($mediaList as $media) {
            foreach($media as $mediaVersionList) {
                foreach($mediaVersionList as $mediaVersion) {
                    $file = $repositoryFileBundle->find($mediaVersion['id']);
                    // delete file published only if file has been deleted in the database
                    if (!($file instanceof FileInterface)) {
                        $fileManager->unpublish($mediaVersion['filePath'], false);
                        if(isset($mediaVersion['fileList']) && count($mediaVersion['fileList'])>0){
                            foreach($mediaVersion['fileList'] as $fileListInfo) {
                                $fileManager->unpublish($fileListInfo['filePath'], false);
                            }
                        }
                    }
                }
            }
        }
    }

    public function mediaList($data, $publish) {
        $em = $this->getDoctrine()->getManager();
        $listMedia = array();
        if (count($data)>0 ) {
            foreach($data as $field => $value) {
                if (substr($field, '0', '6') == 'media_') {
                    foreach($this->valueMedia($value) as $indexMedia => $idMedia) {
                        $file = $em->getRepository('KitpagesFileBundle:File')->find($idMedia);
                        if ($file != null && $file instanceof FileInterface) {
                            $mediaInfo = array();

                            $url = $this->mediaUrl($file, $publish);
                            $mediaInfo['default'] = $this->mediaInfo($file, $url);

                            if(method_exists($file,'getParent')){
                                    $fileOriginal = $file->getParent();
                                    if ($fileOriginal instanceof FileInterface) {
                                        $urlOriginal = $this->mediaUrl($fileOriginal, $publish);
                                        $mediaInfo['original'] = $this->mediaInfo(
                                            $fileOriginal,
                                            $urlOriginal,
                                            $file->getPublishParent()
                                        );
                                    } else {
                                        $mediaInfo['original'] = $mediaInfo['default'];
                                    }
                            }

                            $listMedia[substr($field, '6')][$indexMedia] = $mediaInfo;
                        }
                    }
                }
            }
        }
        return $listMedia;
    }

    public function mediaUrl($file, $publish){
        $fileManager = $this->getFileManager();
        if ($publish) {
            $url = $fileManager->getFileLocationPublic($file, false);
        } else {
            $url = $fileManager->getFileLocationPrivate($file->getId());
        }
        return $url;
    }

    public function mediaInfo($file, $url, $isPublished = true) {
        $private = !$isPublished;
        $fileInfo = array(
            'id' => $file->getId(),
            'type' => '',
            'mime' => '',
            'url' => $url,
            'fileName' => $file->getFileName(),
            'isPublished' => $isPublished,
            'filePath' => $this->getFileManager()->getFilePath($file, $private),
            'info' => array()
        );

        if(method_exists($file,'getHtml')){
            $fileInfo['html'] = $file->getHtml();
        }
        if(method_exists($file,'getType')){
            $fileInfo['type'] = $file->getType();
        }
        if(method_exists($file,'getMimeType')){
            $fileInfo['mime'] = $file->getMimeType();
        }
        $fileData = $file->getData();
        if(isset($fileData['info'])){
            $fileInfo['info'] = $fileData['info'];
        }
        return $fileInfo;
    }

    public function validateFile($file, $itemClass, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $file->setStatus(FileInterface::STATUS_VALID);
        $file->setItemClass($itemClass);
        $file->setItemId($id);
        $em->persist($file);
        $em->flush();
    }

    public function validateFileMediaList($data, $itemClass, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $mediaIdList = array();
        if (count($data)>0 ) {
            foreach($data as $field => $value) {
                if (substr($field, '0', '6') == 'media_') {
                    foreach($this->valueMedia($value) as $indexMedia => $idMedia) {
                        $file = $em->getRepository('KitpagesFileBundle:File')->find($idMedia);
                        if ($file != null) {
                            $mediaIdList[$idMedia] = 1;
                            $this->validateFile($file, $itemClass, $id);
                            $fileParent = $file->getParent();
                            if($fileParent instanceof FileInterface) {
                                $mediaIdList[$fileParent->getId()] = 1;
                                $this->validateFile($fileParent, $itemClass, $id);
                            }
                        }
                    }
                }
            }
        }
        return $mediaIdList;
    }
    public function deleteFileMediaList($data, $idNoDeleteList)
    {
        $em = $this->getDoctrine()->getManager();
        if (count($data)>0 ) {
            foreach($data as $field => $value) {
                if (substr($field, '0', '6') == 'media_') {
                    foreach($this->valueMedia($value) as $indexMedia => $idMedia) {
                        if (!isset($idNoDeleteList[$idMedia])) {
                            $file = $em->getRepository('KitpagesFileBundle:File')->find($idMedia);
                            if ($file != null) {
                                $fileParent = $file->getParent();
                                if($fileParent instanceof FileInterface) {
                                    if (!isset($idNoDeleteList[$fileParent->getId()])) {
                                        $this->fileManager->delete($fileParent);
                                    }
                                }
                                $this->fileManager->delete($file);
                            }
                        }
                    }
                }
            }
        }
    }

    public function afterBlockModify(Event $event)
    {
        $block = $event->getBlock();
        $blockData = $block->getData();
        $oldBlockData = $event->getData('oldBlockData');
        $entityId = $block->getId();
        $mediaIdList = array();
        if (isset($blockData['root'])){
            $mediaIdList = $this->validateFileMediaList($blockData['root'], $this->itemClassBlock, $entityId);
        }

        //delete old file with status = Valid
        if (isset($oldBlockData['root'])){
            $this->deleteFileMediaList($oldBlockData['root'], $mediaIdList);
        }
        $this->fileManager->deleteTemp($this->itemClassBlock, $entityId);
    }

    public function afterPageModify(Event $event)
    {
        $page = $event->getPage();
        $pageData = $page->getData();
        $oldPageData = $event->getData('oldPageData');
        $entityId = $page->getId();
        $mediaIdList = array();
        if (isset($pageData['root'])){
            $mediaIdList = $this->validateFileMediaList($pageData['root'], $this->itemClassPage, $entityId);
        }

        //delete old file with status = Valid
        if (isset($oldPageData['root'])){
            $this->deleteFileMediaList($oldPageData['root'], $mediaIdList);
        }
        $this->fileManager->deleteTemp($this->itemClassPage, $entityId);
    }

    public function valueMedia($value)
    {
        if (!is_array($value)) {
            if ($value == null)
            {
                return array();
            }
            return array($value);
        }  else {
            return $value;
        }
    }

}


<?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;

use \Mmf\Model\MySQLModelAbstract;
/**
 * The AuthModel.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class AuthModel extends MySQLModelAbstract{

    /**
     * Return the role and user attributes from the given token.
     *
     * @param string $token
     * @return boolean
     */
    public function getRoleAndUserFromToken($token) {
        $sql = 'SELECT
                    user.username,
                    user.id_user,
                    role.name,
                    role.id_role,
                    role.id_parent,
                    NOW() AS db_date,
                    token.expire
                FROM
                    role
                        INNER JOIN
                    user ON user.id_role = role.id_role
                        INNER JOIN
                    token ON user.id_user = token.id_user
                WHERE token.token="'.$token.'"
                 ';
        $role = $this->select($sql);
        if(is_array($role) && count($role)>0) {
            return $role[0];
        } else {
            return false;
        }
    }

    /**
     * @param string $token
     * @param string $expireDate
     *
     * @return bool
     */
    public function updateExpireDate($token, $expireDate) {
        $sql = 'UPDATE `token`
                SET
                `expire` = "'.$expireDate.'"
                WHERE `token` = "'.$token.'";';
        $updateResult = $this->update($sql);
        if ($updateResult>0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @param string $username
     * @param string $password
     * @return boolean
     */
    public function getRoleAndUserFromUsernamePassword($username, $password) {
        $sql = 'SELECT
                    user.username,
                    user.id_user,
                    role.name,
                    role.id_role,
                    role.id_parent,
                    NOW() AS db_date
                FROM
                    role
                        INNER JOIN
                    user ON user.id_role = role.id_role
                WHERE user.username="'.$username.'"
                    AND user.password="'.$password.'"
                 ';
        $role = $this->select($sql);
        if(is_array($role) && count($role)>0) {
            return $role[0];
        } else {
            return false;
        }
    }

    /**
     * Return user information given id user.
     *
     * @param int $userId
     *
     * @return array
     */
    public function getRoleAndUserFromIdUser($userId) {
        $sql = 'SELECT
                    user.username,
                    user.id_user,
                    role.name,
                    role.id_role,
                    role.id_parent,
                    NOW() AS db_date
                FROM
                    role
                        INNER JOIN
                    user ON user.id_role = role.id_role
                WHERE user.id_user="'.$userId.'"
                 ';
        $role = $this->select($sql);
        if(is_array($role) && count($role)>0) {
            return $role[0];
        } else {
            return false;
        }
    }
}


<?php
namespace Kitpages\CmsBundle\Model;

use Kitpages\CmsBundle\Entity\Zone;
use Kitpages\CmsBundle\Entity\Block;
use Kitpages\CmsBundle\Entity\ZonePublish;
use Kitpages\CmsBundle\Entity\ZoneBlock;
use Kitpages\CmsBundle\Event\ZoneEvent;
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 Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;

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

    public function __construct(
        Registry $doctrine,
        EventDispatcherInterface $dispatcher,
        $blockManager,
        LoggerInterface $logger
    )
    {
        $this->dispatcher = $dispatcher;
        $this->doctrine = $doctrine;
        $this->blockManager = $blockManager;
        $this->logger = $logger;
    }

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

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

    /**
     * @return $blockManager
     */
    public function getBlockManager() {
        return $this->blockManager;
    }

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

    ////
    // actions
    ////
    public function publish(Zone $zone, array $listRenderer)
    {
        $event = new ZoneEvent($zone, $listRenderer);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onZonePublish, $event);
        if (! $event->isDefaultPrevented()) {
            // publish blocks
            $em = $this->getDoctrine()->getManager();
            foreach($em->getRepository('KitpagesCmsBundle:Block')->findByZone($zone) as $block){
                $this->getBlockManager()->publish($block, $listRenderer[$block->getTemplate()]);
            }
            $em->flush();
            // remove old zonePublish
            $zonePublish = null;
            $query = $em->createQuery("
                SELECT zp FROM KitpagesCmsBundle:ZonePublish zp
                WHERE zp.zone = :zone
            ")->setParameter('zone', $zone);
            $zonePublishList = $query->getResult();
            if (count($zonePublishList) == 1) {
                $zonePublish = $zonePublishList[0];
                $this->deletePublished($zonePublish);
            }

            // create zone publish
            $blockPublishList = array();
            foreach($em->getRepository('KitpagesCmsBundle:BlockPublish')->findByZone($zone) as $blockPublish){
                $blockPublishList[$blockPublish->getRenderer()][] = $blockPublish->getId();
            }
            $zonePublishNew = new ZonePublish();
            $zonePublishNew->initByZone($zone);
            $zonePublishNew->setData(array("blockPublishList"=>$blockPublishList));
            $zone->setIsPublished(true);
            $zone->setZonePublish($zonePublishNew);
            $em->persist($zonePublishNew);
            $em->persist($zone);
            $em->flush();
        }
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterZonePublish, $event);
    }

    public function updateBlockPublishId(Block $block)
    {
        $em = $this->getDoctrine()->getManager();
        // remove old zonePublish
        $zoneList = $em->getRepository('KitpagesCmsBundle:Zone')->findByBlock($block);

        foreach($zoneList as $zone) {
            $em->remove($zone->getZonePublish());
            $em->flush();
           // create zone publish
            $blockPublishList = array();
            $zoneIsPublished = 1;
            foreach($em->getRepository('KitpagesCmsBundle:Block')->findByZone($zone) as $block){
                foreach($block->getBlockPublishList() as $blockPublish) {
                    $blockPublishList[$blockPublish->getRenderer()][] = $blockPublish->getId();
                }
                $isPublished = $block->getIsPublished();
                if (!$isPublished) {
                    $zoneIsPublished = 0;
                }
            }
            $zonePublishNew = new ZonePublish();
            $zonePublishNew->initByZone($zone);
            $zonePublishNew->setData(array("blockPublishList"=>$blockPublishList));
            if ($zoneIsPublished) {
                $zone->setIsPublished(true);
            }
            $zone->setZonePublish($zonePublishNew);
            $em->persist($zonePublishNew);
            $em->persist($zone);
            $em->flush();
        }
    }

    public function unpublish($zone){
        $event = new ZoneEvent($zone);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onZoneUnpublish, $event);
        $em = $this->getDoctrine()->getManager();
        $zone->setIsPublished(false);
        $em->flush();
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterZoneUnpublish, $event);
    }
    public function deletePublished($zonePublish){
        $data = $zonePublish->getData();
        $em = $this->getDoctrine()->getManager();
        foreach ($data['blockPublishList'] as $renderer => $blockPublishList){
            foreach($blockPublishList as $blockPublishId) {
                $blockPublish = $em->getRepository('KitpagesCmsBundle:BlockPublish')->find($blockPublishId);
                if ($blockPublish != null) {
                    $this->getBlockManager()->deletePublished($blockPublish);
                }
            }
        }
        $em->remove($zonePublish);
        $em->flush();
    }
    public function delete(Zone $zone)
    {
        // throw on event
        $event = new ZoneEvent($zone);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onZoneDelete, $event);

        // preventable action
        if (!$event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            $blockManager = $this->getBlockManager();
            foreach($em->getRepository('KitpagesCmsBundle:Block')->findByZone($zone) as $block){
                $nbr = $em->getRepository('KitpagesCmsBundle:ZoneBlock')->nbrZoneBlockByBlockWithZoneDiff($block, $zone);
                if ($nbr == 0) {
                    $blockManager->delete($block);
                }
            }
            $em->remove($zone);
            $em->flush();
        }
        // throw after event
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterZoneDelete, $event);
    }
    public function moveUpBlock(Zone $zone, $block_id)
    {
        $event = new ZoneEvent($zone);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onBlockMove, $event);
        if (!$event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            $zoneBlock = $em->getRepository('KitpagesCmsBundle:ZoneBlock')->findByZoneAndBlock($zone, $block_id);
            $position = $zoneBlock->getPosition()-1;
            if ($position >= 0) {
                $zoneBlock->setPosition($position);
                $em->flush();
            }
            $this->reorderBlockList($zone);
            $this->unpublish($zone);
            $em->flush();
        }
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterBlockMove, $event);
    }
    public function moveDownBlock(Zone $zone, $block_id)
    {
        $event = new ZoneEvent($zone);
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::onBlockMove, $event);
        if (!$event->isDefaultPrevented()) {
            $em = $this->getDoctrine()->getManager();
            $zoneBlock = $em->getRepository('KitpagesCmsBundle:ZoneBlock')->findByZoneAndBlock($zone, $block_id);
            $position = $zoneBlock->getPosition()+1;
            if ($position >= 0) {
                $zoneBlock->setPosition($position);
                $em->flush();
            }
            $this->reorderBlockList($zone);
            $this->unpublish($zone);
        }
        $this->getDispatcher()->dispatch(KitpagesCmsEvents::afterBlockMove, $event);
    }

    public function reorderBlockList(Zone $zone)
    {
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery("
            SELECT zb FROM KitpagesCmsBundle:ZoneBlock zb
            WHERE zb.zone = :zone
            ORDER BY zb.position ASC
        ")->setParameter('zone', $zone);
        $zoneBlockList = $query->getResult();
        $cnt = 0;
        foreach ($zoneBlockList as $zoneBlock) {
            $zoneBlock->setPosition($cnt);
            $cnt ++;
        }
        $em->flush();
    }

    ////
    // event listener
    ////
    public function afterBlockModify(Event $event)
    {
        $block = $event->getBlock();
        $em = $this->getDoctrine()->getManager();
        foreach($em->getRepository('KitpagesCmsBundle:Zone')->findByBlock($block) as $zone) {
            $this->unpublish($zone);
        }
    }

    public function onBlockDelete(Event $event)
    {
        $block = $event->getBlock();
        $em = $this->getDoctrine()->getManager();
        $zoneList = $em->getRepository('KitpagesCmsBundle:Zone')->findByBlock($block);
        $event->set("zoneList", $zoneList);
        foreach($zoneList as $zone) {
            $zone->setIsPublished(false);
        }
        $em->flush();
    }
    public function afterBlockDelete(Event $event)
    {
        $zoneList = $event->get('zoneList');
        $em = $this->getDoctrine()->getManager();
        foreach($zoneList as $zone) {
            $this->reorderBlockList($zone);
        }
        $em->flush();
    }

}


<?php
/**
 * Combo widget for Yii2
 *
 * @link      https://github.com/hiqdev/yii2-combo
 * @package   yii2-combo
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

namespace hiqdev\combo;

use hiqdev\yii2\assets\select2\Select2SelectAllAsset;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\JsExpression;
use yii\web\View;
use yii\widgets\InputWidget;

/**
 * Widget Combo.
 *
 * @property mixed $return see [[_return]]
 * @property mixed $rename see [[_rename]]
 * @property mixed $filter see [[_filter]]
 * @property mixed $pluginOptions see [[_pluginOptions]]
 * @property mixed $primaryFilter see [[_primaryFilter]]
 * @property mixed hasId
 */
class Combo extends InputWidget
{
    /**
     * @var array the url that will be passed to [[Url::to()]] method to create the request URL
     */
    public $url;

    /**
     * @var string the type of the field.
     * Usual should be module/comboName.
     * For example: client/client, hosting/account, domain/domain.
     * In case of the combo overriding with some specific filters,
     * the type should represent the filter.
     * For example: if the hosting/service combo is extended with filter
     * to show only DB services, the type should be hosting/service/db or hosting/dbService.
     * The decision of the style depends on overall code style and readability
     */
    public $type;

    /**
     * @var string the name of the representative field in the model.
     * Used by [[getPrimaryFilter]] to create the name of the filtering field
     * @see getPrimaryFilter()
     */
    public $name;

    /**
     * @var string md5 of the configuration.
     * Appears only after the combo registration in [[register]]
     * @see register()
     */
    public $configId;

    /**
     * @var array the HTML options for the input element
     */
    public $inputOptions = [];

    /**
     * @var string the outer element selector, that holds all of related Combos
     */
    public $formElementSelector = 'form';

    /**
     * @var string the language. Default is application language
     */
    public $language;

    /**
     * @var bool allow multiple selection
     */
    public $multiple;

    /**
     * @var bool allow `Select All` button. Only if multiple is true
     */
    public $selectAllButton = true;

    /**
     * @var array
     */
    public $current;

    /**
     * @var mixed returning arguments
     * Example:
     *
     * ```
     *  ['id', 'password', 'another_column']
     * ```
     *
     * @see getReturn()
     * @see setReturn()
     */
    protected $_return;

    /**
     * @var array renamed arguments
     * Example:
     *
     * ```
     *  [
     *      'new_col_name' => 'old_col_name',
     *      'text' => 'login',
     *      'deep' => 'array.subarray.value' // can extract some value from an array
     *  ]
     * ```
     *
     * @see getName()
     * @see setName()
     */
    protected $_rename;

    /**
     * @var array the static filters
     * Example:
     *
     * ```
     * [
     *      'someStaticValue' => ['format' => 'the_value'],
     *      'type'            => ['format' => 'seller'],
     *      'is_active'       => [
     *          'field'  => 'server',
     *          'format' => new JsExpression('function (id, text, field) {
     *              if (field.isSet()) {
     *                  return 1;
     *              }
     *          }'),
     *      ]
     * ]
     * @see setFilter()
     * @see getFilter()
     */
    protected $_filter = [];

    /**
     * @var string the name of the primary filter. Default: [[name]]_like
     * @see getPrimaryFilter
     * @see setPrimaryFilter
     */
    protected $_primaryFilter;

    /**
     * @var boolean|string whether the combo has a primary key
     *   null (default) - decision will be taken automatically.
     *                    In case when [[attribute]] has the `_id` postfix, this property will be treated as `true`
     *            false - the combo does not have an id. Meaning the value of the attribute will be used as the ID
     *           string - the explicit name of the ID attribute
     */
    public $_hasId;

    /**
     * Options that will be passed to the plugin.
     *
     * @var array
     * @see getPluginOptions()
     */
    public $_pluginOptions = [];

    /** {@inheritdoc} */
    public function init()
    {
        parent::init();

        // Set language
        if ($this->language === null && ($language = Yii::$app->language) !== 'en-US') {
            $this->language = substr($language, 0, 2);
        }
        if (!$this->_return) {
            $this->return = ['id'];
        }
        if (!$this->rename) {
            $this->rename = ['text' => $this->name];
        }
        if (!$this->inputOptions['id']) {
            $this->inputOptions['id'] = Html::getInputId($this->model, $this->attribute);
        }
        if ($this->multiple) {
            $this->inputOptions['multiple'] = true;
        }
        if ($this->inputOptions['readonly']) {
            // According to the HTML specification, the `select` element does not support
            // property `readonly`. Solution: render `readonly` field as disabled and prepend hidden
            // input to submit the attribute value.
            $this->inputOptions['disabled'] = true;
        }
        if (!$this->inputOptions['data-combo-field']) {
            $this->inputOptions['data-combo-field'] = $this->name;
        }
        if (!isset($this->inputOptions['unselect'])) {
            $this->inputOptions['unselect'] = null;
        }
    }

    public function run()
    {
        $this->registerClientConfig();
        $this->registerClientScript();
        return $this->renderInput();
    }

    /**
     * Renders text input that will be used by the plugin.
     * Must apply [[inputOptions]] to the HTML element.
     *
     * @param string $type for compatible reasons. Should not be used
     * @return string
     */
    protected function renderInput($type = null)
    {
        $html = [];
        if ($this->inputOptions['readonly']) {
            // As it was said in comments of `init` method, the `select` element does not support property `readonly`.
            // However, disabled select will not be submitted.
            // Solution: render hidden input to submit the attribue value.
            $html[] = Html::activeHiddenInput($this->model, $this->attribute, [
                'id' => $this->inputOptions['id'] . '-hidden',
            ]);
        }
        $html[] = Html::activeDropDownList($this->model, $this->attribute, $this->getCurrentOptions(), $this->inputOptions);

        return implode('', $html);
    }

    public function registerClientConfig()
    {
        $view = $this->view;
        ComboAsset::register($view);

        $pluginOptions = Json::encode($this->pluginOptions);
        $this->configId = md5($this->type . $pluginOptions);
        $view->registerJs("$.comboConfig().add('{$this->configId}', $pluginOptions);", View::POS_READY, 'combo_' . $this->configId);
    }

    public function registerClientScript()
    {
        $selector = $this->inputOptions['id'];
        $js = "if ($('#$selector').length > 0) $('#$selector').closest('{$this->formElementSelector}').combo().register('#$selector', '$this->configId');";

        $this->view->registerJs($js);
    }

    public function getReturn()
    {
        return $this->_return;
    }

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

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

    /**
     * @param mixed $filter
     */
    public function setFilter($filter)
    {
        $this->_filter = $filter;
    }

    /**
     * @param mixed $rename
     */
    public function setRename($rename)
    {
        $this->_rename = $rename;
    }

    /**
     * @param mixed $return
     */
    public function setReturn($return)
    {
        $this->_return = $return;
    }

    /**
     * @return string
     * @see _primaryFilter
     */
    public function getPrimaryFilter()
    {
        return $this->_primaryFilter ?: $this->name . '_like';
    }

    /**
     * @param $primaryFilter
     * @see _primaryFilter
     */
    public function setPrimaryFilter($primaryFilter)
    {
        $this->_primaryFilter = $primaryFilter;
    }

    /**
     * Returns the config of the Combo, merges with the passed $config.
     *
     * @param array $options
     * @return array
     */
    public function getPluginOptions($options = [])
    {
        $defaultOptions = [
            'name' => $this->name,
            'type' => $this->type,
            'hasId' => $this->hasId,
            'select2Options' => [
                'width'       => '100%',
                'placeholder' => '----------',
                'minimumInputLength' => '0',
                'ajax'        => [
                    'url'    => Url::toRoute($this->url),
                    'type'   => 'post',
                    'return' => $this->return,
                    'rename' => $this->rename,
                    'filter' => $this->filter,
                    'data' => new JsExpression("
                        function (event) {
                            return $(this).data('field').createFilter($.extend(true, {
                                '{$this->primaryFilter}': {format: event.term}
                            }, event.filters || {}));
                        }
                    "),
                ],
            ],
        ];
        if ($this->multiple && $this->selectAllButton) {
            Select2SelectAllAsset::register($this->view);
            $defaultOptions = ArrayHelper::merge($defaultOptions, [
                'select2Options' => [
                    'tags' => false,
                    'tokenSeparators' => [',', ', ', ' '],
                    'dropdownAdapter' => new JsExpression('$.fn.select2.amd.require("select2/custom/dropdown-adapter/select-all")'),
                ],
            ]);
        }

        return ArrayHelper::merge($defaultOptions, $this->_pluginOptions, $options);
    }

    public function getFormIsBulk()
    {
        return preg_match("/^\[.*\].+$/", $this->attribute);
    }

    /**
     * @param array $pluginOptions
     */
    public function setPluginOptions($pluginOptions)
    {
        $this->_pluginOptions = $pluginOptions;
    }

    /**
     * @return bool|string
     */
    public function getHasId()
    {
        return $this->_hasId === null ? (substr($this->attribute, -3) === '_id') : $this->_hasId;
    }

    /**
     * @param bool|string $hasId
     */
    public function setHasId($hasId)
    {
        $this->_hasId = $hasId;
    }

    /**
     * Method collects list of options that will be rendered inside the `select` tag.
     * @return array
     */
    protected function getCurrentOptions()
    {
        $value = Html::getAttributeValue($this->model, $this->attribute);

        if (!isset($value) || empty($value)) {
            return [];
        }

        if (!empty($this->current)) {
            return $this->current;
        }

        if ($this->getHasId()) {
            if (!is_scalar($value)) {
                Yii::error('When Combo has ID, property $current must be set manually, or attribute value must be a scalar. Value ' . var_export($value, true) . ' is not a scalar.', __METHOD__);
                return [];
            }

            return [$value => $value];
        } else {
            if (is_array($value)) {
                return array_combine(array_values($value), array_values($value));
            }

            return [$value => $value];
        }
    }
}


<?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 MmfResponseHtml format the input data into the html format.
 *
 * @author Jepi Humet
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 */
class ResponseHtml implements ResponseInterface {

    /**
     * Echo the response and return it as a string to be echo.
     *
     * @param mixed $response
     * @return string
     */
    public function formatResponse($response) {
        if (is_object($response) && is_a($response, '\Mmf\View\BasicViewInterface')) {
            //Is a view
            $return = $response->getContentWithTemplate();
        } else if (is_string($response)) {
            //Is string
            $return = $response;
        } else {
            //Is another structure (object or array)
            $return = print_r($response, true);
        }
        echo $return;
        return $return;
    }

    /**
     * Echo the response and return it as a string to be echo.
     *
     * @param mixed $response
     * @return string
     */
    public function formatResponseBad($response) {
        //TODO replace.
        if (is_object($response) && is_a($response, '\Mmf\View\BasicViewInterface')) {
            //Is a view
            $return = $response->getContentWithTemplate();
        } else if (is_string($response)) {
            //Is string
            $return = $response;
        } else {
            //Is another structure (object or array)
            $return = print_r($response, true);
        }
        echo $return;
        return $return;
    }

}


<?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;

/**
 * Description of RequestHtml
 *
 * @author Jepi Humet
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 */
class RequestHtml implements RequestInterface {

    /**
     *
     * @var array
     */
    private $parameters = array();

    /**
     * Set the initial parameters as Header vars, Post vars and Get vars.
     * The GET vars replace the POST and Header vars in case that have the same
     * name, and POST vars replace the Header vars in case that have the same
     * name.
     */
    public function __construct() {
        if (function_exists('getallheaders')){
            //TODO: create getallheaders functions for nginx
            $this->setBulkOfInputGivenArray(getallheaders());
        } elseif(!empty($_SERVER)) {
            $headers = '';
            foreach ($_SERVER as $name => $value) {
                if (substr($name, 0, 5) == 'HTTP_') {
                    $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
                }
            }
            $this->setBulkOfInputGivenArray($headers);
        }
        $this->setBulkOfInputGivenArray($_POST);
        $this->setBulkOfInputGivenArray($_GET);
    }

    /**
     * Set a bulk of input parameters from and array.
     *
     * @param array $arrayOfParameters
     */
    protected function setBulkOfInputGivenArray($arrayOfParameters) {
        if(is_array($arrayOfParameters)) {
            foreach ($arrayOfParameters as $nameOfParameter => $valueOfParameter) {
                $this->setInput($nameOfParameter, $valueOfParameter);
            }
        }
    }

    /**
     * Get the input var.
     *
     * @param string $varName name of the var to retrive the value.
     * @return mixed input
     */
    public function input($varName) {
        if (isset($this->parameters[$varName])) {
            return $this->filterVar($this->parameters[$varName]);
        } else {
            return null;
        }
    }

    /**
     * Set the input var to concret value.
     *
     * @param string $varName
     * @param mixed $value
     */
    public function setInput($varName, $value) {
        $this->parameters[$varName] = $value;
    }

    /**
     * Function to filter the input var. Is it define as public to replicate
     * the logic for every var that you want.
     *
     * @param string $var
     * @return mixed sanitize var
     */
    public function filterVar($var) {
        $response = NULL;
        if (is_bool($var)) {
            $response = $var;
        } elseif(is_int($var)) {
            $response = $var;
        } elseif(is_float($var)) {
            $response = $var;
        }
        if($var != 'null') {
            if(is_string($var)) {
                $response = filter_var($var, FILTER_SANITIZE_SPECIAL_CHARS);
            } elseif(is_array($var)) {
                $response = array();
                foreach ($var as $key => $value) {
                    if(is_array($value)) {
                        $response[$key] = $this->filterVar($value);
                    } else {
                        $response[$key] = filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
                    }
                }
            }
        }
        return $response;

    }

}


<?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 MmfResponseHtmlAutomatic format the input data into the html format.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 */
class ResponseHtmlAutomatic extends ResponseHtml{

    /**
     * Echo the response and return it as a string to be echo.
     *
     * @param mixed $response
     * @return string
     */
    public function formatResponseBad($response) {
        //TODO replace.
        if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) { // AJAX specific code
            return parent::formatResponseBad($response);
        } else {
            if (is_array($response) &&
                    isset($response['errorCode']) &&
                    isset($response['errorMessage'])
            ) {
                switch ($response['errorCode']) {
                    case 1600: //URL NOT MATCH
                        http_response_code(404);
                        $return = $response['errorMessage'];
                        break;
                    case 1500: //FORBIDEN
                        http_response_code(401);
                        $return = $response['errorMessage'];
                        break;
                    default:
                        http_response_code(500);
                        $return = $response['errorMessage'];
                        break;
                }
            } else {
                http_response_code(500);
                $return = print_r($response, true);
            }
            echo $return;
            return $return;
        }
    }

}


<?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\Model;

/**
 * The PDO specifies a way to open and close connections.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
class PDO implements ConnectionInterface{

    /**
     *
     * @var MParametersInterface
     */
    public $config = false;

    /**
     *
     * @var array(name, link).
     */
    private $connections = array();

    /**
     *
     * @param ParametersInterface $config
     */
    public function __construct(\Mmf\Parameter\ParametersInterface $config) {
        $this->config = $config;
    }

    /**
     * Open connection if is not already open.
     *
     * @param string $name optional parameter if nothing is send it gets
     * the default connection.
     *
     * @return \PDO
     * @throws \ModelException
     */
    public function openConnection($name='db_default') {
        foreach ($this->connections as $connection) {
            if($connection['name'] == $name) {
                return $connection['lynk'];
            }
        }
        //Open new connection
        try {
            //Get the configuration of the connection.
            $dbConfig = $this->config->get($name);
            //Create the new connection.
            $connection = new \PDO('mysql:host=' . $dbConfig['host'] .
                                       ';port=' . $dbConfig['port'] .
                                       ';dbname=' . $dbConfig['name'],
                                   $dbConfig['user'],
                                   $dbConfig['pass'],
                                   array(\PDO::MYSQL_ATTR_FOUND_ROWS => true, \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

            $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $this->connections[] = array('name'=>$name,'lynk'=>$connection);

            return $connection;

        } catch (\Exception $e) {
            throw new ModelException('Error trying to connect to db');
        }
    }

    /**
     * Close connection if is still open.
     *
     * @param string $name optional parameter if nothing is send it gets
     * the default connection.
     *
     * @return bool
     */
    public function closeConnection($name='db_default') {
        foreach ($this->connections as $key => $connection) {
            if($connection['name'] == $name) {
                $this->connections[$key]['lynk'] = null; //closing the connection
                array_splice($this->connections, $key, 1);
                return true;
            }
        }
        return false;
    }
}


<?php
namespace Kitpages\CmsBundle\Model;

use Doctrine\Bundle\DoctrineBundle\Registry;

use Kitpages\CmsBundle\Entity\UserPreference;
use Kitpages\CmsBundle\Entity\Page;

class UserPreferenceManager
{
    ////
    // dependency injection
    ////
    protected $doctrine = null;

    public function __construct(
        Registry $doctrine
    )
    {
        $this->doctrine = $doctrine;
    }

     ////
    // actions
    ////
    public function getPreference($userName)
    {
        $em = $this->doctrine->getManager();
        $userPreference = $em->getRepository('KitpagesCmsBundle:UserPreference')->findOneByUserName($userName);
        if (!($userPreference instanceof UserPreference)) {
            $userPreference = $this->setUserPreference($userName);
        }
        return $userPreference;
    }

    public function setUserPreference($userName) {
        $em = $this->doctrine->getManager();
        $userPreference = new UserPreference();
        $userPreference->setUserName($userName);
        $em->persist($userPreference);
        $em->flush();
        return $userPreference;
    }

    public function setPreferenceDataTreeState($userName, $pageId, $action, $target){
        $em = $this->doctrine->getManager();
        $userPreference = $em->getRepository('KitpagesCmsBundle:UserPreference')->findOneByUserName($userName);

        if ($userPreference instanceof UserPreference) {
            $dataTree = $userPreference->getDataTree();
            if ($target == 'tree' && $pageId == null) {
                if ($action == 'expand') {
                    $pageList = $em->getRepository('KitpagesCmsBundle:Page')->findAll();
                    foreach($pageList as $page) {
                        $dataTree['stateTree'][$page->getId()] = true;
                    }
                } else {
                    $dataTree['stateTree'] = array();
                }
            } elseif ($target == 'page' && $pageId != null) {
                if ($action == 'expand') {
                    $dataTree['stateTree'][$pageId] = true;
                } else {
                    $dataTree['stateTree'][$pageId] = false;
                }
            }
            $userPreference->setDataTree($dataTree);
            $em->persist($userPreference);
            $em->flush();
        }
    }

    public function setPreferenceDataTreeScroll($userName, $scroll){
            $em = $this->doctrine->getManager();
            $userPreference = $em->getRepository('KitpagesCmsBundle:UserPreference')->findOneByUserName($userName);
            if ($userPreference instanceof UserPreference) {
                $dataTree = $userPreference->getDataTree();
                $dataTree['scrollTree'] = $scroll;
                $userPreference->setDataTree($dataTree);
                $em->persist($userPreference);
                $em->flush();
            }
        }
    ////
    // event listener
    ////

}


<?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 AuthBasic extends Auth {

    /**
     * Logic of authentication.
     *
     * @return void
     */
    public function authenticate() {
        $authorization = $this->request->input('Authorization');
        if($authorization === null) {
            $userInfo = ['username' => 'guest', 'name' => 'guest', 'id_user' => 1];
        } else {
            $authorizationCredentials = str_replace('Basic', '', $authorization);
            list($username,$password) = explode(':',base64_decode(trim($authorizationCredentials)));

            $userInfo = $this->authModel->getRoleAndUserFromUsernamePassword($username, $password);
        }
        $this->setUsername($userInfo['username']);
        $this->setRoleName($userInfo['name']);
        $this->setUserId($userInfo['id_user']);
        $this->setDefaultLanguage($userInfo['id_user']);
    }

    /**caos
     * 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']);
            }
        }
    }

}


<?php

namespace pvsaintpe\db\components;

use yii\db\ColumnSchemaBuilder;
use yii\db\TableSchema;
use pvsaintpe\boost\db\Migration as BaseMigration;

/**
 * Class Migration
 * @package pvsaintpe\db\components
 * @property Connection $db
 * @method Connection getDb()
 */
class Migration extends BaseMigration
{
    public $logTableTriggerInit = false;

    /**
     * @param string $conditions
     * @param array $params
     * @return false|null|string
     * @throws \yii\db\Exception
     */
    public function selectScalar($conditions = '', $params = [])
    {
        return $this->db->createCommand($conditions, $params)->queryScalar();
    }

    /**
     * @param string $conditions
     * @param array $params
     * @param integer $fetchMode
     * @return false|null|string
     * @throws \yii\db\Exception
     */
    public function selectOne($conditions = '', $params = [], $fetchMode = null)
    {
        return $this->db->createCommand($conditions, $params)->queryOne($fetchMode);
    }

    /**
     * @param string $conditions
     * @param array $params
     * @return array
     * @throws \yii\db\Exception
     */
    public function selectColumn($conditions = '', $params = [])
    {
        return $this->db->createCommand($conditions, $params)->queryColumn();
    }

    /**
     * @param string $conditions
     * @param array $params
     * @param integer $fetchMode
     * @return array
     * @throws \yii\db\Exception
     */
    public function selectAll($conditions = '', $params = [], $fetchMode = null)
    {
        return $this->db->createCommand($conditions, $params)->queryAll($fetchMode);
    }

    /**
     * @param string $table
     * @param array $columns
     * @throws \yii\db\Exception
     */
    public function insert($table, $columns)
    {
        $this->db->createCommand()->insert($table, $columns)->execute();
    }

    /**
     * @param string $table
     * @param array $columns
     * @param array $rows
     * @throws \yii\db\Exception
     */
    public function batchInsert($table, $columns, $rows)
    {
        $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute();
    }

    /**
     * @param string $table
     * @param array $columns
     * @param array $condition
     * @throws \yii\db\Exception
     */
    public function batchUpdate($table, $columns, $condition)
    {
        $this->db->createCommand()->batchUpdate($table, $columns, $condition)->execute();
    }

    /**
     * @param string $sql
     * @param array $params
     * @throws \yii\db\Exception
     */
    public function execute($sql, $params = [])
    {
        $this->db->createCommand($sql)->bindValues($params)->execute();
    }

    /**
     * @param string $table
     * @param array $columns
     * @param string $condition
     * @param array $params
     * @throws \yii\db\Exception
     */
    public function update($table, $columns, $condition = '', $params = [])
    {
        $this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
    }

    /**
     * @param string $name
     * @param string $sql
     * @throws \yii\db\Exception
     */
    public function createView($name, $sql)
    {
        $this->dropView($name);
        $this->execute("CREATE VIEW `{$name}` AS {$sql}");
    }

    /**
     * @param string $name
     * @throws \yii\db\Exception
     */
    public function dropView($name)
    {
        $this->execute("DROP VIEW IF EXISTS `{$name}`;");
    }

    /**
     * @param string $tableName
     * @param string $name
     * @param string $sql
     * @param string $event enum(
     *      'BEFORE INSERT',
     *      'BEFORE UPDATE',
     *      'BEFORE_DELETE',
     *      'AFTER INSERT',
     *      'AFTER UPDATE',
     *      'AFTER DELETE',
     * )
     * @param string $definer CURRENT_USER
     * @param boolean $leavePrefixEnable
     * @param string $dbPrefix
     * @throws \yii\db\Exception
     */
    public function createTrigger(
        $tableName,
        $name,
        $sql,
        $event = 'BEFORE INSERT',
        $definer = null,
        $leavePrefixEnable = false,
        $dbPrefix = null
    ) {
        if ($definer === null) {
            $definer = 'CURRENT_USER';
        }
        if (($dbName = $this->db->getName()) !== false) {
            $leaveSuffix = '';
            $leavePrefix = '';
            $definerPrefix = '';
            if (YII_ENV_TEST && !$this->logTableTriggerInit) {
                $leaveSuffix = "
                    IF (@TRIGGER_CHECKS = FALSE) THEN
                      LEAVE thisTrigger;
                    END IF;
                ";
                $leavePrefixEnable = true;
            }
            if ($leavePrefixEnable) {
                $leavePrefix = 'thisTrigger:';
            }
            if ($definer) {
                $definerPrefix = "DEFINER = {$definer}";
            }

            $dbName = $dbPrefix ?: $dbName;
            $this->dropTrigger($name);
            $this->execute("
                CREATE {$definerPrefix}
                TRIGGER `{$dbName}`.`{$name}`
                {$event} ON `{$dbName}`.`{$tableName}`
                FOR EACH ROW
                {$leavePrefix} BEGIN {$leaveSuffix}
                    {$sql}
                END
            ");
        }
    }

    /**
     * @param string $name
     * @param string $sql
     * @param array $params @example [['type' => 'IN', 'name' => 'arg_name', 'format' => 'INT UNSIGNED'], ...]
     * @param string $definer CURRENT_USER
     * @param array $options @example ['NOT DETERMINISTIC', 'CONTAINS SQL', 'SQL SECURITY DEFINER']
     * @param string $dbPrefix
     * @throws \yii\db\Exception
     */
    public function createProcedure($name, $sql, $params = [], $definer = 'CURRENT_USER', $options = [], $dbPrefix = null)
    {
        if (($dbName = $this->db->getName()) !== false) {
            $args = array_map(
                function ($item) {
                    return join(' ', [
                        $item['type'],
                        $item['name'],
                        $item['format'],
                    ]);
                },
                $params
            );
            $dbName = $dbPrefix ?: $dbName;
            $this->dropProcedure($name);
            $this->execute("
                CREATE DEFINER = {$definer}
                PROCEDURE {$dbName}.{$name}(" . implode(', ', $args) . ")
                " . join(' ', $options) . "
                BEGIN
                    {$sql}
                END
            ");
        }
    }

    /**
     * @param string $name
     * @param string $dbPrefix
     * @throws \yii\db\Exception
     */
    public function dropProcedure($name, $dbPrefix = null)
    {
        if (($dbName = $this->db->getName()) !== false) {
            $dbName = $dbPrefix ?: $dbName;
            $this->execute("DROP PROCEDURE IF EXISTS `{$dbName}`.`{$name}`");
        }
    }

    /**
     * @param string $name
     * @param string $dbPrefix
     * @throws \yii\db\Exception
     */
    public function dropTrigger($name, $dbPrefix = null)
    {
        if (($dbName = $this->db->getName()) !== false) {
            $dbName = $dbPrefix ?: $dbName;
            $this->execute("DROP TRIGGER IF EXISTS `{$dbName}`.`{$name}`");
        }
    }

    /**
     * @param string $table
     * @param string $column
     * @param string $type
     */
    public function alterColumn($table, $column, $type)
    {
        parent::alterColumn($table, $column, $this->fixColumnType($type));
    }

    /**
     * @param string $tableName
     * @param string $columnName
     * @return false|null|string
     * @throws \yii\db\Exception
     */
    public function hasColumn($tableName, $columnName)
    {
        return $this->db->existColumn($tableName, $columnName);
    }

    /**
     * @param string $table
     * @param string $column
     * @param \yii\db\ColumnSchemaBuilder|string $type
     */
    public function addColumn($table, $column, $type)
    {
        parent::addColumn($table, $column, $type);
    }

    /**
     * @param string $table
     * @param string $column
     */
    public function dropColumn($table, $column)
    {
        $tableColumns = $this->db->getTableSchema($table)->columnNames;
        if (!in_array($column, $tableColumns)) {
            return;
        }
        $fks = $this->getForeignNamesColumns($this->db->getTableSchema($table));
        if ($name = array_search($column, $fks)) {
            $this->dropForeignKey($name, $table);
        }
        parent::dropColumn($table, $column);
    }

    /**
     * @param string $table
     * @param array $columns
     */
    public function dropColumns($table, array $columns)
    {
        foreach ($columns as $column) {
            $this->dropColumn($table, $column);
        }
    }

    /**
     * @param null|string $name
     * @param string $table
     * @param string|array $columns
     * @param string $refTable
     * @param string|array $refColumns
     * @param null $delete
     * @param null $update
     */
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
    {
        $name = $this->fixKeyName($name, $table, $columns, true, static::FOREIGN_KEY);
        parent::addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
    }

    /**
     * @param null|string $name
     * @param string $table
     * @param array|string $columns
     * @param bool $unique
     */
    public function createIndex($name, $table, $columns, $unique = false)
    {
        $name = $this->fixKeyName($name, $table, $columns, true, static::INDEX);
        parent::createIndex($name, $table, $columns, $unique);
    }

    /**
     * @param null|string $name
     * @param string $table
     * @param array|string $columns
     */
    public function createUnique($name, $table, $columns)
    {
        $name = $this->fixKeyName($name, $table, $columns, true, static::UNIQUE_KEY);
        parent::createUnique($name, $table, $columns);
    }

    /**
     * @param null|string $name
     * @param string $table
     * @param array|string $columns
     */
    public function addPrimaryKey($name, $table, $columns)
    {
        $name = $this->fixKeyName($name, $table, $columns, true, static::PRIMARY_KEY);
        parent::addPrimaryKey($name, $table, $columns);
    }

    /**
     * @param string $name
     * @param string $table
     */
    public function dropForeignKey($name, $table)
    {
        parent::dropForeignKey($name, $table);
    }

    /**
     * @param string $table
     * @param string $name
     * @param string $newName
     */
    public function renameColumn($table, $name, $newName)
    {
        parent::renameColumn($table, $name, $newName);
    }

    /**
     * @param string $table
     */
    public function dropTable($table)
    {
        parent::dropTable($table);
    }

    /**
     * @param string $tableName
     * @throws \yii\db\Exception
     */
    protected function createTriggerDeleteRestrictions($tableName)
    {
        $this->createTrigger(
            $tableName,
            $tableName . "_BEFORE_DELETE",
            /** @lang SQL */
            "
    SIGNAL SQLSTATE VALUE '03999'
    SET MESSAGE_TEXT = 'Delete operations are restricted.', MYSQL_ERRNO = 999;
            ",
            'BEFORE DELETE'
        );
    }

    /**
     * @param string $tableName
     * @throws \yii\db\Exception
     */
    protected function createTriggerUpdateRestrictions($tableName)
    {
        $this->createTrigger(
            $tableName,
            $tableName . "_BEFORE_UPDATE",
            /** @lang SQL */
            "
    SIGNAL SQLSTATE VALUE '03999'
    SET MESSAGE_TEXT = 'Update operations are restricted.', MYSQL_ERRNO = 998;
            ",
            'BEFORE UPDATE'
        );
    }

    /**
     * Получает имена колонок с внешнем ключом
     * ```php
     * [
     *  nameFk => column,
     *  ....
     * ]
     * ```
     *
     * @param TableSchema $tableSchema
     * @return array
     */
    private function getForeignNamesColumns(TableSchema $tableSchema)
    {
        return array_map(function ($foreignKey) {
            return array_filter(array_keys($foreignKey))[1];
        }, $tableSchema->foreignKeys);
    }

    /**
     * Получить расширенную информацию о колонках $tableName, исключая $restrict-columns
     * @param string $tableName
     * @param array $restrict
     * @return array
     * @throws \yii\db\Exception
     */
    public function getColumns($tableName, $restrict = [])
    {
        return $this->db->getColumns($tableName, $restrict);
    }

    /**
     * Получить уникальные ключи (без PRIMARY)
     * @param string $tableName
     * @return array
     * @throws \yii\db\Exception
     */
    public function getUniqueKeys($tableName)
    {
        return $this->db->getUniqueKeys($tableName);
    }

    /**
     * Получить обычные ключи/индексы
     * @param string $tableName
     * @return array
     * @throws \yii\db\Exception
     */
    public function getKeys($tableName)
    {
        return $this->db->getKeys($tableName);
    }

    /**
     * Получить PRIMARY ключи в таблице $tableName
     * @param string $tableName
     * @return array
     * @throws \yii\db\Exception
     */
    public function getPrimaryKeys($tableName)
    {
        return $this->db->getPrimaryKeys($tableName);
    }

    /**
     * @param $tableName
     * @return array
     */
    public function getForeignKeys($tableName)
    {
        return $this->db->getForeignKeys($tableName);
    }

    /**
     * Проверяет наличие таблицы $tableName
     * @param string $tableName
     * @return false|null|string
     * @throws \yii\db\Exception
     */
    public function existTable($tableName)
    {
        return $this->db->existTable($tableName);
    }

    /**
     * Проверяет наличие столбца $columnName в таблице $tableName
     * @param string $tableName
     * @param string $columnName
     * @return false|null|string
     * @throws \yii\db\Exception
     */
    public function existColumn($tableName, $columnName)
    {
        return $this->db->existColumn($tableName, $columnName);
    }

    /**
     * Проверяет наличие ключа/индекса $key в таблице $tableName
     * @param string $tableName
     * @param string $key
     * @return false|null|string
     * @throws \yii\db\Exception
     */
    public function existKey($tableName, $key = 'PRIMARY')
    {
        return $this->db->existKey($tableName, $key);
    }

    /**
     * Проверяет наличие ключа/индекса к столбцу $columnName в таблице $tableName
     * @param string $tableName
     * @param string $columnName
     * @return array|false
     * @throws \yii\db\Exception
     */
    public function existKeyOnColumn($tableName, $columnName)
    {
        return $this->db->existKeyOnColumn($tableName, $columnName);
    }

    /**
     * Создает таблицу $tableName клонируя структуру таблицы $sourceTable в $sourceSchema
     * @param string $tableName Целевое имя таблицы
     * @param string $sourceTable Имя таблицы источника
     * @param string|null $sourceSchema Имя схемы источника
     * @throws \yii\db\Exception
     * @return void
     */
    public function cloneTable($tableName, $sourceTable, $sourceSchema = null)
    {
        $this->db->cloneTable($tableName, $sourceTable, $sourceSchema);
    }

    /**
     * @param string $baseName
     * @param string $prefix
     * @return string
     */
    protected function generateKeyName($baseName, $prefix)
    {
        $tableIndex = [];
        foreach (explode('_', $baseName) as $table_part) {
            $tableIndex[] = substr($table_part, 0, 1);
        }
        return $prefix . '-' . uniqid(join('_', $tableIndex) ?: 'johndoe');
    }

    /**
     * @param string|null $name
     * @param string $table
     * @param string|array $columns
     * @param bool $checkExists
     * @param int $type
     * @return string
     * @throws
     */
    protected function fixKeyName($name, $table, $columns, $checkExists = false, $type = BaseMigration::FOREIGN_KEY)
    {
        if ($type == static::PRIMARY_KEY) {
            return $name;
        }

        if (!$name) {
            $name = implode('-', array_merge((array)$table, (array)$columns));
        }

        if (strlen($name) >= 60) {
            if (strlen($table) > 30) {
                $tableIndex = [];
                foreach (explode('_', $table) as $table_part) {
                    $tableIndex[] = substr($table_part, 0, 1);
                }
                $table = join('_', $tableIndex);
            }

            switch ($type) {
                case static::UNIQUE_KEY:
                    $name = join('-', ['uk', $table, uniqid('u')]);
                    break;
                case static::FOREIGN_KEY:
                    $name = join('-', ['fk', $table, uniqid('f')]);
                    break;
                case static::INDEX:
                    $name = join('-', ['index', $table, uniqid('i')]);
                    break;
                default:
                    $name = join('-', ['key', $table, uniqid('k')]);
                    break;
            }
        }

        return $name;
    }

    /**
     * Удаляет внешний ключ на колонке
     * @param $table
     * @param $column
     */
    public function dropColumnForeignKey($table, $column)
    {
        $tableColumns = $this->db->getTableSchema($table)->columnNames;
        if (!in_array($column, $tableColumns)) {
            return;
        }
        $fks = $this->getForeignNamesColumns($this->db->getTableSchema($table));
        if ($name = array_search($column, $fks)) {
            $this->dropForeignKey($name, $table);
        }
    }

    /**
     * Creates a medium text column.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     * @throws
     */
    public function mediumText()
    {
        return $this->db->getSchema()->createColumnSchemaBuilder('mediumtext');
    }

    /**
     * Creates a long text column.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     * @throws
     */
    public function longText()
    {
        return $this->db->getSchema()->createColumnSchemaBuilder('longtext');
    }

    /**
     * Creates a tiny text column.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     * @throws
     */
    public function tinyText()
    {
        return $this->db->getSchema()->createColumnSchemaBuilder('tinytext');
    }
}


<?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     Andreas Isaak <info@andreas-isaak.de>
 * @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\FilterSetting\Published;

use MetaModels\Filter\IFilter as IMetaModelFilter;
use MetaModels\Filter\Rules\SearchAttribute;
use MetaModels\Filter\Rules\StaticIdList as MetaModelFilterRuleStaticIdList;
use MetaModels\Filter\Setting\Simple as MetaModelFilterSetting;

/**
 * Filter setting to filter for translated checkboxes.
 */
class TranslatedCheckbox extends MetaModelFilterSetting
{
    /**
     * {@inheritDoc}
     */
    public function prepareRules(IMetaModelFilter $objFilter, $arrFilterUrl)
    {
        if ($this->get('check_ignorepublished') && $arrFilterUrl['ignore_published' . $this->get('id')]) {
            return;
        }

        // Skip filter when in front end preview.
        if ($this->get('check_allowpreview') && BE_USER_LOGGED_IN) {
            return;
        }

        $objAttribute = $this->getMetaModel()->getAttributeById($this->get('attr_id'));
        if ($objAttribute) {
            $objFilterRule = new SearchAttribute($objAttribute, '1', $this->getMetaModel()->getActiveLanguage());
            $objFilter->addFilterRule($objFilterRule);
            return;
        }
        // Attribute not found, do not return anyting to prevent leaking of items.
        $objFilter->addFilterRule(new MetaModelFilterRuleStaticIdList([]));
    }

    /**
     * {@inheritdoc}
     */
    public function getParameters()
    {
        return ($this->get('check_ignorepublished')) ? ['ignore_published' . $this->get('id')] : [];
    }

    /**
     * {@inheritdoc}
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     * @SuppressWarnings(PHPMD.CamelCaseVariableName)
     */
    public function getParameterDCA()
    {
        if (!$this->get('check_ignorepublished')) {
            return [];
        }

        $objAttribute = $this->getMetaModel()->getAttributeById($this->get('attr_id'));

        $arrLabel = [];
        foreach ($GLOBALS['TL_LANG']['MSC']['metamodel_filtersetting']['ignore_published'] as $strLabel) {
            $arrLabel[] = \sprintf($strLabel, $objAttribute->getName());
        }

        return [
            'ignore_published' . $this->get('id') =>
                [
                    'label'     => $arrLabel,
                    'inputType' => 'checkbox',
                ]
        ];
    }
}


<?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\Model;

/**
 * The MySQLModelAbstract is the main abstract class for the SQL models.
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */
abstract class MySQLModelAbstract implements BasicModelInterface {

    /**
     *
     * @var ConnectionInterface
     */
    protected $connection = false;

    /**
     * Init the core var and connection var.
     *
     * @param ConnectionInterface    $connection
     * @param string | false            $name is the same as in the config.ini file.
     */
    public function __construct(ConnectionInterface $connection, $name=false) {
        if($name){ //Open the connection send in the parameter $name.
            $this->connection = $connection->openConnection($name);
        } else { //Open the default connection.
            $this->connection = $connection->openConnection();
        }
    }

    /**
     * Execute SQL and return the object.
     *
     * @param string $SQL
     * @throws ModelException
     */
    private function executeSQL($SQL, $parameters = null) {
        try {
            $queryPrepare = $this->connection->prepare($SQL);
            if (is_array($parameters)) {
                $queryPrepare->execute($parameters);
            } else {
                $queryPrepare->execute();
            }
        } catch (\PDOException $e) {
            throw new ModelException('Error in the Select QUERY ('.$SQL.') '
                    . 'and error message('.$e->getMessage().')');
        }
        return $queryPrepare;
    }

    /**
     * Do a select query to Database and return the result in a array type.
     *
     * @param string $SQL
     * @return array selected rows.
     * @throws ModelException
     */
    public function select($SQL, $parameters = null) {
        $queryResult = $this->executeSQL($SQL, $parameters);
        return $queryResult->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * Do a insert query to Database and return the id of the row inserted.
     *
     * @param string $SQL
     * @return int id of inserted row.
     * @throws ModelException
     */
    public function insert($SQL, $parameters = null) {
        $this->executeSQL($SQL, $parameters);
        return $this->connection->lastInsertId();
    }

    /**
     * Do a delete query to Database and return the number of deleted rows.
     *
     * @param string $SQL
     * @return int number of deleted rows.
     * @throws ModelException
     */
    public function delete($SQL, $parameters = null) {
        $queryResult = $this->executeSQL($SQL, $parameters);
        return $queryResult->rowCount();
    }

    /**
     * Do a update query to Database and return the number of updated rows
     *
     * @param string $SQL
     * @return int number of update rows.
     * @throws ModelException
     */
    public function update($SQL, $parameters = null) {
        $queryResult = $this->executeSQL($SQL, $parameters);
        return $queryResult->rowCount();
    }

    /**
     * Begin a transaction.
     *
     * @throws ModelException
     */
    public function beginTransaction() {

    }

    /**
     * End the transaction.
     *
     * @throws ModelException
     */
    public function endTransaction() {

    }
}