<?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: emailService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Service;

use Openbizx\Object\MetaObject;
use Openbizx\Object\MetaIterator;

/**
 * The email service provides access to a \Zend_Mail object in conjunction with a predefined email account.
 * One can simply request the configured email object and work directly with the \Zend_Mail API
 * or use one of several convenience functions.
 * Additional functions bundled with the class are to run email through a template filter
 * or to log attempted emails to a text file or DB Table.
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class emailService extends MetaObject
{

    /**
     * An array of Account objects
     *
     * @var array
     */
    public $accounts = null;

    /**
     * Error Message returned by mail object
     *
     * @var string
     */
    private $_errorMessage;

    /**
     * The default account to be used when issuing email
     *
     * @var unknown_type
     */
    protected $useAccount;

    /**
     * The mail object generated by \Zend_Mail
     *
     * @var \Zend_Mail
     */
    private $_mail;

    /**
     * Is logging enabled?
     *
     * @param boolean
     */
    private $_logEnabled = null;

    /**
     * How should log entries be stored?  Can either use the default logging service or
     *  a BizDataObject in order to log a DB table
     *
     * @param boolean
     */
    private $_logType = 'DEFAULT';

    /**
     * In the case of DB logging, what BizDataObject object should be used to store log entries?
     *
     * @param object
     */
    private $_logObject;

    /**
     * Initialize emailService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
        $this->_constructMail();
        $acct = $this->accounts->current();
        if (!$acct)
            return; //TODO Throw exception
        $this->useAccount($acct->objectName);
    }

    /**
     * Read array meta-data, and store to meta-object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->accounts = new MetaIterator($xmlArr["PLUGINSERVICE"]["ACCOUNTS"]["ACCOUNT"], "EmailAccount");
        $this->_logEnabled = $xmlArr["PLUGINSERVICE"]["LOGGING"]["ATTRIBUTES"]["ENABLED"];
        if ($this->_logEnabled) {
            $this->_logType = $xmlArr["PLUGINSERVICE"]["LOGGING"]["ATTRIBUTES"]["TYPE"];
            $this->_logObject = $xmlArr["PLUGINSERVICE"]["LOGGING"]["ATTRIBUTES"]["OBJECT"];
        }
    }

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

    /**
     * Will construct the initial mail object
     *
     * @return void
     */
    private function _constructMail()
    {
        $this->_mail = new \Zend_Mail('utf-8');
    }

    /**
     * Will set the Default Transport object for the mail object based on the supplied accountname
     *
     * @param string $accountName
     * @return boolean TRUE/FALSE
     */
    public function useAccount($accountName)
    {
        //If a mail object exists, overwrite with new object
        if ($this->_mail)
            $this->_constructMail();

        $this->useAccount = $accountName;
        $account = $this->accounts->get($accountName);

        if ($account->isSMTP == "Y") {
            if ($account->sMTPAuth == "Y") {
                $config = array('auth' => 'login', 'username' => $account->username, 'password' => $account->password, "port" => $account->port, 'ssl' => $account->sSL);
            } else {
                $config = array();
            }
            $mailTransport = new \Zend_Mail_Transport_Smtp($account->host, $config);
            $this->_mail->setDefaultTransport($mailTransport);
        } else {
            require_once 'Zend/Mail/Transport/Sendmail.php';
            $mailTransport = new \Zend_Mail_Transport_Sendmail();
            $this->_mail->setDefaultTransport($mailTransport);
        }
        $this->_mail->setFrom($account->fromEmail, $account->fromName);
        return $this;
    }

    /**
     * A convenience function that will issue an email based on the parameter provided
     * Will log email attempts but will NOT run the body through a template
     *
     * @param array $TOs
     * @param array $CCs
     * @param array $BCCs
     * @param array $subject
     * @param array $body
     * @param array $attachments
     * @param boolean $isHTML
     * @return boolean $result - TRUE on success, FALSE on failure
     */
    public function sendEmail($TOs = null, $CCs = null, $BCCs = null, $subject, $body, $attachments = null, $isHTML = false)
    {
        $mail = $this->_mail;
        // add TO addresses
        if ($TOs) {
            foreach ($TOs as $to) {
                if (is_array($to)) {
                    $mail->addTo($to['email'], $to['name']);
                } else {
                    $mail->addTo($to);
                }
            }
        }
        // add CC addresses
        if ($CCs) {
            foreach ($CCs as $cc) {
                if (is_array($cc)) {
                    $mail->AddCC($cc['email'], $cc['name']);
                } else {
                    $mail->AddCC($cc);
                }
            }
        }
        // add BCC addresses
        if ($BCCs) {
            foreach ($BCCs as $bcc) {
                if (is_array($bcc)) {
                    $mail->AddBCC($bcc['email'], $bcc['name']);
                } else {
                    $mail->AddBCC($bcc);
                }
            }
        }
        // add attachments
        if ($attachments)
            foreach ($attachments as $att)
                $mail->CreateAttachment(file_get_contents($att));
        $mail->setSubject($subject);
        $body = str_replace("\\n", "\n", $body);
        if ($isHTML == TRUE) {
            $mail->setBodyHTML($body);
        } else {
            $mail->setBodyText($body);
        }

        try {
            $result = $mail->Send(); //Will throw an exception if sending fails
            $this->logEmail('Success', $subject, $body, $TOs, $CCs, $BCCs);
            return TRUE;
        } catch (Exception $e) {
            $result = "ERROR: " . $e->getMessage();
            $this->logEmail($result, $subject, $body, $TOs, $CCs, $BCCs);
            return FALSE;
        }
    }

    /**
     * Log that an email attemp was made.
     * We assume it was successfull, since \Zend_Mail throws an exception otherwise
     *
     * @param string $subject
     * @param array $To
     * @param array $CCs
     * @param array $BCCs
     * @return mixed boolean|string|void
     */
    public function logEmail($result, $subject, $body = NULL, $TOs = NULL, $CCs = NULL, $BCCs = NULL)
    {
        //Log the email attempt
        $recipients = '';
        // add TO addresses
        if ($TOs) {
            foreach ($TOs as $to) {
                if (is_array($to)) {
                    $recipients .= $to['name'] . "<" . $to['email'] . ">;";
                } else {
                    $recipients .= $to . ";";
                }
            }
        }
        // add CC addresses
        if ($CCs) {
            foreach ($CCs as $cc) {
                if (is_array($cc)) {
                    $recipients .= $cc['name'] . "<" . $cc['email'] . ">;";
                } else {
                    $recipients .= $cc . ";";
                }
            }
        }
        // add BCC addresses
        if ($BCCs) {
            foreach ($BCCs as $bcc) {
                if (is_array($bcc)) {
                    $recipients .= $bcc['name'] . "<" . $bcc['email'] . ">;";
                } else {
                    $recipients .= $bcc . ";";
                }
            }
        }
        if ($this->_logType == 'DB') {
            $account = $this->accounts->get($this->useAccount);
            $sender_name = $account->fromName;
            $sender = $account->fromEmail;

            // Store the message log
            $boMessageLog = Openbizx::getObject($this->_logObject);
            $mlArr = $boMessageLog->newRecord();
            $mlArr["sender"] = $sender;
            $mlArr["sender_name"] = $sender_name;
            $mlArr["recipients"] = $recipients;
            $mlArr["subject"] = $subject;
            $mlArr["content"] = $body;
            $mlArr["result"] = $result;
            /*
             * as long as data could read from db, its no longer need to addslashes
              //Escape Data since this may contain quotes or other goodies
              foreach ($mlArr as $key => $value)
              {
              $mlArr[$key] = addslashes($value);
              }
             */
            $ok = $boMessageLog->insertRecord($mlArr);
            if (!$ok) {
                return $boMessageLog->getErrorMessage();
            } else {
                return TRUE;
            }
        } else {
            $back_trace = debug_backtrace();
            if ($result == 'Success') {
                $logNum = LOG_INFO;
            } else {
                $logNum = LOG_ERR;
            }
            Openbizx::$app->getLog()->log($logNum, "EmailService", "Sent email with subject - \"$subject\" and body - $body to - $recipients with result $result.", NULL, $back_trace);
        }
    }

}

