public static function readLine(string $file, callable $callable, ?int $length = 4096): void
	{
		if (!$handle = fopen($file, "r")) {
			throw new IOException("File '$file' cannot be open.");
		}

		$fgets = function () use (&$handle, &$length) {
			if ($length !== null) {
				return fgets($handle, $length);
			} else {
				return fgets($handle);
			}
		};

		$line = 1;
		$stopped = false;
		while (($buffer = $fgets()) !== false) {
			if ($callable($buffer, $line++) === false) {
				$stopped = true;
				break;
			}
		}
		if (!$stopped && !feof($handle)) {
			throw new IOException("Error: unexpected fgets() fail '$file'");
		}
		fclose($handle);
	}

Cteni ze souboru po radcich
@param string $file
@param callable $callable function($buffer, $line) $line -> cislo radku, pokud metoda vrati false, ukonci se cyklus
@param int|null $length
@throws IOException


public static function size(string $path): float
	{
		if (is_file($path)) {
			return filesize($path);
		} else {
			$size = 0;
			foreach (glob(rtrim($path, '/') . '/*', GLOB_NOSORT) as $each) {
				$size += self::size($each);
			}
			return $size;
		}
	}

public static function size ( string $ path ) : float { if ( is_file ( $ path ) ) { return filesize ( $ path ) ; } else { $ size = 0 ; foreach ( glob ( rtrim ( $ path , '/' ) . '/*' , GLOB_NOSORT ) as $ each ) { $ size += self :: size ( $ each ) ; } return $ size ; } }

Vrati velikost souboru nebo slozky
@param string $path
@return float


public static function getClasses(string $file): array
	{
		$php_code = file_get_contents($file);
		$classes = [];
		$tokens = token_get_all($php_code);
		$count = count($tokens);
		for ($i = 2; $i < $count; $i++) {
			if ($tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) {
				$class_name = $tokens[$i][1];
				$classes[] = $class_name;
			}
		}
		return $classes;
	}

public static function getClasses ( string $ file ) : array { $ php_code = file_get_contents ( $ file ) ; $ classes = [ ] ; $ tokens = token_get_all ( $ php_code ) ; $ count = count ( $ tokens ) ; for ( $ i = 2 ; $ i < $ count ; $ i ++ ) { if ( $ tokens [ $ i - 2 ] [ 0 ] == T_CLASS && $ tokens [ $ i - 1 ] [ 0 ] == T_WHITESPACE && $ tokens [ $ i ] [ 0 ] == T_STRING ) { $ class_name = $ tokens [ $ i ] [ 1 ] ; $ classes [ ] = $ class_name ; } } return $ classes ; }

Vrati nazvy trid v souboru
@param string $file
@return string[]


public function add($methods, string $uri, $target): Route
    {
        // Create new Route instance
        $route = new Route($methods, $uri, $target, $this->config);

        // Index the route
        $this->indexRoute($route);

        return $route;
    }

public
function
add
(
$
methods
,
string
$
uri
,
$
target
)
:
Route
{
// Create new Route instance
$
route
=
new
Route
(
$
methods
,
$
uri
,
$
target
,
$
this
->
config
)
;
// Index the route
$
this
->
indexRoute
(
$
route
)
;
return
$
route
;
}

Add a route

@param array $methods
@param string $uri
@param string|callable $target
@return Route


public function resolve(Request $request): ?Route
    {
        foreach( $this->indexes[$request->getMethod()] ?? [] as $route ){

            if( $route->matchUri($request->getPathInfo()) &&
                $route->matchMethod($request->getMethod()) &&
                $route->matchHostname($request->getHost()) &&
                $route->matchScheme($request->getScheme()) ){

                return $route;
            }
        }

        return null;
    }

public function resolve ( Request $ request ) : ? Route { foreach ( $ this -> indexes [ $ request -> getMethod ( ) ] ?? [ ] as $ route ) { if ( $ route -> matchUri ( $ request -> getPathInfo ( ) ) && $ route -> matchMethod ( $ request -> getMethod ( ) ) && $ route -> matchHostname ( $ request -> getHost ( ) ) && $ route -> matchScheme ( $ request -> getScheme ( ) ) ) { return $ route ; } } return null ; }

Resolve a request into its route.

@param Request $request
@return Route|null


protected function resolve(string $key)
    {
        // Break the dotted notation keys into its parts
        $parts = explode(".", $key);

        // Set the pointer at the root of the items array
        $pointer = &$this->items;

        /**
         *
         * Loop through all the parts and see if the key exists.
         *
         */
        foreach( $parts as $part ){

            if( array_key_exists($part, $pointer) === false ){
                throw new \Exception("Config key {$key} not found.");
            }

            $pointer = &$pointer[$part];
        }

        return $pointer;
    }

Resolve the flattened key into the actual value.

@param string $key
@throws \Exception
@return mixed

Resolve the flattened key into the actual value .


public function has(string $key): bool
    {
        try {

            $this->resolve($key);

        } catch( \Exception $exception ){

            return false;
        }

        return true;
    }

public function has ( string $ key ) : bool { try { $ this -> resolve ( $ key ) ; } catch ( \ Exception $ exception ) { return false ; } return true ; }

See if config has given key.

@param string $key
@return boolean


public function get(string $key, $default = null)
    {
        // Attempt to lazy load keys.
        if( $this->has($key) === false ){

            $this->load($key);

        }

        return $this->resolve($key);
    }

public
function
get
(
string
$
key
,
$
default
=
)
{
// Attempt to lazy load keys.
if
(
$
this
->
has
(
$
key
)
===
false
)
{
$
this
->
load
(
$
key
)
;
}
return
$
this
->
resolve
(
$
key
)
;
}

Lazy load configuration files.

@TODO How do we fallback to a default value?

@param string $key
@param mixed|null $default
@return mixed


public function loadFile(string $key, string $file): void
    {
        // Check for file's existence
        if( file_exists($file) === false ){
            throw new \Exception("Config file not found: {$file}");
        }

        // Pull config file in and add values into master config
        $config = require_once $file;
        $this->add($key, $config);
    }

Load a file and assign it to the key.

@param string $key
@param string $file
@return void


protected function getBackgroundDetails()
    {
        return [
            'position'  => [
                '0 0'           => Translate::t('background.details.position.left_top', [], 'backgroundfield'),
                '50% 0'         => Translate::t('background.details.position.center_top', [], 'backgroundfield'),
                '100% 0'        => Translate::t('background.details.position.right_top', [], 'backgroundfield'),
                '0 50%'         => Translate::t('background.details.position.left_middle', [], 'backgroundfield'),
                '50% 50%'       => Translate::t('background.details.position.center_middle', [], 'backgroundfield'),
                '100% 50%'      => Translate::t('background.details.position.right_middle', [], 'backgroundfield'),
                '0 100%'        => Translate::t('background.details.position.left_bottom', [], 'backgroundfield'),
                '50% 100%'      => Translate::t('background.details.position.center_bottom', [], 'backgroundfield'),
                '100% 100%'     => Translate::t('background.details.position.right_bottom', [], 'backgroundfield'),
            ],
            'repeat'    => [
                'no-repeat'     => Translate::t('background.details.repeat.no_repeat', [], 'backgroundfield'),
                'repeat-x'      => Translate::t('background.details.repeat.repeat_x', [], 'backgroundfield'),
                'repeat-y'      => Translate::t('background.details.repeat.repeat_y', [], 'backgroundfield'),
                'repeat'        => Translate::t('background.details.repeat.repeat', [], 'backgroundfield'),
            ],
            'size'      => [
                'auto'          => [
                    'times',
                    Translate::t('background.details.size.auto', [], 'backgroundfield'),
                ],
                'cover'         => [
                    'arrows-h',
                    Translate::t('background.details.size.cover', [], 'backgroundfield'),
                ],
                'contain'       => [
                    'arrows',
                    Translate::t('background.details.size.contain', [], 'backgroundfield'),
                ],
            ],
        ];
    }

Return all available background details.

@return array $array Contains all background details

@since 0.0.1

Return all available background details .


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);
	}

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
)
;
}

Opens a connection to the Twitter Streaming API.

Opens a connection to the Twitter Streaming API .


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);
		}
	}

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
)
;
}
}

Checks the HTTP response code recieved from the server.

@param string $response
@throws Exception\ConnectionException If the response code different than 200.

Checks the HTTP response code recieved from the server .


protected function handleMessage(string $messageJson) : void
	{
		$message = json_decode($messageJson);
		$this->logger->info('Message received', [$message]);
	}

protected
function
handleMessage
(
string
$
messageJson
)
:
void
{
$
message
=
json_decode
(
$
messageJson
)
;
$
this
->
logger
->
info
(
'Message received'
,
[
$
message
]
)
;
}

Handles the message from twitter.

@param string $messageJson


private function isMessage(string $status) : bool
	{
		$testStr = substr($status, 0, 14);
		if ('{"created_at":' == $testStr) {
			return false;
		}

		return true;
	}

private function isMessage ( string $ status ) : bool { $ testStr = substr ( $ status , 0 , 14 ) ; if ( '{"created_at":' == $ testStr ) { return false ; } return true ; }

Determines if the received json is a message from twitter.

@param string $status
@return bool

Determines if the received json is a message from twitter .


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.');
	}

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.'
)
;
}

Reads the size of the next chunk from the stream.

@return int
@throws Exception\ConnectionClosedException

Reads the size of the next chunk from the stream .


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();
	}

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 ( ) ; }

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

