<?php

namespace UWDOEM\Person;

use UWDOEM\Connection\Connection;

/**
 * Container class for data received from Person Web Service and Student Web Service
 *
 * @package UWDOEM\Person
 */
class Person
{

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

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

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

    /** @var \UWDOEM\Connection\Connection */
    protected static $personConnection;

    /** @var \UWDOEM\Connection\Connection */
    protected static $studentConnection;

    /** @var string */
    protected static $AFFILIATION_TYPE = "person";

    /**
     * Sets a value on your LOCAL COPY of the person.
     *
     * SWS/PWS do not support UPDATING person/student models.
     * @param string $key
     * @param mixed  $value
     * @return void
     */
    public function setAttr($key, $value)
    {
        $this->attrs[$key] = $value;
    }

    /**
     * Gets a value from your local copy of the person.
     *
     * @param string $key
     * @return mixed
     */
    public function getAttr($key)
    {
        return $this->attrs[$key];
    }

    /**
     * Returns whether the given person has the given affiliation.
     *
     * @param string $affiliation
     * @return boolean
     */
    public function hasAffiliation($affiliation)
    {
        return in_array($affiliation, $this->affiliations);
    }

    /**
     * Returns an arry of the affiliate's attributes.
     *
     * @return array
     */
    public function getAttrs()
    {
        return $this->attrs;
    }

    /**
     * Queries PWS/SWS to generate a Person, given a UWNetID.
     * @param string $uwnetid
     * @return null|Person
     */
    public static function fromUWNetID($uwnetid)
    {
        return static::fromIdentifier("uwnetid", $uwnetid);
    }

    /**
     * Queries PWS/SWS to generate a Person, given a UWRegID.
     *
     * @param string $uwregid
     * @return null|Person
     */
    public static function fromUWRegID($uwregid)
    {
        return static::fromIdentifier("uwregid", $uwregid);
    }

    /**
     * Queries PWS/SWS to generate a Person, given an identifier type and value.
     *
     * Identifier type must be one of ["uwregid", "uwnetid", "employee_id", "student_number",
     *                                 "student_system_key", "development_id"].
     *
     * @param string $identifierKey
     * @param string $identifierValue
     * @return null|Person
     * @throws \Exception If $identifierKey is not one of ["uwregid", "uwnetid", "employee_id",
     *                                                     "student_number", "student_system_key",
     *                                                     "development_id"].
     */
    public static function fromIdentifier($identifierKey, $identifierValue)
    {
        /** @var null|Person $person */
        $person = null;

        /** @var string $simpleIdentifier */
        $simpleIdentifier = "";

        /** @var string[] $validIdentifierKeys */
        $validIdentifierKeys = [
            "uwregid", "uwnetid", "employee_id", "student_number", "student_system_key", "development_id"
        ];

        /** @var string[] $simpleIdentifierKeys */
        $simpleIdentifierKeys = ["uwregid", "uwnetid"];

        /** @var boolean $identifierKeyIsValid */
        $identifierKeyIsValid = in_array($identifierKey, $validIdentifierKeys);

        /** @var boolean $identifierKeyIsSimple */
        $identifierKeyIsSimple = in_array($identifierKey, $simpleIdentifierKeys);

        if ($identifierKeyIsValid === false) {
            throw new \Exception(
                "Identifier key '$identifierKey' must be one of [" . implode(", ", $validIdentifierKeys) . "]."
            );
        }

        if ($identifierKeyIsSimple === true) {
            $simpleIdentifier = $identifierValue;
        } else {
            $resp = static::getPersonConnection()->execGET(
                "person.json?$identifierKey=$identifierValue"
            );
            $resp = static::parse($resp->getData());

            if (array_key_exists("Persons", $resp) === true && sizeof($resp["Persons"]) > 0) {
                $simpleIdentifier = $resp["Persons"][0]["PersonFullURI"]["UWNetID"];
            }
        }

        if ($simpleIdentifier !== "") {
            $resp = static::getPersonConnection()->execGET(
                "person/$simpleIdentifier/full.json"
            );
            $resp = static::parse($resp->getData());

            if (array_key_exists("UWRegID", $resp) === true) {
                $person = new static();
                $person = static::fill($person, $resp);
            }
        }

        return $person;
    }

    /**
     * Casts one subclass of Person into another.
     *
     * Ex:
     * $p = Person::fromUWNetId($uwnetid); // $p is a Person
     * $p = Employee::fromPerson($p); // $p is now cast into an employee
     *
     * @param Person $oldPerson
     * @return Person
     */
    public static function fromPerson(Person $oldPerson)
    {
        $newPerson = new static();
        return static::fill($newPerson, $oldPerson->raw);
    }

    /**
     * @param Person $person
     * @param array  $attrs
     * @return Person
     */
    protected static function fill(Person $person, array $attrs)
    {
        $person->raw = $attrs;
        $person->affiliations = $attrs["EduPersonAffiliations"];

        foreach ($attrs as $key => $value) {
            if (is_string($value) === true || is_bool($value) === true || $value === null) {
                $person->setAttr($key, $value);
            }
        }

        return $person;
    }

    /**
     * @param string $baseUrl
     * @return Connection
     * @throws \Exception If any of the required constants have not been set.
     */
    protected static function makeConnection($baseUrl)
    {
        $requiredConstants = ["UW_WS_BASE_PATH", "UW_WS_SSL_KEY_PATH", "UW_WS_SSL_CERT_PATH", "UW_WS_SSL_KEY_PASSWD"];

        foreach ($requiredConstants as $constant) {
            if (defined($constant) === false) {
                throw new \Exception("You must define the constant $constant before using this library.");
            }
        }

        $user = $_SERVER['REMOTE_USER'];

        return new Connection(
            UW_WS_BASE_PATH . $baseUrl,
            UW_WS_SSL_KEY_PATH,
            UW_WS_SSL_CERT_PATH,
            UW_WS_SSL_KEY_PASSWD,
            defined("UW_WS_VERBOSE") && UW_WS_VERBOSE,
            [CURLOPT_HTTPHEADER => ["X-UW-ACT-AS: $user"]]
        );
    }

    /**
     * @return Connection
     */
    protected static function getPersonConnection()
    {
        if (static::$personConnection === null) {
            static::$personConnection = static::makeConnection("identity/v1/");
        }
        return static::$personConnection;
    }

    /**
     * @return Connection
     */
    protected static function getStudentConnection()
    {
        if (static::$studentConnection === null) {
            static::$studentConnection = static::makeConnection("student/v5/");
        }
        return static::$studentConnection;
    }

    /**
     * @param string $resp
     * @return array
     */
    protected static function parse($resp)
    {
        return Parser::parse($resp);
    }
}


<?php

namespace Tree6bee\Queue\Drivers\Jobs;

use Pheanstalk\PheanstalkInterface;
use Pheanstalk\Job as PheanstalkJob;

class BeanstalkdJob implements JobInterface
{
    /**
     * @var PheanstalkInterface
     */
    protected $pheanstalk;

    /**
     * @var PheanstalkJob
     */
    protected $job;

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

    public function __construct(PheanstalkInterface $pheanstalk, PheanstalkJob $job, $queue)
    {
        $this->pheanstalk = $pheanstalk;
        $this->job = $job;
        $this->queue = $queue;
    }

    /**
     * Get the raw body string for the job.
     *
     * @return string
     */
    public function getRawBody()
    {
        return $this->job->getData();
    }

    /**
     * Delete the job from the queue.
     *
     * @return void
     */
    public function delete()
    {
        $this->pheanstalk->delete($this->job);
    }

    /**
     * Release the job back into the queue.
     *
     * @param  int   $delay
     * @return void
     */
    public function release($delay = PheanstalkInterface::DEFAULT_DELAY)
    {
        $this->pheanstalk->release($this->job, PheanstalkInterface::DEFAULT_PRIORITY, $delay);
    }

    /**
     * Bury the job in the queue.
     *
     * @return void
     */
    public function bury()
    {
        $this->pheanstalk->bury($this->job);
    }

    /**
     * Get the number of times the job has been attempted.
     *
     * @return int
     */
    public function attempts()
    {
        $stats = $this->pheanstalk->statsJob($this->job);

        return (int) $stats->reserves;
    }

    /**
     * Get the job identifier.
     *
     * @return string
     */
    public function getJobId()
    {
        return $this->job->getId();
    }

    /**
     * Get the underlying Pheanstalk instance.
     *
     * @return PheanstalkInterface
     */
    public function getPheanstalk()
    {
        return $this->pheanstalk;
    }

    /**
     * Get the underlying Pheanstalk job.
     *
     * @return \Pheanstalk\Job
     */
    public function getPheanstalkJob()
    {
        return $this->job;
    }
}


<?php

/*

  usage sample:
  include_once 'bin/app_init.php';
  $svcobj = Openbizx::getObject('service.compileService');
  $svcobj->compile("document.do.DocumentDO",'Obj');

 */

namespace Openbizx\Service;

use Openbizx\Object\ObjectFactoryHelper;

class compileService
{

