<?php
/**
 * This file is part of the MimeMailer package.
 *
 * Copyright (c) 2013-2016 Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The source code of this package is available online at
 * <http://github.com/atelierspierrot/mime-mailer>.
 */

namespace MimeMailer;

use \Patterns\Abstracts\AbstractSingleton;
use \Patterns\Interfaces\OptionableInterface;
use \Library\Converter\Html2Text;
use \Library\Helper\Directory as DirectoryHelper;
use \Validator\EmailValidator;

/**
 * @author  piwi <me@e-piwi.fr>
 */
class Mailer
    extends AbstractSingleton
    implements OptionableInterface
{

    // --------------------
// Constants
// --------------------
    const MM_CLASSNAME = "MimeMailer package";
    const MM_CLASSVERSION = "0.1";
    const BOUNDARY_OPENER = "--";
    const BOUNDARY_CLOSER = "--";
    const BOUNDARY_PREFIX = "=_MimeMailerClass_";

// --------------------
// Statics
// --------------------
    public static $LINE_ENDING = "\n";
    public static $ADDERSSES_SEPARATOR = ", ";
    public static $HEADERS_SEPARATOR = "; ";

// --------------------
// Variables
// --------------------

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

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

    /**
     * @var array of \MimeMailer\MessageInterface objects
     */
    private $messages = array();

    /**
     * @var \MimeMailer\TransportInterface
     */
    private $transporter;

    /**
     * @var \MimeMailer\SpoolInterface
     */
    private $spooler;

    /**
     * @var int
     */
    private $sent_messages = 0;

    /**
     * @var int
     */
    private $sent_errors = 0;

    /**
     * @var array
     */
    protected $options = array(
        'headers' => array(
            'MIME-Version'=>'1.0',
            'Return-Path'=>false,
            'Reply-To'=>'no-reply@mail.class',
            'X-Sender'=>false,
            'X-Priority'=>'3',
        ),
        'defaults'=>array(
            'transporter' => '\MimeMailer\Transport\MailTransport',
            'messager' => '\MimeMailer\MimeMessage',
            'spooler' => '\MimeMailer\SpoolManager',
        ),
//        'charset' => 'iso-8859-1',
        'charset' => 'utf-8',
        'wordwrap_limit' => 78,
        'sender_mailer' => "mime@mail.class",
        'boundary' => '',
        'boundary_ctt' => '',
        'message_type' => '',
        'spool_directory' => '',
        // Redefine the sendmail executable path
        'sendmail_path' => null,
    );

    /**
     * Set to TRUE to not send the mails but test its contents
     * @var bool
     */
    protected $dry_run = false;

    /**
     * Set to TRUE to not send the mails but write them in a file
     * @var bool
     */
    protected $spool = false;

// --------------------
// Construction
// --------------------

    /**
     * Construction of a MimeEmail object
     *
     * @param array $options
     */
    protected function init(array $options = null)
    {
        $this->boot();
        if (!is_null($options)) {
            $this->setOptions(
                array_merge($this->getOptions(), $options)
            );
        }
    }

// --------------------
// OptionableInterface
// --------------------

    /**
     * Set an array of options
     *
     * @param array $options
     * @return self
     */
    public function setOptions(array $options)
    {
        $this->options = $options;
        return $this;
    }

    /**
     * Set the value of a specific option
     *
     * @param string $name
     * @param mixed $value
     * @return self
     */
    public function setOption($name, $value)
    {
        $this->options[$name] = $value;
        return $this;
    }

    /**
     * Get the array of options
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Get the value of a specific option
     *
     * @param string $name
     * @param mixed $default
     * @return mixed
     */
    public function getOption($name, $default = null)
    {
        return isset($this->options[$name]) ? $this->options[$name] : $default;
    }

    /**
     * Get the value of a specific option
     *
     * @param string $name
     * @return mixed
     */
    public function getDefault($name)
    {
        return isset($this->options['defaults'][$name]) ? $this->options['defaults'][$name] : null;
    }

// --------------------
// Internal boot
// --------------------

    /**
     * First initialization of the object
     *
     * @return void
     */
    protected function boot()
    {
        if (defined('PHP_EOL')) {
            self::$LINE_ENDING = PHP_EOL;
        } else {
            self::$LINE_ENDING = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
        }
        $this->setRegistry('X-Mailer', "PHP ".PHP_VERSION." - ".self::MM_CLASSNAME." ".self::MM_CLASSVERSION, 'headers');
    }

    /**
     * Initialization before sending messages
     *
     * @return void
     */
    protected function _presendInit()
    {
        // Fournir si possible un Message-Id: conforme au RFC1036,
        // sinon SpamAssassin denoncera un MSGID_FROM_MTA_HEADER
        $sender_mailer = $this->getOption('sender_mailer');
        if (Helper::isEmail($sender_mailer)) {
            preg_match('/(@\S+)/', $sender_mailer, $domain);
            $this->setRegistry('Message-Id', '<'.time().'_'.rand().'_'.md5($this->getMessage()->get('text')).$domain[1].'>', 'headers');
        } else {
            $this->addError(
                sprintf('!! - Error in "sender" address (%s) - the message will probably be considered as a spam.', $sender_mailer)
            );
        }
    }

// --------------------
// Infos / Errors
// --------------------

    /**
     * Add error
     *
     * @param string $message
     * @return self
     */
    public function addError($message)
    {
        $this->errors[] = $message;
        return $this;
    }

    /**
     * Get the errors
     *
     * @param bool $echoable Do we have to return a string to echo ? (FALSE by default)
     * @return mixed The errors stack as an array by default, a string to display if $echoable=true
     * @return string|array
     */
    public function getErrors($echoable = false)
    {
        if (true===$echoable) {
            return join("\n
", $this->errors);
        } else {
            return $this->errors;
        }
    }

    /**
     * Add info
     *
     * @param string $message
     * @return self
     */
    public function addInfo($message)
    {
        $this->infos[] = $message;
        return $this;
    }

    /**
     * Get the informations
     *
     * @param bool $echoable Do we have to return a string to echo ? (FALSE by default)
     * @return mixed The errors stack as an array by default, a string to display if $echoable=true
     * @return string|array
     */
    public function getInfos($echoable = false)
    {
        if (true===$echoable) {
            return join("\n
", $this->infos);
        } else {
            return $this->infos;
        }
    }

// --------------------
// Setters / Getters
// --------------------

    /**
     * Set a registry entry
     *
     * @param   string  $var The entry name
     * @param   mixed   $val The entry value
     * @param   string  $section A sub-section to search the entry
     * @return void
     */
    public function setRegistry($var = null, $val = null, $section = false)
    {
        if (is_null($var)) {
            return;
        }
        if ($section) {
            if (!isset($this->registry[$section])) {
                $this->registry[$section] = array();
            }
            $this->registry[$section][$var] = $val;
        } else {
            $this->registry[$var] = $val;
        }
        return $this;
    }

    /**
     * Get a registry entry
     *
     * @param string $var The entry name
     * @param string $section A sub-section to search the entry
     * @param mixed $default The value returned if nothing had been found
     * @return mixed The value of the entry if found, $default otherwise
     */
    public function getRegistry($var = null, $section = false, $default = false)
    {
        if (is_null($var)) {
            return;
        }
        if ($section && isset($this->registry[$section])) {
            if (isset($this->registry[$section][$var])) {
                return $this->registry[$section][$var];
            } else {
                return $default;
            }
        }
        if (isset($this->registry[$var])) {
            return $this->registry[$var];
        }
        return $default;
    }

    /**
     * Build a new message
     *
     * @param \MimeMailer\MessageInterface $message
     * @return self
     */
    public function addMessage(MessageInterface $message)
    {
        $this->messages[$message->getId()] = $message;
        return $this;
    }

    /**
     * Get a message by id or current message
     *
     * If no message exists for now, it will be created using the default `messager` class.
     *
     * @param   int $id
     * @return string
     * @throws \Exception if the default `messager` class doesn't exist
     */
    public function getMessage($id = null)
    {
        if (!is_null($id)) {
            return array_key_exists($id, $this->messages) ? $this->messages[$id] : null;
        } elseif (count($this->messages)>0) {
            return current($this->messages);
        } else {
            $message_class = $this->getDefault('messager');
            if (class_exists($message_class)) {
                $this->addMessage(new $message_class);
                return current($this->messages);
            } else {
                throw new \Exception(
                    sprintf('Default message class "%s" not found!', $message_class)
                );
            }
        }
    }

    /**
     * Set a transporter
     *
     * @param \MimeMailer\TransportInterface $transporter
     * @return self
     * @throws \Exception if the default `transporter::validate()` does not return `true`
     */
    public function setTransporter(TransportInterface $transporter)
    {
        if ($transporter->validate()) {
            $this->transporter = $transporter;
        } else {
            throw new \Exception(
                sprintf('Transporter "%s" is not valid for current environment!', get_class($transporter))
            );
        }
        return $this;
    }

    /**
     * Get the transporter
     *
     * If no message exists for now, it will be created using the default `transporter` class.
     *
     * @return string
     * @throws \Exception if the default `transporter` class doesn't exist
     */
    public function getTransporter()
    {
        if (empty($this->transporter)) {
            $transport_class = $this->getDefault('transporter');
            if (class_exists($transport_class)) {
                $this->setTransporter(new $transport_class);
            } else {
                throw new \Exception(
                    sprintf('Default transport class "%s" not found!', $transport_class)
                );
            }
        }
        return $this->transporter;
    }

    /**
     * Set a spooler manager
     *
     * @param \MimeMailer\SpoolInterface $spooler
     * @return self
     */
    public function setSpooler(SpoolInterface $spooler)
    {
        $this->spooler = $spooler;
        return $this;
    }

    /**
     * Get the spooler
     *
     * If no message exists for now, it will be created using the default `spooler` class.
     *
     * @return string
     * @throws \Exception if the default `spooler` class doesn't exist
     */
    public function getSpooler()
    {
        if (empty($this->spooler)) {
            $spool_class = $this->getDefault('spooler');
            if (class_exists($spool_class)) {
                $this->setSpooler(new $spool_class);
            } else {
                throw new \Exception(
                    sprintf('Default spool class "%s" not found!', $spool_class)
                );
            }
        }
        return $this->spooler;
    }

    /**
     * Make a dry run of the class : no mail will be sent
     *
     * @param bool $dry Activate dry run or not
     * @return self
     */
    public function setDryRun($dry = true)
    {
        $this->dry_run = $dry;
        return $this;
    }

    /**
     * Get the dry run value
     *
     * @return bool
     */
    public function getDryRun()
    {
        return (bool) $this->dry_run;
    }

    /**
     * Is it dry run?
     *
     * @return bool
     */
    public function isDryRun()
    {
        return true===$this->dry_run;
    }

    /**
     * Activate emails spooling
     *
     * @param bool $spool Activate spool or not
     * @return self
     */
    public function setSpool($spool = true)
    {
        $this->spool = $spool;
        return $this;
    }

    /**
     * Get the spool value
     *
     * @return bool
     */
    public function getSpool()
    {
        return (bool) $this->spool;
    }

    /**
     * Is it spooling?
     *
     * @return bool
     */
    public function isSpool()
    {
        return true===$this->spool;
    }

    /**
     * Set the spooled mails directory
     *
     * @param string $dir The directory where to create spooled mails files
     * @return self
     */
    public function setSpoolDirectory($dir)
    {
        $this->spool_dir = $dir;
        return $this;
    }

    /**
     * Get the spooled mails directory
     *
     * @return string
     */
    public function getSpoolDirectory()
    {
        return $this->spool_dir;
    }

// --------------------
// Sending
// --------------------

    /**
     * Messages sender
     *
     * @param bool $return_info Do we have to return an information about sending ?
     * @return bool|mixed
     */
    public function send($return_info = false)
    {
        $this->_presendInit();

        $msg = $this->getMessage()
            ->buildMessage()
            ->getMessage();

        // Then we send one by one
        if (false===$this->dry_run) {
            foreach ($this->getMessage()->get('to') as $set) {
                if (!empty($set) && is_array($set)) {
                    foreach ($set as $name=>$mail) {
                        if (is_numeric($name)) {
                            $name = $mail;
                        }
                        if (true===$this->spool) {
                            if (true===$this->spoolMessage($mail, $this->getMessage()->get('subject'), '', $msg)) {
                                $this->addInfo(
                                    sprintf('Spooling message to send to "%s".', $mail)
                                );
                            } else {
                                $this->addError(
                                    sprintf('!! - Error while spooling message to send to "%s"!', $mail)
                                );
                            }
                        } else {
                            if (false===$this->sendMessage($mail, $this->getMessage()->get('subject'), '', $msg)) {
                                $this->addError(
                                    sprintf('!! - The message can not be sent to "%s"!', $mail)
                                );
                                $this->sent_errors++;
                            } else {
                                $this->addInfo(
                                    sprintf('Message sent to "%s".', $mail)
                                );
                                $this->sent_messages++;
                            }
                        }
                    }
                }
            }
        } else {
            $this->addInfo('DryRun : no mail will be sent');
        }

        // errors ? infos ?
        if ($this->sent_errors>0) {
            $msg = "Error - The message(s) can not been sent ... Check errors pile!";
            $this->addInfo($msg);
            $this->addError($msg);
        } else {
            $msg = "OK - The message(s) have been sent ...";
            $this->addInfo($msg);
        }

        // return
        if (true===$return_info) {
            return $msg;
        }
        return $this->sent_messages>0;
    }

    /**
     * Messages spooler : prepare the whole content and write it in a file
     *
     * @param bool $return_info Do we have to return an information about sending ?
     * @return mixed
     */
    public function spool($return_info = false)
    {
        $this->setSpool(true);
        return $this->send($return_info);
    }

    /**
     * Messages sender : prepare the whole content and send the e-mail
     *
     * @param string $to
     * @param string $subject
     * @param string $message
     * @param string $additional_headers
     * @param string $additional_parameters
     * @return mixed
     */
    protected function sendMessage($to, $subject, $message, $additional_headers = '', $additional_parameters = '')
    {
        return $this->getTransporter()
            ->transport($to, $subject, $message, $additional_headers, $additional_parameters);
    }

    /**
     * Messages spooler : prepare the whole content and write it in a file
     *
     * @param string $to
     * @param string $subject
     * @param string $message
     * @param string $additional_headers
     * @param string $additional_parameters
     * @return mixed
     * @throws \Exception if `spool_dir` is not defined
     */
    protected function spoolMessage($to, $subject, $message, $additional_headers = '', $additional_parameters = '')
    {
        if (empty($this->spool_dir)) {
            throw new \Exception('You must define a spool directory to spool emails!');
        }
        $contents = array(
            'to'=>$to,
            'subject'=>$subject,
            'message'=>$message,
            'additional_headers'=>$additional_headers,
            'additional_parameters'=>$additional_parameters
        );
        return $this->getSpooler()
            ->setSpoolDirectory($this->spool_dir)
            ->addMessageToSpool($this->getMessage()->getId(), $contents, false);
    }
}

/* EXAMPLE */
/*
ini_set('display_errors','1'); error_reporting(E_ALL ^ E_NOTICE);
$txt_message = "Hello dude !\n\nMy line 1\nLine 2\nLine 3";
$txt_message_iso = "Hello dude !\n\nMy line 1 with special chars : é à\nLine 2\nLine 3";
$html_message = "Hello dude !\n\n

Line 1	Line 2	Line 3

";
$html_message_iso = "Hello dude !\n\n

My line 1 with special chars : é à	Line 2	Line 3

";
$test_adress_1 = 'piero.wbmstr@gmail.com';
$test_name_1 = 'Piero';
$test_name_1_iso = 'Piéro';
$test_adress_2 = 'pierre.cassat@gmail.com';
$test_name_2 = 'Piero2';
$test_adress_3 = 'pierrecassat@free.fr';
$test_name_3 = 'PieroFree';
$from = 'the_tester@system.fr';
$from_name = 'mister Tester';
$file = 'inc/lorem_ipsum.txt';
$subject = 'The subject of this test message ...';
$subject_iso = 'The subject of this test message with special chars : é à ...';

// Initialisation of the mail
// standard simple mail
//$mail = new MimeEmail($from_name, $from, $test_adress_1, $subject, $txt_message);
// mail with ISO chars
$mail = new MimeEmail($from_name, $from, $test_adress_1, $subject_iso, $txt_message_iso);

// Adding some emails
$mail->setCc($test_adress_2, 'yo');
$mail->setCc($test_adress_3, $test_name_3);

// This will send an error : this is not an email adress
//$mail->setCc('yuiuy');

// Loading HTML content
// Simple HTML content
//$mail->setHtml($html_message);
// ISO chars HTML content
$mail->setHtml($html_message_iso);

// Attah a file
$mail->setAttachment($file);

// Send mails with feedback
$ok = $mail->send(1);

// See the object
echo "
"; var_export($mail); echo "
";
exit;
*/

// Endfile


<?php

/*
 * This File is part of the Thapp\Jmg\Http\Psr7 package
 *
 * (c) iwyg <mail@thomas-appel.com>
 *
 * For full copyright and license information, please refer to the LICENSE file
 * that was distributed with this package.
 */

namespace Thapp\Jmg\Http\Psr7;

use Thapp\Jmg\ParamGroup;
use Thapp\Jmg\Exception\InvalidSignatureException;
use Thapp\Jmg\Http\UrlSigner as BaseSigner;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * @class UrlSigner
 *
 * @package Thapp\Jmg\Http
 * @version $Id$
 * @author iwyg <mail@thomas-appel.com>
 */
class UrlSigner extends BaseSigner implements UrlSignerInterface
{
    /**
     * {@inheritdoc}
     */
    public function validateRequest(Request $request, ParamGroup $params)
    {
        $key   = $this->getQParamKey();
        $query = $request->getQueryParams();

        if (!isset($query[$key])) {
            throw InvalidSignatureException::missingSignature();
        }

        if (0 !== strcmp($query[$key], $this->createSignature($request->getUri()->getPath(), $params))) {
            throw InvalidSignatureException::invalidSignature();
        }

        return true;
    }
}


<?php

namespace yii2module\fixture\controllers;

use Yii;
use yii2lab\console\yii\console\Controller;
use yii2module\fixture\helpers\Fixtures;
use yii2lab\console\helpers\Output;
use yii2lab\console\helpers\input\Question;
use yii2lab\console\helpers\input\Select;
use yii2lab\console\helpers\input\Enter;

class DefaultController extends Controller
{

	/**
	 * Export or import fixtures
	 */
	public function actionIndex($option = null)
	{
		$fixtures = Yii::createObject(Fixtures::className());
		$option = Question::displayWithQuit('Select operation', ['Export', 'Import'], $option);
		if($option == 'e') {
			$allTables = $fixtures->tableNameList();
			if(!empty($allTables)) {
				$answer = Select::display('Select tables for export', $allTables, 1);
				$tables = $fixtures->export($answer);
				Output::items($tables, 'Exported tables');
			} else {
				Output::block("not tables for export!");
			}
		} elseif($option == 'i') {
			$allTables = $fixtures->fixtureNameList();
			if(!empty($allTables)) {
				$answer = Select::display('Select tables for import', $allTables, 1);
				$tables = $fixtures->import($answer);
				Output::items($tables, 'Imported tables');
			} else {
				Output::block("not tables for import!");
			}
		}

	}

	/**
	 * Export or import one table
	 */
	public function actionOne($option = null)
	{
		$fixtures = Yii::createObject(Fixtures::className());
		$option = Question::displayWithQuit('Select operation', ['Export', 'Import'], $option);
		if($option == 'e') {
			$table = Enter::display('Enter table name for export');
			$tables = $fixtures->export([$table]);
			Output::items($tables, 'Exported tables');
		} elseif($option == 'i') {
			$table = Enter::display('Enter table name for import');
			$tables = $fixtures->import([$table]);
			Output::items($tables, 'Imported tables');
		}
	}

}


<?php

namespace AbuseIO\Parsers;

use AbuseIO\Models\Incident;

/**
 * Class Netcraft
 * @package AbuseIO\Parsers
 */
class Netcraft extends Parser
{
    /**
     * Create a new Netcraft instance
     *
     * @param \PhpMimeMailParser\Parser $parsedMail phpMimeParser object
     * @param array $arfMail array with ARF detected results
     */
    public function __construct($parsedMail, $arfMail)
    {
        parent::__construct($parsedMail, $arfMail, $this);
    }

    /**
     * Parse attachments
     * @return array    Returns array with failed or success data
     *                  (See parser-common/src/Parser.php) for more info.
     */
    public function parse()
    {
        foreach ($this->parsedMail->getAttachments() as $attachment) {
            if (preg_match(config("{$this->configBase}.parser.report_file"), $attachment->filename)) {
                if (preg_match_all(
                    '/([\w\-]+): (.*)[ ]*\r?\n/',
                    str_replace("\r", "", $attachment->getContent()),
                    $matches
                )) {
                    $report = array_combine($matches[1], $matches[2]);

                    // We need this field to detect the feed, so we need to check it first
                    if (!empty($report['Report-Type'])) {
                        // Handle aliasses first
                        foreach (config("{$this->configBase}.parser.aliases") as $alias => $real) {
                            if ($report['Report-Type'] == $alias) {
                                $report['Report-Type'] = $real;
                            }
                        }

                        $this->feedName = $report['Report-Type'];

                        // If feed is known and enabled, validate data and save report
                        if ($this->isKnownFeed() && $this->isEnabledFeed()) {
                            switch ($report['Source-Type']) {
                                case 'uri':
                                    // Match case 1:
                                    // A single line with 'http* [x.x.x.x]' (note the space)
                                    preg_match(
                                        '/\[([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\]/',
                                        $this->parsedMail->getMessageBody(),
                                        $matches
                                    );
                                    if (count($matches) == 2 && empty($report['Ip'])) {
                                        $report['Ip'] = $matches[1];
                                    }

                                    // Match case 2:
                                    // Somewhere a line will end (watch out for mime split!) 'address x.x.x.x.'
                                    preg_match(
                                        '/address ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\./',
                                        $this->parsedMail->getMessageBody(),
                                        $matches
                                    );
                                    if (count($matches) == 2 && empty($report['Ip'])) {
                                        $report['Ip'] = $matches[1];
                                    }

                                    // Match case 3:
                                    // IPv6 report
                                    if (preg_match(
                                        '/(?>(?>([a-f0-9]{1,4})(?>:(?1)){7}|'.
                                        '(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>('.
                                        '?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:('.
                                        '?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?4)){3}))/',
                                        $this->parsedMail->getMessageBody(),
                                        $matches
                                    )) {
                                        $report['Ip'] = $matches[0];
                                    }
                                    break;
                                case 'ipv4':
                                case 'ipv6':
                                case 'ip-address':
                                default:
                                    $report['Ip'] = $report['Source'];
                                    break;
                            }

                            // Sanity check
                            if ($this->hasRequiredFields($report) === true) {
                                // incident has all requirements met, filter and add!
                                $report = $this->applyFilters($report);

                                // Manually update some fields for easier handling
                                if ($report['Report-Type'] == 'phishing') {
                                    $url = $report['Source'];
                                }

                                if ($report['Report-Type'] == 'malware-attack') {
                                    // Download-Link to Domain / Uri
                                    $url = $report['Download-Link'];
                                }

                                $incident = new Incident();
                                $incident->source      = config("{$this->configBase}.parser.name");
                                $incident->source_id   = false;
                                $incident->ip          = $report['Ip'];
                                $incident->domain      = empty($url) ? false : getDomain($url);
                                $incident->class       = config("{$this->configBase}.feeds.{$this->feedName}.class");
                                $incident->type        = config("{$this->configBase}.feeds.{$this->feedName}.type");
                                $incident->timestamp   = strtotime($report['Date']);
                                $incident->information = json_encode($report);

                                $this->incidents[] = $incident;

                            }
                        }
                    }
                }
            }
        }

        return $this->success();
    }
}


<?php

namespace Lab123\Odin\Entities;

use Illuminate\Database\Eloquent\Model;
use Lab123\Odin\Libs\Api;
use Request;

abstract class Entity extends Model
{
	/**
	 * Return entities loads to response API.
	 *
	 * @var boolean
	 */
	static $loaded = false;

    /**
     * The resource name from model.
     *
     * @var string
     */
    protected $resource = '';

    /**
     * Class Fields Manage.
     *
     * @var Lab123\Odin\FieldManager
     */
    protected $fieldManager = '';

    /**
     * The parent resource.
     *
     * @var string
     */
    protected $parent = '';

    /**
     * Load model from relation.
     *
     * @var array
     */
    public $load = [];

    /**
     * Load only URI.
     *
     * @var array
     */
    public $loadUri = [];

    /**
     * The actions from resource.
     *
     * @var array
     */
    public $actions = [];

    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     * @return void
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        /* Adiciona o Hash Id nas entidades */
        if (config('odin.hashid.active')) {
            self::addPublicId();
        }
    }

    /**
     * Fill the model with an array of attributes.
     *
     * @param array $attributes
     * @return $this
     *
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
     */
    public function fill(array $attributes)
    {
        if ($this->getFieldManager()) {
            $attributes = $this->getFieldManager()->transformToResource($attributes);
        }

        return parent::fill($attributes);
    }

    /**
     * Adiciona propriedade public_id na serialização do recurso
     *
     * @return void
     */
    public function addPublicId()
    {
        parent::append([
            'public_id'
        ]);
    }

    /**
     * Return resource name
     *
     * @return array
     */
    public function getResourceName()
    {
        return ($this->resource) ? $this->resource : $this->getTable();
    }

    /**
     * Return parent URI
     *
     * @return string
     */
    public function getParentUri()
    {
        if ($this->getParentName()) {

            $func = $this->getParentName();
            if (! is_string($func)) {
                return;
            }
            $relat = $this->$func();
            $parentResourceName = $relat->getRelated()->getResourceName();

            $field = $relat->getForeignKey();

            if (! $this->$field/* || ! Request::is($parentResourceName . '/*')*/) {
                return Api::url();
            }

            return Api::url() . '/' . $parentResourceName . '/' . Api::encodeHashId($this->$field);
        }

        return Api::url();
    }

    /**
     * Return parent key name
     *
     * @return string
     */
    public function getParentKeyName()
    {
        if ($this->getParentName()) {

            $func = $this->getParentName();
            $relat = $this->$func();

            /*
             * if (! $relat instanceof \Illuminate\Database\Eloquent\Relations\BelongsTo) {
             * $field = $relat->getForeignKey();
             * } else {
             * $field = 'id';
             * }
             */

            $field = $relat->getForeignKey();

            return $field;
        }

        return 'id';
    }

    public function getParentName()
    {
        return $this->parent;
    }

    /**
     * Return resource URL
     *
     * @return array
     */
    public function getResourceURL()
    {
        return $this->getParentUri() . '/' . $this->getResourceName() . '/' . $this->getId();
    }

    /**
     * Create link attribute to client
     *
     * @return array
     */
    public function getResourceData()
    {
        return $this->getResourceURL();

        /*
         * return [
         * 'type' => $this->getResourceName(),
         * 'uri' => $this->getResourceURL()
         * ];
         */
    }

    /**
     * Create link attribute to client
     *
     * @return array
     */
    public function getActions()
    {
        $actions = [];

        if (is_array($this->actions)) {

            foreach ($this->actions as $action) {
                $actions[$action] = $action;
            }
        }

        return $actions;
    }

    /**
     * Retorna o Id do resource
     *
     * @return array
     */
    public function getId()
    {
        if (config('odin.hashid.active')) {
            return $this->getPublicIdAttribute();
        }

        return $this->id;
    }

    /**
     * Retorna o hash id a partir do Id
     *
     * @return void
     */
    protected function getPublicIdAttribute()
    {
        if ($id = Api::decodeHashId($this->attributes['id'])) {
            return $id;
        }

        return Api::encodeHashId($this->attributes['id']);
    }

    /**
     * Cria o hash id a partir do Id
     *
     * @return void
     */
    protected function setPublicIdAttribute($value)
    {
        $this->attributes['public_id'] = Api::decodeHashId($this->attributes['id']);
    }

    /**
     * Convert the model's attributes to an array.
     *
     * @return array
     */
    public function attributesToArray()
    {
        $array = parent::attributesToArray();

        if ($this->getFieldManager()) {
            $array = $this->getFieldManager()->transformToFrontName($array);
        }

        /*$array = array(
            'uri' => $this->getResourceData()
        ) + $array;*/

        return $array;
    }

    /**
     * Convert the model's attributes to an array.
     *
     * @return array
     */
    public function autoload()
    {
        if (self::$loaded) {
            return;
        }

        if (is_array($this->load)) {
            foreach ($this->load as $k => $load) {
                $this->load($load);
            }
        }

        if (is_array($this->loadUri)) {
            foreach ($this->loadUri as $k => $load) {
                $this->load([
                    $load => function ($query) {
                        $query->select('id', $query->getForeignKey());
                    }
                ]);
            }
        }

        self::$loaded = true;
    }

    /**
     * Get the rules attributes for the model.
     *
     * @return array
     */
    public function getRules()
    {
        return $this->getFieldManager()->rules();
    }

    /**
     * Get the config of autocomplete.
     *
     * @return array
     */
    public function getAutocomplete()
    {
        return $this->getFieldManager()->getAutocomplete();
    }

    /**
     * Create a new Eloquent Collection instance.
     *
     * @param array $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new \Lab123\Odin\Collection($models);
    }

    /**
     * Return instance Field Manager of controller
     *
     * @return object Lab123\Odin\FieldManager
     */
    public function getFieldManager()
    {
        /* Verifica se existe Field Manager com prefixo igual a controller */
        if (! $this->fieldManager) {
            $pathClassExploded = explode('\\', get_class($this));
            $namespace = array_first($pathClassExploded);
            $resourceName = array_last($pathClassExploded);

            /* Verifica se existe o Field Manager para o recurso */
            if (! class_exists("{$namespace}\\FieldManagers\\{$resourceName}FieldManager")) {
                return null;
                echo "Crie o Field Manager {$resourceName}FieldManager em {$namespace}\\FieldManagers";
                exit();
            }

            $this->fieldManager = $namespace . "\\FieldManagers\\{$resourceName}FieldManager";
        }

        /* Ainda precisa instanciar o objeto */
        if (is_string($this->fieldManager)) {
            return new $this->fieldManager();
        }

        /* Objeto já instanciado, só retornar */
        return $this->fieldManager;
    }

    /**
     * Copia a entidade e suas relações
     *
     * @return object
     */
    public function copy($attributes = [])
    {
        // copy attributes
        $new = $this->replicate();

        // fill attributes resource
        $new->fill($attributes);

        // save model before you recreate relations (so it has an id)
        $new->save();

        // re-sync everything
        foreach ($this->relations as $relationName => $values) {
            if ($new->{$relationName}() instanceof \Illuminate\Database\Eloquent\Relations\BelongsToMany) {
                $new->{$relationName}()->sync($values);
            } else {
                $new->{$relationName}()->attach($values);
            }
        }

        return $new;
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\taxonomy;

use canis\base\exceptions\Exception;
use Yii;

/**
 * Collector [[@doctodo class_description:cascade\components\taxonomy\Collector]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Collector extends \canis\base\collector\Module
{
    const EVENT_AFTER_TAXONOMY_REGISTRY = 'afterTaxonomyRegistry';

    /**
     * @inheritdoc
     */
    public function getCollectorItemClass()
    {
        return Item::className();
    }

    /**
     * @inheritdoc
     */
    public function getModulePrefix()
    {
        return 'TaxonomyType';
    }

    /**
     * @inheritdoc
     */
    public function register($owner, $itemComponent, $systemId = null)
    {
        if ($itemComponent instanceof Module) {
            return parent::register($owner, $itemComponent->settings, $systemId);
        }

        return parent::register($owner, $itemComponent, $systemId);
    }

    /**
     * @inheritdoc
     */
    public function mergeExistingItems($originalItem, $newItem)
    {
        $originalItem = parent::mergeExistingItems($originalItem, $newItem);
        $originalItem->models = array_unique(array_merge($originalItem->models, $newItem->models));
        $originalItem->modules = array_unique(array_merge($originalItem->modules, $newItem->modules));
        if ($newItem->systemVersion > $originalItem->systemVersion) {
            if ($this->initializeTaxonomies($originalItem->object, $newItem->initialTaxonomies)) {
                $originalItem->object->systemVersion = $newItem->systemVersion;
                $originalItem->object->save(true, ['systemVersion']);
            }
        }

        return $originalItem;
    }

    /**
     * @inheritdoc
     */
    public function prepareComponent($component)
    {
        if (!Yii::$app->isDbAvailable) {
            return $component;
        }

        Yii::beginProfile('Component:::taxonomy::prepare');
        $taxonomyTypeClass = Yii::$app->classes['TaxonomyType'];
        $component['object'] = $taxonomyTypeClass::findOne(['system_id' => $component['systemId']]);
        if (empty($component['object'])) {
            $component['object'] = new $taxonomyTypeClass();
            $component['object']->name = $component['name'];
            $component['object']->system_id = $component['systemId'];
            $component['object']->system_version = 0;
            if (!$component['object']->save()) {
                throw new Exception("Couldn't save new taxonomy type {$component['systemId']} " . print_r($component['object']->getFirstErrors(), true));
            }
            Yii::trace("Taxonomy type has been initialized {$component['name']} ({$component['systemId']})");
        }

        if (!isset($component['initialTaxonomies'])) {
            $component['initialTaxonomies'] = [];
        }

        if ($component['object']->system_version < $component['systemVersion']) {
            if ($this->initializeTaxonomies($component['object'], $component['initialTaxonomies'])) {
                $component['object']->system_version = $component['systemVersion'];
                if (!$component['object']->save()) {
                    throw new Exception("Couldn't save new taxonomy type {$component['systemId']} with new version");
                }
                Yii::trace("Taxonomy type has been upgraded {$component['name']} ({$component['systemId']}) to version {$component['systemVersion']}");
            } else {
                throw new Exception("Couldn't upgrade taxonomy type {$component['systemId']} to version {$component['systemVersion']}");
            }
        }
        Yii::endProfile('Component:::taxonomy::prepare');

        return $component;
    }

    /**
     * [[@doctodo method_description:initializeTaxonomies]].
     *
     * @param [[@doctodo param_type:model]]      $model      [[@doctodo param_description:model]]
     * @param [[@doctodo param_type:taxonomies]] $taxonomies [[@doctodo param_description:taxonomies]]
     *
     * @return [[@doctodo return_type:initializeTaxonomies]] [[@doctodo return_description:initializeTaxonomies]]
     */
    public function initializeTaxonomies($model, $taxonomies)
    {
        $taxonomyClass = Yii::$app->classes['Taxonomy'];
        foreach ($taxonomies as $systemId => $name) {
            $taxonomy = $taxonomyClass::findOne(['taxonomy_type_id' => $model->id, 'system_id' => $systemId]);
            if (empty($taxonomy)) {
                $taxonomy = new $taxonomyClass();
                $taxonomy->taxonomy_type_id = $model->id;
                $taxonomy->name = $name;
                $taxonomy->system_id = $systemId;
                if (!$taxonomy->save()) {
                    return false;
                }
            }
        }

        return true;
    }
}


<?php

namespace Esockets\Base;

/**
 * Событие, на которое можно подписаться.
 */
final class Event
{
    private $uid = 0;
    /**
     * @var CallbackEventListener[]
     */
    private $listeners = [];

    /**
     * Создаёт нового слушателя на основе callback функции, и возвращает его.
     * По-умолчанию все слушатели находятся в подписанном состоянии.
     *
     * @param callable $callback
     *
     * @return CallbackEventListener
     */
    public function attachCallbackListener(callable $callback): CallbackEventListener
    {
        $uid = $this->uid++;
        return $this->listeners[$uid] = CallbackEventListener::create($uid, $callback, [$this, 'detachListener']);
    }

    public function detachListener(int $uid): void
    {
        if (isset($this->listeners[$uid])) {
            unset($this->listeners);
        }
    }

    /**
     * Чистит контейнер, удаляя все события.
     *
     * @param bool $notSubscribedOnly
     *
     * @return void
     */
    public function clearListeners(bool $notSubscribedOnly = false): void
    {
        if ($notSubscribedOnly) {
            $this->clearNotSubscribedListeners();
        } else {
            $this->listeners = [];
        }
    }

    /**
     * Очистит контейнер ото всех неподписанных слушателей.
     */
    private function clearNotSubscribedListeners(): void
    {
        foreach ($this->listeners as $key => $listener) {
            if (!$listener->isSubscribed()) {
                unset($this->listeners[$key]);
            }
        }
    }

    /**
     * Генерирует наступление события, и оповещает об этом всех слушателей.
     *
     * @param array ...$arguments
     */
    public function call(...$arguments): void
    {
        array_walk($this->listeners, function ($eventListener) use ($arguments) {
            /**
             * @var $eventListener CallbackEventListener
             */
            $eventListener->call($arguments);
        });
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Stats.php.
 *
 * @author    allen05ren <allen05ren@outlook.com>
 * @copyright 2016 overtrue <i@overtrue.me>
 *
 * @see       https://github.com/overtrue
 * @see       http://overtrue.me
 */

namespace EasyWeChat\ShakeAround;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class Stats.
 */
class Stats extends AbstractAPI
{
    const API_DEVICE = 'https://api.weixin.qq.com/shakearound/statistics/device';
    const API_DEVICE_LIST = 'https://api.weixin.qq.com/shakearound/statistics/devicelist';
    const API_PAGE = 'https://api.weixin.qq.com/shakearound/statistics/page';
    const API_PAGE_LIST = 'https://api.weixin.qq.com/shakearound/statistics/pagelist';

    /**
     * Fetch statistics data by deviceId.
     *
     * @param array $deviceIdentifier
     * @param int   $beginDate        (Unix timestamp)
     * @param int   $endDate          (Unix timestamp)
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function deviceSummary(array $deviceIdentifier, $beginDate, $endDate)
    {
        $params = [
            'device_identifier' => $deviceIdentifier,
            'begin_date' => $beginDate,
            'end_date' => $endDate,
        ];

        return $this->parseJSON('json', [self::API_DEVICE, $params]);
    }

    /**
     * Fetch all devices statistics data by date.
     *
     * @param int $timestamp
     * @param int $pageIndex
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function batchDeviceSummary($timestamp, $pageIndex)
    {
        $params = [
            'date' => $timestamp,
            'page_index' => $pageIndex,
        ];

        return $this->parseJSON('json', [self::API_DEVICE_LIST, $params]);
    }

    /**
     * Fetch statistics data by pageId.
     *
     * @param int $pageId
     * @param int $beginDate (Unix timestamp)
     * @param int $endDate   (Unix timestamp)
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function pageSummary($pageId, $beginDate, $endDate)
    {
        $params = [
            'page_id' => $pageId,
            'begin_date' => $beginDate,
            'end_date' => $endDate,
        ];

        return $this->parseJSON('json', [self::API_PAGE, $params]);
    }

    /**
     * Fetch all pages statistics data by date.
     *
     * @param int $timestamp
     * @param int $pageIndex
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function batchPageSummary($timestamp, $pageIndex)
    {
        $params = [
            'date' => $timestamp,
            'page_index' => $pageIndex,
        ];

        return $this->parseJSON('json', [self::API_PAGE_LIST, $params]);
    }
}


<?php

/**
 * Manage Form
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib;

/**
 * This class manage the Form
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Mail
{
	/**
	 * the recipient of mail
	 * @access private
	 * @var    array
	 */
	private $_aRecipient = array();

	/**
	 * the from of mail
	 * @access private
	 * @var    string
	*/
	private $_sFrom = "no-reply@iscreenway.com";

	/**
	 * the subject of mail
	 * @access private
	 * @var    string
	 */
	private $_sSubject = "nosubject";

	/**
	 * the content of mail
	 * @access private
	 * @var    string
	 */
	private $_sMessage = "";

	/**
	 * the format of mail
	 * @access private
	 * @var    string
	 */
	private $_sFormat = "TXT"; // valeur : TXT ou HTML;

	/**
	 * file to send with mail
	 * @access private
	 * @var    array
	 */
	private $_aAttachments = array();

	/**
	 * add a recipient of mail
	 *
	 * @access public private
	 * @param  string $sRecipient
	 * @return Mail
	 */
	public function addRecipient(string $sRecipient) : Mail
	{
		$this->_aRecipient[] = $sRecipient;
		return $this;
	}

	/**
	 * add a file to the mail
	 *
	 * @access public private
	 * @param  string $sFileName
	 * @param  string $sContent
	 * @param  string $sType
	 * @return bool
	 */
	public function attachFile(string $sFileName, string $sContent, string $sType) : bool
	{
		$this->_aAttachments[] = array(
			"name" => $sFileName,
			"content" => $sContent,
			"type" => $sType
		);

		return true;
	}

	/**
	 * set the from of mail
	 *
	 * @access public private
	 * @param  string $sFrom
	 * @return Mail
	 */
	public function setFrom(string $sFrom) : Mail
	{
		$this->_sFrom = $sFrom;
		return $this;
	}

	/**
	 * set the subjet of mail
	 *
	 * @access public private
	 * @param  string $sSubject
	 * @return Mail
	 */
	public function setSubject(string $sSubject) : Mail
	{
		$this->_sSubject = $sSubject;
		return $this;
	}

	/**
	 * set the message of mail
	 *
	 * @access public private
	 * @param  string $sMessage
	 * @return Mail
	 */
	public function setMessage(string $sMessage) : Mail
	{
		$this->_sMessage = $sMessage;
		return $this;
	}

	/**
	 * set the format HTML of mail
	 *
	 * @access public private
	 * @return Mail
	 */
	public function setFormatHtml() : Mail
	{
		$this->_sFormat = "HTML";
		return $this;
	}

	/**
	 * set the format HTML of mail
	 *
	 * @access public private
	 * @return Mail
	 */
	public function setFormatText() : Mail
	{
		$this->_sFormat = "TXT";
		return $this;
	}

	/**
	 * send the mail
	 *
	 * @access public private
	 * @return bool
	 */
	public function send() : bool
	{
		$sHeaders = 'From: ' . $this->_sFrom . "\r\n";

		if (empty($this->_aAttachments)) {

			if ($this->_sFormat == "HTML") {

				$sHeaders .= 'MIME-Version: 1.0' . "\r\n";
				$sHeaders .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
			}

			return mail(implode(',', $this->_aRecipient), $this->_sSubject, $this->_sMessage, $sHeaders);
		}
		else {

			$sBoundary = "_" . md5(uniqid(rand()));

			$sAttached = "";

			foreach ($this->_aAttachments as $aAttachment) {

				$sAttached_file = chunk_split(base64_encode($aAttachment["content"]));
				$sAttached = "\n\n" . "--" . $sBoundary . "\nContent-Type: application; name=\"" . $aAttachment["name"] . "\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"" . $aAttachment["name"] . "\"\r\n\n" . $sAttached_file . "--" . $sBoundary . "--";
			}

			$sHeaders = 'From: ' . $this->_sFrom . "\r\n";
			$sHeaders .= "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$sBoundary\"\r\n";

			$sBody = "--" . $sBoundary . "\nContent-Type: " . ($this->_sFormat == "HTML" ? "text/html" : "text/plain") . "; charset=UTF-8\r\n\n" . $this->_sMessage . $sAttached;

			return mail(implode(',', $this->_aRecipient), $this->_sSubject, $sBody, $sHeaders);
		}
	}
}


<?php
namespace eMacros\Runtime\Collection;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;
use eMacros\Symbol;

class ArrayMap implements Applicable {
	/**
	 * Applies a callback to a given array
	 * Usage: (Array::map "strtoupper" (array "a" "b" "c"))
	 * Returns: array
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		$nargs = count($arguments);
		if ($nargs == 0) throw new \BadFunctionCallException("ArrayMap: No callback specified.");
		elseif ($nargs == 1) throw new \BadFunctionCallException("ArrayMap: No target specified.");
		$op = $arguments[0]->evaluate($scope);

		if (is_callable($op)) {
			$args = [];
			$it = $arguments->getIterator();
			$it->rewind();

			for ($it->next(); $it->valid(); $it->next()) {
				 $el = $it->current()->evaluate($scope);

				 if ($el instanceof \IteratorAggregate) {
				 	$eit = $el->getIterator();
				 	$eit->rewind();
				 	$el = [];
				 	for (;$eit->valid(); $eit->next())
				 		$el[] = $eit->current();
				 }

				 $args[] = $el;
			}

			array_unshift($args, $op);
			return call_user_func_array('array_map', $args);
		}

		throw new \InvalidArgumentException("ArrayMap: Expected callable as first argument.");
	}
}
?>


<?php

namespace Litecms\Forum\Http\Controllers;

use App\Http\Controllers\ResourceController as BaseController;
use Form;
use Litecms\Forum\Http\Requests\ResponseRequest;
use Litecms\Forum\Interfaces\ResponseRepositoryInterface;
use Litecms\Forum\Interfaces\QuestionRepositoryInterface;
use Litecms\Forum\Models\Response;
use Illuminate\Http\Request;

/**
 * Resource controller class for response.
 */
class ResponseResourceController extends BaseController
{

    /**
     * Initialize response resource controller.
     *
     * @param type ResponseRepositoryInterface $response
     *
     * @return null
     */
    public function __construct(ResponseRepositoryInterface $response,
                                QuestionRepositoryInterface $question)
    {
        parent::__construct();
        $this->repository = $response;
        $this->question = $question;
        $this->repository
            ->pushCriteria(\Litepie\Repository\Criteria\RequestCriteria::class)
            ->pushCriteria(\Litecms\Forum\Repositories\Criteria\ResponseResourceCriteria::class);
    }

    /**
     * Display a list of response.
     *
     * @return Response
     */
    public function index(ResponseRequest $request)
    {
        $view = $this->response->theme->listView();

        if ($this->response->typeIs('json')) {
            $function = camel_case('get-' . $view);
            return $this->repository
                ->setPresenter(\Litecms\Forum\Repositories\Presenter\ResponsePresenter::class)
                ->$function();
        }

        $responses = $this->repository->paginate();

        return $this->response->title(trans('forum::response.names'))
            ->view('forum::response.index', true)
            ->data(compact('responses'))
            ->output();
    }

    /**
     * Display response.
     *
     * @param Request $request
     * @param Model   $response
     *
     * @return Response
     */
    public function show(ResponseRequest $request, Response $response)
    {

        if ($response->exists) {
            $view = 'forum::response.show';
        } else {
            $view = 'forum::response.new';
        }

        return $this->response->title(trans('app.view') . ' ' . trans('forum::response.name'))
            ->data(compact('response'))
            ->view($view, true)
            ->output();
    }

    /**
     * Show the form for creating a new response.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function create(ResponseRequest $request)
    {

        $response = $this->repository->newInstance([]);
        return $this->response->title(trans('app.new') . ' ' . trans('forum::response.name'))
            ->view('forum::response.create', true)
            ->data(compact('response'))
            ->output();
    }

    /**
     * Create new response.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function store(ResponseRequest $request)
    {

        try {
            $request              = $request->all();
            $slug = $request['slug'];
            $attributes['comment'] = $request['comment'];
            $attributes['question_id'] = $request['question_id'];
            $attributes['user_id']   = user_id();
            $attributes['user_type'] = user_type();
            $response                 = $this->repository->create($attributes);

            return $this->response->message(trans('messages.success.created', ['Module' => trans('forum::response.name')]))
                ->code(204)
                ->status('success')
                ->url(trans_url('/discussion/'.$slug))
                ->redirect();
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(trans_url('/question/'.$slug))
                ->redirect();
        }

    }

    /**
     * Show response for editing.
     *
     * @param Request $request
     * @param Model   $response
     *
     * @return Response
     */
    public function edit(ResponseRequest $request, Response $response)
    {
        return $this->response->title(trans('app.edit') . ' ' . trans('forum::response.name'))
            ->view('forum::response.edit', true)
            ->data(compact('response'))
            ->output();
    }

    /**
     * Update the response.
     *
     * @param Request $request
     * @param Model   $response
     *
     * @return Response
     */
    public function update(ResponseRequest $request, Response $response)
    {
        try {
            $attributes = $request->all();
            $id = $attributes['question_id'];
            $question = $this->question->selectquestion($id);
            $response->update($attributes);
            return redirect('/discussion/'.$question['slug']);
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('forum/response/' . $response->getRouteKey()))
                ->redirect();
        }

    }

    /**
     * Remove the response.
     *
     * @param Model   $response
     *
     * @return Response
     */
    public function destroy(ResponseRequest $request, Response $response)
    {
        try {
            $id = $response['question_id'];
            $question = $this->question->selectquestion($id);
            $response->delete();
            return redirect('/discussion/'.$question['slug']);

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('forum/response/' . $response->getRouteKey()))
                ->redirect();
        }

    }

    /**
     * Remove multiple response.
     *
     * @param Model   $response
     *
     * @return Response
     */
    public function delete(ResponseRequest $request, $type)
    {
        try {
            $ids = hashids_decode($request->input('ids'));

            if ($type == 'purge') {
                $this->repository->purge($ids);
            } else {
                $this->repository->delete($ids);
            }

            return $this->response->message(trans('messages.success.deleted', ['Module' => trans('forum::response.name')]))
                ->status("success")
                ->code(202)
                ->url(guard_url('forum/response'))
                ->redirect();

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->status("error")
                ->code(400)
                ->url(guard_url('/forum/response'))
                ->redirect();
        }

    }

    /**
     * Restore deleted responses.
     *
     * @param Model   $response
     *
     * @return Response
     */
    public function restore(ResponseRequest $request)
    {
        try {
            $ids = hashids_decode($request->input('ids'));
            $this->repository->restore($ids);

            return $this->response->message(trans('messages.success.restore', ['Module' => trans('forum::response.name')]))
                ->status("success")
                ->code(202)
                ->url(guard_url('/forum/response'))
                ->redirect();

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->status("error")
                ->code(400)
                ->url(guard_url('/forum/response/'))
                ->redirect();
        }

    }

    public function bestanswer(Request $request)
    {

        $request = $request->all();
        $c = $this->repository->updatecomment($request);
        return redirect('/discussion/'.$request['slug']);

    }

}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web;

/**
 * ObjectViewEvent [[@doctodo class_description:cascade\components\web\ObjectViewEvent]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class ObjectViewEvent extends \yii\base\Event
{
    /**
     * @var [[@doctodo var_type:action]] [[@doctodo var_description:action]]
     */
    public $action;
    /**
     * @var [[@doctodo var_type:accessed]] [[@doctodo var_description:accessed]]
     */
    public $accessed = true;
    /**
     * @var [[@doctodo var_type:_object]] [[@doctodo var_description:_object]]
     */
    protected $_object;
    /**
     * @var [[@doctodo var_type:_objectType]] [[@doctodo var_description:_objectType]]
     */
    protected $_objectType;

    /**
     * [[@doctodo method_description:handleWith]].
     *
     * @param [[@doctodo param_type:callable]] $callable [[@doctodo param_description:callable]]
     * @param boolean                          $always   [[@doctodo param_description:always]] [optional]
     *
     * @return [[@doctodo return_type:handleWith]] [[@doctodo return_description:handleWith]]
     */
    public function handleWith($callable, $always = false)
    {
        if ($this->handled && !$always) {
            return false;
        }
        if (!is_callable($callable)) {
            return false;
        }
        call_user_func($callable, $this);

        return false;
    }

    /**
     * Set object.
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     */
    public function setObject($object)
    {
        if (is_null($this->_objectType)) {
            $this->objectType = $object->objectType;
        }
        $this->_object = $object;
    }

    /**
     * Get object.
     *
     * @return [[@doctodo return_type:getObject]] [[@doctodo return_description:getObject]]
     */
    public function getObject()
    {
        return $this->_object;
    }

    /**
     * Set object type.
     *
     * @param [[@doctodo param_type:type]] $type [[@doctodo param_description:type]]
     */
    public function setObjectType($type)
    {
        if (!is_object($type)) {
            if (Yii::$app->collectors['types']->has($type)) {
                $type = Yii::$app->collectors['types']->getOne($type)->object;
            } else {
                $type = null;
            }
        }
        $this->_objectType = $type;
    }

    /**
     * Get object type.
     *
     * @return [[@doctodo return_type:getObjectType]] [[@doctodo return_description:getObjectType]]
     */
    public function getObjectType()
    {
        return $this->_objectType;
    }
}


<?php

/**
 * Manage Less
 *
 * @category  	Venus
 * @package		Venus\lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib;

/**
 * Manage Less
 *
 * @category  	Venus
 * @package		Venus\lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Less
{
    /**
     * @var string
     */
    const LESS_WINDOWS = LESS_WINDOWS;

	/**
	 * translate the content
	 *
	 * @access public
	 * @param  mixed $sFile content to translate
	 * @return void
	 */
	public static function toCss(string $sFile)
	{
	    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {

	        $sCmd = self::LESS_WINDOWS." ".$sFile." --watch";
            $sContent = shell_exec($sCmd);
	    }
	    else {

	        $sCmd = "lessc ".$sFile." --no-color 2>&1";
            $sContent = shell_exec($sCmd);
	    }

        header("content-type:text/css");
        echo $sContent;
	}
}


<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types = 1);