/**
 * An object that stores email account data from the service config file.
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class EmailAccount extends MetaObject
{

    public $objectName;
    public $host;
    public $port;
    public $sSL;
    public $fromName;
    public $fromEmail;
    public $isSMTP;
    public $sMTPAuth;
    public $username;
    public $password;

    /**
     * Load the supplied array of config data into the object
     *
     * @param array $xmlArr
     */
    public function __construct($xmlArr)
    {
        $this->objectName = $xmlArr["ATTRIBUTES"]["NAME"];
        $this->host = $xmlArr["ATTRIBUTES"]["HOST"];
        $this->port = $xmlArr["ATTRIBUTES"]["PORT"];
        $this->sSL = $xmlArr["ATTRIBUTES"]["SSL"];
        $this->fromName = $xmlArr["ATTRIBUTES"]["FROMNAME"];
        $this->fromEmail = $xmlArr["ATTRIBUTES"]["FROMEMAIL"];
        $this->isSMTP = $xmlArr["ATTRIBUTES"]["ISSMTP"];
        $this->sMTPAuth = $xmlArr["ATTRIBUTES"]["SMTPAUTH"];
        $this->username = $xmlArr["ATTRIBUTES"]["USERNAME"];
        $this->password = $xmlArr["ATTRIBUTES"]["PASSWORD"];
    }

}


<?php

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

class CreateBlocksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blocks', function(Blueprint $table)
        {
            $table->string('name')->index();
            $table->string('title');
            $table->boolean('show');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('blocks');
    }
}


<?php
/**
 * Very basic RBAC-ACL mechanism (Role Based Access Control-Access Control List)
 *	uses a rudimentary "tree" (parent ID reference) to give
 *  VERY BASIC role/group based access control mimicing Apache mod_access
 *  with role/group replacing "host"
 *
 *	https://httpd.apache.org/docs/current/mod/mod_access_compat.html
 *
 *	The following table structure results in this "tree"
 *	with the group 'super' having 2 subgroups 'legal_adviser' & 'industry_adviser'
 *  and all other groups being undifferentiated
 *  subgroups having the option of permission "extension" or "contraction"
 *
 *	$ACL = array (
 *	  'admin',
 *	  'super' =>
 *			array ( 'legal_adviser', 'industry_adviser'	),
 *	  'client',
 *	  'guest'
 *	);
 *
 *  PK	Role		Parent_PK
 *	1	admin		1
 *	2	super_user	2
 *	3	client		3
 *	4	CSR			2
 *	5	Tech		2
 *	6	guest		6
 *
 *  see AUTOLOAD/acl.global.php for $perms = array() structures
 *  applied to menu item permissions in /_UI/MAIN_UI/menu.php
 *
 *
 * @author	Jason Medland<jason.medland@gmail.com>
 * @package	JCORE\SERVICE\AUTH
 *
 */

namespace JCORE\SERVICE\AUTH;
/**
* we DGAF about exposing this as a public API class
* so we don't need to extend from SOA_BASE
* use JCORE\TRANSPORT\SOA\SOA_BASE as SOA_BASE;
*/
use JCORE\SERVICE\AUTH\USER_ROLE_ENTITY as USER_ROLE_ENTITY;
use JCORE\SERVICE\AUTH\CRUDE_ACL_ENTITY as CRUDE_ACL_ENTITY;

/**
* just-core/foundation/CORE/AUTH/AUTH.interface.php
* https://chglongstone.github.io/just-core/api/classes/JCORE.AUTH.AUTH_INTERFACE.html
*/
use JCORE\AUTH\AUTH_INTERFACE as AUTH_INTERFACE;

/**
 * Class CRUDE_ACL
 * ALL PERMISSION FAILURES EVALUATE TO FALSE
 *
 * ALLOW === TRUE
 * DENY === FALSE
 *
 * @package JCORE\SERVICE\AUTH
*/
class CRUDE_ACL  implements AUTH_INTERFACE{
	/**
	* @access public
	* @var string
	*/
	public $ROLE_LIST = null;
	/**
	* @access public
	* @var string
	*/
	public $WORKING_RULE = null;
	/**
	* @access public
	* @var string
	*/
	public $WORKING_ROLE = null;
	/**
	* @access public
	* @var string
	*/
	public $ERROR_MESSAGE = null;
	/**
	* STRICT to return FLASE by default from authorizeDeny
	* or any other value to return TRUE by default
	* this could be pulled from the config
	*
	* @access public
	* @var string
	*/
	public $PERMISSIVE = 'STRICT';

	/**
	* DESCRIPTOR: an empty constructor, the service MUST be called with
	* the service name and the service method name specified in the
	* in the method property of the JSONRPC request in this format
	* 		""method":"AJAX_STUB.aServiceMethod"
	*
	* @param param
	* @return return
	*/
	public function __construct(){
		return;
	}
	/**
	* initialize
	* @param array args
	* @return return
	*/
	public function init($args){
		#echo __METHOD__.'@'.__LINE__.'  '.'
';
		/**
		* acl.global.php
		*/
		#$this->config = $GLOBALS["CONFIG_MANAGER"]->getSetting('AUTH','ACL_ENTITY_CONTAINER','RULE');
		#$this->config = $GLOBALS["CONFIG_MANAGER"]->getSetting('AUTH','ACL_ENTITY_CONTAINER','ROLE');
		$this->CRUDE_USER_ROLE_ENTITY = new CRUDE_USER_ROLE_ENTITY();
		#echo __METHOD__.'@'.__LINE__.'  '.'
';
		#$this->ROLE_TABLE = $this->CRUDE_USER_ROLE_ENTITY->getRoleTable();
		#$this->ROLE_TREE = $this->CRUDE_USER_ROLE_ENTITY->getRoleTree();
		$this->ROLE_LIST = $this->CRUDE_USER_ROLE_ENTITY->getRoleList();
		#echo __METHOD__.'@'.__LINE__.'$this->ROLE_LIST
['.var_export($this->ROLE_LIST, true).']
'.'
';
		/***/
		$this->CRUDE_ACL_ENTITY = new CRUDE_ACL_ENTITY();
		#$this->RULE_TABLE = $this->CRUDE_ACL_ENTITY->getRuleTable();
		#$this->RULE_TREE = $this->CRUDE_ACL_ENTITY->getRuleTree();
		$this->RULE_LIST = $this->CRUDE_ACL_ENTITY->getRuleList();
		#echo __METHOD__.'@'.__LINE__.'$this->RULE_LIST
['.var_export($this->RULE_LIST, true).']
'.'
';
		/***/
		$this->ACL_SCHEMES = $GLOBALS["CONFIG_MANAGER"]->getSetting('AUTH','CRUDE_ACL_SCHEMES');

		return;
	}

	/**
	* authenticate
	*
	* @params array
	* @return bool
	*/
	public function authenticate($params = null){
		if(isset($_SESSION['role_id'])){

			return true;
		}
		return false;

	}