Connects to the Twitter API and starts reading the stream .


public function getProperty($propertyName)
    {
        if ($propertyName == "Value") return $this->getValue();
        $ret = parent::getProperty($propertyName);
        if ($ret) return $ret;
        return $this->$propertyName;
    }

public function getProperty ( $ propertyName ) { if ( $ propertyName == "Value" ) return $ this -> getValue ( ) ; $ ret = parent :: getProperty ( $ propertyName ) ; if ( $ ret ) return $ ret ; return $ this -> $ propertyName ; }

Get property of element

@param string $propertyName
@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;
    }


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

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


protected function getText()
    {
        if ($this->text == null)
            return null;
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->text, $formobj);
    }

protected function getText ( ) { if ( $ this -> text == null ) return null ; $ formobj = $ this -> getFormObj ( ) ; return Expression :: evaluateExpression ( $ this -> text , $ formobj ) ; }


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 shortcut key function map

@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;
    }

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


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

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

Get function of element in JavaScript format

@return string


public function getRedirectPage($eventHandlerName)
    {
        $formObj = $this->getFormObj();
        $eventHandler = $this->eventHandlers->get($eventHandlerName);
        if (!$eventHandler) return null;
        //echo $evthandler->redirectPage."<br>";
        return Expression::evaluateExpression($eventHandler->redirectPage, $formObj);
    }

Get redirect page

@param string $eventHandlerName event handler name
@return string


public function getFunctionType($eventHandlerName)
    {
        $eventHandler = $this->eventHandlers->get($eventHandlerName);
        if (!$eventHandler) return null;
        return $eventHandler->functionType;
    }

public function getFunctionType ( $ eventHandlerName ) { $ eventHandler = $ this -> eventHandlers -> get ( $ eventHandlerName ) ; if ( ! $ eventHandler ) return null ; return $ eventHandler -> functionType ; }

Get function type

@param string $eventHandlerName event handler name
@return string function type in string format


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
    }

Set form name that contain element and EventHandler

@param string $formName
@param string $elemName
@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);
			}
        }
    }

Adjust form name

@param string $formName
@return void


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

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

parse function string and get functionName and functionParams


public function call($method, array &$arguments = [])
    {
        try {
            // alias for code readability
            $middle = &$this->middleware;

            if ($middle instanceof MiddlewareInterface) {
                assert(is_string($method));
                $middle->method($method);
                if (is_object($this->result)) {
                    $middle->as($this->result);
                }
                $this->result = $middle->handle($arguments, $this->type);

            } elseif (is_callable($middle)) {
                $callback = $middle;
                $this->result = $callback($method, ...$arguments);

            } elseif (is_array($middle) || $middle instanceof MiddlewareCollection) {
                assert(is_string($method));
                $this->result = Group::wrap($middle)->call($method, $arguments, $this->type, $this->result);
            }

            $this->called = true;

        } catch (HaltPropagationException $exception) {
            $this->halt($exception);
        }
        return $this->result;
    }

public
function
call
(
$
method
,
array
&
$
arguments
=
[
]
)
{
try
{
// alias for code readability
$
middle
=
&
$
this
->
middleware
;
if
(
$
middle
instanceof
MiddlewareInterface
)
{
assert
(
is_string
(
$
method
)
)
;
$
middle
->
method
(
$
method
)
;
if
(
is_object
(
$
this
->
result
)
)
{
$
middle
->
as
(
$
this
->
result
)
;
}
$
this
->
result
=
$
middle
->
handle
(
$
arguments
,
$
this
->
type
)
;
}
elseif
(
is_callable
(
$
middle
)
)
{
$
callback
=
$
middle
;
$
this
->
result
=
$
callback
(
$
method
,
...
$
arguments
)
;
}
elseif
(
is_array
(
$
middle
)
||
$
middle
instanceof
MiddlewareCollection
)
{
assert
(
is_string
(
$
method
)
)
;
$
this
->
result
=
Group
::
wrap
(
$
middle
)
->
call
(
$
method
,
$
arguments
,
$
this
->
type
,
$
this
->
result
)
;
}
$
this
->
called
=
true
;
}
catch
(
HaltPropagationException
$
exception
)
{
$
this
->
halt
(
$
exception
)
;
}
return
$
this
->
result
;
}

Calls the given method on the given middleware.

@throws \MichaelRShelton\MiddleMan\Exceptions\HaltPropagationException

@param string|mixed $method or first argument in callable functions
@param array $arguments
@return mixed

Calls the given method on the given middleware .


public function clear()
    {
        $this->result = null;
        $this->middleware = new Group;
        $this->called = false;
        return $this;
    }

public function clear ( ) { $ this -> result = null ; $ this -> middleware = new Group ; $ this -> called = false ; return $ this ; }

Clears the results for a new call.

@return $this;


public function halt(HaltPropagationException $exception = null)
    {
        if ($this->haltEvent !== "") {
            $pointer = $this->middleware instanceof MiddlewareCollection ? $this->middleware->current() : $this->middleware;
            $event = $this->haltEvent;

            if (is_callable(static::$eventCallable)) {
                static::$eventCallable(new $event($pointer, $exception));
            }
        }

        if ($exception !== null && ! $this->catchHalt) {
            throw $exception;
        }

        return $this;
    }

public function halt ( HaltPropagationException $ exception = null ) { if ( $ this -> haltEvent !== "" ) { $ pointer = $ this -> middleware instanceof MiddlewareCollection ? $ this -> middleware -> current ( ) : $ this -> middleware ; $ event = $ this -> haltEvent ; if ( is_callable ( static :: $ eventCallable ) ) { static :: $ eventCallable ( new $ event ( $ pointer , $ exception ) ) ; } } if ( $ exception !== null && ! $ this -> catchHalt ) { throw $ exception ; } return $ this ; }

The method that will trigger the event and exception, if set, for halted calls.

@throws \MichaelRShelton\MiddleMan\Exceptions\HaltPropagationException

@param \MichaelRShelton\MiddleMan\Exceptions\HaltPropagationException|null $exception
@return $this

The method that will trigger the event and exception if set for halted calls .


public function reset()
    {
        $this->clear();
        $this->called = false;
        $this->catchHalt = true;
        $this->haltEvent = MiddlewareHalted::class;
        return $this;
    }

public function reset ( ) { $ this -> clear ( ) ; $ this -> called = false ; $ this -> catchHalt = true ; $ this -> haltEvent = MiddlewareHalted :: class ; return $ this ; }

Resets the entire object.

@return $this


public function create($elementName, Project $project, $creatingClass) {
    $typedefs = $project->getDataTypeDefinitions();
    if(array_key_exists($elementName, $typedefs) && class_exists($typedefs[$elementName])) {
      $object = new $typedefs[$elementName];
      foreach($this->getAfterCreationCallbacksForClass($creatingClass) as $callback) {
        call_user_func($callback, $object, $elementName);
      }
      return $object;
    }
    throw new MissingConfigurationException(sprintf('No class or class definition found for %s', $elementName) . PHP_EOL . sprintf('Defintions: %s', print_r($typedefs)));
  }

Creates the object for the child element

@param string $elementName the name of the element that has been requested
@param Project $project The project the element is in
@return object Returns the nested element


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);
    }

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 ) ; }

Convert an integer counter into a string of 8 bytes.

@param  integer $counter The counter value
@return string Returns an 8-byte binary string

Convert an integer counter into a string of 8 bytes .


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

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 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 Post($url = null, $params = array())
    {
        if (null !== $url)
            $this->url = $url;

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

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

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


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

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

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

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

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 ...


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

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


public static function parseStr( $mixed ) {
	    return is_array($mixed) ? array_map([self, 'parse_str'], $mixed) : self::parse_str($mixed);
	}

public static function parseStr ( $ mixed ) { return is_array ( $ mixed ) ? array_map ( [ self , 'parse_str' ] , $ mixed ) : self :: parse_str ( $ mixed ) ; }

It parses URL encoded data, detects encoding, converts coding to internal encoding and set values to the array

@param array|string $mixed
@return array|string

It parses URL encoded data detects encoding converts coding to internal encoding and set values to the array


private static function parse_str( $str ) {
	    $output = [];
	    if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) {
	        mb_parse_str($str, $output);
	    } else {
	        parse_str($str, $output);
	    }
	    return $output;
	}

private static function parse_str ( $ str ) { $ output = [ ] ; if ( function_exists ( 'mb_parse_str' ) && ! isset ( $ this -> env [ 'slim.tests.ignore_multibyte' ] ) ) { mb_parse_str ( $ str , $ output ) ; } else { parse_str ( $ str , $ output ) ; } return $ output ; }

Se usa cuando llegan objetos de Ajax
@param string $str
@return Ambigous <multitype:, string, multitype:a r y s t i n g >


static public function render($formObj)
    {
        $tplEngine = $formObj->templateEngine;
        $tplAttributes = FormRenderer::buildTemplateAttributes($formObj);
        if (isset($formObj->jsClass)) {
            $subForms = ($formObj->subForms) ? implode(";", $formObj->subForms) : "";

            if ($formObj->staticOutput != true) {
                $formScript = "\n<script>Openbizx.newFormObject('$formObj->objectName','$formObj->jsClass','$subForms'); </script>\n";
            }
            if ($formObj->autoRefresh > 0) {
                $formScript .= "\n<script>setTimeout(\"Openbizx.CallFunction('$formObj->objectName.UpdateForm()');\",\"" . ($formObj->autoRefresh * 1000) . "\") </script>\n";
            }
        }

        if ($tplEngine == "Smarty" || $tplEngine == null) {
            return FormRenderer::renderSmarty($formObj, $tplAttributes) . $formScript;
        } else
            return FormRenderer::renderPHP($formObj, $tplAttributes) . $formScript;
    }