namespace Cawa\Renderer;

class HtmlElement extends Element
{
    /**
     * @param string $tag
     * @param string $content
     */
    public function __construct(string $tag = null, string $content = null)
    {
        if (is_null($this->tag) && is_null($tag)) {
            throw new \InvalidArgumentException(sprintf('Missing tag on %s', get_class($this)));
        }

        if ($tag) {
            $this->tag = $tag;
        }

        parent::__construct($content);
    }

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

    /**
     * @return string
     */
    public function getTag() : string
    {
        return $this->tag;
    }

    /**
     * @param string $tag
     *
     * @return $this|self
     */
    public function setTag(string $tag) : self
    {
        $this->tag = $tag;

        return $this;
    }

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

    /**
     * @param string $name
     *
     * @return string|null
     */
    public function getAttribute(string $name)
    {
        return isset($this->attributes[$name]) ? $this->attributes[$name] : null;
    }

    /**
     * @param array $attributes
     *
     * @return $this|self
     */
    public function addAttributes(array $attributes) : self
    {
        foreach ($attributes as $key => $value) {
            $this->attributes[$key] = $value;
        }

        return $this;
    }

    /**
     * @param string $name
     * @param string $value
     *
     * @return $this|self
     */
    public function addAttribute(string $name, string $value) : self
    {
        $this->attributes[$name] = $value;

        return $this;
    }

