<?php
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.service
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: chartService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Service;

use Openbizx\Object\ObjectFactoryHelper;

/**
 * chartService class is the plug-in service of printing bizform to chart
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class chartService
{
    /**
     * List of plot objects used in drawing group plot and accurated plot
     *
     * @var array
     */
    public $plotList;

    /**
     * Initialize chartService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
    }

    /**
     * Render the chart output
     *
     * @param string $objName object name which is the bizform name
     * @return void
     */
    Public function render($objName)
    {
        // get the value of the control that issues the call
        $chartName = Openbizx::$app->getClientProxy()->getFormInputs("__this");

        // get the current UI bizobj
        $formObj = Openbizx::getObject($objName);    // get the existing bizform object
        $bizDataObj = $formObj->getDataObj();

        // get chart config xml file
        $chartXmlFile = ObjectFactoryHelper::getXmlFileWithPath($objName."_chart");
        $xmlArr = ObjectFactoryHelper::getXmlArray($chartXmlFile);

        ob_clean();
        // get the chart section from config xml file
        foreach($xmlArr["BIZFORM_CHART"]["CHARTLIST"]["CHART"] as $chart)
        {
            if (count($xmlArr["BIZFORM_CHART"]["CHARTLIST"]["CHART"]) == 1)
                $chart = $xmlArr["BIZFORM_CHART"]["CHARTLIST"]["CHART"];
            // try to match the chartName, if no chartName given, always draw the first chart defined in xml file
            if (($chartName && $chart["ATTRIBUTES"]["NAME"] == $chartName) || !$chartName)
            {
                if ($chart["ATTRIBUTES"]["GRAPHTYPE"] == 'XY')
                {
                    $this->xyGraphRender($bizDataObj, $chart);
                    break;
                }
                if ($chart["ATTRIBUTES"]["GRAPHTYPE"] == 'Pie')
                {
                    $this->pieGraphRender($bizDataObj, $chart);
                    break;
                }
            }
        }
    }

    /**
     * Get plot data array
     *
     * @param BizObj $bizObj object reference of bizobj
     * @param array $fields list of bizobj fields
     * @param array $labelField label field of bizobj
     * @return array reference of the array [field][index]
     */
    public function &getPlotData(&$bizObj, $fields, $labelField)
    {
        $oldCacheMode = $bizObj->GetCacheMode();
        $bizObj->SetCacheMode(0);    // turn off cache mode, not affect the current cache
        $bizObj->runSearch(-1);  // don't use page search
        while (1)
        {
            $recArray = $bizObj->GetRecord(1);
            if (!$recArray) break;
            $bizObj->UnformatInputRecArr($recArray);

            foreach($fields as $fld)
                $recMatrix[$fld][] = $recArray[$fld];   // get data without format
            $recMatrix[$labelField][] = $recArray[$labelField];   // get symbol with format
        }
        $bizObj->SetCacheMode($oldCacheMode);
        return $recMatrix;
    }

    /**
     * Draw the XY type graph (can have > 1 plots)
     *
     * @param BizObj $bizObj object reference of bizobj
     * @param array $xmlArr xml array reference
     * @return void
     */
    public function xyGraphRender(&$bizObj, &$xmlArr)
    {
        include_once (JPGRAPH_DIR.'/jpgraph.php');

        $graph = new Graph($xmlArr["ATTRIBUTES"]["WIDTH"],$xmlArr["ATTRIBUTES"]["HEIGHT"],"auto");
        //$graph->img->SetAntiAliasing();
        $graph->SetScale("textlin");
        $graph->yaxis->scale->SetGrace(10);
        list($m1, $m2, $m3, $m4) = explode(',', $xmlArr["ATTRIBUTES"]["MARGIN"]);
        $graph->img->SetMargin($m1, $m2, $m3, $m4);

        // get the data set
        foreach($xmlArr['DATASET']['DATA'] as $dtmp)
        {
            if ($xmlArr['DATASET']['DATA']['ATTRIBUTES'])
                $dtmp = $xmlArr['DATASET']['DATA'];
            $fieldName = $dtmp["ATTRIBUTES"]["FIELD"];
            if ($fieldName)
                $fields[$fieldName] = $fieldName;
        }

        $labelFld = $xmlArr['XAXIS']['ATTRIBUTES']['LABELFIELD'];

        $recArray = &$this->getPlotData($bizObj, $fields, $labelFld);

        $i = 0;
        foreach($xmlArr['DATASET']['DATA'] as $dtmp)
        {
            if ($xmlArr['DATASET']['DATA']['ATTRIBUTES'])
                $dtmp = $xmlArr['DATASET']['DATA'];
            $data = $recArray[$dtmp["ATTRIBUTES"]["FIELD"]];
            $plot = $this->renderXYPlot($data, $dtmp);
            if ($plot)
                $graph->Add($plot);
            $i++;
        }

        // render titles
        $graph->title->Set($xmlArr['TITLE']['ATTRIBUTES']['CAPTION']);
        $this->_drawString($graph->title,$xmlArr['TITLE']['ATTRIBUTES']['FONT'],$xmlArr['TITLE']['ATTRIBUTES']['COLOR']);

        // render xaxis
        $this->_drawAxis($graph->xaxis, $recArray[$labelFld],
                $xmlArr['XAXIS']['ATTRIBUTES']['FONT'], $xmlArr['XAXIS']['ATTRIBUTES']['COLOR'],
                $xmlArr['XAXIS']['ATTRIBUTES']['LABELANGLE'], $xmlArr['XAXIS']['ATTRIBUTES']['TITLE'],
                $xmlArr['XAXIS']['ATTRIBUTES']['TITLEFONT'], $xmlArr['XAXIS']['ATTRIBUTES']['TITLECOLOR'],
                $xmlArr['XAXIS']['ATTRIBUTES']['TITLEMARGIN']);
        // render yaxis
        $this->_drawAxis($graph->yaxis, null,
                $xmlArr['YAXIS']['ATTRIBUTES']['FONT'], $xmlArr['YAXIS']['ATTRIBUTES']['COLOR'],
                $xmlArr['YAXIS']['ATTRIBUTES']['LABELANGLE'], $xmlArr['YAXIS']['ATTRIBUTES']['TITLE'],
                $xmlArr['YAXIS']['ATTRIBUTES']['TITLEFONT'], $xmlArr['YAXIS']['ATTRIBUTES']['TITLECOLOR'],
                $xmlArr['YAXIS']['ATTRIBUTES']['TITLEMARGIN']);

        // render legend
        $this->_drawLegend($graph->legend,$xmlArr['LAGEND']['ATTRIBUTES']['POSITION'],
                $xmlArr['LAGEND']['ATTRIBUTES']['LAYOUT'], $xmlArr['legend']['ATTRIBUTES']['FONT'],
                $xmlArr['LAGEND']['ATTRIBUTES']['COLOR'], $xmlArr['legend']['ATTRIBUTES']['FILLCOLOR']);
        $graph->Stroke();
    }

    /**
     * draw the Pie type graph (can have 1 pie plot)
     *
     * @param BizObj $bizObj object reference of bizobj
     * @param array $xmlArr xml array reference
     * @return void
     */
    public function pieGraphRender(&$bizObj, &$xmlArr)
    {
        include_once (JPGRAPH_DIR.'/jpgraph.php');
        include_once (JPGRAPH_DIR.'/jpgraph_pie.php');
        include_once (JPGRAPH_DIR.'/jpgraph_pie3d.php');

        $graph = new PieGraph($xmlArr["ATTRIBUTES"]["WIDTH"],$xmlArr["ATTRIBUTES"]["HEIGHT"]);
        //$graph->SetAntiAliasing();

        // get the data set - only support one data
        $fields[0] = $xmlArr['DATASET']['DATAPIE']["ATTRIBUTES"]["FIELD"];
        $legendFld = $xmlArr['DATASET']['DATAPIE']["ATTRIBUTES"]["LEGENDFIELD"];

        $recArray = &$this->getPlotData($bizObj, $fields, $legendFld);

        $chartData = $xmlArr['DATASET']['DATAPIE'];
        $plot = $this->renderPiePlot($recArray[$fields[0]], $chartData);
        $plot->SetLegends($recArray[$legendFld]);
        $graph->Add($plot);

        // render titles
        $graph->title->Set($xmlArr['TITLE']['ATTRIBUTES']['CAPTION']);
        $this->_drawString($graph->title,$xmlArr['TITLE']['ATTRIBUTES']['FONT'],$xmlArr['TITLE']['ATTRIBUTES']['COLOR']);

        // render legend
        $this->_drawLegend($graph->legend,$xmlArr['LEGEND']['ATTRIBUTES']['POSITION'],
                $xmlArr['LEGEND']['ATTRIBUTES']['LAYOUT'], $xmlArr['LEGEND']['ATTRIBUTES']['FONT'],
                $xmlArr['LEGEND']['ATTRIBUTES']['COLOR'], $xmlArr['LEGEND']['ATTRIBUTES']['FILLCOLOR']);
        $graph->Stroke();
    }

    /**
     * Draw the XY type plot
     *
     * @param array $data plot data array reference
     * @param array $xmlArr xml array reference
     * @return object refernce XY plot object reference
     */
    public function renderXYPlot(&$data, &$xmlArr)
    {
        $id = $xmlArr['ATTRIBUTES']['ID'];
        $field = $xmlArr['ATTRIBUTES']['FIELD'];
        $chartType = $xmlArr['ATTRIBUTES']['CHARTTYPE'];
        $pointType = $xmlArr['ATTRIBUTES']['POINTTYPE'];
        $weight = $xmlArr['ATTRIBUTES']['WEIGHT'];
        $color = $xmlArr['ATTRIBUTES']['COLOR'];
        $fillColor = $xmlArr['ATTRIBUTES']['FILLCOLOR'];
        $showVal = $xmlArr['ATTRIBUTES']['SHOWVALUE'];
        $legend = $xmlArr['ATTRIBUTES']['LEGENDFIELD'];
        $visible = $xmlArr['ATTRIBUTES']['VISIBLE'];

        if ($chartType == 'Line' or $chartType == 'Bar')
        {
            if ($chartType == 'Line')
            {
                include_once (JPGRAPH_DIR.'/jpgraph_line.php');
                $plot = new LinePlot($data);
                $this->_drawMark($plot->mark,
                        $xmlArr['POINTMARK']['ATTRIBUTES']['TYPE'], $xmlArr['POINTMARK']['ATTRIBUTES']['COLOR'],
                        $xmlArr['POINTMARK']['ATTRIBUTES']['FILLCOLOR'], $xmlArr['POINTMARK']['ATTRIBUTES']['SIZE']);
                $plot->SetBarCenter();
                $plot->SetCenter();
            }
            else if ($chartType == 'Bar')
            {
                include_once (JPGRAPH_DIR.'/jpgraph_bar.php');
                $plot = new BarPlot($data);
                $plot->SetAlign('center');
            }
            if ($color) $plot->SetColor($color);
            if ($fillColor) $plot->SetFillColor($fillColor);
            if ($weight) $plot->SetWeight($weight);
            if ($showVal == 1) $plot->value->Show();
            if ($legend) $plot->SetLegend($legend);
            $this->_drawString($plot->value,$xmlArr['VALUE']['ATTRIBUTES']['FONT'],$xmlArr['VALUE']['ATTRIBUTES']['COLOR']);
        }

        if ($chartType == 'GroupBar' or $chartType == 'AccBar')
        {
            $children = $xmlArr['ATTRIBUTES']['CHILDREN'];
            $childList = explode(",",$children);
            foreach($childList as $child)
            {
                $childPlotList[] = $this->plotList[$child];
            }
            if ($chartType == 'GroupBar')
                $plot = new GroupBarPlot($childPlotList);
            else if ($chartType == 'AccBar')
                $plot = new AccBarPlot($childPlotList);
        }

        $this->plotList[$id] = $plot;

        if ($visible == 1)
            return $plot;
        return null;
    }

    /**
     * chartService::renderPiePlot() - draw the Pie type plot
     *
     * @param array $data plot data array reference
     * @param array $xmlArr xml array reference
     * @return object refernce Pie plot object reference
     */
    public function renderPiePlot(&$data, &$xmlArr)
    {
        $id = $xmlArr['ATTRIBUTES']['ID'];
        $field = $xmlArr['ATTRIBUTES']['FIELD'];
        $chartType = $xmlArr['ATTRIBUTES']['CHARTTYPE'];
        $size = $xmlArr['ATTRIBUTES']['SIZE'];
        $center = $xmlArr['ATTRIBUTES']['CENTER'];
        $height = $xmlArr['ATTRIBUTES']['HEIGHT'];
        $angle = $xmlArr['ATTRIBUTES']['ANGLE'];
        $labelPos = $xmlArr['ATTRIBUTES']['LABELPOS'];
        $legendField = $xmlArr['ATTRIBUTES']['LAGENDFIELD'];

        if ($chartType == "Pie")
        {
            $plot = new PiePlot($data);
            $plot->SetLabelPos($labelPos);
        }
        else if ($chartType == "Pie3D")
        {
            $plot = new PiePlot3D($data);
            $plot->SetHeight($height);
            $plot->SetAngle($angle);
        }
        list($c1, $c2) = explode(',', $center);
        $plot->SetCenter($c1,$c2);
        $plot->SetSize($size);

        $this->_drawString($plot->value,$xmlArr['VALUE']['ATTRIBUTES']['FONT'],$xmlArr['VALUE']['ATTRIBUTES']['COLOR']);

        return $plot;
    }

    /**
     * draw string
     *
     * @param object $g plot object reference
     * @access private
     * @return void
     */
    private function _drawString(&$g, $font=null, $color=null)
    {
        if ($font)
        {
            list($ft,$fs,$size) = explode(",",$font);
            $g->SetFont($this->_getFont($ft),$this->_getFontStyle($fs),$size);
        }
        if ($color) $g->SetColor($color);
    }

    /**
     * Draw legend
     *
     * @param object $g plot object reference
     * @access private
     * @return void
     */
    private function _drawLegend(&$g, $pos, $layout, $font, $color, $fcolor)
    {
        $this->_drawString($g,$font,$color);
        if ($fcolor) $g->SetFillColor($fcolor);
        if ($pos)
        {
            list($x,$y,$hap,$vap) = explode(",",$pos);
            $g->SetPos($x,$y,$hap,$vap);
        }
        if ($layout && $layout == 'HOR')
        {
            $g->SetLayout(LEGEND_HOR);
        }
    }

    /**
     * Draw Axis (legend?)
     *
     * @param object $g plot object reference
     * @access private
     * @return void
     */
    private function _drawAxis(&$g, $labels, $font, $color, $labelAng, $title, $titleFont, $titleColor, $titleMargin)
    {
        $this->_drawString($g,$font, $color);
        if ($title) $g->title->Set($title);
        $this->_drawString($g->title,$titleFont, $titleColor);
        if ($labels) $g->SetTickLabels($labels);
        if ($labelAng) $g->SetLabelAngle($labelAng);
        if ($titleMargin) $g->SetTitleMargin($titleMargin);
    }

    /**
     * Draw mark
     *
     * @param object $g plot object reference
     * @access private
     * @return void
     */
    private function _drawMark(&$g, $type, $color, $fcolor, $size)
    {
        if ($type) $g->SetType($this->_getMark($type));
        if ($color) $g->SetColor($color);
        if ($fcolor) $g->SetFillColor($fcolor);
        if ($size) $g->SetSize($size);
    }

    /**
     * Get the point make number
     *
     * @param string $mark point mark string
     * @access private
     * @return integer mark number
     */
    private function _getMark($mark)
    {
        switch (strtoupper($mark))
        {
            case "SQUARE": return MARK_SQUARE;
            case "UTRIANGLE": return MARK_UTRIANGLE;
            case "DTRIANGLE": return MARK_DTRIANGLE;
            case "DIAMOND": return MARK_DIAMOND;
            case "CIRCLE": return MARK_CIRCLE;
            case "FILLEDCIRCLE": return MARK_FILLEDCIRCLE;
            case "CROSS": return MARK_CROSS;
            case "STAR": return MARK_STAR;
            case "X": return MARK_X;
            default: return 0;
        }
    }

    /**
     * Get the font number
     *
     * @param string $font font string
     * @access private
     * @return integer font number
     */
    private function _getFont($font)
    {
        switch (strtoupper($font))
        {
            case "ARIAL": return FF_ARIAL;
            case "COURIER;": return FF_COURIER;
            case "TIMES": return FF_TIMES;
            case "VERDANA": return FF_VERDANA;
            case "COMIC": return FF_COMIC;
            case "GEORGIA": return FF_GEORGIA;
            default: return FF_FONT1;
        }
    }

    /**
     * Get the font style number
     *
     * @param string $fontStyle font style string
     * @access private
     * @return integer font style number
     */
    private function _getFontStyle($fontStyle)
    {
        switch (strtoupper($fontStyle))
        {
            case "NORMAL": return FS_NORMAL;
            case "BOLD": return FS_BOLD;
            case "ITALIC": return FS_ITALIC;
            case "BOLDITALIC": return FS_BOLDITALIC;
            default: return FS_NORMAL;
        }
    }
}