	/**
	* DESCRIPTOR: authorize
	* https://httpd.apache.org/docs/current/mod/mod_access_compat.html#order
	* Allow,Deny
	*	First, all Allow directives are evaluated; at least one must match,
	*	or the request is rejected. Next, all Deny directives are evaluated.
	*	If any matches, the request is rejected. Last, any requests which do
	*	not match an Allow or a Deny directive are denied by default.
	*
	* Deny,Allow
	*	First, all Deny directives are evaluated; if any match, the request is
	*	denied unless it also matches an Allow directive. Any requests which do
	*	not match any Allow or Deny directives are permitted.
	*
	* @params array
	* @return this->serviceResponse
	*/
	public function authorize($params = null){
		#echo __METHOD__.'@'.__LINE__.'$args
['.var_export($params, true).']
'.'
';
		$this->init($params);
		$_SESSION['role_id'];
		if(!isset($params["role"])){
			return false;
		}

		if(!isset($params["rule"])){
			return false;
		}
		$this->WORKING_ROLE = $this->CRUDE_USER_ROLE_ENTITY->getRole($params["role"]);
		if(is_numeric($params["role"])){
			#echo __METHOD__.'@'.__LINE__.'$args
['.var_export($params, true).']
'.'
';
			$params["role"] = $this->CRUDE_USER_ROLE_ENTITY->getRoleName($params["role"]);
		}
		#echo __METHOD__.'@'.__LINE__.'$args
['.var_export($params, true).']
'.'
'.PHP_EOL;
		#$params["rule"] =
		#echo __METHOD__.'@'.__LINE__.'$workingRole
['.var_export($workingRole, true).']
'.'
';

		$this->WORKING_RULE = $this->CRUDE_ACL_ENTITY->getRule($params["rule"]);
		#echo __METHOD__.'@'.__LINE__.'$this->WORKING_ROLE
['.var_export($this->WORKING_ROLE, true).']
'.'
'.PHP_EOL;
		#echo __METHOD__.'@'.__LINE__.'$this->WORKING_RULE
['.var_export($this->WORKING_RULE, true).']
'.'
'.PHP_EOL;
		$authtest = false;

		switch(strtoupper($params["order"])){//authType
			case "ALLOW":
			case "ALLOW,DENY":
				$authtest = $this->authorizeAllowDeny($params);
				break;
			case "DENY":
			case "DENY,ALLOW":
				$authtest = $this->authorizeDenyAllow($params);
				break;
			default:
				return false;
				break;
		}
		#echo __METHOD__.'@'.__LINE__.'$authtest
['.var_export($authtest, true).']
'.'
'.PHP_EOL;
		return $authtest;
	}
	/**
	* DESCRIPTOR: authorizeAllowDeny
	*  https://httpd.apache.org/docs/current/mod/mod_access_compat.html#order
	*  First, all Allow directives are evaluated; at least one must match,
	*  or the request is rejected. Next, all Deny directives are evaluated.
	*  If any matches, the request is rejected. Last, any requests which do not
	*  match an Allow or a Deny directive are denied by default.
	*
	* @args array
	* @return this->serviceResponse
	*/
	public function authorizeAllowDeny($params = null){
		#echo __METHOD__.'@'.__LINE__.'$args
['.var_export($params, true).']
'.'
';

		if(TRUE === $this->authorizeAllow($params)){
			#echo __METHOD__.'@'.__LINE__.'$params
['.var_export($params, true).']
'.'
';
			return TRUE;
		}

		if(TRUE === $this->authorizeDeny($params)){
			return TRUE;
		}
		$this->getErrorMessage($params);
		return FALSE;

	}
	/**
	* DESCRIPTOR: an example namespace call
	*  https://httpd.apache.org/docs/current/mod/mod_access_compat.html#order
	*  First, all Deny directives are evaluated; if any match, the request is denied
	*  unless it also matches an Allow directive. Any requests which do not match
	*  any Allow or Deny directives are permitted.
	*
	* @args array
	* @return this->serviceResponse
	*/
	public function authorizeDenyAllow($params = null){
		#echo __METHOD__.'@'.__LINE__.'$args
['.var_export($params, true).']
'.'
';

		if(FALSE === $this->authorizeDeny($params)){
			if(TRUE === $this->authorizeAllow($params)){
				return TRUE;
			}

			$this->getErrorMessage($params);
			return FALSE;
		}

		return TRUE;
	}
	/**
	* DESCRIPTOR:  authorizeAllow
	*  https://httpd.apache.org/docs/current/mod/mod_access_compat.html#order
	*
	* Look for the role in the allow list
	* if the role exists in the allow list return true
	*
	* DEFAULT IS FALSE
	*
	* @params array
	* @return bool
	*/
	public function authorizeAllow($params = null){
		#echo __METHOD__.'@'.__LINE__.'$params
['.var_export($params, true).']
'.'
';
		#echo __METHOD__.'@'.__LINE__.'$this->WORKING_RULE
['.var_export($this->WORKING_RULE, true).']
'.'
';
		#$this->WORKING_ROLE; $this->WORKING_RULE;

		if('allow' == $params["order"]){
			if(true === in_array($params["role"], $this->WORKING_RULE[$params["order"]]) ){
				return true;
			}
			if(true === in_array('all', $this->WORKING_RULE[$params["order"]]) ){
				return true;
			}
			/**
			* just for clairity
			*/
			if(true === in_array('none', $this->WORKING_RULE[$params["order"]]) ){
				return false;
			}

		}
		#echo __METHOD__.'@'.__LINE__.'$params
['.var_export($params, true).']
'.'
';
		return FALSE;
	}
	/**
	* DESCRIPTOR: authorizeDeny
	*  https://httpd.apache.org/docs/current/mod/mod_access_compat.html#order
	*
	* Look for the role in the deny list
	* if the role exists in the deny list return deny
	*
	* DEFAULT IS TRUE
	*
	* @args array
	* @return bool
	*/
	public function authorizeDeny($params = null){
		#echo __METHOD__.'@'.__LINE__.'$params
['.var_export($params, true).']
'.'
';
		$this->WORKING_ROLE; $this->WORKING_RULE;

		if('deny' == $params["order"]){
			if(true === in_array($params["role"], $this->WORKING_RULE[$params["order"]]) ){
				return false;
			}
			if(true === in_array('all', $this->WORKING_RULE[$params["order"]]) ){
				return false;
			}
			/**
			* just for clairity
			*/
			if(true === in_array('none', $this->WORKING_RULE[$params["order"]]) ){
				return true;
			}
		}
		if('STRICT' == $this->PERMISSIVE){
			return false;
		}
		return true;
	}
	/**
	* getErrorMessage
	* @args array
	* @return bool
	*/
	public function getErrorMessage($params = null){
		if(isset($this->WORKING_RULE[$params["order"]]["rule_fail_msg"])){
			$this->ERROR_MESSAGE = $this->WORKING_RULE[$params["order"]]["rule_fail_msg"];
			return;
		}
		$this->ERROR_MESSAGE = 'failed authorization';
		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: InputPassword.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Easy\Element\Password;

/**
 * InputPassword class is element for input password
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class InputPassword extends Password
{

    /**
     * Mask character for hidden original/real value
     * @var string
     */
    public $maskChar='*';

    /**
     * length of mask character will be displayed
     * @var number
     */
    public $maskLength=6;

    /**
     * Real value of password
     * @var string
     */
    protected $value_Real;

    public $passwordMask;

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    public function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "input_text";
        $this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : $this->cssClass."_error";
        $this->cssFocusClass = isset($xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"] : $this->cssClass."_focus";

        $this->maskChar = isset($xmlArr["ATTRIBUTES"]["MASKCHAR"]) ? $xmlArr["ATTRIBUTES"]["MASKCHAR"] : $this->maskChar;
        $this->maskLength = isset($xmlArr["ATTRIBUTES"]["MASKLENGTH"]) ? $xmlArr["ATTRIBUTES"]["MASKLENGTH"] : $this->maskLength;
        $this->passwordMask = str_repeat($this->maskChar, $this->maskLength);
    }

    /**
     * Render / draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $value = $this->value;

        	$this->value_Real = $this->value;
            $value = $this->passwordMask;

        $disabledStr = ($this->getEnabled() == "N") ? "DISABLED=\"true\"" : "";
        $style = $this->getStyle();

        $func = $this->getEnabled() == 'N' ? "" : $this->getFunction();
        $formobj = $this->GetFormObj();
        if($formobj->errors[$this->objectName]){
			$func .= "onchange=\"this.className='$this->cssClass'\"";
		}else{
			$func .= "onfocus=\"this.className='$this->cssFocusClass'\" onblur=\"this.className='$this->cssClass'\"";
		}
        $sHTML = "<INPUT TYPE=\"PASSWORD\" NAME='$this->objectName' ID=\"" . $this->objectName ."\" VALUE='$value' $disabledStr $this->htmlAttr $style $func />";
    	if($this->hint){
        	$sHTML.="<script>
        	\$j('#" . $this->objectName . "').tbHinter({
				text: '".$this->hint."',
			});
        	</script>";
        }
        return $sHTML;

    }

    /**
     * Get value of element
     *
     * @return string
     */
    public function getValue()
    {
    	if($this->value==null){
    		$this->value = Openbizx::$app->getClientProxy()->getFormInputs($this->objectName);
    	}
        if($this->value==$this->passwordMask)
        {
    		$rawDataArr = $this->getFormObj()->getActiveRecord();
    		$this->value_Real = $rawDataArr[$this->fieldName];
    		$this->value = $rawDataArr[$this->fieldName];
            return $this->value_Real;
        }
        else
        {
            return $this->value;
        }
    }

    /**
     * Set value of element
     *
     * @param string $value
     * @return void
     */
    public function setValue($value)
    {
        if($value==$this->passwordMask)
        {
            $this->value = $this->value_Real;
        }
        else
        {
            $this->value = $value;
        }
    }

}

?>


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

use Instaphp\Request;
use Instaphp\Response;

/**
 * Tags
 * The Tags class handles all tag based API calls
 * @package Instaphp
 * @version 1.0
 * @author randy sesser <randy@instaphp.com>
 */
class Tags extends InstagramBase
{

    public function __construct($token = null, $config = array())
    {
        parent::__construct($token, $config);
        $this->api_path = '/tags';
    }

    /**
     * Gets infor about a particular tag
     * @access public
     * @param string $tag A tag name
     * @param string $token An access token
     * @return Response
     */
    public function Info($tag = mull)
    {
        if (empty($tag))
            trigger_error("You didn't supply a tag, not sure what whill happen here...", E_USER_WARNING);

        return $this->Get($this->buildUrl($tag));
    }

    /**
     * Gets recent media tagged with $tag
     * @access public
     * @param string $tag A tag name
     * @param string $token An access token
     * @param Array $params An associative array of key/value pairs to pass to the API
     * @return Response
     */
    public function Recent($tag, Array $params = array())
    {
		if (!empty($params))
			$this->AddParams($params);

        return $this->Get($this->buildUrl($tag . '/media/recent'));
    }