    /**
     * @param string $name
     *
     * @return bool
     */
    public function hasAttribute(string $name) : bool
    {
        return isset($this->attributes[$name]) && $this->attributes[$name] ? true : false;
    }

    /**
     * @param string $name
     *
     * @return $this|self
     */
    public function removeAttribute(string $name) : self
    {
        if (isset($this->attributes[$name])) {
            unset($this->attributes[$name]);
        }

        return $this;
    }

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

    /**
     * @param array $props
     *
     * @return $this|self
     */
    public function addProps(array $props) : self
    {
        foreach ($props as $value) {
            $this->props[] = $value;
        }

        return $this;
    }

    /**
     * @param string $value
     *
     * @return $this|self
     */
    public function addProp(string $value) : self
    {
        $this->props[] = $value;

        return $this;
    }

    /**
     * @param string $name
     *
     * @return bool
     */
    public function hasProp(string $name) : bool
    {
        return in_array($name, $this->props) ? true : false;
    }

    /**
     * @param string $name
     *
     * @return $this|self
     */
    public function removeProp(string $name) : self
    {
        if (($key = array_search($name, $this->props)) !== false) {
            unset($this->props[$key]);
        }

        return $this;
    }

    /**
     * @param string $value
     *
     * @return $this|self
     */
    public function setId(string $value) : self
    {
        return $this->addAttribute('id', $value);
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->getAttribute('id');
    }