    protected $objTemplateData;
    protected $xmlTemplateData;

    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
    }

    protected function readMetadata(&$xmlArr)
    {
        $this->objTemplateData = $xmlArr["PLUGINSERVICE"]["OBJLOADERTEMPLATE"]["VALUE"];
        $this->xmlTemplateData = $xmlArr["PLUGINSERVICE"]["XMLLOADERTEMPLATE"]["VALUE"];
    }

    public function compile($objName, $type)
    {
        switch (strtoupper($type)) {
            case 'XML':
                $template = $this->xmlTemplateData;
                break;
            default:
            case 'OBJ':
                $template = $this->objTemplateData;
                break;
        }
        $this->_doCompile($objName, $template);
    }

    private function _doCompile($objName, $template)
    {
        $xmlArr = $this->getMetadataArray($objName);
        $xmlArrStr = serialize($xmlArr);
        $objNameNew = str_replace(".", "_", $objName);
        $xmlArrCode = $this->encode($xmlArrStr, $objNameNew);

        $output = str_replace("{\$className}", $objNameNew, $template);
        $output = str_replace("{\$metadata}", $xmlArrCode, $output);

        $xmlFile = ObjectFactoryHelper::getXmlFileWithPath($objName);
        $xmlCmpFile = $xmlFile . ".php";
        return file_put_contents($xmlCmpFile, $output);
    }

    public function encode($str, $key)
    {
        return base64_encode(base64_encode($str));
    }

    public function decode($str, $key)
    {
        return base64_decode(base64_decode($str));
    }

    /*
      public function encode($str,$key) {
      $td = mcrypt_module_open('twofish', '', 'ecb', '');
      $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
      $ks = mcrypt_enc_get_key_size($td);
      $keystr = substr(md5($key), 0, $ks);
      mcrypt_generic_init($td, $keystr, $iv);
      $encrypted = mcrypt_generic($td, $str);
      mcrypt_module_close($td);
      $hexdata = bin2hex($encrypted);
      return $hexdata;
      }

      public function decode($str,$key) {
      $td = mcrypt_module_open('twofish', '', 'ecb', '');
      $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
      $ks = mcrypt_enc_get_key_size($td);
      $keystr = substr(md5($key), 0, $ks);
      mcrypt_generic_init($td, $keystr, $iv);
      $encrypted = pack( "H*", $str);
      $decrypted = mdecrypt_generic($td, $encrypted);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
      return $decrypted;
      }
     */

    private function getMetadataArray($objName)
    {
        $xmlFile = ObjectFactoryHelper::getXmlFileWithPath($objName);
        if (!$xmlFile) {
            $dotPos = strrpos($objName, ".");
            $package = $dotPos > 0 ? substr($objName, 0, $dotPos) : null;
            $class = $dotPos > 0 ? substr($objName, $dotPos + 1) : $objName;
        } else {
            $xmlArr = ObjectFactoryHelper::getXmlArray($xmlFile);
        }

        if ($xmlArr) {
            $keys = array_keys($xmlArr);
            $root = $keys[0];

            // add by mr_a_ton , atrubut name must match with object name
            $dotPos = strrpos($objName, ".");
            $shortObjectName = $dotPos > 0 ? substr($objName, $dotPos + 1) : $objName;
            if ($xmlArr[$root]["ATTRIBUTES"]["NAME"] == "") {
                $xmlArr[$root]["ATTRIBUTES"]["NAME"] = $shortObjectName;
            } else {
                if ($shortObjectName != $xmlArr[$root]["ATTRIBUTES"]["NAME"]) {
                    trigger_error("Metadata file parsing error for object $objName. Name attribut [" . $xmlArr[$root]["ATTRIBUTES"]["NAME"] . "] not same with object name. Please double check your metadata xml file again.", E_USER_ERROR);
                }
            }

            //$package = $xmlArr[$root]["ATTRIBUTES"]["PACKAGE"];
            $class = $xmlArr[$root]["ATTRIBUTES"]["CLASS"];
            // if class has package name as prefix, change the package to the prefix
            $dotPos = strrpos($class, ".");
            $classPrefix = $dotPos > 0 ? substr($class, 0, $dotPos) : null;
            $classPackage = $classPrefix ? $classPrefix : null;
            if ($classPrefix) {
                $class = substr($class, $dotPos + 1);
            }
            // set object package
            $dotPos = strrpos($objName, ".");
            $package = $dotPos > 0 ? substr($objName, 0, $dotPos) : null;
            if (!$classPackage) {
                $classPackage = $package;
            }
            $xmlArr[$root]["ATTRIBUTES"]["PACKAGE"] = $package;
            return $xmlArr;
        }
        return;
    }

}

?>


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

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;

//include_once("OptionElement.php");

/**
 * ColumnList class is element that show description from "Selection.xml" on column/table view
 *
 * @package openbiz.bin.easy.element
 * @author Agus Suhartono, Rocky Swen (original ListBox and ColumnText author)
 * @copyright Copyright (c) 2009
 * @access public
 */
class ColumnList extends OptionElement
{
    public $sortable;
    public $columnStyle;

    /**
     * Read metadata info from metadata array and store to class variable
     *
     * @param array $xmlArr metadata array
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->sortable = isset($xmlArr["ATTRIBUTES"]["SORTABLE"]) ? $xmlArr["ATTRIBUTES"]["SORTABLE"] : null;
        $this->link = isset($xmlArr["ATTRIBUTES"]["LINK"]) ? $xmlArr["ATTRIBUTES"]["LINK"] : null;
        $this->columnStyle = $this->style;
    }

    /**
     * set the sort flag of the element
     *
     * @param integer $flag 1 or 0
     * @return void
     */
    public function setSortFlag($flag=null)
    {
        $this->sortFlag = $flag;
    }

    /**
     * Get link that evaluated by Expression::evaluateExpression
     *
     * @return string link
     */
    protected function getLink()
    {
        if ($this->link == null)
            return null;
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->link, $formobj);
    }

    /**
     * When render table, it return the table header; when render array, it return the display name
     *
     * @return string HTML text
     */
   public function renderLabel()
    {
        if ($this->sortable == "Y")
        {
            $rule = $this->objectName;

            $function = $this->formName . ".SortRecord($rule,$this->sortFlag)";
            if($this->sortFlag == "ASC" || $this->sortFlag == "DESC"){
            	$class=" class=\"current\" ";
            }else{
            	$class=" class=\"normal\" ";
            }
            if ($this->sortFlag == "ASC")
            	$span_class = " class=\"sort_up\" ";
            else if ($this->sortFlag == "DESC")
                $span_class = " class=\"sort_down\" ";
            $sHTML = "" . $this->label ."";
            $sHTML .= "";
        }
        else
        {
            $sHTML = $this->label;
        }
        return $sHTML;
    }

    /**
     * Draw/Render the element to show description
     *
     * @return string HTML text
     */
    public function render()
    {
        $fromList   = array();
        $this->getFromList($fromList);
        $value_arr  = explode(',', $this->value);
        $style      = $this->getStyle();
        $func       = $this->getFunction();

        $selectedStr = '';

        $selectedStr = $this->value;

        foreach ($fromList as $opt)
        {
            $test = array_search($opt['val'], $value_arr);
            if (!($test === false))
            {
                $selectedStr = $opt['txt'] ;
                break;
            }
        }

        if ($this->link)
        {
            $link = $this->getLink();
            $sHTML = "" . $selectedStr . "";
        }
        else
            $sHTML = "" . $selectedStr . "";

        return $sHTML;
    }
}

?>


<?php
/**
 * Created by PhpStorm.
 * User: tamaskovacs
 * Date: 2017. 01. 14.
 * Time: 16:32
 */

namespace Callisto;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

abstract class Stream extends Psr7Stream
{
	/**
	 * Streaming API base URL.
	 */
	const BASE_URL = 'https://stream.twitter.com';

	/**
	 * @var Oauth
	 */
	protected $oauth;

	/**
	 * Streaming endpoint.
	 *
	 * @var string
	 */
	protected $endpoint = '';

	/**
	 * Http method to use when connecting to the streaming API.
	 *
	 * @var string
	 */
	protected $httpMethod = 'GET';

	/**
	 * @var LoggerInterface
	 */
	protected $logger;

	/**
	 * Parameters to use to filter the statuses.
	 *
	 * @var \Callisto\RequestParameter[]
	 */
	protected $requestParameters = [];

	/**
	 * Stream constructor.
	 *
	 * @param Oauth $oauth
	 */
	public function __construct(Oauth $oauth)
	{
		$this->oauth = $oauth;
		$this->logger = new NullLogger();
	}

	/**
	 * Opens a connection to the Twitter Streaming API.
	 */
	public function connect() : void
	{
		if (is_resource($this->connection)) {
			$this->logger->info('Connection already opened.');
			return;
		}

		$this->logger->info('Opening new connection.');

		$request = $this->oauth->getOauthRequest(
			$this->getParams(),
			$this->httpMethod,
			self::BASE_URL,
			$this->endpoint
		);

		$this->connection = fsockopen('ssl://stream.twitter.com', 443);
		stream_set_blocking($this->connection, true);
		$this->write($request);

		$response = [];
		while (!$this->eof()) {
			$line = trim((string)$this->readLine());
			if (empty($line)) {
				break;
			}

			$response[] = $line;
		}

		$this->checkResponseStatusCode($response[0]);

		$this->logger->info('Connection successful.', $response);
	}

	/**
	 * Checks the HTTP response code recieved from the server.
	 *
	 * @param string $response
	 * @throws Exception\ConnectionException If the response code different than 200.
	 */
	protected function checkResponseStatusCode($response)
	{
		preg_match('/^HTTP\/1\.1 ([0-9]{3}).*$/', $response, $matches);
		if (200 !== (int)$matches[1]) {
			$this->logger->critical('Connection error', [$response]);
			throw new Exception\ConnectionException('Connection error: ' . $response);
		}
	}

	/**
	 * Returns the parameters to use in the request.
	 *
	 * @return array
	 */
	protected function getParams() : array
	{
		$return = [
			'stall_warnings' => 'true'
		];

		foreach ($this->requestParameters as $filter) {
			$return[$filter->getKey()] = $filter->getValue();
		}

		return $return;
	}

	/**
	 * Sets the filters to use in the request.
	 *
	 * @param RequestParameter[] $requestParameters
	 * @return $this Fluent interface.
	 */
	public function setRequestParameters($requestParameters)
	{
		$this->requestParameters = $requestParameters;
		return $this;
	}

	/**
	 * Handles the message from twitter.
	 *
	 * @param string $messageJson
	 */
	protected function handleMessage(string $messageJson) : void
	{
		$message = json_decode($messageJson);
		$this->logger->info('Message received', [$message]);
	}

	/**
	 * Determines if the received json is a message from twitter.
	 *
	 * @param string $status
	 * @return bool
	 */
	private function isMessage(string $status) : bool
	{
		$testStr = substr($status, 0, 14);
		if ('{"created_at":' == $testStr) {
			return false;
		}

		return true;
	}

	/**
	 * Override the default NullLogger
	 *
	 * @param LoggerInterface $logger
	 * @return Stream $this Fluent interface.
	 */
	public function setLogger(LoggerInterface $logger) : Stream
	{
		$this->logger = $logger;
		return $this;
	}

	/**
	 * Reads the next chunk of $chunkSize from the stream.
	 *
	 * @param int $chunkSize
	 * @return string
	 */
	protected function readChunk(int $chunkSize) : string
	{
		return $this->read($chunkSize);
	}

	/**
	 * Reads the size of the next chunk from the stream.
	 *
	 * @return int
	 * @throws Exception\ConnectionClosedException
	 */
	protected function readNextChunkSize() : int
	{
		while (!$this->eof()) {
			$line = trim($this->readLine());

			if (!empty($line)) {
				$chunkSize = hexdec($line);
				return (int)$chunkSize;
			}
		}

		$this->logger->error('Connection closed.');
		throw new Exception\ConnectionClosedException('Connection closed.');
	}

	/**
	 * Connects to the Twitter API and starts reading the stream.
	 *
	 * When it recieves a new status it will be passed on to the @link self::enqueueStatus() method.
	 *
	 * @return \Generator
	 */
	public function readStream() : \Generator
	{
		$this->connect();

		$status = '';
		while (!$this->eof()) {
			$chunkSize = $this->readNextChunkSize();

			if ($this->isEmptyChunk($chunkSize)) {
				continue;
			}

			$chunk = $this->readChunk($chunkSize);
			$status .= $chunk;

			if ($this->isJsonFinished($chunk, $chunkSize)) {
				if ($this->isMessage($status)) {
					$this->handleMessage($status);
				} else {
					yield $status;
				}

				$status = '';
			}
		}

		$this->close();
	}