    /**
     * Searches for media by tag
     * @access public
     * @param string $query
     * @param string $token
     * @return Response
     */
    public function Search($query = '')
    {
        $this->AddParam('q', $query);
        return $this->Get($this->buildUrl('search'));
    }

}


<?php

/**
 * Openbizx Framework
 *
 * This file contain BizApplication class, the C from MVC of phpOpenBiz framework,
 * and execute it. So bootstrap script simply include this file. For sample of
 * bootstrap script please see controller.php under baseapp/bin
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: BizApplication.php 4882 2012-11-30 07:48:46Z hellojixian@gmail.com $
 */

namespace Openbizx;

/**
 * BizApplication is the class that dispatches client requests to proper objects
 *
 * @package   openbiz.bin
 * @author    Rocky Swen <rocky@phpopenbiz.org> and Openbizx Dev Team
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @access    public
 */
class ClassLoader
{

    private static $_classNameCache = array();

    protected function __construct()
    {
        //  $coreClassMap = include(__DIR__ . DIRECTORY_SEPARATOR  . 'autoload_classmap.php' )  ;
        //  print_r($coreClassMap);
        // exit;
        //self::registerClassMap($coreClassMap);
    }

    /**
     * Class autoloading
     *    - not check $_classNameCache, because autoload called only class not yet load
     *    - not need package
     * @param type $className
     * @return boolean
     */
    public static function autoload($className)
    {
        $filePath = self::getAutoloadLibFileWithPath($className);
        if ($filePath) {
            include_once($filePath); // auto_load
            self::$_classNameCache[$className] = 1; //
            return true;
        }
        return false;
    }

    /**
     * Get openbiz library php file path for autoload, remove metadata package searching
     *
     * @param string $className
     * @return string php library file path
     * */
    public static function getAutoloadLibFileWithPath($className)
    {
        if (!$className) {
            return;
        }

        // use class map first
        if (isset(self::$classMap[$className])) {
            return self::$classMap[$className];
        }

        // search it in cache first
        $cacheKey = $className . "_path";
        if (extension_loaded('apc') && ($filePath = apc_fetch($cacheKey)) != null) {
            return $filePath;
        }

        $filePath = self::getCoreLibFilePath($className);

        // cache it to save file search
        if ($filePath && extension_loaded('apc')) {
            apc_store($cacheKey, $filePath);
        }
        return $filePath;
    }

    /**
     * Load class of MetaObject
     *
     * @param type $className
     * @param type $packageName
     * @return boolean
     */
    public static function loadMetadataClass($className, $packageName = '')
    {
        if (class_exists($className, false)) {
            return true;
        }
        if (isset(self::$_classNameCache[$packageName . $className])) {
            return true;
        }
        $filePath = self::getLibFileWithPath($className, $packageName);
        if ($filePath) {
            include_once($filePath);
            self::$_classNameCache[$packageName . $className] = 1;
            return true;
        }
        return false;
    }

    /**
     * Get core path of class
     *
     * @param string $className class name
     * @return string full file name of class
     */
    public static function getCoreLibFilePath($className)
    {
        // if class not yet collect on class map, scan core path.
        $classFile = $className . '.php';
        // TODO: search the file under bin/, bin/data, bin/ui. bin/service, bin/easy, bin/Easy/element.
        // guess class type and folder
        $lowClassName = strtolower($className);
        if (strrpos($lowClassName, 'service') > 0) {
            $corePaths = array('service/');
        } else if (strrpos($lowClassName, 'form') > 0 || strrpos($lowClassName, 'form') === 0) {
            $corePaths = array('easy/');
        } else if (strrpos($lowClassName, 'view') > 0 || strrpos($lowClassName, 'view') === 0) {
            $corePaths = array('easy/');
        } else if (strrpos($lowClassName, 'dataobj') > 0) {
            $corePaths = array('data/');
        } else {
            $corePaths = array('easy/element/', '', 'data/', 'easy/', 'service/');
        }
        //$corePaths = array('', 'data/', 'easy/', 'easy/element/', 'ui/', 'service/');
        foreach ($corePaths as $path) {
            $_classFile = OPENBIZ_BIN . $path . $classFile;
            //echo "file_exists($_classFile)\n";
            if (file_exists($_classFile)) {
                return $_classFile;
            }
        }
        return null;
    }

    /**
     * Get openbiz library php file path by searching modules/package, /bin/package and /bin
     *
     * @param string $className
     * @return string php library file path
     * */
    public static function getLibFileWithPath($className, $packageName = "")
    {
        if (!$className) {
            return;
        }

        if (isset(self::$classMap[$packageName . $className])) {
            return self::$classMap[$packageName . $className];
        }

        // search it in cache first
        $cacheKey = $className . "_path";
        if (extension_loaded('apc') ) {
            $filePath = apc_fetch($cacheKey);
            if ( $filePath !== null ) {
                return $filePath;
            }
        }

        $filePath = self::findClassFileOnCache($className);
        if ( $filePath !== null ) {
            return $filePath;
        }

        if (strpos($className, ".") > 0) {
            $className = str_replace(".", "/", $className);
        }

        $filePath = null;
        $classFile = $className . ".php";
        $classFile_0 = $className . ".php";
        // convert package name to path, add it to classfile
        $classFileIsFound = false;
        if ($packageName) {
            $path = str_replace(".", "/", $packageName);
            // check the leading char '@'
            $checkExtModule = true;
            if (strpos($path, '@') === 0) {
                $path = substr($path, 1);
                $checkExtModule = false;
            }

            // search in apphome/modules directory first, search in apphome/bin directory then
            $classFiles[0] = Openbizx::$app->getModulePath() . "/" . $path . "/" . $classFile;
            $classFiles[1] = OPENBIZ_APP_PATH . "/bin/" . $path . "/" . $classFile;
            if ($checkExtModule && defined('MODULE_EX_PATH')) {
                array_unshift($classFiles, MODULE_EX_PATH . "/" . $path . "/" . $classFile);
            }
            foreach ($classFiles as $classFile) {
                if (file_exists($classFile)) {
                    $filePath = $classFile;
                    $classFileIsFound = true;
                    break;
                }
            }
        }

        if (!$classFileIsFound) {
            $filePath = self::getCoreLibFilePath($className);
        }
        // cache it to save file search
        if ($filePath && extension_loaded('apc')) {
            apc_store($cacheKey, $filePath);
        }
        /* if (!file_exists($filePath)) {
          trigger_error("Cannot find the library file of $className", E_USER_ERROR);
          } */
        return $filePath;
    }

    /**
     * Find class file location from cache dictionary.
     * @param type $className
     * @return string|null full path filename if found or null if not found
     */
    private static function findClassFileOnCache($className) {
        // search it in cache first
        $cacheKey = $className . "_path";
        if (extension_loaded('apc') ) {
            $filePath = apc_fetch($cacheKey);
            return $filePath;
        }
        return null;
    }

    public static function registerClassMap($classMap)
    {
        self::$classMap = array_merge(self::$classMap, $classMap);
    }

    /**
     * class map for openbiz core class
     * @author agus suhartono
     * @var array
     */
    public static $classMap = array();

}


<?php

namespace UWDOEM\Person;

/**
 * Container class for person and alumni-specific information received from Person Web
 * Service and Student Web Service
 *
 * @method static null|Alumni fromUWNetID() fromUWNetID(string $uwnetid)
 *                            Queries PWS/SWS to generate a Alumni, given a UWNetID.
 * @method static null|Alumni fromUWRegID() fromUWRegID(string $uwregid)
 *                            Queries PWS/SWS to generate a Alumni, given a UWRegID.
 * @method static null|Alumni fromIdentifier() fromIdentifier(string $identifierKey, string $identifierValue)
 *                            Queries PWS/SWS to generate a Person, given an identifier type and value.
 *
 * @package UWDOEM\Person
 */
class Alumni extends Person
{

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

    /**
     * Create an Alumni from a Person and a set of supplementary attributes.
     *
     * @param Person $person
     * @param array  $attrs
     * @return Alumni
     */
    protected static function fill(Person $person, array $attrs)
    {
        $attrs = array_merge(
            $attrs,
            $attrs["PersonAffiliations"]["AlumPersonAffiliation"]
        );

        return parent::fill($person, $attrs);
    }

    /**
     * Create an Alumni from a development ID.
     *
     * @param string $developmentID
     * @return null|Alumni
     */
    public static function fromDevelopmentID($developmentID)
    {
        return static::fromIdentifier("development_id", $developmentID);
    }
}


<?php

namespace Monolyth\Croney;

use InvalidArgumentException;
use Exception;
use ArrayObject;
use Monolog\Logger;

class Scheduler extends ArrayObject
{
    private $now;
    private $minutes = 1;
    private $jobs = [];
    private $logger;