    /**
     * @return $this|self
     */
    public function generateId() : self
    {
        return $this->setId('uid-' . mt_rand());
    }

    /**
     * @return array
     */
    private function getStyles() : array
    {
        return $this->getAttribute('style') ? explode(';', $this->getAttribute('style')) : [];
    }

    /**
     * @param array|string $style
     *
     * @return $this|self
     */
    public function setStyle($style) : self
    {
        if (is_array($style) && sizeof($style)) {
            $finalStyle = implode(';', $style);
        } elseif (is_string($style)) {
            $finalStyle = $style;
        } else {
            $finalStyle = '';
        }

        return $this->addAttribute('style', trim($finalStyle, ';'));
    }

    /**
     * @param array|string $value
     *
     * @return $this|self
     */
    public function addStyle($value) : self
    {
        $currentStyles = $this->getStyles();
        $styles = array_unique(array_merge($currentStyles, (is_array($value) ? $value : explode(';', $value))));

        return $this->setStyle($styles);
    }

    /**
     * @return array
     */
    public function getClasses() : array
    {
        return $this->getAttribute('class') ? explode(' ', $this->getAttribute('class')) : [];
    }

    /**
     * @param string $name
     *
     * @return bool
     */
    public function hasClass(string $name) : bool
    {
        return $this->getAttribute('class') ? in_array($name, explode(' ', $this->getAttribute('class'))) : false;
    }