?>


<?php

/**
 * Instaphp
 *
 * Copyright (c) 2011 randy sesser <randy@instaphp.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author randy sesser <randy@instaphp.com>
 * @copyright 2011, randy sesser
 * @license http://www.opensource.org/licenses/mit-license The MIT License
 * @package Instaphp
 * @filesource
 */

namespace Instaphp;

/**
 * A simple base class used to instantiate the various other API classes
 * @package Instaphp
 * @version 1.0
 * @author randy sesser <randy@instaphp.com>
 */
class Instaphp
{

    /**
     * @var Users
     * @access public
     */
    public $Users = null;
    /**
     * @var Media
     * @access public
     */
    public $Media = null;
    /**
     * @var Tags
     * @access public
     */
    public $Tags = null;
    /**
     * @var Locations
     */
    public $Locations = null;

    /**
     * Contains the last API url called
     *
     * @var string
     **/
    public $url = null;

    public $configDefaults = array(
      'version'=> 'v1',
      'endpoint'=> 'https://api.instagram.com',
      'endpoint_timeout'=> '10',
      'client_id'=> null,
      'client_secret'=> null,
      'oauth_path'=> '/oauth/authorize/?client_id={client_id}&response_type=code&redirect_uri={redirect_uri}',
      'oauth_token_path'=> 'oauth/access_token',
      'redirect_uri'=> '',
    );

    public $config;

    private static $instance = null;
    /**
     * The constructor constructs, but only for itself
     */
    final private function __construct($token = null, $config = array())
    {
        $config = array_merge($this->configDefaults, $config);
        self::parseConfigArray($config);

        $this->config = $config;

        $this->Users = new Instagram\Users($token, $config);
        $this->Media = new Instagram\Media($token, $config);
        $this->Tags = new Instagram\Tags($token, $config);
        $this->Locations = new Instagram\Locations($token, $config);
    }

    public static function parseConfigArray(&$config)
    {
        $path = $config['oauth_path'];
        $path = str_replace("{client_id}", $config['client_id'], $path);
        $path = str_replace("{redirect_uri}", urlencode($config['redirect_uri']), $path);

        if (!empty($config['scope'])){
            $path .= '&scope=' . $config['scope'];
        }

        $config['oauth_uri'] =  $config['endpoint'] . $path;

        $config['oauth_token_uri'] = $config['endpoint'] . $config['oauth_token_path'];
    }

    public function GetOAuthUri()
    {
        return $this->config['oauth_uri'];
    }

    /**
     * I AM SINGLETON
     * We don't need to go instantiating all these objects more than once here
     * @return Instaphp
     */
    public static function Instance($token = null, $config = array())
    {
        if (self::$instance == null || !empty($token)) {
            self::$instance = new self($token, $config);
        }
        return self::$instance;
    }
}


<?php

/**
 * Email [ MODEL ]
 * Modelo responável por configurar a SparkPost, validar os dados e disparar e-mails do sistema!
 *
 * @copyright (c) 2018, Edinei J. Bauer
 */

namespace EmailControl;

use Helpers\Check;
use Helpers\DateTime;
use Helpers\Template;
use SparkPost\SparkPost;
use GuzzleHttp\Client;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;

class EmailSparkPost
{
    private $assunto;
    private $mensagem;
    private $html;
    private $destinatarioNome;
    private $destinatarioEmail;
    private $anexo;
    private $data;
    private $serverEmail;
    private $serverPassword;
    private $remetenteEmail;
    private $remetenteNome;
    private $replyToEmail;
    private $replyToNome;
    private $copyToEmail;
    private $copyToNome;
    private $library;
    private $template;
    private $result;

    public function __construct()
    {
        $this->remetenteNome = "Contato" . (defined('SITENAME') ? " " . SITENAME : "");
        $this->serverEmail = defined('EMAIL') ? EMAIL : "contato@uebster.com";
        $this->setRemetenteEmail($this->serverEmail);
        $this->assunto = "Contato através do site " . (defined('SITENAME') ? SITENAME : "");
        $this->mensagem = "";
        $this->html = "";
        $this->destinatarioNome = "";
        $this->destinatarioEmail = [];
    }

    /**
     * @param string $template
     * @param array $data
     */
    public function setTemplate(string $template, array $data = [])
    {
        $this->template = trim(strip_tags($template));
        if ($data)
            $this->data = $data;
    }

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

    /**
     * @param mixed $library
     */
    public function setLibrary($library)
    {
        $this->library = trim(strip_tags($library));
    }

    /**
     * @param mixed $assunto
     */
    public function setAssunto($assunto)
    {
        $this->assunto = trim(strip_tags($assunto));
    }

