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

use Phossa2\Shared\Message\Message;
use Phossa2\Shared\Base\StaticAbstract;
use Phossa2\Shared\Exception\RuntimeException;

/**
 * Reader
 *
 * Read from file base on the suffix
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @version 2.0.16
 * @since   2.0.2 added
 * @since   2.0.16 updated
 */
class Reader extends StaticAbstract
{
    /**
     * supported types
     *
     * @var    string[]
     * @access protected
     * @staticvar
     */
    protected static $supported = ['ini', 'json', 'php', 'xml', 'serialized'];

    /**
     * Read, parse & return contents from the $path
     *
     * @param  string $path
     * @param  string $type force this type
     * @return mixed
     * @throws NotFoundException if $path not found
     * @throws RuntimeException if something goes wrong
     * @access public
     * @since  2.0.16 added $type param
     * @static
     */
    public static function readFile(
        /*# string */ $path,
        /*# string */ $type = ''
    ) {
        $suffix = $type ?: substr($path, strpos($path, '.') + 1);

        if (!static::isSupported($suffix)) {
            throw new RuntimeException(
                Message::get(Message::MSG_PATH_TYPE_UNKNOWN, $suffix),
                Message::MSG_PATH_TYPE_UNKNOWN
            );
        }

        /* @var ReaderInterface $class */
        $class = static::getNameSpace() . '\\' . ucfirst($suffix) . 'Reader';

        return $class::readFile($path);
    }

    /**
     * Is this type supported
     *
     * @param  string $type
     * @return bool
     * @access public
     * @static
     */
    public static function isSupported(/*# string */ $type)/*# : bool */
    {
        return in_array($type, static::$supported);
    }
}


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

use EXSyst\Component\IO\Channel\ChannelInterface;
use EXSyst\Component\IO\Source;
use EXSyst\Component\IO\Source\BufferedSource;
use EXSyst\Component\Worker\Bootstrap\WorkerBootstrapProfile;
use EXSyst\Component\Worker\Internal\AdminEncoding;
use EXSyst\Component\Worker\Internal\IdentificationHelper;
use EXSyst\Component\Worker\Internal\SocketFactory;
use EXSyst\Component\Worker\Internal\WorkerRunner;

class SharedWorker implements ChannelInterface
{
    /**
     * @var string
     */
    private $socketAddress;
    /**
     * @var false|int|null
     */
    private $processId;
    /**
     * @var ChannelInterface
     */
    private $channel;
    /**
     * @var string|null
     */
    private $adminCookie;
    /**
     * @var array
     */
    private $unreceivedMessages;

    /**
     * @param string                 $socketAddress
     * @param WorkerBootstrapProfile $bootstrapProfile
     * @param string|null            $implementationExpression
     * @param bool                   $autoStart
     *
     * @throws Exception\ConnectException
     */
    protected function __construct($socketAddress, WorkerBootstrapProfile $bootstrapProfile, $implementationExpression = null, $autoStart = true)
    {
        $this->socketAddress = $socketAddress;
        $this->processId = false;
        $this->adminCookie = $bootstrapProfile->getAdminCookie();
        $this->unreceivedMessages = [];
        try {
            $this->channel = self::connect($socketAddress, $bootstrapProfile);
        } catch (Exception\ConnectException $e) {
            if (!$autoStart) {
                throw $e;
            }
            static::startWithExpression($socketAddress, $bootstrapProfile, $implementationExpression, $e);
            // Try every 0.2s for 10s
            for ($i = 0; $i < 50; ++$i) {
                try {
                    // If we get here, the timeout should be useless, but, just in case ...
                    $this->channel = self::connect($socketAddress, $bootstrapProfile, 1);
                    break;
                } catch (Exception\ConnectException $e2) {
                    // The worker may still be initializing, so wait, and try again
                }
                usleep(200000);
            }
            if (!$this->channel) {
                // Final attempt
                $this->channel = self::connect($socketAddress, $bootstrapProfile);
            }
        }
    }

    /**
     * @param string                 $socketAddress
     * @param WorkerBootstrapProfile $bootstrapProfile
     * @param int|null               $timeout
     *
     * @throws Exception\ConnectException
     *
     * @return ChannelInterface
     */
    private static function connect($socketAddress, WorkerBootstrapProfile $bootstrapProfile, $timeout = null)
    {
        $socket = SocketFactory::createClientSocket($socketAddress, $timeout);
        $connection = Source::fromStream($socket, true, null, false);

        return $bootstrapProfile->getChannelFactory()->createChannel(new BufferedSource($connection), $connection);
    }

    /**
     * @param string                 $socketAddress
     * @param WorkerBootstrapProfile $bootstrapProfile
     * @param string|null            $implementationClassName
     * @param bool                   $autoStart
     *
     * @throws Exception\ConnectException
     *
     * @return static
     */
    public static function withClass($socketAddress, WorkerBootstrapProfile $bootstrapProfile, $implementationClassName = null, $autoStart = true)
    {
        return new static($socketAddress, $bootstrapProfile, ($implementationClassName === null) ? null : $bootstrapProfile->generateExpression($implementationClassName), $autoStart);
    }

    /**
     * @param string                 $socketAddress
     * @param WorkerBootstrapProfile $bootstrapProfile
     * @param string|null            $implementationExpression
     * @param bool                   $autoStart
     *
     * @throws Exception\ConnectException
     *
     * @return static
     */
    public static function withExpression($socketAddress, WorkerBootstrapProfile $bootstrapProfile, $implementationExpression = null, $autoStart = true)
    {
        return new static($socketAddress, $bootstrapProfile, $implementationExpression, $autoStart);
    }

    /**
     * @param string                 $socketAddress
     * @param WorkerBootstrapProfile $bootstrapProfile
     * @param string                 $implementationClassName
     *
     * @throws Exception\ConnectException
     * @throws Exception\LogicException
     */
    public static function startWithClass($socketAddress, WorkerBootstrapProfile $bootstrapProfile, $implementationClassName)
    {
        static::startWithExpression($socketAddress, $bootstrapProfile, $bootstrapProfile->generateExpression($implementationClassName));
    }

    /**
     * @param string                          $socketAddress
     * @param WorkerBootstrapProfile          $bootstrapProfile
     * @param string                          $implementationExpression
     * @param Exception\ConnectException|null $e
     *
     * @throws Exception\ConnectException
     * @throws Exception\LogicException
     */
    public static function startWithExpression($socketAddress, WorkerBootstrapProfile $bootstrapProfile, $implementationExpression, Exception\ConnectException $e = null)
    {
        if (!IdentificationHelper::isLocalAddress($socketAddress)) {
            if ($e) {
                throw $e;
            } else {
                throw new Exception\LogicException("Can't start the worker, because its socket address is not local");
            }
        }

        $bootstrapProfile->getOrFindPhpExecutablePathAndArguments($php, $phpArgs);
        $bootstrapProfile->compileScriptWithExpression($implementationExpression, $socketAddress, $scriptPath, $deleteScript);

        try {
            $line = array_merge([$php], $phpArgs, [$scriptPath]);
            self::startDaemon($line, $bootstrapProfile->getOutputPath());
        } catch (\Exception $e) {
            if ($deleteScript) {
                unlink($scriptPath);
            }
            throw $e;
        }
    }

    /**
     * @param array $argv
     * @param string|null $outputPath
     *
     * @throws Exception\RuntimeException
     */
    public static function startDaemon(array $argv, $outputPath = null)
    {
        // This part purges the file descriptors of the daemon.
        // Caveat : it may contain "Bashisms", for example if a FD is >= 10.
        $fdPurge = implode(array_map(function ($fd) {
            return ' '.intval($fd).'>&-';
        }, IdentificationHelper::getMyFileDescriptors(false)));
        $command = implode(' ', array_map('escapeshellarg', $argv));
        system($command.' 0</dev/null 1'.(($outputPath !== null) ? ('>>'.escapeshellarg($outputPath)) : '>/dev/null').' 2>&1'.$fdPurge.' &');
    }

    /**
     * @param string $socketAddress
     *
     * @throws Exception\RuntimeException
     *
     * @return int|null
     */
    public static function getWorkerProcessId($socketAddress)
    {
        return IdentificationHelper::getListeningProcessId($socketAddress);
    }

    /**
     * @param string                 $socketAddress
     * @param WorkerBootstrapProfile $bootstrapProfile
     *
     * @throws Exception\LogicException
     * @throws Exception\RuntimeException
     *
     * @return bool
     */
    public static function stopWorker($socketAddress, WorkerBootstrapProfile $bootstrapProfile)
    {
        $adminCookie = $bootstrapProfile->getAdminCookie();
        if ($adminCookie === null) {
            throw new Exception\LogicException('Cannot stop a shared worker without an admin cookie');
        }
        try {
            $channel = self::connect($socketAddress, $bootstrapProfile);
        } catch (Exception\RuntimeException $e) {
            return false;
        }
        AdminEncoding::sendStopMessage($channel, $adminCookie);

        return true;
    }

    /**
     * @param string                 $socketAddress
     * @param WorkerBootstrapProfile $bootstrapProfile
     *
     * @throws Exception\LogicException
     * @throws Exception\RuntimeException
     *
     * @return Status\WorkerStatus
     */
    public static function queryWorker($socketAddress, WorkerBootstrapProfile $bootstrapProfile)
    {
        $adminCookie = $bootstrapProfile->getAdminCookie();
        $channel = self::connect($socketAddress, $bootstrapProfile);
        AdminEncoding::sendQueryMessage($channel, $adminCookie);
        for (;;) {
            $message = $channel->receiveMessage();
            $status = AdminEncoding::getStatusMessage($message);
            if ($status !== null) {
                return $status;
            }
        }
    }

    public static function stopCurrent()
    {
        WorkerRunner::stopListening();
    }

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

    /**
     * @throws Exception\RuntimeException
     *
     * @return int|null
     */
    public function getProcessId()
    {
        if ($this->processId === false) {
            $this->processId = IdentificationHelper::getListeningProcessId($this->socketAddress);
        }

        return $this->processId;
    }

    /**
     * @throws Exception\LogicException
     * @throws Exception\RuntimeException
     *
     * @return $this
     */
    public function stop()
    {
        if ($this->adminCookie === null) {
            throw new Exception\LogicException('Cannot stop a shared worker without an admin cookie');
        }
        AdminEncoding::sendStopMessage($this->channel, $this->adminCookie);

        return $this;
    }

