<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Gui\Cards;

/**
 * Page navigation arrows at the bottom of the lists
 */
class PageNavigator extends \ManiaLib\Gui\Elements\Frame
{

    /**
     * @var \ManiaLib\Gui\Elements\Icons64x64_1
     */
    public $arrowNext;

    /**
     * @var \ManiaLib\Gui\Elements\Icons64x64_1
     */
    public $arrowPrev;

    /**
     * @var \ManiaLib\Gui\Elements\Icons64x64_1
     */
    public $arrowFastNext;

    /**
     * @var \ManiaLib\Gui\Elements\Icons64x64_1
     */
    public $arrowFastPrev;

    /**
     * @var \ManiaLib\Gui\Elements\Icons64x64_1
     */
    public $arrowLast;

    /**
     * @var \ManiaLib\Gui\Elements\Icons64x64_1
     */
    public $arrowFirst;

    /**
     * @var \ManiaLib\Gui\Elements\Label
     */
    public $text;

    /**
     * @var \ManiaLib\Gui\Elements\Bgs1
     */
    public $textBg;
    public $arrowNoneStyle = \ManiaLib\Gui\Elements\Icons64x64_1::ArrowDisabled;
    public $arrowNextStyle = \ManiaLib\Gui\Elements\Icons64x64_1::ArrowNext;
    public $arrowPrevStyle = \ManiaLib\Gui\Elements\Icons64x64_1::ArrowPrev;
    public $arrowFastNextStyle = \ManiaLib\Gui\Elements\Icons64x64_1::ArrowFastNext;
    public $arrowFastPrevStyle = \ManiaLib\Gui\Elements\Icons64x64_1::ArrowFastPrev;
    public $arrowFirstStyle = \ManiaLib\Gui\Elements\Icons64x64_1::ArrowFirst;
    public $arrowLastStyle = \ManiaLib\Gui\Elements\Icons64x64_1::ArrowLast;

    /*	 * #@+
     * @ignore
     */
    protected $showLast;
    protected $showFastNext;
    protected $showText;
    protected $pageNumber;
    protected $currentPage;

    /*	 * #@- */

    function __construct($iconSize = 8)
    {
        parent::__construct();

        $this->arrowNext = new \ManiaLib\Gui\Elements\Icons64x64_1($iconSize);
        $this->arrowPrev = new \ManiaLib\Gui\Elements\Icons64x64_1($iconSize);
        $this->arrowFastNext = new \ManiaLib\Gui\Elements\Icons64x64_1($iconSize);
        $this->arrowFastPrev = new \ManiaLib\Gui\Elements\Icons64x64_1($iconSize);
        $this->arrowLast = new \ManiaLib\Gui\Elements\Icons64x64_1($iconSize);
        $this->arrowFirst = new \ManiaLib\Gui\Elements\Icons64x64_1($iconSize);
        $this->text = new \ManiaLib\Gui\Elements\Label(14);
        $this->textBg = new \ManiaLib\Gui\Elements\Bgs1(16, $iconSize - 2);

        $this->showLast = false;
        $this->showFastNext = false;
        $this->showText = true;

        $this->arrowNext->setSubStyle($this->arrowNoneStyle);
        $this->arrowPrev->setSubStyle($this->arrowNoneStyle);
        $this->arrowFastNext->setSubStyle($this->arrowNoneStyle);
        $this->arrowFastPrev->setSubStyle($this->arrowNoneStyle);
        $this->arrowLast->setSubStyle($this->arrowNoneStyle);
        $this->arrowFirst->setSubStyle($this->arrowNoneStyle);
    }

    /**
     * Cloning behaviour: if you clone this, it also clones sub-Elements
     */
    function __clone()
    {
        foreach ($this as $name => $property) {
            if ($property instanceof \ManiaLib\Gui\Element) {
                $this->$name = clone $property;
            }
        }
    }

    /**
     * Sets the size of the navigation icons
     */
    function setSize($iconSize = 5, $nullValue = null)
    {
        $this->arrowNext->setSize($iconSize, $iconSize);
        $this->arrowPrev->setSize($iconSize, $iconSize);
        $this->arrowFastNext->setSize($iconSize, $iconSize);
        $this->arrowFastPrev->setSize($iconSize, $iconSize);
        $this->arrowLast->setSize($iconSize, $iconSize);
        $this->arrowFirst->setSize($iconSize, $iconSize);
    }

    /**
     * Sets the page number
     */
    function setPageNumber($pageNumber)
    {
        $this->pageNumber = $pageNumber;
    }

    /**
     * Sets the current page
     */
    function setCurrentPage($currentPage)
    {
        $this->currentPage = $currentPage;
    }

    /**
     * Shows or hides the "go to first/last" navigation icons
     */
    function showLast($show = true)
    {
        $this->showLast = $show;
    }

    /**
     * Returns whether the "go to first/last" navigation icons are shown
     */
    function isLastShown()
    {
        return $this->showLast;
    }

    /**
     * Shows or hides the "fast prev/next" navigation icons
     */
    function showFastNext($show = true)
    {
        $this->showFastNext = $show;
    }

    /**
     * Returns whether the "fast prev/next" navigation icons are shown
     */
    function isFastNextShown()
    {
        return $this->showFastNext;
    }

    /**
     * Shows or hides the text. Note that if the current page or the page number
     * isn't declared, the text won't be shown
     */
    function showText($show = true)
    {
        $this->showText = $show;
    }

    /**
     * Returns whether the text is shown
     */
    function isTextShown()
    {
        return $this->showText;
    }

    /**
     * Saves the PageNavigator in the GUI objects stack
     */
    function preFilter()
    {
        // Show / hide text
        if (!$this->currentPage || !$this->pageNumber) {
            $this->showText(false);
        }

        // Auto show fast next / last
        if ($this->arrowFirst->hasLink() || $this->arrowLast->hasLink()) {
            $this->showLast();
        }
        if ($this->arrowFastNext->hasLink() || $this->arrowFastPrev->hasLink()) {
            $this->showFastNext();
        }

        // Arrow styles
        if ($this->arrowNext->hasLink()) {
            $this->arrowNext->setSubStyle($this->arrowNextStyle);
        }
        if ($this->arrowPrev->hasLink()) {
            $this->arrowPrev->setSubStyle($this->arrowPrevStyle);
        }
        if ($this->arrowNext->hasLink() && $this->arrowFastNext->hasLink()) {
            $this->arrowFastNext->setSubStyle($this->arrowFastNextStyle);
        } else {
            $this->arrowFastNext->setManialink(null);
        }
        if ($this->arrowPrev->hasLink() && $this->arrowFastPrev->hasLink()) {
            $this->arrowFastPrev->setSubStyle($this->arrowFastPrevStyle);
        } else {
            $this->arrowFastPrev->setManialink(null);
        }
        if ($this->arrowNext->hasLink() && $this->arrowLast->hasLink()) {
            $this->arrowLast->setSubStyle($this->arrowLastStyle);
        } else {
            $this->arrowLast->setManialink(null);
        }
        if ($this->arrowPrev->hasLink() && $this->arrowFirst->hasLink()) {
            $this->arrowFirst->setSubStyle($this->arrowFirstStyle);
        } else {
            $this->arrowFirst->setManialink(null);
        }

        // Text
        $this->text->setStyle(\ManiaLib\Gui\Elements\Label::TextValueSmall);
        $this->text->setText($this->currentPage . ' / ' . $this->pageNumber);

        // Positioning in relation to the center of the containing frame
        $this->text->setAlign("center", "center2");
        $this->text->setPosZ(1);

        $this->textBg->setSubStyle(\ManiaLib\Gui\Elements\Bgs1::BgPager);
        $this->textBg->setAlign('center', 'center');
        $this->textBg->setPosZ(.5);

        $this->arrowNext->setValign("center");
        $this->arrowFastNext->setValign("center");
        $this->arrowLast->setValign("center");

        $this->arrowNext->setPosition(($this->text->getSizeX() / 2) + 1, 0, 1);
        $this->arrowFastNext->setPosition($this->arrowNext->getPosX() + $this->arrowNext->getSizeX(), 0, 1);
        $this->arrowLast->setPosition(
            $this->arrowNext->getPosX() +
            (int)$this->showFastNext * $this->arrowFastNext->getSizeX() +
            $this->arrowNext->getSizeX(), 0, 1);

        $this->arrowPrev->setAlign("right", "center");
        $this->arrowFastPrev->setAlign("right", "center");
        $this->arrowFirst->setAlign("right", "center");

        $this->arrowPrev->setPosition(-($this->text->getSizeX() / 2) - 1, 0, 1);
        $this->arrowFastPrev->setPosition($this->arrowPrev->getPosX() - $this->arrowPrev->getSizeX(), 0, 1);
        $this->arrowFirst->setPosition(
            $this->arrowPrev->getPosX() -
            (int)$this->showFastNext * $this->arrowFastPrev->getSizeX() -
            $this->arrowPrev->getSizeX(), 0, 1);

        // Save the gui
        if ($this->showText) {
            $this->add($this->textBg);
            $this->add($this->text);
        }
        $this->add($this->arrowNext);
        $this->add($this->arrowPrev);
        if ($this->showLast) {
            $this->add($this->arrowFirst);
            $this->add($this->arrowLast);
        }
        if ($this->showFastNext) {
            $this->add($this->arrowFastNext);
            $this->add($this->arrowFastPrev);
        }
    }

}


<?php

namespace Nexmo\Service\Number;

use Nexmo\Entity\MatchingStrategy;
use Nexmo\Entity\NumberCollection;
use Nexmo\Exception;
use Nexmo\Service\Service;

/**
 * Get all inbound numbers associated with your account.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class Cancel extends Service
{
    /**
     * @inheritdoc
     */
    public function getRateLimit()
    {
        // Max number of requests per second. Nexmo developer API claims 3/sec max, but actually more than 2/sec causes error 429 Too Many Requests.
        return 2;
    }

    /**
     * @inheritdoc
     */
    public function getEndpoint()
    {
        return 'number/cancel';
    }

    /**
     * @param string     $country
     * @param string     $msisdn
     *
     * @return boolean
     * @throws Exception
     */
    public function invoke($country = null, $msisdn = null)
    {
        if (!$country) {
            throw new Exception("\$country parameter cannot be blank");
        }
        if (!$msisdn) {
            throw new Exception("\$msisdn parameter cannot be blank");
        }

        return $this->exec([
            // Nexmo API requires $country value to be uppercase.
            'country' => strtoupper($country),
            'msisdn' => $msisdn,
        ], 'POST');
    }

    /**
     * @inheritdoc
     */
    protected function validateResponse(array $json)
    {
        if (!isset($json['error-code'])) {
            throw new Exception('no error code');
        }

        switch ($json['error-code']) {
        case '200':
            return true;

        case '401':
            throw new Exception('error 401 wrong credentials');

        case '420':
            throw new Exception('error 420 wrong parameters');

        default:
            throw new Exception('unknown error code');
        }
    }
}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Gui\Cards\Navigation;