    /**
     * @param string $mensagem
     */
    public function setMensagem(string $mensagem)
    {
        $this->mensagem = trim(strip_tags($mensagem));
        if (empty($this->html))
            $this->html = $this->mensagem;
    }

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

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

    /**
     * @param string $nome
     */
    public function setDestinatarioNome(string $nome)
    {
        $this->destinatarioNome = trim(strip_tags($nome));
    }

    /**
     * @param string|array $email
     */
    public function setDestinatarioEmail($email)
    {
        if (!empty($email)) {
            if (is_array($email)) {
                if(isset($email['email'])){
                    if (!empty($email['name'])) {
                        $this->destinatarioEmail[] = ['address' => [
                            'name' => trim(strip_tags($email['name'])),
                            'email' => trim($email['email'])
                        ]];
                    } else {
                        $this->destinatarioEmail[] = ['address' => ['name' => $this->prepareNameFromEmail($email['email']), 'email' => trim($email['email'])]];
                    }
                } else {
                    foreach ($email as $item) {
                        if (is_array($item) && !empty($item['email']) && Check::email($item['email'])) {
                            if (!empty($item['name'])) {
                                $this->destinatarioEmail[] = ['address' => [
                                    'name' => trim(strip_tags($item['name'])),
                                    'email' => trim(strip_tags($item['email']))
                                ]];
                            } else {
                                $this->destinatarioEmail[] = ['address' => ['email' => trim($item['email'])]];
                            }
                        } elseif (is_string($item) && Check::email($item)) {
                            $this->destinatarioEmail[] = ['address' => ['name' => $this->prepareNameFromEmail($item), 'email' => trim($item)]];
                        }
                    }
                }
            } elseif (is_string($email) && Check::email($email)) {
                $this->destinatarioEmail[] = ['address' => ['name' => $this->prepareNameFromEmail($email), 'email' => trim($email)]];
            }
        }
    }

    /**
     * @param string $emailRemetente
     */
    public function setRemetenteEmail(string $emailRemetente)
    {
        $this->remetenteEmail = trim(strip_tags($emailRemetente));
    }

    /**
     * @param string $nomeRemetente
     */
    public function setRemetenteNome(string $nomeRemetente)
    {
        $this->remetenteNome = trim(strip_tags($nomeRemetente));
    }

    /**
     * @param string $copyToEmail
     */
    public function setCopyToEmail(string $copyToEmail)
    {
        $this->copyToEmail = trim(strip_tags($copyToEmail));
    }

    /**
     * @param string $copyToNome
     */
    public function setCopyToNome(string $copyToNome)
    {
        $this->copyToNome = trim(strip_tags($copyToNome));
    }

    /**
     * @param string $replyToEmail
     */
    public function setReplyToEmail(string $replyToEmail)
    {
        $this->replyToEmail = trim(strip_tags($replyToEmail));
    }

    /**
     * @param string $replyToNome
     */
    public function setReplyToNome(string $replyToNome)
    {
        $this->replyToNome = trim(strip_tags($replyToNome));
    }

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

    public function setAnexo($file, $name)
    {
        $this->anexo[$file] = $name;
    }

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

    /**
     * @param mixed $email
     */
    public function enviar($email = null)
    {
        if (defined("EMAILKEY") && !empty(EMAILKEY) && (!empty($this->mensagem) || !empty($this->template) || !empty($this->html))) {
            try {
                if (!empty($email))
                    $this->setDestinatarioEmail(!empty($this->destinatarioNome) ? ['name' => $this->destinatarioNome, 'email' => $email] : $email);

                if(!empty($this->destinatarioEmail)) {
                    $this->html = !empty($this->html) ? $this->html : (!empty($this->template) ? $this->getTemplateData($this->template) : $this->turnMensagemIntoEmail());

                    $httpClient = new GuzzleAdapter(new Client());
                    $sparky = new SparkPost($httpClient, ['key' => EMAILKEY]);
                    $sparky->setOptions(['async' => false]);

                    $results = $sparky->transmissions->post([
                        'content' => [
                            'from' => ['name' => $this->remetenteNome, 'email' => $this->remetenteEmail],
                            'subject' => $this->assunto,
                            'html' => $this->html
                        ],
                        'recipients' => $this->destinatarioEmail
                    ]);
                }

            } catch (\Exception $e) {
                $this->result = 'Erro ao enviar';
            }
        } else {
            if (defined("EMAILKEY") && !empty(EMAILKEY))
                $this->result = "Conteúdo do email não definido, informe uma mensagem ou template pré-definido";
            else
                $this->result = "Key de SparkPost não informado nas configurações.";
        }
    }

    /*
     * ***************************************
     * **********  PRIVATE METHODS  **********
     * ***************************************
     */

    /**
     * Retorna estrutura HTML default com mensagem
     * @param string $template
     * @return string
     */
    private function getTemplateData(string $template)
    {
        switch ($template) {
            case "password":
                $this->assunto = "Recuperação de Senha";
                break;
        }

        $tpl = new Template($this->library ?? "email-control");
        return $tpl->getShow($template, $this->getData());
    }

    /**
     * Retorna estrutura HTML default com mensagem
     * @return string
     */
    private function turnMensagemIntoEmail()
    {
        $tpl = new Template("email-control");
        $data = $this->getData();
        $data['email_header'] = $tpl->getShow("model/header", $data);
        $data['email_footer'] = $tpl->getShow("model/footer", $data);
        $data['email_content'] = $tpl->getShow("model/container", $data);

        return $tpl->getShow("model/base", $data);
    }

    /**
     * Retorna dados padrão para passar para templates
     * @return array
     */
    private function getData(): array
    {
        list($color, $background) = $this->getColorTheme();
        $date = new DateTime();
        $data = [
            "assunto" => $this->assunto,
            "mensagem" => $this->mensagem,
            "email" => $this->destinatarioEmail,
            "nome" => $this->destinatarioNome,
            "remetente" => $this->remetenteEmail,
            "remetenteNome" => $this->remetenteNome,
            "sitename" => defined('SITENAME') ? SITENAME : "",
            "home" => defined('HOME') ? HOME : "",
            "sitedesc" => defined('SITEDESC') ? SITEDESC : "",
            "sitesub" => defined('SITESUB') ? SITESUB : "",
            "logo" => defined('LOGO') ? HOME . LOGO : "",
            "favicon" => defined('FAVICON') ? HOME . FAVICON : "",
            "date" => $date->getDateTime(date("Y-m-d H:i:s"), 'd/m/Y H:i'),
            "footerColor" => "dddddd",
            "headerColor" => $color,
            "headerBackground" => $background
        ];

        return !empty($this->data) ? array_merge($this->data, $data) : $data;
    }

    /**
     * Retorna um nome a partir do email
     * @param string $email
     * @return string
     */
    private function prepareNameFromEmail(string $email): string
    {
        return ucwords(str_replace(['.', '_'], ' ', explode('@', $email)[0]));
    }

    private function getColorTheme()
    {
        if (file_exists(PATH_HOME . "public/assets/theme.min.css")) {
            $theme = file_get_contents(PATH_HOME . "public/assets/theme.min.css");
            $theme = explode('.theme{', $theme)[1];
            $color = trim(explode('!important', explode('color:', $theme)[1])[0]);
            $backgroun = trim(explode('!important', explode('background-color:', $theme)[1])[0]);
            return [$color, $backgroun];
        }

        return ["#111", "70bbd9"];
    }
}


<?php

namespace Interpro\QuickStorage;

use Illuminate\Bus\Dispatcher;
use Illuminate\Support\ServiceProvider;

class QuickStorageServiceProvider extends ServiceProvider {

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot(Dispatcher $dispatcher)
    {
        //Publishes package config file to applications config folder
        $this->publishes([__DIR__.'/Laravel/config/qstorage.php' => config_path('qstorage.php')]);

        $this->publishes([
            __DIR__.'/Laravel/migrations' => $this->app->databasePath().'/migrations'
        ], 'migrations');

        //Карта для поиска хэндлеров команд
        $dispatcher->maps([
            'Interpro\QuickStorage\Concept\Command\CreateGroupItemCommand' => 'Interpro\QuickStorage\Laravel\Handle\CreateGroupItemCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\UpdateGroupItemCommand' => 'Interpro\QuickStorage\Laravel\Handle\UpdateGroupItemCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\DeleteGroupItemCommand' => 'Interpro\QuickStorage\Laravel\Handle\DeleteGroupItemCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\ReinitGroupCommand'     => 'Interpro\QuickStorage\Laravel\Handle\ReinitGroupCommandHandler@handle',

            'Interpro\QuickStorage\Concept\Command\InitAllBlockCommand' => 'Interpro\QuickStorage\Laravel\Handle\InitAllBlockCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\InitOneBlockCommand' => 'Interpro\QuickStorage\Laravel\Handle\InitOneBlockCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\UpdateBlockCommand'  => 'Interpro\QuickStorage\Laravel\Handle\UpdateBlockCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\ReinitOneBlockCommand'  => 'Interpro\QuickStorage\Laravel\Handle\ReinitOneBlockCommandHandler@handle',

            'Interpro\QuickStorage\Concept\Command\Image\RefreshAllGroupImageCommand' => 'Interpro\QuickStorage\Laravel\Handle\Image\RefreshAllGroupImageCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Image\RefreshBlockImageCommand'    => 'Interpro\QuickStorage\Laravel\Handle\Image\RefreshBlockImageCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Image\RefreshOneGroupImageCommand' => 'Interpro\QuickStorage\Laravel\Handle\Image\RefreshOneGroupImageCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Image\UpdateAllGroupImageCommand'  => 'Interpro\QuickStorage\Laravel\Handle\Image\UpdateAllGroupImageCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Image\UpdateBlockImageCommand'     => 'Interpro\QuickStorage\Laravel\Handle\Image\UpdateBlockImageCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Image\UpdateOneGroupImageCommand'  => 'Interpro\QuickStorage\Laravel\Handle\Image\UpdateOneGroupImageCommandHandler@handle',

            'Interpro\QuickStorage\Concept\Command\Crop\InitAllBlockCropCommand'     => 'Interpro\QuickStorage\Laravel\Handle\Crop\InitAllBlockCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\InitGroupCropCommand'        => 'Interpro\QuickStorage\Laravel\Handle\Crop\InitGroupCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\InitOneBlockCropCommand'     => 'Interpro\QuickStorage\Laravel\Handle\Crop\InitOneBlockCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\InitOneGroupCropCommand'     => 'Interpro\QuickStorage\Laravel\Handle\Crop\InitOneGroupCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\RefreshAllGroupCropCommand'  => 'Interpro\QuickStorage\Laravel\Handle\Crop\RefreshAllGroupCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\RefreshBlockCropCommand'     => 'Interpro\QuickStorage\Laravel\Handle\Crop\RefreshBlockCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\RefreshOneGroupCropCommand'  => 'Interpro\QuickStorage\Laravel\Handle\Crop\RefreshOneGroupCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\UpdateBlockCropCommand'      => 'Interpro\QuickStorage\Laravel\Handle\Crop\UpdateBlockCropCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Crop\UpdateOneGroupCropCommand'   => 'Interpro\QuickStorage\Laravel\Handle\Crop\UpdateOneGroupCropCommandHandler@handle',

            'Interpro\QuickStorage\Concept\Command\Flat\UpdateBlockFlatCommand'      => 'Interpro\QuickStorage\Laravel\Handle\Flat\UpdateBlockFlatCommandHandler@handle',
            'Interpro\QuickStorage\Concept\Command\Flat\UpdateGroupItemFlatCommand'  => 'Interpro\QuickStorage\Laravel\Handle\Flat\UpdateGroupItemFlatCommandHandler@handle'
        ]);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(
            'Interpro\QuickStorage\Concept\QSource',
            'Interpro\QuickStorage\Laravel\QSource'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\FieldProviding\FieldExtMediator',
            'Interpro\QuickStorage\Laravel\FieldProviding\FieldExtMediator'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\FieldProviding\FieldSaveMediator',
            'Interpro\QuickStorage\Laravel\FieldProviding\FieldSaveMediator'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\Repository',
            'Interpro\QuickStorage\Laravel\Repository'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\CropRepository',
            'Interpro\QuickStorage\Laravel\CropRepository'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\ImageRepository',
            'Interpro\QuickStorage\Laravel\ImageRepository'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\StorageStructure',
            'Interpro\QuickStorage\Laravel\StorageStructure'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\Sorting\GroupSortingSet',
            'Interpro\QuickStorage\Laravel\Sorting\GroupSortingSet'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\Specification\GroupSpecificationSet',
            'Interpro\QuickStorage\Laravel\Specification\GroupSpecificationSet'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\Param\GroupParam',
            'Interpro\QuickStorage\Laravel\Param\GroupParam'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\QueryAgent',
            'Interpro\QuickStorage\Laravel\QueryAgent'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\PaginalQueryAgent',
            'Interpro\QuickStorage\Laravel\PaginalQueryAgent'
        );

        $this->app->singleton(
            'Interpro\QuickStorage\Concept\JSONQueryAgent',
            'Interpro\QuickStorage\Laravel\JSONQueryAgent'
        );

        // Let Laravel Ioc Container know about our Controller
        $this->app->make('Interpro\QuickStorage\Laravel\Http\AdminCreateController');
        $this->app->make('Interpro\QuickStorage\Laravel\Http\AdminUpdateController');
        $this->app->make('Interpro\QuickStorage\Laravel\Http\AdminDeleteController');
        $this->app->make('Interpro\QuickStorage\Laravel\Http\ImageFileController');
        $this->app->make('Interpro\QuickStorage\Laravel\Http\AdminCropImageController');

        include __DIR__ . '/Laravel/Http/routes.php';
    }

}


