protected function getMiddlewareGroup(string $id = Group::DEFAULT_ID): MiddlewareCollection
    {
        if (! isset($this->middleware[$id]) || $this->middleware[$id] instanceof MiddlewareCollection === false) {
            $this->middleware[$id] = $this->middlewareCollection($id);
        }
        return $this->middleware[$id];
    }

protected function getMiddlewareGroup ( string $ id = Group :: DEFAULT_ID ) : MiddlewareCollection { if ( ! isset ( $ this -> middleware [ $ id ] ) || $ this -> middleware [ $ id ] instanceof MiddlewareCollection === false ) { $ this -> middleware [ $ id ] = $ this -> middlewareCollection ( $ id ) ; } return $ this -> middleware [ $ id ] ; }

Looks for the given group id in the middle collection, creating a new instance if it doesn't exist.

@param string $id
@return \MichaelRShelton\MiddleMan\Concerns\Group

Looks for the given group id in the middle collection creating a new instance if it doesn t exist .


protected function groupMiddleware(string $name = null, Closure $closure = null)
    {
        if ($name === null) {
            return $this->middlewareGroupId;
        } else {
            $previousGroup = $this->middlewareGroupId;
            $this->middlewareGroupId = $name;
            if ($closure !== null) {
                $closure($this);
                $this->middlewareGroupId = $previousGroup;
            }
            return $this;
        }
    }

protected function groupMiddleware ( string $ name = null , Closure $ closure = null ) { if ( $ name === null ) { return $ this -> middlewareGroupId ; } else { $ previousGroup = $ this -> middlewareGroupId ; $ this -> middlewareGroupId = $ name ; if ( $ closure !== null ) { $ closure ( $ this ) ; $ this -> middlewareGroupId = $ previousGroup ; } return $ this ; } }

Define the default group setting.

@param string|null $name
@param \Closure|null $closure
@return string|$this


protected function hasMiddleware(string $key, string $group = null): bool
    {
        return $this->getMiddlewareGroup($group ?: $this->middlewareGroupId)->has($key);
    }

protected function hasMiddleware ( string $ key , string $ group = null ) : bool { return $ this -> getMiddlewareGroup ( $ group ? : $ this -> middlewareGroupId ) -> has ( $ key ) ; }

Determine if the instance has a given middleware.

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

Determine if the instance has a given middleware .


protected function isMiddlewareDisabled(string $key = '', string $group = null): bool
    {
        $middleware = $this->getMiddleware($key, $group);
        return $middleware instanceof Disableable ? $middleware->isDisabled() : false;
    }

protected function isMiddlewareDisabled ( string $ key = '' , string $ group = null ) : bool { $ middleware = $ this -> getMiddleware ( $ key , $ group ) ; return $ middleware instanceof Disableable ? $ middleware -> isDisabled ( ) : false ; }

Checks the disabled status of the given middleware.

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

Checks the disabled status of the given middleware .


protected function isMiddlewareEnabled(string $key = '', string $group = null): bool
    {
        $middleware = $this->getMiddleware($key, $group);
        return $middleware instanceof Enableable ? $middleware->isEnabled() : false;
    }

protected function isMiddlewareEnabled ( string $ key = '' , string $ group = null ) : bool { $ middleware = $ this -> getMiddleware ( $ key , $ group ) ; return $ middleware instanceof Enableable ? $ middleware -> isEnabled ( ) : false ; }

Checks the enabled status of the given middleware.

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

Checks the enabled status of the given middleware .


protected function middleware(string $key = null, string $group = Group::DEFAULT_ID)
    {
        $middleware = $this->middleMan->getGroup($group)->get($key);
        if ($middleware) {
            $this->result = $this->then($middleware);
        }
        return $this->resultUnlessChainable();
    }

protected function middleware ( string $ key = null , string $ group = Group :: DEFAULT_ID ) { $ middleware = $ this -> middleMan -> getGroup ( $ group ) -> get ( $ key ) ; if ( $ middleware ) { $ this -> result = $ this -> then ( $ middleware ) ; } return $ this -> resultUnlessChainable ( ) ; }

Resolve the defined middleware and include it here if it exists.

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

Resolve the defined middleware and include it here if it exists .


protected function middlewareCollection(string $id = Group::DEFAULT_ID, $middleware = []): MiddlewareCollection
    {
        if (function_exists('collect_middleware')) {
            return collect_middleware($middleware, $id);
        } else {
            return new Group($middleware, $id);
        }
    }

protected function middlewareCollection ( string $ id = Group :: DEFAULT_ID , $ middleware = [ ] ) : MiddlewareCollection { if ( function_exists ( 'collect_middleware' ) ) { return collect_middleware ( $ middleware , $ id ) ; } else { return new Group ( $ middleware , $ id ) ; } }

Get the collection calls.

@param string $id
@param array $middleware
@return \MichaelRShelton\MiddleMan\Interfaces\MiddlewareCollection


protected function prependMiddleware($middleware, string $key = "", string $group = null)
    {
        $middleware = $this->middlewareResolver()->resolveOrFail($middleware, $key);
        $this->getMiddlewareGroup($group ?: $this->middlewareGroupId)->prepend($middleware, $key);
        return $this;
    }

protected function prependMiddleware ( $ middleware , string $ key = "" , string $ group = null ) { $ middleware = $ this -> middlewareResolver ( ) -> resolveOrFail ( $ middleware , $ key ) ; $ this -> getMiddlewareGroup ( $ group ? : $ this -> middlewareGroupId ) -> prepend ( $ middleware , $ key ) ; return $ this ; }

Add a new middleware to beginning of the stack if it does not already exist.

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

Add a new middleware to beginning of the stack if it does not already exist .


protected function pushMiddleware($middleware, string $key = "", string $group = null)
    {
        $middleware = $this->middlewareResolver()->resolveOrFail($middleware, $key);
        $this->getMiddlewareGroup($group ?: $this->middlewareGroupId)->put($key, $middleware);
        return $this;
    }

protected function pushMiddleware ( $ middleware , string $ key = "" , string $ group = null ) { $ middleware = $ this -> middlewareResolver ( ) -> resolveOrFail ( $ middleware , $ key ) ; $ this -> getMiddlewareGroup ( $ group ? : $ this -> middlewareGroupId ) -> put ( $ key , $ middleware ) ; return $ this ; }

Add a new middleware to end of the stack if it does not already exist.

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

Add a new middleware to end of the stack if it does not already exist .


protected function setMiddlewareContext($context, MiddlewareCollection &$group = null)
    {
        if ($group === null) {
            $group = $this->middleware;
        }
        if ($group) {
            foreach ($group as &$value) {
                if ($value instanceof MiddlewareCollection) {
                    $this->setMiddlewareContext($context, $value);
                } elseif ($value instanceof MiddlewareInterface) {
                    $value->as($context);
                }
            }
        }
        return $this;
    }

protected function setMiddlewareContext ( $ context , MiddlewareCollection & $ group = null ) { if ( $ group === null ) { $ group = $ this -> middleware ; } if ( $ group ) { foreach ( $ group as & $ value ) { if ( $ value instanceof MiddlewareCollection ) { $ this -> setMiddlewareContext ( $ context , $ value ) ; } elseif ( $ value instanceof MiddlewareInterface ) { $ value -> as ( $ context ) ; } } } return $ this ; }

Sets the context for the middleware.

@param $context
@param \MichaelRShelton\MiddleMan\Interfaces\MiddlewareCollection|null $group
@return $this


protected function thenCallMiddleware($middleware)
    {
        if (function_exists('call_middleware')) {
            $this->result = call_middleware($middleware, $this->result);
        } else {
            $this->result = (new Caller($middleware))->call($this->result);
        }
        return $this->resultUnlessChainable();
    }

protected function thenCallMiddleware ( $ middleware ) { if ( function_exists ( 'call_middleware' ) ) { $ this -> result = call_middleware ( $ middleware , $ this -> result ) ; } else { $ this -> result = ( new Caller ( $ middleware ) ) -> call ( $ this -> result ) ; } return $ this -> resultUnlessChainable ( ) ; }

Calls the given middleware and returns the result as if part of the middleware chains.

The helper function will check for an app container, which can assist in injecting dependencies.

@param mixed $middleware
@return \MichaelRShelton\MiddleMan\Controller|mixed

Calls the given middleware and returns the result as if part of the middleware chains .


public function save()
    {
        $location = $this->location;

        // no location given from commandline -> use config values or fallback to default location
        if (empty($location)) {
            $location = $this->parameters->get(
                'write_location',
                $this->parameters->get(
                    'location',
                    $this->getDefaultLocation()
                )
            );
        }

        $this->location = $location;

        $data = array();
        foreach ($this->settings as $setting) {
            $data[] = $setting->toArray();
        }

        $flags = 0;
        if ($this->parameters->get('pretty', true) && version_compare(PHP_VERSION, '5.4.0') >= 0) {
            $flags |= JSON_PRETTY_PRINT;
        }

        $content = json_encode($data, $flags);

        if (false === $content) {
            throw new \Exception('Could not json_encode cachable settings. Nothing written to cache.');
        }

        $success = (false !== file_put_contents($location, $content));

        $success &= chmod($location, 0600); // only current user should read/write potentially sensitive info

        return $success;
    }

Writes the current set of ISetting instances to the cache file location.

@return boolean true when cache file writing succeeded

@throws \Exception if content could not be encoded

Writes the current set of ISetting instances to the cache file location .


private function _getForms($forms)
    {
        $recArr = array();
        if (count($forms) == 0)
            return $recArr;

        foreach ($forms as $form) {
            if (!is_null($form["ATTRIBUTES"]))
                $recArr[] = $form["ATTRIBUTES"];
            else
                $recArr[] = $form;
        }
        return $recArr;
    }

private function _getForms ( $ forms ) { $ recArr = array ( ) ; if ( count ( $ forms ) == 0 ) return $ recArr ; foreach ( $ forms as $ form ) { if ( ! is_null ( $ form [ "ATTRIBUTES" ] ) ) $ recArr [ ] = $ form [ "ATTRIBUTES" ] ; else $ recArr [ ] = $ form ; } return $ recArr ; }

Get forms or the form to hide or show.
When It has one form It hasn't the ATTRIBUTES property

@param array $forms
@return array

Get forms or the form to hide or show . When It has one form It hasn t the ATTRIBUTES property


protected function setup()
    {
        $autoloader = $this->decode($this->filename);
        if (null === $autoloader) {
            throw new InvalidJsonFormatException(sprintf('The json file %s is malformed. Please check the file syntax to fix the problem', $this->filename));
        }

        if (empty($autoloader["bundles"])) {
            throw new InvalidJsonFormatException(sprintf('The json file %s requires the bundles section. Please add that section to fix the problem', $this->filename));
        }

        foreach ($autoloader["bundles"] as $bundleClass => $options) {
            $environments = (isset($options["environments"])) ? $options["environments"] : 'all';
            if (!is_array($environments)) $environments = array($environments);
            $overrides = (isset($options["overrides"])) ? $options["overrides"] : array();
            $bundle = new Bundle();
            $bundle
                ->setClass($bundleClass)
                ->setOverrides($overrides)
            ;
            foreach ($environments as $environment) {
                $this->bundles[$environment][] = $bundle;
            }
        }

        if (isset($autoloader["actionManager"])) {
            $this->actionManagerClass = $autoloader["actionManager"];
        }

        if (isset($autoloader["routing"])) {
            $this->routing = $autoloader["routing"];
        }
    }

Parses the json file and sets up the object