	/**
	 * Decides weather the read chunk is the end of a complete json object.
	 *
	 * @param string $chunk
	 * @param int $chunkSize
	 * @return bool
	 */
	protected function isJsonFinished($chunk, $chunkSize)
	{
		return "\r\n" == substr($chunk, $chunkSize - 2, 2) || $this->eof();
	}

	/**
	 * Decides weather the read chunk is empty or not.
	 *
	 * @param int $chunkSize
	 * @return bool
	 */
	protected function isEmptyChunk($chunkSize)
	{
		return 2 == $chunkSize || 0 == $chunkSize;
	}
}


<?php
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: Element.php 4049 2011-05-01 12:56:06Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;
use Openbizx\I18n\I18n;
use Openbizx\Object\MetaObject;
use Openbizx\Object\MetaIterator;
use Openbizx\Object\UIControlInterface;

/**
 * Element class is the base class of all HTML Element
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class Element extends MetaObject implements UIControlInterface
{
    public $style;
    public $cssClass;
    public $cssErrorClass;
    public $cssFocusClass;
    public $width;
    public $height;
    public $bizDataObj;
    public $hidden = "N";       // support expression
    public $htmlAttr;
    public $label;
    public $text;
    public $eventHandlers;
    public $translatable;
    public $fuzzySearch;
    public $onEventLog;
    public $allowURLParam = 'N';
    public $xmlMeta;

    public $sortFlag;
    public $value = "";
    public $formName;
    public $extra;
    public $elementSet;
    public $elementSetCode;
    public $tabSet;
    public $tabSetCode;
    public $fieldName;
    public $required = null;
    public $validator = null;
    public $clientValidator = null;
	public $keepCookie = null;
	public $cookieLifetime = 3600;
	public $backgroundColor;

	public $dataRole = "";

    public $defaultValue;

    /**
     * Initialize Element with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr, $formObj)
    {
    	$this->xmlMeta = $xmlArr;
        $this->formName = $formObj->objectName;
        $this->package = $formObj->package;

        $this->readMetaData($xmlArr);

        $this->translate();	// translate for multi-language support
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        $this->objectName = isset($xmlArr["ATTRIBUTES"]["NAME"]) ? $xmlArr["ATTRIBUTES"]["NAME"] : null;
        $this->bizDataObj = isset($xmlArr["ATTRIBUTES"]["BIZDATAOBJ"]) ? $xmlArr["ATTRIBUTES"]["BIZDATAOBJ"] : null;
		$this->backgroundColor = isset($xmlArr["ATTRIBUTES"]["BACKGROUNDCOLOR"]) ? $xmlArr["ATTRIBUTES"]["BACKGROUNDCOLOR"] : null;
        $this->className = isset($xmlArr["ATTRIBUTES"]["CLASS"]) ? $xmlArr["ATTRIBUTES"]["CLASS"] : null;
        $this->objectDescription = isset($xmlArr["ATTRIBUTES"]["DESCRIPTION"]) ? $xmlArr["ATTRIBUTES"]["DESCRIPTION"] : null;
        $this->access = isset($xmlArr["ATTRIBUTES"]["ACCESS"]) ? $xmlArr["ATTRIBUTES"]["ACCESS"] : null;
        $this->defaultValue = isset($xmlArr["ATTRIBUTES"]["DEFAULTVALUE"]) ? $xmlArr["ATTRIBUTES"]["DEFAULTVALUE"] : null;
        $this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : null;
        $this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : "input_error";
        $this->style = isset($xmlArr["ATTRIBUTES"]["STYLE"]) ? $xmlArr["ATTRIBUTES"]["STYLE"] : null;
        $this->width = isset($xmlArr["ATTRIBUTES"]["WIDTH"]) ? $xmlArr["ATTRIBUTES"]["WIDTH"] : null;
        $this->height = isset($xmlArr["ATTRIBUTES"]["HEIGHT"]) ? $xmlArr["ATTRIBUTES"]["HEIGHT"] : null;
        $this->hidden = isset($xmlArr["ATTRIBUTES"]["HIDDEN"]) ? $xmlArr["ATTRIBUTES"]["HIDDEN"] : null;
        $this->htmlAttr = isset($xmlArr["ATTRIBUTES"]["HTMLATTR"]) ? $xmlArr["ATTRIBUTES"]["HTMLATTR"] : null;
        $this->elementSet = isset($xmlArr["ATTRIBUTES"]["ELEMENTSET"]) ? $xmlArr["ATTRIBUTES"]["ELEMENTSET"] : null;
        $this->elementSetCode = isset($xmlArr["ATTRIBUTES"]["ELEMENTSET"]) ? $xmlArr["ATTRIBUTES"]["ELEMENTSET"] : null;
        $this->tabSet = isset($xmlArr["ATTRIBUTES"]["TABSET"]) ? $xmlArr["ATTRIBUTES"]["TABSET"] : null;
        $this->tabSetCode = isset($xmlArr["ATTRIBUTES"]["TABSET"]) ? $xmlArr["ATTRIBUTES"]["TABSET"] : null;

        $this->text = isset($xmlArr["ATTRIBUTES"]["TEXT"]) ? $xmlArr["ATTRIBUTES"]["TEXT"] : null;

        $this->translatable = isset($xmlArr["ATTRIBUTES"]["TRANSLATABLE"]) ? $xmlArr["ATTRIBUTES"]["TRANSLATABLE"] : null;
        $this->fuzzySearch = isset($xmlArr["ATTRIBUTES"]["FUZZYSEARCH"]) ? $xmlArr["ATTRIBUTES"]["FUZZYSEARCH"] : null;
        $this->onEventLog = isset($xmlArr["ATTRIBUTES"]["ONEVENTLOG"]) ? $xmlArr["ATTRIBUTES"]["ONEVENTLOG"] : null;
        $this->required = isset($xmlArr["ATTRIBUTES"]["REQUIRED"]) ? $xmlArr["ATTRIBUTES"]["REQUIRED"] : null;
        $this->validator = isset($xmlArr["ATTRIBUTES"]["VALIDATOR"]) ? $xmlArr["ATTRIBUTES"]["VALIDATOR"] : null;
        $this->clientValidator = isset($xmlArr["ATTRIBUTES"]["CLIENTVALIDATOR"]) ? $xmlArr["ATTRIBUTES"]["CLIENTVALIDATOR"] : null;
        $this->allowURLParam = isset($xmlArr["ATTRIBUTES"]["ALLOWURLPARAM"]) ? $xmlArr["ATTRIBUTES"]["ALLOWURLPARAM"] : 'Y';
        $this->keepCookie = isset($xmlArr["ATTRIBUTES"]["KEEPCOOKIE"]) ? $xmlArr["ATTRIBUTES"]["KEEPCOOKIE"] : 'N';
        $this->cookieLifetime = isset($xmlArr["ATTRIBUTES"]["COOKIELIFETIME"]) ? (int)$xmlArr["ATTRIBUTES"]["COOKIELIFETIME"] : '3600';
		$this->dataRole = isset($xmlArr["ATTRIBUTES"]["DATAROLE"]) ? $xmlArr["ATTRIBUTES"]["DATAROLE"] : null;
		$this->extra = isset($xmlArr["ATTRIBUTES"]["EXTRA"]) ? $xmlArr["ATTRIBUTES"]["EXTRA"] : null;

        // read EventHandler element
        if (isset($xmlArr["EVENTHANDLER"]))  // 2.1 eventhanlders
            $this->eventHandlers = new MetaIterator($xmlArr["EVENTHANDLER"],"EventHandler");

        if ($this->eventHandlers != null)
        {
            foreach ($this->eventHandlers as $eventHandler)
                $eventHandler->setFormName($this->formName, $this->objectName);
        }

        // additional data in HTMLAttr
		$this->htmlAttr .= ($this->dataRole) ? " data-role='".$this->dataRole."'" : "";
        $this->htmlAttr .= " title='".$this->objectDescription."'"." clientValidator='".$this->clientValidator."'";
    }

    /**
     * Get form ({@link EasyForm}) object
     *
     * @return EasyForm
     */
    protected function getFormObj()
    {
        return Openbizx::getObject($this->formName);
    }

    //
    /**
     * Adjust form ({@link EasyForm}) name
     * change the form name after inherit from parent form
     *
     * @param string $formName
     * @return void
     */
    public function adjustFormName($formName)
    {
        if ($this->formName == $formName)
            return;
        $this->formName = $formName;
        if ($this->eventHandlers != null)
        {
            foreach ($this->eventHandlers as $eventHandler)
                $eventHandler->adjustFormName($this->formName);
        }
    }

    public function reset()
    {
    	$this->value = null;
    	if ($this->eventHandlers != null)
        {
            foreach ($this->eventHandlers as $eventHandler)
                $eventHandler->formedFunction = null;
        }
    }

    /**
     * Set value of element
     *
     * @param mixed $value
     */
    public function setValue($value)
    {
        $this->value = $value;
        if($this->keepCookie=='Y'){
        	if($value!=""){
        		$formName = $this->getFormObj()->objectName;
        		setcookie($formName."-".$this->objectName,$value,time()+(int)$this->cookieLifetime,"/");
        	}
        }
    }

    /**
     * Get value of element
     *
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Get property of element
     *
     * @param string $propertyName
     * @return mixed
     */
    public function getProperty($propertyName)
    {
        if ($propertyName == "Value") return $this->getValue();
        $ret = parent::getProperty($propertyName);
        if ($ret) return $ret;
        return $this->$propertyName;
    }

    /**
     * Check if the element can be displayed
     *
     * @return boolean
     */
    public function canDisplayed()
    {
        if (!$this->allowAccess())
            return false;
        if ($this->getHidden() == "Y")
            return false;
        return true;
    }

    /**
     * Get default value
     *
     * @return mixed
     */
    public function getDefaultValue()
    {
        if ($this->defaultValue == "" && $this->keepCookie!='Y')
            return "";
        $formObj = $this->getFormObj();
        if($this->keepCookie=='Y'){
        	$cookieName = $formObj->objectName."-".$this->objectName;
        	$cookieName = str_replace(".","_",$cookieName);
        	$defValue = $_COOKIE[$cookieName];
        }
        if(!$defValue){
        	$defValue = Expression::evaluateExpression($this->defaultValue, $formObj);
        }
        //add automatic append like new record (2)
        if($this->defaultValueRename!='N'){
	        if(!is_numeric($defValue)){
		        $dataobj = $formObj->getDataObj();
		        if($this->fieldName && $dataobj){
		        	if(substr($this->fieldName,0,1)!='_'){
			        	$recs = $dataobj->directfetch("[".$this->fieldName."] = '$defValue' OR "."[".$this->fieldName."] LIKE '$defValue (%)'" );
			        	if($recs->count()>0){
			        		$defValue.= " ( ".$recs->count()." )";
			        	}
		        	}
		        }
	        }
        }
        return $defValue;
    }

    /**
     * Render the element by html
     *
     * @return string HTML text
     */
    public function render()
    {
     	return "";
    }

    public function renderLabel()
    {
        $sHTML = $this->translateString($this->label);
        return $sHTML;
    }

    /**
     * Get hidden status
     *
     * @return mixed
     */
    protected function getHidden()
    {
		if (!$this->hidden || $this->hidden=='N') return "N";
        $formObj = $this->getFormObj();
        return Expression::evaluateExpression($this->hidden, $formObj);
    }

    /**
     * Get style of element
     *
     * @return string
     */
    protected function getStyle()
    {
		$formobj = $this->getFormObj();
        $htmlClass = Expression::evaluateExpression($this->cssClass, $formobj);
        $htmlClass = "CLASS='$htmlClass'";
        if(!$htmlClass){
        	$htmlClass = null;
        }
        $style ='';
        if ($this->width && $this->width>=0)
            $style .= "width:".$this->width."px;";
        if ($this->height && $this->height>=0)
            $style .= "height:".$this->height."px;";
        if ($this->style)
            $style .= $this->style;
        if (!isset($style) && !$htmlClass)
            return null;
        if (isset($style))
        {

            $style = Expression::evaluateExpression($style, $formobj);
            $style = "STYLE='$style'";
        }
        if($formobj->errors[$this->objectName])
        {
      	    $htmlClass = "CLASS='".$this->cssErrorClass."'";
        }
        if ($htmlClass)
            $style = $htmlClass." ".$style;
        return $style;
    }

    protected function getBackgroundColor()
    {
        if ($this->backgroundColor == null)
            return null;
        $formObj = $this->getFormObj();
        return Expression::evaluateExpression($this->backgroundColor, $formObj);
    }

    /**
     * Get text of element
     *
     * @return string
     */
    protected function getText()
    {
        if ($this->text == null)
            return null;
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->text, $formobj);
    }

    public function getDescription()
    {
        if ($this->objectDescription == null)
            return null;
        $formobj = $this->getFormObj();
        $text =  Expression::evaluateExpression($this->objectDescription, $formobj);
        $text = str_replace("[b]","",$text);
        $text = str_replace("[/b]","",$text);
        return $text;
    }

    /**
     * Get shortcut key function map
     *
     * @return array
     */
    public function getSCKeyFuncMap()
    {
        if (!$this->canDisplayed()) return null;

        $map = array();
        /**
         * @todo need to remove, not used (mr_a_ton)
         */
        //$formObj = $this->getFormObj(); // not used

        if ($this->eventHandlers == null)
            return null;
        foreach ($this->eventHandlers as $eventHandler)
        {
            if ($eventHandler->shortcutKey)
            {
                $map[$eventHandler->shortcutKey] = $eventHandler->getFormedFunction();
            }
        }
        return $map;
    }

    /**
     * Get context menu
     *
     * @return array
     */
    public function getContextMenu()
    {
        if (!$this->canDisplayed()) return null;
        $menus = array();
        $formObj = $this->getFormObj();
        if ($this->eventHandlers == null)
            return null;
        $i = 0;
        foreach ($this->eventHandlers as $eventHandler)
        {
            if ($eventHandler->contextMenu)
            {
                $menus[$i]['text'] = $eventHandler->contextMenu;
                $menus[$i]['func'] = $eventHandler->getFormedFunction();
                $menus[$i]['key']  = $eventHandler->shortcutKey;
            }
            $i++;
        }
        return $menus;
    }

    /**
     * Get function of element in JavaScript format
     *
     * @return string
     */
    protected function getFunction()
    {
        $events = $this->getEvents();
		foreach ($events as $event=>$function){
			if(is_array($function)){
				foreach($function as $f){
					$function_str.=$f.";";
				}
				$func .= " $event=\"$function_str\"";
			}else{
				$func .= " $event=\"$function\"";
			}
		}
        return $func;
    }

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

        $events = array();

        if ($this->eventHandlers == null)
            return $events;
        $formobj = $this->getFormObj();

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

    public function getFunctionByEventHandlerName($eventHandlerName)
    {
    	if ($this->eventHandlers == null)
            return null;
    	$eventHandler = $this->eventHandlers->get($eventHandlerName);
    	if ($eventHandler)
    		$func = Expression::evaluateExpression($eventHandler->function, $formobj);
    	return $func;
    }

    /**
     * Get redirect page
     *
     * @param string $eventHandlerName event handler name
     * @return string
     */
    public function getRedirectPage($eventHandlerName)
    {
        $formObj = $this->getFormObj();
        $eventHandler = $this->eventHandlers->get($eventHandlerName);
        if (!$eventHandler) return null;
        //echo $evthandler->redirectPage."
";
        return Expression::evaluateExpression($eventHandler->redirectPage, $formObj);
    }

    /**
     * Get parameter
     *
     * @param string $eventHandlerName
     * @return mixed
     */
    public function getParameter($eventHandlerName){
    	$formObj = $this->getFormObj();
        $eventHandler = $this->eventHandlers->get($eventHandlerName);
        if (!$eventHandler) return null;
        //echo $evthandler->redirectPage."
";
        return Expression::evaluateExpression($eventHandler->parameter, $formObj);
    }

    /**
     * Get function type
     *
     * @param string $eventHandlerName event handler name
     * @return string function type in string format
     */
    public function getFunctionType($eventHandlerName)
    {
        $eventHandler = $this->eventHandlers->get($eventHandlerName);
        if (!$eventHandler) return null;
        return $eventHandler->functionType;
    }

    /**
     * Check if element must required (must have value)
     *
     * @return boolean
     */
    public function checkRequired()
    {
        if (!$this->required || $this->required == "")
            return false;
        else if ($this->required == "Y")
            $required = true;
        else if($this->required == "N")
            $required = false;
        else{
            $required = Expression::evaluateExpression($this->required, $this->getFormObj());
            if(strtoupper($required)=='Y')
            {
            	$required=true;
            }
            elseif(strtoupper($required)=='N')
            {

            }
            else
            {
            	$required=false;
            }
        }
        return $required;
    }

    /**
     * Validate element
     *
     * @return boolean
     */
    public function validate()
    {
        $ret = true;
        if ($this->validator)
            $ret = Expression::evaluateExpression($this->validator, $this->getFormObj());
        return $ret;
    }

    /**
     * Get client validator
     *
     * @return string
     */
    public function getClientValidator()
    {
        if ($this->clientValidator)
            return $this->clientValidator;

        //return Expression::evaluateExpression($this->clientValidator, $this->getFormObj());
        return null;
    }

    public function matchRemoteMethod($method)
    {
        return false;
    }

    protected function translate()
    {
    	$module = $this->getModuleName($this->formName);
    	if (!empty($this->text))
    		$this->text = I18n::t($this->text, $this->getTransKey('Text'), $module, $this->getTransPrefix());
    	if (!empty($this->label))
    		$this->label = I18n::t($this->label, $this->getTransKey('Label'), $module, $this->getTransPrefix());
    	if (!empty($this->objectDescription))
    		$this->objectDescription = I18n::t($this->objectDescription, $this->getTransKey('Description'), $module, $this->getTransPrefix());
        if (!empty($this->defaultValue) && !preg_match("/\{/si",$this->defaultValue))
    		$this->defaultValue = I18n::t($this->defaultValue, $this->getTransKey('DefaultValue'), $module, $this->getTransPrefix());
		if (!empty($this->elementSet))
    		$this->elementSet = I18n::t($this->elementSet, $this->getTransKey('ElementSet'), $module, $this->getTransPrefix());
    	if (!empty($this->blankOption))
    		$this->blankOption = I18n::t($this->blankOption, $this->getTransKey('BlankOption'), $module, $this->getTransPrefix());
    	if (!empty($this->tabSet))
    		$this->tabSet = I18n::t($this->tabSet, $this->getTransKey('TabSet'), $module, $this->getTransPrefix());
    	if (!empty($this->hint))
    		$this->hint = I18n::t($this->hint, $this->getTransKey('Hint'), $module, $this->getTransPrefix());
    }

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

    protected function getTransKey($name)
    {
    	$shortFormName = substr($this->formName,intval(strrpos($this->formName,'.')+1));
    	return strtoupper($shortFormName.'_'.$this->objectName.'_'.$name);
    }

    protected function translateString($value)
    {
        $module = $this->getModuleName($this->formName);
        if(defined($value)) $value = constant($value);
        return I18n::t($value, 'STRING_'.$value, $module);
    }

    public function getDataObj()
    {
    	if(!$this->bizDataObj){
    		return $this->getFormObj()->getDataObj();
    	}else{
    		return Openbizx::getDataObject($this->bizDataObj);
    	}
    }
}