<?php

namespace WobbleCode\ManagerBundle\Traits\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

trait Attributable
{
    /**
     * Example of schema
     *
     *     {
     *       "intercom": {
     *         "id": "23"
     *       }
     *     }
     *
     * @ODM\Hash
     */
    protected $attributes = [];

    /**
     * Set attributes
     *
     * @param array $attributes
     * @return self
     */
    public function setAttributes($attributes)
    {
        $this->attributes = $attributes;
        return $this;
    }

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

    /**
     * Set attribute
     *
     * @param string $key
     * @param mixed $attributes
     *
     * @return self
     */
    public function setAttribute($key, $data)
    {
        $this->attributes[$key] = $data;

        return $this;
    }

    /**
     * Get attribute by key
     *
     * @param string $group
     *
     * @return array
     */
    public function getAttribute($key)
    {
        if (isset($this->attributes[$key])) {
            return $this->attributes[$key];
        }

        return null;
    }

    /**
     * Set attributes by group and key
     *
     * @param string $group
     * @param string $key
     * @param array $attributes
     *
     * @return self
     */
    public function setAttributeInGroup($group, $key, $value)
    {
        $this->attributes[$group][$key] = $value;

        return $this;
    }

    /**
     * Get attribute by group and key. It will return null if doesn't exists
     *
     * @param array $group
     * @param string $key
     *
     * @return string|null
     */
    public function getAttributeInGroup($group, $key)
    {
        if (isset($this->attributes[$group][$key])) {
            return $this->attributes[$group][$key];
        }

        return null;
    }
}


<?php namespace FelipeeDev\Utilities\Eloquent;

use FelipeeDev\Utilities\DependenciesTrait;
use Illuminate\Database\Eloquent\Model;

/**
 * ModelRepository Overview
 * ========================
 * Base model's repository utilities wrapper.
 *
 * Class containing the following trait should have declared `model` field with is an:
 * `\Illuminate\Database\Eloquent\Model`
 * reference.
 *
 * @property   Model model
 */
abstract class ModelRepository
{
    use DependenciesTrait;

    protected $dependencies = [];

    /**
     * Find a model by its primary key.
     *
     * @param int $id
     * @param array $columns
     * @return Model|null
     */
    public function find($id, array $columns = ['*'])
    {
        return $this->query()->find($id, $columns);
    }

    /**
     * Find a model by its primary key. If not then ne instance is being created.
     *
     * @param int $id
     * @param array $columns
     * @return Model
     */
    public function findOrCreate($id, array $columns = ['*'])
    {
        $model = $this->query()->find($id, $columns);
        if (!$model) {
            return $this->getModel()->newInstance();
        }

        return $model;
    }

    /**
     * Alias of findOrCreate.
     *
     * @param int $id
     * @param array $columns
     * @return Model
     */
    public function findOrNew($id, array $columns = ['*'])
    {
        return $this->findOrCreate($id, $columns);
    }

    /**
     * Find a many models by its primary keys.
     *
     * @param array $ids
     * @param array $columns
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function findMany(array $ids, array $columns = ['*'])
    {
        return $this->query()->findMany($ids, $columns);
    }

    /**
     * Find a model by its primary key. If not then exception is being handle.
     *
     * @param int $id
     * @param array $columns
     * @return Model
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function findOrFail($id, array $columns = ['*'])
    {
        return $this->query()->findOrFail($id, $columns);
    }

    /**
     * Get all result.
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function get()
    {
        return $this->query()->get();
    }

    /**
     * Alias of a get method.
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function all()
    {
        return $this->get();
    }

    /**
     * Creates model's new instance.
     *
     * @param array $data
     * @param bool $exists
     * @return Model $model
     */
    public function newInstance(array $data = [], $exists = false)
    {
        return $this->getModel()->newInstance($data, $exists);
    }

    /**
     * Get repository model's instance.
     *
     * @return Model
     *
     * @throws Exceptions\NoModelSetException
     */
    public function getModel()
    {
        if (!$this->hasDependency('model') && !$this->model instanceof Model) {
            throw new Exceptions\NoModelSetException;
        }

        return $this->model;
    }

    /**
     * Get name of a class.
     *
     * @return string
     */
    public function getModelClass()
    {
        return get_class($this->getModel());
    }

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

    /**
     * Gets new Eloquent model's query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return $this->getModel()->newQuery();
    }

    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function baseQuery()
    {
        return $this->query()->getQuery();
    }
}


<?php
/**
 * @author awan <nawa@yahoo.com>
 * @license GPL-3.0+
 * @version 1.0
 */
namespace Pentagonal\Hookable;

/**
 * Class Hookable
 * @license  Follow WordPress GPL-3.0+
 * @see  {@link: https://wordpress.org/license} for more related WordPress License
 * @package Pentagonal\Hookable
 */
class Hookable
{
    /**
     * Merged Hooks Records
     * @var array
     */
    protected $merged = array();

    /**
     * Current Hooks Record
     * @var array
     */
    protected $current = array();

    /**
     * Actions Records
     * @var array
     */
    protected $actions = array();

    /**
     * Filter Records
     * @var array
     */
    protected $filters = array();

    /**
     * PHP5 Constructor
     */
    public function __construct()
    {
    }

    /**
     * Create Unique ID if function is not string
     *
     * @param string   $hookName determine the hook name
     * @param callable $function function to call
     * @param integer  $priority the priority of hooks
     *
     * @access private
     * @return string|bool
     */
    private function uniqueId($hookName, $function, $priority)
    {
        static $count = 0;
        if (is_string($function)) {
            return $function;
        }
        if (is_object($function)) {
            // Closures are currently implemented as objects
            $function = array($function, '');
        } elseif (!is_array($function)) {
            $function = array($function);
        }

        if (is_object($function[0])) {
            // Object Class Calling
            if (function_exists('spl_object_hash')) {
                return spl_object_hash($function[0]) . $function[1];
            } else {
                $object_id = get_class($function[0]).$function[1];
                if (!isset($function[0]->id)) {
                    if (false === $priority) {
                        return false;
                    }
                    $object_id .= isset($this->filters[$hookName][$priority])
                        ? count((array) $this->filters[$hookName][$priority])
                        : $count;
                    $function[0]->id = $count;
                    $count++;
                } else {
                    $object_id .= $function[0]->id;
                }
                return $object_id;
            }
        } elseif (is_string($function[0])) {
            // callas static
            return $function[0] . '::' . $function[1];
        }
        // unexpected result
        return null;
    }

    /**
     * Call the 'all' hook, which will process the functions hooked into it.
     *
     * The 'all' hook passes all of the arguments or parameters that were used for
     * the hook, which this function was called for.
     *
     * Inherited docs from WordPress :
     * -------------------------------
     * This function is used internally for apply_filters(), do_action(), and
     * do_action_ref_array() and is not meant to be used from outside those
     * functions. This function does not check for the existence of the all hook, so
     * it will fail unless the all hook exists prior to this function call.
     *
     * @access private
     * @param array $args The collected parameters from the hook that was called.
     */
    private function callAll($args)
    {
        if (isset($this->filters['all'])) {
            reset($this->filters['all']);
            do {
                foreach ((array) current($this->filters['all']) as $fn_arr) {
                    if (!is_null($fn_arr['function'])) {
                        call_user_func_array($fn_arr['function'], $args);
                    }
                }
            } while (next($this->filters['all']) !== false);
        }
    }

    /**
     * Sanitize keyname that must be as string and not empty
     *
     * @param string $key
     *
     * @return bool|string
     */
    public function sanitize($key)
    {
        if (is_string($key) && trim($key)) {
            return trim($key);
        }
        return false;
    }

    /**
     * Add Hooks Function it just like a WordPress add_action() / add_filter() hooks
     *
     * @param string    $hookName            Hook Name
     * @param Callable  $callable            Callable
     * @param integer   $priority            priority
     * @param integer   $accepted_args       num count of accepted args / parameter
     *
     * @return boolean
     * @throws \Exception
     */
    public function add($hookName, $callable, $priority = 10, $accepted_args = 1)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName) {
            throw new \Exception("Invalid Hook Name Specified", E_USER_ERROR);
        }