protected function findTransition(Execution $execution)
    {
        $out = (array) $execution->getProcessModel()->findOutgoingTransitions($execution->getNode()->getId());
        $trans = null;

        if ($this->transitionId === null) {
            if (count($out) != 1) {
                throw new \RuntimeException(sprintf('No single outgoing transition found at node "%s"', $execution->getNode()->getId()));
            }

            return array_pop($out);
        }

        foreach ($out as $tmp) {
            if ($tmp->getId() === $this->transitionId) {
                $trans = $tmp;

                break;
            }
        }

        if ($trans === null) {
            throw new \RuntimeException(sprintf('Transition "%s" not connected to node "%s"', $this->transitionId, $execution->getNode()->getId()));
        }

        return $trans;
    }

Find the outgoing transition to be taken by the given execution.

@param Execution $execution
@throws \RuntimeException
@return Transition

Find the outgoing transition to be taken by the given execution .


public function remoteCall($options = array())
    {
        return function ($options) {
            $type = isset($options['type']) ? $options['type'] : "POST";
            $dataType = isset($options['dataType']) ? $options['dataType'] : "html";
            $js = "$.ajax({
							url: '" . $options['url'] . "',
							type: '" . $type . "',
							dataType: '" . $dataType . "',";

            if (isset($options['before'])) {
                $before = str_replace('"', "'", $options['before']);
                $js .= "beforeSend: function(){" . $before . "},";
            }

            $js .= "success: function( data ){ $('" . $options['update'] . "').html(data);";

            if (isset($options['after'])) {
                $after = str_replace('"', "'", $options['after']);
                $js .= $after;
            }

            $js .= "}";

            if (isset($options['complete'])) {
                $complete = str_replace('"', "'", $options['complete']);
                $js .= ",complete: function(){" . $complete . "},";
            }

            $js .= "});";

            return $js;
        };
    }

Generate Js function to send ajax request.

@param array $options

Generate Js function to send ajax request .


public function submitCall($options = array())
    {
    	return function ($options) {
    		$type = isset($options['type']) ? $options['type'] : "POST";
    		$dataType = isset($options['dataType']) ? $options['dataType'] : "html";
    		$js = "$.ajax({
		    		url: '" . $options['url'] . "',
		    		type: '" . $type . "',
		    		data: $(this.form.elements).serializeArray(),
		    		dataType: '" . $dataType . "',";
    		if (isset($options['before'])) {
    			$before = str_replace('"', "'", $options['before']);
    			$js .= "beforeSend: function(){" . $before . "},";
    		}
    		$js .= "success: function( data ){";
    		if (isset($options['success'])) {
    			$success = str_replace('"', "'", $options['success']);
    			$js .= $success ;
    		}
    		if (isset($options['after'])) {
    			$after = str_replace('"', "'", $options['after']);
    			$js .= $after;
    		}

    		$js .= "}});";

    		return $js;
    	};
    }

Generate Js function to send ajax form data.

@param array $options

Generate Js function to send ajax form data .


public function linkTag($options = array())
    {
        $jsRequest = $this->remoteCall();

        return function ($options) use($jsRequest)
        {
            $confirm = '';
            if (isset($options['confirm']) && $options['confirm'] === true) {

                $msg = "Are you sure you want to perform this action?";
                if(isset($options['confirm_msg'])) {
                    $msg = htmlentities(str_replace("'", '"', $options['confirm_msg']), ENT_QUOTES);
                }
            	$confirm .= "if(confirm('".$msg."'))" ;
            }
            $html = '';
            $html .= $options['text'];
            $html .= '';

            return $html;
        };
    }

Generate link tag with js function to send ajax request

@param array $options


public function submitTag($options = array())
    {
    	$jsSubmit = $this->submitCall();

    	return function ($options) use($jsSubmit)
    	{
    		$confirm = '';
    		if (isset($options['confirm']) && $options['confirm'] === true) {

    			$msg = "Are you sure you want to perform this action?";
    			if(isset($options['confirm_msg'])) {
    				$msg = htmlentities(str_replace("'", '"', $options['confirm_msg']), ENT_QUOTES);
    			}
    			$confirm .= "if(confirm('".$msg."'))" ;
    		}
    		$html = '<button class="' . (isset($options['class']) ? $options['class'] : "") . '"
    		id="' . (isset($options['id']) ? $options['id'] : "") . '"
    		onclick="' .$confirm. call_user_func($jsSubmit, $options) . 'return false;">';
    		$html .= $options['text'];
    		$html .= '</button>';

    		return $html;
    	};
    }

Generate submit button tag with js function to send ajax form

@param array $options


public function castKey($key, string $default = ""): string
    {
        return is_int($key) || empty($key) ? $default : (string)$key;
    }

public function castKey ( $ key , string $ default = "" ) : string { return is_int ( $ key ) || empty ( $ key ) ? $ default : ( string ) $ key ; }

The key should be a native string, so it will cast what it can with a fallback.
The goal of this is to normalize associative keys and allowing the developer to
decide if they want to included non-associative keys.

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

The key should be a native string so it will cast what it can with a fallback . The goal of this is to normalize associative keys and allowing the developer to decide if they want to included non - associative keys .


protected function isAbstract($middleware): bool
    {
        return is_string($middleware) &&
            class_exists($middleware) &&
            is_a($middleware, MiddlewareInterface::class, true);
    }

protected function isAbstract ( $ middleware ) : bool { return is_string ( $ middleware ) && class_exists ( $ middleware ) && is_a ( $ middleware , MiddlewareInterface :: class , true ) ; }

Determines if the given middleware value is a string that can be instantiated.
Note that it does not check an application container.

@param mixed $middleware
@return bool

Determines if the given middleware value is a string that can be instantiated . Note that it does not check an application container .


public function isCollection($middleware): bool
    {
        $isArray = is_array($middleware) && ! is_callable($middleware);
        return $isArray || $middleware instanceof Traversable || $middleware instanceof ArrayAccess;
    }

public function isCollection ( $ middleware ) : bool { $ isArray = is_array ( $ middleware ) && ! is_callable ( $ middleware ) ; return $ isArray || $ middleware instanceof Traversable || $ middleware instanceof ArrayAccess ; }

Checks to see if the given value has a lot of middleware or just one.

@param $middleware
@return bool

Checks to see if the given value has a lot of middleware or just one .


public function resolve($middleware, &$key = null)
    {
        if ($this->isCollection($middleware)) {
            return $this->resolveMany($middleware, $key ?: Group::DEFAULT_ID);
        } else {
            return $this->resolveOne($middleware, $key);
        }
    }

public function resolve ( $ middleware , & $ key = null ) { if ( $ this -> isCollection ( $ middleware ) ) { return $ this -> resolveMany ( $ middleware , $ key ? : Group :: DEFAULT_ID ) ; } else { return $ this -> resolveOne ( $ middleware , $ key ) ; } }

Resolve the given middleware.

@param mixed $middleware
@param mixed $key
@return bool|\Closure|\MichaelRShelton\MiddleMan\Interfaces\MiddlewareInterface|\MichaelRShelton\MiddleMan\Contracts|MiddlewareCollection


public function resolveOrFail($middleware, &$key = null)
    {
        if ($this->isCollection($middleware)) {
            return $this->resolveManyOrFail($middleware, $key ?: Group::DEFAULT_ID);
        } else {
            return $this->resolveOneOrFail($middleware, $key);
        }
    }

public function resolveOrFail ( $ middleware , & $ key = null ) { if ( $ this -> isCollection ( $ middleware ) ) { return $ this -> resolveManyOrFail ( $ middleware , $ key ? : Group :: DEFAULT_ID ) ; } else { return $ this -> resolveOneOrFail ( $ middleware , $ key ) ; } }

Resolve the given middleware or throw an exception if the argument isn't valid.

@throws \InvalidArgumentException

@param mixed $middleware
@param mixed $key
@return bool|\Closure|\MichaelRShelton\MiddleMan\Interfaces\MiddlewareInterface|\MichaelRShelton\MiddleMan\Interfaces\MiddlewareCollection

Resolve the given middleware or throw an exception if the argument isn t valid .


protected function resolveMany($group, string $id = Group::DEFAULT_ID): MiddlewareCollection
    {
        $group = $group instanceof MiddlewareCollection ? clone $group : $this->collection($group, $id);
        foreach ($group as $key => $middleware) {
            $middleware = $this->resolveOne($middleware, $key);
            if ($middleware !== false) {
                $group->put($key, $middleware);
            }
        }
        return $group;
    }

protected function resolveMany ( $ group , string $ id = Group :: DEFAULT_ID ) : MiddlewareCollection { $ group = $ group instanceof MiddlewareCollection ? clone $ group : $ this -> collection ( $ group , $ id ) ; foreach ( $ group as $ key => $ middleware ) { $ middleware = $ this -> resolveOne ( $ middleware , $ key ) ; if ( $ middleware !== false ) { $ group -> put ( $ key , $ middleware ) ; } } return $ group ; }

Resolve a group of middleware.

@param mixed $group
@param string $id
@return \MichaelRShelton\MiddleMan\Interfaces\MiddlewareCollection


protected function resolveManyOrFail($group, string $id = Group::DEFAULT_ID): MiddlewareCollection
    {
        $group = $group instanceof MiddlewareCollection ? clone $group : $this->collection($group, $id);
        foreach ($group as $key => $middleware) {
            $middleware = $this->resolveOneOrFail($middleware, $key);
            if ($middleware !== false) {
                $group->put($key, $middleware);
            }
        }
        return $group;
    }

protected function resolveManyOrFail ( $ group , string $ id = Group :: DEFAULT_ID ) : MiddlewareCollection { $ group = $ group instanceof MiddlewareCollection ? clone $ group : $ this -> collection ( $ group , $ id ) ; foreach ( $ group as $ key => $ middleware ) { $ middleware = $ this -> resolveOneOrFail ( $ middleware , $ key ) ; if ( $ middleware !== false ) { $ group -> put ( $ key , $ middleware ) ; } } return $ group ; }

Resolve a group of middleware or throw an exception if one is not valid.

@throws \InvalidArgumentException

@param mixed $group
@param string $id
@return \MichaelRShelton\MiddleMan\Interfaces\MiddlewareCollection

Resolve a group of middleware or throw an exception if one is not valid .