/**
 * EventHandler class is manage event handler of element
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class EventHandler
{
    public $objectName;
    public $event;
    public $function;     // support expression
    public $functionType;
    public $postAction;   // support expression
    public $shortcutKey;
    public $contextMenu;
    public $redirectPage;
    public $parameter;
    public $eventLogMsg;
    public $formedFunction;
    private $_formName;
    private $_elemName;

    // add URL here so that direct url string can be given
    public $url;

    /**
     * Initialize EventHandler with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->objectName = isset($xmlArr["ATTRIBUTES"]["NAME"]) ? $xmlArr["ATTRIBUTES"]["NAME"] : null;
        $this->event = isset($xmlArr["ATTRIBUTES"]["EVENT"]) ? $xmlArr["ATTRIBUTES"]["EVENT"] : null;
        $this->function = isset($xmlArr["ATTRIBUTES"]["FUNCTION"]) ? $xmlArr["ATTRIBUTES"]["FUNCTION"] : null;
        $this->origFunction = $this->function;
        $this->functionType = isset($xmlArr["ATTRIBUTES"]["FUNCTIONTYPE"]) ? $xmlArr["ATTRIBUTES"]["FUNCTIONTYPE"] : null;
        $this->postAction = isset($xmlArr["ATTRIBUTES"]["POSTACTION"]) ? $xmlArr["ATTRIBUTES"]["POSTACTION"] : null;
        $this->shortcutKey = isset($xmlArr["ATTRIBUTES"]["SHORTCUTKEY"]) ? $xmlArr["ATTRIBUTES"]["SHORTCUTKEY"] : null;
        $this->contextMenu = isset($xmlArr["ATTRIBUTES"]["CONTEXTMENU"]) ? $xmlArr["ATTRIBUTES"]["CONTEXTMENU"] : null;
        $this->redirectPage = isset($xmlArr["ATTRIBUTES"]["REDIRECTPAGE"]) ? $xmlArr["ATTRIBUTES"]["REDIRECTPAGE"] : null;
		$this->parameter = isset($xmlArr["ATTRIBUTES"]["PARAMETER"]) ? $xmlArr["ATTRIBUTES"]["PARAMETER"] : null;
        $this->eventLogMsg = isset($xmlArr["ATTRIBUTES"]["EVENTLOGMSG"]) ? $xmlArr["ATTRIBUTES"]["EVENTLOGMSG"] : null;
        $this->url = isset($xmlArr["ATTRIBUTES"]["URL"]) ? $xmlArr["ATTRIBUTES"]["URL"] : null;
    }

    /**
     * Set form name that contain element and EventHandler
     *
     * @param string $formName
     * @param string $elemName
     * @return void
     */
    public function setFormName($formName, $elemName)
    {
        $this->_formName = $formName;
        $this->_elemName = $elemName;
        if (strpos($this->function, "js:")===0)
            return;
        // if no class name, add default class name. i.e. NewRecord => ObjName.NewRecord
        if ($this->function)
        {
            $pos_dot = strpos($this->function, ".");
            $pos_lpt = strpos($this->function, "(");
            if (!$pos_dot || $pos_lpt < $pos_dot)
                $this->function = $this->_formName.".".$this->function;
        }
        $this->translate();	// translate for multi-language support
    }

    /**
     * Adjust form name
     *
     * @param string $formName
     * @return void
     */
    public function adjustFormName($formName)
    {
        $this->_formName = $formName;
        // if no class name, add default class name. i.e. NewRecord => ObjName.NewRecord
        if ($this->function)
        {
        	if(strtolower(substr($this->function,0,3))!='js:'){
				$pos0 = strpos($this->function, "(");
				$len = strlen($this->function);
				if ($pos0 > 0)
					$pos = strrpos($this->function, ".", $pos0-$len);
				else
					$pos = strrpos($this->function, ".");
				if ($pos > 0)
					$this->function = $this->_formName.".".substr($this->function, $pos+1);
			}
        }
    }

    /**
     * Get formed function
     *
     * @return string
     */
    public function getFormedFunction()
    {
        //return $this->getInvokeAction();
        $name = $this->_elemName;
        $ehName = $this->objectName;
        $formobj = Openbizx::getObject($this->_formName);
        if ($this->formedFunction)
        {
            return $this->formedFunction;
        }
        if (!$this->formedFunction || $isDataPanelElement==true)
        {
            // add direct URL support
            if ($this->url)
            {
                $_func = "loadPage('" . $this->url . "');";
                $_func = Expression::evaluateExpression($_func, $formobj);
            }
            else if (strpos($this->function, "js:") === 0)
            {
                $_func = substr($this->function, 3).";";
                $_func = Expression::evaluateExpression($_func, $formobj);
            }
            else
            {
                //$temp = ($this->functionType==null) ? "" : ",'".$this->functionType."'";
                //$_func = "SetOnElement('$name:$ehName'); $selectRecord CallFunction('" . $this->function . "'$temp);";
                //$_func = "Openbizx.CallFunction('" . $this->function . "'$temp);";
                $_func = Expression::evaluateExpression($this->function, $formobj);
                $options = "{'type':'$this->functionType','target':'','evthdl':'$name:$ehName'}";
                $_func = "Openbizx.CallFunction('$_func',$options);";
            }
            $this->formedFunction = $_func;
        }
        return $this->formedFunction;
    }

    public function getInvokeAction()
    {
        if ($this->formedFunction)
            return $this->formedFunction;
    	$name = $this->_elemName;
        $ehName = $this->objectName;
        $formobj = Openbizx::getObject($this->_formName);

        if (!$this->formedFunction)
        {
            // add direct URL support
            if ($this->url)
                $_func = "loadPage('" . $this->url . "');";
            else if (strpos($this->function, "js:") === 0)
                $_func = substr($this->function, 3).";";
            else
            {
                $temp = ($this->functionType==null) ? "" : ",'".$this->functionType."'";
                //$_func = "SetOnElement('$name:$ehName'); Openbizx.CallFunction('" . $this->function . "'$temp);";
                list($funcName, $funcParams) = $this->parseFunction($this->function);
                $funcParams = Expression::evaluateExpression($funcParams, $formobj);
                $action = "$name:$ehName";
                // TODO: encrypt paramString to add more security
                $_func = "Openbizx.invoke('$this->_formName','$action','$funcParams'$temp);";
            }
            //$_func = Expression::evaluateExpression($_func, $formobj);
            $this->formedFunction = $_func;
        }
        return $this->formedFunction;
    }

    // parse function string and get functionName and functionParams
    public function parseFunction($funcString)
    {
        $pos = strpos($funcString, "(");
        $pos1 = strpos($funcString, ")");
        if ($pos>0 && $pos1>$pos)
        {
            $funcName = substr($funcString,0,$pos);
            $funcParams = substr($funcString,$pos+1,$pos1-$pos-1);
            return array($funcName, $funcParams);
        }
        return null;
    }

    protected function translate()
    {
    	$module = substr($this->_formName,0,intval(strpos($this->_formName,'.')));
    	if (!empty($this->contextMenu))
    		$this->contextMenu = I18n::t($this->contextMenu, $this->getTransKey('ContextMenu'), $module);
    }

    protected function getTransKey($name)
    {
    	$shortFormName = substr($this->formName,intval(strrpos($this->formName,'.'))+1);
    	return strtoupper($shortFormName.'_'.$this->objectName.'_'.$name);
    }

}
?>


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