Render form object

@param EasyForm $formObj
@return string result of rendering process


static protected function renderSmarty($formObj, $tplAttributes = Array())
    {
        $smarty = TemplateHelper::getSmartyTemplate();
        $tplFile = TemplateHelper::getTplFileWithPath($formObj->templateFile, $formObj->package);

        //Translate Array of template variables to \Zend template object
        foreach ($tplAttributes as $key => $value) {
            $smarty->assign($key, $value);
        };

        return $smarty->fetch($tplFile);
    }

Render smarty template for form object

@param EasyForm $formObj
@param string $tplFile
@return string result of rendering process


static protected function renderPHP($formObj, $tplAttributes = Array())
    {
        $form = TemplateHelper::getZendTemplate();
        $tplFile = TemplateHelper::getTplFileWithPath($formObj->templateFile, $formObj->package);
        $form->addScriptPath(dirname($tplFile));

        /* $formOutput = $formObj->outputAttrs();
          foreach ($formOutput as $k=>$v) {
          $form->$k = $v;
          } */

        foreach ($tplAttributes as $key => $value) {
            if ($value == NULL) {
                $form->$key = '';
            } else {
                $form->$key = $value;
            }
        }

        // render the formobj attributes
        //$form->form = $formOutput;

        return $form->render($formObj->templateFile);
    }

Render PHP template for form object

@param EasyForm $formObj
@param string $tplFile
@return string result of rendering process


public function view(Request $request)
    {
        $this->request = $request;

        $entity = $this->findEntity($request);
        $this->authorizeView($request, $entity);

        return $this->createViewEntityResponse($entity);
    }

public function view ( Request $ request ) { $ this -> request = $ request ; $ entity = $ this -> findEntity ( $ request ) ; $ this -> authorizeView ( $ request , $ entity ) ; return $ this -> createViewEntityResponse ( $ entity ) ; }

View an entity
@param Request $request
@return Response


public function store(Request $request)
    {
        $this->request = $request;

        $this->authorizeCreate($request);

        $writeContext = $this->getContext(Action::CREATE);
        $inputResource = $this->bodyToResource($writeContext);

        try {
            $inputResource->validate($writeContext);
        } catch (ResourceValidationException $e) {
            return $this->getValidationErrorResponse($e);
        }

        $entity = $this->toEntity($inputResource, $writeContext);

        // Save the entity
        $this->saveEntity($request, $entity);

        // Turn back into a resource
        return $this->createViewEntityResponse($entity);
    }

public
function
store
(
Request
$
request
)
{
$
this
->
request
=
$
request
;
$
this
->
authorizeCreate
(
$
request
)
;
$
writeContext
=
$
this
->
getContext
(
Action
::
CREATE
)
;
$
inputResource
=
$
this
->
bodyToResource
(
$
writeContext
)
;
try
{
$
inputResource
->
validate
(
$
writeContext
)
;
}
catch
(
ResourceValidationException
$
e
)
{
return
$
this
->
getValidationErrorResponse
(
$
e
)
;
}
$
entity
=
$
this
->
toEntity
(
$
inputResource
,
$
writeContext
)
;
// Save the entity
$
this
->
saveEntity
(
$
request
,
$
entity
)
;
// Turn back into a resource
return
$
this
->
createViewEntityResponse
(
$
entity
)
;
}


protected function callEntityMethod(Request $request, $method)
    {
        // We don't want to include the first argument.
        $args = func_get_args();
        array_shift($args);
        array_shift($args);

        return call_user_func_array([ $this->getEntityClassName(), $method ], $args);
    }

Call a static method on the entity.
@param Request $request
@param $method
@return mixed


public function middleware(string $key, string $group = null)
    {
        return $this->middleMan->middle($key, $group);
    }

public function middleware ( string $ key , string $ group = null ) { return $ this -> middleMan -> middle ( $ key , $ group ) ; }

Use an a particular middleware once at this spot using the given identifiers.

@param string $key
@param string|null $group
@return mixed

Use an a particular middleware once at this spot using the given identifiers .


protected function getDefaultCommands()
    {
        $commands = parent::getDefaultCommands();

        $commands[] = new Command\AboutCommand();
        $commands[] = new Command\CheckCommand();

        return $commands;
    }

protected function getDefaultCommands ( ) { $ commands = parent :: getDefaultCommands ( ) ; $ commands [ ] = new Command \ AboutCommand ( ) ; $ commands [ ] = new Command \ CheckCommand ( ) ; return $ commands ; }


public function updateUser(UserInterface $user, $andFlush = true)
    {
        /** @var EntityManager $em */
        $em = $this->objectManager;
        $meta = $em->getClassMetadata(get_class($user));
        $roleClass = $meta->getAssociationTargetClass('roles');
        $roles = array();
        foreach ($user->getRoles() as $role) {
            if ($roleClass !== get_class($role)) {
                /** Try to get Role */
                if ($em->find($roleClass, $role->getRole())) {
                    try {
                        $_ref = $em->getReference($roleClass, $role->getRole());
                        $roles[] = $_ref;
                    } catch (ORMException $e) {
                        var_dump($e);
                    }
                }else{
                    $_ref = new $roleClass($role->getRole());
                    $em->persist($_ref);
                    $roles[] = $_ref;
                }
            }else{
                $roles[] = $role;
            }
        }
        $user->setRoles($roles);
        parent::updateUser($user, $andFlush);
    }

public
function
updateUser
(
UserInterface
$
user
,
$
andFlush
=
true
)
{
/** @var EntityManager $em */
$
em
=
$
this
->
objectManager
;
$
meta
=
$
em
->
getClassMetadata
(
get_class
(
$
user
)
)
;
$
roleClass
=
$
meta
->
getAssociationTargetClass
(
'roles'
)
;
$
roles
=
array
(
)
;
foreach
(
$
user
->
getRoles
(
)
as
$
role
)
{
if
(
$
roleClass
!==
get_class
(
$
role
)
)
{
/** Try to get Role */
if
(
$
em
->
find
(
$
roleClass
,
$
role
->
getRole
(
)
)
)
{
try
{
$
_ref
=
$
em
->
getReference
(
$
roleClass
,
$
role
->
getRole
(
)
)
;
$
roles
[
]
=
$
_ref
;
}
catch
(
ORMException
$
e
)
{
var_dump
(
$
e
)
;
}
}
else
{
$
_ref
=
new
$
roleClass
(
$
role
->
getRole
(
)
)
;
$
em
->
persist
(
$
_ref
)
;
$
roles
[
]
=
$
_ref
;
}
}
else
{
$
roles
[
]
=
$
role
;
}
}
$
user
->
setRoles
(
$
roles
)
;
parent
::
updateUser
(
$
user
,
$
andFlush
)
;
}

Updates a user.

@param UserInterface $user
@param Boolean       $andFlush Whether to flush the changes (default true)


protected function getSettings(): array {
    $configurationManager = $this->objectManager->get(ConfigurationManagerInterface::class);
    $configuration        = $configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);

    return $configuration['plugin.']['tx_t3vcontent.']['settings.'];
  }

protected function getSettings ( ) : array { $ configurationManager = $ this -> objectManager -> get ( ConfigurationManagerInterface :: class ) ; $ configuration = $ configurationManager -> getConfiguration ( ConfigurationManagerInterface :: CONFIGURATION_TYPE_FULL_TYPOSCRIPT ) ; return $ configuration [ 'plugin.' ] [ 'tx_t3vcontent.' ] [ 'settings.' ] ; }

Gets the settings from `plugin.tx_t3vcontent.settings`.

@return array The settings

Gets the settings from plugin . tx_t3vcontent . settings .


public function getGroup()
    {
        /** @var null|Person $person */

        if (is_null($this->regid) === true) {
            try {
                $resp = static::getGroupConnection()->execGET(
                    $this->identifier
                );
            } catch (\Exception $e) {
                throw $e;
            }

            $this->parseGroup($resp->getData());
        }

        return $this;
    }

public
function
getGroup
(
)
{
/** @var null|Person $person */
if
(
is_null
(
$
this
->
regid
)
===
true
)
{
try
{
$
resp
=
static
::
getGroupConnection
(
)
->
execGET
(
$
this
->
identifier
)
;
}
catch
(
\
Exception
$
e
)
{
throw
$
e
;
}
$
this
->
parseGroup
(
$
resp
->
getData
(
)
)
;
}
return
$
this
;
}

Queries GWS to generate a Group, given an identifier. Identifier may be group id, or group regid

@return Group

Queries GWS to generate a Group given an identifier . Identifier may be group id or group regid


protected function getDirectMembership()
    {
        if (isset($this->regid) === false) {
            $this->getGroup();
        }
        if (is_null($this->regid) === true) {
            throw new \Exception('Group Id not specified');
        }
        $resp = static::getGroupConnection()->execGET(
            "$this->identifier/member"
        );

        $this->directmembers = [];
        $this->parseMembership($resp->getData());
    }

