<?php
/**
 *  Dolumar engine, php/html MMORTS engine
 *  Copyright (C) 2009 Thijs Van der Schaeghe
 *  CatLab Interactive bvba, Gent, Belgium
 *  http://www.catlab.eu/
 *  http://www.dolumar.com/
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

class Neuron_GameServer_Windows_Window
	implements Neuron_GameServer_Interfaces_Window
{
	private
		$width = 300,
		$height = 150,
		$posLeft = null,
		$posTop = null,
		$posRight = null,
		$posBottom = null,
		$fixed = false,
		$className = 'windowContent',
		$isFixed = 'false',
		$noBorder = 'false',
		$zLevel = 10,
		$bottom = 'auto',
		$title = 'Untitled Window',
		$divId,
		$onlyOnce = 'false',
		$onLoad = false,
		$onFirstload = false,
		$onResize = false,
		$ajaxPollSeconds = null,
		$canClose = true,
		$sPool = 'general',

		$minWidth = 100,
		$minHeight = 20,

		$modal = false,
		$centered = false,

		$container = 'center',

		$requires = null
	;

	public $channel;

	// There we go with the new functions!
	private $sType = 'window';
	private $updates = array (), $dom;
	private $requestData = Array (), $inputData = array ();

	private $fGetUrlCallback;

	// Windows should know about their server
	private $server;

	/*
		Do nothing really...
	*/
	public final function __construct ()
	{
		$this->channel = new Neuron_GameServer_Models_Channel ();

		$this->setUrlCallback (array ($this, '_getUrl'));
		libxml_use_internal_errors(true);
	}

	protected function getXMLNamespace ()
	{
		return 'http://www.w3.org/1999/xhtml';
	}

	public function setServer (Neuron_GameServer $server)
	{
		$this->server = $server;
	}

	public function getServer ()
	{
		return $this->server;
	}

	public function setContainer ($container)
	{
		$this->container = $container;
	}

	public function getContainer ()
	{
		return $this->container;
	}

	public static function getWindow ($v)
	{
		$classname = 'Neuron_GameServer_Windows_'.ucfirst ($v);
		return new $classname ();
	}

	public function setUrlCallback ($callback)
	{
		$this->fGetUrlCallback = $callback;
	}

	public function setSettings ()
	{

	}

	public function setModal ($modal = true)
	{
		$this->modal = $modal == true;
	}

	public function setDom ($dom)
	{
		$this->dom = $dom;
	}

	public function setDivId ($id)
	{
		$this->divId = $id;
	}

	public function getDivId ()
	{
		return $this->divId;
	}

	public function getOnload ()
	{
		return $this->onLoad;
	}

	public function setOnload ($j)
	{
		$this->onLoad = $j;
	}

	public function getFirstOnload ()
	{
		return $this->onFirstload;
	}

	public function setOnFirstload ($j)
	{
		$this->onFirstload = $j;
	}

	public function getOnResize ()
	{
		return $this->onResize;
	}

	public function setOnResize ($t)
	{
		$this->onResize = $t;
	}

	public function setAjaxPollSeconds ($sec)
	{
		$this->ajaxPollSeconds = $sec;
	}

	public function setType ($sType)
	{
		$this->sType = $sType;
	}

	public function getType ()
	{
		return $this->sType;
	}

	public function setPool ($pool)
	{
		$this->sPool = $pool;
	}

	/*
		This function makes sure certain trackers are available in the window
		content.
	*/
	public final function getWindowContent ()
	{
		$out = $this->getContent ();

		if (!$out || $this->getType () == 'invisible')
		{
			return false;
		}

		// Tracker (yes, we need opensocial as well)
		if (isset ($_SESSION['just_logged_in']) && $_SESSION['just_logged_in'])
		{
			$me = Neuron_GameServer::getPlayer ();
			if ($me)
			{
				$out .= 'getTrackerUrl ('login')).'" width="1" '.
					'height="1" border="0" class="hidden-iframe">';
			}

			$_SESSION['just_logged_in'] = false;
		}

		return $out;
	}

	public function getNewWindow ()
	{
		$contentInput = $this->getWindowContent ();

		if ($contentInput || $this->getType () == 'invisible')
		{
			$dom = $this->dom;

			$element = $dom->createElement('openwindow');

			// Type
			switch ($this->sType)
			{
				case 'window':
				case 'panel':
				case 'invisible':
					$element->setAttribute ('type', $this->sType);
				break;

				default:
					$element->setAttribute ('type', 'window');
				break;
			}

			// Size
			$element->setAttribute ('width', $this->width);
			$element->setAttribute ('height', $this->height);

			$element->setAttribute ('minWidth', $this->minWidth);
			$element->setAttribute ('minHeight', $this->minHeight);

			if (isset ($this->container))
			{
				$element->setAttribute ('container', $this->container);
			}

			// Position
			/*
			$this->posLeft = $left;
			$this->posTop = $top;
			$this->posRight = $right;
			$this->posBottom = $bottom;
			*/

			$element->setAttribute ('left', $this->posLeft);
			$element->setAttribute ('top', $this->posTop);
			$element->setAttribute ('right', $this->posRight);
			$element->setAttribute ('bottom', $this->posBottom);

			// Title (in CDATA element)
			$element->setAttribute ('title', $this->title);

			// Dialog ID (from session) must be unique, but doesn't have to be linear.
			if (!isset ($_SESSION['iDialogCounter']))
			{
				$_SESSION['iDialogCounter'] = time ();
			}

			$element->setAttribute ('dialogId', $_SESSION['iDialogCounter']);
			$_SESSION['iDialogCounter'] ++;

			$element->setAttribute ('windowId', $this->getWindowId ());
			$element->setAttribute ('className', $this->className);

			$element->setAttribute ('onlyOnce', $this->onlyOnce);

			$element->setAttribute ('center', $this->centered ? '1' : '0');
			$element->setAttribute ('modal', $this->modal ? '1' : '0');

			$element->setAttribute ('requires', $this->requires);

			//$element->appendChild ($dom->createElement ('ajaxPollSec', $this->ajaxPollSeconds));
			$element->setAttribute ('pollInterval', $this->ajaxPollSeconds);

			// Content (XML)
			if ($this->getType () == 'invisible')
			{

			}
			else
			{
				$content = $dom->createElement ('content');
				$content->setAttribute ('xmlns', $this->getXMLNamespace ());

				$contentInput = $this->xmlEntities ($contentInput);

				$fragment = $dom->createDocumentFragment ();
				if ($fragment->appendXML ($contentInput))
				{
					$content->appendChild ($fragment);
				}
				else
				{
					$this->displayXMLErrors ($contentInput, $content);
				}

				$element->appendChild ($content);
			}

			$element->setAttribute ('onLoad', $this->getOnload () . $this->getFirstOnload ());
			$element->setAttribute ('pool', $this->sPool);
			$element->setAttribute ('closable', $this->canClose);

			// Request data
			$content = $dom->createCDATASection (json_encode ($this->getRequestData ()));
			$attribute = $dom->createElement ('requestData');
			$attribute->appendChild ($content);
			$element->appendChild ($attribute);

			$subsribed = $dom->createElement ('subscriptions');
			foreach ($this->channel->getSubscriptions () as $v)
			{
					$el = $dom->createElement ('channel');
					$el->setAttribute ('channel', $v);
					$subsribed->appendChild ($el);
			}
			$element->appendChild ($subsribed);

			return $element;
		}
		else
		{
			return false;
		}
	}

	/*
		Return the name of this window
	*/
	public function getWindowId ()
	{
		$sn = explode ('_', get_class ($this));
		return $sn[count ($sn) - 1];
	}

	/*
		Equals: checks if this window is a duplicate of another window
	*/
	public function equals (Neuron_GameServer_Windows_Window $window)
	{
		if ($this->getWindowId () == $window->getWindowId ())
		{
			// Check the request data
			if (json_encode ($this->getRequestData ()) == json_encode ($window->getRequestData ()))
			{
				return true;
			}
		}
		return false;
	}

	public function getContent ()
	{
		return '
This is a default test window.
';
	}

	public function setSize ($sizeX, $sizeY = 'auto')
	{
		$this->width = $sizeX;
		$this->height = $sizeY;
	}

	public function setMinSize ($sizeX, $sizeY)
	{
		$this->minWidth = $sizeX;
		$this->minHeight = $sizeY;
	}

	public function setNoClose ()
	{
		$this->canClose = false;
	}

	public function setPosition ($left, $top, $right = null, $bottom = null)
	{
		$this->posLeft = $left;
		$this->posTop = $top;
		$this->posRight = $right;
		$this->posBottom = $bottom;
	}

	public function setFixed ()
	{
		$this->isFixed = 'fixed';
	}

	public function setZ ($l)
	{
		$this->zLevel = $l;
	}

	public function setClassName ($class)
	{
		$this->setClass ($class);
	}

	public function setClass ($class)
	{
		$this->className = $class;
	}

	public function setNoBorder ()
	{
		$this->noBorder = 'noborder';
	}

	public function setCentered ()
	{
		$this->centered = 'centered';
	}

	public function setTitle ($title)
	{
		$title = html_entity_decode ($title, ENT_QUOTES, 'UTF-8');

		if (mb_strlen ($title, 'UTF-8') > 30)
		{
			$title = mb_substr ($title, 0, 30, 'UTF-8') . '...';
			if (strpos ($title, '('))
			{
				$title .= ')';
			}
		}

		$this->title = $title;
	}

	public function setAllowOnlyOnce ()
	{
		$this->onlyOnce = 'true';
	}

	public function getRefresh () {}

	private function appendChannelUpdates ($element)
	{
		$dom = $this->dom;
		foreach ($this->channel->getUpdates () as $v)
		{
			$up = $dom->createElement ('update');
			$up->setAttribute ('action', 'channel');
			$up->setAttribute ('chaction', $v['action']);
			$up->setAttribute ('channel', $v['channel']);
			$element->appendChild ($up);
		}
	}

	public function getDOMRefresh ()
	{
		// Process input
		if (count ($this->getInputData ()) > 0)
		{
			$this->processInput ();
		}

		else
		{
			// Regular update
			$this->getRefresh ();
		}

		$dom = $this->dom;

		if (count ($this->updates) > 0)
		{
			$element = $dom->createElement('updatewindow');
			$element->setAttribute ('windowId', $this->getWindowId ());
			$element->setAttribute ('dialogId', $this->divId);

			if ($this->ajaxPollSeconds !== null)
			{
				$element->setAttribute ('pollInterval', $this->ajaxPollSeconds);
			}

			// $this->updates (array) has DOM objects which we will append now.
			foreach ($this->updates as $v)
			{
				$element->appendChild ($v);
			}

			$content = $dom->createCDATASection (urlencode (json_encode ($this->getRequestData ())));
			$attribute = $dom->createElement ('requestData');
			$attribute->appendChild ($content);
			$element->appendChild ($attribute);

			$element->setAttribute ('onLoad', $this->getOnload ());

			$this->appendChannelUpdates ($element);

			return $element;
		}

		else
		{
			return false;
		}
	}

	public function updateContent ($data = false)
	{
		if ($this->getType () == 'invisible')
		{
			return;
		}

		$dom = $this->dom;

		if (!$data)
		{
			$data = $this->getWindowContent ();
		}

		$update = $dom->createElement ('update');
		//$update->appendChild ($dom->createElement ('action', 'updateContent'));
		$update->setAttribute ('action', 'updateContent');

		$content = $dom->createElement ('content');
		$content->setAttribute ('xmlns', $this->getXMLNamespace ());

		$data = $this->xmlEntities ($data);

		$fragment = $dom->createDocumentFragment ();
		if ($fragment->appendXML ($data))
		{
			$content->appendChild ($fragment);
		}
		else
		{
			$this->displayXMLErrors ($data, $content);
		}

		$update->appendChild ($content);

		$this->updates[] = $update;
	}

	private function displayXmlErrors ($data, $content)
	{
		$dom = $this->dom;

		$content->appendChild ($dom->createElement ('h2', 'O-ow! Failed parsing XML'));
		$content->appendChild ($dom->createElement ('p', 'The content if this window is not valid XML. Please contact the game administrator.'));

		$a = simplexml_load_string ($data);
		foreach (libxml_get_errors () as $v)
		{
			$content->appendChild ($dom->createElement ('p', $v->line . ':' . $v->column . ': ' . $v->message));
		}

		$dommy = $dom->createElement ('textarea', htmlentities ($data));
		$dommy->setAttribute ('style', 'width: 90%; height: 100px;');

		$content->appendChild ($dommy);

		//customMail ('thijs@catlab.be', 'Invalid xml content debug', $data);
	}

	public function javascriptCommand ($command)
	{

	}

	public function mapJump ($x, $y)
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'scrollmap');
		$update->setAttribute ('x', $x);
		$update->setAttribute ('y', $y);

		$this->updates[] = $update;
	}

	public function updateRequestData ($data)
	{
		if (!is_array ($data))
		{
			$data = array ($data);
		}

		$this->setRequestData ($data);

		$update = $this->dom->createElement ('update');
		$update->setAttribute ('action', 'updaterequestdata');

		$this->updates[] = $update;
	}

	public function alert ($alert)
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'alert');
		$update->appendChild ($dom->createElement ('message', $alert));

		$this->updates[] = $update;
	}

	public function dialog ($alert, $label1, $action1, $label2 = 'Cancel', $action2 = 'void(0);')
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'dialog');

		$update->appendChild ($dom->createElement ('message', $alert));
		$update->appendChild ($dom->createElement ('label1', $label1));
		$update->appendChild ($dom->createElement ('action1', $action1));
		$update->appendChild ($dom->createElement ('label2', $label2));
		$update->appendChild ($dom->createElement ('action2', $action2));

		$this->updates[] = $update;
	}

	public function highlight ($id)
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'highlight');

		$update->appendChild ($dom->createElement ('id', $id));

		$this->updates[] = $update;
	}

	public function addHtmlToElement ($div, $html, $pos = 'top')
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');

		$update->setAttribute ('action', 'addContentToElement');
		$update->setAttribute ('className', $div);
		$update->setAttribute ('position', $pos);

		/*
		$html = $dom->createCDATASection ($html);

		$attribute = $dom->createElement ('content');
		$attribute->appendChild ($html);
		$update->appendChild ($attribute);
		*/

		$content = $dom->createElement ('content');
		$content->setAttribute ('xmlns', $this->getXMLNamespace ());

		$html = $this->xmlEntities ($html);

		$fragment = $dom->createDocumentFragment ();
		if ($fragment->appendXML ($html))
		{
			$content->appendChild ($fragment);
		}
		else
		{
			$this->displayXMLErrors ($html, $content);
		}

		$update->appendChild ($content);

		$this->updates[] = $update;
	}

	public function showNewsflash ($html)
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');

		$update->setAttribute ('action', 'showNewsflash');

		$content = $dom->createElement ('content');
		$content->setAttribute ('xmlns', $this->getXMLNamespace ());

		$html = $this->xmlEntities ($html);

		$fragment = $dom->createDocumentFragment ();
		if ($fragment->appendXML ($html))
		{
			$content->appendChild ($fragment);
		}
		else
		{
			$this->displayXMLErrors ($html, $content);
		}

		$update->appendChild ($content);

		$this->updates[] = $update;
	}

	public function updateMap ()
	{
		// Trigger a "reload" map event.
		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'updateMap');
		$this->updates[] = $update;
	}

	public function watchObject (Neuron_GameServer_Map_MapObject $object)
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'watch');
		$update->setAttribute ('object', $object->getUOID ());

		$this->updates[] = $update;
	}

	public function reloadLocation ($x, $y, $z = 0)
	{
		if ($x instanceof Neuron_GameServer_Map_Location)
		{
			$z = $x->z ();
			$y = $x->y ();
			$x = $x->x ();
		}

		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'reloadLocation');
		$update->setAttribute ('x', $x);
		$update->setAttribute ('y', $y);

		$this->updates[] = $update;
	}

	public function reloadMap ()
	{
		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'reloadMap');

		$this->updates[] = $update;
	}

	public function setRequestData ($data)
	{
		//$this->requestData = explode ('&', urldecode ($data));
		if (is_array ($data))
		{
			$this->requestData = $data;
		}
		else
		{
			$this->requestData = json_decode (urldecode ($data), true);
		}
	}

	public function getRequestData ()
	{
		return $this->requestData;
	}

	public function setJsonInputData ($json)
	{
		$this->setInputData (json_decode ($json, true));
	}

	public function setInputData ($data)
	{
		$this->inputData = $data;
	}

	public function getInputData ()
	{
		return $this->inputData;
	}

	/*
		Return the value of the request
		or the input data.
	*/
	public function getInput ($key)
	{
		$data = $this->getInputData ();
		$data2 = $this->getRequestData ();
		return isset ($data[$key]) ? $data[$key] : (isset ($data2[$key]) ? $data2[$key] : null);
	}

	public function reloadContent ()
	{
		$this->updateContent ();
	}

	public function updateTitle ($title = null)
	{
		if (!empty ($title))
		{
			$this->title = $title;
		}

		$dom = $this->dom;

		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'changeTitle');

		// Put in CData
		$content = $dom->createCDATASection ($this->title);

		$attribute = $dom->createElement ('title');
		$attribute->appendChild ($content);
		$update->appendChild ($attribute);

		$this->updates[] = $update;
	}

	public function closeWindow ()
	{
		$dom = $this->dom;
		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'closeWindow');
		$this->updates[] = $update;
	}

	public function reloadWindow ()
	{
		$dom = $this->dom;
		$update = $dom->createElement ('update');
		$update->setAttribute ('action', 'reloadWindow');
		$this->updates[] = $update;
	}

	public function popupWindow ($url, $width = 600, $height = 400)
	{
		$dom = $this->dom;
		$update = $dom->createElement ('update');

		$update->setAttribute ('action', 'popup');

		$data = $dom->createElement ('url');
		$data->appendChild ($dom->createCDATASection ($url));
		$update->appendChild ($data);

		$update->appendChild ($dom->createElement ('width', $width));
		$update->appendChild ($dom->createElement ('height', $height));
		$this->updates[] = $update;
	}

	public function processInput ()
	{
		$this->updateContent ();
	}

	public function throwOkay ($text)
	{
		return '
'.$text.'
';
	}

	public function throwError ($text)
	{
		return '
'.$text.'
';
	}

	/*
		This function generates the links.
	*/
	public function getUrl ($data, $display, $title = null)
	{
		return call_user_func ($this->fGetUrlCallback, $display, $title);
	}

	private function _getUrl ($data, $title)
	{
		$data = str_replace ('"', "'", json_encode ($data));

		if (is_array ($title))
		{
			return $title[0].''.$title[1].''.$title[2];
		}
		elseif (isset ($confirm))
		{
			$confirm = str_replace ("'", "\'", $confirm);
			return ''.$title.'';
		}
		else
		{
			return ''.$title.'';
		}
	}

	private function xmlEntities ($str)
	{
		$xml = array('"','&','&','<','>',' ','¡','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾','¿','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ');
		$html = array('"','&','&','<','>',' ','¡','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾','¿','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ');
		$str = str_replace($html,$xml,$str);
		$str = str_ireplace($html,$xml,$str);
		return $str;
	}

	public function requires ($script)
	{
		$this->requires = $script;
	}
}


