<?php

/**
 * Request context setup
 *
 * @version DR1.7
 */
class RequestSetupFilter implements InterceptingFilter {



	protected $defaultAction;



	public function __construct($action) {
		$a = Action::buildAction($action);
		$this->defaultAction = $a->getActionString();
		if (array_key_exists('RequestSetupFilter', $_SESSION)) {
			$this->defaultAction = &$_SESSION['RequestSetupFilter'];
		}
	}



	public static function savepoint($action) {
		$a = Action::buildAction($action);
		$_SESSION['RequestSetupFilter'] = $a->getActionString();
	}



	/**
	 * Returns if current request is made asynchronously
	 *
	 * @return boolean, true if Ajax
	 */
	public static function isAjaxCall() {
		return array_key_exists('ajax', $_REQUEST);
	}



	public function preProcess(RequestContext $request, ResponseContext $response) {
		$action = array_key_exists('action', $_REQUEST)
			? $_REQUEST['action']
			: $this->defaultAction;

		$args = new ArrayObject();
		$ajax = RequestSetupFilter::isAjaxCall();
		$mq = get_magic_quotes_runtime();
		$rawArgs = (array)@$_REQUEST['args'];

		// iterate over each argument passed
		foreach ($rawArgs as $arg) {
			if ($ajax) {
				$arg = str_replace(' ', '+', $arg); // Javascript base64 function bug workaround
				$arg = base64_decode($arg); // if there was Ajax call the argument needs to be decoded
			}
			// Magic Quotes is supposed to be turned off
			if (!$arg or is_numeric($arg) or ($arg[0] != '{' and $arg[strlen($arg) - 1] != '}')) {
				 // primitive value argument
				$arg = $mq ? addslashes($arg) : $arg;
				$args[] = $arg;
			} else {
				// form context argument
				$tr = array("\n" => '\n', "\t" => '\t', "\r" => '\r');
				$arg = str_replace(array_keys($tr), array_values($tr), $arg);
				$arg = (array)json_decode($arg, true);
				if (is_array($arg)) {
					$formData = new ArrayObject();
					foreach ($arg as $k => $v) {
						$formData[$k] = $mq ? addslashes($v) : $v;
					}
					$args[] = new FormContext($formData);
				}
			}
		}

		$request->configure($action, $args);
	}



	public function postProcess(RequestContext $request, ResponseContext $response) {

	}



} // class RequestSetupFilter

?>