protected
function
getDirectMembership
(
)
{
if
(
isset
(
$
this
->
regid
)
===
false
)
{
$
this
->
getGroup
(
)
;
}
if
(
is_null
(
$
this
->
regid
)
===
true
)
{
throw
new
\
Exception
(
'Group Id not specified'
)
;
}
$
resp
=
static
::
getGroupConnection
(
)
->
execGET
(
"$this->identifier/member"
)
;
$
this
->
directmembers
=
[
]
;
$
this
->
parseMembership
(
$
resp
->
getData
(
)
)
;
}

Queries GWS to for direct members of the group. Members are added to the object.
@return void

Queries GWS to for direct members of the group . Members are added to the object .


protected function getEffectiveMembership()
    {
        if (isset($this->regid) === false) {
            $this->getGroup();
        }
        if (is_null($this->regid) === true) {
            throw new \Exception('Group Id not specified');
        }
        try {
            $resp = static::getGroupConnection()->execGET(
                "$this->identifier/effective_member"
            );
        } catch (\Exception $e) {
            throw $e;
        }

        $this->effectivemembers = [];
        $this->parseMembership($resp->getData());
    }

protected
function
getEffectiveMembership
(
)
{
if
(
isset
(
$
this
->
regid
)
===
false
)
{
$
this
->
getGroup
(
)
;
}
if
(
is_null
(
$
this
->
regid
)
===
true
)
{
throw
new
\
Exception
(
'Group Id not specified'
)
;
}
try
{
$
resp
=
static
::
getGroupConnection
(
)
->
execGET
(
"$this->identifier/effective_member"
)
;
}
catch
(
\
Exception
$
e
)
{
throw
$
e
;
}
$
this
->
effectivemembers
=
[
]
;
$
this
->
parseMembership
(
$
resp
->
getData
(
)
)
;
}

Queries GWS to for effective members of the group. Members are added to the object.
@return void

Queries GWS to for effective members of the group . Members are added to the object .


protected function parseMembership($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        foreach ($html->find('a.member') as $name) {
            array_push($this->directmembers, $name->innertext);
        }
        foreach ($html->find('a.effective_member') as $name) {
            array_push($this->effectivemembers, $name->innertext);
        }
    }

protected function parseMembership ( $ data ) { $ html = HtmlDomParser :: str_get_html ( $ data ) ; foreach ( $ html -> find ( 'a.member' ) as $ name ) { array_push ( $ this -> directmembers , $ name -> innertext ) ; } foreach ( $ html -> find ( 'a.effective_member' ) as $ name ) { array_push ( $ this -> effectivemembers , $ name -> innertext ) ; } }

parses Membership data and saves it to the Group object

@param string $data
@return void


protected function parseHistory($data)
    {
        $this->history = [];
        $html = HtmlDomParser::str_get_html($data);
        foreach ($html->find('li.history') as $e) {
            $item = array();
            $item['date'] =  $e->date;
            $item['user'] =  $e->user;
            $item['actas'] =  $e->actas;
            $item['activity'] =  $e->activity;
            $item['description'] = $e->description;
            array_push($this->history, $item);
        }
    }

protected function parseHistory ( $ data ) { $ this -> history = [ ] ; $ html = HtmlDomParser :: str_get_html ( $ data ) ; foreach ( $ html -> find ( 'li.history' ) as $ e ) { $ item = array ( ) ; $ item [ 'date' ] = $ e -> date ; $ item [ 'user' ] = $ e -> user ; $ item [ 'actas' ] = $ e -> actas ; $ item [ 'activity' ] = $ e -> activity ; $ item [ 'description' ] = $ e -> description ; array_push ( $ this -> history , $ item ) ; } }

parses History data and saves it to the Group object

@param string $data
@return void


protected function parseAffiliate($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        $affiliate['group_identifier']  = (empty($html->find('span.identifier', 0)) === false)
                                            ? ($html->find('span.identifier', 0)->innertext)
                                            : ('');
        $affiliate['affiliate_name']    = (empty($html->find('span.affiliate', 0)) === false)
                                            ? ($html->find('span.affiliate', 0)->name)
                                            : ('');
        $affiliate['affiliate_status']  = (empty($html->find('span.affiliate', 0)) === false)
                                            ? ($html->find('span.affiliate', 0)->status)
                                            : ('');
        $affiliate['error']             = (empty($html->find('span.error', 0)) === false)
                                            ? ($html->find('span.error', 0)->innertext)
                                            : ('');

        if ($html->find('span.error', 0) === true) {
        } else {
            $this->affiliates[$affiliate['affiliate_name']] = $affiliate;
        }

        return $affiliate;
    }

protected function parseAffiliate ( $ data ) { $ html = HtmlDomParser :: str_get_html ( $ data ) ; $ affiliate [ 'group_identifier' ] = ( empty ( $ html -> find ( 'span.identifier' , 0 ) ) === false ) ? ( $ html -> find ( 'span.identifier' , 0 ) -> innertext ) : ( '' ) ; $ affiliate [ 'affiliate_name' ] = ( empty ( $ html -> find ( 'span.affiliate' , 0 ) ) === false ) ? ( $ html -> find ( 'span.affiliate' , 0 ) -> name ) : ( '' ) ; $ affiliate [ 'affiliate_status' ] = ( empty ( $ html -> find ( 'span.affiliate' , 0 ) ) === false ) ? ( $ html -> find ( 'span.affiliate' , 0 ) -> status ) : ( '' ) ; $ affiliate [ 'error' ] = ( empty ( $ html -> find ( 'span.error' , 0 ) ) === false ) ? ( $ html -> find ( 'span.error' , 0 ) -> innertext ) : ( '' ) ; if ( $ html -> find ( 'span.error' , 0 ) === true ) { } else { $ this -> affiliates [ $ affiliate [ 'affiliate_name' ] ] = $ affiliate ; } return $ affiliate ; }

Parses out affiliate information from the GWS XHTML. Successful queries will also be added to the Group object.

@param string $data
@return array affiliate information

Parses out affiliate information from the GWS XHTML . Successful queries will also be added to the Group object .


protected function parseSearch($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        $groups = array();
        foreach ($html->find('li.groupreference') as $e) {
            $item = array();
            $item['regid'] =  $e->find('span.regid', 0)->innertext;
            $item['title'] =  $e->find('span.title', 0)->innertext;
            $item['description'] = $e->find('span.description', 0)->innertext;
            array_push($groups, $item);
        }
        return $groups;
    }

protected function parseSearch ( $ data ) { $ html = HtmlDomParser :: str_get_html ( $ data ) ; $ groups = array ( ) ; foreach ( $ html -> find ( 'li.groupreference' ) as $ e ) { $ item = array ( ) ; $ item [ 'regid' ] = $ e -> find ( 'span.regid' , 0 ) -> innertext ; $ item [ 'title' ] = $ e -> find ( 'span.title' , 0 ) -> innertext ; $ item [ 'description' ] = $ e -> find ( 'span.description' , 0 ) -> innertext ; array_push ( $ groups , $ item ) ; } return $ groups ; }

Parses out group information from a search.

@param string $data
@return array group information

Parses out group information from a search .


public function getWebpageObject()
    {
        $viewName = Openbizx::$app->getCurrentViewName();
        if (!$viewName) {
            return null;
        }
        $viewObj = Openbizx::getObject($viewName);
        return $viewObj;
    }

public function getWebpageObject ( ) { $ viewName = Openbizx :: $ app -> getCurrentViewName ( ) ; if ( ! $ viewName ) { return null ; } $ viewObj = Openbizx :: getObject ( $ viewName ) ; return $ viewObj ; }

Get view object

@global BizSystem $g_BizSystem
@return WebPage


public function getElement($elementName)
    {
        if ($this->dataPanel->get($elementName)) {
            return $this->dataPanel->get($elementName);
        }
        if ($this->actionPanel->get($elementName)) {
            return $this->actionPanel->get($elementName);
        }
        if ($this->navPanel->get($elementName)) {
            return $this->navPanel->get($elementName);
        }
        if ($this->searchPanel->get($elementName)) {
            return $this->searchPanel->get($elementName);
        }
        if ($this->wizardPanel) {
            if ($this->wizardPanel->get($elementName))
                return $this->wizardPanel->get($elementName);
        }
    }

public function getElement ( $ elementName ) { if ( $ this -> dataPanel -> get ( $ elementName ) ) { return $ this -> dataPanel -> get ( $ elementName ) ; } if ( $ this -> actionPanel -> get ( $ elementName ) ) { return $ this -> actionPanel -> get ( $ elementName ) ; } if ( $ this -> navPanel -> get ( $ elementName ) ) { return $ this -> navPanel -> get ( $ elementName ) ; } if ( $ this -> searchPanel -> get ( $ elementName ) ) { return $ this -> searchPanel -> get ( $ elementName ) ; } if ( $ this -> wizardPanel ) { if ( $ this -> wizardPanel -> get ( $ elementName ) ) return $ this -> wizardPanel -> get ( $ elementName ) ; } }

Get an element object

@param string $elementName - name of the control
@return Element


public function getErrorElements($fields)
    {
        $errElements = array();
        foreach ($fields as $field => $error) {
            $element = $this->dataPanel->getByField($field);
            $errElements[$element->objectName] = $error;
        }
        return $errElements;
    }

public function getErrorElements ( $ fields ) { $ errElements = array ( ) ; foreach ( $ fields as $ field => $ error ) { $ element = $ this -> dataPanel -> getByField ( $ field ) ; $ errElements [ $ element -> objectName ] = $ error ; } return $ errElements ; }