        $id = $this->uniqueId($hookName, $callable, $priority);
        if ($id === null) {
            throw new \Exception(
                sprintf("Invalid callable specified on hook name %s", $hookName),
                E_USER_ERROR
            );
        }

        $hook_list = $this->filters;
        $hook_list[$hookName][$priority][$id] = array(
            'function' => $callable,
            'accepted_args' => $accepted_args
        );
        $this->filters = array_merge($this->filters, $hook_list);
        unset($this->merged[$hookName]);
        return true;
    }

    /**
     * Appending Hooks Function, if hooks existor just append the hooks
     *
     * @param  string    $hookName            Hook Name
     * @param  Callable  $callable            Callable
     * @param  integer   $priority            priority
     * @param  integer   $accepted_args       num count of accepted args / parameter
     * @param  boolean   $create              true if want to create new if not exists
     *
     * @return boolean
     */
    public function append($hookName, $callable, $priority = 10, $accepted_args = 1, $create = true)
    {
        if ($create || ! $this->has($hookName, $callable)) {
            return $this->add($hookName, $callable, $priority, $accepted_args);
        }
        return false;
    }

    /**
     * Check if hook name exists
     *
     * @param  string      $hookName          Hook name
     * @param  string|mixed $function_to_check Specially Functions on Hook
     *
     * @return boolean|int
     */
    public function exists($hookName, $function_to_check = false)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName || !isset($this->filters[$hookName])) {
            return false;
        }
        // Don't reset the internal array pointer
        $has    = !empty($this->filters[$hookName]);
        // Make sure at least one priority has a filter callback
        if ($has) {
            $exists = false;
            foreach ($this->filters[$hookName] as $callbacks) {
                if (! empty($callbacks)) {
                    $exists = true;
                    break;
                }
            }

            if (! $exists) {
                $has = false;
            }
        }

        // recheck
        if (false === $function_to_check || false === $has) {
            return $has;
        }

        if (! $id = $this->uniqueId($hookName, $function_to_check, false)) {
            return false;
        }

        foreach (array_keys($this->filters[$hookName]) as $priority) {
            if (isset($this->filters[$hookName][$priority][$id])) {
                return $priority;
            }
        }

        return false;
    }

    /**
     * Check if hook name exists
     *
     * @param  string       $hookName              Hook name
     * @param  string|mixed $function_to_check     Specially Functions on Hook
     *
     * @return boolean
     */
    public function has($hookName, $function_to_check = false)
    {
        return $this->exists($hookName, $function_to_check) !== false;
    }

    /**
     * Applying Hooks for replaceable and returning as $value param
     *
     * @param  string $hookName Hook Name replaceable
     * @param  mixed $value     returning value
     *
     * @return mixed
     */
    public function apply($hookName, $value)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName) {
            return $value;
        }

        $args = array();
        // Do 'all' actions first.
        if (isset($this->filters['all'])) {
            $this->current[] = $hookName;
            $args = func_get_args();
            $this->callAll($args);
        }

        if (! isset($this->filters[$hookName])) {
            if (isset($this->filters['all'])) {
                array_pop($this->current);
            }
            return $value;
        }

        if (! isset($this->filters['all'])) {
            $this->current[] = $hookName;
        }

        // Sort.
        if (!isset($this->merged[$hookName])) {
            ksort($this->filters[$hookName]);
            $this->merged[$hookName] = true;
        }

        reset($this->filters[$hookName]);
        if (empty($args)) {
            $args = func_get_args();
        }
        do {
            foreach ((array) current($this->filters[$hookName]) as $fn_array) {
                if (!is_null($fn_array['function'])) {
                    $args[1] = $value;
                    $value = call_user_func_array(
                        $fn_array['function'],
                        array_slice($args, 1, (int) $fn_array['accepted_args'])
                    );
                }
            }
        } while (next($this->filters[$hookName]) !== false);

        array_pop($this->current);
        return $value;
    }

    /**
     * Call hook from existing declared hook record
     *
     * @param  string $hookName Hook Name
     * @param  string $arg      the arguments for next parameter
     *
     * @return boolean
     */
    public function call($hookName, $arg = '')
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName) {
            return false;
        }
        if (! isset($this->actions[$hookName])) {
            $this->actions[$hookName] = 1;
        } else {
            $this->actions[$hookName]++;
        }

        // Do 'all' actions first
        if (isset($this->filters['all'])) {
            $this->current[] = $hookName;
            $all_args = func_get_args();
            $this->callAll($all_args);
        }

        if (!isset($this->filters[$hookName])) {
            if (isset($this->filters['all'])) {
                array_pop($this->current);
            }
            return null;
        }

        if (!isset($this->filters['all'])) {
            $this->current[] = $hookName;
        }

        $args = array();
        if (is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0])) {
            // array(&$this)
            $args[] =& $arg[0];
        } else {
            $args[] = $arg;
        }

        for ($a = 2, $num = func_num_args(); $a < $num; $a++) {
            $args[] = func_get_arg($a);
        }
        // Sort
        if (!isset($this->merged[$hookName])) {
            ksort($this->filters[$hookName]);
            $this->merged[$hookName] = true;
        }
        reset($this->filters[$hookName]);
        do {
            foreach ((array) current($this->filters[$hookName]) as $the_) {
                if (!is_null($the_['function'])) {
                    call_user_func_array(
                        $the_['function'],
                        array_slice($args, 0, (int) $the_['accepted_args'])
                    );
                }
            }
        } while (next($this->filters[$hookName]) !== false);
        array_pop($this->current);

        return true;
    }

    /**
     * Replace Hooks Function, this will replace all existing hooks
     *
     * @param  string    $hookName            Hook Name
     * @param  string    $function_to_replace Function to replace
     * @param  Callable  $callable            Callable
     * @param  integer   $priority            priority
     * @param  integer   $accepted_args       num count of accepted args / parameter
     * @param  boolean   $create              true if want to create new if not exists
     *
     * @return boolean
     * @throws \Exception
     */
    public function replace(
        $hookName,
        $function_to_replace,
        $callable,
        $priority = 10,
        $accepted_args = 1,
        $create = true
    ) {
        $hookName = $this->sanitize($hookName);
        if (!$hookName) {
            throw new \Exception("Invalid Hook Name Specified", E_ERROR);
        }

        if (!is_callable($callable)) {
            throw new \Exception("Invalid Hook Callable Specified", E_ERROR);
        }

        if (($has = $this->has($hookName, $function_to_replace)) || $create) {
            $has && $this->remove($hookName, $function_to_replace);
            // add hooks first
            return $this->add($hookName, $callable, $priority, $accepted_args);
        }

        return false;
    }

    /**
     * Removing Hook (remove single hook)
     *
     * @param  string  $hookName           Hook Name
     * @param  string  $function_to_remove functions that to remove from determine $hookName
     * @param  integer $priority           priority
     *
     * @return boolean
     */
    public function remove($hookName, $function_to_remove, $priority = 10)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName) {
            return false;
        }
        $function_to_remove = $this->uniqueId($hookName, $function_to_remove, $priority);
        $r = isset($this->filters[$hookName][$priority][$function_to_remove]);
        if (true === $r) {
            unset($this->filters[$hookName][$priority][$function_to_remove]);
            if (empty($this->filters[$hookName][$priority])) {
                unset($this->filters[$hookName][$priority]);
            }
            if (empty($this->filters[$hookName])) {
                $this->filters[$hookName] = array();
            }
            unset($this->merged[$hookName]);
        }

        return $r;
    }

    /**
     * Remove all of the hooks from a filter.
     *
     * @param string   $hookName    The filter to remove hooks from.
     * @param int|bool $priority    Optional. The priority number to remove. Default false.
     *
     * @return boolean
     */
    public function removeAll($hookName, $priority = false)
    {
        if (isset($this->filters[$hookName])) {
            if (false === $priority) {
                $this->filters[$hookName] = array();
            } elseif (isset($this->filters[$hookName][$priority])) {
                $this->filters[$hookName][$priority] = array();
            }
        }
        unset($this->merged[$hookName]);
        return true;
    }

    /**
     * Current position
     *
     * @return string functions
     */
    public function current()
    {
        return end($this->current);
    }

    /**
     * Count all existences Hook
     *
     * @param string $hookName Hook name
     *
     * @return integer          Hooks Count
     */
    public function count($hookName)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName || !isset($this->filters[$hookName])) {
            return false;
        }
        return count((array) $this->filters[$hookName]);
    }

    /**
     * Check if hook has doing
     *
     * @param string $hookName Hook name
     *
     * @return boolean           true if has doing
     */
    public function isDo($hookName = null)
    {
        if (null === $hookName) {
            return ! empty($this->current);
        }

        $hookName = $this->sanitize($hookName);
        return $hookName && in_array($hookName, $this->current);
    }

    /**
     * Check if action hook as execute
     *
     * @param string $hookName Hook Name
     *
     * @return integer Count of hook action if has did action
     */
    public function isCalled($hookName)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName || ! isset($this->actions[$hookName])) {
            return 0;
        }

        return $this->actions[$hookName];
    }

    /**
     * Clear all resource properties
     */
    public function clear()
    {
        $this->merged = array();
        $this->current = array();
        $this->actions = array();
        $this->filters = array();
    }
}


<?php
/**
 * @author    Antoine Hedgecock <antoine.hedgecock@gmail.com>
 *
 * @copyright Interactive Solutions
 */

declare(strict_types = 1);

namespace InteractiveSolutions\Bernard\Factory\Router;

use InteractiveSolutions\Bernard\Router\PluginManagerRouter;
use InteractiveSolutions\Bernard\Router\ConsumerTaskManager;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class PluginManagerRouterFactory implements FactoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator):PluginManagerRouter
    {
        /* @var $consumerPluginManager ConsumerTaskManager */
        $consumerPluginManager = $serviceLocator->get(ConsumerTaskManager::class);

        return new PluginManagerRouter($consumerPluginManager);
    }
}


<?php

namespace D4rk4ng3l\Oxid\Compiler;

use D4rk4ng3l\Oxid\AdvancedModule\Annotations\Method;
use D4rk4ng3l\Oxid\Module\Mapping;
use Doctrine\Common\Annotations\Reader;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;

class Compiler
{
    /**
     * @var Reader
     */
    private $reader;

    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * @var string
     */
    private $annotationClass = "D4rk4ng3l\\Oxid\\AdvancedModule\\Annotations\\Module";

    public function __construct(Reader $reader, OutputInterface $output = null)
    {
        $this->reader = $reader;
        $this->output = $output;
    }