class Button extends \ManiaLib\Gui\Elements\Bgs1
{

    /**
     * TrackMania formatting string appended to the text when a button
     * is selected (default is just a light blue color)
     */
    static public $unselectedTextStyle = '$fff';

    /**
     * @var \ManiaLib\Gui\Elements\Label
     */
    public $text;

    /**
     * @var \ManiaLib\Gui\Elements\Icon
     */
    public $icon;
    public $iconSizeMinimizer = 1.5;
    public $textSizeMinimizer = 10;

    /**
     * @var \ManiaLib\Gui\Elements\Icons64x64_1
     */
    protected $selectedIcon;
    protected $isSelected = false;
    protected $forceLinks = true;

    function __construct($sizeX = 69, $sizeY = 8.5)
    {
        parent::__construct($sizeX, $sizeY);

        $this->setSubStyle(\ManiaLib\Gui\Elements\Bgs1::BgEmpty);

        $this->cardElementsValign = 'center2';

        $this->text = new \ManiaLib\Gui\Elements\Label(45);
        $this->text->setSizeY(0);
        $this->text->setValign("center");
        $this->text->setPosition(8);
        $this->text->setStyle(\ManiaLib\Gui\Elements\Label::TextButtonNav);
        $this->addCardElement($this->text);

        $this->icon = new \ManiaLib\Gui\Elements\Icons128x128_1($this->sizeY);
        $this->icon->setValign("center");
        $this->icon->setPosition(55, 0, 0.1);
        $this->addCardElement($this->icon);
    }

    /**
     * Sets the button selected and change its styles accordingly
     */
    function setSelected()
    {
        $this->isSelected = true;

        $this->selectedIcon = new \ManiaLib\Gui\Elements\Icons64x64_1(11);
        $this->selectedIcon->setSubStyle(\ManiaLib\Gui\Elements\Icons64x64_1::ShowRight);
        $this->selectedIcon->setValign('center');
        $this->selectedIcon->setPosX(71);
        $this->addCardElement($this->selectedIcon);
    }

    protected function preFilter()
    {
        if (!$this->isSelected && $this->text->getText()) {
            $this->text->setText(self::$unselectedTextStyle . $this->text->getText());
        }

        $this->text->addLink($this);
        $this->icon->addLink($this);
    }

}


<?php

namespace Nexmo\Service;

use Nexmo\Exception as NexmoException;
use Nexmo\Exception;

/**
 * Class MarketingMessage
 * @package Nexmo\Service
 */
class MarketingMessage extends Service
{
    /**
     * @return string The short code marketing SMS endpoint.
     */
    public function getEndpoint()
    {
        return 'sc/us/marketing/json';
    }

    /**
     * Send a marketing message from Nexmo's shared short code.
     *
     * @param string|int    $from           Required. Nexmo Shared Short Code, can be found on your Dashboard.
     * @param string        $keyword        Required. The keyword you selected during Shared Short Code sign up process.
     * @param string|int    $to             Required. Mobile number in international format.
     *                                      Ex: 447525856424 or 00447525856424 when sending to UK.
     * @param string        $text           Required. Body of the text message.
     * @throws \Nexmo\Exception
     * @return array
     */
    public function invoke($from = null, $keyword = null, $to = null, $text = '')
    {
        if(!$from) {
            throw new Exception("\$from parameter cannot be blank");
        }

        if(!$keyword) {
            throw new Exception("\$keyword parameter cannot be blank");
        }

        if(!$to) {
            throw new Exception("\$to parameter cannot be blank");
        }

        if(!$text) {
            throw new Exception("\$text parameter cannot be blank");
        }

        return $this->exec([
            'from' => $from,
            'keyword' => $keyword,
            'to' => $to,
            'text' => $text
        ]);
    }

    protected function validateResponse(array $json)
    {
        if (!isset($json['message-count'])) {
            throw new NexmoException('message-count property expected');
        }

        if (!isset($json['messages'])) {
            throw new NexmoException('messages property expected');
        }

        foreach ($json['messages'] as $message) {
            if (!isset($message['status'])) {
                throw new NexmoException('status property expected');
            }

            if (!empty($message["error-text"])) {
                throw new NexmoException("Unable to send sms message: " . $message["error-text"] . ' - status ' . $message['status']);
            }

            if ($message['status'] > 0) {
                throw new NexmoException("Unable to send sms message: status " . $message['status']);
            }
        }

        return true;
    }
}


<?php

use Arcanedev\LaravelSeo\Bases\Migration;
use Arcanedev\LaravelSeo\Seo;
use Illuminate\Database\Schema\Blueprint;

/**
 * Class     CreateSeoMetasTable
 *
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 *
 * @see \Arcanedev\LaravelSeo\Models\Meta
 */
class CreateSeoMetasTable extends Migration
{
    /* -----------------------------------------------------------------
     |  Constructor
     | -----------------------------------------------------------------
     */

    /**
     * CreateSeoMetasTable constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->setTable(Seo::getConfig('metas.table', 'metas'));
    }

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * {@inheritdoc}
     */
    public function up()
    {
        $this->createSchema(function(Blueprint $table) {
            $table->increments('id');
            $table->morphs('seoable');
            $table->string('title');
            $table->string('description')->nullable();
            $table->string('keywords')->nullable();
            $table->boolean('noindex')->default(false);
            $table->text('extras')->nullable();
            $table->timestamps();
        });
    }
}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Gui\Elements;

class Music extends \ManiaLib\Gui\Element
{

    protected $xmlTagName = 'music';
    protected $halign = null;
    protected $valign = null;
    protected $posX = null;
    protected $posY = null;
    protected $posZ = null;
    protected $data;
    protected $dataId;
    protected $music;
    protected $volume;

    function __construct()
    {

    }

    /**
     * Sets the data to play
     * @param string The data filename (or URL)
     * @param bool Whether to prefix the filename with the default media dir URL
     */
    function setData($filename, $absoluteUrl = false)
    {
        if (!$absoluteUrl) {
            $this->data = \ManiaLib\Gui\Manialink::$mediaURL . $filename;
        } else {
            $this->data = $filename;
        }
    }

    /**
     * Sets the data id to play
     * @param string The data id
     */
    function setDataId($dataId)
    {
        $this->dataId = $dataId;
    }

    /**
     * Fi set to true will send the sound in the music mix
     * (so that the volume gets controlled by the music slider instead of the sound volume slider)
     * @param bool $music
     */
    function setMusic($music)
    {
        $this->music = $music;
    }

    /**
     * Will change the sound attenuation. default value is 0.707 (-3dB)
     * @param float $volume
     */
    function setVolume($volume)
    {
        $this->volume = $volume;
    }

    /**
     * Returns the data URL
     * @return string
     */
    function getData()
    {
        return $this->data;
    }

    /**
     * Returns the data id
     * @return string
     */
    function getDataId()
    {
        return $this->dataId;
    }

    function getMusic()
    {
        return $this->music;
    }

    function getVolume()
    {
        return $this->volume;
    }

    protected function postFilter()
    {
        if ($this->data !== null)
            $this->xml->setAttribute('data', $this->data);
        if ($this->dataId !== null)
            $this->xml->setAttribute('dataId', $this->dataId);
        if ($this->music !== null)
            $this->xml->setAttribute('music', $this->music);
        if ($this->volume !== null)
            $this->xml->setAttribute('volume', $this->volume);
    }

}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Database;

abstract class Tools
{
    const ORDER_ASC = 1;
    const ORDER_DESC = -1;

    /**
     * Returns the "LIMIT x,x" string depending on both values
     */
    static function getLimitString($offset, $length)
    {
        $offset = (int)$offset;
        $length = (int)$length;
        if (!$offset && !$length) {
            return '';
        } elseif (!$offset && $length == 1) {
            return 'LIMIT 1';
        } else {
            return 'LIMIT ' . $offset . ', ' . $length;
        }
    }

    /**
     * @param int 1 or -1
     * @return " ASC " or " DESC "
     */
    static function getOrder($order)
    {
        switch ($order) {
            case null:
            case static::ORDER_ASC:
                return ' ASC ';
            case static::ORDER_DESC:
                return ' DESC ';
            default:
                throw new \InvalidArgumentException(sprintf('Invalid order value: %s',
                    $order));
        }
    }

    /**
     * Returns string like "(name1, name2) VALUES (value1, value2)"
     * WARNING: Field names and values are not escaped !!!
     */
    static function getValuesString(array $values)
    {
        return
            '(' . implode(', ', array_keys($values)) . ') ' .
            'VALUES ' .
            '(' . implode(', ', $values) . ')';
    }

    /**
     * Returns string like "name1=VALUES(name1), name2=VALUES(name2)"
     */
    static function getOnDuplicateKeyUpdateValuesString(array $valueNames)
    {
        $strings = array();
        foreach ($valueNames as $valueName) {
            $strings[] = $valueName . '=VALUES(' . $valueName . ')';
        }
        return implode(', ', $strings);
    }

    /**
     * Returns string like "name1=value1, name2=value2"
     */
    static function getUpdateString(array $values)
    {
        $tmp = array();

        foreach ($values as $key => $value) {
            $tmp[] = $key . '=' . $value;
        }
        return implode(', ', $tmp);
    }

}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Application;

use InvalidArgumentException;
use ManiaLib\Utils\Singleton;

/**
 * Handles HTTP requests: retrieves params, creates links and redirections
 *
 * @method Request getInstance()
 */
class Request extends Singleton
{

    protected $requestParams = array();
    protected $params = array();
    protected $protectedParams = array();
    protected $globalParams = array();
    protected $fragment;
    protected $registerRefererAtDestruct;
    protected $appURL;
    protected $action;
    protected $controller;
    protected $defaultController;
    protected $referer;