<?php
namespace Volantus\FlightBase\Src\General\FlightController;

use Volantus\FlightBase\Src\Server\Messaging\IncomingMessage;
use Volantus\FlightBase\Src\Server\Messaging\MessageFactory;
use Volantus\FlightBase\Src\Server\Messaging\Sender;
use Volantus\FlightBase\Src\Server\Network\NetworkRawMessage;

/**
 * Class PIDTuningMessageFactory
 *
 * @package Volantus\FlightBase\Src\General\FlightController
 */
abstract class PIDTuningMessageFactory extends MessageFactory
{
    /**
     * @param PIDTuningStatus $yawStatus
     * @param PIDTuningStatus $rollStatus
     * @param PIDTuningStatus $pitchStatus
     *
     * @return PIDTuningCollection
     */
    abstract protected function createCollection(PIDTuningStatus $yawStatus, PIDTuningStatus $rollStatus, PIDTuningStatus $pitchStatus): PIDTuningCollection;

    /**
     * @param Sender              $sender
     * @param PIDTuningCollection $pidCollection
     *
     * @return IncomingPIDTuningMessage
     */
    abstract protected function createIncomingMessage(Sender $sender, PIDTuningCollection $pidCollection): IncomingPIDTuningMessage;

    /**
     * @param NetworkRawMessage $rawMessage
     *
     * @return IncomingMessage
     */
    public function create(NetworkRawMessage $rawMessage): IncomingMessage
    {
        $data = $rawMessage->getData();
        $this->validateArray($data, 'yaw');
        $this->validateArray($data, 'roll');
        $this->validateArray($data, 'pitch');

        foreach ($data as $type => $statusData) {
            $this->validateNumeric($data[$type], 'Kp');
            $this->validateNumeric($data[$type], 'Ki');
            $this->validateNumeric($data[$type], 'Kd');
        }

        $statusCollection = $this->createCollection($this->buildStatus($data['yaw']), $this->buildStatus($data['roll']), $this->buildStatus($data['pitch']));
        return $this->createIncomingMessage($rawMessage->getSender(), $statusCollection);
    }