    /**
     * @throws Exception\RuntimeException
     *
     * @return Status\WorkerStatus
     */
    public function query()
    {
        AdminEncoding::sendQueryMessage($this->channel, $this->adminCookie);
        foreach ($this->unreceivedMessages as $i => $message) {
            $status = AdminEncoding::getStatusMessage($message);
            if ($status !== null) {
                array_splice($this->unreceivedMessages, $i, 1);

                return $status;
            }
        }
        for (;;) {
            $message = $this->channel->receiveMessage();
            $status = AdminEncoding::getStatusMessage($message);
            if ($status !== null) {
                return $status;
            }
            $this->unreceivedMessages[] = $message;
        }
    }

    /** {@inheritdoc} */
    public function getStream()
    {
        return $this->channel->getStream();
    }

    /** {@inheritdoc} */
    public function sendMessage($message)
    {
        $this->channel->sendMessage($message);

        return $this;
    }

    /** {@inheritdoc} */
    public function receiveMessage()
    {
        if (count($this->unreceivedMessages)) {
            return array_shift($this->unreceivedMessages);
        }

        return $this->channel->receiveMessage();
    }

    /**
     * @throws Exception\RuntimeException
     *
     * @return mixed
     */
    public function receiveMessageDirectly()
    {
        return $this->channel->receiveMessage();
    }

    /**
     * @return int
     */
    public function getUnreceivedMessageCount()
    {
        return count($this->unreceivedMessages);
    }

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

    /**
     * @param int $index
     *
     * @throws Exception\OutOfRangeException
     *
     * @return $this
     */
    public function removeUnreceivedMessage($index)
    {
        if ($index < 0 || $index >= count($this->unreceivedMessages)) {
            throw new Exception\OutOfRangeException('The "un-received" message index must be between 0 (inclusive) and the length of the queue (exclusive)');
        }
        array_splice($this->unreceivedMessages, $index, 1);

        return $this;
    }

    /**
     * @param mixed $message
     *
     * @return $this
     */
    public function unreceiveMessage($message)
    {
        $this->unreceivedMessages[] = $message;

        return $this;
    }
}


