/** * 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"); } }
public static function __exception_error_handler($errno, $errstr, $errfile, $errline) { if (in_array($errno, self::$trap_list)) { if (strpos($errstr, "open_basedir restriction in effect") !== false) { throw new Amslib_Exception_Openbasedir($errstr, $errno); } else { throw new Amslib_Exception($errstr, $errno); } } else { Amslib_Debug::log("Error/Warning occurred but did not trigger exception", $errno, $errstr, $errfile, $errline); } }
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 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); } }
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; }
/** * 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 listPlugins() { Amslib_Debug::log("DEPRECATED METHOD", "stack_trace"); return self::listPlugin(); }
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; }
/** * method: __construct * * todo: write documentation */ public function __construct($source) { $this->route = false; $this->import = false; $this->valid = false; $v = new Amslib_Validator($source); $v->add("lang", "text", true); $v->add("route", "text", true); $v->add("route_type", "text", true); $v->add("options", "text", true); $v->add("options_input", "text", true); $v->add("options_output", "text", true); $v->add("options_record", "text", true); $v->add("options_failure", "text", true); $v->add("url", "text", true); $v->add("param", "text", true); $v->add("param_type", "text", true); $v->add("handler", "text", true); $v->add("handler_type", "text", true); $v->add("database", "instanceof", true, array("type" => "Amslib_Database_MySQL")); $s = $v->execute(); $d = $v->getValid(); $e = $v->getErrors(); if ($s) { try { $this->database = $d["database"]; $this->table = $d; unset($this->table["database"]); $this->processPath(); $this->processService(); $this->processConfig(); $this->valid = true; } catch (Exception $e) { Amslib_Debug::log("Exception: ", $e->getMessage()); Amslib_Debug::log("stack_trace"); } } }
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: config * * todo: write documentation */ public function config($name) { $this->isConfigured = false; $this->isLoaded = false; $this->name = $name; if ($this->source) { // Prepare, execute and process all the selectors loaded $this->source->execute($this); // Save memory, be water my friend, delete unwanted things // NOTE: probably this is not the best way to do this... $this->deleteConfigSource(); $this->isConfigured = true; // Now the configuration data is loaded, initialise the plugin with any custom requirements $this->initialisePlugin(); } else { Amslib_Debug::log(self::ERROR_PLUGIN_SOURCE_INVALID, $this->source); } return $this->isConfigured; }
public static function log() { foreach (self::get(NULL, false) as $item) { Amslib_Debug::log("code_location,{$item["title"]}", "time[{$item["time"]}], diff[{$item["diff"]}]"); } if ($totals = self::totals()) { Amslib_Debug::log("start[{$totals["start"]}], finish[{$totals["finish"]}], total[{$totals["total"]}]"); } }
public static function abs($url = "", $resolve = false) { Amslib_Debug::log("DEPRECATED METHOD", "stack_trace"); return self::absolute($url, $resolve); }
/** * method: __construct * * todo: write documentation */ public function __construct($source) { $this->route = false; $this->import = false; $this->valid = false; $filename = false; try { // NOTE: This is ugly and I believe it's a failure of Amslib_File::find() to not do this automatically if (file_exists($source)) { $filename = $source; } else { if (file_exists($f = Amslib_File::find(Amslib_Website::relative($source), true))) { $filename = $f; } else { if (file_exists($f = Amslib_File::find(Amslib_Website::absolute($source), true))) { $filename = $f; } } } if (!$filename) { Amslib_Debug::log("The filename was not valid, we could not getRoutes from this XML Source"); } else { Amslib_QueryPath::qp($filename); Amslib_QueryPath::execCallback("router > path[name]", array($this, "configPath"), $this); Amslib_QueryPath::execCallback("router > service[name]", array($this, "configService"), $this); Amslib_QueryPath::execCallback("router > callback", array($this, "configCallback"), $this); Amslib_QueryPath::execCallback("router > import", array($this, "configImport"), $this); Amslib_QueryPath::execCallback("router > export", array($this, "configExport"), $this); $this->valid = true; } } catch (Exception $e) { Amslib_Debug::log("Exception: ", $e->getMessage(), "file=", $filename, "source=", $source); Amslib_Debug::log("stack_trace"); } }
/** * method: load * * returns: * Boolean true or false depending on whether it succeeded, there are some codepaths which call setError() * this is because of serious errors which can't be handled at the moment * * NOTE: * - if language is false, you need to call setLanguage before you * call load otherwise the source can't load the correct file */ public function load() { if (!$this->language) { return false; } $dir = $this->getConfig("directory"); $source = Amslib_File::reduceSlashes("{$dir}/{$this->language}.xml"); $filename = false; try { // NOTE: This is ugly and I believe it's a failure of Amslib_File::find() to not do this automatically if (file_exists($source)) { $filename = $source; } else { if (file_exists($f = Amslib_File::find(Amslib_Website::relative($source), true))) { $filename = $f; } else { if (file_exists($f = Amslib_File::find(Amslib_Website::absolute($source), true))) { $filename = $f; } } } if (!$filename) { Amslib_Debug::log("stack_trace", "directory", $dir, "filename", $filename, "language", $this->language); } else { $this->qp = Amslib_QueryPath::qp($filename); return true; } } catch (Exception $e) { Amslib_Debug::log("Exception: ", $e->getMessage(), "file=", $filename, "source=", $source); Amslib_Debug::log("stack_trace"); } return false; }
/** * method: execute * * execute the application, or process a web service, depending on the type of the route * * NOTE: * - if the route has type='service' we are going to process a webservice * - override this default behaviour by overriding this method with a customised version */ public function execute($params = array()) { // If the url executed belonds to a web service, run the service code // NOTE: this isService() call, I think is a bit hacky, I would // like to do away with it and have the framework do it if (Amslib_Router::isService()) { $this->runService(); } // Get the current route and acquire the api object for the current route and render it // NOTE: we do this so you can render pages from other plugins or the application based // on what route has been opened, sometimes you want to define webpages in separate // plugins and render them just based on the url and/or route $route = Amslib_Router::getRoute(); if (!$route || !isset($route["group"])) { Amslib_Debug::log("ROUTE OR ROUTE/GROUP DOES NOT EXIST", $route); return; } $api = $this->getAPI($route["group"]); if (!$api || !method_exists($api, "render")) { Amslib_Debug::log("API OR ITS RENDER METHOD DOES NOT EXIST", get_class($api), $route); return; } // If the url executed belongs to a page, render the default view of the application print $api->render("default", $params); }
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; }
public function setConnectionDetails($details = NULL) { $s = $d = false; if ($details) { $v = new Amslib_Validator($details); $v->add("username", "text", true); $v->add("password", "text", true); $v->add("database", "text", true); $v->add("server", "text", true); $v->add("encoding", "text", true, array("default" => "utf8", "limit-input" => $this->validEncoding)); $s = $v->execute(); $d = $v->getValid(); $e = $v->getErrors(); if (!$s) { if (isset($e["password"])) { $e["password"]["value"] = "*CENSORED*"; } Amslib_Debug::log("database details were invalid", $e); } } $this->connectionDetails = $s ? $d : false; return $this->getConnectionDetails(); }
/** * 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]); } } }
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: 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; }
/** * method: getImage * * todo: write documentation * * NOTE: this function is being abused to be a generic "make relative url for a file" method for pretty much everything */ public function getImage($id, $relative = true) { if (!is_string($id)) { return false; } // Step 1: Expand any recognised tokens in the path $path = Amslib_Website::expandPath($id); // Step 2: Is the image absolute, beginning with http? if (strpos($id, "http") === 0) { return $id; } // Step 3: find the image inside the plugin if (isset($this->image[$id])) { return $this->image[$id]; } // Step 4: find the image relative to the website base (perhaps it's a path) $path = Amslib_Website::absolute($this->location . "/" . $id); if (file_exists($path)) { return $relative ? Amslib_Website::relative($path) : $path; } Amslib_Debug::log("stack_trace", "failed to find image", $id, $relative, $path, $this->location); // Step 4: return false, image was not found return false; }
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: 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: 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; }
public static function implodeQuoteDouble($array, $join = ",") { Amslib_Debug::log("DEPRECATED METHOD, USE self::implode DIRECTLY"); return self::implode($array, $join, "\""); }
/** * method: importRouter * * todo: write documentation */ public static function importRouter($import) { $params = self::encodeURLPairs($import, "/", array("output", "url", "name")); // acquire the latest route for the export url and construct the url to call the external remote service $route = self::getRoute("service:framework:router:export:" . $import["output"]); $import["url"] = Amslib_File::resolvePath(Amslib_Website::expandPath($import["url"])); $import["url_full"] = rtrim($import["url"], "/") . rtrim($route["src"]["default"], "/") . "/{$params}/"; if ($import["output"] == "json") { // We are going to install a router using json as a data transfer medium // Acquire the json, decode it and obtain the domain $data = Amslib_File::getContents($import["url_full"], $error); if (strlen($error)) { Amslib_Debug::log("FAILED TO IMPORT ROUTER IN JSON FORMAT, OR OTHER PROBLEM DETECTED", $error, error_get_last()); } $data = json_decode($data, true); $domain = $data["domain"]; // For each route in the cache, create a new route in the local router, giving the name, group, domain and route data // You are not supposed to update the url cache, imported routes are not accessible through url // The reason for this is because it doesnt make sense a url from a remote system will be processed by the local system // All url requests for imported services should goto the remote server directly foreach (Amslib_Array::valid($data["cache"]) as $route) { // We cannot use the service inheritance when importing a remote router unset($route["extend"]); self::setRoute($route["name"], $route["group"], $domain, $route, false); } // Record that we imported something so we can possibly use this information self::setImportData($import["name"], $import); } else { if ($import["output"] == "xml") { $data = Amslib_File::getContents($import["url_full"], $error); if (strlen($error)) { Amslib_Debug::log("FAILED TO IMPORT ROUTER IN XML FORMAT, OR OTHER PROBLEM DETECTED", $error, error_get_last()); } // TODO: implement the logic to import from XML } } }
/** * 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; }
public static function showErrors($state = true) { Amslib_Debug::log("deprecated, use 'enable(\$state)' instead", "stack_trace"); self::enable($state); }
/** * method: getHandlerData * * todo: write documentation */ public function getHandlerData($plugin, $default, $name = NULL) { if ($this->handler === false && $this->countHandler()) { $this->processHandler(); } if ($this->handler === false) { // TODO: move into the logging system instead of here Amslib_Debug::log("INVALID HANDLER", Amslib_Debug::pdump(true, $this->handler)); return NULL; } $keys = array(self::HD, $this->handler); if ($plugin !== NULL) { $keys[] = self::pluginToName($plugin); } if ($name !== NULL) { $keys[] = $name; } return $this->getKey($keys, $default); }