    public function compile($path)
    {
        $this->output->write('Searching for files...');
        $finder = new Finder();
        $finder->files()->name('*.php')->in($path);
        $count = $finder->count();
        $this->output->writeln(sprintf('%u file(s) found', $count));
        $index = 0;

        $mappings = array();
        foreach ($finder as $file) {
            $index++;
            $this->output->writeln(sprintf('Parsing file [%u/%u]: %s', $index, $count, $file));
            $fileContent = file_get_contents($file);
            $tokenParser = new TokenParser($fileContent);
            $tokenParser->parse($fileContent);
            if (!$tokenParser->hasClass()) {
                $this->output->writeln('skipped!');
                continue;
            }

            if (!class_exists($tokenParser->getFullClassName(), false)) {
                include $file;
            }

            $mappings = array_merge(
                $mappings,
                $this->processClass($tokenParser->getFullClassName(), $path)
            );
        }

        return $mappings;
    }

    /**
     * @param string $className
     *
     * @return array
     */
    public function processClass($className, $path)
    {
        $reflection = new \ReflectionClass($className);
        if (null === $this->reader->getClassAnnotation($reflection, $this->annotationClass)) {
            return array();
        }

        $mappings = array();

        $this->output->writeln("Found class: $className");
        foreach ($reflection->getMethods() as $method) {
            /** @var Method[] $annotations */
            $annotations = $this->reader->getMethodAnnotations($method);
            if (0 == count($annotations)) {
                continue;
            }

            $this->output->writeln(
                sprintf(
                    "Found annotations for method %s::%s.",
                    $method->class,
                    $method->getName()
                )
            );

            foreach ($annotations as $annotation) {
                if (!($annotation instanceof Method)) {
                    continue;
                }

                $this->output->writeln(
                    sprintf(
                        "Found mapping: %s::%s --> %s::%s",
                        $method->class,
                        $method->getName(),
                        $annotation->getClass(),
                        $annotation->getMethod()
                    )
                );

                $mapping = new Mapping();
                $moduleFile = $reflection->getFileName();
                $moduleFile = substr($moduleFile, strpos($moduleFile, $path));
                $mapping
                    ->setOxidClass($annotation->getClass())
                    ->setOxidMethod($annotation->getMethod())
                    ->setModuleClass($className)
                    ->setModuleMethod($method->getName())
                    ->setReturn($annotation->hasReturnValue())
                    ->setParentExecution($annotation->getParentExecution())
                    ->setModuleFile($moduleFile);
                $mappings[] = $mapping;
            }
        }

        return $mappings;
    }
}


<?php
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.service
 * @copyright Copyright (c) 2005-2011, Rocky Swen, Jixian
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: cryptService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Service;

class cryptService
{
    protected $defaultKey ;
    public $algorithm;
    public $operationMode;

    /**
     * Initialize auditService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        $this->defaultKey 	= strtolower($xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["DEFAULTKEY"]);
    	$this->algorithm 		= strtolower($xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["ALGORITHM"]);
        $this->operationMode 	= strtolower($xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["OPERATIONMODE"]);
    }

    public function encrypt($data, $key=null)
    {
    	if(!function_exists("mcrypt_module_open"))
    	{
    		return $data;
    	}
    	if($key==null){
    		$key = $this->defaultKey;
    	}
    	if($data==null)
    		return;
        $td = mcrypt_module_open($this->algorithm, '', $this->operationMode, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
       // $iv ="jixian";
        $ks = mcrypt_enc_get_key_size($td);
        $keystr = substr(md5($key), 0, $ks);
        mcrypt_generic_init($td, $keystr, $iv);
        $encrypted = mcrypt_generic($td, $data);
        mcrypt_module_close($td);
        $hexdata = bin2hex($encrypted);
        return $hexdata;
    }

    public function decrypt($data, $key=null)
    {
    	if(!function_exists("mcrypt_module_open"))
    	{
    		return $data;
    	}
   	 	if($key==null){
    		$key = $this->defaultKey;
    	}
    	if($data==null)
    		return;
        $td = mcrypt_module_open($this->algorithm, '', $this->operationMode, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        $ks = mcrypt_enc_get_key_size($td);
        $keystr = substr(md5($key), 0, $ks);
        mcrypt_generic_init($td, $keystr, $iv);
        $encrypted = pack( "H*", $data);
        $decrypted = mdecrypt_generic($td, $encrypted);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return trim($decrypted);
    }

}

?>


<?php
/**
 * @package SugiPHP.Container
 * @author  Plamen Popov <tzappa@gmail.com>
 * @license http://opensource.org/licenses/mit-license.php (MIT License)
 */

namespace SugiPHP\Container;

use ArrayAccess;
use Interop\Container\ContainerInterface;

class Container implements ArrayAccess, ContainerInterface
{
    /**
     * Table of Definitions
     */
    protected $definitions = array();

    /**
     * Table of returned objects
     */
    protected $objects = array();

    /**
     * Table of generated objects
     */
    protected $calcs = array();

    /**
     * Table of all closures that should always return fresh objects.
     */
    protected $factories;

    /**
     * Table of closures that get() method should always return raw results
     */
    protected $raws;

    /**
     * Table of locked keys that cannot be overridden and deleted
     */
    protected $locks = array();

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->factories = new \SplObjectStorage();
        $this->raws = new \SplObjectStorage();
    }

    /**
     * Property overloading magic method.
     *
     * @param string $name  Parameter name
     * @param mixed  $value The value to be assigned for the parameter
     *
     * @return void
     */
    public function __set($name, $value)
    {
        return $this->set($name, $value);
    }

    /**
     * Property overloading magic method.
     *
     * @param string $name Parameter name
     *
     * @return mixed
     */
    public function __get($name)
    {
        return $this->get($name);
    }

    /**
     * Property overloading magic method.
     *
     * @param string $name Parameter name
     *
     * @return boolean
     */
    public function __isset($name)
    {
        return $this->has($name);
    }

    /**
     * Property overloading magic method.
     *
     * @param string $name Parameter name
     *
     * @return void
     */
    public function __unset($name)
    {
        return $this->delete($name);
    }

    /**
     * Sets a parameter defined in an unique key ID.
     * You can set objects as a closures.
     *
     * @param string $id    Key Name
     * @param mixed  $value Value or closure function
     *
     * @return void
     */
    public function set($id, $value)
    {
        if (!empty($this->locks[$id])) {
            throw new ContainerException("Cannot override locked key {$id}");
        }
        $this->definitions[$id] = $value;
        $this->calcs[$id] = false;
        // unset on override
        unset($this->objects[$id]);
    }

    /**
     * Finds an entry of the container by its identifier and returns it.
     *
     * @param string $id Identifier of the entry to look for.
     *
     * @throws NotFoundException  No entry was found for this identifier.
     * @throws ContainerException Error while retrieving the entry.
     *
     * @return mixed Entry.
     */
    public function get($id)
    {
        if (!$this->has($id)) {
            throw new NotFoundException("No entry was found for the identifier '$id'");
        }

        if (method_exists($this->definitions[$id], "__invoke")) {
            if (isset($this->raws[$this->definitions[$id]])) {
                return $this->definitions[$id];
            }

            if (isset($this->factories[$this->definitions[$id]])) {
                return $this->definitions[$id]();
            }

            if ($this->calcs[$id]) {
                return $this->objects[$id];
            }
            $obj = $this->definitions[$id]();
            $this->objects[$id] = $obj;
            $this->calcs[$id] = true;

            return $obj;
        }

        return $this->definitions[$id];
    }

    /**
     * Gets or sets callable to return fresh objects.
     * If a callable is given, then it sets that the get() method always
     * to return new objects. If an string (key ID's) is given, then it
     * will return new object.
     *
     * @param mixed $idOrClosure
     *
     * @return mixed
     */
    public function factory($idOrClosure)
    {
        if (is_object($idOrClosure) && method_exists($idOrClosure, "__invoke")) {
            $this->factories->attach($idOrClosure);

            return $idOrClosure;
        }

        if (!isset($this->definitions[$idOrClosure])) {
            return null;
        }

        if (method_exists($this->definitions[$idOrClosure], '__invoke')) {
            return $this->definitions[$idOrClosure]($this);
        }

        return $this->definitions[$idOrClosure];
    }

    /**
     * Returns a raw definition. Used when a closure is set and
     * you want to get the closure not the result of it.
     *
     * @param string $idOrClosure
     *
     * @return mixed Returns whatever it is stored in the key. NULL if
     * nothing is stored.
     */
    public function raw($idOrClosure)
    {
        if (is_object($idOrClosure) && method_exists($idOrClosure, "__invoke")) {
            $this->raws->attach($idOrClosure);

            return $idOrClosure;
        }

        if (!isset($this->definitions[$idOrClosure])) {
            return null;
        }

        return $this->definitions[$idOrClosure];
    }

    /**
     * Returns true if the container can return an entry for the given identifier.
     * Returns false otherwise.
     *
     * @param string $id Identifier of the entry to look for.
     *
     * @return boolean
     */
    public function has($id)
    {
        return array_key_exists($id, $this->definitions);
    }

    /**
     * Unsets a parameter or an object.
     *
     * @param string $id
     *
     * @return void
     */
    public function delete($id)
    {
        if (!empty($this->locks[$id])) {
            throw new ContainerException("Cannot delete locked key {$id}");
        }
        if (is_object($this->definitions[$id])) {
            unset($this->factories[$this->definitions[$id]]);
        }
        unset($this->definitions[$id], $this->objects[$id], $this->calcs[$id]);
    }

    /**
     * Lock the key, so it cannot be overwritten.
     * Note that there is no unlock method and will never be!
     *
     * @param string $id
     *
     * @return mixed
     */
    public function lock($id)
    {
        $this->locks[$id] = true;
    }

    /**
     * Method is needed to implement \ArrayAccess.
     *
     * @see set() method
     */
    public function offsetSet($id, $value)
    {
        $this->set($id, $value);
    }

    /**
     * Method is needed to implement \ArrayAccess.
     *
     * @see get() method
     */
    public function offsetGet($id)
    {
        return $this->get($id);
    }

    /**
     * Method is needed to implement \ArrayAccess.
     *
     * @see has() method
     */
    public function offsetExists($id)
    {
        return $this->has($id);
    }

    /**
     * Method is needed to implement \ArrayAccess.
     *
     * @see delete() method
     */
    public function offsetUnset($id)
    {
        $this->delete($id);
    }
}


<?php

namespace Interpro\QuickStorage\Laravel\Specification;

use Interpro\QuickStorage\Concept\Exception\BuildQueryException;
use Interpro\QuickStorage\Concept\Specification\GroupSpecification;
use Interpro\QuickStorage\Concept\Specification\GroupSpecificationSet as GroupSpecificationSetInterface;
use Interpro\QuickStorage\Laravel\GroupSet;

class GroupSpecificationSet implements GroupSpecificationSetInterface
{
    use GroupSet;

    /**
     * @param string $groupName
     *
     * @param string $field_name
     *
     * @param string $oper
     *
     * @param mixed $val
     *
     * @return void
     */
    private function rawAdd($group_name, $field_name, $oper, $val)
    {
        //Вызываем из конструктора
        //Вызываем из конструктора
        //Вызываем из конструктора
        //Вызываем из конструктора
    }