<?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_Server
{
	public static function __getInstance ()
	{
		static $in;
		if (!isset ($in))
		{
			$in = new self ();
		}
		return $in;
	}

	public static function getInstance ()
	{
		return self::__getInstance ();
	}

	public static function getOnlineUser ($start = 0, $limit = 250)
	{
		//die ($start . ' - '. $limit);

		$start = (int)$start;

		$db = Neuron_Core_Database::__getInstance ();

		$l = $db->select
		(
			'n_players',
			array ('*'),
			"lastRefresh > '".Neuron_Core_Tools::timestampToMysqlDatetime ((time () - ONLINE_TIMEOUT))."' AND isPlaying = '1'",
			'nickname ASC',
			$start . ", " . $limit
		);

		$o = array ();
		foreach ($l as $v)
		{
			$o[] = Neuron_GameServer::getPlayer ($v['plid'], $v);
		}
		return $o;
	}

	public static function countOnlineUsers ($timeout = null)
	{
		$db = Neuron_Core_Database::__getInstance ();

		if ($timeout == null)
		{
			$timeout = ONLINE_TIMEOUT;
		}

		$l = $db->getDataFromQuery
		($db->customQuery(
		"
			SELECT
				COUNT(plid) as aantal
			FROM
				n_players
			WHERE
				lastRefresh > '".Neuron_Core_Tools::timestampToMysqlDatetime ((time () - $timeout))."'
				AND isPlaying = '1'
		"));

		return $l[0]['aantal'];
	}

	public static function countPremiumPlayers ($timeout = null)
	{
		$db = Neuron_Core_Database::__getInstance ();

		if ($timeout == null)
		{
			$timeout = ONLINE_TIMEOUT;
		}

		$l = $db->getDataFromQuery
		($db->customQuery(
		"
			SELECT
				COUNT(plid) as aantal
			FROM
				n_players
			WHERE
				lastRefresh > '".Neuron_Core_Tools::timestampToMysqlDatetime ((time () - $timeout))."'
				AND isPlaying = '1'
				AND UNIX_TIMESTAMP(creationDate) < ".time()."
				AND UNIX_TIMESTAMP(premiumEndDate) > ".time()."
		"));

		return $l[0]['aantal'];
	}

	public static function countSponsors ()
	{
		$db = Neuron_Core_Database::__getInstance ();

		$l = $db->getDataFromQuery
		($db->customQuery(
		"
			SELECT
				COUNT(plid) as aantal
			FROM
				n_players
			WHERE
				sponsorEndDate > '".Neuron_Core_Tools::timestampToMysqlDatetime (time ())."'
		"));

		return $l[0]['aantal'];
	}

	public static function countTotalPlayers ()
	{
		$db = Neuron_Core_Database::__getInstance ();

		$l = $db->getDataFromQuery
		($db->customQuery(
		"
			SELECT
				COUNT(plid) as aantal
			FROM
				n_players
		"));

		return $l[0]['aantal'];
	}

	public static function countPlayersFromAuth ($auth)
	{
		$db = Neuron_Core_Database::__getInstance ();

		if (!empty ($auth))
		{
			$where = "authType = '".$db->escape ($auth)."'";
		}
		else
		{
			$where = "authType IS NULL";
		}

		$l = $db->getDataFromQuery
		($db->customQuery(
		"
			SELECT
				COUNT(plid) as aantal
			FROM
				n_players
			WHERE
				$where
		"));

		return $l[0]['aantal'];
	}

	public static function searchPlayer ($sName, $iStart = 0, $iLength = 10, $literal = false)
	{
		$db = Neuron_Core_Database::__getInstance ();

		if ($literal)
		{
			$where = "nickname = '".$db->escape ($sName)."'";
		}
		else
		{
			$where = "nickname LIKE '".$db->escape ($sName)."'";
		}

		$l = $db->getDataFromQuery
		($db->customQuery(
		"
			SELECT
				*
			FROM
				n_players
			WHERE
				$where AND
				isRemoved = '0'
			LIMIT
				$iStart, $iLength
		"));

		$o = array ();
		foreach ($l as $v)
		{
			$o[] = Neuron_GameServer::getPlayer ($v['plid'], $v);
		}
		return $o;
	}

	public function getDonationUrl ($amount = null, $currency = 'EUR')
	{
		$login = Neuron_Core_Login::__getInstance ();
		$text = Neuron_Core_Text::__getInstance ();

		$url = DONATION_URL . "?amount=".$amount."&currency=".$currency."&language=".$text->getCurrentLanguage ();
		$url .= "&callback=".urlencode (API_FULL_URL."?action=processPayment&key=".API_MASTER_KEY);

		if ($login->isLogin ())
		{
			return $url . "&userid=".urlencode ($login->getUserId ());
		}
		else
		{
			return $url;
		}
	}

	public static function countAuthTypes ()
	{
		$out = array ();

		$db = Neuron_Core_Database::__getInstance ();

		// Select the different auth types
		$auths = $db->getDataFromQuery ($db->customQuery
		("
			SELECT
				authType
			FROM
				n_players
			GROUP BY
				authType
		"));

		foreach ($auths as $v)
		{
			if (empty ($v['authType']))
			{
				$out['dolumar'] = self::countPlayersFromAuth ($v['authType']);
			}
			else
			{
				$out[$v['authType']] = self::countPlayersFromAuth ($v['authType']);
			}
		}

		return $out;
	}

	private static function getFilesToKeep ()
	{
		return array ('openid');
	}

	public static function removeDirRecursive ($dir, $emptyOnly = false)
	{
		$scanDir = scandir ($dir);
		$filesToKeep = self::getFilesToKeep ();

		foreach ($scanDir as $file)
		{
			if ($file != '.' && $file != '..' && array_search ($file, $filesToKeep) === false)
			{
				if (is_dir ($dir . '/' . $file))
				{
					self::removeDirRecursive ($dir . '/' . $file, true);
					rmdir ($dir . '/' . $file);
				}
				else
				{
					unlink ($dir . '/' . $file);
				}
			}
		}

		if (!$emptyOnly)
		{
			if (is_dir ($dir))
			{
				rmdir ($dir);
			}
			else
			{
				unlink ($dir);
			}
		}
	}

	public static function emptyDir ($dir)
	{
		self::removeDirRecursive ($dir, true);
	}

	public static function clearCache ($clearMapCache = true)
	{
		self::emptyDir (CACHE_DIR);
		/*
		self::emptyDir ('cache/minimap');
		self::emptyDir ('cache/mediawiki');
		self::emptyDir ('cache/hugemap');
		self::emptyDir ('cache/heightmap');
		*/

		//self::emptyDir (CACHE_DIR . 'openid');

		if ($clearMapCache)
		{
			$db = Neuron_Core_Database::__getInstance ();
			//$db->customQuery (" TRUNCATE TABLE `z_cache_tiles`  ");

			$server = self::__getInstance ();
			$server->setData ('prepRadD', 0);
		}

		$cache = Neuron_Core_Memcache::getInstance ();
		$cache->flush ();
	}

	public static function countInvitations ()
	{
		$db = Neuron_Core_Database::__getInstance ();

		$l = $db->select
		(
			'invitation_codes',
			array ('invCode', 'invLeft'),
			"i_infinite = '1'"
		);

		$o = array ();
		foreach ($l as $v)
		{
			$o[$v['invCode']] = $v['invLeft'];
		}
		return $o;
	}

	public static function getPremiumcallKey ()
	{
		return md5 (md5 (PREMIUM_API_KEY.date ('dDWY').PREMIUM_API_KEY));
	}

	public static function cleanServer ()
	{
		$db = Neuron_Core_Database::__getInstance ();

		$log = array ();

		// Kill players
		$last = Neuron_Core_Tools::timestampToMysqlDatetime (time () - 60*60*24*45);

		$l = $db->select
		(
			'n_players',
			array ('plid', 'killCounter'),
			"lastRefresh < '".$last."' AND isPlaying = 1"
		);

		foreach ($l as $v)
		{
			if ($v['killCounter'] < 5)
			{
				$db->update
				(
					'n_players',
					array
					(
						'killCounter' => '++'
					),
					"plid = '".$v['plid']."'"
				);
			}

			else
			{
				// Kill!
				$player = Neuron_GameServer::getPlayer ($v['plid']);

				if (!$player->isModerator ())
				{
					$player->doResetAccount ();

					/*
					$log[] = array
					(
						'action' => 'reset',
						'subject' => 'account',
						'name' => $player->getNickname ()
					);
					*/

					$player->__destruct ();
				}
			}
		}

		// Kill villages
		$last = Neuron_Core_Tools::timestampToMysqlDatetime (time () - 60*60*24*5);
		//$last = Neuron_Core_Tools::timestampToMysqlDatetime (time ());

		$l = $db->select
		(
			'villages',
			array ('vid'),
			"isActive = '0' AND (removalDate < '$last' OR removalDate IS NULL)"
		);

		foreach ($l as $v)
		{
			$village = Dolumar_Players_Village::getVillage ($v['vid'], false, true, true);
			$village->destroyVillage ();

			$village->__destruct ();
		}

		// Remove old login data (2 weeks old)
		$rem = $db->remove ('n_login_log', "l_datetime < '".date ('Y-m-d H:i:s', time () - 60*60*24*7*2)."'");
		$log[] = "Removed ".$rem." login logs.\n";

		// Remove old game log data (2 months old)
		//$db->remove ('game_log', "l_date < '".date ('Y-m-d H:i:s', time () - 60*60*31*2)."'");

		// Remove old battle reports (2 months old)
		$rem = $db->remove ('battle_report', "fightDate < '". (time () - 60*60*24*31*2)."'");
		$log[] = "Removed ".$rem." battle reports.\n";

		return $log;
	}

	private $data = null;
	private $error = null;

	public function __construct ()
	{

	}

	private function loadData ()
	{
		if ($this->data === null)
		{
			$this->data = array ();

			$db = Neuron_Core_Database::__getInstance ();

			$l = $db->select
			(
				'n_server_data',
				array ('*')
			);

			foreach ($l as $v)
			{
				$this->data[$v['s_name']] = $v['s_value'];
			}
		}
	}

	/*
		Return true if the server is online
	*/
	public function isOnline ()
	{
		$this->loadData ();
		$timecheck = isset ($this->data['lastDaily']) && intval ($this->data['lastDaily']) > (time () - 60*60*24*7);

		if (!$this->isInstalled ())
		{
			$this->error = 'not_installed';
			return false;
		}
		elseif (!$timecheck)
		{
			$this->error = 'daily_cron_failed';
			return false;
		}
		else
		{
			return true;
		}
	}

	public function getServerId ()
	{
		$this->loadData ();
		return isset ($this->data['serverid']) ? $this->data['serverid'] : false;
	}

	public function getServerName ()
	{
		$this->loadData ();
		return isset ($this->data['servername']) ? $this->data['servername'] : null;
	}

	public function isInstalled ()
	{
		$this->loadData ();
		return isset ($this->data['servername']) && isset ($this->data['serverid']);
	}

	public function setServerName ($id, $sName)
	{
		$db = Neuron_Core_Database::__getInstance ();
		$db->insert
		(
			'n_server_data',
			array
			(
				's_name' => 'servername',
				's_value' => $sName
			)
		);

		$db->insert
		(
			'n_server_data',
			array
			(
				's_name' => 'serverid',
				's_value' => $id
			)
		);
	}

	public function updateServerName ($sName)
	{
		$db = Neuron_Core_Database::__getInstance ();

		$db->update
		(
			'n_server_data',
			array
			(
				's_value' => $sName
			),
			"s_name = 'servername'"
		);
	}

	public function setData ($sKey, $sData)
	{
		$db = Neuron_DB_Database::getInstance ();

		// Check if key exists
		$chk = $db->query
		("
			SELECT
				s_value
			FROM
				n_server_data
			WHERE
				s_name = '{$db->escape ($sKey)}'
		");

		if (count ($chk) > 0)
		{
			$db->query
			("
				UPDATE
					n_server_data
				SET
					s_value = '{$db->escape ($sData)}'
				WHERE
					s_name = '{$db->escape ($sKey)}'
			");
		}
		else
		{
			$db->query
			("
				INSERT INTO
					n_server_data
				SET
					s_value = '{$db->escape ($sData)}',
					s_name = '{$db->escape ($sKey)}'
			");
		}

		$this->data[$sKey] = $sData;
	}

	public function getData ($sKey)
	{
		$this->loadData ();
		return isset ($this->data[$sKey]) ? $this->data[$sKey] : null;
	}

	public function setLastDaily ($now = NOW)
	{
		$this->loadData ();

		$db = Neuron_Core_Database::__getInstance ();
		if (isset ($this->data['lastDaily']))
		{
			$db->update
			(
				'n_server_data',
				array ('s_value' => $now),
				"s_name = 'lastDaily'"
			);
		}
		else
		{
			$db->insert
			(
				'n_server_data',
				array
				(
					's_name' => 'lastDaily',
					's_value' => $now
				)
			);
		}
	}

	private $textdata;

	private function loadTextData ($lang)
	{
		$lang = $this->getTextKey ($lang);

		if (!isset ($this->textdata))
		{
			$this->textdata = array ();

			if (!isset ($this->textdata[$lang]))
			{
				$this->textdata[$lang] = array ();

				$db = Neuron_DB_Database::getInstance ();

				$data = $db->query
				("
					SELECT
						*
					FROM
						n_server_text
					WHERE
						s_lang = '{$db->escape ($lang)}'
				");

				foreach ($data as $v)
				{
					$this->textdata[$lang][$v['s_id']] = $v['s_value'];
				}
			}
		}
	}

	private function getTextKey ($key)
	{
		$text = Neuron_Core_Text::getInstance ();

		if (!isset ($key))
		{
			return $text->getCurrentLanguage ();
		}

		return $key;
	}

	public function getText ($key, $lang = null)
	{
		$lang = $this->getTextKey ($lang);

		$this->loadTextData ($lang);
		return isset ($this->textdata[$lang][$key]) ? $this->textdata[$lang][$key] : null;
	}

	public function getError ()
	{
		return $this->error;
	}
}
?>


<?php

namespace SQRT\QueryBuilder\Query;

use SQRT\QueryBuilder\Query;

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

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

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

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

    return $vars;
  }

  /** @return static */
  public function setEqual($column, $value)
  {
    return parent::setEqual($column, $value);
  }

  /** @return static */
  public function setExpr($expr)
  {
    return parent::setExpr($expr);
  }

  /** @return static */
  public function setFromArray(array $array)
  {
    return parent::setFromArray($array);
  }
}


<?php
namespace Cora;

class Database
{
    public static $defaultDb;
    public static $testingDb;

    protected $tables;
    protected $selects;
    protected $updates;
    protected $delete;
    protected $distinct;
    protected $wheres;
    protected $ins;
    protected $limit;
    protected $offset;
    protected $groupBys;
    protected $orderBys;
    protected $havings;
    protected $joins;
    protected $inserts;
    protected $values;
    protected $create;
    protected $primaryKeys;
    protected $foreignKeys;
    protected $indexes;
    protected $query;
    protected $queryDisplay;

    // For overridding with a custom query
    protected $customQuery;
    protected $customValues;
    protected $customStmt;

    // For calculating total row from last query within LIMIT
    protected $last_wheres;
    protected $last_distinct;
    protected $last_ins;
    protected $last_groupBys;
    protected $last_havings;
    protected $last_joins;

    public function __construct()
    {
        $this->reset();
    }

    public function isSelectSet()
    {
        if(empty($this->selects))
            return false;
        return true;
    }

    /**
     *  Whether or not a custom query is defined on this query builder object.
     *
     *  @return bool
     */
    public function isCustom()
    {
      return $this->customQuery;
    }

    public function resetSelect()
    {
        $this->selects  = array();
    }

    public function table($tables)
    {
        $this->storeValue('tables', $tables);
        return $this;
    }

    // Alias of $this->table
    public function from($tables)
    {
        $this->table($tables);
        return $this;
    }

    public function select($fields, $delim = false)
    {
        $this->storeValue('selects', $fields, $delim);
        return $this;
    }

    // Alias of $this->table
    public function update($tables)
    {
        $this->table($tables);
        return $this;
    }

    public function set($field, $value)
    {
        $this->store('keyValue', 'updates', $field, $value);
        return $this;
    }

    public function delete()
    {
        $this->delete = true;
        return $this;
    }

    public function distinct()
    {
        $this->distinct = true;
        return $this;
    }

    /**
     *  WHERE array format:
        [
            [
                [
                    ['amount', '>', '1000'],
                    ['savings', '>', '100']
                ],
                'AND'
            ]
        ]
    */
    public function where($conditions, $value = false, $comparison = '=')
    {
        $this->store('condition', 'wheres', $conditions, $value, $comparison);
        return $this;
    }

    public function orWhere($conditions, $value = false, $comparison = '=')
    {
        $this->store('condition', 'wheres', $conditions, $value, $comparison, 'OR');
        return $this;
    }

    //public function in($column, $fields)
    public function in($conditions, $value = false, $comparison = 'IN')
    {
        $val = $value;
        if (!is_array($value)) {
            $val = explode(',', $val);
        }
        $this->store('condition', 'wheres', $conditions, $val, $comparison);
        return $this;
    }

    public function limit($num)
    {
        $this->limit = $num;
        return $this;
    }

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

    public function groupBy($fields)
    {
        $this->storeValue('groupBys', $fields);
        return $this;
    }

    public function orderBy($field, $direction = 'DESC')
    {
        $this->store('keyValue', 'orderBys', $field, $direction, '');
        return $this;
    }

    public function having($conditions, $value = false, $comparison = '=')
    {
        $this->store('condition', 'havings', $conditions, $value, $comparison);
        return $this;
    }

    public function orHaving($conditions, $value = false, $comparison = '=')
    {
        $this->store('condition', 'havings', $conditions, $value, $comparison, 'OR');
        return $this;
    }

    public function insert($columns)
    {
        $val = $columns;
        if (!is_array($val)) {
            $val = array_map('trim', explode(',', $val));
        }
        $this->storeValue('inserts', $val);
        return $this;
    }

    // Alias of $this->table
    public function into($table)
    {
        $this->table($table);
        return $this;
    }

    public function values($values)
    {
        $this->storeValue('values', $values);
        return $this;
    }

    public function create($table)
    {
        $this->create = $table;
        return $this;
    }

    public function field($name, $type, $attributes = ' ')
    {
        $this->store('keyValue', 'fields', $name, $attributes, $type);
        return $this;
    }

    public function primaryKey($columns) {
        $this->storeValue('primaryKeys', $columns);
        return $this;
    }

    public function foreignKey($column, $foreignTable, $foreignColumn)
    {
        $this->store('keyValue', 'foreignKeys', $column, $foreignColumn, $foreignTable);
        return $this;
    }

    public function index($columns) {
        $this->storeValue('indexes', $columns);
        return $this;
    }

    public function getQuery()
    {
      // If a user written custom query was passed in, use that
      if ($this->customQuery != '') {
        return $this->calculateCustom();
      }

      // Otherwise calculate the query from the components
      if ($this->query == '') {
          $this->calculate();
      }

      // Save the generated query
      $this->queryDisplay = $this->query;

      // Reset the query string, since we don't want to execute that yet.
      $this->query = '';

      return $this->queryDisplay;
    }

    public function reset()
    {
        $this->tables   = array();
        $this->selects  = array();
        $this->updates  = array();
        $this->wheres   = array();
        $this->ins      = array();
        $this->groupBys = array();
        $this->orderBys = array();
        $this->havings  = array();
        $this->joins    = array();
        $this->inserts  = array();
        $this->values   = array();
        $this->fields   = array();
        $this->primaryKeys  = array();
        $this->foreignKeys  = array();
        $this->indexes  = array();

        $this->distinct = false;
        $this->delete   = false;
        $this->limit    = false;
        $this->offset   = false;
        $this->create   = false;
        $this->query    = '';
        $this->queryDisplay = '';

        $this->customQuery  = '';
        $this->customValues = [];
    }

    /**
        JOIN array format:
        [
            [
                table,
                [
                    conditions
                ],
                type
            ]
        ]
     */
    public function join($table, $conditions, $type = 'INNER')
    {
        $dataMember = &$this->joins;
        $item = [$table, $conditions, $type];
        array_push($dataMember, $item);
        return $this;
    }

    protected function store($type, $dataMember, $fields, $value = false, $comparison = '=', $conjunction = 'AND')
    {

        // If the data being stored DOES need its key.
        // E.g. adding WHERE field = value pairs to wheres array.
        if ($type == 'keyValue') {
            if ($value !== false) {
                $key = $fields;
                $this->storeKeyValue($dataMember, $value, $key, $comparison);
            }

            // If the value passed in is FALSE, then convert that into string 'NULL'.
            else {
                $value = 'NULL';
                $key = $fields;
                $this->storeKeyValue($dataMember, $value, $key, $comparison);
                //$this->storeKeyValue($dataMember, $fields);
            }
        }

        // If the data being stored is condition statements (WHERE, HAVING)
        else if($type == 'condition') {
            if ($value !== false) {
                $key = $fields;
                $this->storeCondition($dataMember, $value, $key, $comparison, $conjunction);
            }
            else {
                $this->storeCondition($dataMember, $fields, $conjunction);
            }
        }
    }

    /**
     *  For storing a single value or flat list of values.
     *  STORAGE FORMAT:
     *  [item1, item2, item3]
     */
     protected function storeValue($type, $data, $delim = false)
     {
         $dataMember = &$this->$type;
         // If array or object full of data was passed in, add all data
         // to appropriate data member.
         if (is_array($data) || is_object($data)) {
             foreach ($data as $value) {
                 if ($value !== false) {
                     if ($delim) {
                         $value = $delim.$value.$delim;
                     }
                 }
                 else {
                     $value = 'NULL';
                 }
                 array_push($dataMember, $value);
             }
         }

         // Add singular data item to data member.
         else {
             if ($data !== false) {
                 if ($delim) {
                     $data = $delim.$data.$delim;
                 }
             }
             else {
                 $data = 'NULL';
             }
             array_push($dataMember, $data);
         }
     }

    /**
     *  For storing an array of data that represents an item.
     *  STORAGE FORMAT:
     *  [
     *      [column, operator, value],
     *      [name, LIKE, %s],
     *      [price, >, 100]
     *  ]
     */
    protected function storeKeyValue($type, $data, $key = false, $comparison = false)
    {
        $dataMember = &$this->$type;
        // If array or object full of data was passed in, add all data
        // to appropriate data member.
        if (is_array($data) || is_object($data)) {
            foreach ($data as $item) {
                array_push($dataMember, $item);
            }
        }

        // Add singular data item to data member.
        else {
            $item = array($key, $comparison, $data);
            array_push($dataMember, $item);
        }
    }

    /**
     *  For storing an array of data that represents an item which needs a custom conjunction connecting them.
     *  STORAGE FORMAT:
     *  [
     *      [
     *          [
     *              [column, operator, value],
     *              [name, LIKE, %s],
     *              [price, >, 100]
     *          ],
     *          AND
     *      ]
     *  ]
     */
    protected function storeCondition($type, $data, $key = false, $comparison = false, $conjunction = false)
    {
        $dataMember = &$this->$type;
        // If array or object full of data was passed in, add all data
        // to appropriate data member.
        if ($comparison != 'IN' && (is_array($data) || is_object($data))) {
            $conj = $key;
            $condition = array($data, $conj);
            array_push($dataMember, $condition);
        }

        // Add singular data item to data member.
        else {
            $item = [array($key, $comparison, $data)];
            $condition = array($item, $conjunction);
            array_push($dataMember, $condition);
        }
    }

    // Just a convenience method to invoke a result method without having to call exec() first.
    public function fetch()
    {
        return $this->exec()->fetch();
    }

    // Just a convenience method to invoke a result method without having to call exec() first.
    public function fetchAll()
    {
        return $this->exec()->fetchAll();
    }

    public function exec()
    {
        // To be implemented by specific DB adaptor.
        throw new Exception('exec() needs to be implemented by a specific database adaptor!');
    }

    protected function execCustom()
    {
        // To be implemented by specific DB adaptor.
        throw new Exception('execCustom() needs to be implemented by a specific database adaptor!');
    }

    public function emptyDatabase()
    {
        // to be implemented by specific adaptor.
        throw new Exception('emptyDatabase() needs to be implemented by a specific database adaptor!');
    }

    protected function calculate()
    {
        // To be implemented by specific DB adaptor.
        throw new Exception('getQuery() calls calculate(), which needs to be implemented by a specific database adaptor!');
    }

    protected function calculateCustom()
    {
        // To be implemented by specific DB adaptor.
        throw new Exception('getQuery() calls calculate(), which needs to be implemented by a specific database adaptor!');
    }

    public function tableExists($name)
    {
        // Implemented by Adaptor.
        throw new Exception('tableExists() needs to be implemented by a specific database adaptor!');
    }

    public function startTransaction()
    {
        // Implemented by Adaptor.
        throw new Exception('startTransaction() needs to be implemented by a specific database adaptor!');
    }

    public function commit()
    {
        // Implemented by Adaptor.
        throw new Exception('commit() needs to be implemented by a specific database adaptor!');
    }

    public function rollback()
    {
        // Implemented by Adaptor.
        throw new Exception('rollback() needs to be implemented by a specific database adaptor!');
    }

    // Clean user provided input to make it safe for use in a database query.
    public function clean($value)
    {
         // Implemented by Adaptor.
        throw new Exception('clean() needs to be implemented by a specific database adaptor!');
    }

    public function getConnection($name)
    {
        return false;
    }

    public static function getDefaultConnectionName()
    {
        // Load Cora DB settings
        require(dirname(__FILE__).'/../config/config.php');
        require(dirname(__FILE__).'/../config/database.php');

        // Load app specific DB settings
        if (file_exists($config['basedir'].'cora/config/database.php')) {
            include($config['basedir'].'cora/config/database.php');
        }

        return $dbConfig['defaultConnection'];
        //return $dbConfig['connections'][$defaultConn]['adaptor'];
    }

    public static function getDefaultDb($getFresh = false, $existingConnection = false)
    {
        // Check if default DB instance is already created.
        if (isset(self::$defaultDb) && $getFresh == false && empty($GLOBALS['coraRunningTests'])) {
            return self::$defaultDb;
        }

        // Check if default TESTING DB instance is already created.
        if (isset(self::$testingDb) && $getFresh == false && !empty($GLOBALS['coraRunningTests'])) {
            return self::$testingDb;
        }

        // Load Cora DB settings
        require(dirname(__FILE__).'/../config/config.php');
        require(dirname(__FILE__).'/../config/database.php');

        // Load app specific DB settings
        if (file_exists($config['basedir'].'cora/config/database.php')) {
            include($config['basedir'].'cora/config/database.php');
        }

        if ($getFresh) {
            // Return a brand new default adaptor.
            $defaultConn = $dbConfig['defaultConnection'];
            $dbAdaptor = '\\Cora\\Db_'.$dbConfig['connections'][$defaultConn]['adaptor'];
            return new $dbAdaptor(false, $existingConnection, true);
        }
        else {
            // Use Default Adaptor as defined in the settings.
            $defaultConn = $dbConfig['defaultConnection'];
            $dbAdaptor = '\\Cora\\Db_'.$dbConfig['connections'][$defaultConn]['adaptor'];

            if (empty($GLOBALS['coraRunningTests'])) {
                self::$defaultDb = new $dbAdaptor(false, $existingConnection);
                return self::$defaultDb;
            } else {
                self::$testingDb = new $dbAdaptor(false, $existingConnection);
                return self::$testingDb;
            }
        }
    }

    public static function getDb($connectionName, $existingConnection = false)
    {
        // Load Cora DB settings
        require(dirname(__FILE__).'/../config/config.php');
        require(dirname(__FILE__).'/../config/database.php');

        // Load app specific DB settings
        if (file_exists($config['basedir'].'cora/config/database.php')) {
            include($config['basedir'].'cora/config/database.php');
        }

        $dbAdaptor = '\\Cora\\Db_'.$dbConfig['connections'][$connectionName]['adaptor'];
        return new $dbAdaptor($connectionName, $existingConnection);
    }

}


<?php

declare(strict_types=1);

namespace Chubbyphp\Config\Pimple;

use Chubbyphp\Config\ConfigProviderInterface;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

final class ConfigServiceProvider implements ServiceProviderInterface
{
    /**
     * @var ConfigProviderInterface
     */
    private $configProvider;

    /**
     * @param ConfigProviderInterface $configProvider
     */
    public function __construct(ConfigProviderInterface $configProvider)
    {
        $this->configProvider = $configProvider;
    }

    /**
     * @param Container $container
     */
    public function register(Container $container)
    {
        $config = $this->configProvider->get($container['env']);

        foreach ($config->getConfig() as $key => $value) {
            if (isset($container[$key])) {
                $container[$key] = $this->mergeRecursive($container[$key], $value, $key);
            } else {
                $container[$key] = $value;
            }
        }

        foreach ($config->getDirectories() as $requiredDirectory) {
            if (!is_dir($requiredDirectory)) {
                mkdir($requiredDirectory, 0777, true);
            }
        }
    }

    /**
     * @param array|string|float|int|bool $existingValue
     * @param array|string|float|int|bool $newValue
     * @param string                      $path
     *
     * @return array|string|float|int|bool
     */
    private function mergeRecursive($existingValue, $newValue, string $path)
    {
        $existingType = gettype($existingValue);
        $newType = gettype($newValue);

        if ($existingType !== $newType) {
            throw new \LogicException(
                sprintf('Type conversion from "%s" to "%s" at path "%s"', $existingType, $newType, $path)
            );
        }

        if ('array' !== $newType) {
            return $newValue;
        }

        foreach ($newValue as $key => $newSubValue) {
            if (!is_string($key)) {
                $existingValue[] = $newSubValue;

                continue;
            }

            if (isset($existingValue[$key])) {
                $subPath = $path.'.'.$key;

                $existingValue[$key] = $this->mergeRecursive($existingValue[$key], $newSubValue, $subPath);
            } else {
                $existingValue[$key] = $newSubValue;
            }
        }

        return $existingValue;
    }
}


<?php
namespace Cora;

class Validate
{
    protected $controller;    // Stores a reference to the calling controller.
    protected $errors;        // Array of validation errors.
    protected $data;          // The data array to be validated. Defaults to $_POST.
    protected $lang;          // For holding error strings.
    protected $customChecks;  // For holding custom check definitions.
    protected $matchedArg;

    public function __construct($controller, $data = false)
    {
        // Store reference to calling controller.
        $this->controller = $controller;

        // If no data is passed in for validation, default to $_POST array.
        if ($data == false)
            $this->data = $_POST;
        else
            $this->data = $data;

        // Init stuff.
        $this->errors = array();
        $this->lang = new \stdClass();
        $this->customChecks = new \stdClass();
        $this->matchedArg = false;

        // Setting this up for future language localization.
        $this->lang->required       = '%s is required!';
        $this->lang->valid_email    = "%s must be a valid email address.";
        $this->lang->valid_date     = "%s must be a valid date.";
        $this->lang->matches        = "%s does not match %s!";
        $this->lang->min_length     = "%s must be at least %s characters.";
        $this->lang->max_length     = "%s must be at most %s characters.";
        $this->lang->is_numeric     = '%s must be numeric. Make sure to remove any $ symbol.';
    }

    public function getValue($fieldName)
    {
        // Grab data from array or leave as false if no data exists.
        $fieldData = false;
        if (isset($this->data[$fieldName])) {
            $fieldData = $this->data[$fieldName];
        }
        return $fieldData;
    }

    /**
     *  Passes list of errors to calling controller.
     *  Returns TRUE if all checks passed. False otherwise.
     */
    public function run()
    {
        if (count($this->errors) == 0) {
            return true;
        }
        else {
            $this->controller->setData('errors', $this->errors);
            return false;
        }
    }

    /**
     *  Stores a customly defined validation check.
     */
    public function def ($checkName, $class, $method, $errorMessage, $passing = true, $arguments = false)
    {
        $this->customChecks->$checkName = ['_call', $class, $method, $passing, $arguments];
        $this->lang->$checkName = $errorMessage;
    }

    /**
     *  Checks a data field for validness by running all the specified checks
     *  against it.
     */
    public function rule($fieldName, $checks, $humanName = false)
    {
        $checkFailures = 0;

        // Default human readable name of form field to the field name.
        if ($humanName == false) {
            $humanName = ucfirst($fieldName);
        }

        // Grab data from array or leave as false if no data exists.
        $fieldData = $this->getValue($fieldName);

        if (!is_array($checks)) {
            $checks = explode('|', $checks);
        }

        // Run checks
        foreach ($checks as $check) {

            $checkName = $check;

            if (isset($this->customChecks->$check)) {

                // Grab this custom check's definition.
                $customCheckDef = $this->customChecks->$check;

                // Grab custom check type. Ex. "call"
                //$checkName = $check;
                $customType = $customCheckDef[0];

                // Define the arguments that will be passed to the custom check.
                $arguments = array($fieldData, $customCheckDef[1], $customCheckDef[2], $customCheckDef[3], $customCheckDef[4]);

                // Call the custom check.
                $checkResult = call_user_func_array(array($this, $customType), $arguments);
            }
            else {

                // See if validation check needs additional argument. E.g "matches[password]"
                $checkArgs = explode('[', $check, 2);
                if (count($checkArgs)>1) {

                    // Set corrected method check name to call. E.g. "matches[password]" calls "matches"
                    $check = $checkArgs[0];
                    $checkName = $checkArgs[0];

                    // explode strips out the leading '[' from '[value]' so we are just restoring it.
                    $checkArgs[1] = '['.$checkArgs[1];

                    // Grab arguments that need to be passed to Check. E.g. "matches[password][title]" would
                    // return "array('password', 'title')"
                    $args = array();
                    preg_match_all("/\[([^\]]*)\]/", $checkArgs[1], $args);
                    $this->matchedArg = $args[1][0];

                    // Append underscore to the check method's name.
                    $check = '_'.$checkName;

                    // Call a built-in check that's part of this Validation class.
                    $checkResult = $this->$check($fieldData, $args[1]);
                }
                else {
                    // Append underscore to the check method's name.
                    $check = '_'.$checkName;

                    // Call a built-in check that's part of this Validation class.
                    $checkResult = $this->$check($fieldData);
                }
            }

            // If the result of the called check is anything other than true, set a validation error.
            if ($checkResult == false) {
                $this->errors[] =  sprintf($this->lang->$checkName, $humanName, $this->matchedArg);
                $this->matchedArg = false;
                $checkFailures++;
            }
        }

        // After all checks for this data field have been run, return if Validation passed (TRUE) or failed (FALSE);
        return $checkFailures == 0 ? true : false;
    }

    ////////////////////////////////////////////////
    //
    //  The Validation Methods
    //
    ////////////////////////////////////////////////

    /**
     *  Form field is required.
     */
    protected function _required($fieldData)
    {
        if ($fieldData !== false && $fieldData != null && $fieldData != '')
            return true;
        else
            return false;
    }

    /**
     *  This handles when a user wants to call a custom validation method in some other class.
     *  A common example would be checking if a username is already taken in a database
     *  when using a user register form.
     *
     *  $fieldData is the actual data.
     *  $controller is the controller that needs to be invoked for this custom check.
     *  $method is the method that needs to be called.
     *  $passing defines what the method should return to pass the test. Two Examples below:
     *          $user->nameExists($fieldData) you would want to return FALSE. So set $passing = false.
     *          $user->nameAvailable($fieldData) you would want to return TRUE. So set $passing = true.
     */
    protected function _call($fieldData, $controller, $method, $passing, $arguments)
    {
        // If data to be passed to the method isn't an array, put it in array format.
        $fieldData = array($fieldData, $arguments);

        // Call custom controller->method and pass the data to it.
        $result = call_user_func_array(array($controller, $method), $fieldData);

        // If the returned result meets expections, pass test (return false) otherwise return message.
        return $result == $passing ? true : false;
    }

    /**
     *  Just trims the field. This check Never fails.
     */
    protected function _trim(&$fieldData)
    {
        $fieldData = trim($fieldData);
        return true;
    }

    protected function _is_numeric($fieldData)
    {
        if ($fieldData == '') {
            return true;
        }
        return is_numeric($fieldData);
    }

    // valid_email
    protected function _valid_email($fieldData)
    {
        if ($fieldData == '') {
            return true;
        }
        else if (preg_match('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/', $fieldData)) {
            return true;
        }
        return false;
    }

    protected function _valid_date($fieldData)
    {
        // Check if mm/dd/yyyy
        $date = \DateTime::createFromFormat('m/d/Y', $fieldData);
        if ($date && $date->format('m/d/Y') === $fieldData) {
            return true;
        }

        // Check if yyyy/mm/dd
        $date = \DateTime::createFromFormat('Y/m/d', $fieldData);
        if ($date && $date->format('Y/m/d') === $fieldData) {
            return true;
        }

        // Check if yyyy-mm-dd
        $date = \DateTime::createFromFormat('Y-m-d', $fieldData);
        if ($date && $date->format('Y-m-d') === $fieldData) {
            return true;
        }

        // Check if dd-mm-yyyy
        $date = \DateTime::createFromFormat('d-m-Y', $fieldData);
        if ($date && $date->format('d-m-Y') === $fieldData) {
            return true;
        }

        // Check if dd.mm.yyyy
        $date = \DateTime::createFromFormat('d.m.Y', $fieldData);
        if ($date && $date->format('d.m.Y') === $fieldData) {
            return true;
        }
        return false;
    }

    // matches
    protected function _matches($fieldData, $array)
    {
        $passes = true;
        foreach ($array as $dataName) {
            $dataValue = $this->getValue($dataName);
            if ($fieldData != $dataValue) {
                $passes = false;
            }
        }
        return $passes;
    }

    protected function _min_length($fieldData, $reqLength)
    {
        $passes = true;
        if (strlen($fieldData) < $reqLength[0]) {
            $passes = false;
        }
        return $passes;
    }

    protected function _max_length($fieldData, $reqLength)
    {
        $passes = true;
        if (strlen($fieldData) > $reqLength[0]) {
            $passes = false;
        }
        return $passes;
    }

    // matches[password]
    // min_length[5]
    // max_length[12]
    // PHP single arg functions like: htmlspecialchars, trim
    // Custom functions

    ////////////////////////////////////////////////
    //
    //  Form Utility Methods
    //
    ////////////////////////////////////////////////

    /**
     *  For resetting a form field's data after a failed validation.
     *  Default is displayed if no data exists for this field.
     */
    public function setField($name, $default = '')
    {
        if (isset($this->data[$name])) {
            return $this->data[$name];
        }
        else {
            return $default;
        }
    }

    /**
     *  For resetting a form Checkbox's data after a failed validation.
     *  $name = checkbox's name
     *  $value = checkbox's value
     *  $default = whether this checkbox should be checked by default.
     */
    public function setCheckbox($name, $value, $default = false)
    {
        if (isset($this->data[$name])) {
            $return = '';
            foreach ($this->data[$name] as $checkBox) {
                if ($checkBox == $value) {
                    $return = 'checked';
                }
            }
            return $return;
        }
        else {
            if ($default) {
                return 'checked';
            }
            else {
                return '';
            }
        }
    }

    /**
     *  For resetting a form Select's data after a failed validation.
     *  $name = Select's name
     *  $value = Option's value
     *  $default = whether this Option should be selected by default.
     */
    public function setSelect($name, $value, $default = false)
    {
        if (isset($this->data[$name])) {
            if ($this->data[$name] == $value) {
                return 'selected';
            }
            else {
                return '';
            }
        }
        else {
            if ($default) {
                return 'selected';
            }
            else {
                return '';
            }
        }
    }

    /**
     *  For resetting a form Select's data after a failed validation.
     *  $name = Select's name
     *  $value = Option's value
     *  $default = whether this Option should be selected by default.
     */
    public function setMultiSelect($name, $value, $default = false)
    {
        if (isset($this->data[$name])) {
            if (in_array($value, $this->data[$name])) {
                return 'selected';
            }
            else {
                return '';
            }
        }
        else {
            if ($default) {
                return 'selected';
            }
            else {
                return '';
            }
        }
    }

}


<?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_Core_Stats
{
	private $folder, $files = array ();

	public static function __getInstance ($folder = '')
	{
		static $in;
		if (empty ($in[$folder]))
		{
			$in[$folder] = new Neuron_Core_Stats ($folder);
		}
		return $in[$folder];
	}

	public function __construct ($folder)
	{
		$this->folder = $folder . '/';
	}

	public function get ($key, $groep, $file, $default = null, $race = null)
	{
		if (is_object ($race))
		{
			$race = $race->getName ();
		}

		if ($race != null)
		{
			$file = STATS_DIR . $this->folder . $race . '/' . $file . '.ini';
		}

		else
		{
			$file = STATS_DIR . $this->folder . $file . '.ini';
		}

		if (!isset ($this->files[$file]))
		{
			$this->loadFile ($file);
		}

		if (isset ($this->files[$file][$groep][$key]))
		{
			return $this->files[$file][$groep][$key];
		}

		else
		{
			// Return value
			if ($race != null)
			{
				return $this->get ($key, $groep, $file, null, $default);
			}

			else
			{
				return $default;
			}
		}
	}

	/*
		Backwards comptability
	*/
	public function getSection ($groep, $file)
	{
		return $this->getGroup ($groep, $file);
	}

	public function getGroup ($groep, $orgFile, $default = array (), $race = null)
	{
		if (is_object ($race))
		{
			$race = $race->getName ();
		}

		if ($race != null)
		{
			$file = STATS_DIR . $this->folder . '/'. $race . '/' . $orgFile . '.ini';
		}

		else
		{
			$file = STATS_DIR . $this->folder . '/'. $orgFile . '.ini';
		}

		if (!isset ($this->files[$file]))
		{
			$this->loadFile ($file);
		}

		if (isset ($this->files[$file][$groep]) && is_array ($this->files[$file][$groep]))
		{
			foreach ($this->files[$file][$groep] as $k => $v)
			{
				if (!empty ($v))
				{
					return $this->files[$file][$groep];
				}
			}
		}

		else
		{
			// Return value
			if ($race != null)
			{
				return $this->getGroup ($groep, $orgFile, null, $default);
			}

			else
			{
				return $default;
			}
		}
	}

	/*
		Simply returns the whole file:
		$return[$section][$id] = $value
	*/
	public function getFile ($orgFile, $default = array (), $race = null)
	{
		if (is_object ($race))
		{
			$race = $race->getName ();
		}

		if ($race != null)
		{
			$file = STATS_DIR . $this->folder . '/'. $race . '/' . $orgFile . '.ini';
		}

		else
		{
			$file = STATS_DIR . $this->folder . '/'. $orgFile . '.ini';
		}

		if (!isset ($this->files[$file]))
		{
			$this->loadFile ($file);
		}

		if (isset ($this->files[$file]) && is_array ($this->files[$file]))
		{
			return $this->files[$file];
		}

		else
		{
			// Return value
			if ($race != null)
			{
				return $this->getFile ($groep, $orgFile, $default);
			}

			else
			{
				return $default;
			}
		}
	}

	private function loadFile ($file)
	{
		if (file_exists ($file))
		{
			$this->files[$file] = parse_ini_file ($file, true);
		}

		else
		{
			$this->files[$file] = false;
		}
	}
}
?>


<?php

namespace DreamFactory\Core\Email\Models;

class MandrillConfig extends CloudEmailConfig
{
    protected $fillable = [
        'service_id',
        'key',
        'parameters'
    ];

    protected $rules = ['key' => 'required'];

    /**
     * {@inheritdoc}
     */
    public static function getConfigSchema()
    {
        $schema = parent::getConfigSchema();
        $out = [];
        foreach ($schema as $key => $field) {
            if ($field['name'] === 'key' || $field['name'] === 'parameters') {
                $out[] = $schema[$key];
            }
        }

        return $out;
    }

    /**
     * @param array $schema
     */
    protected static function prepareConfigSchemaField(array &$schema)
    {
        parent::prepareConfigSchemaField($schema);

        switch ($schema['name']) {
            case 'key':
                $schema['label'] = 'API Key';
                $schema['description'] = 'A Mandrill service API Key.';
                break;
        }
    }
}


<?php

namespace SQRT\QueryBuilder;

use SQRT\QueryBuilder\Condition\Equal;
use SQRT\QueryBuilder\Condition\In;
use SQRT\QueryBuilder\Condition\Between;
use SQRT\QueryBuilder\Condition\Like;
use SQRT\QueryBuilder\Condition\Greater;
use SQRT\QueryBuilder\Condition\Less;
use SQRT\QueryBuilder\Condition\Expr;

class Conditions extends Condition
{
  /** @var Condition[] */
  protected $conditions;
  protected $join_by_and = true;

  /** Условие в виде запроса SQL */
  public function asSQL($force_braces = null)
  {
    $arr = array();
    if ($this->conditions) {
      foreach ($this->conditions as $cond) {
        $arr[] = $cond->asSQL(
          is_null($force_braces)
            ? $cond instanceof Conditions && !$this->join_by_and
            : $force_braces
        );
      }
    }

    return $this->processPieces($arr, $force_braces);
  }

  /** Условие в виде подготовленного выражения с переменными */
  public function asStatement($prefix = null)
  {
    $arr = array();
    if ($this->conditions) {
      foreach ($this->conditions as $cond) {
        $arr[] = $cond->asStatement($prefix);
      }
    }

    return $this->processPieces($arr);
  }

  /** Значения переменных для подстановки в запрос */
  public function getBindedValues($prefix = null)
  {
    $arr = array();
    if ($this->conditions) {
      foreach ($this->conditions as $cond) {
        $vals = $cond->getBindedValues($prefix);
        if (is_array($vals)) {
          $arr = array_merge($vals, $arr);
        }
      }
    }

    return $arr;
  }

  /** Произвольный формат */
  public function mixed($mixed)
  {
    if ($mixed instanceof Condition) {
      $this->add($mixed);
    } elseif (is_array($mixed)) {
      foreach ($mixed as $key => $val) {
        if (is_array($val)) {
          $this->in($key, $val);
        } elseif (is_numeric($key)) {
          $this->expr($val);
        } else {
          $this->equal($key, $val);
        }
      }
    } elseif (is_numeric($mixed)) {
      $this->equal('id', $mixed);
    } else {
      $this->expr($mixed);
    }

    return $this;
  }

  /** Встраивание условия или набора условий */
  public function add(Condition $cond)
  {
    if ($cond instanceof Conditions && !$cond->hasConditions()) {
      return $this;
    }

    $this->conditions[] = $cond;

    return $this;
  }

  public function expr($expr, $values = null)
  {
    $this->conditions[] = new Expr($expr, $values);

    return $this;
  }

  public function equal($column, $value)
  {
    $this->conditions[] = new Equal($column, $value);

    return $this;
  }

  public function notEqual($column, $value)
  {
    $this->conditions[] = new Equal($column, $value, true);

    return $this;
  }

  public function in($column, $array)
  {
    $this->conditions[] = new In($column, $array);

    return $this;
  }

  public function notIn($column, $array)
  {
    $this->conditions[] = new In($column, $array, true);

    return $this;
  }

  public function between($column, $from, $to, $date_format = null)
  {
    $btw = new Between($column, $from, $to);
    if ($date_format) {
      $btw->setDateFormat($date_format);
    }

    $this->conditions[] = $btw;

    return $this;
  }

  public function notBetween($column, $from, $to, $date_format = null)
  {
    $btw = new Between($column, $from, $to, true);
    if ($date_format) {
      $btw->setDateFormat($date_format);
    }

    $this->conditions[] = $btw;

    return $this;
  }

  public function like($column, $expr)
  {
    $this->conditions[] = new Like($column, $expr);

    return $this;
  }

  public function notLike($column, $expr)
  {
    $this->conditions[] = new Like($column, $expr, true);

    return $this;
  }

  public function greater($column, $value)
  {
    $this->conditions[] = new Greater($column, $value);

    return $this;
  }

  public function greaterOrEqual($column, $value)
  {
    $this->conditions[] = new Greater($column, $value, true);

    return $this;
  }

  public function less($column, $value)
  {
    $this->conditions[] = new Less($column, $value);

    return $this;
  }

  public function lessOrEqual($column, $value)
  {
    $this->conditions[] = new Less($column, $value, true);

    return $this;
  }

  public function setJoinByAnd()
  {
    $this->join_by_and = true;

    return $this;
  }

  public function setJoinByOr()
  {
    $this->join_by_and = false;

    return $this;
  }

  /** @return Condition[] */
  public function getConditions()
  {
    return $this->conditions ?: array();
  }

  /** Проверка, есть ли условия */
  public function hasConditions()
  {
    return !empty($this->conditions);
  }

  /** Собираем общую строку из отдельных условий */
  protected function processPieces($arr, $force_braces = null)
  {
    if (empty($arr)) {
      return '';
    }

    $glue   = ' AND ';
    $braces = $force_braces ?: (bool)$this->not;
    if (!$this->join_by_and) {
      $glue   = ' OR ';
      $braces = true;
    }

    $str = join($glue, $arr);

    return ($this->not ? 'NOT ' : '') . ($braces ? '(' . $str . ')' : $str);
  }
}


<?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_Map_Movement
{
	private $startTime;
	private $endTime;

	private $locations;

	private $acceleration = 0;
	private $startSpeed = 0;

	private $startRotation = null;
	private $endRotation = null;

	private $startUp = null;
	private $endUp = null;

	/**
	* A bezier curved movement description
	* @param $startTime: Start timestamp
	* @param $endTime: End timestamp
	* @param $more: locations
	*/
	public function __construct
	(
		$startTime,
		$endTime,
		Neuron_GameServer_Map_Location $l1,
		Neuron_GameServer_Map_Location $l2
	)
	{
		$arguments = func_get_args ();

		$this->setStartTime (array_shift ($arguments));
		$this->setEndTime (array_shift ($arguments));

		$this->setPoints ($arguments);
	}

	protected function setStartTime ($startTime)
	{
		$this->startTime = $startTime;
	}

	protected function setEndTime ($endTime)
	{
		$this->endTime = $endTime;
	}

	protected function setPoints ($arguments)
	{
		if (count ($arguments) < 2)
		{
			throw new Exception ("Path must have at least two points.");
		}
		else if (count ($arguments) > 4)
		{
			throw new Exception ("The maximal amount of points is 4 right now.");
		}

		$this->locations = $arguments;
	}

	public static function getFromPath ($startTime, $endTime, $points)
	{
		$path = array ();
		foreach ($points as $v)
		{
			$path[] = new Neuron_GameServer_Map_Location ($v[0], $v[1], $v[2]);
		}

		if (count ($path) < 2)
		{
			throw new Exception ("Path must have at least two points.");
		}

		else if (count ($path) === 2)
		{
			return new self ($startTime, $endTime, $path[0], $path[1]);
		}

		else if (count ($path) === 3)
		{
			return new self ($startTime, $endTime, $path[0], $path[1], $path[2]);
		}

		else if (count ($path) === 4)
		{
			return new self ($startTime, $endTime, $path[0], $path[1], $path[2], $path[3]);
		}

		else
		{
			throw new Exception ("The maximal amount of points is 4 right now.");
		}
	}

	public function getStartTime ()
	{
		return $this->startTime;
	}

	public function getEndTime ()
	{
		return $this->endTime;
	}

	public function isActive ($time = NOW)
	{
		return $this->startTime <= $time && $this->endTime > $time;
	}

	private function calcPositionFromVelocity ($progress)
	{
		$progress *= $this->getDuration ();
		$speed = $this->calculateSpeed ();
		return (( $speed['start'] * $progress) + (0.5 * $speed['acceleration'] * $progress * $progress)) / $this->getDistance ();
	}

	private function calcPositionFromBezierCurve ($t)
	{
		$u = (1 - $t);

		$location = array (0, 0, 0);
		if (count ($this->locations) == 2)
		{
			for ($i = 0; $i <= 2; $i ++)
			{
				$location[$i] = ($u * $this->locations[0][$i])
					+ ($t * $this->locations[1][$i]);
			}
		}

		else if (count ($this->locations) == 3)
		{
			$uu = $u * $u;
			$tt = $t * $t;

			for ($i = 0; $i <= 2; $i ++)
			{
				$location[$i] = ($uu * $this->locations[0][$i])
					+ (2 * $u * $t * $this->locations[1][$i])
					+ ($tt * $this->locations[2][$i]);
			}
		}

		else if (count ($this->locations) == 4)
		{
			$uu = $u * $u;
			$tt = $t * $t;
			$uuu = $uu * $u;
			$ttt = $tt * $t;

			for ($i = 0; $i <= 2; $i ++)
			{
				$location[$i] = ($uuu * $this->locations[0][$i])
					+ (3 * $uu * $t * $this->locations[1][$i])
					+ (3 * $u * $tt * $this->locations[2][$i])
					+ ($ttt * $this->locations[3][$i]);
			}
		}

		return new Neuron_GameServer_Map_Location ($location[0], $location[1], $location[2]);;
	}

	public function getCurrentLocation ($time = NOW)
	{
		$diff = $this->endTime - $this->startTime;
		$percentage = ($time - $this->startTime) / $diff;

		//customMail ('daedelson@gmail.com', 'coortest', $percentage);
		$percentage = $this->calcPositionFromVelocity ($percentage);

		return $this->calcPositionFromBezierCurve ($percentage);
	}

	public function getCurrentUp ($time = NOW)
	{
		if (isset ($this->startUp) && isset ($this->endUp))
		{
			$diff = $this->endTime - $this->startTime;
			$percentage = ($time - $this->startTime) / $diff;

			$rotation = $this->startUp->transform ($this->endUp->transform ($this->startUp->inverse ())->scale ($percentage));
			return $rotation->normalize ();
		}
		else
		{
			return null;
		}
	}

	public function getCurrentDirection ($time = NOW)
	{
		if (isset ($this->startRotation) && isset ($this->endRotation))
		{
			$diff = $this->endTime - $this->startTime;
			$percentage = ($time - $this->startTime) / $diff;

			$rotation = $this->startRotation->transform ($this->endRotation->transform ($this->startRotation->inverse ())->scale ($percentage));
			return $rotation->normalize ();
		}

		else
		{
			$t1 = $this->getCurrentLocation ($time);
			$t2 = $this->getCurrentLocation ($time + 0.001);

			return $t2->transform ($t1)->normalize ();
		}
	}

	public function getStartLocation ()
	{
		$values = array_values ($this->locations);
		return array_shift ($values);
	}

	public function getEndLocation ()
	{
		$values = array_values ($this->locations);
		return array_pop ($values);
	}

	public function getDuration ()
	{
		return $this->endTime - $this->startTime;
	}

	public function getDistance ()
	{
		// TODO! Fix this, currently we just calculate the distance between the start & end point
		return $this->getEndLocation ()->getDistance ($this->getStartLocation ());
	}

	public function setAcceleration ($startSpeed, $acceleration)
	{
		$this->startSpeed = $startSpeed;
		$this->acceleration = $acceleration;
	}

	public function getInitialSpeed ()
	{
		$a = $this->calculateSpeed ();
		return $a['start'];
	}

	public function getAcceleration ()
	{
		$a = $this->calculateSpeed ();
		return $a['acceleration'];
	}

	/**
	* Return an array of speed & acceleration
	* Speed is defined in pixels / second
	*/
	private function calculateSpeed ()
	{
		$startSpeed;
		$endSpeed;
		$acceleration = 0;

		// Accelerated speed
		if (abs ($this->acceleration) > 0)
		{
			$startSpeed = $this->startSpeed;
			$acceleration = $this->acceleration;
			$endSpeed = $this->startSpeed + ($acceleration * $this->getDuration ());
		}

		// Constant velocity
		else
		{
			$startSpeed = $this->getDistance () / $this->getDuration ();
			$endSpeed = $startSpeed;
		}

		return array
		(
			'start' => $startSpeed,
			'end' => $endSpeed,
			'acceleration' => $acceleration
		);
	}

	public function getPath ()
	{
		$out = array ();

		foreach ($this->locations as $v)
		{
			$out[] = $v->getData (false);
		}

		return $out;
	}

	/**
	* If no rotation is set, object will face in direction of movement
	*/
	public function setDirection (Neuron_GameServer_Map_Vector3 $start, Neuron_GameServer_Map_Vector3 $end)
	{
		$this->startRotation = $start;
		$this->endRotation = $end;
	}

	/**
	* Set "UP" vector that will be interpolated
	*/
	public function setUp (Neuron_GameServer_Map_Vector3 $start, Neuron_GameServer_Map_Vector3 $end)
	{
		$this->startUp = $start->normalize ();
		$this->endUp = $end->normalize ();
	}

	public function getStartUp ()
	{
		return $this->startUp;
	}

	public function getEndUp ()
	{
		return $this->endUp;
	}

	public function getData ()
	{
		$out = array ();

		$out['attributes'] = array
		(
			'duration' => $this->getDuration (),
			'distance' => $this->getDistance ()
		);

		$start = $this->getStartLocation ()->getData ();
		$start['timestamp'] = $this->getStartTime ();

		$end = $this->getEndLocation ()->getData ();
		$end['timestamp'] = $this->getEndTime ();

		$out['start'] = array  ( 'attributes' => $start );
		$out['end'] = array ( 'attributes' => $end );

		$path = array ();
		foreach ($this->locations as $v)
		{
			$path[] = array ('attributes' => $v->getData (true));
		}

		$out['points'] = $path;

		$out['velocity'] = array
		(
			'attributes' => $this->calculateSpeed ()
		);

		if (isset ($this->startRotation) && isset ($this->endRotation))
		{
			$out['diration'] = array
			(
				'start' => array ('attributes' => $this->startRotation->getData ()),
				'end' => array ('attributes' => $this->startRotation->getData ())
			);
		}

		if (isset ($this->startUp) && isset ($this->endUp))
		{
			$out['up'] = array
			(
				'start' => array ('attributes' => $this->startUp->getData ()),
				'end' => array ('attributes' => $this->endUp->getData ())
			);
		}

		return $out;
	}
}


<?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_LogSerializer
{
	public static function encode ($data)
	{
		// Collect thze data
		$out = array ();
		foreach ($data as $v)
		{
			if (is_object ($v))
			{
				if ($v instanceof Neuron_GameServer_Interfaces_Logable)
				{
					$out[] = self::getClassId ($v).':'.$v->getId();
				}
				else
				{
					$out[] = 'unknown';
				}
			}
			else
			{
				$out[] = $v;
			}
		}

		return json_encode ($out);
	}

	public static function decode ($sData)
	{
		if (is_array ($sData))
		{
			$data = json_decode ($sData['l_data'], true);
		}

		elseif (empty ($sData))
		{
			$data = array ();
		}
		else
		{
			$data = json_decode ($sData, true);
		}

		$out = array ();

		if (!is_array ($data))
		{
			throw new Neuron_Core_Error ('getObjectsFromLog expects an array.');
		}

		foreach ($data as $v)
		{
			$classn = explode (':', $v);

			if (count ($classn) >= 2)
			{
				$class = self::getClassName ($classn[0]);

				if ($class)
				{
					array_shift ($classn);
					$object = call_user_func (array ($class, 'getFromId'), implode (':', $classn));
					$out[] = $object;
				}
				else
				{
					$out[] = null;
				}
			}
			else
			{
				$out[] = $v;
			}
		}

		return $out;
	}

	private static function & getClasses ($reload = false)
	{
		static $classes;

		// Check if this log is found
		if (!isset ($classes) || $reload)
		{
			$classes = array ();

			// Load the classnames
			$db = Neuron_DB_Database::__getInstance ();

			$data = $db->query
			("
				SELECT
					*
				FROM
					n_logables
			");

			$classes['names'] = array ();
			$classes['ids'] = array ();

			// Put them in thze array
			foreach ($data as $v)
			{
				$classes['names'][$v['l_name']] = $v['l_id'];
				$classes['ids'][$v['l_id']] = $v['l_name'];
			}
		}

		return $classes;
	}

	/*
		Get classname ID
	*/
	private static function getClassId ($object)
	{
		$name = get_class ($object);

		$classes = self::getClasses ();

		$classnames = $classes['names'];

		// Check if isset!
		if (!isset ($classnames[$name]))
		{
			// Insert a new ID
			$db = Neuron_DB_Database::__getInstance ();

			$db->query
			("
				INSERT INTO
					n_logables
				SET
					l_name = '".$name."'
			");

			/*
			$id = $db->getInsertId ();

			$classes['names'][$name] = $id;
			$classes['ids'][$id] = $name;
			*/

			$classes = self::getClasses (true);
		}

		return $classes['names'][$name];
	}

	private static function getClassName ($id)
	{
		$classes = self::getClasses ();

		if (isset ($classes['ids'][$id]))
		{
			return $classes['ids'][$id];
		}
		return false;
	}
}
?>


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

namespace Wakers\StructureModule\Component\Frontend\RecipeSummaryModal;

use Wakers\BaseModule\Component\Frontend\BaseControl;
use Wakers\StructureModule\Repository\RecipeRepository;

class RecipeSummaryModal extends BaseControl
{
    /**
     * @var RecipeRepository
     */
    protected $recipeRepository;

    /**
     * RecipeSummaryModal constructor.
     * @param RecipeRepository $recipeRepository
     */
    public function __construct(RecipeRepository $recipeRepository)
    {
        $this->recipeRepository = $recipeRepository;
    }

    /**
     * Render
     */
    public function render() : void
    {
        $this->template->recipes = $this->recipeRepository->findAllJoinVariables();
        $this->template->setFile(__DIR__ . '/templates/recipeSummaryModal.latte');
        $this->template->render();
    }
}


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

namespace Wakers\StructureModule\Component\Frontend\RecipeRemoveModal;

use Wakers\BaseModule\Component\Frontend\BaseControl;
use Wakers\StructureModule\Database\Recipe;
use Wakers\StructureModule\Manager\RecipeManager;
use Wakers\StructureModule\Repository\RecipeRepository;
use Wakers\StructureModule\Security\StructureAuthorizator;

class RecipeRemoveModal extends BaseControl
{
    /**
     * @var RecipeRepository
     */
    protected $recipeRepository;

    /**
     * @var RecipeManager
     */
    protected $recipeManager;

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

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

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

    /**
     * RecipeRemoveModal constructor.
     * @param RecipeRepository $recipeRepository
     * @param RecipeManager $recipeManager
     */
    public function __construct(RecipeRepository $recipeRepository, RecipeManager $recipeManager)
    {
        $this->recipeRepository = $recipeRepository;
        $this->recipeManager = $recipeManager;
    }

    /**
     * Render
     */
    public function render() : void
    {
        $this->template->recipe = $this->recipeEntity;
        $this->template->setFile(__DIR__.'/templates/recipeRemoveModal.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->recipeEntity = $this->recipeRepository->findOneById($id);

            $this->presenter->handleModalToggle('show', '#wakers_structure_recipe_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_RECIPE_REMOVE_MODAL))
        {
            $this->recipeEntity = $this->recipeRepository->findOneById($id);

            $this->recipeManager->delete($this->recipeEntity);

            $this->presenter->notificationAjax(
                'Předpis odstaněn.',
                "Předpis '{$this->recipeEntity->getName()}' byl úspěšně odstraněn.",
                'success',
                FALSE
            );

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

            $this->onRemove();
        }
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Migration\Repository;

use PDO;
use Roquie\Database\Migration\Exception\InvalidArgumentException;

class SqlMigrationRepository implements MigrationRepositoryInterface
{
    /**
     * @var \PDO
     */
    private $pdo;

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

    /**
     * SqlMigrationRepository constructor.
     *
     * @param \PDO $pdo
     * @param $table
     */
    public function __construct(PDO $pdo, string $table)
    {
        $this->pdo = $pdo;
        $this->table = $table;
    }

    /**
     * @param string|null $query
     */
    public function execute(?string $query): void
    {
        if (is_null($query)) {
            return;
        }

        $this->pdo->exec($query);
    }

    /**
     * Get the completed migrations.
     *
     * @return array
     */
    public function getRan(): array
    {
        $stmt = $this->pdo->query("select migration from {$this->table} order by batch, migration");
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_COLUMN);

        return $results;
    }

    /**
     * Get list of migrations.
     *
     * @param  int $steps
     * @return array
     */
    public function getMigrations(int $steps): array
    {
        $sql = "select migration from {$this->table}
                where batch >= 1
                order by batch, migration desc
                limit ?";

        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam(1, $steps, PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }

    /**
     * Get the last migration batch.
     *
     * @return array
     */
    public function getLast(): array
    {
        $sql = "select migration from {$this->table} as b
                where exists (select max(batch) from {$this->table} as a where b.batch = a.batch)
                order by migration desc";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }

    /**
     * Get the completed migrations with their batch numbers.
     *
     * @return array
     */
    public function getMigrationBatches(): array
    {
        $stmt = $this->pdo->prepare("select * from {$this->table} order by batch, migration");
        $stmt->execute();

        $array = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $item) {
            $array[$item['migration']] = $item['batch'];
        }

        return $array;
    }

    /**
     * Log that a migration was run.
     *
     * @param  string $file
     * @param  int $batch
     * @return void
     */
    public function log(string $file, int $batch): void
    {
        $stmt = $this->pdo->prepare("insert into {$this->table} (migration, batch) values (?, ?)");
        $stmt->bindParam(1, $file);
        $stmt->bindParam(2, $batch, PDO::PARAM_INT);
        $stmt->execute();
    }

    /**
     * Remove a migration from the log.
     *
     * @param  string $migration
     * @return void
     */
    public function delete(string $migration): void
    {
        $stmt = $this->pdo->prepare("delete from {$this->table} where migration = ?");
        $stmt->bindParam(1, $migration);
        $stmt->execute();
    }

    /**
     * Get the next migration batch number.
     *
     * @return int
     */
    public function getNextBatchNumber(): int
    {
        return $this->getLastBatchNumber() + 1;
    }

    /**
     * Get the last migration batch number.
     *
     * @return int
     */
    public function getLastBatchNumber(): int
    {
        $stmt = $this->pdo->query("select max(batch) from {$this->table}");
        $stmt->execute();

        return (int) $stmt->fetch(PDO::FETCH_ASSOC)['max'];
    }

    /**
     * Create the migration repository data store.
     *
     * @return void
     */
    public function createRepository(): void
    {
        $sql = "CREATE TABLE {$this->table} (
                    migration Character Varying (255) NOT NULL,
                    batch Integer NOT NULL
                );";

        $this->pdo->exec($sql);
    }

    /**
     * Determine if the migration repository exists.
     *
     * @return bool
     */
    public function repositoryExists(): bool
    {
        switch ($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) {
            case 'pgsql':
                $sql = 'select count(*) from information_schema.tables
                        where table_schema = current_schema()
                        and table_name = ?';
                break;
            case 'mysql':
                $sql = 'select count(*) from information_schema.tables
                        where table_schema = database()
                        and table_name = ?';
                break;
            case 'sqlsrv':
                $sql = "select count(*) from sysobjects where type = 'U' and name = ?";
                break;
            case 'sqlite':
                $sql = "select count(*) from sqlite_master where type = 'table' and name = ?";
                break;
            default:
                throw InvalidArgumentException::forDatabaseNotSupported();
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam(1, $this->table);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_COLUMN) > 0;
    }

    /**
     * Wraps the queries inside callback into transaction.
     *
     * @param callable $callback
     * @return void
     */
    public function transaction(callable $callback): void
    {
        $this->pdo->beginTransaction();
        $callback($this);
        $this->pdo->commit();
    }

    /**
     * Drop all views and tables.
     */
    public function drop(): array
    {
        $touched = [];
        $this->pdo->beginTransaction();

        foreach ($this->getViews() as $view) {
            $this->pdo->exec("drop view if exists {$view} cascade");
            $touched[] = ['view', $view];
        }

        foreach ($this->getTables() as $table) {
            $this->pdo->exec("drop table if exists {$table} cascade");
            $touched[] = ['table', $table];
        }

        $this->pdo->commit();

        return $touched;
    }

    /**
     * @return array
     * @throws \Roquie\Database\Migration\Exception\InvalidArgumentException
     */
    private function getTables(): array
    {
        switch ($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) {
            case 'pgsql':
                $sql = 'select table_name from information_schema.tables where table_schema = current_schema()';
                break;
            case 'mysql':
                $sql = 'select table_name from information_schema.tables where table_schema = database()';
                break;
            case 'sqlsrv':
                $sql = "select name from sysobjects where type = 'U'";
                break;
            case 'sqlite':
                $sql = "select name from sqlite_master where type = 'table'";
                break;
            default:
                throw InvalidArgumentException::forDatabaseNotSupported();
        }

        return $this->pdo
            ->query($sql)
            ->fetchAll(PDO::FETCH_COLUMN);
    }

    /**
     * @return array
     * @throws \Roquie\Database\Migration\Exception\InvalidArgumentException
     */
    private function getViews(): array
    {
        switch ($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) {
            case 'pgsql':
                $sql = 'select table_name from information_schema.views where table_schema = current_schema()';
                break;
            case 'mysql':
                // TODO mysql not tested
                $sql = 'select table_name from information_schema.views where table_schema = database()';
                break;
            case 'sqlsrv':
                // TODO sqlsrv not tested
                $sql = "select name from sysobjects where type = 'v'";
                break;
            case 'sqlite':
                // TODO sqlite not tested
                $sql = "select name from sqlite_master where type = 'view'";
                break;
            default:
                throw InvalidArgumentException::forDatabaseNotSupported();
        }

        return $this->pdo
            ->query($sql)
            ->fetchAll(PDO::FETCH_COLUMN);
    }

    /**
     * Close database connection.
     *
     * @return void
     */
    public function close(): void
    {
        $this->pdo = null;
    }
}