    protected function __construct()
    {
        if (array_key_exists(Session::NAME, $_GET)) {
            Session::$id = $_GET[Session::NAME];
            unset($_GET[Session::NAME]);
        }

        // This is a hack because of a bug on the master server
        // May it cause bugs ? IDK
        foreach ($_GET as $key => $value)
            $this->params[str_replace('amp;', '', $key)] = $value;

        if (get_magic_quotes_gpc()) {
            $this->params = array_map('stripslashes', $this->params);
        }
        $this->requestParams = $this->params;
        $config = Config::getInstance();
        $this->appURL = $config->getLinkCreationURL();
        $this->defaultController = $config->defaultController;

        $session = Session::getInstance();
        $this->referer = $session->get('referer');
        if ($this->referer) {
            $this->referer = rawurldecode($this->referer);
        }
    }

    function __destruct()
    {
        if ($this->registerRefererAtDestruct) {
            if (!Response::getInstance()->dialog) {
                $session = Session::getInstance();
                $session->set('referer', rawurlencode($this->registerRefererAtDestruct));
            }
        }
    }

    function exists($name)
    {
        return array_key_exists($name, $this->params);
    }

    /**
     * Retriece the fragment
     * @return mixed
     */
    function getFragment()
    {
        return $this->fragment;
    }

    /**
     * Retrieves a GET parameter, or the default value if not found
     * @param string
     * @param mixed
     * @return mixed
     */
    function get($name, $default = null)
    {
        if (array_key_exists($name, $this->params)) {
            return $this->params[$name];
        } else {
            return $default;
        }
    }

    /**
     * Retrieves a POST parameter, or the default value if not found
     * @param string
     * @param mixed
     * @return mixed
     */
    function getPost($name, $default = null)
    {
        if (array_key_exists($name, $_POST)) {
            return $_POST[$name];
        } else {
            return $default;
        }
    }

    function getAll()
    {
        return $this->params;
    }

    /**
     * Retrieves a GET parameter, or throws an exception if not found or null
     * @param string
     * @param string Optional human readable name for error dialog
     * @return mixed
     */
    function getStrict($name, $message = null)
    {
        if (array_key_exists($name, $this->params) && $this->params[$name]) {
            return $this->params[$name];
        } elseif ($message) {
            throw new UserException($message);
        } else {
            throw new InvalidArgumentException($name);
        }
    }

    /**
     * Retrieves a POST parameter, or throws an exception if not found or null
     * @param string
     * @param string Optional human readable name for error dialog
     * @return mixed
     */
    function getPostStrict($name, $message = null)
    {
        if (array_key_exists($name, $_POST) && $_POST[$name]) {
            return $_POST[$name];
        } elseif ($message) {
            throw new UserException($message);
        } else {
            throw new InvalidArgumentException($name);
        }
    }

    /**
     * Sets a GET parameter
     *
     * @param string
     * @param mixed
     */
    function set($name, $value)
    {
        $this->params[$name] = $value;
    }

    function setFragment($value)
    {
        $this->fragment = $value;
    }

    /**
     * Deletes a GET parameter
     *
     * @param string
     */
    function delete($name)
    {
        unset($this->params[$name]);
    }

    function deleteFragment()
    {
        $this->fragment = null;
    }

    /**
     * Restores a GET parameter to the value it had when the page was loaded
     *
     * @param string
     */
    function restore($name)
    {
        if (array_key_exists($name, $this->requestParams)) {
            $this->params[$name] = $this->requestParams[$name];
        } else {
            $this->delete($name);
        }
    }

    /**
     * @deprecated
     */
    public function getAction($defaultAction = null)
    {
        return Dispatcher::getInstance()->getAction($defaultAction);
    }

    /**
     * @deprecated
     */
    public function getController()
    {
        return Dispatcher::getInstance()->getController();
    }

    /**
     * Registers the current page as referer
     */
    function registerReferer()
    {
        $this->registerRefererAtDestruct = $this->createLink();
    }

    /**
     * Returns the referer, or the specified default page, or index.php
     * @param string
     */
    function getReferer($default = null)
    {
        return $this->referer ?: ($default ?: $this->appURL);
    }

    /**
     * Redirects to the specified route with all defined GET vars in the URL
     */
    function redirect($route)
    {
        Response::getInstance()->redirect($this->createLink($route));
    }

    /**
     * Redirects to the specified route with, with names of GET vars as parameters of the method
     */
    function redirectArgList($route = '')
    {
        $args = func_get_args();
        array_shift($args);
        $args = $this->filterArgs($args);
        $manialink = $this->createLinkString($route, $args);
        Response::getInstance()->redirect($manialink);
    }

    /**
     * Creates a Manialink redirection to the specified absolute URI
     */
    function redirectAbsolute($URL)
    {
        Response::getInstance()->redirect($URL);
    }

    /**
     * Creates a Manialink redirection to the previously registered referer, or
     * the index if no referer was previously registered
     */
    function redirectToReferer()
    {
        Response::getInstance()->redirect($this->getReferer());
    }

    /**
     * Creates a link to the specified route with all defined GET vars in the URL
     * @param string Can be the name of a controller or a class const of Route
     * @param string Can be the name of an action or a class const of Route
     */
    public function createLink($route = '')
    {
        return $this->createLinkString($route, $this->params);
    }

    /**
     * Creates a link to the specified route with, with names of GET vars as parameters of the method
     */
    function createLinkArgList($route = '')
    {
        $args = func_get_args();
        array_shift($args);
        $args = $this->filterArgs($args);
        return $this->createLinkString($route, $args);
    }

    /**
     * Returns an URL with the request parameters specified as method arguments
     *
     * @param string The absolute URL
     * @return string
     * @deprecated Old code, not sure if it is still used?
     */
    function createAbsoluteLinkArgList($absoluteLink)
    {
        $args = func_get_args();
        array_shift($args);
        $args = $this->filterArgs($args);
        return $absoluteLink . ($args ? '?' . http_build_query($args) : '');
    }

    protected function createLinkString($route = '', $params = array())
    {
        // Current pages
        if (!$route || $route == '.') {
            $controller = $this->getController();
            $action = $this->getAction(null);
        } // Root
        elseif ($route == '/') {
            $controller = null;
            $action = null;
        } // Controller root
        elseif ($route == '..' || $route == '../') {
            $controller = $this->getController();
            $action = null;
        } else {
            // Absolute route
            if (substr($route, 0, 1) == '/') {
                list($controller, $action) = Route::getActionAndControllerFromRoute($route);
            } // Relative route
            elseif (strlen($route) > 3 && substr($route, 0, 3) == '../') {
                $_route = substr($route, 3);
                if (substr($_route, -1, 1) == '/') {
                    $_route = substr($_route, 0, -1);
                }

                $controller = $this->getController();
                $action = $_route;
            } // Syntax error
            else {
                throw new Exception('Request link: syntax error');
            }
        }

        $config = Config::getInstance();

        if ($controller == $config->defaultController && !$action) {
            $controller = null;
        }

        $url = $config->getLinkCreationURL();
        $url .= Route::computeRoute($controller, $action);
        $addSid = $config->sessionUseURL && defined('SID') && SID && !array_key_exists(Session::NAME, $_COOKIE);
        $sid = $addSid ? htmlspecialchars(SID) : '';
        $queryString = http_build_query($params, '', '&');
        return $url . ($sid || $queryString ? '?' : '') . $sid . ($sid ? '&' : '') . $queryString . ($this->fragment ? '#' . $this->fragment : '');
    }

    /**
     * @return array
     */
    protected function filterArgs(array $args)
    {
        $result = array();
        foreach ($args as $elt) {
            if (array_key_exists($elt, $this->params)) {
                $result[$elt] = $this->params[$elt];
            }
        }
        return $result;
    }

}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Gui;

abstract class Component
{

    protected $id;
    protected $visible = true;
    protected $hidden;
    protected $posX = 0;
    protected $posY = 0;
    protected $posZ = 0;
    protected $sizeX;
    protected $sizeY;
    protected $scale;
    protected $valign;
    protected $halign;
    protected $relativeHalign;
    protected $relativeValign;
    protected $scriptEvents;

    /**
     * @var array
     */
    protected $attributes = array();

    /**
     * @var \DOMNode
     */
    protected $parentNode = false;

    /**
     * @var Layouts\AbstractLayout
     */
    protected $parentLayout = false;

    /**
     * @var Elements\Frame
     */
    protected $parentFrame = false;