    public function __construct()
    {
        //Забираем из сессии установки спецификаций
        //Забираем из сессии установки спецификаций
        //Забираем из сессии установки спецификаций
        //Забираем из сессии установки спецификаций
        //Забираем из сессии установки спецификаций
    }

    /**
     * @param string $group_name
     *
     * @param GroupSpecification $specification
     *
     * @return void
     */
    public function add($group_name, GroupSpecification $specification)
    {
        $field_name = $specification->getFieldName();

        if(!($specification->getGroup() == $group_name))
        {
            throw new BuildQueryException('Добавление условия по полю '.$field_name.' не в ту группу '.$group_name);
        }

        $this->addEmptyGroup($group_name);

        if(array_key_exists($field_name, $this->keys[$group_name]))
        {
            $this->items[$group_name][$this->keys[$group_name][$field_name]] = $specification;
        }else{
            $this->items[$group_name][] = $specification;
            $this->keys[$group_name][$field_name] = count($this->items[$group_name])-1;
        }
    }

}


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: DropDownList.php 3856 2011-04-21 18:10:41Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;
use Openbizx\I18n\I18n;
use Openbizx\Data\Helpers\QueryStringParam;
use Openbizx\Object\ObjectFactoryHelper;

include_once("InputElement.php");

/**
 * InputText class is element for input text
 *
 * @package openbiz.bin.easy.element
 * @author Jixian W.
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class DropDownList extends InputElement
{

	public $readOnly;
	public $defaultDisplayValue;
	public $cssHoverClass;
    public $selectFrom;
    public $selectFromSQL;
    public $selectedList;
    public $blankOption;
	protected $_listCache;
    protected $formPrefix = true;

	protected function readMetaData(&$xmlArr){
		parent::readMetaData($xmlArr);
		$this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "input_select_w";
		$this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : $this->cssClass."_error";
		$this->cssFocusClass = isset($xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"] : $this->cssClass."_focus";
		$this->cssHoverClass = isset($xmlArr["ATTRIBUTES"]["CSSHOVERCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSHOVERCLASS"] : $this->cssClass."_hover";
		//$this->value = isset($xmlArr["ATTRIBUTES"]["DEFAULTVALUE"]) ? $xmlArr["ATTRIBUTES"]["DEFAULTVALUE"] : null;
		$this->readOnly = isset($xmlArr["ATTRIBUTES"]["READONLY"]) ? $xmlArr["ATTRIBUTES"]["READONLY"] : "N";
        $this->selectFrom = isset($xmlArr["ATTRIBUTES"]["SELECTFROM"]) ? $xmlArr["ATTRIBUTES"]["SELECTFROM"] : null;
        $this->selectedList = isset($xmlArr["ATTRIBUTES"]["SELECTEDLIST"]) ? $xmlArr["ATTRIBUTES"]["SELECTEDLIST"] : null;
        $this->selectFromSQL = isset($xmlArr["ATTRIBUTES"]["SELECTFROMSQL"]) ? $xmlArr["ATTRIBUTES"]["SELECTFROMSQL"] : null;
    	$this->blankOption = isset($xmlArr["ATTRIBUTES"]["BLANKOPTION"]) ? $xmlArr["ATTRIBUTES"]["BLANKOPTION"] : null;
        $this->blankOption = $this->translateString($this->blankOption);
		$this->defaultValueRename = isset($xmlArr["ATTRIBUTES"]["DEFAULTVALUERENAME"]) ? $xmlArr["ATTRIBUTES"]["DEFAULTVALUERENAME"] : "N";

	}
    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
    	if($this->formPrefix){
    		$formNameStr = str_replace(".","_", $this->getFormObj()->objectName)."_";
    	}
    	if($this->value!=null){
    		$value = $this->value;
    	}else{
    		$value = $this->getText();
    	}
    	if($value==null){
    		$value = $this->getDefaultValue();
    	}
    	if(preg_match('/\{.*?@.*?\}/si',$value)){
    		$formObj = $this->getFormObj();
    		$value = Expression::evaluateExpression($value, $formObj);
    	}
        $disabledStr = ($this->getEnabled() == "N") ? "READONLY=\"true\"" : "";
        $style = $this->getStyle();
        $func = $this->getFunction();
        $optionList= $this->renderList();

        $htmlClass = Expression::evaluateExpression($this->cssClass, $formobj);
        $htmlClass = "CLASS='$htmlClass'";

        $sHTML .= "
cssClass."\">";
        if($this->readOnly=='Y')
        {
	        $display_input = "style=\"display:none;\"";
	        $display_span = "style=\"position:;\"";
        }
        else
        {
	        $display_span = "style=\"display:none;\"";
	        $display_input = "style=\"position:;\"";
        }
        $list = $this->getList();
        if ($this->blankOption) // ADD a blank option
        {
            $entry = explode(",",$this->blankOption);
            $text = $entry[0];
            $blkvalue = ($entry[1]!= "") ? $entry[1] : null;
            $display_value = $text;
            $entryList = array(array("val" => $blkvalue, "txt" => $text ));
            $list = array_merge($entryList, $list);
        }

        $display_value=$this->getDisplayValue($value);
    	if(!$list){$list=array();}
        foreach ($list as $item){
        	if($item['val']==$value){
        		if(!preg_match("/\</si",$item['txt'])){
        			$display_value = $item['txt'];
        		}else{
        			$display_value = $item['val'];
        		}
        		break;
        	}
        }

        if($value==''){
            $defaultOpt = array_shift($list);
            if($display_value==''){
            	$value = $defaultOpt['val'];
        		$display_value = $defaultOpt['txt'];
            }
        	array_unshift($list,$defaultOpt);
        }

        $this->setValue($value);
        $display_value = strip_tags($display_value);

		$elem_id = $formNameStr.$this->objectName;
		$elem_scroll_id = $formNameStr.$this->objectName."_scroll";
		$elem_list_id = $formNameStr.$this->objectName."_list";
		$elem_hidden_id = $formNameStr.$this->objectName."_hidden";

		$onchange_func = $this->getOnChangeFunction();
		$sHTML .= $optionList;
		$sHTML .= "\n
";
		// jquery $j('a.maxmin').click(function() {...});
		// jquery $j('a.maxmin').hover(function() {...}, function() {...});
		if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
			$sHTML .= "\nhtmlAttr $style>$display_value\n";
		}
		else {
	        $sHTML .= "htmlAttr $style
						onclick=\"if($('$elem_list_id').visible()){\$('$elem_list_id').hide();\$('$elem_scroll_id').hide();$('$elem_id').className='".$this->cssClass."'}else{\$('$elem_list_id').show();\$('$elem_scroll_id').show();$('$elem_id').className='".$this->cssFocusClass."'}\"
						onmouseover=\"$('span_$elem_id').className='".$this->cssHoverClass."'\"
						onmouseout=\"$('span_$elem_id').className='".$this->cssClass."'\"
						>$display_value";
		}
		$sHTML .= "
";
		$sHTML .= "
";
		if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
			$sHTML .= "<INPUT NAME=\"$elem_id\" ID=\"$elem_id\" VALUE=\"" . $display_value . "\" $disabledStr $this->htmlAttr $style />\n";
		}
		else {
			$sHTML .= "<INPUT NAME=\"$elem_id\" ID=\"$elem_id\" VALUE=\"" . $display_value . "\" $disabledStr $this->htmlAttr $style
						onclick=\"if($('$elem_list_id').visible()){\$('$elem_list_id').hide();\$('$elem_scroll_id').hide();$('$elem_id').className='".$this->cssClass."'}else{\$('$elem_list_id').show();\$('$elem_scroll_id').show();$('$elem_id').className='".$this->cssFocusClass."'}\"
							onmouseover=\"$('span_$elem_id').className='".$this->cssHoverClass."'\"
							onmouseout=\"$('span_$elem_id').className='".$this->cssClass."'\"
						/>";
		}
		$sHTML .= "<INPUT NAME=\"$elem_id\" ID=\"$elem_hidden_id\" VALUE=\"" . $value . "\" type=\"hidden\" $func />";
		$sHTML .= "
";

        $sHTML .= "
";

if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
	$sHTML .= "";
}
else {
	$sHTML .= "";
}
        return $sHTML;
    }

    public function getDisplayValue($value)
    {
    	if($value===null)
    	{
    		return null;
    	}
		$list = $this->getList();
    	/*$selectFrom = $this->selectFrom;
    	$selectFrom = substr($selectFrom,0,strpos($selectFrom,','));

    	$list= array();
        if (!$selectFrom) {
        	$this->getSQLFromList($list);
        }
        else
        {
        	$this->getXMLFromList($list, $selectFrom);
        	if (!is_array($list) || count($list)==0){
        		$this->getDOFromList($list, $selectFrom);
        		if (!is_array($list) || count($list)==0){
        			$this->getSimpleFromList($list, $selectFrom);
        		}
        	}
        }*/

       	if(!is_array($list)||count($list)==0){
       		return $value;
       	}

    	foreach ($list as $item){
        	if($item['val']==$value){
        		if(!preg_match("/\</si",$item['txt'])){
        			$display_value = $item['txt'];
        			return $display_value;
        		}else{
        			$display_value = $item['val'];
        			return $display_value;
        		}
        		break;
        	}
        }
    	return $display_value;
    }

    protected function renderList(){

    	if($this->formPrefix){
    		$formNameStr = str_replace(".","_", $this->getFormObj()->objectName)."_";
    	}
    	$onchange_func = $this->getOnChangeFunction();
    	$list = $this->getList();

        if ($this->blankOption) // ADD a blank option
        {
            $entry = explode(",",$this->blankOption);
            $text = $entry[0];
            $value = ($entry[1]!= "") ? $entry[1] : null;
            $entryList = array(array("val" => $value, "txt" => $text ));
            $list = array_merge($entryList, $list);
        }

    	$value = $this->value!==null ? $this->value : $this->getText();
		$elem_id = $formNameStr.$this->objectName;
		$elem_scroll_id = $formNameStr.$this->objectName."_scroll";
		$elem_list_id = $formNameStr.$this->objectName."_list";
		$elem_hidden_id = $formNameStr.$this->objectName."_hidden";
    	$sHTML = "\n
".
    	$sHTML .= "\n
\n";
    	if(!$list){$list=array();}
    	foreach($list as $item){
    		$val = $item['val'];
    		$txt = $item['txt'];
    		$pic = $item['pic'];
    		if($pic){
    			if(preg_match('/\{.*\}/si',$pic)){
    				$pic = Expression::evaluateExpression($pic,null);
    			}elseif(!preg_match('/\//si',$pic)){
        			$pic = Openbizx::$app->getImageUrl()."/".$pic;
        		}
    			$str_pic="";

    		}else{
    			$str_pic = "";
    		}
    	    if(!preg_match("/</si",$txt)){
        		$display_value = $txt;
    	    }else{
    	    	$display_value = $val;
    	    }
    	    if($str_pic){
    	    	$li_option_value =  $str_pic."".$txt."";
    	    }
    	    else{
    	    	$li_option_value = "".$txt.""; //$txt ;
    	    }

    	    if($val==$value)
    	    {
    	    	$option_item_style=" class='selected' ";
    	    }else{
    	    	$option_item_style=" onmouseover=\"this.className='hover'\" onmouseout=\"this.className=''\" ";
    	    }
    	    // jquery $j('a.maxmin').click( function () {...} );
			if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
				$sHTML .= "
$li_option_value
\n";
			}
			else {
				$sHTML .= "
cssClass."'
									\"
					>$li_option_value
";
    		}
    		if($val == $value){
    			$this->defaultDisplayValue="".$str_pic."".$txt."";
    		}
    	}
    	$sHTML .= "