Get error elements

@param array $fields
@return array


protected function rerenderSubForms()
    {
        if (!$this->subForms) {
            return;
        }
        $this->prepareSubFormsDataObj();
        foreach ($this->subForms as $subForm) {
            $formObj = Openbizx::getObject($subForm);
            $formObj->rerender();
        }
        return;
    }

protected function rerenderSubForms ( ) { if ( ! $ this -> subForms ) { return ; } $ this -> prepareSubFormsDataObj ( ) ; foreach ( $ this -> subForms as $ subForm ) { $ formObj = Openbizx :: getObject ( $ subForm ) ; $ formObj -> rerender ( ) ; } return ; }

Rerender sub forms who has dependecy on this form.
This method is called when parent form's change affect the sub forms

@return void

Rerender sub forms who has dependecy on this form . This method is called when parent form s change affect the sub forms


public function setClass($class)
    {
        preg_match('/\\\([\w]+Bundle)$/', $class, $match);
        if (empty($match[1])) {
            throw new InvalidJsonParameterException(sprintf("The class %s does not seem to be a valid bundle class. Check your autoloader.json file", $class));
        }
        $this->name = basename($match[1]);
        $this->class = $class;

        return $this;
    }

Sets the bundle class

@param  string                                               $class
@return \RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json\Bundle\Bundle
@throws InvalidJsonParameterException


public function getTranslationKey($key): string
    {
        return sprintf('%s.%s', $this->prefix, kebab_case($this->get($key)));
    }

public function getTranslationKey ( $ key ) : string { return sprintf ( '%s.%s' , $ this -> prefix , kebab_case ( $ this -> get ( $ key ) ) ) ; }

Get translation key.

@param string|int $key
@return string


public function lists(): array
    {
        $data = [];
        foreach (array_keys($this->words) as $key) {
            $data[$key] = $this->trans($key);
        }

        return $data;
    }

public function lists ( ) : array { $ data = [ ] ; foreach ( array_keys ( $ this -> words ) as $ key ) { $ data [ $ key ] = $ this -> trans ( $ key ) ; } return $ data ; }

Get full list of dictionary with translated words from dictionary.

@return array

Get full list of dictionary with translated words from dictionary .


private function loadConfig(&$configs, &$options)
    {
        foreach ($configs as $config) {
            $value_up = strtoupper($config["ATTRIBUTES"]["VALUE"]);
            if ($value_up == "Y") {
                $config["ATTRIBUTES"]["VALUE"] = true;
            } elseif ($value_up == "N") {
                $config["ATTRIBUTES"]["VALUE"] = false;
            }
            $options[$config["ATTRIBUTES"]["NAME"]] = $config["ATTRIBUTES"]["VALUE"];
            if ($config["ATTRIBUTES"]["NAME"] == 'cache_dir') {
                $options[$config["ATTRIBUTES"]["NAME"]] = OPENBIZ_CACHE_PATH . "/" . $config["ATTRIBUTES"]["VALUE"];
            }
        }
    }

private function loadConfig ( & $ configs , & $ options ) { foreach ( $ configs as $ config ) { $ value_up = strtoupper ( $ config [ "ATTRIBUTES" ] [ "VALUE" ] ) ; if ( $ value_up == "Y" ) { $ config [ "ATTRIBUTES" ] [ "VALUE" ] = true ; } elseif ( $ value_up == "N" ) { $ config [ "ATTRIBUTES" ] [ "VALUE" ] = false ; } $ options [ $ config [ "ATTRIBUTES" ] [ "NAME" ] ] = $ config [ "ATTRIBUTES" ] [ "VALUE" ] ; if ( $ config [ "ATTRIBUTES" ] [ "NAME" ] == 'cache_dir' ) { $ options [ $ config [ "ATTRIBUTES" ] [ "NAME" ] ] = OPENBIZ_CACHE_PATH . "/" . $ config [ "ATTRIBUTES" ] [ "VALUE" ] ; } } }

Load cache configuratoon

@param array $configs
@param array $options
@return void


public function remove($id)
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->remove($id);
        } else {
            return false;
        }
    }

public function remove ( $ id ) { if ( $ this -> cacheObj && strtoupper ( $ this -> cache ) == "ENABLED" ) { return $ this -> cacheObj -> remove ( $ id ) ; } else { return false ; } }

Remove a cache

@param string $id cache id to remove
@return boolean true if ok


public function getIds()
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->getIds();
        } else {
            return false;
        }
    }

public function getIds ( ) { if ( $ this -> cacheObj && strtoupper ( $ this -> cache ) == "ENABLED" ) { return $ this -> cacheObj -> getIds ( ) ; } else { return false ; } }

get a list of all caches

@return array ids


public function cleanAll()
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->clean(\Zend_Cache::CLEANING_MODE_ALL);
        } else {
            return false;
        }
    }

public function cleanAll ( ) { if ( $ this -> cacheObj && strtoupper ( $ this -> cache ) == "ENABLED" ) { return $ this -> cacheObj -> clean ( \ Zend_Cache :: CLEANING_MODE_ALL ) ; } else { return false ; } }

clean all cache

@return boolean true if ok


private function _makeDirectory($pathName, $mode)
    {
        is_dir(dirname($pathName)) || $this->_makeDirectory(dirname($pathName), $mode);
        return is_dir($pathName) || @mkdir($pathName, $mode);
    }

private function _makeDirectory ( $ pathName , $ mode ) { is_dir ( dirname ( $ pathName ) ) || $ this -> _makeDirectory ( dirname ( $ pathName ) , $ mode ) ; return is_dir ( $ pathName ) || @ mkdir ( $ pathName , $ mode ) ; }

Make directory recursively

@param string $pathName The directory path.
@param int $mode<p>
The mode is 0777 by default, which means the widest possible
access. For more information on modes, read the details
on the chmod page.
@return bool Returns true on success or false on failure.
@todo need move to utility class or helper?


protected function readLocation($location)
    {
        $reader = null;

        if (is_dir($location)) {
            $base_location = Validator::fixPath(Validator::fixRelativePath($location));
            foreach ($this->default_filenames as $filename) {
                $file = $base_location . $filename;
                if (is_readable($file)) {
                    try {
                        $reader = $this->getReaderByExtension($file);
                        break; // found possible config file \o/
                    } catch (\InvalidArgumentException $e) {
                        // next attempt as extension has no handler
                    }
                }
                // next attempt, as file is not readable or does not exist
            }

            if (!$reader instanceof IConfigReader) {
                throw new \InvalidArgumentException(
                    'Could not find an environaut config file in "' . $base_location . '".' . PHP_EOL .
                    'Attempted files were: ' . implode(', ', $this->default_filenames) . '.' . PHP_EOL .
                    'Try calling from a different folder or specify a file using the "--config" option.'
                );
            }
        } elseif (is_file($location)) {
            $reader = $this->getReaderByExtension($location);
        } else {
            throw new \InvalidArgumentException(
                'Currently only regular files and directories are supported for config file reading.'
            );
        }

        $config_data = $reader->getConfigData($location);

        return $config_data;
    }

Reads a config file from the given location and returns it's
data as an associative array.

@param mixed $location location of config file (as a string with a file or directory path)

@return array config data

@throws \InvalidArgumentException on errors like missing config file

Reads a config file from the given location and returns it s data as an associative array .


protected function getReaderByExtension($location)
    {
        $ext = pathinfo($location, PATHINFO_EXTENSION);

        $reader = null;

        switch ($ext) {
            case 'json':
                $reader = new JsonConfigReader();
                break;
            case 'xml':
                $reader = new XmlConfigReader();
                break;
            case 'php':
                $reader = new PhpConfigReader();
                break;
            default:
                throw new \InvalidArgumentException(
                    'File could not be read: ' . $location . PHP_EOL .
                    'Supported config file extensions are: ' . implode(', ', $this->supported_file_extensions)
                );
                break;
        }

        return $reader;
    }

Returns a specific reader instance depending on the file
extension of the given config file location.

@param string $location

@return IConfigReader

@throws \InvalidArgumentException in case of unsupported file extensions

Returns a specific reader instance depending on the file extension of the given config file location .


protected function addBranch(string $key): RouteBranch
    {
        if( array_key_exists($key, $this->branches) ){
            throw new \Exception("{$key} branch already exists for this node.");
        }

        $this->branches[$key] = new RouteBranch("{$this->path}/{$key}");
        return $this->branches[$key];
    }

Add a branch dangling from this branch.

@param string $key
@param RouteBranch $routeBranch
@return RouteBranch

Add a branch dangling from this branch .


public function addRoute(Route $route): void
    {
        foreach( $route->getMethods() as $method ){

            if( array_key_exists($method, $this->routes) ){
                throw new \Exception("{$method}#{$this->path} route has already been defined.");
            }

            $this->routes[$method] = $route;
        }
    }

Add route to this leaf.

@param Route $route
@return void


public function findBranch(string $part): ?RouteBranch
    {
        // Try finding an exact match first.
        if( array_key_exists($part, $this->branches) ){
            return $this->branches[$part];
        }

        // Loop through each branch key and match it using a regex.
        foreach( $this->branches as $key => $branch ){
            if( preg_match("/^{$key}$/", $part) ){
                return $branch;
            }
        }

        return null;
    }

Find the matching branch for the given URI path part.

@param string $part
@return RouteBranch|null

Find the matching branch for the given URI path part .