    /**
     * @param string $name
     * @param mixed $value
     */
    function setAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }

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

    /**
     * Set the id of the element
     * @param int
     */
    function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Sets the X position of the element
     * @param float
     */
    function setPositionX($posX)
    {
        $oldX = $this->posX;
        $this->posX = $posX;
        $this->onMove($oldX, $this->posY, $this->posZ);
    }

    /**
     * Sets the Y position of the element
     * @param float
     */
    function setPositionY($posY)
    {
        $oldY = $this->posY;
        $this->posY = $posY;
        $this->onMove($this->posX, $oldY, $this->posZ);
    }

    /**
     * Sets the Z position of the element
     * @param float
     */
    function setPositionZ($posZ)
    {
        $oldZ = $this->posZ;
        $this->posZ = $posZ;
        $this->onMove($this->posX, $this->posY, $oldZ);
    }

    /**
     * Sets the X position of the element
     * @param float
     */
    function setPosX($posX)
    {
        $oldX = $this->posX;
        $this->posX = $posX;
        $this->onMove($oldX, $this->posY, $this->posZ);
    }

    /**
     * Sets the Y position of the element
     * @param float
     */
    function setPosY($posY)
    {
        $oldY = $this->posY;
        $this->posY = $posY;
        $this->onMove($this->posX, $oldY, $this->posZ);
    }

    /**
     * Sets the Z position of the element
     * @param float
     */
    function setPosZ($posZ)
    {
        $oldZ = $this->posZ;
        $this->posZ = $posZ;
        $this->onMove($this->posX, $this->posY, $oldZ);
    }

    /**
     * Increment position X
     * @param float
     */
    function incPosX($posX)
    {
        $oldX = $this->posX;
        $this->posX += $posX;
        $this->onMove($oldX, $this->posY, $this->posZ);
    }

    /**
     * Increment position Y
     * @param float
     */
    function incPosY($posY)
    {
        $oldY = $this->posY;
        $this->posY += $posY;
        $this->onMove($this->posX, $oldY, $this->posZ);
    }

    /**
     * Increment position Z
     * @param float
     */
    function incPosZ($posZ)
    {
        $oldZ = $this->posZ;
        $this->posZ += $posZ;
        $this->onMove($this->posX, $this->posY, $oldZ);
    }

    /**
     * Sets the position of the element
     * @param float
     * @param float
     * @param float
     */
    function setPosition()
    {
        $oldX = $this->posX;
        $oldY = $this->posY;
        $oldZ = $this->posZ;

        $args = func_get_args();

        if (!empty($args)) $this->posX = array_shift($args);

        if (!empty($args)) $this->posY = array_shift($args);

        if (!empty($args)) $this->posZ = array_shift($args);

        $this->onMove($oldX, $oldY, $oldZ);
    }

    /**
     * Sets the scale factor of the element. 1=original size, 2=double size, 0.5
     * =half size
     * @param float
     */
    function setScale($scale)
    {
        $oldScale = $this->scale;
        $this->scale = $scale;
        $this->onScale($oldScale);
    }

    /**
     * Sets the visibility of the Component.
     * This is used by ManiaLive.
     * @param bool $visible If set to false the Component (and subcomponents) is not rendered.
     */
    function setVisibility($visible)
    {
        $this->visible = $visible;
    }

    /**
     * Sets the visibility of the Component.
     * Usefull when a script is going to init the values and show it later on
     * @param bool $hidden If set to false the Component (and subcomponents) is hidden.
     */
    function setHidden($hidden)
    {
        $this->hidden = $hidden;
    }

    function getId()
    {
        return $this->id;
    }

    /**
     * Returns the X position of the element
     * @return float
     */
    function getPosX()
    {
        return $this->posX;
    }

    /**
     * Returns the Y position of the element
     * @return float
     */
    function getPosY()
    {
        return $this->posY;
    }

    /**
     * Returns the Z position of the element
     * @return float
     */
    function getPosZ()
    {
        return $this->posZ;
    }

    /**
     * Returns the scale of the element
     * @return float
     */
    function getScale()
    {
        return $this->scale;
    }

    /**
     * Is the Component rendered onto the screen or not?
     * This is used by ManiaLive.
     * @return bool
     */
    function isVisible()
    {
        return $this->visible;
    }

    function isHidden()
    {
        return $this->hidden;
    }

    /**
     * Sets the vertical alignment of the element.
     * @param string Vertical alignment can be either "top", "center" or
     * "bottom"
     */
    function setValign($valign)
    {
        $old = $this->valign;
        $this->valign = $valign;
        $this->onAlign($this->halign, $old);
    }

    /**
     * Sets the horizontal alignment of the element
     * @param string Horizontal alignement can be eithe "left", "center" or
     * "right"
     */
    function setHalign($halign)
    {
        $old = $this->halign;
        $this->halign = $halign;
        $this->onAlign($old, $this->valign);
    }

    /**
     * Sets the alignment of the element
     * @param string Horizontal alignement can be eithe "left", "center" or
     * "right"
     * @param string Vertical alignment can be either "top", "center" or
     * "bottom"
     */
    function setAlign($halign = null, $valign = null)
    {
        $oldHalign = $this->halign;
        $oldValign = $this->valign;
        $this->valign = $valign;
        $this->halign = $halign;
        $this->onAlign($oldHalign, $oldValign);
    }

    function setRelativeHalign($halign)
    {
        $this->relativeHalign = $halign;
    }

    function setRelativeValign($valign)
    {
        $this->relativeValign = $valign;
    }

    function setRelativeAlign($halign = null, $valign = null)
    {
        $this->relativeHalign = $halign;
        $this->relativeValign = $valign;
    }

    /**
     * Sets the width of the element
     * @param float
     */
    function setSizeX($sizeX)
    {
        $oldX = $this->sizeX;
        $this->sizeX = $sizeX;
        $this->onResize($oldX, $this->sizeY);
    }

    /**
     * Sets the height of the element
     * @param float
     */
    function setSizeY($sizeY)
    {
        $oldY = $this->sizeY;
        $this->sizeY = $sizeY;
        $this->onResize($this->sizeX, $oldY);
    }

    /**
     * Sets the size of the element
     * @param float
     * @param float
     */
    function setSize()
    {
        $oldX = $this->sizeX;
        $oldY = $this->sizeY;

        $args = func_get_args();

        if (!empty($args)) $this->sizeX = array_shift($args);

        if (!empty($args)) $this->sizeY = array_shift($args);

        $this->onResize($oldX, $oldY);
    }

    /**
     * Sets additional ManiaScript events to be generated for this element.
     * @param string
     */
    function setScriptEvents($scriptEvent = true)
    {
        $this->scriptEvents = $scriptEvent;
    }

    /**
     * Returns the width of the element
     * @return float
     */
    function getSizeX()
    {
        return $this->sizeX;
    }

    /**
     * Returns the height of the element
     * @return float
     */
    function getSizeY()
    {
        return $this->sizeY;
    }

    /**
     * Returns the width of the element with the
     * applied scaling factor.
     * @return float
     */
    function getRealSizeX()
    {
        return $this->sizeX * ($this->scale ? $this->scale : 1);
    }

    /**
     * Returns the height of the element with the
     * applied scaling factor.
     * @return float
     */
    function getRealSizeY()
    {
        return $this->sizeY * ($this->scale ? $this->scale : 1);
    }

    /**
     * Return the x-coordinate for the left border of the Component.
     * @return float
     */
    function getBorderLeft()
    {
        return $this->getPosX();
    }

    /**
     * Return the x-coordinate for the right border of the Component.
     * @return float
     */
    function getBorderRight()
    {
        return $this->getPosX() + $this->getRealSizeX();
    }

    /**
     * Return y-coordinate for the top border of the Component.
     * @return float
     */
    function getBorderTop()
    {
        return $this->getPosY();
    }

    /**
     * Return y-coordinate for the bottom border of the Component.
     * @return float
     */
    function getBorderBottom()
    {
        return $this->getPosY() + $this->getRealSizeY();
    }

    /**
     * Returns the horizontal alignment of the element
     * @return string
     */
    function getHalign($default = null)
    {
        return $this->halign ?: $default;
    }

    /**
     * Returns the vertical alignment of the element
     * @return string
     */
    function getValign($default = null)
    {
        return $this->valign ?: $default;
    }

    function getRelativeHalign($default = null)
    {
        return $this->relativeHalign ?: $default;
    }

    function getRelativeValign($default = null)
    {
        return $this->relativeValign ?: $default;
    }

    function getScriptEvents()
    {
        return $this->scriptEvents;
    }

    function setParentNode(\DOMNode $node)
    {
        $this->parentNode = $node;
    }

    function setParentLayout($layout)
    {
        $this->parentLayout = $layout;
    }

    function setParentFrame(Elements\Frame $frame)
    {
        $this->parentFrame = $frame;
    }

    /**
     * @return \DOMNode
     */
    function getParentNode()
    {
        return $this->parentNode !== false ? $this->parentNode : end(Manialink::$parentNodes);
    }

    /**
     * @return Layouts\AbstractLayout
     */
    function getParentLayout()
    {
        return $this->parentLayout !== false ? $this->parentLayout : end(Manialink::$parentLayouts);
    }

    /**
     * @return Elements\Frame
     */
    function getParentFrame()
    {
        return $this->parentFrame !== false ? $this->parentFrame : end(Manialink::$parentFrames);
    }

    /**
     * Overridable callback on component change
     */
    protected function onResize($oldX, $oldY)
    {

    }

    /**
     * Overridable callback on component change
     */
    protected function onAlign($oldHalign, $oldValign)
    {

    }

    /**
     * Overridable callback on component change
     */
    protected function onMove($oldX, $oldY, $oldZ)
    {

    }

    /**
     * Overridable callback on component change
     */
    protected function onScale($oldScale)
    {

    }

}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Gui\Cards\Navigation;

use ManiaLib\Gui\Manialink;
use ManiaLib\Gui\Elements\Quad;
use ManiaLib\Gui\Elements\Bgs1;
use ManiaLib\Gui\Elements\Icons128x128_1;
use ManiaLib\Gui\Elements\Icons64x64_1;
use ManiaLib\Gui\Elements\Label;
use ManiaLib\Gui\Layouts\Column;

/**
 * Navigation menu
 * Looks like the navigation menu on the left in the game menus
 */
class Menu extends Bgs1
{
    const BUTTONS_TOP = true;
    const BUTTONS_BOTTOM = false;

    /**
     * @var Label
     */
    public $title;

    /**
     * @var Label
     */
    public $subTitle;

    /**
     * @var \ManiaLib\Gui\Elements\Quad
     */
    public $titleBg;

    /**
     * @var \ManiaLib\Gui\Elements\Quad
     */
    public $logo;

    /**
     * @var \ManiaLib\Gui\Cards\Navigation\Button
     */
    public $quitButton;

    /**
     * @var \ManiaLib\Gui\Cards\Navigation\Button
     */
    public $lastItem;
    protected $showQuitButton = true;
    protected $items = array();
    protected $bottomItems = array();
    protected $marginHeight = 1;
    protected $yIndex = -10;

    function __construct()
    {
        parent::__construct(70, 180);

        $this->setSubStyle(Bgs1::BgWindow1);
        $this->setPosition(-150, 90, 0.1);

        $this->titleBg = new Quad(70, 70);
        $this->titleBg->setImage(Config::getInstance()->titleBgURL, true);
        $this->addCardElement($this->titleBg);

        $this->logo = new Icons128x128_1(16);
        $this->logo->setPosition(4, -38, 0.1);
        $this->logo->setSubStyle(Icons128x128_1::Vehicles);
        $this->addCardElement($this->logo);

        $this->title = new Label(46);
        $this->title->setPosition(22, -41, 0.1);
        $this->title->setStyle(Label::TextTitle1);
        $this->title->setScriptEvents();
        $this->addCardElement($this->title);

        $this->subTitle = new Label(46);
        $this->subTitle->setPosition(22, -47.75, 0.1);
        $this->subTitle->setStyle(Label::TextSubTitle1);
        $this->addCardElement($this->subTitle);

        $this->quitButton = new Button();
        $this->quitButton->setPosition(-1, -163.5, 0.1);
        $this->quitButton->text->setText('Back');
        $this->quitButton->text->setStyle(Label::TextButtonNavBack);
        $this->quitButton->icon->setPosition(-8.5, -0.5, 0.1);
        $this->quitButton->icon->setStyle(Quad::Icons128x128_1);
        $this->quitButton->icon->setSubStyle(Icons128x128_1::BackFocusable);
        $this->quitButton->icon->setSize(11, 11);
    }