namespace SugiPHP\Auth;

/**
 * HOTP: An HMAC-Based One-Time Password Algorithm
 * @see http://www.ietf.org/rfc/rfc4226.txt
 * TOTP: Time-Based One-Time Password Algorithm
 * @see http://www.ietf.org/rfc/rfc6238.txt
 */
class HOTP
{
    protected $digits = 6;
    protected $secret;

    public function __construct($secret, $digits = 6)
    {
        $this->secret = (string) $secret;
        $this->digits = $digits;
    }

    public function gen($counter)
    {
        $digits = $this->digits;
        $secret = $this->secret;
        $counter = $this->counterToString($counter);

        $hash = hash_hmac("sha1", $counter, $secret, true);

        $otp = $this->truncateHash($hash);
        if ($digits < 10) {
            $otp %= pow(10, $digits);
        }

        return str_pad($otp, $digits, "0", STR_PAD_LEFT);
    }

    public function check($otp, $counter, $window = 5)
    {
        $counter = max(0, $counter);

        $offset = -1;
        for ($i = $counter; $i <= $counter + $window; $i++) {
            if ($otp == $this->gen($i)) {
                $offset = $i - $counter;
                break;
            }
        }

        return $offset;
    }

    /**
     * Extract 4 bytes from a hash value
     * Uses the method defined in RFC 4226 section 5.4
     *
     * @param  string $hash
     * @return integer
     */
    protected function truncateHash($hash)
    {
        $offset = ord($hash[19]) & 0xf;
        $value = (ord($hash[$offset + 0]) & 0x7f) << 24;
        $value |= (ord($hash[$offset + 1]) & 0xff) << 16;
        $value |= (ord($hash[$offset + 2]) & 0xff) << 8;
        $value |= (ord($hash[$offset + 3]) & 0xff);

        return $value;
    }

    /**
     * Convert an integer counter into a string of 8 bytes.
     *
     * @param  integer $counter The counter value
     * @return string Returns an 8-byte binary string
     */
    protected function counterToString($counter)
    {
        $tmp = "";
        while ($counter != 0) {
            $tmp .= chr($counter & 0xff);
            $counter >>= 8;
        }

        return substr(str_pad(strrev($tmp), 8, "\0", STR_PAD_LEFT), 0, 8);
    }
}


<?php

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

namespace Instaphp;

use Instaphp\Cache;
use Instaphp\WebRequest;
/**
 * Request
 * The Request class performs simple curl requests to a URL optionally passing
 * parameters on the querystring. Currently, it supports GET,POST and DELETE requests.
 * @package Instaphp
 * @version 1.0
 * @author randy sesser <randy@instaphp.com>
 */
class Request
{

    /**
     * Associative array of key/value pairs to pass to the Instagram API
     * @var Array
     * @access public
     */
    public $parameters = array();
    /**
     * The URL in which to make the request
     * @var String
     * @access public
     */
    public $url = null;
    /**
     * A var to store whether or not to use curl
     * @var boolean
     * @access private
     */
    private $useCurl = false;

    private $config;

    /**
     * The constructor contructs
     * @param string $url A URL in which to create a new request (optional)
     * @param Array $params An associated array of key/value pairs to pass to said URL (optional)
     */
    public function __construct($config, $url = null, $params = array())
    {
        $this->useCurl = self::HasCurl();
        $this->parameters = $params;
        $this->url = $url;
        $this->config = $config;
    }

    /**
     * Makes a GET request
     * @param string $url A URL in which to make a GET request
     * @param Array $params An associative array of key/value pairs to pass to said URL
     * @return Request
     */
    public function Get($url = null, $params = array())
    {
        if (null !== $url)
            $this->url = $url;

		if (!empty($params))
			$this->parameters = $params;
		$query = '';
		foreach ($this->parameters as $k => $v)
			$query .= ((strlen ($query) == 0) ? '?' : '&') . sprintf('%s=%s', $k, $v);

		$response = $this->GetResponse();

        $this->response = $response;
        return $this;
    }

    /**
     * Makes a POST request
     * @param string $url A URL in which to make a POST request
     * @param Array $params An associative array of key/value pairs to pass to said URL
     * @return Request
     */
    public function Post($url = null, $params = array())
    {
        if (null !== $url)
            $this->url = $url;

		if (!empty($params))
			$this->parameters = $params;

        $this->response = $this->GetResponse('POST');
        return $this;
    }

    /**
     * Makes a PUT request (currently unused)
     * @param string $url A URL in which to make a PUT request
     * @param Array $params An associative array of key/value pairs to pass to said URL
     * @return void
     */
    public function Put($url = null, $params = array())
    {

    }

    /**
     * Makes a DELETE request
     * @param string $url A URL in which to make a DELETE request
     * @param Array $params An associative array of key/value pairs to pass to said URL
     * @return Request
     */
    public function Delete($url = null, $params = array())
    {
        if (null !== $url)
            $this->url = $url;

		if (!empty($params))
			$this->parameters = $params;

        $this->response = $this->GetResponse('DELETE');
        return $this;
    }

    /**
     * Makes a request
     * @param string $url A URL in which to make a GET request
     * @param Array $params An associative array of key/value pairs to pass to said URL
     * @access private
     * @return Response
     */
    private function GetResponse($method = 'GET')
    {
        //-- since there's no option to use anything other curl, this check is kinda useless
        //-- I had high hopes with this one using sockets and whatnot, but alas, time is of
        //-- the essence... in internet time
        if ($this->useCurl) {

			$response = new Response;

			$http = WebRequest::Instance($this->config);
			$res = $http->Create($this->url, $method, $this->parameters);

			if ($res instanceof Error)
				return $res;

			$response->info = $res->Info;
			$response->json = $res->Content;
			$response = Response::Create($this, $response);
            return $response;
        }
    }