";
    	$sHTML .= "
";
    	return $sHTML;
    }

    protected function getList(){
		if ($this->_listCache) return $this->_listCache;
    	$list= array();
        if (!$selectFrom) {
            $selectFrom = $this->getSelectFrom();
        }
        if (!$selectFrom) {
        	return $this->getSQLFromList($list);
        }
        $this->getXMLFromList($list, $selectFrom);
        if ($list != null) {
            $this->_listCache=$list; return $list;
		}
        $this->getDOFromList($list, $selectFrom);
        if ($list != null) {
            $this->_listCache=$list; return $list;
		}
        $this->getSimpleFromList($list, $selectFrom);
        if ($list != null) {
            $this->_listCache=$list; return $list;
		}

    	return $list;
    }
// below code is copied from OptionElement
    protected function getSelectFrom()
    {
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->selectFrom, $formobj);
    }

    protected function getSelectedList()
    {
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->selectedList, $formobj);
    }

	protected function getSelectFromSQL()
    {
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->selectFromSQL, $formobj);
    }

    protected function getXMLFromList(&$list, $selectFrom)
    {
        $pos0 = strpos($selectFrom, "(");
        $pos1 = strpos($selectFrom, ")");
        if ($pos0>0 && $pos1 > $pos0)
        {  // select from xml file
            $xmlFile = substr($selectFrom, 0, $pos0);
            $tag = substr($selectFrom, $pos0 + 1, $pos1 - $pos0-1);
            $tag = strtoupper($tag);
            $xmlFile = ObjectFactoryHelper::getXmlFileWithPath($xmlFile);
            if (!$xmlFile) return false;

            $xmlArr = &ObjectFactoryHelper::getXmlArray($xmlFile);
            if ($xmlArr)
            {
                $i = 0;
                if ( !isset($xmlArr["SELECTION"][$tag]) ) {
                    return false;
                }
                if(!$xmlArr["SELECTION"][$tag][0]){
                	$array = $xmlArr["SELECTION"][$tag];
                	unset($xmlArr["SELECTION"][$tag]);
                	$xmlArr["SELECTION"][$tag][0]=$array;
                }
                foreach($xmlArr["SELECTION"][$tag] as $node)
                {
                    $list[$i]['val'] = $node["ATTRIBUTES"]["VALUE"];
                    $list[$i]['pic'] = $node["ATTRIBUTES"]["PICTURE"];
                    if ($node["ATTRIBUTES"]["TEXT"])
                    {
                        $list[$i]['txt'] = $node["ATTRIBUTES"]["TEXT"];
                    }
                    else
                    {
                        $list[$i]['txt'] = $list[$i]['val'];
                    }
                    $i++;
                }
                $this->translateList($list, $tag);	// supprot multi-language
            }
            return true;
        }
        return false;
    }

    protected function getDOFromList(&$list, $selectFrom)
    {
        $pos0 = strpos($selectFrom, "[");
        $pos1 = strpos($selectFrom, "]");
        if ($pos0 > 0 && $pos1 > $pos0)
        {  // select from bizObj
            // support BizObjName[BizFieldName] or
            // BizObjName[BizFieldName4Text:BizFieldName4Value] or
            // BizObjName[BizFieldName4Text:BizFieldName4Value:BizFieldName4Pic]
            $bizObjName = substr($selectFrom, 0, $pos0);
            $pos3 = strpos($selectFrom, ":");
            if($pos3 > $pos0 && $pos3 < $pos1)
            {
                $fieldName = substr($selectFrom, $pos0 + 1, $pos3 - $pos0 - 1);
                $fieldName_v = substr($selectFrom, $pos3 + 1, $pos1 - $pos3 - 1);
            }
            else
            {
                $fieldName = substr($selectFrom, $pos0 + 1, $pos1 - $pos0 - 1);
                $fieldName_v = $fieldName;
            }
            $pos4 = strpos($fieldName_v, ":");
            if($pos4){
            	$fieldName_v_mixed = $fieldName_v;
            	$fieldName_v = substr($fieldName_v_mixed,0,$pos4);
            	$fieldName_p = substr($fieldName_v_mixed, $pos4+1, strlen($fieldName_v_mixed)-$pos4-1);
            	unset($fieldName_v_mixed);
            }
            $commaPos = strpos($selectFrom, ",", $pos1);
            if ($commaPos > $pos1)
                $searchRule = trim(substr($selectFrom, $commaPos + 1));

            /* @var $bizObj BizDataObj */
            $bizObj = Openbizx::getObject($bizObjName);
            if (!$bizObj)
                return false;

            $recList = array();
            $oldAssoc = $bizObj->association;
            $bizObj->association = null;
            QueryStringParam::reset();
            $recList = $bizObj->directFetch($searchRule);
            $bizObj->association = $oldAssoc;

            foreach ($recList as $rec)
            {
                $list[$i]['val'] = $rec[$fieldName_v];
                $list[$i]['txt'] = $rec[$fieldName];
                $list[$i]['pic'] = $rec[$fieldName_p];
                $i++;
            }
            return true;
        }
        return false;
    }

    protected function getSimpleFromList(&$list, $selectFrom)
    {
        // in case of a|b|c
        if (strpos($selectFrom, "[") > 0 || strpos($selectFrom, "(") > 0)
            return;
        $recList = explode('|',$selectFrom);
        foreach ($recList as $rec)
        {
            $list[$i]['val'] = $rec;
            $list[$i]['txt'] = $rec;
            $list[$i]['pic'] = $rec;
            $i++;
        }
    }

    public function getSQLFromList(&$list)
    {
    	$sql = $this->getSelectFromSQL();
    	if (!$sql) return;
    	$formObj = $this->getFormObj();
    	$do = $formObj->getDataObj();
    	$db = $do->getDBConnection();
    	try {
    		$resultSet = $db->query($sql);
    		$recList = $resultSet->fetchAll();
	    	foreach ($recList as $rec)
	        {
	            $list[$i]['val'] = $rec[0];
	            $list[$i]['txt'] = isset($rec[1]) ? $rec[1] : $rec[0];
	            $i++;
	        }
    	}
    	catch (Exception $e)
        {
            Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: ".$e->getMessage());
            $this->errorMessage = "Error in SQL query: ".$sql.". ".$e->getMessage();
            throw new Openbizx\Data\Exception($this->errorMessage);
            return null;
        }
    }

    protected function getOnChangeFunction()
    {
        $name = $this->objectName;
        // loop through the event handlers
        $func = "";

        if ($this->eventHandlers == null)
            return null;
        $formobj = $this->getFormObj();
        foreach ($this->eventHandlers as $eventHandler)
        {
            $ehName = $eventHandler->objectName;
            $event = $eventHandler->event;
            $type = $eventHandler->functionType;
            if (!$event) continue;
            if($events[$event]!=""){
            	$events[$event]=array_merge(array($events[$event]),array($eventHandler->getFormedFunction()));
            }else{
            	$events[$event]=$eventHandler->getFormedFunction();
            }
        }

		$function=$events['onchange'];
		if(is_array($function)){
			foreach($function as $f){
				$function_str.=$f.";";
			}
			$func .= $function_str;
		}else{
			$func .= $function;
		}

        return $func;
    }

	protected function translateList(&$list, $tag)
    {
    	$module = $this->getModuleName($this->selectFrom);
        if (empty($module))
            $module = $this->getModuleName($this->formName);
    	for ($i=0; $i<count($list); $i++)
    	{
    		$key = 'SELECTION_'.strtoupper($tag).'_'.$i.'_TEXT';
    		$list[$i]['txt'] = I18n::t($list[$i]['txt'], $key, $module, $this->getTransLOVPrefix());
    	}
    }

    protected function getTransLOVPrefix()
    {
    	$nameArr = explode(".",$this->selectFrom);
    	for($i=1;$i<count($nameArr)-1;$i++)
    	{
    		$prefix .= strtoupper($nameArr[$i])."_";
    	}
    	return $prefix;
    }
}
?>


<?php namespace Interpro\QuickStorage\Laravel\Handle;

use Illuminate\Support\Facades\Log;
use Interpro\QuickStorage\Concept\Command\DeleteGroupItemCommand;
use Interpro\QuickStorage\Laravel\Model\Block;
use Interpro\QuickStorage\Laravel\Model\Bool;
use Interpro\QuickStorage\Laravel\Model\Group;
use Interpro\QuickStorage\Laravel\Model\Imageitem;
use Interpro\QuickStorage\Laravel\Model\Numb;
use Interpro\QuickStorage\Laravel\Model\Pdatetime;
use Interpro\QuickStorage\Laravel\Model\Stringfield;
use Interpro\QuickStorage\Laravel\Model\Textfield;

class DeleteGroupItemCommandHandler {

    /**
     * Update the command handler.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the command.
     *
     * @param DeleteGroupItemCommand  $command
     * @return array
     */
    public function handle(DeleteGroupItemCommand $command)
    {
        $deleted=[];

        $group_item = Group::find($command->group_id);

        if($group_item)
        {
            $this->deleteGroupItem($group_item, $deleted);
        }

        return $deleted;
    }

    public function deleteGroupItem($group_item, & $deleted)
    {
        $id = $group_item->id;

        $groups = Group::where('owner_id', '=', $id)->get();

        foreach($groups as $item)
        {
            $this->deleteGroupItem($item, $deleted);
        }

        $collection = Stringfield::where('group_id', '=', $id)->get();
        foreach($collection as $field){
            $field->delete();
        }

        $collection = Textfield::where('group_id', '=', $id)->get();
        foreach($collection as $field){
            $field->delete();
        }

        $collection = Numb::where('group_id', '=', $id)->get();
        foreach($collection as $field){
            $field->delete();
        }

        $collection = Bool::where('group_id', '=', $id)->get();
        foreach($collection as $field){
            $field->delete();
        }

        $collection = Pdatetime::where('group_id', '=', $id)->get();
        foreach($collection as $field){
            $field->delete();
        }

        $collection = Imageitem::where('group_id', '=', $id)->get();
        foreach($collection as $field){
            $field->delete();
        }

        $group_item->delete();

        $deleted[] = $id;

    }

}