    /**
     * Adds a navigation button to the menu
     */
    function addItem($topItem = self::BUTTONS_TOP)
    {
        $item = new Button();
        $item->setSubStyle(Bgs1::BgEmpty);
        if ($topItem == self::BUTTONS_TOP) {
            $this->items[] = $item;
        } else {
            $this->bottomItems[] = $item;
        }
        $this->lastItem = $item;
    }

    /**
     * Adds a vertical gap before the next item
     * @param float
     */
    function addGap($gap = 4)
    {
        $item = new \ManiaLib\Gui\Elements\Spacer(1, $gap);
        $this->items[] = $item;
    }

    /**
     * Hides the quit/back button
     */
    function hideQuitButton()
    {
        $this->showQuitButton = false;
    }

    protected function preFilter()
    {
        $this->subTitle->setText('$o$999' . $this->subTitle->getText());
        if ($this->showQuitButton) {
            $this->quitButton->text->setText('$09f' . $this->quitButton->text->getText());
            $this->quitButton->text->setPosX($this->quitButton->text->getPosX() - 1);
            $this->addCardElement($this->quitButton);
        }
    }

    protected function postFilter()
    {
        Manialink::beginFrame($this->posX, $this->posY, $this->posZ + 0.1);
        {
            if ($this->items) {
                $layout = new Column();
                $layout->setMarginHeight(5);
                Manialink::beginFrame(0, -62, 0, 1, $layout);
                foreach ($this->items as $item) {
                    $item->save();
                }
                Manialink::endFrame();
            }
            if ($this->bottomItems) {
                $this->bottomItems = array_reverse($this->bottomItems);

                $layout = new Column();
                $layout->setDirection(Column::DIRECTION_UP);
                $layout->setMarginHeight(5);
                Manialink::beginFrame(0, -160, 0, 1, $layout);
                foreach ($this->bottomItems as $item) {
                    $item->save();
                }
                Manialink::endFrame();
            }
        }
        Manialink::endFrame();
    }

}


<?php namespace Arcanedev\LaravelSeo\Entities;

use Arcanedev\LaravelSeo\Seo;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class     RedirectStatuses
 *
 * @package  Arcanedev\LaravelSeo\Entities
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class RedirectStatuses
{
    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Get the all status codes.
     *
     * @return \Illuminate\Support\Collection
     */
    public static function keys()
    {
        return collect([
            Response::HTTP_MOVED_PERMANENTLY,
            Response::HTTP_SEE_OTHER,
            Response::HTTP_TEMPORARY_REDIRECT,
            Response::HTTP_PERMANENTLY_REDIRECT,
        ]);
    }

    /**
     * Get the all status names.
     *
     * @param  string|null  $locale
     *
     * @return \Illuminate\Support\Collection
     */
    public static function all($locale = null)
    {
        return static::keys()->mapWithKeys(function ($code) use ($locale) {
            return [$code => Seo::getTrans("redirections.statuses.{$code}", [], $locale)];
        });
    }

    /**
     * Get the status name.
     *
     * @param  int          $key
     * @param  string|null  $default
     * @param  string|null  $locale
     *
     * @return string
     */
    public static function get($key, $default = null, $locale = null)
    {
        return static::all($locale)->get($key, $default);
    }
}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Application;

abstract class ErrorHandling
{

    protected static $exception;

    protected static $messageConfigs = array(
        'default' => array(
            'title' => '%s',
            'simpleLine' => '    %s',
            'line' => '    %s: %s'
        ),
        'debug' => array(
            'title' => '$<$ff0$o%s$>',
            'simpleLine' => '    %s',
            'line' => '    $<$ff0%s$> :    %s'
        ),
    );

    /**
     * @return \Exception
     */
    static function getException()
    {
        return static::$exception;
    }

    /**
     * Error handler: converts PHP errors into ErrorException
     *
     * @throws ErrorException
     */
    static function exceptionErrorHandler($errno, $errstr, $errfile, $errline)
    {
        if (!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting
            return;
        }
        throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
    }

    static function exceptionHandler(\Exception $exception)
    {
        self::$exception = $exception;

        $request = Request::getInstance();
        $refererURL = $request->getReferer();
        $requestURI = \ManiaLib\Utils\URI::getCurrent();
        $debug = \ManiaLib\Application\Config::getInstance()->debug;

        if ($exception instanceof SilentUserException) {
            $message = static::computeShortMessage($exception) . '  ' . $requestURI;
            $userMessage = $exception->getMessage();
        } elseif ($exception instanceof UserException) {
            $message = static::computeShortMessage($exception) . '  ' . $requestURI;
            \ManiaLib\Utils\Logger::user($message);
            $userMessage = $exception->getMessage();
        } else {
            $requestURILine = sprintf(static::$messageConfigs['default']['line'],
                'Request URI', $requestURI);
            $message = static::computeMessage($exception,
                static::$messageConfigs['default'], array($requestURILine));
            \ManiaLib\Utils\Logger::error($message);
            $userMessage = null;
        }

        $response = Response::getInstance();
        if ($message) {
            $response->message = $debug ? $message : $userMessage;
        }
        if ($debug) {
            $response->width = 300;
            $response->height = 150;
        }
        $response->backLink = $refererURL;
        $response->registerErrorView();
        $response->registerException($exception);
    }

    static function logException(\Exception $e)
    {
        $requestURI = Dispatcher::getInstance()->getCalledURL();
        $requestURILine = sprintf(static::$messageConfigs['default']['line'],
            'Request URI', $requestURI);
        $message = static::computeMessage($e, static::$messageConfigs['default'],
            array($requestURILine));
        \ManiaLib\Utils\Logger::error($message);
    }

    /**
     * Fallback exception handler when nothing works. It tries to dump the
     * exception in a file at the app root and prints a message.
     */
    static function fatalExceptionHandler(\Exception $exception)
    {
        throw $exception;

        file_put_contents(MANIALIB_APP_PATH . 'fatal-error.log', print_r($exception, true),
            FILE_APPEND);
        if (array_key_exists('HTTP_USER_AGENT', $_SERVER) && $_SERVER['HTTP_USER_AGENT'] == 'GameBox') {
            echo '<manialink><timeout>0</timeout></manialink>';
        } else {
            echo '
Oops
';
            echo '
An error occured. Please try again later.
';
            echo '
';
            if (\ManiaLib\Application\Config::getInstance()->debug) {
                var_dump($exception);
            }
        }
    }

    /**
     * Computes a human readable log message from any exception
     * @return string
     */
    final static function computeMessage(\Exception $e, $styles = array(),
                                         $additionalLines = array())
    {
        if (!$styles) {
            $styles = static::$messageConfigs['default'];
        }

        $trace = $e->getTraceAsString();
        $trace = explode("\n", $trace);
        foreach ($trace as $key => $value) {
            $trace[$key] = sprintf($styles['simpleLine'],
                preg_replace('/#[0-9]*\s*/u', '', $value));
        }
        $file = sprintf($styles['simpleLine'], $e->getFile() . ' (' . $e->getLine() . ')');

        $lines[] = sprintf($styles['title'], get_class($e));
        $lines[] = '';
        $lines[] = sprintf($styles['line'], 'Message', print_r($e->getMessage(), true));
        $lines[] = sprintf($styles['line'], 'Code', $e->getCode());
        $lines = array_merge($lines, $additionalLines, array($file), $trace);
        $lines[] = '';
        return implode("\n", $lines);
    }

    /**
     * Computes a short human readable log message from any exception
     * @return string
     */
    final static function computeShortMessage(\Exception $e)
    {
        $message = get_class($e) . '  ' . $e->getMessage() . ' (' . $e->getCode() . ') in ' . $e->getFile() . ' at line ' . $e->getLine();
        return $message;
    }

}


<?php namespace Arcanedev\LaravelSeo\Http\Middleware;

use Arcanedev\LaravelSeo\Contracts\RedirectorFactory;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class     RedirectsMissingPages
 *
 * @package  Arcanedev\LaravelSeo\Http\Middleware
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class RedirectsMissingPages
{
    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /** @var  \Arcanedev\LaravelSeo\Contracts\Redirector */
    protected $redirector;

    /* -----------------------------------------------------------------
     |  Constructor
     | -----------------------------------------------------------------
     */

    /**
     * RedirectsMissingPages constructor.
     *
     * @param  \Arcanedev\LaravelSeo\Contracts\RedirectorFactory  $redirectorManager
     */
    public function __construct(RedirectorFactory $redirectorManager)
    {
        $this->redirector = $redirectorManager->driver();
    }

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Handle the missing pages redirection.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure                  $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if ($response->getStatusCode() !== Response::HTTP_NOT_FOUND)
            return $response;

        return $this->redirector->getRedirectFor($request) ?: $response;
    }
}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Utils;

final class Upload
{

    const UPLOADED_FILE_RIGHTS = 0770;

    /**
     * Tries to read the specified file and save it
     * @param string The path where the file will be saved
     * @param string filename
     * @param int The maximum file size in bytes
     */
    static function uploadFile($path, $filename, $maxSize = 2097152)
    {
        $inputFile = file_get_contents('php://input', null, null, null, $maxSize);

        // Else try to get GET data
        if ($inputFile === false && array_key_exists('input', $_GET)) {
            $inputFile = $_GET['input'];
        }

        // Check for error
        if ($inputFile === false) {
            throw new \Exception('Couldn\'t read input file');
        }
        if (!file_put_contents($path . $filename, $inputFile)) {
            throw new \Exception('Couldn\'t save input file to ' . $path . $filename);
        }
        if (filesize($path . $filename) > $maxSize) {
            // Not sure if usefull here
            unlink($path . $filename);
            throw new FileTooLargeException();
        }
    }
}

class FileTooLargeException extends \ManiaLib\Application\UserException
{

}


<?php

namespace Nexmo\Service;

use Nexmo\Exception as NexmoException;
use Nexmo\Exception;