    /**
     * Checks to see if cURL extension is available
     * @access private
     * @return boolean
     */
    private static function HasCurl()
    {
        return function_exists('curl_init');
    }

    /**
     * Determines whether or not curl will follow redirects over SSL
     * See the constructor for details, but there are cases in which
     * if curl can't verify the certificate of an SSL request, AND
     * PHP is in safe_mode OR there are open_basedir restrictions, it will
     * not follow a redirect. There's a fix for this that involves
     * parsing all the response headers from a request and detecting
     * a Location header, but that's kind of a hack as it bypasses the
     * whole point of SSL. This method left for posterity. Or something...
     *
     * @return boolean
     * @access private
     **/
    private function WillFollowRedirects()
    {
        $open_basedir = ini_get('open_basedir');
        $safe_mode = strtolower(ini_get('safe_mode'));
        if (empty($open_basedir) && $safe_mode == 'off') {
            return true;
        }
        return false;
    }

}


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

namespace Openbizx\Easy\Element;

/**
 * Listbox class is element that show ListBox with data from Selection.xml
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class CheckListbox extends OptionElement
{

    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $fromList = array();
        $this->getFromList($fromList);
        $style = $this->getStyle();
        $func = $this->getFunction();
        $valueList = array(); $valueArray = array();
        $this->getFromList($valueList, $this->getSelectedList());
        foreach ($valueList as $vl) {
            $valueArray[] = $vl['val'];
        }

        $sHTML = "
objectName . "\" ID=\"" . $this->objectName ."\" $this->htmlAttr $style>";

        foreach ($fromList as $option)
        {
            $test = array_search($option['val'], $valueArray);
            if ($test === false)
            {
                $selectedStr = '';
            }
            else
            {
                $selectedStr = "CHECKED";
            }
            $sHTML .= "<input type=\"checkbox\" name=\"".$this->objectName."[]\" VALUE=\"" . $option['val'] . "\" $selectedStr></input>" . $option['txt'] . "
";
        }
        $sHTML .= "
";
        return $sHTML;
    }
}

?>


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

use Illuminate\Support\Facades\Log;
use Interpro\QuickStorage\Concept\Command\Flat\UpdateBlockFlatCommand;
use Interpro\QuickStorage\Concept\FieldProviding\FieldSaveMediator;
use Interpro\QuickStorage\Laravel\Model\Block;
use Interpro\QuickStorage\Laravel\Model\Bool;
use Interpro\QuickStorage\Laravel\Model\Imageitem;
use Interpro\QuickStorage\Laravel\Model\Numb;
use Interpro\QuickStorage\Laravel\Model\Pdatetime;
use Interpro\QuickStorage\Laravel\Model\Stringfield;
use Interpro\QuickStorage\Laravel\Model\Textfield;

class UpdateBlockFlatCommandHandler {

    private $saveMediator;

    /**
     * Create the command handler.
     *
     * @return void
     */
    public function __construct(FieldSaveMediator $saveMediator)
    {
        $this->saveMediator = $saveMediator;
    }

    /**
     * Handle the command.
     *
     * @param  UpdateBlockFlatCommand  $command
     * @return void
     */
    public function handle(UpdateBlockFlatCommand $command)
    {
        $qstorage = config('qstorage');

        $data_arr = &$command->data_arr;

        $block_name = $data_arr['name'];

        $block = Block::find($block_name);

        if($block)
        {
            if(array_key_exists($block_name, $qstorage))
            {

                $blockstruct = $qstorage[$block_name];
                $field_types = [];
                foreach(['stringfields', 'textfields', 'numbs', 'images', 'bools', 'pdatetimes'] as $typename) {
                    if (array_key_exists($typename, $blockstruct)){
                        foreach($blockstruct[$typename] as $field_name){
                            $field_types[$field_name] = $typename;
                        }
                    }
                }

                if(array_key_exists('title', $data_arr))
                {
                    $block->title = $data_arr['title'];
                }

                $block->save();

                foreach($data_arr as $field_name => $field_val)
                {
                    if($field_name == 'block_name' or $field_name == 'title'){
                        continue;
                    }

                    if(array_key_exists($field_name, $field_types)){

                        $typename = $field_types[$field_name];

                        if($typename == 'stringfields'){
                            $field = Stringfield::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>0]);
                            $field->value = $field_val;
                            $field->save();

                        }else if($typename == 'textfields'){
                            $field = Textfield::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>0]);
                            $field->value = $field_val;
                            $field->save();

                        }else if($typename == 'numbs'){
                            $field = Numb::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>0]);
                            $field->value = $field_val;
                            $field->save();

                        }else if($typename == 'bools'){
                            $field = Bool::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>0]);
                            $field->value = $field_val == "true" ? true : false;
                            $field->save();

                        }else if($typename == 'pdatetimes'){
                            $field = Pdatetime::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>0]);
                            $field->value = $field_val;
                            $field->save();

                        }else if($typename == 'images'){
                            $field = Imageitem::firstOrNew(['block_name'=>$block_name, 'name'=>$field_name, 'group_id'=>0]);

                            if(array_key_exists('alt', $field_val)){
                                $field->alt = $field_val['alt'];
                            }
                            if(array_key_exists('original_link', $field_val)){
                                $field->original_link = $field_val['original_link'];
                            }
                            if(array_key_exists('primary_link', $field_val)){
                                $field->primary_link = $field_val['primary_link'];
                            }
                            if(array_key_exists('secondary_link', $field_val)){
                                $field->secondary_link = $field_val['secondary_link'];
                            }
                            if(array_key_exists('icon_link', $field_val)){
                                $field->icon_link = $field_val['icon_link'];
                            }
                            if(array_key_exists('preview_link', $field_val)){
                                $field->preview_link = $field_val['preview_link'];
                            }
                            if(array_key_exists('prefix', $field_val)){
                                $field->prefix = $field_val['prefix'];
                            }

                            $field->cache_index++;

                            $field->save();

                        }

                    }else{
                        Log::info('Ошибка при сохранении блока('.$block_name.'): нет поля '.$field_name.' ни в одном типе в настройках блока!');
                    }

                }

                //С доп. полями пока не ясно

                /*Сохраняем все внешние (отностиельно quickstorage поля)
                foreach($this->saveMediator->list as $suffix=>$saver) {
                    if(array_key_exists($suffix, $dataobj)){
                        $dataobj['entity_name'] = $block_name;
                        $saver->save($suffix, $dataobj[$suffix]);
                    }
                }*/

            }else{
                throw new \Exception('Не нашел блок по имени '.$block_name);
            }
        }else{
            throw new \Exception('Не нашел блок по имени в БД '.$block_name);
        }

    }

}


<?php
declare(strict_types=1);

namespace zauberfisch\SerializedDataObject;

require_once 'Serialize/JsonSerializer.php';

use zauberfisch\NamespaceTemplates\Form\FormField;
use zauberfisch\SerializedDataObject\Serialize\JsonSerializable;
use zauberfisch\SerializedDataObject\Serialize\JsonSerializer;
use zauberfisch\SerializedDataObject\Serialize\Serializer;

/**
 * @author Zauberfisch
 * @method static \Config_ForClass|\stdClass config
 */
abstract class AbstractDataObject extends \ViewableData implements \Serializable, JsonSerializable, \i18nEntityProvider {
	private static $fields = [];
	private static $lists = [];
	protected $fieldsData = [];
	protected $listsData = [];

	use JsonSerializer {
		jsonSerialize as jsonSerializeTrait;
	}

	public function jsonSerialize() {
		return array_merge([
			'fieldsData' => $this->fieldsData,
			'listsData' => $this->listsData,
		], $this->jsonSerializeTrait());
	}

	public function jsonDeserialize(array $data = null) {
		$this->fieldsData = isset($data['fieldsData']) ? $data['fieldsData'] : [];
		$this->listsData = isset($data['listsData']) ? $data['listsData'] : [];
	}

	/**
	 * @deprecated 4.0 Support for php serialisation will be removed in Version 4.0
	 * @return string
	 */
	public function serialize() {
		return serialize([
			'fieldsData' => $this->fieldsData,
			'listsData' => $this->listsData,
		]);
	}

	/**
	 * @deprecated 4.0 Support for php serialisation will be removed in Version 4.0
	 * @param string $serialized
	 */
	public function unserialize($serialized) {
		$data = unserialize($serialized);
		$this->class = get_class($this);
		$this->fieldsData = isset($data['fieldsData']) ? $data['fieldsData'] : [];
		$this->listsData = isset($data['listsData']) ? $data['listsData'] : [];
		foreach (\ClassInfo::ancestry(get_called_class()) as $class) {
			if (in_array($class, \Config::inst()->get(\Object::class, 'unextendable_classes'))) {
				continue;
			}
			$extensions = \Config::inst()->get($class, 'extensions',
				\Config::UNINHERITED | \Config::EXCLUDE_EXTRA_SOURCES);

			if ($extensions) foreach ($extensions as $extension) {
				$instance = self::create_from_string($extension);
				$instance->setOwner(null, $class);
				$this->extension_instances[$instance->class] = $instance;
			}
		}
	}

	public function __get($fieldName) {
		return $this->getField($fieldName);
	}

	public function __set($fieldName, $value) {
		return $this->setField($fieldName, $value);
	}

//	public function __call($method, $arguments) {
//		if ($this->hasList($method)) {
//			return $this->getList($method);
//		}
//		//	if (strlen($method) > 3) {
//		//		list($prefix, $fieldName) = str_split($method, 3);
//		//		if ($this->hasField($fieldName)) {
//		//			return $this->{$prefix . "Field"}($arguments);
//		//		}
//		//	}
//		return parent::__call($method, $arguments);
//	}

	public function defineMethods() {
		parent::defineMethods();
		// TODO how to handle method name collisions?
		foreach (static::config()->fields as $field) {
			$this->createMethod("set$field", sprintf('return $obj->setField("%s", $args[0]);', $field));
			$this->createMethod("get$field", sprintf('return $obj->getField("%s");', $field));
			//$this->addWrapperMethod("set$field", 'setField');
			//$this->addWrapperMethod("get$field", 'getField');
		}
		foreach (static::config()->lists as $field) {
			$this->createMethod("set$field", sprintf('return $obj->setList("%s", $args[0]);', $field));
			$this->createMethod("get$field", sprintf('return $obj->getList("%s");', $field));
			//$this->addWrapperMethod("set$field", 'setField');
			//$this->addWrapperMethod("get$field", 'getField');
		}
	}

	public function hasField($name) {
		return in_array($name, static::config()->fields);
	}