protected function resolveOne($middleware, &$key = null)
    {
        if ($middleware instanceof Closure) {
            $key = $key ? $this->castKey($key) : "";

        } elseif ($this->isAbstract($middleware)) {
            $key = $this->castKey($key, $middleware);
            $middleware = new $middleware;

        } elseif (is_object($middleware) && $middleware instanceof MiddlewareInterface) {
            $key = $this->castKey($key, get_class($middleware));

        } elseif (is_callable($middleware)) {
            $key = $key ? $this->castKey($key) : "";

        } elseif ($middleware instanceof MiddlewareCollection) {
            $key = $middleware->getId();
            $middleware = $this->resolveMany($middleware, $middleware->getId());

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

protected function resolveOne ( $ middleware , & $ key = null ) { if ( $ middleware instanceof Closure ) { $ key = $ key ? $ this -> castKey ( $ key ) : "" ; } elseif ( $ this -> isAbstract ( $ middleware ) ) { $ key = $ this -> castKey ( $ key , $ middleware ) ; $ middleware = new $ middleware ; } elseif ( is_object ( $ middleware ) && $ middleware instanceof MiddlewareInterface ) { $ key = $ this -> castKey ( $ key , get_class ( $ middleware ) ) ; } elseif ( is_callable ( $ middleware ) ) { $ key = $ key ? $ this -> castKey ( $ key ) : "" ; } elseif ( $ middleware instanceof MiddlewareCollection ) { $ key = $ middleware -> getId ( ) ; $ middleware = $ this -> resolveMany ( $ middleware , $ middleware -> getId ( ) ) ; } else { $ middleware = false ; } return $ middleware ; }

Resolve a single middleware.

@param mixed $middleware
@param null $key
@return bool|\Closure|\MichaelRShelton\MiddleMan\Interfaces\MiddlewareInterface


protected function resolveOneOrFail($middleware, &$key = null)
    {
        $type = is_object($middleware) ? get_class($middleware) : gettype($middleware);
        $middleware = $this->resolveOne($middleware, $key);

        if ($middleware === false) {
            $className = MiddlewareInterface::class;
            $method = get_class($this) . "::resolve";
            $msg = "%s expected a Closure, a callable or abstract %s string, or %s. Received: %s";

            throw new InvalidArgumentException(sprintf($msg, $method, $className, $className, $type));
        }
        return $middleware;
    }

Resolve a single middleware or throw an exception if it fails.

@throws \InvalidArgumentException

@param mixed $middleware
@param mixed $key
@return bool|\Closure|\MichaelRShelton\MiddleMan\Interfaces\MiddlewareInterface

Resolve a single middleware or throw an exception if it fails .


public function render($objName)
    {
        // get the current UI bizobj
        $bizform = Openbizx::getObject($objName);    // get the existing bizform object
        $bizobj = $bizform->getDataObj();

        $h=opendir($this->targetReportPath);
        if (!$h)
        {
            echo "cannot read dir ".$this->targetReportPath;
            exit;
        }
        // create a tmp csv file for hold the data, then feed csv file to report engine
        $uid = $this->getUniqueString();
        $tmpfname = $this->targetReportPath . $uid . ".csv";
        //echo "csv file is at $tmpfname.
";
        $fp = fopen($tmpfname, 'w');

        $keyList = $bizform->recordRow->GetSortControlKeys();
        $fieldNames = array();
        foreach($keyList as $key)
        {
            $fieldNames[] = $bizform->GetControl($key)->bizFieldName;
        }
        fputcsv($fp, $fieldNames);

        $recList = $bizobj->directFetch();
        foreach ($recList as $recArray)
        {
            unset($fieldValues);
            $fieldValues = array();
            $line = "";
            foreach($keyList as $key)
            {
                $fieldValues[] = $recArray[$bizform->GetControl($key)->bizFieldName];
            }
            fputcsv($fp, $fieldValues);
        }

        fclose($fp);

        $i = 0;
        foreach($keyList as $key)
        {
            $rpt_fields[$i]["name"] = $bizform->GetControl($key)->bizFieldName;
            $rpt_fields[$i]["type"] = $bizobj->getField($rpt_fields[$i]["name"])->type;
            $i++;
        }

        // dataobj.rptdesign.tpl
        // $rpt_data_dir, $rpt_title, $rpt_csv_file, $rpt_fields[](name,type)
        $smarty = TemplateHelper::getSmartyTemplate();
        $smarty->assign("rpt_data_dir", $this->targetReportPath);
        $smarty->assign("rpt_title", $bizform->title);
        $smarty->assign("rpt_csv_file", basename($tmpfname));
        $smarty->assign("rpt_fields", $rpt_fields);
        $reportContent = $smarty->fetch($this->rptTemplate);

        $tmpRptDsgn = $this->targetReportPath . $uid . ".rptdesign";
        //echo "temp rpt design file is at $tmpRptDsgn.
";
        $fp = fopen($tmpRptDsgn, 'w');
        fwrite($fp, $reportContent);
        fclose($fp);

        ob_clean();
        $designFileName = $uid . ".rptdesign";
        $content = "
";
        $content .= "Reports can be viewed as ";
        $content .= "
birtViewer."/run?__report=report\\$designFileName' target='__blank'>HTML report
";
        $content .= "
birtViewer."/run?__report=report\\$designFileName&__format=pdf' target='__blank'>PDF report
";
        $content .= "
birtViewer."/frameset?__report=report\\$designFileName' target='__blank'>Interactive report
";
        $content .= "
";

        echo $content;
        exit;
    }

//echo "temp rpt design file is at $tmpRptDsgn.<br>";

"<div style='font-family:Arial; font-size:12px; background-color:#FCFCFC;'>"

render the report output

@param string $objName object name which is the bizform name
@return void


public function getUniqueString()
    {
        $mdy = date("mdy");
        $hms = date("His");
        $rightnow = $mdy.$hms;

        return md5($rightnow);
    }

public function getUniqueString ( ) { $ mdy = date ( "mdy" ) ; $ hms = date ( "His" ) ; $ rightnow = $ mdy . $ hms ; return md5 ( $ rightnow ) ; }

Get unique string by time and MD5

@return string


public function is($role, $all = false)
    {
        if ($this->isPretendEnabled()) {
            return $this->pretend('is');
        }

        return $this->{$this->getMethodName('is', $all)}($this->getArrayFrom($role));
    }

public function is ( $ role , $ all = false ) { if ( $ this -> isPretendEnabled ( ) ) { return $ this -> pretend ( 'is' ) ; } return $ this -> { $ this -> getMethodName ( 'is' , $ all ) } ( $ this -> getArrayFrom ( $ role ) ) ; }

Check if the user has a role or roles.

@param int|string|array $role
@param bool $all
@return bool


protected function hasRole($role)
    {
        return $this->getRoles()->contains(function ($key, $value) use ($role) {
            return $role == $value->id || Str::is($role, $value->slug);
        });
    }

protected function hasRole ( $ role ) { return $ this -> getRoles ( ) -> contains ( function ( $ key , $ value ) use ( $ role ) { return $ role == $ value -> id || Str :: is ( $ role , $ value -> slug ) ; } ) ; }

Check if the user has role.

@param int|string $role
@return bool


public function getHash()
    {
        $paramString = $this->getParamString(func_get_args());
        $encrypted = crypt($paramString, '$2a$07$'.$this->secret.'$');
        //echo "encrypted=$encrypted ; paramString=$paramString";
        return $encrypted;
    }

return a hash for a list of params
@param mixed variable length param list


public function getInfo($opt = null) {
		if (null === $opt) {
			return curl_getinfo($this->getCurl());
		}

		return curl_getinfo($this->getCurl(), $opt);
	}

public function getInfo ( $ opt = null ) { if ( null === $ opt ) { return curl_getinfo ( $ this -> getCurl ( ) ) ; } return curl_getinfo ( $ this -> getCurl ( ) , $ opt ) ; }

Get information regarding a specific transfer
@param null|int $opt
@return array|string


public function perform(): Client {
		if (!empty($this->getUrl())){
			$this->setOption(CURLOPT_URL, $this->getUrl());
		}

		if ($this->getOptions()[CURLOPT_HEADER] === 1) {
			$this->setResponse(substr($this->getResponse(), $this->getInfo(CURLINFO_HEADER_SIZE)));
		}

		$this->setResponse(curl_exec($this->getCurl()));

		/**
		 * Check returned HTTP code between 100 and 399.
		 * See issue #1
		 */
		if (filter_var(
			$this->getInfo(CURLINFO_HTTP_CODE),
			FILTER_VALIDATE_INT,
			['options' => ['min_range' => 100, 'max_range' => 399]])
		) {
			$this->_call($this->successCallback ?? function(Client $instance){}, $this);
		}
		else {
			$this->_call($this->errorCallback ?? function(Client $instance){}, $this);
		}

		return $this;
	}


public function allowViewAccess($viewName, $role=null)
    {
        if (!$role)
            $role = "";

        $view = $this->getMatchView($viewName);
        if (!$view)
            return true;

        $roleList = $view->getRoleList();
        if (!$roleList)
            return true;
        if ($roleList->get($role))
            return true;

        return false;
    }

public function allowViewAccess ( $ viewName , $ role = null ) { if ( ! $ role ) $ role = "" ; $ view = $ this -> getMatchView ( $ viewName ) ; if ( ! $ view ) return true ; $ roleList = $ view -> getRoleList ( ) ; if ( ! $ roleList ) return true ; if ( $ roleList -> get ( $ role ) ) return true ; return false ; }

Allow view access

@param string $viewName
@param <type> $role
@return boolean


protected function getMatchView($viewName)
    {
        /* @var $viewObj WebPage */
        $viewObj = $this->_restrictedViewList->get($viewName);
        if ($viewObj)
            return $viewObj;
        foreach ($this->_restrictedViewList as $view => $viewObj)
        {
            $preg_view = "/".$view."/";
            if (preg_match($preg_view, $viewName))
            {
                return $viewObj;
            }
        }
        return null;
    }

protected
function
getMatchView
(
$
viewName
)
{
/* @var $viewObj WebPage */
$
viewObj
=
$
this
->
_restrictedViewList
->
get
(
$
viewName
)
;
if
(
$
viewObj
)
return
$
viewObj
;
foreach
(
$
this
->
_restrictedViewList
as
$
view
=>
$
viewObj
)
{
$
preg_view
=
"/"
.
$
view
.
"/"
;
if
(
preg_match
(
$
preg_view
,
$
viewName
)
)
{
return
$
viewObj
;
}
}
return
;
}

Get match view

@param string $viewName
@return WebPage|null


public function format(IReport $report)
    {
        $output = '';
        $params = $this->getParameters();

        $file = $params->get('location', 'environaut-config.php');
        $groups = $params->get('groups');
        $nested = $params->get('nested', true);

        if (is_writable($file)) {
            $output .= '<comment>Overwriting</comment> ';
        } else {
            $output .= 'Writing ';
        }

        if (empty($groups)) {
            $output .= 'all groups ';
        } else {
            $output .= 'group(s) "' . implode(', ', $groups) . '" ';
        }

        $output .= 'to file "<comment>' . $file . '</comment>"...';

        $default_template = <<<EOT
<?php return %settings\$s;
EOT;

        $template = $params->get('template', $default_template);

        $all_settings = $report->getSettingsAsArray($groups);

        $grouped_settings = array();
        foreach ($all_settings as $setting) {
            if ($nested === true) {
                $grouped_settings[$setting['group']][$setting['name']] = $setting['value'];
            } else {
                $grouped_settings[$setting['name']] = $setting['value'];
            }
        }

        $content = XmlSettingsWriter::vksprintf($template, array('settings' => var_export($grouped_settings, true)));

        $ok = file_put_contents($file, $content, LOCK_EX);

        if ($ok !== false) {
            $output .= '<info>ok</info>.';
        } else {
            $output .= '<error>FAILED</error>.';
        }

        return $output;
    }

Writes all or specific groups of settings as a PHP file and
returns a message with some information about that.

@param IReport $report report to take results (and settings) from

@return string messages for CLI output

Writes all or specific groups of settings as a PHP file and returns a message with some information about that .


public function loadXml($source, $options = 0)
    {
        $user_error_handling = $this->enableErrorHandling();

        $success = parent::loadXML($source, $options);

        $this->handleErrors(
            'Loading the document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the mentioned errors.',
            $user_error_handling
        );

        $this->refreshXpath();

        return $success;
    }

Loads XML from a string and registers the Environaut configuration
namespace if the XML document is an Environaut configuration file.

@param string $source xml string to load
@param int $options libXml flags to use for loading (like LIBXML_NOCDATA etc.)

@return bool true on success; false on error

@throws \DOMException in case of errors loading the document from the given string

Loads XML from a string and registers the Environaut configuration namespace if the XML document is an Environaut configuration file .


public function schemaValidate($filename)
    {
        if (!is_readable($filename)) {
            throw new \DOMException("Schema file is not readable: $filename");
        }

        $user_error_handling = $this->enableErrorHandling();

        $success = parent::schemaValidate($filename);

        $this->handleErrors(
            'Validating the document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the mentioned errors or use another schema file.',
            $user_error_handling
        );

        return $success;
    }

Validates the current document according to the given schema file.

@param string $filename path to the schema file

@return bool true on success

@throws \DomException in case of validation errors or non-readable file

Validates the current document according to the given schema file .


public function schemaValidateSource($source)
    {
        if (empty($source)) {
            throw new \DOMException('Schema is empty.');
        }

        $user_error_handling = $this->enableErrorHandling();

        $success = parent::schemaValidateSource($source);

        $this->handleErrors(
            'Validating the document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the mentioned errors or use another schema.',
            $user_error_handling
        );

        return $success;
    }

Validates the current document according to the given schema file content.

@param string $source content of a schema file

@return bool true on success

@throws \DomException in case of validation errors or empty schema

Validates the current document according to the given schema file content .


public function xinclude($options = 0)
    {
        $user_error_handling = $this->enableErrorHandling();

        $number_of_xincludes = parent::xinclude($options);

        $this->handleErrors(
            'Resolving XInclude directives in the current document failed. Details are:' . PHP_EOL . PHP_EOL,
            PHP_EOL . 'Please fix the XInclude directives according to the mentioned errors.',
            $user_error_handling
        );

        return $number_of_xincludes;
    }

Substitutes XIncludes present in the current document.

@param int $options libXml flags to use for loading (like LIBXML_NOCDATA etc.)

@return int number of XIncludes or false if no xincludes were found

@throws \DOMException in case of errors xincluding content

Substitutes XIncludes present in the current document .


public function getElementValue($element_name, $reference_element = null)
    {
        $element_name = trim($element_name);
        if (empty($element_name)) {
            throw new \InvalidArgumentException('Element name must not be empty.');
        }

        if (null === $reference_element) {
            $reference_element = $this->documentElement;
        }

        if ($this->isEnvironautDocument()) {
            foreach ($reference_element->childNodes as $node) {
                if ($node->nodeType == XML_ELEMENT_NODE &&
                    $node->localName == $element_name &&
                    $node->namespaceURI == $this->documentElement->namespaceURI
                ) {
                    return $node->nodeValue;
                }
            }
        }

        return null;
    }

public
function
getElementValue
(
$
element_name
,
$
reference_element
=
)
{
$
element_name
=
trim
(
$
element_name
)
;
if
(
empty
(
$
element_name
)
)
{
throw
new
\
InvalidArgumentException
(
'Element name must not be empty.'
)
;
}
if
(
===
$
reference_element
)
{
$
reference_element
=
$
this
->
documentElement
;
}
if
(
$
this
->
isEnvironautDocument
(
)
)
{
foreach
(
$
reference_element
->
childNodes
as
$
node
)
{
if
(
$
node
->
nodeType
==
XML_ELEMENT_NODE
&&
$
node
->
localName
==
$
element_name
&&
$
node
->
namespaceURI
==
$
this
->
documentElement
->
namespaceURI
)
{
return
$
node
->
nodeValue
;
}
}
}
return
;
}

Returns the nodeValue of the child element with the given name.

@param string $element_name name of child element
@param \DomElement $reference_element reference element for child node iteration, default to documentElement

@return mixed nodeValue or null if Environaut element with that name does not exist

@throws \InvalidArgumentException if name is empty

Returns the nodeValue of the child element with the given name .


public function getElement($name)
    {
        if ($this->isEnvironautDocument()) {
            foreach ($this->documentElement->childNodes as $node) {
                if ($node->nodeType == XML_ELEMENT_NODE &&
                    $node->localName == $name &&
                    $node->namespaceURI == $this->documentElement->namespaceURI
                ) {
                    return $node;
                }
            }
        }

        return null;
    }

public function getElement ( $ name ) { if ( $ this -> isEnvironautDocument ( ) ) { foreach ( $ this -> documentElement -> childNodes as $ node ) { if ( $ node -> nodeType == XML_ELEMENT_NODE && $ node -> localName == $ name && $ node -> namespaceURI == $ this -> documentElement -> namespaceURI ) { return $ node ; } } } return null ; }

Returns the DomElement with the given name.

@param string $name of the element to get

@return DomElement of that name or null if does not exist in the Environaut namespace

Returns the DomElement with the given name .


public function setDefaultNamespace($prefix = self::NAMESPACE_PREFIX, $uri = self::NAMESPACE_ENVIRONAUT_1_0)
    {
        $this->default_namespace_uri = $uri;
        $this->default_namespace_prefix = $prefix;

        $this->xpath->registerNamespace($prefix, $uri);
    }

public function setDefaultNamespace ( $ prefix = self :: NAMESPACE_PREFIX , $ uri = self :: NAMESPACE_ENVIRONAUT_1_0 ) { $ this -> default_namespace_uri = $ uri ; $ this -> default_namespace_prefix = $ prefix ; $ this -> xpath -> registerNamespace ( $ prefix , $ uri ) ; }

Set the default namespace that should be used when accessing elements via
convenience methods and bind it to the internal xpath instance.

@param string $prefix default prefix to use
@param string $uri namespace URI

Set the default namespace that should be used when accessing elements via convenience methods and bind it to the internal xpath instance .


public static function registerEnvironautNamespace(DOMDocument $doc)
    {
        $doc->getXpath()->registerNamespace(self::NAMESPACE_PREFIX, self::NAMESPACE_ENVIRONAUT_1_0);
    }

public static function registerEnvironautNamespace ( DOMDocument $ doc ) { $ doc -> getXpath ( ) -> registerNamespace ( self :: NAMESPACE_PREFIX , self :: NAMESPACE_ENVIRONAUT_1_0 ) ; }

Registers the default Environaut namespace on the internal xpath
instance of the given DomDocument instance.

@param DOMDocument $doc document instance

Registers the default Environaut namespace on the internal xpath instance of the given DomDocument instance .


public static function isEnvironautConfigurationDocument(DOMDocument $doc)
    {
        return (
            $doc->documentElement &&
            $doc->documentElement->localName === 'environaut' &&
            $doc->documentElement->namespaceURI === self::NAMESPACE_ENVIRONAUT_1_0
        );
    }

public static function isEnvironautConfigurationDocument ( DOMDocument $ doc ) { return ( $ doc -> documentElement && $ doc -> documentElement -> localName === 'environaut' && $ doc -> documentElement -> namespaceURI === self :: NAMESPACE_ENVIRONAUT_1_0 ) ; }

Returns whether the given document instance is an Environaut configuration file.

@param DOMDocument $doc document to check

@return bool true if it's an Environaut document; false otherwise

Returns whether the given document instance is an Environaut configuration file .


protected function refreshXpath()
    {
        unset($this->xpath);

        $this->xpath = new \DOMXPath($this);

        if ($this->isEnvironautDocument()) {
            $this->setDefaultNamespace(self::NAMESPACE_PREFIX, self::NAMESPACE_ENVIRONAUT_1_0);
        }
    }

protected function refreshXpath ( ) { unset ( $ this -> xpath ) ; $ this -> xpath = new \ DOMXPath ( $ this ) ; if ( $ this -> isEnvironautDocument ( ) ) { $ this -> setDefaultNamespace ( self :: NAMESPACE_PREFIX , self :: NAMESPACE_ENVIRONAUT_1_0 ) ; } }

Re-instantiates the internal xpath instance and then
registers the Environaut config namespace if necessary.

Re - instantiates the internal xpath instance and then registers the Environaut config namespace if necessary .


protected function parseError(\LibXMLError $error)
    {
        $msg = '';
        switch ($error->level) {
            case LIBXML_ERR_WARNING:
                $msg .= 'Warning ' . $error->code . ': ';
                break;
            case LIBXML_ERR_FATAL:
                $msg .= 'Fatal error: ' . $error->code . ': ';
                break;
            case LIBXML_ERR_ERROR:
            default:
                $msg .= 'Error ' . $error->code . ': ';
                break;
        }

        $msg .= trim($error->message) . PHP_EOL .
                '  Line: ' . $error->line . PHP_EOL .
                'Column: ' . $error->column;

        if ($error->file) {
            $msg .= PHP_EOL . '  File: ' . $error->file;
        }

        return $msg;
    }

protected
function
parseError
(
\
LibXMLError
$
error
)
{
$
msg
=
''
;
switch
(
$
error
->
level
)
{
case
LIBXML_ERR_WARNING
:
$
msg
.=
'Warning '
.
$
error
->
code
.
': '
;
break
;
case
LIBXML_ERR_FATAL
:
$
msg
.=
'Fatal error: '
.
$
error
->
code
.
': '
;
break
;
case
LIBXML_ERR_ERROR
:
default
:
$
msg
.=
'Error '
.
$
error
->
code
.
': '
;
break
;
}
$
msg
.=
trim
(
$
error
->
message
)
.
PHP_EOL
.
'  Line: '
.
$
error
->
line
.
PHP_EOL
.
'Column: '
.
$
error
->
column
;
if
(
$
error
->
file
)
{
$
msg
.=
PHP_EOL
.
'  File: '
.
$
error
->
file
;
}
return
$
msg
;
}

Formats the given libXml error as a multiline string.

@param \LibXMLError $error error to get as formatted string

@return string formatted error message

Formats the given libXml error as a multiline string .


public function getResolvers($subject)
    {
        $key = \is_object($subject) ? \get_class($subject) : \gettype($subject);

        if (\array_key_exists($key, $this->cache)) {
            return $this->cache[$key];
        }

        $this->cache[$key] = [];

        foreach ($this->resolvers as $resolver) {
            if ($resolver->canResolve($subject)) {
                $this->cache[$key][] = $resolver;
            }
        }

        return $this->cache[$key];
    }

public function getResolvers ( $ subject ) { $ key = \ is_object ( $ subject ) ? \ get_class ( $ subject ) : \ gettype ( $ subject ) ; if ( \ array_key_exists ( $ key , $ this -> cache ) ) { return $ this -> cache [ $ key ] ; } $ this -> cache [ $ key ] = [ ] ; foreach ( $ this -> resolvers as $ resolver ) { if ( $ resolver -> canResolve ( $ subject ) ) { $ this -> cache [ $ key ] [ ] = $ resolver ; } } return $ this -> cache [ $ key ] ; }

Get a sorted array of resolvers applicable to the input element.

@param mixed $subject
@return array<ExpressionResolverInterface>

Get a sorted array of resolvers applicable to the input element .


public function checkAuthorizeParams()
    {
        // Get required params
        $clientId = $this->server->getRequestHandler()->getParam('client_id');
        if (is_null($clientId)) {
            throw new Exception\InvalidRequestException('client_id');
        }

        $redirectUri = $this->server->getRequestHandler()->getParam('redirect_uri');
        if (is_null($redirectUri)) {
            throw new Exception\InvalidRequestException('redirect_uri');
        }

        // Validate client ID and redirect URI
        $client = $this->server->getClientStorage()->get(
            $clientId,
            null,
            $redirectUri,
            $this->getIdentifier()
        );

        if (($client instanceof ClientEntity) === false) {
            throw new Exception\InvalidClientException();
        }

        $state = $this->server->getRequestHandler()->getParam('state');
        if ($this->server->stateParamRequired() === true && is_null($state)) {
            throw new Exception\InvalidRequestException('state', $redirectUri);
        }

        $responseType = $this->server->getRequestHandler()->getParam('response_type');
        if (is_null($responseType)) {
            throw new Exception\InvalidRequestException('response_type', $redirectUri);
        }

        // Ensure response type is one that is recognised
        if (!in_array($responseType, $this->server->getResponseTypes())) {
            throw new Exception\UnsupportedResponseTypeException($responseType, $redirectUri);
        }

        // Validate any scopes that are in the request
        $scopeParam = $this->server->getRequestHandler()->getParam('scope');
        $scopes = $this->validateScopes($scopeParam, $client, $redirectUri);

        return array(
            'client'        => $client,
            'redirect_uri'  => $redirectUri,
            'state'         => $state,
            'response_type' => $responseType,
            'scopes'        => $scopes
		);
    }

Check authorize parameters

@return array Authorize request parameters

@throws


public function newAuthorizeRequest($type, $typeId, $authParams = [])
    {
        // Create a new session
        $session = new SessionEntity($this->server);
        $session->setOwner($type, $typeId);
        $session->associateClient($authParams['client']);

        // Create a new auth code
        $authCode = new AuthCodeEntity($this->server);
        $authCode->setId();
        $authCode->setRedirectUri($authParams['redirect_uri']);
        $authCode->setExpireTime(time() + $this->authTokenTTL);

        foreach ($authParams['scopes'] as $scope) {
            $authCode->associateScope($scope);
            $session->associateScope($scope);
        }

        $session->save();
        $authCode->setSession($session);
        $authCode->save();

        return $authCode->generateRedirectUri($authParams['state']);
    }

public
function
newAuthorizeRequest
(
$
type
,
$
typeId
,
$
authParams
=
[
]
)
{
// Create a new session
$
session
=
new
SessionEntity
(
$
this
->
server
)
;
$
session
->
setOwner
(
$
type
,
$
typeId
)
;
$
session
->
associateClient
(
$
authParams
[
'client'
]
)
;
// Create a new auth code
$
authCode
=
new
AuthCodeEntity
(
$
this
->
server
)
;
$
authCode
->
setId
(
)
;
$
authCode
->
setRedirectUri
(
$
authParams
[
'redirect_uri'
]
)
;
$
authCode
->
setExpireTime
(
time
(
)
+
$
this
->
authTokenTTL
)
;
foreach
(
$
authParams
[
'scopes'
]
as
$
scope
)
{
$
authCode
->
associateScope
(
$
scope
)
;
$
session
->
associateScope
(
$
scope
)
;
}
$
session
->
save
(
)
;
$
authCode
->
setSession
(
$
session
)
;
$
authCode
->
save
(
)
;
return
$
authCode
->
generateRedirectUri
(
$
authParams
[
'state'
]
)
;
}

Parse a new authorize request

@param string $type       The session owner's type
@param string $typeId     The session owner's ID
@param array  $authParams The authorize request $_GET parameters

@return string An authorisation code


public function completeFlow(ClientEntity $client)
    {
        // Validate the auth code
        $authCode = $this->server->getRequestHandler()->getParam('code');
        if (is_null($authCode)) {
            throw new Exception\InvalidRequestException('code');
        }

        $code = $this->server->getAuthCodeStorage()->get($authCode);
        if (($code instanceof AuthCodeEntity) === false) {
            throw new Exception\InvalidRequestException('code');
        }

        // Ensure the auth code hasn't expired
        if ($code->isExpired() === true) {
            throw new Exception\InvalidRequestException('code');
        }

        // Check redirect URI presented matches redirect URI originally used in authorize request
        if ($code->getRedirectUri() !== $client->getRedirectUri()) {
            throw new Exception\InvalidRequestException('redirect_uri');
        }

        $session = $code->getSession();
        $session->associateClient($client);

        $authCodeScopes = $code->getScopes();

        // Generate the access token
        $accessToken = new AccessTokenEntity($this->server);
        $accessToken->setId();
        $accessToken->setExpireTime($this->getAccessTokenTTL() + time());

        foreach ($authCodeScopes as $authCodeScope) {
            $session->associateScope($authCodeScope);
        }

        foreach ($session->getScopes() as $scope) {
            $accessToken->associateScope($scope);
        }

        $this->server->getTokenType()->setSession($session);
        $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
        $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());

        // Associate a refresh token if set
        if ($this->server->hasGrantType('refresh_token')) {
            $refreshToken = new RefreshTokenEntity($this->server);
            $refreshToken->setId();
            $refreshToken->setExpireTime($this->server->getGrantType('refresh_token')->getRefreshTokenTTL() + time());
            $this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId());
        }

        // Expire the auth code
        $code->expire();

        // Save all the things
        $accessToken->setSession($session);
        $accessToken->save();

        if (isset($refreshToken) && $this->server->hasGrantType('refresh_token')) {
            $refreshToken->setAccessToken($accessToken);
            $refreshToken->save();
        }

        return $this->server->getTokenType()->generateResponse();
    }