    /**
     * @param array|string $value
     *
     * @return $this|self
     */
    public function addClass($value) : self
    {
        $currentClasses = $this->getClasses();
        $classes = array_unique(array_merge($currentClasses, (is_array($value) ? $value : explode(' ', $value))));

        return $this->addAttribute('class', implode(' ', $classes));
    }

    /**
     * @param string $value
     *
     * @return $this|self
     */
    public function removeClass(string $value) : self
    {
        $currentClasses = $this->getClasses();
        $classes = array_diff($currentClasses, explode(' ', $value));

        return $this->addAttribute('class', implode(' ', $classes));
    }

    /**
     * @throws \LogicException
     *
     * @return string
     */
    public function render()
    {
        if (!$this->tag) {
            throw new \LogicException('Missing tag');
        }

        return $this->isRenderable() ? self::htmlTag($this->tag, $this->attributes, $this->props, $this->content) : '';
    }

    /**
     * @return string
     */
    public function renderInner() : string
    {
        return $this->content;
    }

    /**
     * @return array
     */
    public function renderOuter() : array
    {
        if (!$this->tag) {
            throw new \LogicException('Missing tag');
        }

        $render = self::htmlTag($this->tag, $this->attributes, $this->props, '[-INNER-]');

        return explode('[-INNER-]', $render);
    }