	public function getField($name) {
		if ($this->hasField($name)) {
			if (isset($this->fieldsData[$name])) {
				return $this->fieldsData[$name];
			}
			return null;
		}
		throw new \Exception("Could not find field '$name'.");
	}

	public function setField($name, $value) {
		if ($this->hasField($name)) {
			$this->fieldsData[$name] = $value;
			return $this;
		}
		throw new \Exception("Could not find field '$name'.");
	}

	public function hasList($name) {
		return in_array($name, static::config()->lists);
	}

	public function getList($name) {
		if ($this->hasList($name)) {
			if (!isset($this->listsData[$name])) {
				// TODO separate ArrayList and DataList
				$this->listsData[$name] = new ArrayList();
			}
			return $this->listsData[$name];
		}
		throw new \Exception("Could not find field '$name'.");
	}

	public function setList($name, AbstractList $value) {
		if ($this->hasList($name)) {
			$this->listsData[$name] = $value;
			return $this;
		}
		throw new \Exception("Could not find field '$name'.");
	}

	/**
	 * @param array $data
	 * @return $this
	 * @throws \Exception
	 */
	public function update($data) {
		foreach (array_merge(static::config()->lists, static::config()->fields) as $name) {
			if (isset($data[$name])) {
				$value = $data[$name];
				if (is_a($value, ArrayList::class)) {
					if ($this->hasList($name)) {
						$this->setList($name, $value);
					}
				} else if ($this->hasField($name)) {
					$this->setField($name, $value);
				}
			}
		}
		return $this;
	}

	private static $_cache_field_labels = [];

	protected function i18nFields() {
		$fields = [];
		$ancestry = array_reverse(\ClassInfo::ancestry($this->class));
		if ($ancestry) {
			foreach ($ancestry as $ancestorClass) {
				if ($ancestorClass == __CLASS__) {
					break;
				}
				$fields[$ancestorClass] = [];
				foreach ([
							 'field' => (array)\Config::inst()->get($ancestorClass, 'field', \Config::UNINHERITED),
							 'list' => (array)\Config::inst()->get($ancestorClass, 'list', \Config::UNINHERITED),
						 ] as $type => $attrs) {
					$fields[$ancestorClass][$type] = [];
					foreach ($attrs as $name => $spec) {
						$fields[$ancestorClass][$type][$name] = \FormField::name_to_label($name);
					}
				}
			}
		}
		return $fields;
	}

	public function fieldLabels() {
		$cacheKey = $this->class;
		if (!isset(self::$_cache_field_labels[$cacheKey])) {
			$labels = [];
			foreach ($this->i18nFields() as $className => $types) {
				foreach ($types as $type => $defaultLabels) {
					foreach ($defaultLabels as $name => $defaultValue) {
						$labels["{$type}_$name"] = _t("$className.{$type}_$name", $defaultValue);
						if (!isset($labels[$name])) {
							$labels[$name] = $labels["{$type}_$name"];
						}
					}
				}
			}
			self::$_cache_field_labels[$cacheKey] = $labels;
		}
		return self::$_cache_field_labels[$cacheKey];
	}

	public function fieldLabel($name) {
		$labels = $this->fieldLabels();
		return (isset($labels[$name])) ? $labels[$name] : \FormField::name_to_label($name);
	}

	public function provideI18nEntities() {
		$entities = [];
		foreach ($this->i18nFields() as $className => $types) {
			foreach ($types as $type => $defaultLabels) {
				foreach ($defaultLabels as $name => $defaultValue) {
					$entities["$className.{$type}_$name"] = $defaultValue;
				}
			}
		}
		return $entities;
	}

	public function __toString() {
		return Serializer::serialize($this);
	}

	/**
	 * Process tri-state responses from permission-alterting extensions.  The extensions are
	 * expected to return one of three values:
	 *  - false: Disallow this permission, regardless of what other extensions say
	 *  - true: Allow this permission, as long as no other extensions return false
	 *  - NULL: Don't affect the outcome
	 * This method itself returns a tri-state value, and is designed to be used like this:
	 * <code>
	 * $extended = $this->extendedCan('canDoSomething', $member);
	 * if($extended !== null) return $extended;
	 * else return $normalValue;
	 * </code>
	 *
	 * @param String $methodName Method on the same object, e.g. {@link canEdit()}
	 * @param \Member|int $member
	 * @return boolean|null
	 */
	public function extendedCan($methodName, $member) {
		$results = $this->extend($methodName, $member);
		if ($results && is_array($results)) {
			// Remove NULLs
			$results = array_filter($results, function ($v) {
				return !is_null($v);
			});
			// If there are any non-NULL responses, then return the lowest one of them.
			// If any explicitly deny the permission, then we don't get access
			if ($results) return min($results);
		}
		return null;
	}

	/**
	 * @param \Member $member
	 * @return boolean
	 */
	public function canView($member = null) {
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if ($extended !== null) {
			return $extended;
		}
		return \Permission::check('ADMIN', 'any', $member);
	}

	/**
	 * @param \Member $member
	 * @return boolean
	 */
	public function canEdit($member = null) {
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if ($extended !== null) {
			return $extended;
		}
		return \Permission::check('ADMIN', 'any', $member);
	}

	/**
	 * @param \Member $member
	 * @return boolean
	 */
	public function canDelete($member = null) {
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if ($extended !== null) {
			return $extended;
		}
		return \Permission::check('ADMIN', 'any', $member);
	}

	/**
	 * @todo Should canCreate be a static method?
	 * @param \Member $member
	 * @return boolean
	 */
	public function canCreate($member = null) {
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if ($extended !== null) {
			return $extended;
		}
		return \Permission::check('ADMIN', 'any', $member);
	}

	public function i18n_singular_name() {
		// TODO fix class name
		$class = explode('\\', $this->class);
		$class = $class[count($class) - 1];
		return _t("{$this->class}.SINGULARNAME", FormField::name_to_label($class));
	}

	public function i18n_plural_name() {
		$name = $this->i18n_singular_name();
		//if the penultimate character is not a vowel, replace "y" with "ies"
		if (preg_match('/[^aeiou]y$/i', $name)) {
			$name = substr($name, 0, -1) . 'ie';
		}
		return _t("{$this->class}.PLURALNAME", $name . 's');
	}
}


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

namespace Openbizx\Service;

use Openbizx\Object\MetaIterator;

include_once (OPENBIZ_PATH."/messages/securityService.msg");

/**
 * securityService class is the plug-in service of security
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class securityService
{
    public $mode = 'DISABLED';
    private $_securityFilters = array();
    private $_messageFile;
    protected $errorMessage = null;

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

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        $this->mode =   isset($xmlArr["PLUGINSERVICE"]["SECURITY"]["ATTRIBUTES"]["MODE"]) ? $xmlArr["PLUGINSERVICE"]["SECURITY"]["ATTRIBUTES"]["MODE"] : "DISABLED";
        if(strtoupper($this->mode) == 'ENABLED' )
        {
            $this->_securityFilters[] = new securityFilter($xmlArr["PLUGINSERVICE"]["SECURITY"]["URLFILTER"],		"securityFilter",	"URLFilter");
            $this->_securityFilters[] = new securityFilter($xmlArr["PLUGINSERVICE"]["SECURITY"]["DOMAINFILTER"],	"securityFilter",	"DomainFilter");
            $this->_securityFilters[] = new securityFilter($xmlArr["PLUGINSERVICE"]["SECURITY"]["IPFILTER"],		"securityFilter",	"IPFilter");
            $this->_securityFilters[] = new securityFilter($xmlArr["PLUGINSERVICE"]["SECURITY"]["AGENTFILTER"],		"securityFilter",	"AgentFilter");
            $this->_securityFilters[] = new securityFilter($xmlArr["PLUGINSERVICE"]["SECURITY"]["POSTFILTER"],		"securityFilter",	"PostFilter");
            $this->_securityFilters[] = new securityFilter($xmlArr["PLUGINSERVICE"]["SECURITY"]["GETFILTER"],		"securityFilter",	"GetFilter");
        }
    }

    /**
     * Get error message
     *
     * @return string
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    /**
     * Proses filter
     *
     * @return boolean
     */
    public function processFilters()
    {
        foreach($this->_securityFilters as $filter)
        {
            $filter->processRules();
            if($filter->getErrorMessage())
            {
                $this->errorMessage = $filter->getErrorMessage();
                return false;
            }
        }
        return true;

    }
}

/**
 * securityFilter class is helper class for security filter
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class securityFilter extends MetaIterator
{
    protected $name = null;
    protected $mode = 'DISABLED';
    protected $rules = null;
    protected $errorMessage = null;

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

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @param string $filterName
     * @param string $ruleName
     * @return void
     */
    protected function readMetadata(&$xmlArr, $filterName, $ruleName)
    {
        $this->objectName = $ruleName;
        $this->mode =   isset($xmlArr["ATTRIBUTES"]["MODE"]) ? $xmlArr["ATTRIBUTES"]["MODE"] : "DISABLED";
        if(strtoupper($this->mode) == 'ENABLED' )
        {
            $this->rules 	= new MetaIterator($xmlArr["RULE"],	 $ruleName."Rule",	$this);
        }
    }

    /**
     * Get error message
     *
     * @return string
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    /**
     * Proses rule
     *
     * @return boolean|void
     */
    public function processRules()
    {
        if(is_array($this->rules->varValue))
        {
            foreach($this->rules->varValue as $name=>$obj)
            {
                $obj->process();
                if($obj->getErrorMessage())
                {
                    $this->errorMessage = $obj->getErrorMessage();
                    return false;
                }
            }
        }
    }
}

/**
 * iSecurityRule interface is interface for securityRule_Abstract
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
interface iSecurityRule
{
    /**
     * Proses security rule
     */
    public function process();
}