/**
 * Class Message
 * @package Nexmo\Service
 */
class Message extends Service
{
    /**
     * @return string
     */
    public function getEndpoint()
    {
        return 'sms/json';
    }

    /**
     * Send a message.
     *
     * Nexmo supports Unicode for multiple language support. Text length, however, is limited to
     * 70 characters-exceeding 70 characters will have your message split into parts.
     * Further, the mobile device must support the character encoding, for example, a US device may not display Arabic.
     *
     * In the event your text is longer than 160 characters, Nexmo will split the message into parts.
     * Nexmo's response, in that case, will tell you how many parts the message has been sent in.
     *
     * @param string|int $from            Sender address may be alphanumeric (Ex: from=MyCompany20).
     *                                    Restrictions may apply, depending on the destination.
     * @param string|int $to              Mobile number in international format.
     *                                    Ex: 447525856424 or 00447525856424 when sending to UK.
     * @param string     $type            This can be omitted for text (default),
     *                                    but is required when sending a Binary (binary),
     *                                    WAP Push (wappush), Unicode message (unicode), vcal (vcal) or vcard (vcard).
     * @param string     $text            Required when type='text'.
     *                                    Body of the text message (with a maximum length of 3200 characters).
     * @param string     $statusReportReq Set to 1 if you want to receive a delivery report (DLR) for this request.
     *                                    Make sure to configure your "Callback URL" in your "API Settings"
     * @param string     $clientRef       Include any reference string for your reference.
     *                                    Useful for your internal reports (40 characters max).
     * @param string     $networkCode     Force the recipient network operator MCCMNC, make sure to supply the
     *                                    correct information otherwise the message won't be delivered.
     * @param string     $vcard           vcard text body correctly formatted.
     * @param string     $vcal            vcal text body correctly formatted.
     * @param integer    $ttl             Message life span in milliseconds.
     * @param string     $messageClass    Set to 0 for Flash SMS.
     * @param string     $body            Hex encoded binary data. Ex: 0011223344556677
     * @param string     $udh             To set your custom UDH (Hex encoded). Ex: 06050415811581
     * @throws Exception
     * @return array
     */
    public function invoke(
        $from = null,
        $to = null,
        $type = 'text',
        $text = '',
        $statusReportReq = null,
        $clientRef = null,
        $networkCode = null,
        $vcard = null,
        $vcal = null,
        $ttl = null,
        $messageClass = null,
        $body = null,
        $udh = null
    )
    {
        if(!$from) {
            throw new Exception("\$from parameter cannot be blank");
        }

        if(!$to) {
            throw new Exception("\$to parameter cannot be blank");
        }

        if(!$text) {
            throw new Exception("\$text parameter cannot be blank");
        }

        // If $type is empty, 'text' will be assumed by Nexmo's SMS API.
        if (($type == '' || $type === 'text') && $this->containsUnicode($text)) {
            $type = 'unicode';
        }

        return $this->exec([
            'from' => $from,
            'to' => $to,
            'type' => $type,
            'text' => $text,
            'status-report-req' => $statusReportReq,
            'client-ref' => $clientRef,
            'network-code' => $networkCode,
            'vcard' => $vcard,
            'vcal' => $vcal,
            'ttl' => $ttl,
            'message-class' => $messageClass,
            'body' => $body,
            'udh' => $udh
        ]);
    }

    /**
     * @param string $text
     * @return int
     */
    protected function containsUnicode($text)
    {
        // Valid GSM default character-set codepoint values from http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
        $gsm_0338_codepoints = [0x0040, 0x00A3, 0x0024, 0x00A5, 0x00E8, 0x00E9, 0x00F9, 0x00EC, 0x00F2, 0x00E7, 0x000A, 0x00D8, 0x00F8, 0x000D, 0x00C5, 0x00E5, 0x0394, 0x005F, 0x03A6, 0x0393, 0x039B, 0x03A9, 0x03A0, 0x03A8, 0x03A3, 0x0398, 0x039E, 0x00A0, 0x000C, 0x005E, 0x007B, 0x007D, 0x005C, 0x005B, 0x007E, 0x005D, 0x007C, 0x20AC, 0x00C6, 0x00E6, 0x00DF, 0x00C9, 0x0020, 0x0021, 0x0022, 0x0023, 0x00A4, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x00A1, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x00C4, 0x00D6, 0x00D1, 0x00DC, 0x00A7, 0x00BF, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x00E4, 0x00F6, 0x00F1, 0x00FC, 0x00E0];

        // Split $text into an array in a way that respects multibyte characters.
        $text_chars = preg_split('//u', $text, null, PREG_SPLIT_NO_EMPTY);

        // Array of codepoint values for characters in $text.
        $text_codepoints = array_map([$this, 'uord'], $text_chars);

        // Filter the array to contain only codepoints from $text that are not in the set of valid GSM codepoints.
        $non_gsm_codepoints = array_diff($text_codepoints, $gsm_0338_codepoints);

        // The text contains unicode if the result is not empty.
        return !empty($non_gsm_codepoints);
    }

    /**
     * @param char $unicode_char
     * @return int
     */
    public function uord($unicode_char)
    {
        $k = mb_convert_encoding($unicode_char, 'UCS-2LE', 'UTF-8');
        $k1 = ord(substr($k, 0, 1));
        $k2 = ord(substr($k, 1, 1));
        return $k2 * 256 + $k1;
    }

    /**
     * @param $json
     * @return bool
     * @throws NexmoException
     */
    protected function validateResponse(array $json)
    {
        if (!isset($json['message-count'])) {
            throw new NexmoException('message-count property expected');
        }

        if (!isset($json['messages'])) {
            throw new NexmoException('messages property expected');
        }

        foreach ($json['messages'] as $message) {
            if (!isset($message['status'])) {
                throw new NexmoException('status property expected');
            }

            if (!empty($message['error-text'])) {
                throw new Exception\MessageException($message['status'], $message['error-text']);
            }

            if ($message['status'] > 0) {
                throw new Exception\MessageException($message['status'], 'Unknown');
            }
        }

        return true;
    }
}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Utils;

abstract class URI
{

    /**
     * Returns the Current URL.
     *
     * @return string The current URI
     * @see http://code.google.com/p/oauth2-php
     * @author Originally written by Naitik Shah <naitik@facebook.com>.
     * @author Update to draft v10 by Edison Wong <hswong3i@pantarei-design.com>
     */
    static function getCurrent()
    {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://'
            : 'http://';
        $current_uri = $protocol . $_SERVER['HTTP_HOST'] . self::getRequestURI();
        $parts = parse_url($current_uri);

        $query = '';
        if (!empty($parts['query'])) {
            $params = array();
            parse_str($parts['query'], $params);
            $params = array_filter($params);
            if (!empty($params)) {
                $query = '?' . http_build_query($params, '', '&');
            }
        }

        // Use port if non default.
        $port = isset($parts['port']) &&
        (($protocol === 'http://' && $parts['port'] !== 80) || ($protocol === 'https://' && $parts['port'] !== 443))
            ? ':' . $parts['port'] : '';

        // Rebuild.
        return $protocol . $parts['host'] . $port . $parts['path'] . $query;
    }

    /**
     * Since $_SERVER['REQUEST_URI'] is only available on Apache, we
     * generate an equivalent using other environment variables.
     *
     * @see http://code.google.com/p/oauth2-php
     * @author Originally written by Naitik Shah <naitik@facebook.com>.
     * @author Update to draft v10 by Edison Wong <hswong3i@pantarei-design.com>
     */
    protected static function getRequestURI()
    {
        if (isset($_SERVER['REQUEST_URI'])) {
            $uri = $_SERVER['REQUEST_URI'];
        } else {
            if (isset($_SERVER['argv'])) {
                $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
            } elseif (isset($_SERVER['QUERY_STRING'])) {
                $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
            } else {
                $uri = $_SERVER['SCRIPT_NAME'];
            }
        }
        // Prevent multiple slashes to avoid cross site requests
        $uri = '/' . ltrim($uri, '/');

        return $uri;
    }

}


<?php
/**
 * ManiaLib - Lightweight PHP framework for Manialinks
 *
 * @see         http://code.google.com/p/manialib/
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLib\Gui;

abstract class Tools
{

    /**
     * Returns the X position of an element in relation to another element and
     * according to their respective alignments
     *
     * @param int X position of the parent element
     * @param int Width of the parent element
     * @param string Horizontal alignement of the parent element
     * @param string Horizontal alignement of the element you want to place
     * @return int Calculated X position of the element you want to place
     */
    final public static function getAlignedPosX($posX, $sizeX, $halign, $newAlign)
    {
        if (!$halign) {
            $halign = 'left';
        }
        $alignmentString = $halign . '|' . $newAlign;
        switch ($alignmentString) {
            case 'center|center':
            case 'center|center2':
            case 'left|left':
            case 'right|right':
                $factor = 0;
                break;

            case 'center|left':
            case 'right|center':
            case 'right|center2':
                $factor = -0.5;
                break;

            case 'center|right':
            case 'left|center':
            case 'left|center2':
                $factor = 0.5;
                break;

            case 'left|right':
                $factor = 1;
                break;

            case 'right|left':
                $factor = -1;
                break;

            default:
                throw new \Exception('GUITools: Unsupported positions: ' . $alignmentString);
        }
        return $posX + $factor * $sizeX;
    }

    /**
     * Returns the Y position of an element in relation to another element and
     * according to their respective alignments
     *
     * @param int Y position of the parent element
     * @param int Height of the parent element
     * @param string Vertical alignement of the parent element
     * @param string Vertical alignement of the element you want to place
     * @return int Calculated Y position of the element you want to place
     */
    final public static function getAlignedPosY($posY, $sizeY, $valign, $newAlign)
    {
        switch ($valign) {
            case 'top':
            case null:
                $valign = 'right';
                break;

            case 'bottom':
                $valign = 'left';
                break;
        }
        switch ($newAlign) {
            case 'top':
                $newAlign = 'right';
                break;

            case 'bottom':
                $newAlign = 'left';
                break;
        }
        return self::getAlignedPosX($posY, $sizeY, $valign, $newAlign);
    }

    /**
     * Returns the position of an element in relation to another element and
     * according to their respective alignments
     *
     * @param \ManiaLib\Gui\Element Parent element
     * @param string Horizontal alignement of the element you want to place
     * @param string Vertical alignement of the element you want to place
     * @return array Calculated position of the element you want to place. The
     * array contains 2 elements with "x" and "y" indexes
     */
    final public static function getAlignedPos(\ManiaLib\Gui\Element $object,
                                               $newHalign, $newValign)
    {
        $newPosX = self::getAlignedPosX(
            $object->getPosX(), $object->getRealSizeX(), $object->getHalign(),
            $newHalign);
        $newPosY = self::getAlignedPosY(
            $object->getPosY(), $object->getRealSizeY(), $object->getValign(),
            $newValign);
        return array('x' => $newPosX, 'y' => $newPosY);
    }

}