    /**
     * @param string $tag
     * @param array $attributes
     * @param array $props
     * @param string $innerHtml
     *
     * @throws \InvalidArgumentException
     *
     * @return string
     */
    public static function htmlTag(string $tag, array $attributes = [], array $props = [], $innerHtml = null) : string
    {
        $invalid = $tag[0] != '<' || substr($tag, -1) != '>';

        if (substr($tag, -2) == '/>') {
            $control = trim(substr($tag, 0, -2));
        } else {
            $control = $tag;
        }

        $invalid = $invalid ? $invalid : strpos($control, ' ') !== false;

        if ($invalid) {
            throw new \InvalidArgumentException(sprintf("Please provide a valid tag format, '%s' given", $tag));
        }

        $autoClose = (substr($tag, -2) == '/>');

        $return = ($autoClose) ? trim(substr($tag, 0, -2)) : trim(substr($tag, 0, -1));
        $return .= ' ' . self::htmlAttribute($attributes);
        $return .= ' ' . implode(' ', $props);
        $return = trim($return);

        if ($autoClose) {
            $return .= ' />';
        } else {
            $return .= '>';
            if (!is_null($innerHtml)) {
                $return .= $innerHtml;
            }

            $return .= '</' . substr($tag, 1);
        }

        return $return;
    }