Complete the auth code grant

@return array

@throws


public function printOutput()
    {
        if ($this->isRpc == true) {
            return $this->printJSONOuput();
        }
        foreach ($this->_otherOutput as $output) {
            print $output;
        }
        foreach ($this->_formsOutput as $output) {
            print $output;
        }
    }

public function printOutput ( ) { if ( $ this -> isRpc == true ) { return $ this -> printJSONOuput ( ) ; } foreach ( $ this -> _otherOutput as $ output ) { print $ output ; } foreach ( $ this -> _formsOutput as $ output ) { print $ output ; } }


public function getFormInputs($controlName = null, $toString = TRUE)
    {
        if ($controlName) {
            if (isset($_GET[$controlName])) {
                $_POST[$controlName] = $_GET[$controlName];
            }
            if (isset($_POST[$controlName])) {
                if (is_array($_POST[$controlName]) and $toString == TRUE) {
                    $array_string = '';
                    foreach ($_POST[$controlName] as $rec) {
                        $array_string .= $rec . ",";
                    }
                    $result = substr($array_string, 0, strlen($array_string) - 1);
                } else {
                    $result = $_POST[$controlName];
                }
                if (get_magic_quotes_gpc() == 1) {
                    if (!is_array($result)) {
                        $result = stripslashes($result);
                    }
                }
                return $result;
            } else {
                if (isset($_FILES[$controlName])) {
                    $result = true;
                    return $result;
                } else {
                    return null;
                }
            }
        } else {
            return $_POST;
        }
    }