    /**
     * Constructor. Optionally pass a Monolog\Logger.
     *
     * @param Monolog\Logger|null $logger
     * @return void
     */
    public function __construct(Logger $logger = null)
    {
        $this->now = strtotime(date('Y-m-d H:i:00'));
        $this->logger = $logger ?? new ErrorLogger;
    }

    /**
     * Getter. Only accepts `"logger"` as a property.
     *
     * @param string $property
     * @return Monolog\Logger|null
     */
    public function __get(string $property)
    {
        return $property == 'logger' ? $this->logger : null;
    }

    /**
     * Add a job to the schedule.
     *
     * @param string $name
     * @param callable $job The job.
     */
    public function offsetSet($name, $job)
    {
        if (!is_callable($job)) {
            throw new InvalidArgumentException('Each job must be callable');
        }
        $this->jobs[$name] = $job;
    }

    /**
     * Process the schedule and run all jobs which are due.
     *
     * @return void
     */
    public function process() : void
    {
        global $argv;
        $specific = null;
        foreach ($argv as $arg) {
            if (preg_match('@--job=(.*?)$@', $arg, $match)) {
                $specific = $match[1];
            }
        }
        $start = time();
        $tmp = sys_get_temp_dir();
        array_walk($this->jobs, function ($job, $idx) use ($tmp, $specific, $argv) {
            if (isset($specific) && $specific !== $idx) {
                return;
            }
            if (in_array('--verbose', $argv) || in_array('-v', $argv)) {
                echo "Starting $idx...";
            }
            $fp = fopen("$tmp/".md5($idx).'.lock', 'w+');
            flock($fp, LOCK_EX);
            try {
                $job->call($this);
            } catch (NotDueException $e) {
            } catch (Exception $e) {
                $this->logger->addCritial(sprintf(
                    "%s in file %s on line %d",
                    $e->getMessage(),
                    $e->getFile(),
                    $e->getLine()
                ));
            }
            flock($fp, LOCK_UN);
            fclose($fp);
            if (in_array('--verbose', $argv) || in_array('-v', $argv)) {
                echo " [done]\n";
            }
        });
        if (--$this->minutes > 0) {
            $wait = max(60 - (time() - $start), 0);
            if (!getenv('TOAST')) {
                sleep($wait);
            }
            $this->now += 60;
            $this->process();
        }
    }

    /**
     * The job should run "at" the specified time.
     *
     * @param string $datestring A string parsable by `date` that should match
     *  the current script runtime for the job to execute.
     * @return void
     * @throws Monolyth\Croney\NotDueException if the task isn't due yet.
     */
    public function at(string $datestring) : void
    {
        global $argv;
        if (in_array('--all', $argv) || in_array('-a', $argv)) {
            return;
        }
        $date = date($datestring, $this->now);
        if (!preg_match("@$date$@", date('Y-m-d H:i', $this->now))) {
            throw new NotDueException;
        }
    }

    /**
     * Set the number of minutes this process should run.
     *
     * All jobs are run every minute, hence setting this to '5' would cause the
     * loop to run 5 times. After each loop, the scheduler `sleep`s for sixty
     * seconds (minus the seconds it took the loop to run) before starting the
     * next run.
     *
     * Note that this does not guarantee the scheduler will resume _exactly_ on
     * the next minute. If your task involves handling based on e.g. `time()`,
     * make sure to round/truncate/check its value.
     *
     * @param int $minutes
     * @return void
     */
    public function setDuration(int $minutes) : void
    {
        $this->minutes = $minutes;
    }
}


<?php

namespace Interpro\QuickStorage\Laravel\Model;

use Illuminate\Database\Eloquent\Model;

class Block extends Model
{
    protected $primaryKey = 'name';
    public $timestamps = false;
    protected static $unguarded = true;

    public function groups() {

        return $this->hasMany('Interpro\QuickStorage\Laravel\Model\Group', 'block_name');

    }

    public function images() {

        return $this->hasMany('Interpro\QuickStorage\Laravel\Model\Imageitem', 'block_name');

    }

    public function stringfields() {

        return $this->hasMany('Interpro\QuickStorage\Laravel\Model\Stringfield', 'block_name');

    }

    public function textfields() {

        return $this->hasMany('Interpro\QuickStorage\Laravel\Model\Textfield', 'block_name');

    }

    public function numbs() {

        return $this->hasMany('Interpro\QuickStorage\Laravel\Model\Numb', 'block_name');

    }

    public function bools() {

        return $this->hasMany('Interpro\QuickStorage\Laravel\Model\Bool', 'block_name');

    }

    public function pdatetimes() {

        return $this->hasMany('Interpro\QuickStorage\Laravel\Model\Pdatetime', 'block_name');

    }

    public function saveBlock($dataobj)
    {
        $qstorage = config('qstorage');

        if(array_key_exists($this->name, $qstorage))
        {

            $blockstruct = $qstorage[$this->name];

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

            foreach(['stringfields', 'textfields', 'numbs', 'images', 'bools', 'pdatetimes'] as $typename) {

                if(array_key_exists($typename, $dataobj) && array_key_exists($typename, $blockstruct)){

                    $data_fs = $dataobj[$typename];

                    foreach($blockstruct[$typename] as $fieldname)
                    {
                        if(array_key_exists($fieldname, $data_fs)){

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

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

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

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

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

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

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

                                $field->save();

                            }
                        }
                    }
                }
            }

            $this->save();

            return 'OK';

        }else{
            return 'Key '.$this->name.' not found.';
        }

    }