    /**
     * @param array $attributes
     *
     * @return string
     */
    public static function htmlAttribute(array $attributes = []) : string
    {
        $return = '';
        foreach ($attributes as $attribute => $value) {
            $json = false;
            if ($attribute == 'data-options') {
                if (is_array($value) || is_object($value)) {
                    $value = json_encode($value);
                    $json = true;
                } elseif (is_string($value)) {
                    json_decode($value);
                    $json = json_last_error() == JSON_ERROR_NONE;
                }
            }

            $return .= $attribute;
            if (is_null($value)) {
                $return .= ' ';
            } else {
                $return .= '=' . (!$json ? '"' : "'");

                if (!is_array($value)) {
                    $return .= is_bool($value) ? ($value ? 'true' : 'false') : htmlentities($value);
                } else {
                    switch ($attribute) {
                        case 'style':
                            $return .= implode('; ', $value);
                            break;
                        default:
                            $return .= implode(' ', $value);
                            break;
                    }
                }
                $return .= (!$json ? '"' : "'") . ' ';
            }
        }

        return $return;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository\RepositoryTrait;

use OpenOrchestra\ModelInterface\Repository\RepositoryTrait\KeywordableTraitInterface;

/**
 * Trait KeywordableTrait
 */
trait KeywordableTrait
{
    /**
     * @param string $condition
     * @param int    $count
     * @param array  $aliases
     * @param string $delimiter
     *
     * @return array|null
     */
    public function transformConditionToMongoCondition($condition, $count = 0, array $aliases = array(), $delimiter = '##')
    {
        if (!is_null($condition)) {
            $encapsuledElements = array();
            preg_match_all(KeywordableTraitInterface::GET_BALANCED_BRACKETS, $condition, $encapsuledElements);
            foreach ($encapsuledElements[0] as $key => $encapsuledElement) {
                $alias = $delimiter.$count.$delimiter;
                $condition = preg_replace('/'.preg_quote($encapsuledElement).'/', $alias, $condition, 1);
                $aliases[$alias] = $this->transformSubConditionToMongoCondition($encapsuledElements[1][$key], $aliases);
                $count++;
            }
            if (count($encapsuledElements[0]) > 0) {
                $result = $this->transformConditionToMongoCondition($condition, $count, $aliases, $delimiter);
            } else {
                $result = $this->transformSubConditionToMongoCondition($condition, $aliases);
            }
        } else {
            $result = null;
        }

        return $result;
    }

    /**
     * @param string $condition
     * @param array  $aliases
     *
     * @return array|null
     */
    public function transformSubConditionToMongoCondition($condition, array &$aliases)
    {
        $elements = array();
        $subElements = array();
        $operator = '$and';
        if (preg_match_all(KeywordableTraitInterface::IS_AND_BOOLEAN, $condition, $elements)) {
            preg_match_all(KeywordableTraitInterface::GET_AND_SUB_BOOLEAN, $condition, $subElements);
        } elseif  (preg_match_all(KeywordableTraitInterface::IS_OR_BOOLEAN, $condition, $elements)) {
            $operator = '$or';
            preg_match_all(KeywordableTraitInterface::GET_OR_SUB_BOOLEAN, $condition, $subElements);
        }
        if (count($elements) > 0) {
            foreach ($elements as $key => $element) {
                $elements[$key] = array_merge($element, $subElements[$key]);
            }
            $result = array();
            foreach ($elements[2] as $key => $element) {
                if (array_key_exists($element, $aliases)) {
                    if ($elements[1][$key] != '') {
                        array_push($result, array('$not' => $aliases[$element]));
                    } else {
                        array_push($result, $aliases[$element]);
                    }
                    unset($aliases[$element]);
                } else {
                    $comparison = ($elements[1][$key] == '') ? '$eq' : '$ne';
                    array_push($result, array('keywords.$id' => array($comparison => new \MongoId($element))));
                }
            }

            return (array($operator => $result));
        }

        return null;
    }
}


<?php

/**
 * Provides an API for authentication and includes concrete authentication
 * adapters for common use case scenarios.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.auth.introduction.html Zend_Auth
 */
class Benri_Auth extends Zend_Auth
{
    /**
     * Authenticates against the supplied adapter.
     *
     * @param Zend_Auth_Adapter_Interface $adapter The adapter to use
     * @return Zend_Auth_Result
     * @see http://framework.zend.com/manual/1.12/en/zend.auth.introduction.html#zend.auth.introduction.adapters Zend_Auth_Adapter_Interface
     * @see http://framework.zend.com/manual/1.12/en/zend.auth.introduction.html#zend.auth.introduction.results Zend_Auth_Result
     */
    public function authenticate(Zend_Auth_Adapter_Interface $adapter)
    {
        // Authenticates against the supplied adapter.
        $result = $adapter->authenticate();

        /*
         * ZF-7546 - prevent multiple succesive calls from storing inconsistent
         * results.
         *
         * Ensure storage has clean state.
         */
        if ($this->hasIdentity()) {
            $this->clearIdentity();
        }

        if ($result->isValid()) {
            $this->getStorage()
                ->write($adapter->getResultRowObject());
        }

        return $result;
    }

    /**
     * Returns an instance of Benri_Auth.
     *
     * @return Benri_Auth
     */
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new static();
        }

        return self::$_instance;
    }
}


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

namespace RedKiteCms\Content\Theme;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Content\SlotsManager\SlotsManagerFactoryInterface;
use RedKiteCms\Plugin\Plugin;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Finder\Finder;

/**
 * Class Theme is the object assigned to handle a theme
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Theme
 */
class Theme extends ThemeBase
{
    /**
     * @type array
     */
    private $templateBlocks;
    /**
     * @type string
     */
    private $themeDefinition;
    /**
     * @type string
     */
    private $homepageTemplate;
    /**
     * @var \RedKiteCms\Plugin\Plugin
     */
    private $plugin;
    /**
     * @type \RedKiteCms\Content\SlotsManager\SlotsManagerFactoryInterface
     */
    private $slotsManagerFactory;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     * @param \RedKiteCms\Content\SlotsManager\SlotsManagerFactoryInterface $slotsManagerFactory
     */
    public function __construct(ConfigurationHandler $configurationHandler, SlotsManagerFactoryInterface $slotsManagerFactory)
    {
        parent::__construct($configurationHandler);

        $this->slotsManagerFactory = $slotsManagerFactory;
    }

    /**
     * @return \RedKiteCms\Plugin\Plugin
     */
    public function getPlugin()
    {
        return $this->plugin;
    }

    /**
     * Boots the theme from the given theme plugin
     *
     * @param \RedKiteCms\Plugin\Plugin $theme
     *
     * @return $this
     */
    public function boot(Plugin $theme)
    {
        $this->plugin = $theme;

        parent::boot($theme);

        $this->initTemplates();
        $this->initHomepageTemplate();

        return $this;
    }

    /**
     * Returns the template used by the theme homepage
     *
     * @return string
     */
    public function homepageTemplate()
    {
        return $this->homepageTemplate;
    }

    /**
     * Adds the default theme slots to the page which uses the given template
     *
     * @param string $templateName
     * @param string $username
     */
    public function addTemplateSlots($templateName, $username)
    {
        if (!array_key_exists($templateName, $this->templateBlocks)) {
            return null;
        }

        $blocks = $this->templateBlocks[$templateName];
        $this->addSlots($blocks, $username);
    }

    private function initTemplates()
    {
        $templateNames = array_keys($this->templates["template"]);
        foreach ($templateNames as $templateName) {
            $blocks = array();
            $templateFileName = $this->themeDir . '/' . $templateName;
            if (!is_dir($templateFileName)) {
                $this->templateBlocks[$templateName] = $blocks;

                continue;
            }
            $finder = new Finder();
            $slotFiles = $finder->files()->in($this->themeDir . '/' . $templateName);
            foreach ($slotFiles as $slotFile) {
                $slotName = basename($slotFile, '.json');
                $slot = json_decode(FilesystemTools::readFile((string)$slotFile), true);
                $blocks[$slotName] = $slot["blocks"];
            }

            $this->templateBlocks[$templateName] = $blocks;
        }
    }

    private function initHomepageTemplate()
    {
        $this->homepageTemplate = $this->configurationHandler->homepageTemplate();
        if (null === $this->homepageTemplate) {
            $this->homepageTemplate = $this->themeDefinition["home_template"];
        }
    }

    private function addSlots(array $blocks, $username)
    {
        foreach ($blocks as $slotName => $slotBlocks) {
            $slotManager = $this->slotsManagerFactory->createSlotManager('page');
            $slotManager->addSlot($slotName, $slotBlocks, $username);
        }
    }
}


<?php

namespace Scalify\PuppetMaster\Client;