public function getFormInputs ( $ controlName = null , $ toString = TRUE ) { if ( $ controlName ) { if ( isset ( $ _GET [ $ controlName ] ) ) { $ _POST [ $ controlName ] = $ _GET [ $ controlName ] ; } if ( isset ( $ _POST [ $ controlName ] ) ) { if ( is_array ( $ _POST [ $ controlName ] ) and $ toString == TRUE ) { $ array_string = '' ; foreach ( $ _POST [ $ controlName ] as $ rec ) { $ array_string .= $ rec . "," ; } $ result = substr ( $ array_string , 0 , strlen ( $ array_string ) - 1 ) ; } else { $ result = $ _POST [ $ controlName ] ; } if ( get_magic_quotes_gpc ( ) == 1 ) { if ( ! is_array ( $ result ) ) { $ result = stripslashes ( $ result ) ; } } return $ result ; } else { if ( isset ( $ _FILES [ $ controlName ] ) ) { $ result = true ; return $ result ; } else { return null ; } } } else { return $ _POST ; } }

Get form all inputs or one input if controlName is given

@param string $controlName
@param boolean $toString - Convert array oriented form controls to string?
@return array|string


public function redrawForm($formName, $sHTML)
    {
        if ($this->isRpc) {
            $this->_formsOutput[$formName] = $this->buildTargetContent($formName, $sHTML);
        } else {
            $this->_formsOutput[$formName] = $sHTML;
        }
    }

public function redrawForm ( $ formName , $ sHTML ) { if ( $ this -> isRpc ) { $ this -> _formsOutput [ $ formName ] = $ this -> buildTargetContent ( $ formName , $ sHTML ) ; } else { $ this -> _formsOutput [ $ formName ] = $ sHTML ; } }

Replace the form content with the provided html text,
encoded html string returns to browser,
it'll be processed by client javascript.

@param string $formName - name of the html form on client
@param string $sHTML - html text to redraw the form
@return void

Replace the form content with the provided html text encoded html string returns to browser it ll be processed by client javascript .


public function showClientAlert($alertText)
    {
        if ($this->isRpc) {
            $msg = addslashes($alertText);
            $this->_otherOutput[] = $this->callClientFunction("alert('" . $msg . "')");
        }
    }

public function showClientAlert ( $ alertText ) { if ( $ this -> isRpc ) { $ msg = addslashes ( $ alertText ) ; $ this -> _otherOutput [ ] = $ this -> callClientFunction ( "alert('" . $ msg . "')" ) ; } }

Show popup an alert window on the client browser.
Encoded html string returns to browser, it'll be processed by client javascript.

@param string $alertText
@return void

Show popup an alert window on the client browser . Encoded html string returns to browser it ll be processed by client javascript .


public function showErrorMessage($errMsg)
    {
        if (!$errMsg) {
            return;
        }
        if ($this->isRpc) {
            $_GET['ob_err_msg'] = $errMsg;
            ob_end_clean();
            $form = "common.form.ErrorPopupForm";
            $html = Openbizx::getObject($form)->render();
            $html = $this->buildTargetContent("DIALOG", $html);
            $this->_formsOutput[] = $html;
        } else {
            $this->_errorOutput($errMsg);
        }
    }

public function showErrorMessage ( $ errMsg ) { if ( ! $ errMsg ) { return ; } if ( $ this -> isRpc ) { $ _GET [ 'ob_err_msg' ] = $ errMsg ; ob_end_clean ( ) ; $ form = "common.form.ErrorPopupForm" ; $ html = Openbizx :: getObject ( $ form ) -> render ( ) ; $ html = $ this -> buildTargetContent ( "DIALOG" , $ html ) ; $ this -> _formsOutput [ ] = $ html ; } else { $ this -> _errorOutput ( $ errMsg ) ; } }

Show error message.

If its a remote call, it uses javascript
If it is not a remote call, it outputs to the page's html

@todo Hard code for error form : "common.form.ErrorPopupForm"
change to flexible ErrorPopupForm, save in Class variable and maybe also in configuration

@param char $errMsg
@return void


public function closePopup()
    {
        if ($this->isRpc) {
            $this->_formsOutput[] = $this->callClientFunction("Openbizx.Window.closePopup()");
            $this->_otherOutput[] = $this->callClientFunction("Openbizx.Window.closePopup()");
        }
    }

public function closePopup ( ) { if ( $ this -> isRpc ) { $ this -> _formsOutput [ ] = $ this -> callClientFunction ( "Openbizx.Window.closePopup()" ) ; $ this -> _otherOutput [ ] = $ this -> callClientFunction ( "Openbizx.Window.closePopup()" ) ; } }


public function runClientScript($scriptStr)
    {
        if ($this->isRpc) {
            $this->_otherOutput[] = $this->buildTargetContent("SCRIPT", $scriptStr);
        } else {
            echo $scriptStr;
        }
    }

public function runClientScript ( $ scriptStr ) { if ( $ this -> isRpc ) { $ this -> _otherOutput [ ] = $ this -> buildTargetContent ( "SCRIPT" , $ scriptStr ) ; } else { echo $ scriptStr ; } }

Run client script

@param string $scriptStr
@return void


public function redirectView($view, $rule = null)
    {
        // get the view url form view name
        $viewParts = explode('.', $view);
        $viewMod = $viewParts[0];
        $viewName = $viewParts[count($viewParts) - 1];
        $viewName = strtolower(str_replace("View", "", $viewName));
        $url = OPENBIZ_APP_INDEX_URL . "/$viewMod/$viewName";
        $this->redirectPage($url);
        $this->printOutput();
        //Openbizx::$app->getClientProxy()->printOutput();
    }

Redirect page to the given view.
Encoded html string returns to browser, it'll be processed by client javascript.

@param string $view full name of view (with package)
@param string $rule
@return void