public function next(string $uriPart): RouteBranch
    {
        foreach( $this->branches as $key => $branch ){

            if( $uriPart === $key ){
                return $branch;
            }
        }

        return $this->addBranch($uriPart);
    }

public function next ( string $ uriPart ) : RouteBranch { foreach ( $ this -> branches as $ key => $ branch ) { if ( $ uriPart === $ key ) { return $ branch ; } } return $ this -> addBranch ( $ uriPart ) ; }

Get the next branch or create a new one.

@param string $uriPart
@return RouteBranch

Get the next branch or create a new one .


public function findByIssue(
        IssueInterface $issue,
        \DateTime $createdAt = null,
        $writtenBy = null,
        $limit = null,
        $offset = null
    ) {
        $queryBuilder = $this->getQueryBuilder();
        if ($createdAt instanceof \DateTime) {
            $this->addCriteria($queryBuilder, ['between' => ['createdAt' => $createdAt]]);
        }
        if ($writtenBy !== null) {
            $this->addCriteria($queryBuilder, ['wb.email' => $writtenBy]);
        }
        $this->addCriteria($queryBuilder, ['issue' => $issue]);
        $this->orderBy($queryBuilder, ['createdAt' => 'ASC']);

        if ($limit) {
            $queryBuilder->setMaxResults($limit);
        }
        if ($offset) {
            $queryBuilder->setFirstResult($offset);
        }

        return $queryBuilder->getQuery()->getResult();
    }

public function findByIssue ( IssueInterface $ issue , \ DateTime $ createdAt = null , $ writtenBy = null , $ limit = null , $ offset = null ) { $ queryBuilder = $ this -> getQueryBuilder ( ) ; if ( $ createdAt instanceof \ DateTime ) { $ this -> addCriteria ( $ queryBuilder , [ 'between' => [ 'createdAt' => $ createdAt ] ] ) ; } if ( $ writtenBy !== null ) { $ this -> addCriteria ( $ queryBuilder , [ 'wb.email' => $ writtenBy ] ) ; } $ this -> addCriteria ( $ queryBuilder , [ 'issue' => $ issue ] ) ; $ this -> orderBy ( $ queryBuilder , [ 'createdAt' => 'ASC' ] ) ; if ( $ limit ) { $ queryBuilder -> setMaxResults ( $ limit ) ; } if ( $ offset ) { $ queryBuilder -> setFirstResult ( $ offset ) ; } return $ queryBuilder -> getQuery ( ) -> getResult ( ) ; }

Finds all the comments of issue given ordering by createdAt.
The result can be more strict adding user and createAt criteria.
Can do limit and offset.

@param \Kreta\Component\Issue\Model\Interfaces\IssueInterface $issue     The issue
@param \DateTime                                              $createdAt The created at
@param string                                                 $writtenBy The email of user
@param int                                                    $limit     The limit
@param int                                                    $offset    The offset

@return \Kreta\Component\Comment\Model\Interfaces\CommentInterface[]

Finds all the comments of issue given ordering by createdAt . The result can be more strict adding user and createAt criteria . Can do limit and offset .


protected function getWPContents($type = 'posts', $multiple = false, $options = [], $post_id = 0, $value = '')
    {
        // Access WordPress contents
        $wpcontents = [];

        // Exclude current item
        if (isset($options['exclude']) && 'current' === $options['exclude']) {
            $options['exclude'] = $post;
        }

        // Get asked contents
        $authorized = [
            'categories', 'category',
            'menus', 'menu',
            'pages', 'page',
            'posts', 'post',
            'posttypes', 'posttype',
            'tags', 'tag',
            'taxonomies', 'taxonomy',
            'terms', 'term'
        ];

        // Check contents
        if (!in_array($type, $authorized)) {
            return [];
        }

        // Data retrieved
        if (in_array($type, ['categories', 'category'])) {
            $wptype = 'Categories';
        } else if (in_array($type, ['menus', 'menu'])) {
            $wptype = 'Menus';
        } else if (in_array($type, ['pages', 'page'])) {
            $wptype = 'Pages';
        } else if (in_array($type, ['posts', 'post'])) {
            $wptype = 'Posts';
        } else if (in_array($type, ['posttypes', 'posttype'])) {
            $wptype = 'Posttypes';
        } else if (in_array($type, ['tags', 'tag'])) {
            $wptype = 'Tags';
        } else if (in_array($type, ['taxonomies', 'taxonomy'])) {
            $wptype = 'Taxonomies';
        } else {
            $wptype = 'Terms';
        }

        // Get contents
        $function = 'getWP'.$wptype;
        $wpcontents = $this->$function($options, $value);

        // Return value
        return $wpcontents;
    }

protected
function
getWPContents
(
$
type
=
'posts'
,
$
multiple
=
false
,
$
options
=
[
]
,
$
post_id
=
0
,
$
value
=
''
)
{
// Access WordPress contents
$
wpcontents
=
[
]
;
// Exclude current item
if
(
isset
(
$
options
[
'exclude'
]
)
&&
'current'
===
$
options
[
'exclude'
]
)
{
$
options
[
'exclude'
]
=
$
post
;
}
// Get asked contents
$
authorized
=
[
'categories'
,
'category'
,
'menus'
,
'menu'
,
'pages'
,
'page'
,
'posts'
,
'post'
,
'posttypes'
,
'posttype'
,
'tags'
,
'tag'
,
'taxonomies'
,
'taxonomy'
,
'terms'
,
'term'
]
;
// Check contents
if
(
!
in_array
(
$
type
,
$
authorized
)
)
{
return
[
]
;
}
// Data retrieved
if
(
in_array
(
$
type
,
[
'categories'
,
'category'
]
)
)
{
$
wptype
=
'Categories'
;
}
else
if
(
in_array
(
$
type
,
[
'menus'
,
'menu'
]
)
)
{
$
wptype
=
'Menus'
;
}
else
if
(
in_array
(
$
type
,
[
'pages'
,
'page'
]
)
)
{
$
wptype
=
'Pages'
;
}
else
if
(
in_array
(
$
type
,
[
'posts'
,
'post'
]
)
)
{
$
wptype
=
'Posts'
;
}
else
if
(
in_array
(
$
type
,
[
'posttypes'
,
'posttype'
]
)
)
{
$
wptype
=
'Posttypes'
;
}
else
if
(
in_array
(
$
type
,
[
'tags'
,
'tag'
]
)
)
{
$
wptype
=
'Tags'
;
}
else
if
(
in_array
(
$
type
,
[
'taxonomies'
,
'taxonomy'
]
)
)
{
$
wptype
=
'Taxonomies'
;
}
else
{
$
wptype
=
'Terms'
;
}
// Get contents
$
function
=
'getWP'
.
$
wptype
;
$
wpcontents
=
$
this
->
$
function
(
$
options
,
$
value
)
;
// Return value
return
$
wpcontents
;
}

Get Wordpress contents already registered.

@param   string  $type       Wordpress content type to return
@param   boolean $multiple   Define if there is multiselect or not
@param   array   $options    Define options if needed
@param   integer $post_id    Define the post ID for meta boxes
@param   string  $value      Define the value of each select options
@return  array   $wpcontents Array of Wordpress content type registered

Get Wordpress contents already registered .