use GuzzleHttp\ClientInterface as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class Client implements ClientInterface
{
    /** @var string */
    private $endpoint;

    /** @var string */
    private $apiToken;

    /** @var GuzzleClient */
    private $client;

    /**
     * The amount of time to wait between fetching an updated job from the puppet-master api.
     *
     * @var int
     */
    private $syncSleepMs = 500;

    /**
     * Client constructor.
     *
     * @param GuzzleClient $client
     * @param string       $endpoint
     * @param string       $apiToken
     */
    public function __construct(GuzzleClient $client, string $endpoint, string $apiToken)
    {
        $this->endpoint = trim($endpoint, "/");
        $this->apiToken = trim($apiToken);
        $this->client = $client;
    }

    /**
     * @inheritdoc
     */
    public function setSyncSleepMs(int $syncSleepMs)
    {
        $this->syncSleepMs = $syncSleepMs;
    }

    /**
     * @inheritDoc
     */
    public function getJobs(int $page, int $perPage): array
    {
        return $this->getJobsByStatus("", $page, $perPage);
    }

    /**
     * @inheritDoc
     */
    public function getJobsByStatus(string $status, int $page, int $perPage): array
    {
        $request = new Request("GET", $this->buildUrl(sprintf("/jobs?status=%s&page=%d&per_page=%d", $status, $page, $perPage)));
        $response = $this->send($request);

        if ($response->getStatusCode() !== 200) {
            throw new ClientException(sprintf("Unexpected response: %d %s", $response->getStatusCode(), $response->getReasonPhrase()), $request, $response);
        }

        $data = $this->getJsonBody($request, $response);

        $jobs = [];
        foreach ($data as $values) {
            $jobs[] = new Job($values);
        }

        return $jobs;
    }

    /**
     * Builds the request URL out of the baseUrl and given path.
     *
     * @param string $path
     *
     * @return string
     */
    private function buildUrl(string $path)
    {
        return sprintf("%s/%s", $this->endpoint, trim($path, "/"));
    }

    /**
     * Execute a request, adding required JSON headers and authorization.
     *
     * @param RequestInterface $request
     *
     * @return ResponseInterface
     */
    protected function send(RequestInterface $request): ResponseInterface
    {
        $request = $request->withHeader("Authorization", sprintf("Bearer %s", $this->apiToken));
        $request = $request->withHeader("Content-Type", "application/json");
        $request = $request->withHeader("Accept", "application/json");

        try {
            $response = $this->client->send($request);
        } catch (GuzzleException $e) {
            if ($e->getCode() === 401) {
                throw new ClientException("Authorization failed. Did you specify the right api token?", $request, null, $e);
            }

            throw new ClientException(sprintf("Failed to execute request (code %d): %s", $e->getCode(), $e->getMessage()), $request, null, $e);
        }

        return $response;
    }

    /**
     * Returns the JSON data field from given response.
     *
     * @param RequestInterface  $request
     * @param ResponseInterface $response
     *
     * @return array
     */
    private function getJsonBody(RequestInterface $request, ResponseInterface $response): array
    {
        $data = json_decode($response->getBody(), true);
        if (!$data || !is_array($data) || !array_key_exists("data", $data)) {
            throw new ClientException("Response body does not contain a valid JSON object.", $request, $response);
        }

        if (!is_array($data) || !is_array($data["data"])) {
            throw new ClientException("Not sure what happened. The list jobs endpoint didn't return a list. :worried:", $request, $response);
        }

        return $data["data"];
    }

    /**
     * @inheritDoc
     */
    public function createJob(CreateJob $createJob): Job
    {
        $request = new Request("POST", $this->buildUrl("/jobs"), [], json_encode($createJob->toArray()));
        $response = $this->send($request);

        if ($response->getStatusCode() !== 201) {
            throw new ClientException(sprintf("Unexpected response: %d %s", $response->getStatusCode(), $response->getReasonPhrase()), $request, $response);
        }

        $data = $this->getJsonBody($request, $response);

        return new Job($data);
    }

    /**
     * @inheritdoc
     */
    public function executeSynchronously(CreateJob $createJob): Job
    {
        $job = $this->createJob($createJob);

        do {
            $job = $this->getJob($job->getUUID());
            if ($job->getStatus() !== Job::STATUS_DONE) {
                usleep($this->syncSleepMs * 1000);
            }
        } while ($job->getStatus() !== Job::STATUS_DONE);

        return $job;
    }

    /**
     * @inheritDoc
     */
    public function getJob(string $uuid): Job
    {
        $request = new Request("GET", $this->buildUrl(sprintf("/jobs/%s", $uuid)));
        $response = $this->send($request);

        if ($response->getStatusCode() !== 200) {
            throw new ClientException(sprintf("Unexpected response: %d %s", $response->getStatusCode(), $response->getReasonPhrase()), $request, $response);
        }

        $data = $this->getJsonBody($request, $response);

        return new Job($data);
    }

    /**
     * @inheritDoc
     */
    public function deleteJob(string $uuid)
    {
        $request = new Request("DELETE", $this->buildUrl(sprintf("/jobs/%s", $uuid)));
        $response = $this->send($request);

        if ($response->getStatusCode() !== 204) {
            throw new ClientException(sprintf("Unexpected response: %d %s", $response->getStatusCode(), $response->getReasonPhrase()), $request, $response);
        }
    }

}


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

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Content\BlockManager\BlockManagerApprover;
use RedKiteCms\Content\PageCollection\PageCollectionBase;
use RedKiteCms\Content\SlotsManager\SlotsManagerFactoryInterface;
use RedKiteCms\Content\Theme\Theme;
use RedKiteCms\EventSystem\Event\Page\PageSavedEvent;
use RedKiteCms\EventSystem\Event\PageCollection\PageCollectionAddedEvent;
use RedKiteCms\EventSystem\Event\PageCollection\PageCollectionAddingEvent;
use RedKiteCms\EventSystem\Event\PageCollection\PageCollectionEditedEvent;
use RedKiteCms\EventSystem\Event\PageCollection\PageCollectionEditingEvent;
use RedKiteCms\EventSystem\Event\PageCollection\PageCollectionRemovedEvent;
use RedKiteCms\EventSystem\Event\PageCollection\PageCollectionRemovingEvent;
use RedKiteCms\EventSystem\Event\PageCollection\SiteSavedEvent;
use RedKiteCms\EventSystem\Event\PageCollection\SluggingPageNameEvent;
use RedKiteCms\EventSystem\Event\PageCollection\TemplateChangedEvent;
use RedKiteCms\EventSystem\PageCollectionEvents;
use RedKiteCms\EventSystem\PageEvents;
use RedKiteCms\Exception\General\InvalidArgumentException;
use RedKiteCms\Exception\General\RuntimeException;
use RedKiteCms\Tools\FilesystemTools;
use RedKiteCms\Tools\Utils;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

/**
 * Class Deployer is the object assigned to deploy the website
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Page
 */
class Deployer extends PageCollectionBase
{
    /**
     * Saves the handled page
     *
     * @param \RedKiteCms\Content\BlockManager\BlockManagerApprover $approver
     * @param array $options
     * @param bool $saveCommonSlots Saves the common slots when true
     */
    public function save(BlockManagerApprover $approver, array $options, $saveCommonSlots = true)
    {
        $this->contributorDefined();

        $filesystem = new Filesystem();
        $pageDir = $this->pagesDir . '/' . $options["page"];
        $filesystem->copy($pageDir . '/' . $this->pageFile, $pageDir . '/page.json', true);

        $pageDir .= '/' . $options["language"] . '_' . $options["country"];
        if ($this->seoFile != "seo.json") {

            $sourceFile = $pageDir . '/' . $this->seoFile;
            $values = json_decode(file_get_contents($sourceFile), true);
            if (array_key_exists("current_permalink", $values)) {
                $values["changed_permalinks"][] = $values["current_permalink"];
                unset($values["current_permalink"]);
                file_put_contents($sourceFile, json_encode($values));
            }

            $filesystem->copy($sourceFile, $pageDir . '/seo.json', true);
        }
        $approvedBlocks = $this->saveBlocks($approver, $pageDir, $options);

        if ($saveCommonSlots) {
            $slotsDir = $this->baseDir . '/slots';
            $approvedCommonBlocks = $this->saveBlocks($approver, $slotsDir, $options);
            $approvedBlocks = array_merge($approvedBlocks, $approvedCommonBlocks);
        }

        Dispatcher::dispatch(PageEvents::PAGE_SAVED, new PageSavedEvent($pageDir, null, $approvedBlocks));
        DataLogger::log(sprintf('Page "%s" was successfully saved in production', $options["page"]));
    }

    /**
     * Save the all website pages
     *
     * @param \RedKiteCms\Content\BlockManager\BlockManagerApprover $approver
     * @param array $languages
     * @param bool $saveCommonSlots Saves the common slots when true
     */
    public function saveAllPages(BlockManagerApprover $approver, array $languages, $saveCommonSlots = true)
    {
        $this->contributorDefined();

        $finder = new Finder();
        $pages = $finder->directories()->depth(0)->in($this->pagesDir);
        foreach ($pages as $page) {
            $page = (string)$page;
            $pageName = basename($page);
            foreach ($languages as $language) {
                $tokens = explode("_", $language);
                $options = array(
                    'page' => $pageName,
                    'language' => $tokens[0],
                    'country' => $tokens[1],
                );
                $this->save($approver, $options, $saveCommonSlots);
            }
            $saveCommonSlots = false;
        }

        Dispatcher::dispatch(PageCollectionEvents::SITE_SAVED, new SiteSavedEvent());
        DataLogger::log('The whole website\'s pages were successfully saved in production');
    }

    private function saveBlocks(BlockManagerApprover $approver, $sourcePath, array $options)
    {
        $approvedBlocks = array();
        $finder = new Finder();
        $slots = $finder->directories()->depth(0)->in($sourcePath);
        foreach ($slots as $slot) {
            $basePath = (string)$slot;
            $approvedBlocks[] = $this->doSaveBlocks($approver, $basePath, $options);
        }

        return $approvedBlocks;
    }

    private function doSaveBlocks(BlockManagerApprover $approver, $basePath, array $options)
    {
        $options["slot"] = basename($basePath);
        $slotPath = sprintf('%s/contributors/%s', FilesystemTools::slotDir($this->baseDir, $options), $this->username);
        if (!is_dir($slotPath)) {
            return array();
        }

        $activeSlotDefinition = json_decode(FilesystemTools::readFile($basePath . '/active/slot.json'), true);
        $contributorSlotDefinition = json_decode(FilesystemTools::readFile($slotPath . '/slot.json'), true);

        $removedBlocks = array();
        $contributorSlotDefinitionBlocks = $contributorSlotDefinition["blocks"];
        if (null === $contributorSlotDefinitionBlocks) {
            $contributorSlotDefinitionBlocks = array();
        }
        if (null !== $activeSlotDefinition) {
            $removedBlocks = array_diff_key($activeSlotDefinition["blocks"], $contributorSlotDefinitionBlocks);
        }

        foreach ($removedBlocks as $blockName) {
            $options["blockname"] = $blockName;
            $approver->approveRemoval($this->baseDir, $options, $this->username);
        }

        $approvedBlocks = array();
        $blocks = array_diff_key($contributorSlotDefinitionBlocks, $removedBlocks);
        foreach ($blocks as $blockName) {
            $options["blockname"] = $blockName;
            $approved = $approver->approve($this->baseDir, $options, $this->username);
            $approvedBlocks[] = $approved;
        }

        return $approvedBlocks;
    }
}