Redirect page to the given view . Encoded html string returns to browser it ll be processed by client javascript .


public function appendScripts($scriptKey, $scripts, $isFile = true)
    {
        // if has the script key already, ignore
        if (isset($this->_extraScripts[$scriptKey])) {
            return;
        }
        // add the scripts
        if ($isFile) {
            $_scripts = "<script type='text/javascript' src=\"" . Openbizx::$app->getJsUrl() . "/$scripts\"></script>";
            $this->_extraScripts[$scriptKey] = $_scripts;
        } else {
            $this->_extraScripts[$scriptKey] = $scripts;
        }
    }

Append more scripts - js include, js code

@param mixed $scriptKey
@param string $scripts
@param boolean $isFile
@return void

Append more scripts - js include js code


public function getAppendedScripts()
    {
        $currentView = Openbizx::$app->getCurrentViewName();
        $initScripts = "<script>var APP_URL='" . OPENBIZ_APP_URL . "'; var APP_CONTROLLER='" . OPENBIZ_APP_URL . "/bin/controller.php';</script>\n";
        $initScripts .= "<script>var APP_VIEWNAME='" . $currentView . "';</script>\n";
        $extraScripts = implode("", $this->_extraScripts);
        $extraScript_array = explode("</script>", $extraScripts);
        /* if (defined("OPENBIZ_RESOURCE_PHP")) {
          $js_scripts = OPENBIZ_RESOURCE_PHP."?f=";
          foreach ($extraScript_array as $script)
          {
          // extract src part from each line
          if (preg_match('/.+src="([^"]+)".+/', $script, $matches) > 0 && !empty($matches[1])) {
          if (substr($js_scripts, -2)=='f=') $js_scripts .= $matches[1];
          else $js_scripts .= ','.$matches[1];
          }
          }
          return $initScripts."<script type=\"text/javascript\" src=\"".$js_scripts."\"></script>";
          } */
        $cleanScript_array = array();
        foreach ($extraScript_array as $script) {
            if (in_array($script . "</script>", $cleanScript_array) == FALSE and strlen($script) != 0) {
                $cleanScript_array[] = $script . "</script>";
            }
        }
        return $initScripts . implode("\n", $cleanScript_array);
    }


public function appendStyles($scriptKey, $styles, $isFile = true)
    {
        // if has the script key already, ignore
        if (isset($this->_extraStyles[$scriptKey])) {
            return;
        }
        // add the styles
        $css = Openbizx::$app->getCssUrl();
        if ($isFile) {
            $_styles = "<link rel=\"stylesheet\" href=\"$css/" . $styles . "\" type=\"text/css\">";
            $this->_extraStyles[$scriptKey] = $_styles;
        } else {
            $this->_extraStyles[$scriptKey] = $styles;
        }
    }

Append more styles - include and sections

@param <type> $scriptKey
@param string $styles
@param boolean $isFile
@return void


public function getAppendedStyles($comb = 0)
    {
        $extraStyles = implode("", $this->_extraStyles);
        $extraStyle_array = explode("type=\"text/css\">", $extraStyles);
        if (defined("OPENBIZ_RESOURCE_PHP") && $comb) {
            $css_scripts = OPENBIZ_RESOURCE_PHP . "?f=";
            $matches = array();
            foreach ($extraStyle_array as $style) {
                // extract href part from each line
                if (preg_match('/.+href="([^"]+)".+/', $style, $matches) > 0 && !empty($matches[1])) {
                    if (substr($css_scripts, -2) == 'f=') {
                        $css_scripts .= $matches[1];
                    } else {
                        $css_scripts .= ',' . $matches[1];
                    }
                }
            }
            return "<link rel=\"stylesheet\" href=\"" . $css_scripts . "\" type=\"text/css\"/>";
        }
        $cleanStyle_array = array();
        foreach ($extraStyle_array as $style) {
            if (in_array($style . "type=\"text/css\">", $cleanStyle_array) == FALSE and strlen($style) != 0) {
                $cleanStyle_array[] = $style . "type=\"text/css\">";
            }
        }
        $lang = I18n::getCurrentLangCode();
        $localization_css_file = OPENBIZ_APP_PATH . DIRECTORY_SEPARATOR
                . "languages" . DIRECTORY_SEPARATOR
                . $lang . DIRECTORY_SEPARATOR . "localization.css";
        if (is_file($localization_css_file)) {
            $cleanStyle_array[] = "<link rel=\"stylesheet\" href=\"" . OPENBIZ_APP_URL . "/languages/$lang/localization.css\" type=\"text/css\">";
        }
        return implode("\n", $cleanStyle_array);
    }


public function includeBaseClientScripts()
    {
        if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
            Openbizx::$app->getClientProxy()->appendScripts("jquery", "jquery.js");
            Openbizx::$app->getClientProxy()->appendScripts("jquery_class", "jquery.class.js");
            Openbizx::$app->getClientProxy()->appendScripts("jquery_dollarj", "<script>try{var \$j=\$;}catch(e){}</script>", false);
            Openbizx::$app->getClientProxy()->appendStyles("default", "openbiz.css");
            if (DeviceUtil::$PHONE_TOUCH) {
                Openbizx::$app->getClientProxy()->appendScripts("openbiz", "openbiz.mobile.js");
                Openbizx::$app->getClientProxy()->appendScripts("jquery_mobile", "jqm/jquery.mobile-1.0.js");
                $style = "<link rel=\"stylesheet\" href=\"" . Openbizx::$app->getJsUrl() . "/jqm/jquery.mobile-1.0.css\" type=\"text/css\">";
                Openbizx::$app->getClientProxy()->appendStyles("jquery_mobile_css", $style, false);
            } else {
                Openbizx::$app->getClientProxy()->appendScripts("openbiz", "openbiz.js");
                Openbizx::$app->getClientProxy()->appendScripts("jquery_ui", "jquery-ui-1.8.16.custom.min.js");
                $style = "<link rel=\"stylesheet\" href=\"" . Openbizx::$app->getJsUrl() . "/jquery-ui/ui-lightness/jquery-ui-1.8.16.custom.css\" type=\"text/css\">";
                $style .= "<link rel=\"stylesheet\" href=\"" . Openbizx::$app->getJsUrl() . "/jquery-ui/ui-openbiz/jquery.css\" type=\"text/css\">";
                Openbizx::$app->getClientProxy()->appendStyles("jquery_ui_css", $style, false);
            }
            return;
        }
        // prototype is still the default js lib
        Openbizx::$app->getClientProxy()->appendScripts("prototype", "prototype.js");
        Openbizx::$app->getClientProxy()->appendScripts("scriptaculous", "scriptaculous.js");
        Openbizx::$app->getClientProxy()->appendScripts("effects", "effects.js");
        Openbizx::$app->getClientProxy()->appendScripts("controls", "controls.js");
        Openbizx::$app->getClientProxy()->appendScripts("cookies", "cookies.js");
        Openbizx::$app->getClientProxy()->appendScripts("openbiz", "openbiz.js");
        Openbizx::$app->getClientProxy()->appendStyles("default", "openbiz.css");
        // window lib
        Openbizx::$app->getClientProxy()->includePropWindowScripts();
        // validator lib
        //Openbizx::$app->getClientProxy()->includeValidatorScripts();
    }

Include base client library scripts

@return void


public function includeRTEScripts()
    {
        if (isset($this->_extraScripts['rte'])) {
            return;
        }
        $script = "<script type=\"text/javascript\" src=\"" . Openbizx::$app->getJsUrl() . "/richtext.js\"></script>";
        $script .= "<script language=\"JavaScript\">initRTE('" . Openbizx::$app->getImageUrl() . "/rte/', '../pages/rte/', '', false);</script>";
        $this->appendScripts("rte", $script, false);
    }


public function includeCKEditorScripts()
    {
        if (isset($this->_extraScripts['ckeditor'])) {
            return;
        }

        $script = "<script type=\"text/javascript\" src=\"" . Openbizx::$app->getJsUrl() . "/ckeditor/ckeditor.js\"></script>";

        $this->appendScripts("ckeditor", $script, false);
    }


public function includePropWindowScripts()
    {
        $this->appendScripts("scriptaculous", "scriptaculous.js");
        $this->appendScripts("prop_window", "window.js");
        $style = "<link rel=\"stylesheet\" href=\"" . Openbizx::$app->getJsUrl() . "/window/default.css\" type=\"text/css\">";
        //$style .= "<link rel=\"stylesheet\" href=\"".Openbizx::$app->getJsUrl()."/window/spread.css\" type=\"text/css\">";
        //$style .= "<link rel=\"stylesheet\" href=\"".Openbizx::$app->getJsUrl()."/window/lighting.css\" type=\"text/css\">";
        $this->appendStyles("prop_window", $style, false);
    }

Include PropWindow scripts

@return void


public function includeValidatorScripts()
    {
        $this->appendScripts("yav", "yav/yav.js");
        $this->appendScripts("yav-cfg", "yav/yav-config.js");
        //$this->appendScripts("validator", "validator.js");
        $style = "<link rel=\"stylesheet\" href=\"" . Openbizx::$app->getCssUrl() . "/validator.css\" type=\"text/css\">";
        $this->appendStyles("yav", $style, false);
    }


protected function executeAllActions($doTrigger, $dataObj)
    {
        if (!$this->matchCondition($doTrigger, $dataObj))
            return;
        /* @var $triggerAction TriggerAction */
        foreach ($doTrigger->triggerActions as $triggerAction) {
            $this->executeAction($triggerAction, $dataObj);
        }
    }

protected
function
executeAllActions
(
$
doTrigger
,
$
dataObj
)
{
if
(
!
$
this
->
matchCondition
(
$
doTrigger
,
$
dataObj
)
)
return
;
/* @var $triggerAction TriggerAction */
foreach
(
$
doTrigger
->
triggerActions
as
$
triggerAction
)
{
$
this
->
executeAction
(
$
triggerAction
,
$
dataObj
)
;
}
}

Execute all action

@param DOTrigger $doTrigger
@param BizDataObj $dataObj
@return void


private function _composeActionMessage($triggerAction, $methodName, $argList)
    {
        $actionMsg["Method"] = $methodName;
        $actionMsg["ArgList"] = $argList;
        $actionMsg["DelayMinutes"] = $triggerAction->delayMinutes;
        $actionMsg["RepeatMinutes"] = $triggerAction->repeatMinutes;
        $actionMsg["StartTime"] = strftime("%Y-%m-%d %H:%M:%S");
    }

private
function
_composeActionMessage
(
$
triggerAction
,
$
methodName
,
$
argList
)
{
$
actionMsg
[
"Method"
]
=
$
methodName
;
$
actionMsg
[
"ArgList"
]
=
$
argList
;
$
actionMsg
[
"DelayMinutes"
]
=
$
triggerAction
->
delayMinutes
;
$
actionMsg
[
"RepeatMinutes"
]
=
$
triggerAction
->
repeatMinutes
;
$
actionMsg
[
"StartTime"
]
=
strftime
(
"%Y-%m-%d %H:%M:%S"
)
;
}

Compose action message

@param TriggerAction $triggerAction
@param string $methodName
@param array $argList
@return void


static private function _makeArray($string)
    {
        if (!$string)
            return null;
        $arr = explode(";", $string);
        $size = count($arr);
        for ($i = 0; $i < $size; $i ++)
            $arr[$i] = trim($arr[$i]);
        return $arr;
    }

static private function _makeArray ( $ string ) { if ( ! $ string ) return null ; $ arr = explode ( ";" , $ string ) ; $ size = count ( $ arr ) ; for ( $ i = 0 ; $ i < $ size ; $ i ++ ) $ arr [ $ i ] = trim ( $ arr [ $ i ] ) ; return $ arr ; }