    /**
     * @param array $data
     *
     * @return PIDTuningStatus
     */
    private function buildStatus(array $data): PIDTuningStatus
    {
        return new PIDTuningStatus($data['Kp'], $data['Ki'], $data['Kd']);
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Attribute;

/**
 * AttributeTrait
 *
 * Implementation of AttributeInterface
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @see     AttributeInterface
 * @version 2.0.28
 * @since   2.0.28 added
 */
trait AttributeTrait
{
    use StaticVarTrait; // methods dealing with class static attributes

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

    /**
     * {@inheritDoc}
     */
    public function setAttribute(/*# string */ $attrName, $attrValue)
    {
        $this->attributes[$attrName] = $attrValue;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function addAttribute(/*# string */ $attrName, $attrValue)
    {
        if (!is_array($this->attributes[$attrName])) {
            $this->attributes[$attrName] = (array) $this->attributes[$attrName];
        }
        $this->attributes[$attrName][] = $attrValue;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getAttribute(/*# string */ $attrName)
    {
        if (isset($this->attributes[(string) $attrName])) {
            return $this->attributes[(string) $attrName];
        }
        return null;
    }

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

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


<?php

namespace PhalApi\Crypt;

use PhalApi\Contracts\Crypt;
use PhalApi\Exceptions\InternalServerError;

class Mcrypt implements Crypt
{
    /**
     * @var string $iv 加密向量， 最大长度不得超过 \PhalApi\Crypt\Mcrypt::MAX_IV_SIZE
     */
    protected $iv;

    /**
     * @var int 最大加密向量长度
     */
    const MAX_IV_SIZE = 8;

    /**
     * @var int 最大加密key的长度
     */
    const MAX_KEY_LENGTH = 56;

    /**
     * @param string $iv 加密的向量 最大长度不得超过 MAX_IV_SIZE
     */
    public function __construct($iv = '********')
    {
        $this->iv = str_pad($iv, self::MAX_IV_SIZE, '*');
        if (strlen($this->iv) > self::MAX_IV_SIZE) {
            $this->iv = substr($this->iv, 0, self::MAX_IV_SIZE);
        }
    }

    /**
     * 对称加密
     *
     * @param string $data 待加密的数据
     * @param string $key 私钥
     * @return string 加密后的数据
     */
    public function encrypt($data, $key)
    {
        if ($data === '') {
            return $data;
        }

        $cipher = $this->createCipher($key);

        $encrypted = mcrypt_generic($cipher, $data);

        $this->clearCipher($cipher);

        return $encrypted;
    }

    /**
     * 对称解密
     *
     * @param string $data 待解密的数据
     * @param string $key 私钥
     * @return string 解密后的数据
     * @see \PhalApi\Crypt\Mcrypt::encrypt()
     */
    public function decrypt($data, $key)
    {
        if ($data === '') {
            return $data;
        }

        $cipher = $this->createCipher($key);

        $decrypted = mdecrypt_generic($cipher, $data);

        $this->clearCipher($cipher);

        return rtrim($decrypted, "\0");
    }

    /**
     * 创建cipher
     *
     * @param string $key 私钥
     * @throws InternalServerError
     * @return resource
     */
    protected function createCipher($key)
    {
        $cipher = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');

        if ($cipher === false || $cipher < 0) {
            throw new InternalServerError(
                T('mcrypt_module_open with {cipher}', ['cipher' => $cipher])
            );
        }

        mcrypt_generic_init($cipher, $this->formatKey($key), $this->iv);

        return $cipher;
    }

    /**
     * 格式化私钥
     *
     * @param string $key 私钥
     * @return int
     */
    protected function formatKey($key)
    {
        return strlen($key) > self::MAX_KEY_LENGTH ? substr($key, 0, self::MAX_KEY_LENGTH) : $key;
    }

    /**
     * 释放cipher
     *
     * @param resource $cipher
     */
    protected function clearCipher($cipher)
    {
        mcrypt_generic_deinit($cipher);
        mcrypt_module_close($cipher);
    }
}


<?php

namespace SQRT\QueryBuilder\Query;

use SQRT\QueryBuilder\Query;
use SQRT\QueryBuilder\Conditions;

class Select extends FilteredQuery
{
  /** @var Conditions */
  protected $having;
  protected $join;
  protected $columns;
  protected $groupby;

  /** Создать SQL */
  public function asSQL()
  {
    $q = 'SELECT ' . $this->prepareColumns() . ' FROM ' . $this->prepareTable()
      . $this->prepareJoin()
      . $this->prepareWhere()
      . $this->prepareGroupBy()
      . $this->prepareHaving()
      . $this->prepareOrderBy()
      . $this->prepareLimit();

    return $this->processBindedVarsToSQL($q);
  }

  /** Создать выражение с подстановкой переменных */
  public function asStatement()
  {
    return 'SELECT ' . $this->prepareColumns() . ' FROM ' . $this->prepareTable()
      . $this->prepareJoin()
      . $this->prepareWhere(false)
      . $this->prepareGroupBy()
      . $this->prepareHaving(false)
      . $this->prepareOrderBy()
      . $this->prepareLimit();
  }

  /** Список переменных для подстановки */
  public function getBindedValues()
  {
    $vars = $this->processWhereBindedVars($this->values ? : null);

    if ($this->having) {
      if ($arr = $this->getHaving()->getBindedValues('having')) {
        $vars = $vars ? array_merge($arr, $vars) : $arr;
      }
    }

    return $vars;
  }

  /** @return static */
  public function columns($mixed, $_ = null)
  {
    if (!is_array($mixed)) {
      $mixed = func_get_args();
    }

    $this->columns = $mixed;

    return $this;
  }

  /** @return static */
  public function join($table, $on, $type = null)
  {
    $this->join[$table] = array(
      'table' => $table,
      'on'    => $on,
      'type'  => $type,
    );

    return $this;
  }

  /** @return static */
  public function groupby($mixed, $_ = null)
  {
    if (!is_array($mixed) && !empty($mixed)) {
      $mixed = func_get_args();
    }

    $this->groupby = $mixed;

    return $this;
  }

  /** @return static */
  public function having($mixed)
  {
    if (is_null($mixed)) {
      $this->having = null;
    } else {
      $this->getHaving()->mixed($mixed);
    }

    return $this;
  }

  /** @return Conditions */
  public function getHaving()
  {
    if (is_null($this->having)) {
      $this->having = new Conditions;
    }

    return $this->having;
  }

  protected function prepareColumns()
  {
    return !empty($this->columns) ? Query::QuoteColumns($this->columns) : '*';
  }

  protected function prepareJoin()
  {
    $str = '';
    if (!empty($this->join)) {
      foreach ($this->join as $arr) {
        $str .= (!empty($arr['type']) ? ' ' . strtoupper($arr['type']) : '')
          . ' JOIN ' . self::QuoteTables($arr['table'], $this->getTablePrefix()) . ' ON ' . $arr['on'];
      }
    }

    return $str;
  }

  protected function prepareGroupBy()
  {
    return !empty($this->groupby) ? ' GROUP BY ' . Query::QuoteColumns($this->groupby) : '';
  }

  protected function prepareHaving($as_sql = true)
  {
    $str = '';
    if ($cond = $this->getHaving()) {
      $str = $as_sql ? $cond->asSQL() : $cond->asStatement('having');
    }

    return !empty($str) ? ' HAVING ' . $str : '';
  }
}


<?php

namespace PhalApi\Request\Formatter;

use PhalApi\Contracts\Request\Formatter;
use PhalApi\Exceptions\BadRequest;

class StringFormatter extends BaseFormatter implements Formatter
{
    /**
     * 对字符串进行格式化
     *
     * @param mixed $value 变量值
     * @param array $rule ['len' => '最长长度']
     * @return string 格式化后的变量
     */
    public function parse($value, $rule)
    {
        $rs = strval($this->filterByStrLen(strval($value), $rule));

        $this->filterByRegex($rs, $rule);

        return $rs;
    }

    /**
     * 根据字符串长度进行截取
     *
     * @param mixed $value 变量值
     * @param array $rule 规则
     * @return mixed
     */
    protected function filterByStrLen($value, $rule)
    {
        $lenRule = $rule;
        $lenRule['name'] = $lenRule['name'] . '.len';
        $lenValue = !empty($lenRule['format']) ? mb_strlen($value, $lenRule['format']) : strlen($value);

        $this->filterByRange($lenValue, $lenRule);

        return $value;
    }

    /**
     * 进行正则匹配
     *
     * @param $value
     * @param $rule
     * @throws BadRequest
     */
    protected function filterByRegex($value, $rule)
    {
        if (!isset($rule['regex']) || empty($rule['regex'])) {
            return;
        }

        //如果你看到此行报错，说明提供的正则表达式不合法
        if (preg_match($rule['regex'], $value) <= 0) {
            throw new BadRequest(
                T('{name} can not match {regex}',
                    ['name' => $rule['name'], 'regex' => $rule['regex']])
            );
        }
    }
}


<?php

namespace Makeable\LaravelStripeObjects;

use DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Support\Str;

class StripeObject extends Eloquent
{
    /**
     * @var bool
     */
    public $incrementing = false;

    /**
     * @var null
     */
    public $objectClass = null;

    /**
     * @var string
     */
    public $table = 'stripe_objects';

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

    /**
     * @var array
     */
    protected $casts = [
        'id' => 'string',
        'data' => 'array',
        'meta' => 'array',
    ];

    /**
     * @var array | null
     */
    protected $relatesWith = null;

    /**
     * Add global scope 'type'
     * Attach pre-determined relation on creation.
     */
    public static function boot()
    {
        parent::boot();

        static::addGlobalScope('type', function ($query) {
            return $query->when(static::class !== StripeObject::class, function ($query) {
                $query->where('type', class_basename((new static())->objectClass));
            });
        });

        static::created(function (StripeObject $object) {
            if ($object->relatesWith) {
                list($related, $tag) = $object->relatesWith;
                $object->relations(get_class($related))->attach($related->id, ['tag' => $tag]);
            }
        });
    }

    /**
     * @param \Stripe\StripeObject $object
     *
     * @param null $meta
     * @return StripeObject
     */
    public static function createFromObject(\Stripe\StripeObject $object, $meta = null)
    {
        return (new static())->store($object, $meta);
    }

    /**
     * @param \Stripe\StripeObject $object
     *
     * @param null $meta
     * @return StripeObject
     */
    public function store(\Stripe\StripeObject $object, $meta = null)
    {
        $model = static::firstOrNew(['id' => $object->id]);
        $model->relatesWith = $this->relatesWith;
        $model->fill([
            'type' => class_basename($object),
            'data' => $object->jsonSerialize(),
            'meta' => $meta,
        ]);
        $model->save();

        // Cascade relations
        if ($this->exists && $this->id !== $model->id) {
            DB::table('stripe_object_relations')->where('stripe_object_id', $this->id)->update(['stripe_object_id' => $model->id]);
        }

        return $model;
    }

    /**
     * @return string
     */
    public function getForeignKey()
    {
        return Str::snake(class_basename(self::class)).'_'.$this->primaryKey;
    }

    /**
     * @param $class
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function relations($class)
    {
        return $this->morphedByMany($class, 'related', 'stripe_object_relations')
            ->withPivot(['tag', 'created_at', 'updated_at']);
    }

    /**
     * @param $model
     * @param $tag
     *
     * @return $this
     */
    public function relateWith($model, $tag)
    {
        $this->relatesWith = [$model, $tag];

        return $this;
    }

    /**
     * @return \Stripe\StripeObject
     */
    public function retrieve()
    {
        if (! method_exists($this->objectClass, 'retrieve')) {
            throw new \BadMethodCallException('Cannot retrieve stripe object of type '.$this->objectClass);
        }

        return tap(call_user_func([$this->objectClass, 'retrieve'], $this->id), function (\Stripe\StripeObject $fresh) {
            $this->update(['data' => $fresh->jsonSerialize()]);
        });
    }
}


<?php
/**
 *  Dolumar engine, php/html MMORTS engine
 *  Copyright (C) 2009 Thijs Van der Schaeghe
 *  CatLab Interactive bvba, Gent, Belgium
 *  http://www.catlab.eu/
 *  http://www.dolumar.com/
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/**
* Updates:
*
* Updates are flags that can be set and checked.
* Updates are session based, but are also kept
* in a database. Flags are cancelled right after
* they have been requested, so if you set a flag
* it will stay available until it gets requested.
* (It is available on all sessions and all sessions
* will receive it once.)
*/
class Neuron_GameServer_Player_Updates
{
	private $triggers = array ();

	public function __construct (Neuron_GameServer_Player $profile)
	{
		$this->objProfile = $profile;
	}

	/**
	* This method refreshes the session and makes sure we have
	* the latest data from the database.
	*/
	private function refreshSession ()
	{
		$mapper = Neuron_GameServer_Mappers_UpdateMapper::getInstance ();

		// First check if we have a last id
		if (!isset ($_SESSION['ngpu_lastlog']))
		{
			// New session, can't have updates. No flags set.
			$_SESSION['ngpu_lastlog'] = $mapper->getLastLogId ($this->objProfile);
			$_SESSION['ngpu_data'] = array ();
		}

		else
		{
			$lastLogId = $_SESSION['ngpu_lastlog'];

			// Check for updates
			$updates = $mapper->getUpdates ($this->objProfile, $lastLogId);

			// Process these updates
			foreach ($updates as $v)
			{
				$_SESSION['ngpu_data'][$v['key']] = $v['value'];
				$lastLogId = max ($v['id'], $lastLogId);
			}

			$_SESSION['ngpu_lastlog'] = $lastLogId;
		}
	}

	public function setFlag ($flagname, $value = 1)
	{
		$mapper = Neuron_GameServer_Mappers_UpdateMapper::getInstance ();
		$mapper->addUpdate ($this->objProfile, $flagname, $value);

		$this->refreshSession ();
	}

	public function getFlag ($flagname)
	{
		// Reload the session
		$this->refreshSession ();

		if (isset ($_SESSION['ngpu_data'][$flagname]))
		{
			$output = $_SESSION['ngpu_data'][$flagname];
			unset ($_SESSION['ngpu_data'][$flagname]);
			return $output;
		}

		return null;
	}

	public function __destruct ()
	{
		unset ($this->objProfile);
	}
}


<?php
namespace Cora;

class Paginate
{
    protected $url;
    protected $totalQuantity;
    protected $itemsPerPage;
    protected $offset;
    protected $filters;

    public function __construct($load, $url, $filtersArray, $totalQuantity, $currentOffset = 0, $itemsPerPage = 18)
    {
        $this->load             = $load;
        $this->url              = $url;
        $this->filtersArray     = $filtersArray;
        $this->totalQuantity    = $totalQuantity;
        $this->offset           = $currentOffset;
        $this->itemsPerPage     = $itemsPerPage

        // Setup Descriptions for the filters.
        $this->filters = [
           'letterFilter' => 'Only showing %s that start with "%s"',
           'query' => 'Only showing %s that contain "%s"'
        ];
    }

    public function showNext($offset = false)
    {
        // Check if a specific offset was passed in, otherwise use data member.
        if ($offset === false) {
            $offset = $this->offset;
        }

        // Note: Offsets start with ZERO!
        // The Offset being 0 means this evaluates to 0+1, which means you are on the first page.
        $currentPageNumber = $offset+1;

        if ($this->totalQuantity > $currentPageNumber * $this->itemsPerPage) {
            return true;
        }
        return false;
    }

    public function showPrevious($offset = false)
    {
        // Check if a specific offset was passed in, otherwise use data member.
        if ($offset === false) {
            $offset = $this->offset;
        }

        if ($offset > 0) {
            return true;
        }
        return false;
    }

    public function getNumPages()
    {
        $result = 0;

        if ($this->totalQuantity > 0) {
            $result = ceil($this->totalQuantity / $this->itemsPerPage);
        }
        return $result;
    }

    public function showOffset($offset)
    {
        if ($offset >= 0 && $this->totalQuantity > $offset * $this->itemsPerPage) {
            return true;
        }
        return false;
    }

    public function showRelOffset($num = 0)
    {
        return $this->showOffset($this->offset + $num);
    }

    public function getOffset($num = 0)
    {
        return ($this->offset + $num);
    }

    public function getCalcLink($exclude = false)
    {
        // Turn Exclude into an array
        if ($exclude == false) {
            $exclude = array();
        }
        else if (!is_array($exclude)) {
            $exclude = array($exclude);
        }

        // Setup
        $url = $this->url;
        $filters = count($this->filtersArray);
        $i = 1;

        $url .= '?';
        if ($filters > 0) {
            foreach ($this->filtersArray as $key => $value) {
                if (!in_array($key, $exclude)) {
                    $url .= $key.'='.$value;
                    if ($i != $filters) {
                        $url .= '&';
                    }
                }
                $i++;
            }
        }
        return $url;
    }

    public function getLink($offset)
    {
        return $this->getCalcLink().'&offset='.$offset;
    }

    public function getBaseLink()
    {
        return $this->url;
    }

    public function getFilterLink($value, $filterName = 'letterFilter')
    {
        return $this->getCalcLink(['letterFilter']).'&'.$filterName.'='.$value;
    }

    public function getRelLink($num)
    {
        //return $this->url.'?offset='.($this->offset+$num);
        return $this->getCalcLink().'&offset='.($this->offset+$num);
    }

    public function getSortLink($orderBy)
    {
        if ($orderBy == $this->filtersArray['orderBy']) {
            if ($this->filtersArray['orderDir'] == 'asc') {
                $orderDir = 'desc';
            }
            else {
                $orderDir = 'asc';
            }
        }
        else {
            $orderDir = 'asc';
        }
        return $this->getCalcLink(['orderBy', 'orderDir']).'&orderBy='.$orderBy.'&orderDir='.$orderDir;
    }

    public function getCalcInputs($exclude = false)
    {
        // Turn Exclude into an array
        if ($exclude == false) {
            $exclude = array();
        }
        else if (!is_array($exclude)) {
            $exclude = array($exclude);
        }

        // Setup
        $items = '';
        $filters = count($this->filtersArray);

        if ($filters > 0) {
            foreach ($this->filtersArray as $key => $value) {
                if (!in_array($key, $exclude)) {
                    $items .= '<input name="'.$key.'" type="hidden" value="'.$value.'">';
                }
            }
        }
        return $items;
    }

    public function display($bool, $displayIfTrue = '', $displayIfFalse = 'hide')
	{
		if(!$bool) {
			return $displayIfFalse;
		}
		else
			return $displayIfTrue;
	}

    public function active($bool)
	{
		if(!$bool) {
			return 'disabled';
		}
		else
			return '';
	}

    /**
     *  Returns an array with messages to inform the end-user what filters they have active.
     *  Will look in the Filters array for letterFilters or search queries that are limiting the result set.
     *  In order to return a user-friendly description of what filters are active, it requires an array of column
     *  descriptions. See example below.
     *
     *  $columnDescriptions = ['practices.name' => 'practices'];
     *  $this->filtersArray = ['query' => 'Happy'];
     *  $this->filters = ['query' => 'Showing %s that contain "%s"'];
     *  RETURNED RESULT: ['Showing practices that contain "Happy"']
     */
     public function getFilters($columnDescriptions = [], $activeFieldName = false)
     {
         $filters = [];

         if (count($this->filtersArray) > 0) {
             foreach ($this->filtersArray as $key => $value) {
                 if (isset($this->filters[$key])) {

                     // Filters are active on the active data column
                     $activeFieldName = $activeFieldName?: $this->filtersArray['orderBy'];

                     // There may optionally be passed in a more human friendly name for the active field.
                     $friendlyFieldName = isset($columnDescriptions[$activeFieldName]) ? $columnDescriptions[$activeFieldName] : $activeFieldName;

                     $filters[] = sprintf($this->filters[$key], $friendlyFieldName, $value);
                     //$filters[] = call_user_func_array("sprintf", [$this->filters[$key], ]);
                 }
             }
         }
         return $filters;
     }

    public function view($url = '_partials/paginate')
    {
        $data = array();
        $data['paginate'] = $this;
        return $this->load->view($url, $data, true);
    }
}


<?php
/**
 * Copyright (c) 2018 Wakers.cz
 *
 * @author Jiří Zapletal (http://www.wakers.cz, zapletal@wakers.cz)
 *
 */

namespace Wakers\StructureModule\Component\Frontend\StructureRemoveModal;

use Wakers\BaseModule\Component\Frontend\BaseControl;
use Wakers\StructureModule\Database\Structure;
use Wakers\StructureModule\Manager\StructureManager;
use Wakers\StructureModule\Repository\StructureRepository;
use Wakers\StructureModule\Security\StructureAuthorizator;

class StructureRemoveModal extends BaseControl
{
    /**
     * @var StructureRepository
     */
    protected $structureRepository;

    /**
     * @var StructureManager
     */
    protected $structureManager;

    /**
     * Entita načtena při otevření modálního okna
     * @var Structure
     */
    protected $structureEntity;

    /**
     * @var callable
     */
    public $onRemove = [];

    /**
     * @var callable
     */
    public $onOpen = [];

    /**
     * StructureRemoveModal constructor.
     * @param StructureRepository $structureRepository
     * @param StructureManager $structureManager
     */
    public function __construct(
        StructureRepository $structureRepository,
        StructureManager $structureManager
    ) {
        $this->structureRepository = $structureRepository;
        $this->structureManager = $structureManager;
    }

    /**
     * Render
     */
    public function render() : void
    {
        $this->template->structure = $this->structureEntity;
        $this->template->setFile(__DIR__.'/templates/structureRemoveModal.latte');
        $this->template->render();
    }

    /**
     * Handler pro otevření modálního okna
     * @param int $id
     */
    public function handleOpen(int $id) : void
    {
        if ($this->presenter->isAjax())
        {
            $this->structureEntity = $this->structureRepository->findOneByIdWithRecipe($id);

            if ($this->structureEntity)
            {
                $this->presenter->handleModalToggle('show', '#wakers_structure_structure_remove_modal', FALSE);
                $this->onOpen();
            }
            else
            {
                $this->presenter->notificationAjax(
                    'Položka odstraněna',
                    "Položka s id '{$id}' již byla odstraněna.",
                    'error',
                    TRUE
                );
            }
        }
    }

    /**
     * Handler pro odstranění
     * @param int $id
     * @throws \Exception
     */
    public function handleRemove(int $id) : void
    {
        if ($this->presenter->isAjax() && $this->presenter->user->isAllowed(StructureAuthorizator::RES_STRUCTURE_REMOVE_MODAL))
        {
            $this->structureEntity = $this->structureRepository->findOneByIdWithRecipe($id);

            $this->structureManager->delete($this->structureEntity);

            $this->presenter->notificationAjax(
                "{$this->structureEntity->getRecipeSlug()->getRecipe()->getName()} odstraněn/a.",
                "Položka '{$this->structureEntity->getRecipeSlug()->getRecipe()->getName()}' s id '{$this->structureEntity->getId()}' byla úspěšně odstraněna.",
                'success',
                FALSE
            );

            $this->presenter->handleModalToggle('hide', '#wakers_structure_structure_remove_modal', FALSE);

            $this->onRemove();
        }
    }
}


<?php
/**
 * Copyright (c) 2018 Wakers.cz
 *
 * @author Jiří Zapletal (http://www.wakers.cz, zapletal@wakers.cz)
 *
 */

namespace Wakers\StructureModule\Component\Frontend\VariableRemoveModal;

trait Create
{
    /**
     * @var IVariableRemoveModal
     * @inject
     */
    public $IStructure_VariableRemoveModal;

    /**
     * Modální okno pro odstranění
     * @return VariableRemoveModal
     */
    protected function createComponentStructureVariableRemoveModal() : object
    {
        $control = $this->IStructure_VariableRemoveModal->create();

        $control->onRemove[] = function ()
        {
            $this->getComponent('structureVariableSummaryModal')->redrawControl('modal');
            $this->getComponent('structureRecipeSummaryModal')->redrawControl('modal');
        };

        $control->onOpen[] = function () use ($control)
        {
            $control->redrawControl('modal');
        };

        return $control;
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Debug;

use Psr\Log\LoggerInterface;

/**
 * DebuggableTrait
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @see     DebuggableInterface
 * @version 2.0.26
 * @since   2.0.26 added
 */
trait DebuggableTrait
{
    /**
     * @var    bool
     * @access protected
     */
    protected $debug_mode = false;

    /**
     * @var    LoggerInterface
     * @access protected
     */
    protected $debug_logger;

    /**
     * {@inheritDoc}
     */
    public function enableDebug(/*# bool */ $flag = true)
    {
        $this->debug_mode = (bool) $flag;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function setDebugger(LoggerInterface $logger)
    {
        $this->debug_logger = $logger;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function delegateDebugger($object)
    {
        if ($this->isDebugging() &&
            $object instanceof DebuggableInterface
        ) {
            $object->enableDebug(true)->setDebugger($this->debug_logger);
        }
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function isDebugging()/*# : bool */
    {
        return (bool) ($this->debug_mode && $this->debug_logger);
    }

    /**
     * {@inheritDoc}
     */
    public function debug(/*# string */ $message)
    {
        if ($this->isDebugging()) {
            $this->debug_logger->debug(
                $message,
                ['className' => get_class($this)]
            );
        }
        return $this;
    }
}


<?php
/**
 * Just Framework - It's a PHP micro-framework for Full Stack Web Developer
 *
 * @package     Just Framework
 * @copyright   2016 (c) Mahmoud Elnezamy
 * @author      Mahmoud Elnezamy <http://nezamy.com>
 * @link        http://justframework.com
 * @license     http://www.opensource.org/licenses/mit-license.php MIT
 * @version     1.0.0
 */
namespace System\Support;
/**
 * Str
 *
 * @package     Just Framework
 * @author      Mahmoud Elnezamy <http://nezamy.com>
 * @since       1.0.0
 */

class Str
{
	/**
     * Convert string camelCase to array.
     *
     * @param string 	$str
     *
     * @return mixed
     */
	public static function camelCase($str) {
		return preg_split('/(?<=\\w)(?=[A-Z])/', $str);
	}

    public static function replace_last($search, $replace, $subject)
    {
        $pos = strrpos($subject, $search);

        if($pos !== false)
        {
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
        }

        return $subject;
    }

	/**
     * Encrypt using mcrypt
     *
     * @param   mixed   $data   the data to encrypt, supports any type "it will be serialized"
     * @param   string  $key    the secrt key
     * @param   string  $cipher the cipher
     * @param   string  $mode   the mode
     * @return  string
     */
    public static function encrypt($data, $key, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC)
    {
        $data       =   serialize($data);
        $key        =   hash('sha256', $key, true);
        $iv_size    =   mcrypt_get_iv_size($cipher, $mode);
        $iv         =   mcrypt_create_iv($iv_size, MCRYPT_RAND);

        return  base64_encode(serialize(array($iv, mcrypt_encrypt($cipher, $key, $data, $mode, $iv))));
    }

    /**
     * Decrypt using mcrypt
     *
     * @param   mixed   $data   the data to be decrypted
     * @param   string  $key    the secret key
     * @param   string  $cipher the cipher key
     * @param   string  $mode   the mode
     * @return  string
     */
    public static function decrypt($data, $key, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC)
    {
        $key    =   hash('sha256', $key, true);

        @ list($iv, $encrypted) = (array) unserialize(base64_decode($data));

        return unserialize(trim(mcrypt_decrypt($cipher, $key, $encrypted, $mode, $iv)));
    }

    /**
     * Hash string using crypt function
     *
     * @uses    crypt()
     * @param   string  $string     string to hash
     * @param   string  $algorithm  [blowfish, md5, sha256, sha512]
     * @return  string
     */
    public static function hash($string, $algorithm = 'blowfish')
    {
        switch( strtolower($algorithm) ):
            case('md5'):
                $salt = '$1$'.(static::rand(12)).'$';
                break;
            case('sha256'):
                $salt = '$5$rounds=5000$'.(static::rand(16)).'$';
                break;
            case('sha512'):
                $salt = '$6$rounds=5000$'.(static::rand(16)).'$';
                break;
            case('blowfish'):
            default:
                $salt = '$2a$09$'.(static::rand(22)).'$';
                break;
        endswitch;

        return base64_encode(crypt($string, $salt));
    }

    /**
     * Checks whether a crypted hash is valid
     *
     * @uses    crypt()
     * @param   string $real    the real string
     * @param   string $hash    the hashed string
     * @return  bool
     */
    public static function verify($real, $hash)
    {
        $hash   =   base64_decode($hash);
        return      crypt($real, $hash) == $hash;
    }

    /**
     * Generate a random string with a certain length
     *
     * @param   integer $length
     * @param   bool    $special
     * @return  string
     */
	public static function rand($length = 10, $special = false)
	{
	    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$special && ($characters .= '!@#$%^&*()+=>:;*-~`{}[],');
	    $charactersLength = strlen($characters);
	    $randomString = '';
	    for ($i = 0; $i < $length; $i++) {
	        $randomString .= $characters[rand(0, $charactersLength - 1)];
	    }
	    return $randomString;
	}

	/**
     * Hash string using password_hash function.
     *
     * @param string 	$pass
     *
     * @return string
     */
    public static function password($pass)
    {
        return password_hash($pass, PASSWORD_BCRYPT, ['cost' => 12]);
    }

	/**
     * Checks whether a password hash is valid.
     *
     * @param string 	$pass
     *
     * @return string
     */
    public static function password_verify($pass, $hash)
    {
        return password_verify($pass, $hash);
    }

}


<?php

namespace SQRT\QueryBuilder\Query;

class Delete extends FilteredQuery
{
  /** Создать SQL */
  public function asSQL()
  {
    $q = 'DELETE FROM ' . $this->prepareTable()
      . $this->prepareWhere()
      . $this->prepareOrderBy()
      . $this->prepareLimit();

    return $this->processBindedVarsToSQL($q);
  }

  /** Создать выражение с подстановкой переменных */
  public function asStatement()
  {
    return 'DELETE FROM ' . $this->prepareTable()
    . $this->prepareWhere(false)
    . $this->prepareOrderBy()
    . $this->prepareLimit();
  }

  /** Список переменных для подстановки */
  public function getBindedValues()
  {
    return $this->processWhereBindedVars($this->values ? : null);
  }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Seed;

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use Roquie\Database\Notify\NotifyFactory;
use Roquie\Database\Notify\NotifyInterface;
use Roquie\Database\Migration\Whois;
use Roquie\Database\Seed\Creator\SeedCreator;

final class Creator
{
    /**
     * @var FilesystemInterface
     */
    private $filesystem;

    /**
     * @var NotifyInterface
     */
    private $notify;

    /**
     * @var SeedCreator
     */
    private $creator;

    /**
     * Creator constructor.
     *
     * @param FilesystemInterface|null $filesystem
     * @param NotifyInterface|string $notify
     */
    public function __construct(FilesystemInterface $filesystem, $notify = NotifyInterface::LOGGER)
    {
        $this->filesystem = $filesystem;
        $this->notify = NotifyFactory::create($notify);
        $this->creator = new SeedCreator($this->notify);
    }

    /**
     * @param null|string $source
     * @param \Roquie\Database\Notify\NotifyInterface|string|null $notify
     * @return \Roquie\Database\Seed\Creator
     */
    public static function new(?string $source = Seed::DEFAULT_PATH, $notify = NotifyInterface::LOGGER)
    {
        $seed = new static(new Filesystem(new Local($source)), $notify);

        return $seed;
    }

    /**
     * Create seed class from stub.
     *
     * @param string|null $name
     * @throws \League\Flysystem\FileNotFoundException
     */
    public function create(?string $name = null)
    {
        Whois::print($this->getNotify());

        $this->creator->create($this->filesystem, $name);
    }

    /**
     * @return FilesystemInterface
     */
    public function getFilesystem(): FilesystemInterface
    {
        return $this->filesystem;
    }

    /**
     * @return SeedCreator
     */
    public function getCreator(): SeedCreator
    {
        return $this->creator;
    }

    /**
     * @return NotifyInterface
     */
    public function getNotify(): NotifyInterface
    {
        return $this->notify;
    }
}


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class SmtpAuthOptional extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('smtp_config', function(Blueprint $t){
            $t->text('username')->nullable()->default(null)->change();
            $t->text('password')->nullable()->default(null)->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('smtp_config', function(Blueprint $t){
            $t->text('username')->change();
            $t->text('password')->change();
        });
    }
}


<?php

/*
 * This file is part of the Worker package.
 *
 * (c) EXSyst
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace EXSyst\Component\Worker\Status;

use EXSyst\Component\Worker\Exception;

class WorkerStatus
{
    /**
     * @var string|null
     */
    private $textStatus;
    /**
     * @var array
     */
    private $counters;

    /**
     * @param string|null $textStatus
     * @param array       $counters
     */
    public function __construct($textStatus = null, array $counters = [])
    {
        foreach ($counters as $counter) {
            if (!($counter instanceof WorkerCounter)) {
                throw new Exception\InvalidArgumentException('All the counters must be instances of the WorkerCounter class.');
            }
        }
        $this->textStatus = ($textStatus === null) ? null : strval($textStatus);
        $this->counters = $counters;
    }

    /**
     * @return string|null
     */
    public function getTextStatus()
    {
        return $this->textStatus;
    }

    /**
     * @return array
     */
    public function getCounters()
    {
        return $this->counters;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return [
            'textStatus' => $this->textStatus,
            'counters'   => array_map(function (WorkerCounter $counter) {
                return $counter->toArray();
            }),
        ];
    }

    /**
     * @param array|object $arrayOrObject
     *
     * @return static
     */
    public static function fromArrayOrObject($arrayOrObject)
    {
        if (is_array($arrayOrObject)) {
            return new static(
                isset($arrayOrObject['textStatus']) ? $arrayOrObject['textStatus'] : null,
                isset($arrayOrObject['counters']) ? array_map(function ($counter) {
                    return WorkerCounter::fromArrayOrObject($counter);
                }, $arrayOrObject['counters']) : []);
        } elseif (is_object($arrayOrObject)) {
            return new static(
                isset($arrayOrObject->textStatus) ? $arrayOrObject->textStatus : null,
                isset($arrayOrObject->counters) ? array_map(function ($counter) {
                    return WorkerCounter::fromArrayOrObject($counter);
                }, $arrayOrObject->counters) : []);
        }
    }
}


<?php

namespace PhalApi\Crypt;

use PhalApi\Contracts\Crypt;

class MultiMcrypt implements Crypt
{
    /**
     * @var \PhalApi\Crypt\Mcrypt $mcrypt
     */
    protected $mcrypt;

    public function __construct($iv)
    {
        $this->mcrypt = new Mcrypt($iv);
    }

    /**
     * 加密
     *
     * @param mixed $data 待加密的数据
     * @param $key
     * @return string
     */
    public function encrypt($data, $key)
    {
        $encryptData = serialize($data);

        $encryptData = $this->mcrypt->encrypt($encryptData, $key);

        $encryptData = base64_encode($encryptData);

        return $encryptData;
    }

    /**
     * 解密
     * 忽略不能正常反序列化的操作，并且在不能预期解密的情况下返回原文
     *
     * @param mixed $data 待解密的数据
     * @param $key
     * @return mixed
     */
    public function decrypt($data, $key)
    {
        $decryptData = base64_decode($data);

        if ($decryptData === false || $decryptData === '') {
            return $data;
        }

        $decryptData = $this->mcrypt->decrypt($decryptData, $key);

        $decryptData = @unserialize($decryptData);
        if ($decryptData === false) {
            return $data;
        }

        return $decryptData;
    }
}


<?php
/**
 *  Dolumar engine, php/html MMORTS engine
 *  Copyright (C) 2009 Thijs Van der Schaeghe
 *  CatLab Interactive bvba, Gent, Belgium
 *  http://www.catlab.eu/
 *  http://www.dolumar.com/
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

class Neuron_GameServer_Pages_Admin_Page extends Neuron_GameServer_Pages_Page
{
	public function __construct ()
	{
		Neuron_URLBuilder::getInstance ()->setOpenCallback (array ($this, '_getUrlCallback'));
		Neuron_URLBuilder::getInstance ()->setUpdateCallback (array ($this, '_getUrlCallback'));
	}

	public function _getUrlCallback ($module, $display, $data)
	{
		$module = strtolower ($module);
		return 'getUrl ($module, $data).'">'.$display.'';
	}

	/*
		Return the body, without page specific content
	*/
	public function getHTML ()
	{
		$page = new Neuron_Core_Template ();
		$page->set ('body', $this->getOuterBody ());
		$page->set ('stylesheet', 'admin');

		$page->set ('static_client_url', BASE_URL . 'gameserver/');

		return $page->parse ('pages/index.phpt');
	}

	public function getOuterBody ()
	{
		$page = new Neuron_Core_Template ();
		$page->set ('body', $this->getBody ());

		$page->set ('messages', $this->getUrl ('messages'));
		$page->set ('onlineurl', ABSOLUTE_URL.'test/online/');
		$page->set ('searchplayers', $this->getUrl ('searchplayers'));

		// Add navigations
		$player = Neuron_GameServer::getPlayer ();

		if ($player->isModerator ())
		{
			$page->set ('multiaccounts', $this->getUrl ('multis'));
		}

		if ($player->isAdmin ())
		{
			$page->set ('execute', $this->getUrl ('execute'));
		}

		if ($player->isDeveloper ())
		{
			$page->set ('bonusbuilding', $this->getUrl ('bonusbuilding'));
		}

		$page->set ('isModerator', $player->isModerator ());
		$page->set ('isAdmin', $player->isAdmin ());
		$page->set ('isDeveloper', $player->isDeveloper ());

		return $page->parse ('pages/admin/page.phpt');
	}

	public static function getUrl ($sUrl, $sArrs = null, $sBase = 'admin/')
	{
		return parent::getUrl ($sUrl, $sArrs, $sBase);
	}

	public function getBody ()
	{
		$myself = Neuron_GameServer::getPlayer ();
		return '
Welcome, '.$myself->getName ().'.
';
	}

	public function addModeratorAction ($sAction, $mParams, $reason, Neuron_GameServer_Player $player, $isDone = false)
	{
		$db = Neuron_DB_Database::getInstance ();

		$login = Neuron_Core_Login::getInstance ();
		$userid = intval ($login->getUserId ());

		$isDone = $isDone ? true : false;

		$processed = $isDone ? 1 : 0;
		$executed = $isDone ? 1 : 0;

		$db->query
		("
			INSERT INTO
				n_mod_actions
			SET
				ma_action = '".$db->escape ($sAction)."',
				ma_data = '".$db->escape (json_encode ($mParams))."',
				ma_plid = $userid,
				ma_date = NOW(),
				ma_reason = '".$db->escape ($reason)."',
				ma_target = '{$player->getId ()}',
				ma_processed = {$processed},
				ma_executed = {$executed}
		");
	}
}
?>


<?php

/**
 * ExtDirect\Cache\ExtCache
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to version 3 of the GPL license,
 * that is bundled with this package in the file LICENSE, and is
 * available online at http://www.gnu.org/licenses/gpl.txt
 *
 * PHP version 5
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

namespace ExtDirect\Cache;

use ExtDirect\Exceptions\ExtDirectException;
use ExtDirect\Annotations\Collections\DirectCollection;
use ExtDirect\Utils\Keys;

/**
 * class ExtCache
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

class ExtCache
{
    /**
     * @var string
     */
    protected $key;

    /**
     * constructor
     *
     * @param string $key the cache key
     */
    public function __construct($key)
    {
        $this->key = $key;
    }

    /**
     * Returns ext api as array
     *
     * @return array|bool
     */
    public function getApi()
    {
        $api = $this->get(Keys::EXT_API);
        if (is_array($api)) {
            return $api;
        }
        return false;
    }

    /**
     * Checks if api is cached
     *
     * @return bool
     */
    public function isApiCached()
    {
        // if action array is cached return true
        if ($this->get(Keys::EXT_API)) {
            return true;
        }
        return false;
    }

    /**
     * Returns cache key
     *
     * @return string
     */
    protected function getKey()
    {
        return $this->key;
    }

    /**
     * Checks if actions are cached
     *
     * @return bool
     */
    public function isCached()
    {
        // if action array is cached return true
        if ($this->get(Keys::EXT_ACTION)) {
            return true;
        }
        return false;
    }

    /**
     * Returns a part of cached array
     *
     * @param string $key cache category (action, namespace...)
     *
     * @return bool
     */
    protected function get($key)
    {
        $cache = apc_fetch($this->getKey());
        if (!is_array($cache)) {
            return false;
        } else {
            if (isset($cache[$key])) {
                return $cache[$key];
            }
            return false;
        }
    }

    /**
     * persists given value in cache
     *
     * @param string $key   the cache category (array key)
     * @param mixed  $value the value to be cached
     *
     * @return void
     */
    protected function set($key, $value)
    {
        $cache = apc_fetch($this->getKey());

        $cache[$key] = $value;

        apc_store($this->getKey(), $cache);
    }

    /**
     * Returns array containing cached list of classes and actions which are remote able
     *
     * @return array
     */
    public function getActions()
    {
        $result = $this->get(Keys::EXT_ACTION);
        if (is_string($result)) {
            return unserialize($result);
        }
        return array();
    }

    /**
     * persists list of actions in cache
     *
     * @param DirectCollection $collection the actions which should be cached
     *
     * @return void
     */
    public function cacheActions(DirectCollection $collection)
    {
        $serializedCollection = serialize($collection);

        $this->set(Keys::EXT_ACTION, $serializedCollection);
    }

    /**
     * caches generated ext api
     *
     * @param array $api the api as array
     *
     * @return void
     */
    public function cacheApi(array $api)
    {
        $this->set(Keys::EXT_API, $api);
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Console;

use Roquie\Database\Migration\Whois;
use Roquie\Database\Notify\NotifyConsole;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class BinMakeCommand extends Command
{

    protected function configure()
    {
        $this
            ->setName('bin:make')
            ->setDescription('Create custom rdb binary file')
            ->setHelp('Example of usage: rdb bin:make');

        $this
            ->addArgument('name', InputArgument::OPTIONAL, 'The name of the binary', 'rdb');
//            ->addOption('path', null, InputOption::VALUE_OPTIONAL, 'The path to the create binary file', './');
    }

    /**
     * Execute command, captain.
     *
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        Whois::print(new NotifyConsole($output));

        $stub = file_get_contents(__DIR__ . '/stubs/bin.stub');

        if (file_exists($input->getArgument('name'))) {
            $output->writeln('');
            $output->writeln('<info>File exists</info>');
        }

        file_put_contents($input->getArgument('name'), $stub, LOCK_EX);
        chmod($input->getArgument('name'), 0750);

        $output->writeln('');
        $output->writeln('<info>Binary file created</info>');
    }
}


<?php
/**
 * Copyright (c) 2018 Wakers.cz
 *
 * @author Jiří Zapletal (http://www.wakers.cz, zapletal@wakers.cz)
 *
 */

namespace Wakers\StructureModule\Component\Frontend\VariableRemoveModal;

use Wakers\BaseModule\Component\Frontend\BaseControl;
use Wakers\StructureModule\Database\RecipeVariable;
use Wakers\StructureModule\Manager\RecipeVariableManager;
use Wakers\StructureModule\Repository\RecipeVariableRepository;
use Wakers\StructureModule\Security\StructureAuthorizator;

class VariableRemoveModal extends BaseControl
{
    /**
     * @var RecipeVariableRepository
     */
    protected $variableRepository;

    /**
     * @var RecipeVariableManager
     */
    protected $variableManager;

    /**
     * Entita načtena při otevření modálního okna
     * @var RecipeVariable
     */
    protected $variableEntity;

    /**
     * @var callable
     */
    public $onRemove = [];

    /**
     * @var callable
     */
    public $onOpen = [];

    /**
     * RecipeRemoveModal constructor.
     * @param RecipeVariableRepository $variableRepository
     * @param RecipeVariableManager $recipeVariableManager
     */
    public function __construct(RecipeVariableRepository $variableRepository, RecipeVariableManager $recipeVariableManager)
    {
        $this->variableRepository = $variableRepository;
        $this->variableManager = $recipeVariableManager;
    }

    /**
     * Render
     */
    public function render() : void
    {
        $this->template->variable = $this->variableEntity;
        $this->template->setFile(__DIR__.'/templates/variableRemoveModal.latte');
        $this->template->render();
    }

    /**
     * Handler pro otevření modálního okna
     * @param int $id
     */
    public function handleOpen(int $id) : void
    {
        if ($this->presenter->isAjax())
        {
            $this->variableEntity = $this->variableRepository->findOneById($id);

            $this->presenter->handleModalToggle('show', '#wakers_structure_variable_remove_modal', FALSE);
            $this->onOpen();
        }
    }

    /**
     * Handler pro odstranění
     * @param int $id
     * @throws \Exception
     */
    public function handleRemove(int $id) : void
    {
        if ($this->presenter->isAjax() && $this->presenter->user->isAllowed(StructureAuthorizator::RES_VARIABLE_REMOVE_MODAL))
        {
            $this->variableEntity = $this->variableRepository->findOneById($id);

            $this->variableManager->delete($this->variableEntity);

            $this->presenter->notificationAjax(
                'Proměnná odstraněna.',
                "Proměnná '{$this->variableEntity->getLabel()} byla úspěšně odstraněna.'",
                'success',
                FALSE
            );

            $this->presenter->handleModalToggle('hide', '#wakers_structure_variable_remove_modal', FALSE);

            $this->onRemove();
        }
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Reader;

/**
 * Read & parse json formatted file and return the result
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @version 2.0.1
 * @since   2.0.1 added
 */
class JsonReader extends ReaderAbstract
{
    /**
     * default json error
     *
     * @var    array
     * @access protected
     * @staticvar
     */
    protected static $error = [
        \JSON_ERROR_NONE => 'No error',
        \JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
        \JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
        \JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
        \JSON_ERROR_SYNTAX => 'Syntax error',
        \JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
    ];

    /**
     * {@inheritDoc}
     */
    protected static function readFromFile($path)
    {
        return @json_decode(file_get_contents($path), true);
    }

    /**
     * {@inheritDoc}
     */
    protected static function getError(/*# string */ $path)/*#: string */
    {
        if (function_exists('json_last_error_msg')) {
            return json_last_error_msg();
        } else {
            $error = json_last_error();
            return isset(static::$error[$error]) ?
                static::$error[$error] : 'JSON parse error';
        }
    }
}


<?php
/**
 *  Dolumar engine, php/html MMORTS engine
 *  Copyright (C) 2009 Thijs Van der Schaeghe
 *  CatLab Interactive bvba, Gent, Belgium
 *  http://www.catlab.eu/
 *  http://www.dolumar.com/
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

class Neuron_GameServer_Mappers_CachedChatMapper
	extends Neuron_GameServer_Mappers_ChatMapper
{
	private $objCache;
	private $sPrefix;

	/**
	* We need one instance per player.
	*/
	public static function getInstance ()
	{
		static $in;
		if (!isset ($in))
		{
			$in = new self ();
		}
		return $in;
	}

	/**
	* C-c-c-construct!
	*/
	protected function __construct ()
	{
		$this->objCache = Neuron_Core_Memcache::getInstance ();
		$this->sPrefix = DB_DATABASE.'_chat_';
	}

	public function getChannelID ($channel)
	{
		// Can be cached, but too lazy for now.
		return parent::getChannelID ($channel);
	}

	/**
	* Return the latest messages since $since.
	* $since should be the last received message ID.
	*/
	public function getMessages ($channelId, $limit = 20, $since = null, $before = null)
	{
		$profiler = Neuron_Profiler_Profiler::getInstance ();

		if (isset ($since))
		{
			// Here we do some magic to check if the last id has changed
			$cName = $this->sPrefix . 'lastmessage_' . $channelId;

			$profiler->message ('Checking ' . $cName . ' against ' . $since);

			if (
				$this->objCache->hasCache ($cName)
				&& $this->objCache->getCache ($cName) <= $since
			) {
				$profiler->message ('Not checking for new messages');
				return array ();
			}
		}

		$profiler->message ('Checking for new messages');
		return parent::getMessages ($channelId, $limit, $since, $before);
	}

	public function sendMessage ($channelId, $message, Neuron_GameServer_Player $player)
	{
		$profiler = Neuron_Profiler_Profiler::getInstance ();

		// Here we *must* update the last channelId message
		$id = parent::sendMessage ($channelId, $message, $player);

		$cName = $this->sPrefix . 'lastmessage_' . $channelId;

		$profiler->message ('Setting ' . $cName . ' to ' . $id);

		//echo 'setting ' . $cName . ' to ' . $id;
		$this->objCache->setCache ($cName, $id);

		return $id;
	}

	/**
	*CREATE TABLE  `n_privatechat_updates` (
	*`pu_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
	*`pu_from` INT NOT NULL ,
	*`pu_to` INT NOT NULL ,
	*`pu_date` DATETIME NOT NULL
	*) ENGINE = INNODB
	*/
	public function addPrivateChatUpdate ($msgid, Neuron_GameServer_Player $from, Neuron_GameServer_Player $target)
	{
		$id = parent::addPrivateChatUpdate ($msgid, $from, $target);
		return $id;
	}

	/**
	* If $since is said, return all events since "since".
	* If $since is not said, return the single latest event.
	*
	* ($since is obviously the pu_id)
	*/
	public function getPrivateChatUpdates (Neuron_GameServer_Player $target, $since = null)
	{
		if (isset ($since))
		{

		}

		return parent::getPrivateChatUpdates ($target, $since);
	}
}


<?php

/**
 * ExtDirect\AbstractExtDirect
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to version 3 of the GPL license,
 * that is bundled with this package in the file LICENSE, and is
 * available online at http://www.gnu.org/licenses/gpl.txt
 *
 * PHP version 5
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

namespace ExtDirect;

use ExtDirect\Cache\ExtCache;
use ExtDirect\Request\Parameters;
use ExtDirect\Annotations\Parser;
use ExtDirect\Utils\Keys;

/**
 * class AbstractExtDirect
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

abstract class AbstractExtDirect
{
    /**
     * @var string
     */
    protected $applicationNameSpace;

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

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

    /**
     * @var \ExtDirect\Cache\ExtCache
     */
    protected $extCache;

    /**
     * @var boolean
     */
    protected $useCache;

    /**
     * @var Parameters
     */
    protected $requestParameters;

    /**
     * constructor
     *
     * @param bool   $useCache             value if cache should used
     * @param string $applicationPath      the application path
     * @param string $applicationNameSpace the application namespace
     */
    public function __construct($useCache = true, $applicationPath = "", $applicationNameSpace = "")
    {
        $this->setCacheState($useCache);
        $this->extCache = new ExtCache(Keys::CACHE_KEY);

        $this->setApplicationPath($applicationPath);
        $this->setApplicationNameSpace($applicationNameSpace);
    }

    /**
     * Sets value if cache should be used or not
     *
     * @param boolean $useCache the cache state
     *
     * @return void
     */
    protected function setCacheState($useCache)
    {
        $this->useCache = $useCache;
    }

    /**
     * returns boolean cache state
     *
     * @return boolean
     */
    protected function useCache()
    {
        return $this->useCache;
    }

    /**
     * Returns ext js cache instance
     *
     * @return ExtCache
     */
    protected function getExtCache()
    {
        return $this->extCache;
    }

    /**
     * Returns request parameters instance
     *
     * @return Parameters
     */
    public function getParameters()
    {
        return $this->requestParameters;
    }

    /**
     * injects the request parameters
     *
     * @param Parameters $parameters the request parameters interface
     *
     * @return void
     */
    public function injectParameters(Parameters $parameters)
    {
        $this->requestParameters = $parameters;
    }

    /**
     * Returns a array containing all remote able actions
     *
     * @return array
     */
    public function getActions()
    {
        if ($this->useCache()) {
            if ($this->getExtCache()->isCached()) {
                return $this->getExtCache()->getActions();
            }
        }

        $actions = $this->generateActions();

        if ($this->useCache()) {
            $this->getExtCache()->cacheActions($actions);
        }

        return $actions;
    }

    /**
     * Generates DirectCollection containing all remote able methods
     *
     * @return Annotations\Collections\DirectCollection
     */
    protected function generateActions()
    {
        $parser = new Parser();
        $parser->setPath($this->getApplicationPath());
        $parser->setNameSpace($this->getApplicationNameSpace());

        $list = $parser->run();

        return $list;
    }

    /**
     * Sets the application path
     *
     * @param string $applicationPath path to application
     *
     * @return void
     */
    public function setApplicationPath($applicationPath)
    {
        $this->applicationPath = $applicationPath;
    }

    /**
     * Returns the application path
     *
     * @return string
     */
    public function getApplicationPath()
    {
        return $this->applicationPath;
    }

    /**
     * Sets the application namespace
     *
     * @param string $applicationNameSpace application's namespace
     *
     * @return void
     */
    public function setApplicationNameSpace($applicationNameSpace)
    {
        $this->applicationNameSpace = $applicationNameSpace;
    }

    /**
     * Returns the application namespace
     *
     * @return string
     */
    public function getApplicationNameSpace()
    {
        return $this->applicationNameSpace;
    }
}


<?php
/**
 * Copyright (c) 2018 Wakers.cz
 *
 * @author Jiří Zapletal (http://www.wakers.cz, zapletal@wakers.cz)
 *
 */

namespace Wakers\StructureModule\Component\Frontend\RecipeModal;

trait Create
{
    /**
     * @var IRecipeModal
     * @inject
     */
    public $IStructure_RecipeModal;

    /**
     * Modální okno pro definování struktur
     * @return RecipeModal
     */
    protected function createComponentStructureRecipeModal() : object
    {
        $control = $this->IStructure_RecipeModal->create();

        $control->onSave[] = function () use ($control)
        {
            $control->redrawControl('recipeForm');

            $this->getComponent('structureRecipeSummaryModal')->redrawControl('modal');
        };

        $control->onOpen[] = function () use ($control)
        {
            $control->redrawControl('recipeForm');
        };

        return $control;
    }
}


<?php
/**
 * Copyright (c) 2018 Wakers.cz
 *
 * @author Jiří Zapletal (http://www.wakers.cz, zapletal@wakers.cz)
 *
 */

namespace Wakers\StructureModule\Component\Frontend\StructureModal;

trait Create
{
    /**
     * @var IStructureModal
     * @inject
     */
    public $IStructure_StructureModal;

    /**
     * Modální okno pro nastavení hodnot struktur
     * @return StructureModal
     */
    protected function createComponentStructureStructureModal() : object
    {
        $control = $this->IStructure_StructureModal->create();

        $control->onOpen[] = function () use ($control)
        {
            $control->redrawControl('modal');
            $control->redrawControl('title');

            $control->redrawControl('formNoFile');
            $control->redrawControl('formFile');
            $control->redrawControl('formMain');
        };

        $control->onSaveNoFile[] = function () use ($control)
        {
            $control->redrawControl('modal');
            $control->redrawControl('title');

            $control->redrawControl('formNoFile');
            $control->redrawControl('formFile');
            $control->redrawControl('formMain');

            $this->redrawPrinters();
        };

        $control->onSaveFile[] = function () use ($control)
        {
            $control->redrawControl('modal');
            $control->redrawControl('formFile');

            $this->redrawPrinters();
        };

        $control->onSaveMain[] = function () use ($control)
        {
            $control->redrawControl('modal');
            $control->redrawControl('formMain');

            $this->redrawPrinters();
        };

        return $control;
    }

    /**
     * Překreslí vše obalené snippetem sp-1 až sp-50 (určeno pro komponentu structurePrinter)
     */
    protected function redrawPrinters()
    {
        for ($i = 1; $i <= 50; $i++)
        {
            $this->presenter->redrawControl('sp-' . $i);
        }
    }
}


<?php
/**
 * Copyright (c) 2018 Pushkar Anand. Under MIT License.Copyright (c) 2018 Pushkar Anand. Under MIT License.
 *
 */

namespace EasyRoute;

use Exception;

/**
 * Class Route
 * @package EasyRoute
 */
class Route
{
    public $match_found = false;
    private $ARRAY_METHOD_KEY = "method";
    private $ARRAY_URI_KEY = "uri";
    private $ARRAY_CALLABLE_BOOL_KEY = "callable";
    private $ARRAY_FILE_KEY = "file";
    private $ARRAY_CALLABLE_KEY = "function";
    private $ARRAY_PARAMS_KEY = "params";

    private $server_uri;
    private $supported_methods = array("GET", "POST");
    private $request_method;
    private $script_name;
    private $current_path;
    private $match_list = array();
    private $match;
    private $send404 = true;

    /**
     * Route constructor.
     */
    public function __construct()
    {
        $this->server_uri = $_SERVER['REQUEST_URI'];
        $this->request_method = $_SERVER["REQUEST_METHOD"];
        $this->script_name = $_SERVER['SCRIPT_NAME'];

        $this->current_path = $this->get_request_path($this->server_uri, $this->script_name);
    }

    /**
     * @param string $server_uri
     * @param string $script_name
     * @return string
     */
    private function get_request_path(string $server_uri, string $script_name): string
    {
        $basepath = implode('/',
                array_slice(explode('/', $script_name),
                    0,
                    -1)) . '/';

        $uri = substr($server_uri, strlen($basepath));

        if (strstr($uri, '?')) {
            $uri = substr($uri, 0, strpos($uri, '?'));
        }
        $uri = '/' . trim($uri, '/');

        return $uri;
    }

    /**
     * If this is set to false 404 NOT FOUND will not be sent when no match is found.
     * By default set to true.
     * @param bool $bool
     */
    public function send404(bool $bool)
    {
        $this->send404 = $bool;
    }

    /**
     * Add all routes by calling this method.
     *
     * @param string $method is the request method.
     * @param string $uri is the uri to be matched.
     * @param string|callable $next is either a file to load or a callable function.
     * @throws Exception
     */
    public function addMatch(string $method, string $uri, $next)
    {
        $method = strtoupper($method);

        if (!in_array($method, $this->supported_methods)) {
            throw new Exception("Method " . $method . " is not supported.");
        }

        if (!is_string($uri)) {
            throw new Exception("Uri " . $uri . " is not valid.");
        }

        if (is_callable($next)) {

            $new_match = array(
                $this->ARRAY_METHOD_KEY => $method,
                $this->ARRAY_URI_KEY => $uri,
                $this->ARRAY_CALLABLE_BOOL_KEY => true,
                $this->ARRAY_CALLABLE_KEY => $next
            );

        } elseif (is_string($next)) {

            if (file_exists($next)) {
                $new_match = array(
                    $this->ARRAY_METHOD_KEY => $method,
                    $this->ARRAY_URI_KEY => $uri,
                    $this->ARRAY_CALLABLE_BOOL_KEY => false,
                    $this->ARRAY_FILE_KEY => $next
                );

            } else {
                $dir_next = __DIR__ . "/" . $next;

                if (file_exists($dir_next)) {
                    $new_match = array(
                        $this->ARRAY_METHOD_KEY => $method,
                        $this->ARRAY_URI_KEY => $uri,
                        $this->ARRAY_CALLABLE_BOOL_KEY => false,
                        $this->ARRAY_FILE_KEY => $dir_next
                    );

                } else {

                    throw new Exception("File " . $next . " not found.");
                }
            }
        } else {
            throw new Exception("Invalid third parameter. Expecting callable or file.");
        }

        array_push($this->match_list, $new_match);
    }

    /**
     *
     */
    public function execute()
    {
        if ($this->findMatch()) {
            if ($this->match[$this->ARRAY_CALLABLE_BOOL_KEY] == true) {
                $callable = $this->match[$this->ARRAY_CALLABLE_KEY];
                $callable();
            } else {
                $file = $this->match[$this->ARRAY_FILE_KEY];
                require_once $file;
            }
        } else {
            if ($this->send404) {
                header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
                exit();
            }
        }
    }

    private function findMatch(): bool
    {
        foreach ($this->match_list as $match) {

            if ($match[$this->ARRAY_METHOD_KEY] == $this->request_method &&
                $match[$this->ARRAY_URI_KEY] == $this->current_path) {

                $this->match_found = true;
                $this->match = $match;
                return true;
            }
        }
        return false;
    }

    /**
     * @param array $params
     * @return bool
     */
    private function areParamsValid(array $params): bool
    {

        return false;
    }
}