/** * method: output * * todo: write documentation */ public static function output($name, $data) { $a = func_get_args(); try { $n = array_shift($a); self::$instance->log(count($a) > 1 ? $a : current($a), $n); } catch (Exception $e) { Amslib_Debug::log("stack_trace", "exception occured whilst outputting firephp variables"); } }
/** * method: getHandlerData * * todo: write documentation */ protected function getHandlerData($plugin, $default, $key) { $plugin = self::pluginToName($plugin); if (!$this->handler && count($this->source[self::HD])) { $this->processHandler(); } if (!$this->handler) { // TODO: move into the logging system intead of here error_log("** " . __METHOD__ . " ** " . Amslib_Debug::pdump(true, $this->handler) . " was invalid"); return NULL; } return isset($this->handler[$plugin]) && isset($this->handler[$plugin][$key]) ? Amslib_Array::valid($this->handler[$plugin][$key]) : $default; }
public static function execCallback($key, $callback, $object = NULL) { if (!self::$qp || !is_callable($callback)) { print "FAILED CALLBACK = " . Amslib_Debug::pdump(true, $callback); return; } try { $results = self::$qp->branch()->find($key); } catch (Exception $e) { Amslib_Debug::log("QueryPath Exception", $e->getMessage); } foreach ($results as $r) { $r = Amslib_QueryPath::toArray($r); call_user_func($callback, $r["tag"], $r, $object); } }
public function __construct($message, $data = array(), $use_callback = true) { parent::__construct($message); // This is so if an exception is generated using a true/false/1/0 type value // it'll still process into a predictable format if (is_scalar($data)) { $data = array("data" => $data); } foreach (Amslib_Array::valid($data) as $key => $value) { $this->setData($key, $value); } // NOTE: I have to test whether this records the correct location in all circumstances $this->setData("location", basename($this->getFile()) . "@" . $this->getLine()); // if this callback is usable, call it for the custom functionality if (self::$callback && is_callable(self::$callback) && $use_callback) { call_user_func(self::$callback, $this, Amslib_Debug::getStackTrace("type", "text")); } }
public function setResponse($data) { $exception = ""; ob_start(); try { if (is_string($data)) { $this->response = json_decode($data, true); } else { if (is_array($data)) { $this->response = $data; } } } catch (Exception $e) { $exception = $e->getMessage(); } $output = ob_get_clean(); if (strlen($output) || strlen($exception)) { Amslib_Debug::log("json_decode probably has failed with the following output", $output, $exception); } }
<?php // Change this to the correct path if required require_once "amslib/Amslib.php"; Amslib_Debug::showErrors(); // If you need language support, follow this pattern Amslib_Router_Language::add("en_GB", "en", true); Amslib_Router_Language::add("es_ES", "es"); Amslib_Router_Language::initialise("en"); // Here we create a normal router object $xml = Amslib_Router::getObject("source:xml"); $xml->load("amslib_router.xml"); Amslib_Router::setSource($xml); Amslib_Router::execute(); // This is how to obtain the language catalogue, using the language system linked ot the router $locale = Amslib_Translator_XML::getInstance(); $locale->load("translations/" . Amslib_Router_Language::getCode() . ".xml", true); // Get the resource from the route detected $resource = $router->getResource(); // Here you should put what you need to do in order to complete the work
public function execute($raw = false) { $reply = $exception = false; if ($this->debug) { $raw = true; } try { if (strlen($this->url) == 0) { throw new Exception("webservice url was invalid"); } $curl = curl_init(); // This is just the first version of this code, it works, but it's hardly very elegant. // Also, I think I need to merge code from Amslib_Plugin_Service because we seem to be duplicating // it a lot here, perhaps we need to have a common shared object with methods to set and get from // the storage variable if ($this->sharedSession) { $key_remote = "/amslib/webservice/session/remote/"; $key_request = "/amslib/webservice/session/request/"; $id_session = Amslib_SESSION::get($key_remote); if ($id_session) { $cookie = "PHPSESSID={$id_session}; path=/"; //.Amslib_Router_URL::getFullURL(); curl_setopt($curl, CURLOPT_COOKIE, $cookie); Amslib_SESSION::set("REQUEST_COOKIE", $cookie); } else { $this->params[$key_request] = true; } } $params = http_build_query(Amslib_Array::valid($this->params)); if ($this->username && $this->password) { curl_setopt($curl, CURLOPT_USERPWD, "{$this->username}:{$this->password}"); } curl_setopt($curl, CURLOPT_URL, $this->url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_HTTP_VERSION, 1.0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_POSTFIELDS, $params); $reply = curl_exec($curl); if (!$reply || !strlen($reply)) { Amslib_Debug::log("CURL ERROR", curl_error($curl), Amslib_Debug::dump($reply)); curl_close($curl); return false; } curl_close($curl); $response = new Amslib_Webservice_Response($reply); if ($this->sharedSession && !$id_session) { $data = $response->getData("amslib"); if ($value = $data->getKey($key_remote)) { Amslib_SESSION::set($key_remote, $value); } } return $response; } catch (Exception $e) { $exception = $e->getMessage(); } Amslib_Debug::log("EXCEPTION: ", $exception, "WEBSERVICE URL: ", $this->url, "PARAMS: ", $this->params, "DATA: ", $reply); return false; }
public function process($plugin, $key, $callback) { $callback = is_string($callback) ? array($plugin, $callback) : $callback; $callback = Amslib_Plugin::getCallback($callback); if (!$this->queryPath || !is_callable($callback)) { $callback = $callback instanceof Closure ? "{closure}" : $callback; Amslib_Debug::log("QueryPath or callback not valid", $plugin->getName(), $key, $callback); return; } try { $results = $this->queryPath->branch()->find($key); } catch (Exception $e) { Amslib_Debug::log("QueryPath Exception", $e->getMessage()); } foreach ($results as $r) { $r = Amslib_QueryPath::toArray($r); call_user_func($callback, $r["tag"], $r, $plugin); } }
/** * method: getError * * todo: write documentation */ public function getError() { return is_array($this->error) ? Amslib_Debug::dump($this->error) : $this->error; }
/** * method: setData * * todo: write documentation */ public function setData($identifier, $name, $value) { $identifier = self::getIdentifier($identifier); if ($name == NULL) { if (is_array($value)) { $this->data[$identifier][self::SD] = $value; } else { Amslib_Debug::log("value was invalid array", $value); return NULL; } } else { if (is_numeric($name) || is_string($name)) { $this->data[$identifier][self::SD][$name] = $value; } else { Amslib_Debug::log("name was invalid", $name); return NULL; } } return $value; }
/** * method: recv * * todo: write documentation */ public static function recv() { $base64 = Amslib_GET::get("encrypted"); if (!$base64) { self::reply(false, "missing 'encrypted' parameter"); } $encrypted = base64_decode($base64); $decrypted = AesCtr::decrypt($encrypted, self::getPassword()); try { $json = json_decode($decrypted, true); } catch (Exception $e) { // do nothing Amslib_Debug::log("Exception whilst json_decoding content"); } if (!isset($json) || !$json || !isset($json["check"])) { self::reply(false, "invalid data"); } if ($json["check"] != self::getCheck()) { self::reply(false, "check compare failed"); } unset($json["check"]); // TODO: the sender might have posted an actual file, so we need to maybe check this and // provide the file data from the $_FILES array return $json; }
public function execute() { try { if (strlen($this->url) == 0) { throw new Exception("webservice url was invalid"); } $curl = curl_init(); $params = http_build_query(Amslib_Array::valid($this->params)); if ($this->username && $this->password) { curl_setopt($curl, CURLOPT_USERPWD, "{$this->username}:{$this->password}"); } curl_setopt($curl, CURLOPT_URL, $this->url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_HTTP_VERSION, 1.0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_POSTFIELDS, $params); // FIXME: perhaps we shouldn't disable these? it's maybe a security problem if (strpos($this->url, 'https://') !== false) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } $this->reply = curl_exec($curl); if (!$this->reply || !strlen($this->reply)) { Amslib_Debug::log("CURL ERROR", curl_error($curl), Amslib_Debug::dump($this->reply)); curl_close($curl); return false; } curl_close($curl); return true; } catch (Exception $e) { $exception = $e->getMessage(); } Amslib_Debug::log("EXCEPTION: ", $exception, "WEBSERVICE URL: ", $this->url, "PARAMS: ", $this->params, "DATA: ", $reply); return false; }
/** * method: translateExtended * * todo: write documentation */ public function translateExtended($n, $i, $l = NULL) { $v = parent::translateExtended($n, $i, $l); if ($v == $n && is_numeric($i)) { $i = intval($i); $l = $this->getIdLang($l); $n = $this->database->escape($n); $r = $this->database->select("value from {$this->table} where name='{$n}' and id_object={$i} and id_lang='{$l}'"); $v = ""; if (is_array($r)) { if (count($r) > 1) { Amslib_Keystore::add(__METHOD__, "Multiple conflicting translations for key({$n}),id_object({$i}) and language({$l})"); } else { if (isset($r[0]["value"])) { $v = trim($r[0]["value"]); } } parent::learnExtended($n, $i, $v, $l); } else { $v = $n; } } else { die("FAIL 1: " . Amslib_Debug::pdump(true, $n, $i, $l, $v)); } return $v; }
public static function abs($url = "", $resolve = false) { Amslib_Debug::log("DEPRECATED METHOD", "stack_trace"); return self::absolute($url, $resolve); }
/** * method: getArray * * todo: write documentation */ public function getArray($node = false, $attributes = false) { if (!$node) { if (!$this->queryResults) { return NULL; } $node = $this->queryResults; } $data = array(); foreach ($node as $c) { print __METHOD__ . ": nodeType = " . $c->nodeType . ", nodeName = " . $c->nodeName . "<br/>"; $data[$c->nodeName] = $c->hasChildNodes() && $c->nodeType == XML_ELEMENT_NODE ? $this->getArray($c, $attributes) : $c->nodeValue; if ($attributes) { $data[$c->nodeName]["__attr"] = $this->getArray($c->attributes); } } print __METHOD__ . ": data = " . Amslib_Debug::pdump(true, $data); return $data; }
/** * method: removeJavascript * * todo: write documentation */ public static function removeJavascript($id, $position = NULL) { $position = self::validatePosition($position); if (!isset(self::$javascript[$position])) { Amslib_Debug::log("position requested to remove javascript from is not valid"); } else { if (!isset(self::$javascript[$position][$id])) { Amslib_Debug::log("index requested to remove from javascript array is not valid"); } else { unset(self::$javascript[$position][$id]); } } }
/** * method: setValue * * todo: write documentation */ public function setValue($key, $value) { switch ($key) { case "value": $this->data[$key] = Amslib_Array::valid($this->data[$key]); $this->data[$key] = array_merge($this->data[$key], $value); break; case "translator": $this->data[$key][$value["name"]] = $value; break; case "model": $this->data[$key] = $value; break; case "image": $this->data[$key][$value["id"]] = $value["value"]; break; case "view": $this->data[$key][$value["id"]] = $value; break; default: die(__METHOD__ . ": UNCONVERTED CODE: " . Amslib_Debug::pdump(true, $key, $value)); // THIS IS THE OLD UNCONVERTED CODE // This is important, because otherwise values imported/exported through transfer() will not execute in process() unset($value["import"], $value["export"]); if ($key == "value") { // Search and update any existing values $this->data[$key] = Amslib_Array::valid($this->data[$key]); foreach ($this->data[$key] as &$v) { if ($v["name"] == $value["name"] && !isset($v["export"]) && !isset($v["import"])) { $v["value"] = $value["value"]; return; } } // The value didnt already exist, so we must create it $this->data[$key][] = $value; } else { if (is_string($key)) { $this->data[$key] = $value; } else { $this->data[$key[0]][$key[1]] = $value; } } break; } }
/** * method: set * * Set a single token and it's replacement into the storage * * params: * $token - The name of the token * $replacement - The string value to replace the token with * $overwrite - Whether or not to overwrite existing tokens * * notes: * - The default is to overwrite the tokens * - The replacement value SHOULD be a string, most likely you're replacing tokens in text * - If the replacement value is not a string, I don't know what will happen in your specific situation */ public function set($token, $replacement, $overwrite = true) { if (!$token || !is_string($token) || !strlen($token)) { Amslib_Debug::log("token = ", $token); return false; } if (!$replacement || !is_scalar($replacement) || !strlen($replacement)) { Amslib_Debug::log("token = ", $token, "replacement = ", $replacement, "stack_trace"); return false; } if ($overwrite == false && isset($this->list[$token])) { return false; } return $this->list[$this->getToken($token)] = $replacement; }
/** * method: getConnectionDetails * * todo: write documentation * * note: * - we store the password like this because it hides it from var_dump and friends but * still allows the password to be returned within the duration of the script * - I'm not 100% sure it stops people from grabbing the password, but 90%+ :D */ public function getConnectionDetails() { static $password = NULL; if ($this->connectionDetails) { if (isset($this->connectionDetails["password"])) { $password = $this->connectionDetails["password"]; unset($this->connectionDetails["password"]); } return array($this->connectionDetails, $password); } die(__METHOD__ . ", FATAL ERROR: there were no connection details" . Amslib_Debug::vdump($this->connectionDetails)); }
public static function implodeQuoteDouble($array, $join = ",") { Amslib_Debug::log("DEPRECATED METHOD, USE self::implode DIRECTLY"); return self::implode($array, $join, "\""); }
public function setDestination($index, $destination, $append = true) { if (!isset($this->appender[$index])) { return false; } switch (get_class($this->appender[$index])) { case "LoggerAppenderFile": $exists = $this->createFileLog($destination); if ($exists) { $this->appender[$index]->setFile($destination); $this->appender[$index]->setAppend($append); // Create a default layout, which you can override later $layout = new LoggerLayoutTTCC(); $layout->activateOptions(); $this->appender[$index]->setLayout($layout); } else { // We do this to make sure the appender cannot be activated or used unset($this->appender[$index]); // Ironically, the logging class fails, so we use the error log :) Amslib_Debug::log(__METHOD__ . ", Failed to find or create the log file that we needed"); } break; } return true; }
/** * method: stripComments * * Remove all comments from a string, it might not be perfect * * params: * $string - The string to process * * returns: * A string without comments * * notes: * - I got some of this code originally from: http://stackoverflow.com/a/1581063/279147 */ public static function stripComments($string) { if (!is_string($string)) { Amslib_Debug::log("Attempting to strip comments from something that is not a string"); return false; } $string = preg_replace('#<!--[^\\[<>].*?(?<!!)-->#s', '', $string); $regex = array("`^([\t\\s]+)`ism" => '', "`\\/\\*(.+?)\\*\\/`ism" => "", "`([\n\\A;]+)\\/\\*(.+?)\\*\\/`ism" => "\$1", "`([\n\\A;\\s]+)//(.+?)[\n\r]`ism" => "\$1\n", "`(^[\r\n]*|[\r\n]+)[\\s\t]*[\r\n]+`ism" => "\n"); $string = preg_replace(array_keys($regex), $regex, $string); return $string; }
/** * method: __shutdown_exception * * todo: write documentation */ public static function __shutdown_exception($e) { $stack = Amslib_Debug::getStackTrace("exception", $e); if (empty($stack)) { $stack = array(array("file" => "__STACK_ERROR__", "line" => "__STACK_ERROR__")); } if (!array_key_exists("file", $stack[0])) { $stack[0]["file"] = "__FILE_NOT_AVAILABLE__"; } if (!array_key_exists("line", $stack[0])) { $stack[0]["line"] = "__LINE_NOT_AVAILABLE__"; } $data = array("error" => "Uncaught Exception", "code" => get_class($e), "msg" => $e->getMessage(), "data" => is_callable(array($e, "getData")) ? $e->getData() : false, "file" => $stack[0]["file"], "line" => $stack[0]["line"], "stack" => $stack, "uri" => $_SERVER["REQUEST_URI"], "root" => isset($_SERVER["__WEBSITE_ROOT__"]) ? $_SERVER["__WEBSITE_ROOT__"] : "/"); self::__exec_shutdown($data); }
/** * method: decodeResponse * * todo: write documentation */ protected function decodeResponse($response) { if ($response == false) { return false; } if (is_string($response)) { if ($this->debug) { print "DEBUGGING: " . Amslib_Debug::dump($response); } $parameters = explode("&", $response); $this->response = array(); foreach ($parameters as $p) { list($key, $value) = explode("=", $p); $this->response[urldecode($key)] = urldecode($value); } return $this->getResponse("ACK") == "Success" ? true : false; } }
/** * method: dump * * todo: write documentation */ public static function dump($vdump = false, $print = false, $die = false) { $data = array("path" => self::$path, "current" => self::$route, "cache" => self::$cache, "url" => self::$url, "name" => self::$name); if ($vdump || $print) { $data = Amslib_Debug::vdump($data); } if ($print) { print $data; } if ($die !== false) { if (!is_string($die)) { $die = ""; } die($die . $data); } return $data; }
/** * method: execute * * Execute the validator according to the rules setup * * returns: * If there are no items in the source array, return true or false, depending on whether there are required rules or not * Return whether the result from calling Amslib_Validator::getStatus (true or false, true for no errors) * * operations: * - Reset the hasExecuted flag to false * - Count the number of items in the source array, if zero, return true (hasExecuted will remain false) * - For each item in the rules array (see notes) validate it * - Set the hasExecuted flag to true * - obtain the name of the callback to execute * - Find the required flag and the minlength from the validator structure * - if the validator type is "file" obtain the file from the $_FILES superglobal and assign it as the value * - Otherwise, obtain the value from the source array * - Call the callback and obtain the success code * - If failed, then set data into the error array * - Return the status of the validator (true = no errors) */ public function execute() { $this->hasExecuted = false; // TODO? investigate whether I should also stop processing here if there are no rules to process if (!count($this->source) && $this->hasRequiredRules()) { return false; } foreach ($this->rules as $name => $rule) { $value = $this->getValue($name, $rule["options"]); $callback = isset($this->custom[$rule["type"]]) ? $this->custom[$rule["type"]] : array($this, "validate_{$rule["type"]}"); if (is_callable($callback)) { $status = call_user_func($callback, $name, $value, $rule["required"], $rule["options"]); if ($status !== true) { $this->setError($name, $value, $status); } } else { Amslib_Debug::log("stack_trace", "validator method missing or not callable", $rule["type"], $callback[1]); } } $this->hasExecuted = true; return $this->getStatus(); }
public static function showErrors($state = true) { Amslib_Debug::log("deprecated, use 'enable(\$state)' instead", "stack_trace"); self::enable($state); }
public static function getContents($filename, &$error = NULL) { ob_start(); $data = file_get_contents($filename); $error = ob_get_clean(); if (strlen($error) || !strlen($data)) { Amslib_Debug::log("file = '{$filename}', error output = ", $error, "strlen(data) = ", strlen($data)); } return $data; }
public static function dump() { return Amslib_Debug::vdump(func_get_arg(0)); }
function amslib_autoload_exception($c) { if ($c == __CLASS__) { return false; } $result = false; if (strpos($c, '\\') === false) { $e = new Exception(); $t = $e->getTrace(); if (isset($t[1]) && isset($t[1]["file"])) { $result = Amslib::requireFile(dirname($t[1]["file"]) . "/{$c}.php"); if ($result && !Amslib::autoloaderStatus("exception")) { Amslib_Debug::log("EXCEPTION AUTOLOADER: we loaded the class '{$c}' this is not efficient"); Amslib_Debug::log("EXCEPTION AUTOLOADER: call Amslib::autoloader_exception(true,true) to remove this warning"); } } } return $result; }