Make array from string with semi colon delimited

@param string $string string with ";" (semi colon) delimited
@return array


public function processFormObjError($errors)
    {
        $this->errors = $errors;
        $this->hasError = true;
        return $this->rerender();
    }

public function processFormObjError ( $ errors ) { $ this -> errors = $ errors ; $ this -> hasError = true ; return $ this -> rerender ( ) ; }

Process error of form object

@param array $errors
@return string - HTML text of this form's read mode


final public function setSubForms($subForms)
    {
        // sub controls string with format: ctrl1;ctrl2...
        if (!$subForms || strlen($subForms) < 1) {
            $this->subForms = null;
            return;
        }
        $subFormArr = explode(";", $subForms);
        unset($this->subForms);
        foreach ($subFormArr as $subForm) {
            $this->subForms[] = $this->prefixPackage($subForm);
        }
    }

Set the sub forms of this form. This form is parent of other forms

@param string $subForms - sub controls string with format: ctrl1;ctrl2...
@return void

Set the sub forms of this form . This form is parent of other forms


public function loadPicker($formName, $elementName = "")
    {
        // set the ParentFormName and ParentCtrlName of the popup form
        /* @var $pickerForm EasyForm */
        $pickerForm = Openbizx::getObject($formName);

        if ($elementName != "") {
            // set the picker map as well
            $element = $this->getElement($elementName);
            $pickerMap = $element->pickerMap;
        }
        $currentRecord = $this->readInputRecord();
        $pickerForm->setParentForm($this->objectName);
        $pickerForm->setParentFormData($this->objectName, $elementName, $pickerMap);
        $pickerForm->parentFormRecord = $currentRecord;
        Openbizx::$app->getClientProxy()->redrawForm("DIALOG", $pickerForm->render());
    }

Popup a selection EasyForm in a dynamically generated WebPage

@param string $viewName
@param string $formName
@param string $elementName
@return void
@access remote


public function setRequestParams($paramFields)
    {
        if ($paramFields) {
            $this->fixSearchRule = null; // reset fixsearchrule to clean the previous one in session
            foreach ($paramFields as $fieldName => $val) {
                $element = $this->dataPanel->getByField($fieldName);
                if ($element->allowURLParam == 'Y') {
                    if (!$this->getDataObj()) {
                        return;
                    }
                    if ($this->getDataObj()->getField($fieldName)) {
                        if ($this->getDataObj()->getField($fieldName)->checkValueType($val)) {
                            //echo __METHOD__.__LINE__.'<br />';
                            $this->setFixSearchRule("[$fieldName]='$val'");
                        }
                    }
                }
            }
        }
    }

Set request parameters

@param array $paramFields
@return void


public function fetchDataSet()
    {
        $dataObj = $this->getDataObj();

        if (!$dataObj) {
            return null;
        }

        if ($this->isRefreshData) {
            $dataObj->resetRules();
        } else {
            $dataObj->clearSearchRule();
        }

        if ($this->fixSearchRule) {
            if ($this->searchRule) {
                $searchRule = $this->searchRule . " AND " . $this->fixSearchRule;
            } else {
                $searchRule = $this->fixSearchRule;
            }
        } else {
            $searchRule = $this->searchRule;
        }

        $dataObj->setQueryParameters($this->queryParams);
        $dataObj->setSearchRule($searchRule);
        if ($this->startItem > 1) {
            $dataObj->setLimit($this->range, $this->startItem);
        } else {
            $dataObj->setLimit($this->range, ($this->currentPage - 1) * $this->range);
        }
        if ($this->sortRule && $this->sortRule != $this->getDataObj()->sortRule) {
            $dataObj->setSortRule($this->sortRule);
        }
        $resultRecords = $dataObj->fetch();
        $this->totalRecords = $dataObj->count();
        if ($this->range && $this->range > 0) {
            $this->totalPages = ceil($this->totalRecords / $this->range);
        }
        $selectedIndex = 0;

        //if current page is large than total pages ,then reset current page to last page
        if ($this->currentPage > $this->totalPages && $this->totalPages > 0) {
            $this->currentPage = $this->totalPages;
            $dataObj->setLimit($this->range, ($this->currentPage - 1) * $this->range);
            $resultRecords = $dataObj->fetch();
        }

        $this->getDataObj()->setActiveRecord($resultRecords[$selectedIndex]);

        if (!$this->recordId) {
            $this->recordId = $resultRecords[0]["Id"];
        } else {
            $foundRecordId = false;
            foreach ($resultRecords as $record) {
                if ($this->recordId == $record['Id']) {
                    $foundRecordId = true;
                }
            }
            if ($foundRecordId == false) {
                $this->recordId = $result[0]['Id'];
            }
        }

        return $resultRecords;
    }

Fetch record set

@return array array of record


public function getElementID()
    {
        $id = $this->dataPanel->getByField('Id')->getValue();
        if ($id) {
            return (int) $id;
        } else {
            return (int) $this->recordId;
        }
    }

public function getElementID ( ) { $ id = $ this -> dataPanel -> getByField ( 'Id' ) -> getValue ( ) ; if ( $ id ) { return ( int ) $ id ; } else { return ( int ) $ this -> recordId ; } }


public function autoSuggest($input)
    {
        if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
            $value = $_GET["term"];
            // get the select from list of the element
            $element = $this->getElement($input);
            $element->setValue($value);
            $fromlist = array();
            $element->getFromList($fromlist);
            $arr = array();
            $i = 0;
            foreach ($fromlist as $item) {
                $arr[$i++] = array('label' => $item['txt'], 'value' => $item['val']);
            }
            echo json_encode($arr);
            return;
        }
        $foo = $_POST;
        $hidden_flag = FALSE;
        if (strpos($input, '_hidden')) {
            $realInput = str_replace('_hidden', '', $input);
            $hidden_flag = TRUE;
        } else {
            $realInput = $input;
        }

        $value = Openbizx::$app->getClientProxy()->getFormInputs($input);

        // get the select from list of the element
        $element = $this->getElement($realInput);
        $element->setValue($value);
        $fromlist = array();
        $element->getFromList($fromlist);
        echo "
";
        if ($fromlist) {
            if ($hidden_flag = TRUE) {
                $count = 0;
                foreach ($fromlist as $item) {
                    echo "
" . $item['val'] . "
";
                    $count++;
                    if ($count >= 5)
                        break;
                }
            }
            else {
                $count = 0;
                foreach ($fromlist as $item) {
                    echo "
" . $item['txt'] . "
";
                    $count++;
                    if ($count >= 5)
                        break;
                }
            }
        }
        echo "
";
    }

Generate list for AutoSuggest element
Also supports elements that have hidden values

@param string $input - the search string used to filter the list
@todo rename to createAutoSuggestList or createAutoSuggest(v2.5?)
@return void


protected function renderContextMenu()
    {
        $menuList = array();
        foreach ($this->panels as $panel) {
            $panel->rewind();
            while ($element = $panel->current()) {
                $panel->next();
                if (method_exists($element, 'getContextMenu') && $menus = $element->getContextMenu()) {
                    foreach ($menus as $m)
                        $menuList[] = $m;
                }
            }
        }
        if (count($menuList) == 0)
            return "";
        $str = "
objectName . "_contextmenu'>\n";
        $str .= "

\n";
        $str .= "
\n";
        foreach ($menuList as $m) {
            $func = $m['func'];
            $shortcutKey = isset($m['key']) ? " (" . $m['key'] . ")" : "";
            $str .= "
" . $m['text'] . $shortcutKey . "
\n";
        }
        $str .= "
\n";
        $str .= "

\n";
        $str .= "
\n";
        if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
            $str .= "
";
        } else {
            $str .= "
";
        }
        return $str;
    }

Render context menu code

@return string html code for context menu


protected function renderHTML()
    {
        $formHTML = FormRenderer::render($this);
        $otherHTML = $this->rendercontextmenu();

        if (preg_match('/iPad/si', $_SERVER['HTTP_USER_AGENT']) ||
                preg_match('/iPhone/si', $_SERVER['HTTP_USER_AGENT'])) {
            $otherHTML.="
        		<script>
				var a=document.getElementsByTagName('a');
				for(var i=0;i<a.length;i++)
				{
					if(a[i].getAttribute('href').indexOf('javascript:')==-1
					&& a[i].getAttribute('href').indexOf('#')==-1)
						{
						    a[i].onclick=function()
						    {
							    try{
						    		show_loader();
						    	}catch(e){

						    	}
						        window.location=this.getAttribute('href');
						        return false
						    }
						}else{
						}
				}
				</script>
        		";
        }
        if (!$this->parentFormName) {
            if (($viewObj = $this->getWebpageObject()) != null)
                $viewObj->lastRenderedForm = $this->objectName;
        }
        return $formHTML . "\n" . $otherHTML;
    }

Render html content of this form

@return string - HTML text of this form's read mode


protected function getEventLogMsg()
    {
        list($element, $eventHandler) = $this->getInvokingElement();
        $eventLogMsg = $eventHandler->eventLogMsg;
        if ($eventLogMsg) {
            return $eventLogMsg;
        } else {
            return null;
        }
    }

protected function getEventLogMsg ( ) { list ( $ element , $ eventHandler ) = $ this -> getInvokingElement ( ) ; $ eventLogMsg = $ eventHandler -> eventLogMsg ; if ( $ eventLogMsg ) { return $ eventLogMsg ; } else { return null ; } }

Get event log message

@return mixed string or null


protected function getOnEventElements()
    {
        $elementList = array();
        foreach ($this->dataPanel as $element) {
            if ($element->onEventLog == "Y")
                $elementList[] = $element->value;
        }
        return $elementList;
    }

protected function getOnEventElements ( ) { $ elementList = array ( ) ; foreach ( $ this -> dataPanel as $ element ) { if ( $ element -> onEventLog == "Y" ) $ elementList [ ] = $ element -> value ; } return $ elementList ; }

Get on event elements

@return array element list


protected function runEventLog()
    {
        $logMessage = $this->getEventLogMsg();
        $eventName = $this->eventName;
        if ($logMessage && $eventName) {
            $logElements = $this->getOnEventElements();
            $eventlog = Openbizx::getService(OPENBIZ_EVENTLOG_SERVICE);
            $eventlog->log($eventName, $logMessage, $logElements);
        }
    }

protected function runEventLog ( ) { $ logMessage = $ this -> getEventLogMsg ( ) ; $ eventName = $ this -> eventName ; if ( $ logMessage && $ eventName ) { $ logElements = $ this -> getOnEventElements ( ) ; $ eventlog = Openbizx :: getService ( OPENBIZ_EVENTLOG_SERVICE ) ; $ eventlog -> log ( $ eventName , $ logMessage , $ logElements ) ; } }


protected function getInvokingElement()
    {
        if ($this->invokingElement)
            return $this->invokingElement;
        // __this is elementName:eventHandlerName
        $elementAndEventName = Openbizx::$app->getClientProxy()->getFormInputs("__this");
        if (!$elementAndEventName)
            return array(null, null);
        list ($elementName, $eventHandlerName) = explode(":", $elementAndEventName);
        $element = $this->getElement($elementName);
        $eventHandler = $element->eventHandlers->get($eventHandlerName);
        $this->invokingElement = array($element, $eventHandler);
        return $this->invokingElement;
    }

Get the element that issues the call.

@return array element object and event handler name


protected function setClientScripts()
    {
        // load custom js class
        if ($this->jsClass != "Openbizx.Form" && $this->jsClass != "Openbizx.TableForm" && $this->jsClass != "")
            Openbizx::$app->getClientProxy()->appendScripts($this->jsClass, $this->jsClass . ".js");
        /*
          if ($this->formType == 'LIST')
          {
          Openbizx::$app->getClientProxy()->appendScripts("tablekit", "tablekit.js");
          } */
    }