<?php

namespace NS\BNAME\HTTP;

use PHPixie\HTTP\Request;

/**
 * Simple greeting web page
 */
class Greet extends Processor
{
    /**
     * Default action
     * @param Request $request HTTP request
     * @return mixed
     */
    public function defaultAction($request)
    {
        $template = $this->components()->template();

        $container = $template->get('bname:greet');
        $container->message = "Have fun coding!";
        return $container;
    }
}


<?php

namespace bailangzhan;

use Yii;
use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\base\InvalidConfigException;

/**
 * 图片上传插件
 *
 * @example
 * 同步单图上传的使用
 * ```php
 *   echo $form->field($model, 'image_url')->widget('manks\FileInput');
 * ```
 *
 * @see http://www.manks.top
 */
class FileInput extends InputWidget
{
    /**
     * 图片域名参数，在params.php中进行配置
     * @use Yii::$app->params['imageServer']
     */
    public $imageDomainConfigParam = 'imageServer';
    /**
     * 客户端配置项
     * [[imageServer]] 指定的图片域名，该配置项和$this->imageDomainConfigParam至少配置一个，优先级别该配置项大于$this->imageDomainConfigParam，如果二者都未配置，则抛出异常
     *
     */
    public $clientOptions = [];

    public function run ()
    {
        // 初始化操作
        $this->preInit();
        // 注册所需要的资源
        $this->registerClientScript();

        // 构建html结构
        if ($this->hasModel()) {
            $this->options = array_merge($this->options, $this->clientOptions);

            // 创建上传的input
            $file = Html::activeInput('file', $this->model, $this->attribute, $this->options);

            // 如果当前模型有该属性值，则默认显示
            if ($image = $this->model->{str_replace(['[', ']'], '', $this->attribute)}) {
                $imageServer = !empty($this->options['imageServer']) ? $this->options['imageServer'] : Yii::$app->params[$this->imageDomainConfigParam];
                // 显示该图片
                $li = Html::tag('li', '', ['class' => 'uploader__file', 'style' => 'background: url(' . $imageServer . $image . ') no-repeat; background-size: 100%;']);
                // 追加一个隐藏的input框，否则update的时候会覆盖原图片
                $file .= Html::activeInput('hidden', $this->model, $this->attribute, ['value' => $image]);
            }

            $uploaderFiles = Html::tag('ul', isset($li) ? $li : '', ['class' => 'uploaderFiles']);
            $inputButton = Html::tag('div', $file, ['class' => 'input-box']);
            echo Html::tag('div', $uploaderFiles.$inputButton, ['class' => 'file-div']);
        }
        else {
            throw new InvalidConfigException("'model'必须设置.");
        }
    }
    /**
     * pre init
     */
    public function preInit ()
    {
        if (!isset(Yii::$app->params[$this->imageDomainConfigParam]) && !isset($this->clientOptions['imageServer'])) {
            throw new InvalidConfigException("'FileInput clientOptions的imageServer配置项或者params.php的配置项FileInput::imageDomainConfigParam'至少要设置一个.");
        }
    }
    /**
     * Registers the needed client script and options.
     */
    public function registerClientScript ()
    {
        $view = $this->getView();
        FileInputAsset::register($view);
    }
}


<?php
namespace oe\modules\backuprestore\controllers;

use Yii;
use yii\web\Controller;
use oe\modules\backuprestore\models\UploadForm;
use yii\data\ArrayDataProvider;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
use yii\helpers\Html;
use yii\base\ErrorException;

class DefaultController extends Controller {

    public $menu = [];
    public $tables = [];
    public $fp;
    public $file_name;
    public $_path = null;
    public $back_temp_file = 'db_backup_';

    //public $layout = '//layout2';

    protected function getPath() {
        if (isset($this->module->path))
            $this->_path = $this->module->path;
        else
            $this->_path = Yii::$app->basePath . '/_backup/';

        if (!file_exists($this->_path)) {
            mkdir($this->_path);
            chmod($this->_path, '777');
        }
        return $this->_path;
    }

    public function execSqlFile($sqlFile) {
        $message = "ok";

        if (file_exists($sqlFile)) {
            $sqlArray = file_get_contents($sqlFile);

            $cmd = Yii::$app->db->createCommand($sqlArray);
            try {
                $cmd->execute();
            } catch (CDbException $e) {
                $message = $e->getMessage();
            }
        }
        return $message;
    }

    public function getColumns($tableName) {
        $sql = 'SHOW CREATE TABLE ' . $tableName;
        $cmd = Yii::$app->db->createCommand($sql);
        $table = $cmd->queryOne();

        $create_query = $table['Create Table'] . ';';

        $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
        $create_query = preg_replace('/AUTO_INCREMENT\s*=\s*([0-9])+/', '', $create_query);
        if ($this->fp) {
            $this->writeComment('TABLE `' . addslashes($tableName) . '`');
            $final = 'DROP TABLE IF EXISTS `' . addslashes($tableName) . '`;' . PHP_EOL . $create_query . PHP_EOL . PHP_EOL;
            fwrite($this->fp, $final);
        } else {
            $this->tables[$tableName]['create'] = $create_query;
            return $create_query;
        }
    }

    public function getData($tableName) {
        $sql = 'SELECT * FROM ' . $tableName;
        $cmd = Yii::$app->db->createCommand($sql);
        $dataReader = $cmd->query();

        $data_string = '';

        foreach ($dataReader as $data) {
            $itemNames = array_keys($data);
            $itemNames = array_map("addslashes", $itemNames);
            $items = join('`,`', $itemNames);
            $itemValues = array_values($data);
            $itemValues = array_map("addslashes", $itemValues);
            $valueString = join("','", $itemValues);
            $valueString = "('" . $valueString . "'),";
            $values = "\n" . $valueString;
            if ($values != "") {
                $data_string .= "INSERT INTO `$tableName` (`$items`) VALUES" . rtrim($values, ",") . ";" . PHP_EOL;
            }
        }

        if ($data_string == '')
            return null;

        if ($this->fp) {
            $this->writeComment('TABLE DATA ' . $tableName);
            $final = $data_string . PHP_EOL . PHP_EOL . PHP_EOL;
            fwrite($this->fp, $final);
        } else {
            $this->tables[$tableName]['data'] = $data_string;
            return $data_string;
        }
    }

    public function getTables($dbName = null) {
        $sql = 'SHOW TABLES';
        $cmd = Yii::$app->db->createCommand($sql);
        $tables = $cmd->queryColumn();
        return $tables;
    }

    public function StartBackup($addcheck = true) {
        $this->file_name = $this->path . $this->back_temp_file . date('Y.m.d_H.i.s') . '.sql';

        $this->fp = fopen($this->file_name, 'w+');

        if ($this->fp == null)
            return false;
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        if ($addcheck) {
            fwrite($this->fp, 'SET AUTOCOMMIT=0;' . PHP_EOL);
            fwrite($this->fp, 'START TRANSACTION;' . PHP_EOL);
            fwrite($this->fp, 'SET SQL_QUOTE_SHOW_CREATE = 1;' . PHP_EOL);
        }
        fwrite($this->fp, 'SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;' . PHP_EOL);
        fwrite($this->fp, 'SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;' . PHP_EOL);
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        $this->writeComment('START BACKUP');
        return true;
    }

    public function EndBackup($addcheck = true) {
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        fwrite($this->fp, 'SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;' . PHP_EOL);
        fwrite($this->fp, 'SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;' . PHP_EOL);

        if ($addcheck) {
            fwrite($this->fp, 'COMMIT;' . PHP_EOL);
        }
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        $this->writeComment('END BACKUP');
        fclose($this->fp);
        $this->fp = null;
    }

    public function writeComment($string) {
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        fwrite($this->fp, '-- ' . $string . PHP_EOL);
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
    }

    public function actionCreate() {
        $flashError = '';
        $flashMsg = '';

        $tables = $this->getTables();

        if (!$this->StartBackup()) {
            //render error
            $flashError = 'error';
            $flashMsg = 'Some errors creating the file';
            return $this->render('index');
        }

        foreach ($tables as $tableName) {
            $this->getColumns($tableName);
        }
        foreach ($tables as $tableName) {
            $this->getData($tableName);
        }
        $this->EndBackup();

        $flashError = 'success';
        $flashMsg = 'The file was created !!!';

        \Yii::$app->getSession()->setFlash($flashError, $flashMsg);

        $this->redirect(array('index'));
    }

    public function actionClean($redirect = true) {
        $ignore = array('tbl_user', 'tbl_user_role', 'tbl_event');
        $tables = $this->getTables();

        if (!$this->StartBackup()) {
            //render error
            Yii::$app->user->setFlash('success', "Error");
            return $this->render('index');
        }

        $message = '';

        foreach ($tables as $tableName) {
            if (in_array($tableName, $ignore))
                continue;
            fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
            fwrite($this->fp, 'DROP TABLE IF EXISTS ' . addslashes($tableName) . ';' . PHP_EOL);
            fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);

            $message .= $tableName . ',';
        }
        $this->EndBackup();

        // logout so there is no problme later .
        Yii::$app->user->logout();