protected function getWPCategories($options = [], $value = 'cat_ID')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.category', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'hide_empty' => 0,
            'orderby' => 'name',
            'order' => 'ASC',
            'parent' => 0,
        ], $options);

        // Build request
        $categories_obj = get_categories($args);

        // Iterate on categories
        if (!empty($categories_obj)) {
            foreach ($categories_obj as $cat) {
                // For Wordpress version < 3.0
                if (empty($cat->cat_ID)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($cat->$value) ? $cat->$value : $cat->cat_ID;

                // Get the id and the name
                $contents[0][$item] = $cat->cat_name;

                // Get children
                $contents = $this->getWPSubCategories($contents, $cat->cat_ID, $value);
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Categories registered.

@uses get_categories()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


protected function getWPMenus($options = [], $value = 'term_id')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.menu', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'hide_empty' => false,
            'orderby' => 'none'
        ], $options);

        // Build request
        $menus_obj = wp_get_nav_menus($args);

        // Iterate on menus
        if (!empty($menus_obj)) {
            foreach ($menus_obj as $menu) {
                // For Wordpress version < 3.0
                if (empty($menu->term_id)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($menu->$value) ? $menu->$value : $menu->term_id;

                // Get the id and the name
                $contents[0][$item] = $menu->name;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Menus registered.

@uses wp_get_nav_menus()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


protected function getWPPages($options = [], $value = 'ID')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.page', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'sort_column' => 'post_parent,menu_order'
        ], $options);

        // Build request
        $pages_obj = get_pages($args);

        // Iterate on pages
        if (!empty($pages_obj)) {
            foreach ($pages_obj as $pag) {
                // For Wordpress version < 3.0
                if (empty($pag->ID)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($pag->$value) ? $pag->$value : $pag->ID;

                // Get the id and the name
                $contents[0][$item] = $pag->post_title;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Pages registered.

@uses get_pages()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


protected function getWPPosts($options = [], $value = 'ID')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.post', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'post_type' => 'post',
            'post_status' => 'publish'
        ], $options);

        // Build request
        $posts_obj = wp_get_recent_posts($args, OBJECT);

        // Iterate on posts
        if (!empty($posts_obj)) {
            foreach ($posts_obj as $pos) {
                // For Wordpress version < 3.0
                if (empty($pos->ID)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($pos->$value) ? $pos->$value : $pos->ID;

                // Get the id and the name
                $contents[$pos->post_type][$item] = $pos->post_title;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Posts registered.

@uses wp_get_recent_posts()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


protected function getWPPosttypes($options = [], $value = 'name')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.posttype', [], 'wordpressfield');

        // Build options
        $args = array_merge([], $options);

        // Build request
        $types_obj = get_post_types($args, 'object');

        // Iterate on posttypes
        if (!empty($types_obj)) {
            foreach ($types_obj as $typ) {
                // Check value
                $item = !empty($value) && isset($typ->$value) ? $typ->$value : $typ->name;

                // Get the the name
                $contents[0][$item] = $typ->labels->name.' ('.$typ->name.')';
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Post Types registered.

@uses get_post_types()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


protected function getWPTags($options = [], $value = 'term_id')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.tag', [], 'wordpressfield');

        // Build options
        $args = array_merge([], $options);

        // Build request
        $tags_obj = get_the_tags();

        // Iterate on tags
        if (!empty($tags_obj)) {
            foreach ($tags_obj as $tag) {
                // Check value
                $item = !empty($value) && isset($tag->$value) ? $tag->$value : $tag->term_id;

                // Get the id and the name
                $contents[0][$item] = $tag->name;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Tags registered.

@uses get_the_tags()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


protected function getWPTaxonomies($options = [], $value = '')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.taxonomy', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'public' => 1
        ], $options);

        // Build request
        $taxs_obj = get_taxonomies($args);

        // Iterate on tags
        if (!empty($taxs_obj)) {
            foreach ($taxs_obj as $tax) {
                // Get taxonomy details
                $taxo = get_taxonomy($tax);

                // Get the id and the name
                $contents[0][$tax] = $taxo->labels->name.' ('.$taxo->name.')';
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Taxonomies registered.

@uses get_taxonomies()
@uses get_taxonomy()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


protected function getWPTerms($options = [], $value = 'term_id')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.term', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'hide_empty' => false,
        ], $options);

        // Build request
        $terms_obj = get_terms($args);

        // Iterate on tags
        if (!empty($terms_obj) && ! is_wp_error($terms_obj)) {
            foreach ($terms_obj as $term) {
                // Check value
                $item = !empty($value) && isset($term->$value) ? $term->$value : $term->term_id;

                // Get the id and the name
                $contents[0][$item] = $term->name;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

Get WordPress Terms registered.

@uses get_terms()

@param   array  $options     Define options if needed
@param   string $value       Define the value of each select options
@return  array  $wpcontents  Array of WordPress items


public function addToSearchPath(string $name, string $path, int $precedence)
    {
        if (!is_dir($path))
            throw new \InvalidArgumentException("Path does not exist: " . $path);

        $this->search_path[$name] = array('path' => $path, 'precedence' => $precedence);
        $this->sorted = false;

        return $this;
    }

public
function
addToSearchPath
(
string
$
name
,
string
$
path
,
int
$
precedence
)
{
if
(
!
is_dir
(
$
path
)
)
throw
new
\
InvalidArgumentException
(
"Path does not exist: "
.
$
path
)
;
$
this
->
search_path
[
$
name
]
=
array
(
'path'
=>
$
path
,
'precedence'
=>
$
precedence
)
;
$
this
->
sorted
=
false
;
return
$
this
;
}

Add a module to the search path of the SubResolver.

@param string $name The name of the module. Just for logging purposes.
@param string $path The path of the module.
@param int $precedence The order in which the modules are searched.
Lower means searched earlier.
@return SubResolver Provides fluent interface

Add a module to the search path of the SubResolver .


public function setPrecedence(string $name, int $precedence)
    {
        if (!isset($this->search_path[$name]))
            throw new \InvalidArgumentException("Unknown module: " . $name);

        if ($this->search_path[$name]['precedence'] !== $precedence)
        {
            $this->search_path[$name]['precedence'] = $precedence;
            $this->sorted = false;
        }
        return $this;
    }

public
function
setPrecedence
(
string
$
name
,
int
$
precedence
)
{
if
(
!
isset
(
$
this
->
search_path
[
$
name
]
)
)
throw
new
\
InvalidArgumentException
(
"Unknown module: "
.
$
name
)
;
if
(
$
this
->
search_path
[
$
name
]
[
'precedence'
]
!==
$
precedence
)
{
$
this
->
search_path
[
$
name
]
[
'precedence'
]
=
$
precedence
;
$
this
->
sorted
=
false
;
}
return
$
this
;
}

Set the precedence value of a module
@param string $name The name of the module
@param int $precedence The precedence value to set
@return SubResolver Provides fluent interface


public function getPrecedence(string $name)
    {
        if (!isset($this->search_path[$name]))
            throw new \InvalidArgumentException("Unknown module: " . $name);

        return $this->search_path[$name]['precedence'];
    }

public
function
getPrecedence
(
string
$
name
)
{
if
(
!
isset
(
$
this
->
search_path
[
$
name
]
)
)
throw
new
\
InvalidArgumentException
(
"Unknown module: "
.
$
name
)
;
return
$
this
->
search_path
[
$
name
]
[
'precedence'
]
;
}

Get the precedence value of a module
@param string $name The name of the module
@return int The precedence value


public function clearCache()
    {
        if ($this->cache !== null)
            $this->cache->set('resolve', $this->name, array('data' => [], 'search_path' => $this->search_path));
        return $this;
    }

public function clearCache ( ) { if ( $ this -> cache !== null ) $ this -> cache -> set ( 'resolve' , $ this -> name , array ( 'data' => [ ] , 'search_path' => $ this -> search_path ) ) ; return $ this ; }

Clear the cached resolved files
@return SubResolver Provides fluent interface


protected function getCachedData()
    {
        if ($this->cache === null)
            return null;

        $sp = $this->cache->get('resolve', $this->name, 'search_path');
        if ($sp !== null)
            $sp = $sp->toArray();

        if ($this->search_path !== $sp)
            $this->clearCache();

        return $this->cache->get('resolve', $this->name);
    }

protected function getCachedData ( ) { if ( $ this -> cache === null ) return null ; $ sp = $ this -> cache -> get ( 'resolve' , $ this -> name , 'search_path' ) ; if ( $ sp !== null ) $ sp = $ sp -> toArray ( ) ; if ( $ this -> search_path !== $ sp ) $ this -> clearCache ( ) ; return $ this -> cache -> get ( 'resolve' , $ this -> name ) ; }

Obtain the cached data. The cache is cleared when the sort order does not match
the cache.

@return The cached data

Obtain the cached data . The cache is cleared when the sort order does not match the cache .


public function resolve(string $file)
    {
        if (!$this->sorted)
            $this->sortModules();

        $file = ltrim($file, '/');
        if ($this->ext !== null && substr($file, -strlen($this->ext)) !== $this->ext)
            $file .= $this->ext;

        $cache = $this->getCachedData();
        $cached = $cache !== null ? $cache->get('data', $file) : null;

        if ($cached === false && $this->authorative)
            return null;

        if (!empty($cached))
        {
            if (file_exists($cached['path']) && is_readable($cached['path']))
            {
                self::$logger->debug(
                    "Resolved {0} {1} to path {2} (module: {3}) (cached)",
                    [$this->name, $file, $cached['path'], $cached['module']]
                );
                return $cached['path'];
            }
            else
            {
                self::$logger->error(
                    "Cached path for {0} {1} from module {2} cannot be read: {3}",
                    [$this->name, $file, $cached['module'], $cached['path']]
                );
            }
        }

        $path = null;
        $found_module = null;
        $mods = $this->search_path;

        foreach ($mods as $module => $info)
        {
            $location = $info['path'];
            self::$logger->debug("Trying {0} path: {1}/{2}", [$location, $this->name, $file]);
            $path = $location . '/' . $file;

            if (file_exists($path) && is_readable($path))
            {
                $found_module = $module;
                break;
            }
        }

        if ($found_module !== null)
        {
            self::$logger->debug("Resolved {0} {1} to path {2} (module: {3})", [$this->name, $file, $path, $found_module]);
            if ($cache !== null)
            {
                $cache->set(
                    'data',
                    $file,
                    array("module" => $found_module, "path" => $path)
                );
            }
            return $path;
        }
        elseif ($cache !== null)
        {
            $cache->set('data', $file, false);
        }

        return null;
    }

Helper method that searches the core and modules for a specific type of file.
The files are evaluated in alphabetical order, and core always comes first.

@param $type string The type to find, template or asset
@param $file string The file to locate
@return string A matching file. Null is returned if nothing was found.

Helper method that searches the core and modules for a specific type of file . The files are evaluated in alphabetical order and core always comes first .


public function parserRequestUri($request)
    {
        $url = $request->getPathUri();
        if ($url) {
            $urlArr = preg_split("/\//si", $url);
            if (preg_match("/^[a-z_]*$/si", $urlArr[1])) {
                // http://localhost/?/ModuleName/ViewName/
                $module_name = $urlArr[0];
                $view_name = $request->pathNameToViewName($urlArr, 1);
                $uriParams = $request->getUriParameters($urlArr, 1);
            } elseif (preg_match("/^[a-z_]*$/si", $urlArr[0])) {
                // http://localhost/?/ViewName/
                $module_name = '';
                $view_name = $request->pathNameToViewName($urlArr, 0);
                $uriParams = $request->getUriParameters($urlArr, 0);
            } else {
                throw new Exception();/** @todo Change Exception class more specific. */
            }
        } else {
                $module_name = '';
                $view_name = '';
                $uriParams = [];
        }
        return array(
            'module' => $module_name,
            'shortView' => $view_name,
            'uriParams' => $uriParams,
        );
    }

Parser Uri request
@param Request $request


public function saveStatefullVars($sessionContext)
    {
        if ($this->dropSession){
            $sessionContext->cleanObj($this->objectName, true);
        }else{
            $sessionContext->saveObjVar($this->objectName, "FormStates", $this->formStates, true);
            $sessionContext->saveObjVar($this->objectName, "CurrentStep", $this->currentStep, true);
        }

    }

public function saveStatefullVars ( $ sessionContext ) { if ( $ this -> dropSession ) { $ sessionContext -> cleanObj ( $ this -> objectName , true ) ; } else { $ sessionContext -> saveObjVar ( $ this -> objectName , "FormStates" , $ this -> formStates , true ) ; $ sessionContext -> saveObjVar ( $ this -> objectName , "CurrentStep" , $ this -> currentStep , true ) ; } }

Save Session data of this object

@param \Openbizx\Web\SessionContext $sessionContext
@return void


public function getCurrentStep()
    {  	if($_GET['step'])
	    {
	    	$this->currentStep=$_GET['step'];
	    	return $this->currentStep;
	    }
    	elseif($this->currentStep)
    	{
    		if($this->currentStep > $this->formRefs->count()){
    			return $this->formRefs->count();
    		}else{
    			return $this->currentStep;
    		}
    	}
    	else
    	{
	        $step = isset($_GET['step']) ? $_GET['step'] : 1;
	        $numForms = 0;
	        foreach ($this->formRefs as $formRef)
	            $numForms++;

	        if ($step < 1)
	            $step = 1;
	        if ($step > $numForms)
	            $step = $numForms;
	        $this->currentStep = $step;
	        return $step;
    	}
    }

public function getCurrentStep ( ) { if ( $ _GET [ 'step' ] ) { $ this -> currentStep = $ _GET [ 'step' ] ; return $ this -> currentStep ; } elseif ( $ this -> currentStep ) { if ( $ this -> currentStep > $ this -> formRefs -> count ( ) ) { return $ this -> formRefs -> count ( ) ; } else { return $ this -> currentStep ; } } else { $ step = isset ( $ _GET [ 'step' ] ) ? $ _GET [ 'step' ] : 1 ; $ numForms = 0 ; foreach ( $ this -> formRefs as $ formRef ) $ numForms ++ ; if ( $ step < 1 ) $ step = 1 ; if ( $ step > $ numForms ) $ step = $ numForms ; $ this -> currentStep = $ step ; return $ step ; } }


public function getFormInputs($formName)
    {
        $formObj = Openbizx::getObject($formName);
        $rec = $formObj->getActiveRecord();
        return $rec;
    }

public function getFormInputs ( $ formName ) { $ formObj = Openbizx :: getObject ( $ formName ) ; $ rec = $ formObj -> getActiveRecord ( ) ; return $ rec ; }

Get form inputs

@param string $formName
@return array


public function cancel()
    {
        // call all step forms Cancel method
        if(is_array($this->formStates)){
	        foreach ($this->formStates as $formName=>$state)
	        {
	            if ($state['visited'])
	                Openbizx::getObject($formName)->cancel();
	        }
        }
        $this->dropSession = true;
    }

public
function
cancel
(
)
{
// call all step forms Cancel method
if
(
is_array
(
$
this
->
formStates
)
)
{
foreach
(
$
this
->
formStates
as
$
formName
=>
$
state
)
{
if
(
$
state
[
'visited'
]
)
Openbizx
::
getObject
(
$
formName
)
->
cancel
(
)
;
}
}
$
this
->
dropSession
=
true
;
}

Cancel, clean up the sessions of view and all forms

@return void

Cancel clean up the sessions of view and all forms


public static function registerSubTypeEnum(string $subTypeEnumClass, string $subTypeEnumValueRegexp): bool
    {
        if (!static::hasSubTypeEnum($subTypeEnumClass, $subTypeEnumValueRegexp)) {
            // registering same subtype enum class but with different regexp cause exception in following method
            return static::addSubTypeEnum($subTypeEnumClass, $subTypeEnumValueRegexp);
        }

        return false;
    }

You can register a class just once.

@param string $subTypeEnumClass
@param string $subTypeEnumValueRegexp
@return bool
@throws \Doctrineum\Scalar\Exceptions\SubTypeEnumIsAlreadyRegistered
@throws \Doctrineum\Scalar\Exceptions\SubTypeEnumClassNotFound
@throws \Doctrineum\Scalar\Exceptions\SubTypeEnumHasToBeEnum
@throws \Doctrineum\Scalar\Exceptions\InvalidRegexpFormat


protected function getInput($request, $in, $name)
    {
        switch ($in)
        {
            case 'header':
                return $request->header($name);

            case 'query':
                return $request->query($name);

            case 'path':
                return $request->route($name);

            default:
                throw new \InvalidArgumentException(
                    get_class($this) . " doesn't know how to handle '" . $in . "' parameters"
                );
        }
    }

protected
function
getInput
(
$
request
,
$
in
,
$
name
)
{
switch
(
$
in
)
{
case
'header'
:
return
$
request
->
header
(
$
name
)
;
case
'query'
:
return
$
request
->
query
(
$
name
)
;
case
'path'
:
return
$
request
->
route
(
$
name
)
;
default
:
throw
new
\
InvalidArgumentException
(
get_class
(
$
this
)
.
" doesn't know how to handle '"
.
$
in
.
"' parameters"
)
;
}
}

Get input value from a specific container.
@param Request $request
@param string $in
@param string $name
@return mixed

Get input value from a specific container .


protected function delete($file, $expires)
    {
        if (!is_array($file['path'])) {
            $file['path'] = [$file['path']];
        }

        foreach ($file['path'] as $path) {
            if (File::exists($path)) {
                if ((time() - File::lastModified($path)) >= $expires) {
                    if (!empty($file['before']) && is_callable($file['before'])) {
                        $file['before']($path);
                    }
                    if (File::isDirectory($path)) {
                        File::deleteDirectory($path);
                    } else {
                        File::delete($path);
                    }
                    if (!empty($file['after']) && is_callable($file['after'])) {
                        $file['after']($path);
                    }
                }
            }
        }
    }

protected function delete ( $ file , $ expires ) { if ( ! is_array ( $ file [ 'path' ] ) ) { $ file [ 'path' ] = [ $ file [ 'path' ] ] ; } foreach ( $ file [ 'path' ] as $ path ) { if ( File :: exists ( $ path ) ) { if ( ( time ( ) - File :: lastModified ( $ path ) ) >= $ expires ) { if ( ! empty ( $ file [ 'before' ] ) && is_callable ( $ file [ 'before' ] ) ) { $ file [ 'before' ] ( $ path ) ; } if ( File :: isDirectory ( $ path ) ) { File :: deleteDirectory ( $ path ) ; } else { File :: delete ( $ path ) ; } if ( ! empty ( $ file [ 'after' ] ) && is_callable ( $ file [ 'after' ] ) ) { $ file [ 'after' ] ( $ path ) ; } } } } }

Delete file or directory at given path

@param  array $file [Config item]
@param  int $expires [Expiration in seconds]
@return void


protected function convertToSeconds($expires)
    {
        $seconds = 0;

        if (isset($expires['seconds'])) {
            $seconds += $expires['seconds'];
        }

        if (isset($expires['minutes'])) {
            $seconds += $expires['minutes'] * 60;
        }

        if (isset($expires['hours'])) {
            $seconds += $expires['hours'] * 60 * 60;
        }

        if (isset($expires['days'])) {
            $seconds += $expires['days'] * 24 * 60 * 60;
        }

        if (isset($expires['weeks'])) {
            $seconds += $expires['weeks'] * 7 * 24 * 60 * 60;
        }

        if (isset($expires['months'])) {
            $seconds += $expires['months'] * 30 * 7 * 24 * 60 * 60;
        }

        if (isset($expires['years'])) {
            $seconds += $expires['years'] * 365 * 30 * 7 * 24 * 60 * 60;
        }

        return $seconds;
    }

protected function convertToSeconds ( $ expires ) { $ seconds = 0 ; if ( isset ( $ expires [ 'seconds' ] ) ) { $ seconds += $ expires [ 'seconds' ] ; } if ( isset ( $ expires [ 'minutes' ] ) ) { $ seconds += $ expires [ 'minutes' ] * 60 ; } if ( isset ( $ expires [ 'hours' ] ) ) { $ seconds += $ expires [ 'hours' ] * 60 * 60 ; } if ( isset ( $ expires [ 'days' ] ) ) { $ seconds += $ expires [ 'days' ] * 24 * 60 * 60 ; } if ( isset ( $ expires [ 'weeks' ] ) ) { $ seconds += $ expires [ 'weeks' ] * 7 * 24 * 60 * 60 ; } if ( isset ( $ expires [ 'months' ] ) ) { $ seconds += $ expires [ 'months' ] * 30 * 7 * 24 * 60 * 60 ; } if ( isset ( $ expires [ 'years' ] ) ) { $ seconds += $ expires [ 'years' ] * 365 * 30 * 7 * 24 * 60 * 60 ; } return $ seconds ; }

Convert config to seconds

@param  array $expires  [Config item expires value]
@return int