Set client scripts, auto add javascripts code to the page

@return void

Set client scripts auto add javascripts code to the page


public function remove(string $middlewareClass): void
    {
        foreach( $this->middlewareStack as $i => $middleware ){
            if( $middleware instanceof $middlewareClass ){
                unset($this->middlewareStack[$i]);
            }
        }
    }

public function remove ( string $ middlewareClass ) : void { foreach ( $ this -> middlewareStack as $ i => $ middleware ) { if ( $ middleware instanceof $ middlewareClass ) { unset ( $ this -> middlewareStack [ $ i ] ) ; } } }

Remove a layer by its classname.

@param string $middlewareClass


public function run(Request $request, callable $kernel): Response
    {
        $next = array_reduce(array_reverse($this->middlewareStack), function(callable $next, MiddlewareLayerInterface $layer): \Closure {

            return function(Request $request) use ($next, $layer): Response {
                return $layer->handle($request, $next);
            };

        }, function(Request $request) use ($kernel): Response {
            return $kernel($request);
        });

        return $next($request);
    }

public function run ( Request $ request , callable $ kernel ) : Response { $ next = array_reduce ( array_reverse ( $ this -> middlewareStack ) , function ( callable $ next , MiddlewareLayerInterface $ layer ) : \ Closure { return function ( Request $ request ) use ( $ next , $ layer ) : Response { return $ layer -> handle ( $ request , $ next ) ; } ; } , function ( Request $ request ) use ( $ kernel ) : Response { return $ kernel ( $ request ) ; } ) ; return $ next ( $ request ) ; }

Run the middleware stack.

@param Request $request
@param callable $kernel
@return Response


public static function createFromString(string $interval): self
	{
		list($from, $to) = explode(self::$delimiter, $interval);

		$dateFrom = DateTime::createFromFormat(self::$format, $from);
		$dateTo = DateTime::createFromFormat(self::$format, $to);

		return new self($dateFrom, $dateTo);
	}

public static function createFromString ( string $ interval ) : self { list ( $ from , $ to ) = explode ( self :: $ delimiter , $ interval ) ; $ dateFrom = DateTime :: createFromFormat ( self :: $ format , $ from ) ; $ dateTo = DateTime :: createFromFormat ( self :: $ format , $ to ) ; return new self ( $ dateFrom , $ dateTo ) ; }

Vytvori objekt z retezce intervalu
@param string $interval
@return self


public static function generate($stamp, $key)
    {
        $key = self::base32_decode($key);
        if (strlen($key) < 8) {
            throw new TooShortKeyException('Secret key is too short. Must be at least 16 base 32 characters');
        }

        $bin_counter = pack('N*', 0).pack('N*', $stamp);        // Stamp must be 64-bit int
        $hash = hash_hmac('sha1', $bin_counter, $key, true);

        return str_pad(self::oath_truncate($hash), 6, '0', STR_PAD_LEFT);
    }

Generates a TOTP code.

@param int    $stamp Unit time
@param string $key   TOTP key

@return string TOTP corresponding to the key and stamp provided


protected static function base32_decode($b32)
    {
        $b32 = strtoupper($b32);

        if (!preg_match('/^[ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]+$/', $b32, $match)) {
            throw new Exception('Invalid characters in the base32 string.');
        }

        $l = strlen($b32);
        $n = 0;
        $j = 0;
        $binary = '';

        for ($i = 0; $i < $l; ++$i) {
            $n = $n << 5;                    // Move buffer left by 5 to make room
            $n = $n + self::$lut[$b32[$i]]; // Add value into buffer
            $j = $j + 5;                    // Keep track of number of bits in buffer

            if ($j >= 8) {
                $j = $j - 8;
                $binary .= chr(($n & (0xFF << $j)) >> $j);
            }
        }

        return $binary;
    }

Decodes a base 32 string.

@param mixed Base 32 string to decode

@return string Base 32 string decoded


private function listAllIterator($recursive = false, $showHidden = false)
	{
		if (!$this->isDirectory()) {
			return new \ArrayIterator([]);
		}

		$flags = \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO;

		if (!$showHidden) {
			$flags = $flags | \FilesystemIterator::SKIP_DOTS;
		}

		if ($recursive) {
			return new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->path, $flags), \RecursiveIteratorIterator::SELF_FIRST);
		}

		return new \FilesystemIterator($this->path, $flags);
	}

private function listAllIterator ( $ recursive = false , $ showHidden = false ) { if ( ! $ this -> isDirectory ( ) ) { return new \ ArrayIterator ( [ ] ) ; } $ flags = \ FilesystemIterator :: KEY_AS_PATHNAME | \ FilesystemIterator :: CURRENT_AS_FILEINFO ; if ( ! $ showHidden ) { $ flags = $ flags | \ FilesystemIterator :: SKIP_DOTS ; } if ( $ recursive ) { return new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ this -> path , $ flags ) , \ RecursiveIteratorIterator :: SELF_FIRST ) ; } return new \ FilesystemIterator ( $ this -> path , $ flags ) ; }

Returns an iterator with the files and directories in the current directory.

@param bool $recursive = false
@param bool $showHidden = false
@return \ArrayIterator|\FilesystemIterator|\RecursiveIteratorIterator an iterator with the files and directories in the current directory.

Returns an iterator with the files and directories in the current directory .


public function listAll($recursive = false, $showHidden = false)
	{
		$result = [];

		foreach ($this->listAllIterator($recursive, $showHidden) as $element) {
			$result[] = $element->getFilename();
		}

		return $result;
	}

public function listAll ( $ recursive = false , $ showHidden = false ) { $ result = [ ] ; foreach ( $ this -> listAllIterator ( $ recursive , $ showHidden ) as $ element ) { $ result [ ] = $ element -> getFilename ( ) ; } return $ result ; }

Returns an array with the files and directories in the current directory.

@param bool $recursive = false
@param bool $showHidden = false
@return string[] an array with the files and directories in the current directory.

Returns an array with the files and directories in the current directory .


public function listDirectories($recursive = false, $showHidden = false)
	{
		$result = [];

		foreach ($this->listAllIterator($recursive, $showHidden) as $element) {
			if ($element->isDir()) {
				$result[] = $element->getFilename();
			}
		}

		return $result;
	}

public function listDirectories ( $ recursive = false , $ showHidden = false ) { $ result = [ ] ; foreach ( $ this -> listAllIterator ( $ recursive , $ showHidden ) as $ element ) { if ( $ element -> isDir ( ) ) { $ result [ ] = $ element -> getFilename ( ) ; } } return $ result ; }

Returns an array with the directories in the current directory.

@param bool $recursive = false
@param bool $showHidden = false
@return string[] an array with the directories in the current directory.

Returns an array with the directories in the current directory .


public function listFiles($recursive = false, $showHidden = false)
	{
		$result = [];

		foreach ($this->listAllIterator($recursive, $showHidden) as $element) {
			if ($element->isFile()) {
				$result[] = $element->getFilename();
			}
		}

		return $result;
	}

public function listFiles ( $ recursive = false , $ showHidden = false ) { $ result = [ ] ; foreach ( $ this -> listAllIterator ( $ recursive , $ showHidden ) as $ element ) { if ( $ element -> isFile ( ) ) { $ result [ ] = $ element -> getFilename ( ) ; } } return $ result ; }

Returns an array with the files in the current directory.

@param bool $recursive = false
@param bool $showHidden = false
@return string[] an array with the files in the current directory.

Returns an array with the files in the current directory .


public function makeFile($override = false)
	{
		if ($this->exists() && !$override) {
			return false;
		}

		return file_put_contents($this->path, '') !== false;
	}

public function makeFile ( $ override = false ) { if ( $ this -> exists ( ) && ! $ override ) { return false ; } return file_put_contents ( $ this -> path , '' ) !== false ; }

Returns true if the file has been created.

@param bool $override = false
@return bool true if the file has been created.

Returns true if the file has been created .


public function makeDirectory($recursive = false, $permissions = 0775)
	{
		if ($this->exists()) {
			return false;
		}

		$old = umask(0777 - $permissions);
		$result = mkdir($this->path, $permissions, $recursive);
		umask($old);

		return $result;
	}

public function makeDirectory ( $ recursive = false , $ permissions = 0775 ) { if ( $ this -> exists ( ) ) { return false ; } $ old = umask ( 0777 - $ permissions ) ; $ result = mkdir ( $ this -> path , $ permissions , $ recursive ) ; umask ( $ old ) ; return $ result ; }

Returns true if the directory has been created.

@param bool $recursive = false
@param int $permissions = 0755
@return bool true if the directory has been created.

Returns true if the directory has been created .


public function move($path, $override = false)
	{
		if (!$this->exists()) {
			return false;
		}

		$file = new File($path);

		if (($file->exists() && !$override) || !rename($this->path, $file->getPath())) {
			return false;
		}

		$this->path = $file->getPath();

		return true;
	}

public function move ( $ path , $ override = false ) { if ( ! $ this -> exists ( ) ) { return false ; } $ file = new File ( $ path ) ; if ( ( $ file -> exists ( ) && ! $ override ) || ! rename ( $ this -> path , $ file -> getPath ( ) ) ) { return false ; } $ this -> path = $ file -> getPath ( ) ; return true ; }

Returns true if the file is succesfully moved.

@param string $path
@param bool $override = false
@return bool true if the file is succesfully moved.

Returns true if the file is succesfully moved .


public function rename($file, $override = false)
	{
		return $this->move($this->getDirectory() . static::DIRECTORY_SEPARATOR . basename($file), $override);
	}

public function rename ( $ file , $ override = false ) { return $ this -> move ( $ this -> getDirectory ( ) . static :: DIRECTORY_SEPARATOR . basename ( $ file ) , $ override ) ; }

Returns true if the file is succesfully renamed.

@param string $file
@param bool $override = false
@return bool true if the file is succesfully renamed.

Returns true if the file is succesfully renamed .


public function removeDirectory($recursive = false)
	{
		if (!$recursive) {
			return rmdir($this->path);
		}

		foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->path, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST) as $path) {
			$path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
		}

		return true;
	}

public function removeDirectory ( $ recursive = false ) { if ( ! $ recursive ) { return rmdir ( $ this -> path ) ; } foreach ( new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ this -> path , \ FilesystemIterator :: SKIP_DOTS ) , \ RecursiveIteratorIterator :: CHILD_FIRST ) as $ path ) { $ path -> isFile ( ) ? unlink ( $ path -> getPathname ( ) ) : rmdir ( $ path -> getPathname ( ) ) ; } return true ; }

Returns true if the directory is succesfully removed.

@param bool $recursive = false
@return bool true if the directory is succesfully removed.

Returns true if the directory is succesfully removed .


private function setName(?string $n) : void
    {
        if ($n === null || $n === "") {
            $msg = "Invalid configuration. The attribute \"name\" is required.";
            throw new \InvalidArgumentException($msg);
        } else {
            // Se forem encontrados caracteres inválidos para o nome do campo
            preg_match("/^[a-zA-Z0-9_]+$/", $n, $fnd);
            if (count($fnd) === 0) {
                $msg = "Invalid given field name [\"" . $n . "\"].";
                throw new \InvalidArgumentException($msg);
            }
            $this->name = $n;
        }
    }

Define o nome do campo.

Como regra, um nome de um campo apenas pode aceitar
caracteres "a-zA-Z0-9_".

@param       ?string $n
Nome do campo.

@throws      \InvalidArgumentException
Caso o nome indicado seja inválido.