    public function createGroupItem($group_name, $owner_id)
    {

        $groupstruct_invert = $this->getGroupsStruct();

        $dataArr = ['sorter'=>99,'show'=>true, 'stringfields'=>[], 'textfields'=>[], 'numbs'=>[], 'bools'=>[], 'pdatetimes'=>[], 'images'=>[]];

        $blockname = $this->name;

        $groupstruct = config('qstorage')[$this->name]['groups'][$group_name];

        $newGroupItem = new \Interpro\QuickStorage\Laravel\Model\Group();
        $newGroupItem->block_name = $blockname;
        $newGroupItem->group_name = $group_name;
        $newGroupItem->owner_id   = $owner_id;
        $newGroupItem->save();

        $dataArr['id'] = $newGroupItem->id;

        if(array_key_exists('stringfields', $groupstruct))
        {
            foreach($groupstruct['stringfields'] as $fieldname)
            {
                $stringfield = Stringfield::create(['block_name'=>$blockname, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                $newGroupItem->stringfields()->save($stringfield);
                $dataArr['stringfields'][$fieldname]='';
            }
        }

        if(array_key_exists('textfields', $groupstruct))
        {
            foreach($groupstruct['textfields'] as $fieldname)
            {
                $textfield = Textfield::firstOrNew(['block_name'=>$blockname, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                $newGroupItem->textfields()->save($textfield);
                $dataArr['textfields'][$fieldname]='';
            }
        }

        if(array_key_exists('numbs', $groupstruct))
        {
            foreach($groupstruct['numbs'] as $fieldname)
            {
                $numb = Numb::firstOrNew(['block_name'=>$blockname, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                $newGroupItem->numbs()->save($numb);
                $dataArr['numbs'][$fieldname]='';
            }
        }

        if(array_key_exists('bools', $groupstruct))
        {
            foreach($groupstruct['bools'] as $fieldname)
            {
                $boolitem = Bool::firstOrNew(['block_name'=>$blockname, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                $newGroupItem->bools()->save($boolitem);
                $dataArr['bools'][$fieldname]='';
            }
        }

        if(array_key_exists('pdatetimes', $groupstruct))
        {
            foreach($groupstruct['pdatetimes'] as $fieldname)
            {
                $dtitem = Pdatetime::firstOrNew(['block_name'=>$blockname, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                $dtitem->value = new \DateTime();
                $newGroupItem->pdatetimes()->save($dtitem);
                $dataArr['pdatetimes'][$fieldname]= $dtitem->value->format('d.m.Y H:i:s');

            }
        }

        if(array_key_exists('images', $groupstruct))
        {
            foreach($groupstruct['images'] as $fieldname)
            {
                $image = Imageitem::firstOrNew(['block_name'=>$blockname, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                $newGroupItem->images()->save($image);
                $dataArr['images'][$fieldname]=[
                    'alt'=>'',
                    'original_link'=>'',
                    'primary_link'=>'',
                    'secondary_link'=>'',
                    'icon_link'=>'',
                    'preview_link'=>'',
                    'prefix'=>''
                ];
            }
        }

        $newGroupItem->save();

        $dataArr['groups'] = array_fill_keys($groupstruct_invert[$group_name], []);

        return $dataArr;

    }

    private function getGroupsDepth(&$groupstruct_0, $groupname_x, $depth)
    {

        $depth++;
        $maxdepth = $depth;

        foreach ($groupstruct_0 as $groupname => $groupstruct)
        {
            if(array_key_exists('owner', $groupstruct) and $groupstruct['owner'] == $groupname_x)
            {
                $currdepth = $this->getGroupsDepth($groupstruct_0, $groupname, $depth);

                $maxdepth = $currdepth > $maxdepth ? $currdepth : $maxdepth;
            }
        }

        return $maxdepth;

    }

    private function getMainGroupsDepth()
    {

        $depth = 0;

        $groupstruct_0 = config('qstorage.'.$this->name)['groups'];

        foreach ($groupstruct_0 as $groupname => $groupstruct)
        {
            if(!array_key_exists('owner', $groupstruct))
            {
                $dataArr[$groupname] = [];

                $currdepth = $this->getGroupsDepth($groupstruct_0, $groupname, 0);

                $depth = $currdepth > $depth ? $currdepth : $depth;
            }
        }

        return $depth;
    }

    private static function addGroupsFunc($addshow, $depth, $currdepth = 1)
    {
        $currdepth++;

        if ($currdepth > $depth) {
            return function($query){};
        } else {
            $func = static::addGroupsFunc($addshow, $depth, $currdepth);
            return function($query) use ($func, $addshow)
            {
                $query->with([
                    'groups' => $func
                ]);

                if($addshow)
                {
                    $query->where('show', '=', true);
                }
            };
        }
    }

    private static function fillGroups($depth, & $groupstruct_invert, $groups, & $dataArr, $currdepth = 0)
    {
        $currdepth++;

        if($currdepth > $depth){
            return;
        }

        foreach($groups as $item)
        {

            $dataArrItem = ['updated_at'=>$item->updated_at->timestamp, 'id'=>$item->id, 'sorter'=>$item->sorter, 'show'=>$item->show, 'stringfields'=>[], 'textfields'=>[], 'images'=>[], 'bools'=>[], 'pdatetimes'=>[], 'numbs'=>[]];

            $group_name = $item->group_name;

//            if(!array_key_exists($group_name, $dataArr))
//            {
//                $dataArr[$group_name] = [];
//            }

            $fields = & $dataArrItem['stringfields'];
            foreach($item->stringfields as $stringfield)
            {
                $fields[$stringfield->name] = $stringfield->value;
            }

            $fields = & $dataArrItem['textfields'];
            foreach($item->textfields as $textfield)
            {
                $fields[$textfield->name] = $textfield->value;
            }

            $fields = & $dataArrItem['images'];
            foreach($item->images as $image)
            {
                $fields[$image->name] = [
                    'alt'=>$image->alt,
                    'original_link'=>$image->original_link,
                    'primary_link'=>$image->primary_link,
                    'secondary_link'=>$image->secondary_link,
                    'icon_link'=>$image->icon_link,
                    'preview_link'=>$image->preview_link,
                    'prefix'=>$image->prefix
                ];
            }

            $fields = & $dataArrItem['bools'];
            foreach($item->bools as $boolitem)
            {
                $fields[$boolitem->name] = $boolitem->value;
            }

            $fields = & $dataArrItem['pdatetimes'];
            foreach($item->pdatetimes as $dtitem)
            {
                $fields[$dtitem->name] = $dtitem->value;
            }

            $fields = & $dataArrItem['numbs'];
            foreach($item->numbs as $numb)
            {
                $fields[$numb->name] = $numb->value;
            }

            $dataArrItem['groups'] = array_fill_keys($groupstruct_invert[$group_name], []);

            $item_groups = $item->groups;

            static::fillGroups($depth, $groupstruct_invert, $item_groups, $dataArrItem['groups'], $currdepth);

            $dataArr[$group_name]['id'.$item->id] = $dataArrItem;
        }
    }

    public  function getGroupsStruct()
    {
        $groups_conf = config('qstorage.'.$this->name)['groups'];
        $groupstruct_invert = [];

        foreach ($groups_conf as $groupname => $_conf)
        {
            if(!array_key_exists($groupname, $groupstruct_invert))
            {
                $groupstruct_invert[$groupname] = [];
            }

            if(array_key_exists('owner', $_conf))
            {
                if(!array_key_exists($_conf['owner'], $groupstruct_invert))
                {
                    $groupstruct_invert[$_conf['owner']] = [];
                }

                $groupstruct_invert[$_conf['owner']][] = $groupname;
            }
        }

        return $groupstruct_invert;
    }

    private function getGroupItemsArray($addshow = false)
    {

        $groupstruct_0 = config('qstorage.'.$this->name)['groups'];
        $groupstruct_invert = $this->getGroupsStruct();

        $dataArr = [];

        foreach ($groupstruct_0 as $groupname => $groupstruct)
        {
            if(!array_key_exists('owner', $groupstruct))
            {
                $dataArr[$groupname] = [];
            }
        }

        $depth = $this->getMainGroupsDepth();

        //Построение, выполнение запроса
        $query_fields = ['stringfields', 'textfields', 'numbs', 'bools', 'pdatetimes', 'images'];

        if($depth>1)
        {
            $groupsFunc = static::addGroupsFunc($addshow, $depth);
            $query_fields['groups'] = $groupsFunc;
        } else {
            $query_fields[] = 'groups';
        }

        $query = \Interpro\QuickStorage\Laravel\Model\Group::where('block_name','=',$this->name)->with($query_fields)
            ->where('owner_id', '=', 0);

        if($addshow)
        {
            $query->where('show', '=', true);
        }

        $groups = $query->get();

        //Извлечение данных из результатов запроса
        static::fillGroups($depth, $groupstruct_invert, $groups, $dataArr);

        return $dataArr;
    }

    public static function  getBlocksDisplayArray($addshow=false, $block_name='')
    {

        if($block_name!=''){
            $blocks = Block::where('name', '=', $block_name)->with([
                'stringfields'=>function($query){
                    $query->where('group_id','=',0);
                },
                'textfields'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'numbs'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'bools'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'pdatetimes'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'images'=>function($query){
                        $query->where('group_id','=',0);
                    }
            ])->get();
        }else{
            $blocks = Block::with([
                'stringfields'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'textfields'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'numbs'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'bools'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'pdatetimes'=>function($query){
                        $query->where('group_id','=',0);
                    },
                'images'=>function($query){
                        $query->where('group_id','=',0);
                    }
            ])->get();
        }

        $dataArr = [];

        foreach($blocks as $block)
        {
            $dataArr[$block->name] = ['title'=>$block->title, 'stringfields'=>[], 'textfields'=>[], 'images'=>[], 'bools'=>[], 'pdatetimes'=>[], 'numbs'=>[]];

            $block_strfs = & $dataArr[$block->name]['stringfields'];
            foreach($block->stringfields as $stringfield)
            {
                $block_strfs[$stringfield->name] = $stringfield->value;
            }

            $block_textfs = & $dataArr[$block->name]['textfields'];
            foreach($block->textfields as $textfield)
            {
                $block_textfs[$textfield->name] = $textfield->value;
            }

            $block_images = & $dataArr[$block->name]['images'];
            foreach($block->images as $image)
            {
                $block_images[$image->name] = [
                    'alt'=>$image->alt,
                    'original_link'=>$image->original_link,
                    'primary_link'=>$image->primary_link,
                    'secondary_link'=>$image->secondary_link,
                    'icon_link'=>$image->icon_link,
                    'preview_link'=>$image->preview_link,
                    'prefix'=>$image->prefix
                ];
            }

            $block_bools = & $dataArr[$block->name]['bools'];
            foreach($block->bools as $boolitem)
            {
                $block_bools[$boolitem->name] = $boolitem->value;
            }

            $block_pdatetimes = & $dataArr[$block->name]['pdatetimes'];
            foreach($block->pdatetimes as $dtitem)
            {
                $block_pdatetimes[$dtitem->name] = $dtitem->value;
            }

            $block_numbs = & $dataArr[$block->name]['numbs'];
            foreach($block->numbs as $numb)
            {
                $block_numbs[$numb->name] = $numb->value;
            }

            $dataArr[$block->name]['groups'] = $block->getGroupItemsArray($addshow);

        }

        return $dataArr;
    }

    //Создание структуры блоков лэндинга из конфига
    public static function initBlocks($block_name='')
    {
        if($block_name==''){
            //Создаем поля по структуре
            $qstorage = config('qstorage');
        }else{
            $qstorage = [$block_name=>config('qstorage')[$block_name]];
        }

        foreach($qstorage as $blockname => $blockstruct)
        {
            $newBlock = static::find($blockname);

            if(!$newBlock)
            {

                $newBlock = new static;
                $newBlock->name = $blockname;

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

                if(array_key_exists('stringfields', $blockstruct))
                {
                    foreach($blockstruct['stringfields'] as $fieldname)
                    {
                        $stringfield = Stringfield::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('textfields', $blockstruct))
                {
                    foreach($blockstruct['textfields'] as $fieldname)
                    {
                        $textfield = Textfield::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('numbs', $blockstruct))
                {
                    foreach($blockstruct['numbs'] as $fieldname)
                    {
                        $numb = Numb::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('bools', $blockstruct))
                {
                    foreach($blockstruct['bools'] as $fieldname)
                    {
                        $boolitem = Bool::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('pdatetimes', $blockstruct))
                {
                    foreach($blockstruct['pdatetimes'] as $fieldname)
                    {
                        $dtitem = Pdatetime::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('images', $blockstruct))
                {
                    foreach($blockstruct['images'] as $fieldname)
                    {
                        $image = Imageitem::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                $newBlock->save();

                //Создание элементов групп с фиксированным количеством (только для 1-го уровня),
                //для элементов вложенных групп та же процедура будет проделана при создании элемента - владельца.
                foreach($blockstruct['groups'] as $groupstruct)
                {
                    if(array_key_exists('fixed', $groupstruct) && !array_key_exists('owner', $groupstruct))
                    {
                        $fixed = $groupstruct['fixed'];

                        for ($count=0; $count<$fixed; $count++)
                        {
                            //Создание элемента группы

                        }
                    }
                }

            }
        }

        return 'OK';
    }
}


<?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: Listbox.php 3660 2011-04-11 10:16:41Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
//include_once("OptionElement.php");

/**
 * 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 ColumnListbox extends OptionElement
{
    public $blankOption;

	public function getItemValue($id)
	{
		$valueArr = $this->value;
		return $valueArr[$id];
	}

	public function setValue($value)
	{
		Openbizx::$app->getSessionContext()->loadObjVar($this->getFormObj()->objectName, $this->objectName, $this->value);
		$valueArr = $_POST[$this->objectName];
		if(is_array($valueArr))
		{
			foreach($valueArr as $key=>$value)
			{
				$this->value[$key] = $value;
			}
		}
		Openbizx::$app->getSessionContext()->saveObjVar($this->getFormObj()->objectName, $this->objectName, $this->value);
	}

    /**
     * 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;
    }
    /**
     * 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->blankOption = isset($xmlArr["ATTRIBUTES"]["BLANKOPTION"]) ? $xmlArr["ATTRIBUTES"]["BLANKOPTION"] : null;
    }

    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
    	$rec = $this->getFormObj()->getActiveRecord();
		$recId = $rec["Id"];

        $fromList = array();
        $this->getFromList($fromList);
        $value = $this->getItemValue($recId)!==null?$this->getItemValue($recId):$this->getDefaultValue();
        $valueArray = explode(',', $value);

        $disabledStr = ($this->getEnabled() == "N") ? "DISABLED=\"true\"" : "";
        $style = $this->getStyle();
        $func = $this->getFunction();

        //$sHTML = "<SELECT NAME=\"" . $this->objectName . "[]\" ID=\"" . $this->objectName ."\" $disabledStr $this->htmlAttr $style $func>";
        $sHTML = "<SELECT NAME=\"" . $this->objectName . "[$recId]\" ID=\"" . $this->objectName ."\" $disabledStr $this->htmlAttr $style $func>";

        if ($this->blankOption) // ADD a blank option
        {
            $entry = explode(",",$this->blankOption);
            $text = $entry[0];
            $value = ($entry[1]!= "") ? $entry[1] : null;
            $entryList = array(array("val" => $value, "txt" => $text ));
            $fromList = array_merge($entryList, $fromList);
        }

        $defaultValue = null;
        foreach ($fromList as $option)
        {
            $test = array_search($option['val'], $valueArray);
            if ($test === false)
            {
                $selectedStr = '';
            }
            else
            {
                $selectedStr = "SELECTED";
                $defaultValue = $option['val'];
            }
            $sHTML .= "<OPTION VALUE=\"" . $option['val'] . "\" $selectedStr>" . $option['txt'] . "</OPTION>";
        }
        if($defaultValue == null){
        	$defaultOpt = array_shift($fromList);
        	$defaultValue = $defaultOpt['val'];
        	array_unshift($fromList,$defaultOpt);
        }

        $this->setValue($defaultValue);
        $sHTML .= "</SELECT>";
        return $sHTML;
    }
}

?>


<?php

/**
 * The MIT License
 *
 * Copyright (c) 2016, Coding Matters, Inc. (Gab Amba <gamba@gabbydgab.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.
 */

namespace AimWorld;

use AimWorld\Options\ModuleOptions;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    private $config = [];

    public function onBootstrap(MvcEvent $event)
    {
        $eventManager = $event->getApplication()->getEventManager();
        $eventManager->attach('dispatch', [$this, 'configSiteVariables'], 100);

        $listener = new ModuleRouteListener();
        $listener->attach($eventManager);
    }

    public function configSiteVariables(MvcEvent $event)
    {
        // Fetch configuration
        $config     = $event->getApplication()->getServiceManager()->get("Config");
        $options    = (array_key_exists('aim_world_settings', $config)) ? $config['aim_world_settings'] : [];
        $variables  = new ModuleOptions($options);

        // Set configuration
        $event->getViewModel()->setVariables($variables->toArray());
    }

    /**
     * Return default configuration for zend-mvc applications.
     */
    public function getConfig()
    {
        $provider = new ConfigProvider();

        $this->config = $provider->getTemplateConfig();
        $this->config['middleware_pipeline']    = $provider->getMiddlewareConfig();
        $this->config['service_manager']        = $provider->getDependencyConfig();
        $this->config['router']['routes']       = $provider->getRouteConfig();
        $this->config['navigation']             = $provider->getNavigationConfig();
        $this->config['controllers']            = $provider->getControllerConfig();
        $this->config['controller_plugins']     = $provider->getControllerPluginConfig();

        // Overrides the default config to use Glob module config
        return array_merge_recursive($this->config, $provider->getGlobConfig());
    }
}


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

class WebRequest
{
	/**
	 *
	 * @var resource A cURL multi handle resource
	 * @access private
	 */
	private $mh = null;

	/**
	 *
	 * @var array Array of active requests
	 * @access private
	 */
	private $_requests;

	/**
	 *
	 * @var array Array of stored responses
	 * @access private
	 */
	private $_responses;
	/**
	 *
	 * @var array Array of common cURL options
	 * @access private
	 */
	private $_options = array(
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 2,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_ENCODING => ''
	);

	private $config;

	/**
	 *
	 * @var WebRequest An instance of WebRequest (aka Mr. Singleton)
	 * @access private
	 */
	static $_instance = null;

	/**
	 * Constructor is private final. Can only be instantiated via WebRequest::Instance()
	 * @access private
	 * @final
	 */
	private final function __construct($config)
	{
		$this->mh = curl_multi_init();
		$this->config = $config;

		if (isset($this->config['endpoint_timeout']))
			$this->_options[CURLOPT_TIMEOUT] = $this->config['endpoint_timeout'];

		$this->_options[CURLOPT_USERAGENT] = 'Instaphp/' . $this->config['version'];

		if(isset($this->config['no_verify_peer']))
			$this->_options[CURLOPT_SSL_VERIFYPEER] = false;

		//-- this is an interesting hack to make curl+ssl+windows follow redirects
		//-- without skipping verification. For some reason, the version of libcurl/curl
		//-- included with ZendServer CE doesn't use the systems CA bundle, so, we specify
		//-- the path to the cert here (via config setting)
		if (isset($this->config['ca_cert_bundle_path']) && !empty($this->config['ca_cert_bundle_path'])) {
			$this->_options[CURLOPT_SSL_VERIFYPEER] = true;
			$this->_options[CURLOPT_SSL_VERIFYHOST] = 2;
			$this->_options[CURLOPT_SSLVERSION] = 3;
			$this->_options[CURLOPT_CAINFO] = $this->config['ca_cert_bundle_path'];
		}

		$this->_options[CURLOPT_HTTPHEADER] = array(
			"Connection: keep-alive",
			"Keep-Alive: 300",
			"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
			"Accept-Language: en-us,en;q=0.5"
		);

		$this->_requests = array();
		$this->_responses = array();
	}

	/**
	 * Instantiates a new WebRequest if one does not already exist
	 *
	 * @return WebRequest A single instance of WebRequest
	 * @access public
	 * @static
	 */
	public static function Instance($config)
	{
		if (null == static::$_instance)
			static::$_instance = new self($config);
		return static::$_instance;
	}

	/**
	 * Convenience method for http GET requests
	 *
	 * @param string $url The url to Get
	 * @param array $parameters An array of key/value pairs to pass
	 * @return WebRequestManager A WebRequestManager to manage the current request
	 * @access public
	 */
	public function Get($url, $parameters = array())
	{
		return $this->Create($url, "GET", $parameters);
	}

	/**
	 * Convenience method for http POST requests
	 *
	 * @param string $url The url to POST
	 * @param array $parameters An array of key/value pairs to pass
	 * @return WebRequestManager A WebRequestManager to manage the current request
	 * @access public
	 */
	public function Post($url, $parameters = array())
	{
		return $this->Create($url, "POST", $parameters);
	}

	/**
	 * Convenience method for http DELETE requests
	 *
	 * @param string $url The url to DELETE
	 * @param array $parameters An array of key/value pairs to pass
	 * @return WebRequestManager A WebRequestManager to manage the current request
	 * @access public
	 */
	public function Delete($url, $parameters = array())
	{
		return $this->Create($url, "DELETE", $parameters);
	}

	/**
	 * Creates a new cURL reuest and adds to the request queue for processing
	 * @param string $url The url in which to make the request
	 * @param string $method The method used to make the request [GET|POST|DELETE]
	 * @param array $parameters Array of key/value pairs to pass to the request
	 * @return mixed A WebRequestManager to manage the current request on success, Error on failure
	 * @access public
	 */
	public function Create($url, $method = 'GET', $parameters = array())
	{
		$ch = curl_init();
		$key= (string)$ch;
		$query = '';
		$res = null;

		$options = $this->_options;

		foreach ($parameters as $k => $v)
			$query .= ((strlen ($query) == 0) ? "":"&") . sprintf('%s=%s', $k, urlencode($v));

		switch (strtolower($method))
		{
			case 'post':
				$options[CURLOPT_POST] = true;
				$options[CURLOPT_POSTFIELDS] = $query;
				break;
			case 'delete':
				$options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
				$url .= '?' . $query;
				break;
			default:
				$url .= '?' . $query;
				break;
		}

		$options[CURLOPT_URL] = $url;
		curl_setopt_array($ch, $options);

		$this->_requests[$key] = $ch;

		$res = curl_multi_add_handle($this->mh, $this->_requests[$key]);
		if ($res == CURLM_OK) {
			curl_multi_exec($this->mh, $active);
			return new WebRequestManager($key, $this->config);
		}
		return new Error('cURLError', curl_error($ch), curl_errno($ch), $options[CURLOPT_URL]);
	}

	/**
	 *
	 * @param string $key The key used to get the current request from the queue
	 * @return WebResponse  A WebResponse for the $key
	 * @access public
	 */
	public function GetResponse($key = null)
	{
		if (isset($this->_responses[$key]))
			return $this->_responses[$key];

		$running = null;

		do {
			$res = curl_multi_exec($this->mh, $current);
			if (null !== $running && $current != $running) {
				$this->store();

				if (isset($this->_responses[$key]))
					return $this->_responses[$key];

			}
			$running = $current;
		} while ($current > 0);

		return false;
	}

	/**
	 * Runs through the request queue and processes completed requests
	 * @access private
	 */
	private function store()
	{
		while ($finished = curl_multi_info_read($this->mh, $messages)) {
			$key = (string)$finished["handle"];
			$this->_responses[$key] = new WebResponse(curl_multi_getcontent($finished["handle"]), curl_getinfo($finished["handle"]));
			curl_multi_remove_handle($this->mh, $finished["handle"]);
		}
	}
}


<?php
/**
 * OAuth 2.0 Bearer Token Type
 *
 */

namespace OAuth2\Server\TokenType;

use OAuth2\Server\Request\HandlerInterface as RequestHandler;

class Bearer extends AbstractTokenType implements TokenTypeInterface
{
    /**
     * {@inheritdoc}
     */
    public function generateResponse()
    {
        $return = [
            'access_token'  =>  $this->getParam('access_token'),
            'token_type'    =>  'Bearer',
            'expires_in'    =>  $this->getParam('expires_in'),
        ];

        if (!is_null($this->getParam('refresh_token'))) {
            $return['refresh_token'] = $this->getParam('refresh_token');
        }

        return $return;
    }

    /**
     * {@inheritdoc}
     */
    public function determineAccessTokenInHeader(RequestHandler $requestHandler, $authHeader = 'Authorization')
    {
        $header = $requestHandler->getHeader($authHeader);
        $accessToken = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header));

        return ($accessToken === 'Bearer') ? '' : $accessToken;
    }
}


<?php

namespace Environaut\Config\Reader;

use Environaut\Config\Reader\IConfigReader;

/**
 * Reads configuration data from XML formatters.
 */
class XmlConfigReader implements IConfigReader
{
    /**
     * @var Environaut\Config\Reader\Dom\DomDocument
     */
    protected $doc;

    /**
     * Reads the config from the given location and
     * returns the data as an associative array.
     *
     * @param mixed $location location to read config data from (usually file/directory path)
     *
     * @return array config data as associative array
     *
     * @throws \InvalidArgumentException in case of problems handling the given location
     * @throws \DomException in case of schema validation errors
     */
    public function getConfigData($location)
    {
        if (is_dir($location)) {
            $location = $location . DIRECTORY_SEPARATOR . 'environaut.xml';
        }

        $this->doc = $doc = new Dom\DomDocument();
        $doc->load($location, LIBXML_NOCDATA);
        $doc->xinclude(LIBXML_NOCDATA);
        $doc->schemaValidate(__DIR__ . '/Schema/environaut.xsd');

        $config_data = array();

        $value = $doc->getElementValue('name');
        if (null !== $value) {
            $config_data['name'] = $value;
        }

        $value = $doc->getElementValue('description');
        if (null !== $value) {
            $config_data['description'] = $value;
        }

        $value = $doc->getElementValue('introduction');
        if (null !== $value) {
            $config_data['introduction'] = $value;
        }

        $keywords_element = $doc->getElement('keywords');
        if (null !== $keywords_element) {
            $keywords = array();
            foreach ($keywords_element->getChildren('keyword') as $keyword) {
                $keywords[] = (string) $keyword;
            }
            if (!empty($keywords)) {
                $config_data['keywords'] = $keywords;
            }
        }

        $element = $doc->getElement('cache');
        if (null !== $element) {
            $config_data['cache'] = $element->getParameters();
            $value = $element->getAttributeValue('class');
            if (null !== $value) {
                $config_data['cache']['__class'] = $value;
            }
        }

        $element = $doc->getElement('report');
        if (null !== $element) {
            $config_data['report'] = $element->getParameters();
            $value = $element->getAttributeValue('class');
            if (null !== $value) {
                $config_data['report']['__class'] = $value;
            }
        }

        $element = $doc->getElement('runner');
        if (null !== $element) {
            $config_data['runner'] = $element->getParameters();
            $value = $element->getAttributeValue('class');
            if (null !== $value) {
                $config_data['runner']['__class'] = $value;
            }
        }

        $element = $doc->getElement('export');
        if (null !== $element) {
            $config_data['export'] = $element->getParameters();
            $formatter_nodes = $element->get('formatters');
            $formatters = array();
            foreach ($formatter_nodes as $formatter_node) {
                $attributes = $formatter_node->getAttributes();
                foreach ($attributes as $name => $value) {
                    if ($name === 'class') {
                        $attributes['__class'] = $value;
                    }
                }
                unset($attributes['class']);
                $parameters = $formatter_node->getParameters();
                $formatters[] = array_merge($parameters, $attributes);
            }
            $config_data['export']['formatters'] = $formatters;
            $value = $element->getAttributeValue('class');
            if (null !== $value) {
                $config_data['export']['__class'] = $value;
            }
        }

        $element = $doc->getElement('checks');
        if (null !== $element) {
            $checks = array();
            $check_nodes = $element->get('check');
            foreach ($check_nodes as $check) {
                $attributes = $check->getAttributes();
                foreach ($attributes as $name => $value) {
                    if ($name === 'class') {
                        $attributes['__class'] = $value;
                    } elseif ($name === 'name') {
                        $attributes['__name'] = $value;
                    } elseif ($name === 'group') {
                        $attributes['__group'] = $value;
                    }
                }
                unset($attributes['class']);
                unset($attributes['name']);
                unset($attributes['group']);
                $parameters = $check->getParameters();
                $checks[] = array_merge($parameters, $attributes);
            }
            $config_data['checks'] = $checks;
        }

        return $config_data;
    }

    /**
     * Returns the DomDocument instance that was used for reading the config file.
     *
     * @return Environaut\Config\Reader\Dom\DomDocument or null
     */
    public function getDocument()
    {
        return $this->doc;
    }
}