/**
 * securityRule_Abstract class is helper class for security filter
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class securityRule_Abstract implements iSecurityRule
{
    public $objectName      =	null;
    public $action    =	null;
    public $match     =	null;
    public $status     =	null;
    public $effectiveTime =	null;
    public $errorMessage = null;

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

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        $this->objectName 	= $xmlArr["ATTRIBUTES"]["NAME"];
        $this->action	= $xmlArr["ATTRIBUTES"]["ACTION"];
        $this->status	= $xmlArr["ATTRIBUTES"]["STATUS"];
        $this->match 	= $xmlArr["ATTRIBUTES"]["MATCH"];
        $this->effectiveTime = $xmlArr["ATTRIBUTES"]["EFFECTIVETIME"];
    }

    /**
     * Proses security rule
     *
     * @return string
     */
    public function process()
    {
        return true;
    }

    /**
     * Get message error
     *
     * @return string
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    /**
     * Check Effective Time
     *
     * @return boolean
     */
    public function checkEffectiveTime()
    {
        sscanf( $this->effectiveTime, "%2d%2d-%2d%2d",
                $start_hour, $start_min,
                $end_hour, $end_min
        );

        $startTime  = strtotime(date("Y-m-d ").$start_hour.":".$start_min) ? strtotime(date("Y-m-d ").$start_hour.":".$start_min) : strtotime(date("Y-m-d 00:00"));
        $endTime    = strtotime(date("Y-m-d ").$end_hour.":".$end_min) ? strtotime(date("Y-m-d ").$end_hour.":".$end_min) : strtotime(date("Y-m-d 23:59:59"));

        $nowTime    = time();

        if($startTime>0 && $endTime>0)
        {
            //auto convert start time and end time
            if($endTime < $startTime)
            {
                $tmpTime = $startTime;
                $startTime = $endTime;
                $endTime = $tmpTime;
            }

            if($startTime < $nowTime && $nowTime < $endTime )
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

/**
 * URLFilterRule class
 *
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class URLFilterRule extends securityRule_Abstract
{

    /**
     * Proses security rule
     * return true go to check next rule
     * return false report an error and stop checking
     *
     * @return boolean
     */
    public function process()
    {
    	if(strtoupper($this->status)=='ENABLE')
    	{
	        parent::process();
	        if(!$this->checkEffectiveTime())
	        {
	            return true;
	        }
	        else
	        {
	            $url = $_SERVER['REQUEST_URI'];
	            if(preg_match("/".$this->match."/si",$url))
	            {
	                if(strtoupper($this->action)=='OPENBIZ_DENY')
	                {
	                    $this->errorMessage=MessageHelper::getMessage('SECURITYSVC_URL_DENIED');
	                    return false;
	                }elseif(strtoupper($this->action)=='OPENBIZ_ALLOW')
	                {
	                    return true;
	                }
	                return false;
	            }
	        }
    	}
    }
}

/**
 * DomainFilterRule class
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class DomainFilterRule extends securityRule_Abstract
{

    /**
     * Proses security rule
     * return true go to check next rule
     * return false report an error and stop checking
     *
     * @return boolean
     */
    public function process()
    {
    	if(strtoupper($this->status)=='ENABLE')
    	{
	        parent::process();
	        if(!$this->checkEffectiveTime())
	        {
	            return true;
	        }
	        else
	        {
	            $url = $_SERVER['HTTP_HOST'];
	            if(preg_match("/".$this->match."/si",$url))
	            {
	                if(strtoupper($this->action)=='OPENBIZ_DENY')
	                {
	                    $this->errorMessage=MessageHelper::getMessage('SECURITYSVC_DOMAIN_DENIED');
	                    return false;
	                }
	                elseif(strtoupper($this->action)=='OPENBIZ_ALLOW')
	                {
	                    return true;
	                }
	                return false;
	            }
	        }
    	}
    }
}

/**
 * AgentFilterRule class
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class AgentFilterRule extends securityRule_Abstract
{
    /**
     * Proses security rule
     * return true go to check next rule
     * return false report an error and stop checking
     *
     * @return boolean
     */
    public function process()
    {
    	if(strtoupper($this->status)=='ENABLE')
    	{
	        parent::process();
	        if(!$this->checkEffectiveTime())
	        {
	            return true;
	        }
	        else
	        {
	            $url = $_SERVER['HTTP_USER_AGENT'];
	            if(preg_match("/".$this->match."/si",$url))
	            {
	                if(strtoupper($this->action)=='OPENBIZ_DENY')
	                {
	                    $this->errorMessage=MessageHelper::getMessage('SECURITYSVC_AGENT_DENIED');
	                    return false;
	                }
	                elseif(strtoupper($this->action)=='OPENBIZ_ALLOW')
	                {
	                    return true;
	                }
	                return false;
	            }
	        }
    	}
    }
}

/**
 * IPFilterRule class
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class IPFilterRule extends securityRule_Abstract
{
    /**
     * Proses security rule
     * return true go to check next rule
     * return false report an error and stop checking
     *
     * @return boolean
     */
    public function process()
    {
    	if(strtoupper($this->status)=='ENABLE')
    	{
    		parent::process();
	        if(!$this->checkEffectiveTime())
	        {
	            return true;
	        }
	        else
	        {
	            $url = $_SERVER['REMOTE_ADDR'];
	            if(preg_match("/".$this->match."/si",$url))
	            {
	                if(strtoupper($this->action)=='OPENBIZ_DENY')
	                {
	                    $this->errorMessage = MessageHelper::getMessage('SECURITYSVC_IPADDR_DENIED');
	                    return false;
	                }
	                elseif(strtoupper($this->action)=='OPENBIZ_ALLOW')
	                {
	                    return true;
	                }
	                return false;
	            }
	        }
    	}
    }
}

/**
 * PostFilterRule class
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class PostFilterRule extends securityRule_Abstract
{

    /**
     * Proses security rule
     * return true go to check next rule
     * return false report an error and stop checking
     *
     * @return boolean
     */
    public function process()
    {
    	if(strtoupper($this->status)=='ENABLE')
    	{
	        parent::process();
	        if(!$this->checkEffectiveTime())
	        {
	            return true;
	        }
	        else
	        {
	            $post_str = serialize($_POST);
	            if($this->match!="")
	            {
	                if(preg_match("/".$this->match."/si",$post_str))
	                {
	                    if(strtoupper($this->action)=='OPENBIZ_DENY')
	                    {
	                        $this->errorMessage=MessageHelper::getMessage('SECURITYSVC_POST_DENIED');
	                        return false;
	                    }
	                    elseif(strtoupper($this->action)=='OPENBIZ_ALLOW')
	                    {
	                        return true;
	                    }
	                    return false;
	                }
	            }
	            else
	            {
	                return false;
	            }
	        }
    	}
    }
}

/**
 * GetFilterRule class
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class GetFilterRule extends securityRule_Abstract
{

    /**
     * Proses security rule
     * return true go to check next rule
     * return false report an error and stop checking
     *
     * @return boolean
     */
    public function process()
    {
    	if(strtoupper($this->status)=='ENABLE')
    	{
	        parent::process();
	        if(!$this->checkEffectiveTime())
	        {
	            return true;
	        }
	        else
	        {
	            $get_str = serialize($_GET);
	            if(preg_match("/".$this->match."/si",$get_str))
	            {
	                if(strtoupper($this->action)=='OPENBIZ_DENY')
	                {
	                    $this->errorMessage=MessageHelper::getMessage('SECURITYSVC_GET_DENIED');
	                    return false;
	                }
	                elseif(strtoupper($this->action)=='OPENBIZ_ALLOW')
	                {
	                    return true;
	                }
	                return false;
	            }
	        }
    	}
    }
}
?>


<?php

namespace D4rk4ng3l\Container;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use CompiledContainer;

class ContainerLoader
{
    private static $appPath;
    private static $cachePath;
    private static $configPath;

    /**
     * @param string $appPath
     * @param string $env
     *
     * @return CompiledContainer
     */
    public static function getContainer($appPath, $env = null)
    {
        static::$appPath = $appPath;
        static::$cachePath = $appPath . '/app/cache';
        static::$configPath = $appPath . '/app/config';

        $containerCacheFile   = static::$cachePath . '/container.php';
        $containerConfigCache = new ConfigCache($containerCacheFile, $env != 'prod');

        if (!$containerConfigCache->isFresh()) {
            $containerBuilder = static::buildContainer();
            $dumper           = new PhpDumper($containerBuilder);
            $containerConfigCache->write(
                $dumper->dump(array('class' => 'CompiledContainer')),
                $containerBuilder->getResources()
            );
        }

        require_once $containerCacheFile;

        $container = new CompiledContainer();

        return $container;
    }

    /**
     * @return ContainerBuilder
     */
    private static function buildContainer()
    {
        $containerBuilder = new ContainerBuilder();

        $containerBuilder->setParameter('app.path', static::$appPath);

        // 1st Load service parameters
        $yamlFileLoader = new YamlFileLoader($containerBuilder, new FileLocator(static::$configPath));
        $yamlFileLoader->load("parameters.yml");

        // and now the services
        $xmlFileLoader = new XmlFileLoader($containerBuilder, new FileLocator(__DIR__ . '/../../../config'));
        $xmlFileLoader->load("services.xml");

        $containerBuilder->compile();

        return $containerBuilder;
    }
}


<?php

namespace Purethink\CMSBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\SoftDeleteable;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;

/**
 * @ORM\Table(name="component_has_element")
 * @ORM\Entity(repositoryClass="Purethink\CMSBundle\Repository\ComponentHasElementRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 */
class ComponentHasElement implements SoftDeleteable
{
    use SoftDeleteableEntity;
    use TimestampableEntity;

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\Column(type="boolean")
     */
    private $enabled = true;

    /**
     * @Gedmo\SortableGroup
     * @ORM\ManyToOne(targetEntity="Component", inversedBy="elements")
     * @ORM\JoinColumn(onDelete="CASCADE", nullable=false)
     */
    private $component;

    /**
     * @ORM\OneToMany(targetEntity="ComponentHasValue", mappedBy="componentHasElement", cascade={"persist"}, orphanRemoval=true)
     */
    private $componentHasValues;

    /**
     * @Gedmo\SortablePosition
     * @ORM\Column(type="integer")
     */
    private $position;

    public function __toString()
    {
        return (string)$this->getTitle();
    }

    public function getTitle()
    {
        /** @var ComponentHasValue $value */
        foreach ($this->getComponentHasValues() as $value) {
            if ($value->getExtensionHasField()->getIsMainField()) {
                return $value;
            }
        }

        return '';
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add componentHasValues
     *
     * @param ComponentHasValue $componentHasValues
     * @return ComponentHasElement
     */
    public function addComponentHasValue(ComponentHasValue $componentHasValues)
    {
        $componentHasValues->setComponentHasElement($this);

        $this->componentHasValues[] = $componentHasValues;

        return $this;
    }

    /**
     * Remove componentHasValues
     *
     * @param ComponentHasValue $componentHasValues
     */
    public function removeComponentHasValue(ComponentHasValue $componentHasValues)
    {
        $this->componentHasValues->removeElement($componentHasValues);
    }

    /**
     * Get componentHasValues
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getComponentHasValues()
    {
        return $this->componentHasValues;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->componentHasValues = new ArrayCollection();
    }

    /**
     * Set component
     *
     * @param Component $component
     * @return ComponentHasElement
     */
    public function setComponent(Component $component)
    {
        $this->component = $component;

        return $this;
    }

    /**
     * Get component
     *
     * @return Component
     */
    public function getComponent()
    {
        return $this->component;
    }

    /**
     * Set position
     *
     * @param integer $position
     * @return ComponentHasElement
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set enabled
     *
     * @param boolean $enabled
     * @return ComponentHasElement
     */
    public function setEnabled($enabled)
    {
        $this->enabled = $enabled;

        return $this;
    }

    /**
     * Get enabled
     *
     * @return boolean
     */
    public function getEnabled()
    {
        return $this->enabled;
    }
}