        $this->execSqlFile($this->file_name);
        unlink($this->file_name);
        $message .= ' are deleted.';
        Yii::$app->session->setFlash('success', $message);
        return $this->redirect(array('index'));
    }

    public function actionDelete($file = null) {
        $flashError = '';
        $flashMsg = '';

        $file = $_GET[0]['filename'];

        $this->updateMenuItems();
        if (isset($file)) {
            $sqlFile = $this->path . basename($file);
            if (file_exists($sqlFile)) {
                unlink($sqlFile);
                $flashError = 'success';
                $flashMsg = 'The file ' . $sqlFile . ' was successfully deleted.';
            } else {
                $flashError = 'error';
                $flashMsg = 'The file ' . $sqlFile . ' was not found.';
            }
        } else {
            $flashError = 'error';
            $flashMsg = 'The file ' . $sqlFile . ' was not found.';
        }
        \Yii::$app->getSession()->setFlash($flashError, $flashMsg);
        $this->redirect(array('index'));
    }

    public function actionDownload($file = null) {
        $this->updateMenuItems();
        if (isset($file)) {
            $sqlFile = $this->path . basename($file);
            if (file_exists($sqlFile)) {
                $request = Yii::$app->getRequest();
                $request->sendFile(basename($sqlFile), file_get_contents($sqlFile));
            }
        }
        throw new CHttpException(404, Yii::t('app', 'File not found'));
    }

    public function actionIndex() {
        //$this->layout = 'column1';
        $this->updateMenuItems();
        $path = $this->path;
        $dataArray = array();

        $list_files = glob($path . '*.sql');
        if ($list_files) {
            $list = array_map('basename', $list_files);
            sort($list);
            foreach ($list as $id => $filename) {
                $columns = array();
                $columns['id'] = $id;
                $columns['name'] = basename($filename);
                $columns['size'] = filesize($path . $filename);

                $columns['create_time'] = date('Y-m-d H:i:s', filectime($path . $filename));
                $columns['modified_time'] = date('Y-m-d H:i:s', filemtime($path . $filename));

                $dataArray[] = $columns;
            }
        }
        $dataProvider = new ArrayDataProvider(['allModels' => $dataArray]);
        return $this->render('index', array(
                    'dataProvider' => $dataProvider,
        ));
    }

    public function actionSyncdown() {
        $tables = $this->getTables();

        if (!$this->StartBackup()) {
            //render error
            return $this->render('index');
        }

        foreach ($tables as $tableName) {
            $this->getColumns($tableName);
        }
        foreach ($tables as $tableName) {
            $this->getData($tableName);
        }
        $this->EndBackup();
        return $this->actionDownload(basename($this->file_name));
    }

    public function actionRestore($file = null) {
        $flashError = '';
        $flashMsg = '';

        $file = $_GET['filename'];

        $this->updateMenuItems();
        $sqlFile = $this->path . basename($file);
        if (isset($file)) {
            $sqlFile = $this->path . basename($file);
            $flashError = 'success';
            $flashMsg = 'Looks like working :)';
        } else {
            $flashError = 'error';
            $flashMsg = 'Problems with the file name';
        }
        $this->execSqlFile($sqlFile);

        \Yii::$app->getSession()->setFlash($flashError, $flashMsg);
        $this->redirect(array('index'));
    }

    public function actionUpload() {
        $model = new UploadForm();
        if (isset($_POST['UploadForm'])) {
            $model->attributes = $_POST['UploadForm'];
            //oe change cUploaded for this
            $model->upload_file = UploadedFile::getInstance($model, 'upload_file');
            if ($model->upload_file->saveAs($this->path . $model->upload_file)) {
                // redirect to success page
                return $this->redirect(array('index'));
            }
        }

        return $this->render('upload', array('model' => $model));
    }

    protected function updateMenuItems($model = null) {
        // create static model if model is null
        if ($model == null)
            $model = new UploadForm();

        switch ($this->action->id) {
            case 'restore': {
                    $this->menu[] = array('label' => Yii::t('app', 'View Site'), 'url' => Yii::$app->HomeUrl);
                }
            case 'create': {
                    $this->menu[] = array('label' => Yii::t('app', 'List Backup'), 'url' => array('index'));
                }
                break;
            case 'upload': {
                    $this->menu[] = array('label' => Yii::t('app', 'Create Backup'), 'url' => array('create'));
                }
                break;
            default: {
                    $this->menu[] = array('label' => Yii::t('app', 'List Backup'), 'url' => array('index'));
                    $this->menu[] = array('label' => Yii::t('app', 'Create Backup'), 'url' => array('create'));
                    $this->menu[] = array('label' => Yii::t('app', 'Upload Backup'), 'url' => array('upload'));
                    $this->menu[] = array('label' => Yii::t('app', 'Restore Backup'), 'url' => array('restore'));
                    $this->menu[] = array('label' => Yii::t('app', 'Clean Database'), 'url' => array('clean'));
                    $this->menu[] = array('label' => Yii::t('app', 'View Site'), 'url' => Yii::$app->HomeUrl);
                }
                break;
        }
    }

}


<?php

namespace Praxigento\Accounting\Ui\DataProvider\Grid\Operation;

use Praxigento\Accounting\Repo\Data\Operation as EOperation;
use Praxigento\Accounting\Repo\Data\Type\Operation as ETypeOper;

class Query
    extends \Praxigento\Core\App\Ui\DataProvider\Grid\Query\Builder
{
    /**#@+ Tables aliases for external usage ('camelCase' naming) */
    const AS_OPER = 'pao';
    const AS_TYPE = 'pato';
    /**#@- */

    /**#@+
     * Aliases for data attributes.
     */
    const A_DATE_PERFORMED = 'datePerformed';
    const A_ID = 'id';
    const A_NOTE = 'note';
    const A_TYPE = 'type';

    /**#@- */

    protected function getMapper()
    {
        if (is_null($this->mapper)) {
            $map = [
                self::A_DATE_PERFORMED => self::AS_OPER . '.' . EOperation::A_DATE_PREFORMED,
                self::A_ID => self::AS_OPER . '.' . EOperation::A_ID,
                self::A_NOTE => self::AS_OPER . '.' . EOperation::A_NOTE,
                self::A_TYPE => self::AS_TYPE . '.' . ETypeOper::A_CODE
            ];
            $this->mapper = new \Praxigento\Core\App\Repo\Query\Criteria\Def\Mapper($map);
        }
        $result = $this->mapper;
        return $result;
    }

    protected function getQueryItems()
    {
        $result = $this->conn->select();

        /* define tables aliases for internal usage (in this method) */
        $asOper = self::AS_OPER;
        $asType = self::AS_TYPE;

        /* SELECT FROM prxgt_acc_operation */
        $tbl = $this->resource->getTableName(EOperation::ENTITY_NAME);
        $as = $asOper;
        $cols = [
            self::A_ID => EOperation::A_ID,
            self::A_DATE_PERFORMED => EOperation::A_DATE_PREFORMED,
            self::A_NOTE => EOperation::A_NOTE
        ];
        $result->from([$as => $tbl], $cols);

        /* LEFT JOIN prxgt_acc_type_operation */
        $tbl = $this->resource->getTableName(ETypeOper::ENTITY_NAME);
        $as = $asType;
        $cond = $asType . '.' . ETypeOper::A_ID . '=' . $asOper . '.' . EOperation::A_TYPE_ID;
        $cols = [
            self::A_TYPE => ETypeOper::A_CODE
        ];
        $result->joinLeft([$as => $tbl], $cond, $cols);

        /* return  result */
        return $result;
    }

    protected function getQueryTotal()
    {
        /* get query to select items */
        /** @var \Magento\Framework\DB\Select $result */
        $result = $this->getQueryItems();
        /* ... then replace "columns" part with own expression */
        $value = 'COUNT(' . self::AS_OPER . '.' . EOperation::A_ID . ')';

        /**
         * See method \Magento\Framework\DB\Select\ColumnsRenderer::render:
         */
        /**
         * if ($column instanceof \Zend_Db_Expr) {...}
         */
        $exp = new \Praxigento\Core\App\Repo\Query\Expression($value);
        /**
         *  list($correlationName, $column, $alias) = $columnEntry;
         */
        $entry = [null, $exp, null];
        $cols = [$entry];
        $result->setPart('columns', $cols);
        return $result;
    }
}


<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2018
 */

namespace Praxigento\Accounting\Service\Account\Balance\LastDate\A\Repo\Query;

use Praxigento\Accounting\Repo\Data\Account as EAcc;
use Praxigento\Accounting\Repo\Data\Transaction as ETran;

/**
 * Get base query to select minimal date_applied for transactions by asset type or account IDs.
 * Add appropriate 'where' clauses after build.
 */
class GetMinDateTrans
    extends \Praxigento\Core\App\Repo\Query\Builder
{
    /** Tables aliases for external usage ('camelCase' naming) */
    const AS_ACC = 'acc';
    const AS_TRAN = 'trn';

    /** Columns/expressions aliases for external usage ('camelCase' naming) */
    const A_MIN_DATE = 'minDate';

    /** Entities are used in the query */
    const E_ACC = EAcc::ENTITY_NAME;
    const E_TRAN = ETran::ENTITY_NAME;

    /**
     * Get base query to select minimal date_applied for transactions by asset type or account IDs.
     * Add appropriate 'where' clauses after build.
     *
     * SELECT
     * MIN(trn.date_applied)
     * FROM
     * prxgt_acc_transaction as trn
     * LEFT JOIN prxgt_acc_account as acc ON
     * acc.id = trn.debit_acc_id
     *
     * @inheritdoc
     */
    public function build(\Magento\Framework\DB\Select $source = null)
    {
        /* this is root query builder (started from SELECT) */
        $result = $this->conn->select();

        /* define tables aliases for internal usage (in this method) */
        $asAcc = self::AS_ACC;
        $asTran = self::AS_TRAN;

        /* FROM prxgt_acc_transaction */
        $tbl = $this->resource->getTableName(self::E_TRAN);    // name with prefix
        $as = $asTran;    // alias for 'current table' (currently processed in this block of code)
        $exp = $this->expMin();
        $cols = [
            self::A_MIN_DATE => $exp
        ];
        $result->from([$as => $tbl], $cols);    // standard names for the variables

        /* LEFT JOIN prxgt_acc_account */
        $tbl = $this->resource->getTableName(self::E_ACC);
        $as = $asAcc;
        $cols = [];
        /* bind account to transaction as debit account to bind asset type below (credit acc. has the same type) */
        $cond = "$as." . EAcc::A_ID . "=$asTran." . ETran::A_DEBIT_ACC_ID;
        $result->joinLeft([$as => $tbl], $cond, $cols);

        return $result;
    }

    private function expMin()
    {
        $value = 'MIN(' . self::AS_TRAN . '.' . ETran::A_DATE_APPLIED . ")";
        $result = new \Praxigento\Core\App\Repo\Query\Expression($value);
        return $result;
    }
}