private function __geocodeAddress($address, $can_return_default = true) { $coordinates = null; $cache_id = md5('maplocationfield_' . $address); $cache = new Cacheable(Symphony::Database()); $cachedData = $cache->check($cache_id); // no data has been cached if (!$cachedData) { include_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init(); $ch->setopt('URL', '//maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false&v=3.13'); $response = json_decode($ch->exec()); $coordinates = $response->results[0]->geometry->location; if ($coordinates && is_object($coordinates)) { $cache->write($cache_id, $coordinates->lat . ', ' . $coordinates->lng, $this->_geocode_cache_expire); // cache lifetime in minutes } } else { $coordinates = $cachedData['data']; } // coordinates is an array, split and return if ($coordinates && is_object($coordinates)) { return $coordinates->lat . ', ' . $coordinates->lng; } elseif ($coordinates) { return $coordinates; } elseif ($return_default) { return $this->_default_coordinates; } }
function getValuesFromXML() { $xml_location = $this->get('xml_location'); $cache_life = (int) $this->get('cache'); require TOOLKIT . '/util.validators.php'; // allow use of choice params in URL $xml_location = preg_replace('/{\\$root}/', URL, $xml_location); $xml_location = preg_replace('/{\\$workspace}/', WORKSPACE, $xml_location); $doc = new DOMDocument(); if (preg_match($validators['URI'], $xml_location)) { // is a URL, check cache $cache_id = md5('xml_selectbox_' . $xml_location); $cache = new Cacheable($this->_Parent->_Parent->Database); $cachedData = $cache->check($cache_id); if (!$cachedData) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $xml_location); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; $cache->write($cache_id, $xml, $cache_life); // Cache life is in minutes not seconds e.g. 2 = 2 minutes $xml = trim($xml); if (empty($xml) && $cachedData) { $xml = $cachedData['data']; } } else { $xml = $cachedData['data']; } $doc->loadXML($xml); } elseif (substr($xml_location, 0, 1) == '/') { // relative to DOCROOT $doc->load(DOCROOT . $this->get('xml_location')); } else { // in extension's /xml folder $doc->load(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location')); } $xpath = new DOMXPath($doc); $options = array(); foreach ($xpath->query($this->get('item_xpath')) as $item) { $option = array(); $option['text'] = $this->run($xpath, $item, $this->get('text_xpath')); $option['value'] = $this->run($xpath, $item, $this->get('value_xpath')); if (is_null($option['value'])) { $option['value'] = $option['text']; } $options[] = $option; if ($item->hasChildNodes()) { foreach ($xpath->query('*', $item) as $child) { $text = $this->run($xpath, $child, $this->get('text_xpath')); $value = $this->run($xpath, $child, $this->get('value_xpath')); $options[] = array('text' => $option['text'] . " / " . $text, 'value' => $option['value'] . "-" . (!is_null($value) ? $value : $text)); } } } return $options; }
function getValuesFromXML() { $xml_location = $this->get('xml_location'); $cache_life = (int) $this->get('cache'); require TOOLKIT . '/util.validators.php'; // allow use of choice params in URL $xml_location = preg_replace('/{\\$root}/', URL, $xml_location); $xml_location = preg_replace('/{\\$workspace}/', WORKSPACE, $xml_location); if (preg_match($validators['URI'], $xml_location)) { // is a URL, check cache $cache_id = md5('xml_selectbox_' . $xml_location); $cache = new Cacheable($this->_Parent->_Parent->Database); $cachedData = $cache->check($cache_id); if (!$cachedData) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $xml_location); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; $cache->write($cache_id, $xml, $cache_life); // Cache life is in minutes not seconds e.g. 2 = 2 minutes $xml = trim($xml); if (empty($xml) && $cachedData) { $xml = $cachedData['data']; } } else { $xml = $cachedData['data']; } $xml = simplexml_load_string($xml); } elseif (substr($xml_location, 0, 1) == '/') { // relative to DOCROOT $xml = simplexml_load_file(DOCROOT . $this->get('xml_location')); } else { // in extension's /xml folder $xml = simplexml_load_file(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location')); } $options = array(); if (!$xml) { return $options; } $items = $xml->xpath($this->get('item_xpath')); foreach ($items as $item) { $option = array(); $text_xpath = $item->xpath($this->get('text_xpath')); $option['text'] = General::sanitize((string) $text_xpath[0]); if ($this->get('value_xpath') != '') { $value_xpath = $item->xpath($this->get('value_xpath')); $option['value'] = General::sanitize((string) $value_xpath[0]); } if ((string) $option['value'] == '') { $option['value'] = $option['text']; } $options[] = $option; } return $options; }
function getValuesFromXML() { $xml_location = $this->get('xml_location'); if (General::validateURL($xml_location) != '') { // is a URL, check cache $cache_id = md5($xml_location); $cache = new Cacheable($this->_Parent->_Parent->Database); $cachedData = $cache->check($cache_id); $creation = DateTimeObj::get('c'); if (!$cachedData || time() - $cachedData['creation'] > 5 * 60) { if (Mutex::acquire($cache_id, 6, TMP)) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $xml_location); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; Mutex::release($cache_id, TMP); $xml = trim($xml); if (empty($xml) && $cachedData) { $xml = $cachedData['data']; } } elseif ($cachedData) { $xml = $cachedData['data']; } } else { $xml = $cachedData['data']; } $xml = simplexml_load_string($xml); } elseif (substr($xml_location, 0, 1) == '/') { // relative to DOCROOT $xml = simplexml_load_file(DOCROOT . $this->get('xml_location')); } else { // in extension's /xml folder $xml = simplexml_load_file(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location')); } if (!$xml) { return; } $items = $xml->xpath($this->get('item_xpath')); $options = array(); foreach ($items as $item) { $option = array(); $text_xpath = $item->xpath($this->get('text_xpath')); $option['text'] = General::sanitize((string) $text_xpath[0]); if ($this->get('value_xpath') != '') { $value_xpath = $item->xpath($this->get('value_xpath')); $option['value'] = General::sanitize((string) $value_xpath[0]); } if ((string) $option['value'] == '') { $option['value'] = $option['text']; } $options[] = $option; } return $options; }
function __construct($args) { $this->_env = $args['env']; parent::__construct($args); $this->__processXMLFields(); $this->__processCustom(); $this->__isUrlParamValuesPresent(); }
/** * query - Queries the SEOMoz API * * @param string $apiName * @param string $target_url * @returns mixed URL contents on success, false on failure */ function query($api_call, $argument) { $timestamp = mktime() + 300; // 5 minutes into the future $argument = urlencode($argument); $request_url = "http://lsapi.seomoz.com/linkscape/{$api_call}/{$argument}?AccessID={$this->access_id}&Expires={$timestamp}&Signature=" . $this->generate_signature($timestamp); $cache = new Cacheable(Symphony::Database()); $cache_id = md5('seomoz_cache'); $data = $cache->check($cache_id); if (false == $data) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec($ch); curl_close($ch); $data = $cache->write($cache_id, $data, 60); } return $data['data']; }
public function testIsFlush() { $controller = new Controller(); $req = new SS_HTTPRequest('GET', '/', array('flush' => 1)); $controller->setRequest($req); $this->assertTrue(Cacheable::is_flush($controller)); $req = new SS_HTTPRequest('GET', '/', array('flush' => 'all')); $controller->setRequest($req); $this->assertTrue(Cacheable::is_flush($controller)); $req = new SS_HTTPRequest('GET', '/', array('fluff' => 1)); $controller->setRequest($req); $this->assertFalse(Cacheable::is_flush($controller)); }
/** * Start constructing the page. * Prepare all the shared variables such as dates and check alliance ID. * */ function start() { $this->page = new Page(); $this->plt_id = (int) edkURI::getArg('plt_id'); if (!$this->plt_id) { $this->plt_external_id = (int) edkURI::getArg('plt_ext_id'); if (!$this->plt_external_id) { $id = (int) edkURI::getArg('id', 1); // Arbitrary number bigger than we expect to reach locally if ($id > 1000000) { $this->plt_external_id = $id; } else { $this->plt_id = $id; } } } $this->view = preg_replace('/[^a-zA-Z0-9_-]/', '', edkURI::getArg('view', 2)); if ($this->view) { $this->page->addHeader('<meta name="robots" content="noindex, nofollow" />'); } if (!$this->plt_id) { if ($this->plt_external_id) { $this->pilot = new Pilot(0, $this->plt_external_id); $this->plt_id = $this->pilot->getID(); } else { $html = 'That pilot doesn\'t exist.'; $this->page->generate($html); exit; } } else { $this->pilot = Cacheable::factory('Pilot', $this->plt_id); $this->plt_external_id = $this->pilot->getExternalID(); } $this->page->setTitle('Pilot details - ' . $this->pilot->getName()); if (!$this->pilot->exists()) { $html = 'That pilot doesn\'t exist.'; $this->page->setContent($html); $this->page->generate(); exit; } if ($this->plt_external_id) { $this->page->addHeader("<link rel='canonical' href='" . edkURI::page('pilot_detail', $this->plt_external_id, 'plt_ext_id') . "' />"); } else { $this->page->addHeader("<link rel='canonical' href='" . edkURI::page('pilot_detail', $this->plt_id, 'plt_id') . "' />"); } $this->corp = $this->pilot->getCorp(); $this->alliance = $this->corp->getAlliance(); }
function generate() { global $smarty; $this->toplist->generate(); $i = 1; while ($row = $this->toplist->getRow()) { /* @var $corp Corporation */ $corp = Cacheable::factory('Corporation', $row['crp_id']); if ($corp->getExternalID()) { $uri = KB_HOST . "/?a=corp_detail&crp_ext_id=" . $corp->getExternalID(); } else { $uri = KB_HOST . "/?a=corp_detail&crp_id=" . $row['crp_id']; } $rows[] = array('rank' => $i, 'name' => $corp->getName(), 'uri' => $uri, 'portrait' => imageURL::getURL('Corporation', $corp->getExternalID(false), 32), 'count' => $row['cnt']); $i++; } $smarty->assign('tl_name', 'Corporation'); $smarty->assign('tl_type', $this->entity_); $smarty->assignByRef('tl_rows', $rows); return $smarty->fetch(get_tpl('toplisttable')); }
function __construct($args = NULL) { ## Check the config file is writable if (!is_writeable(CONFIG)) { $this->fatalError(NULL, "<p>Symphony's configuration file is not writable. Please check permissions on <code>/manifest/config.php</code>.</p>", true, true); } $this->_config = new Configuration(true); if (isset($args['config_xml'])) { General::loadConfiguration($args['config_xml'], $this->_config, new XmlDoc()); } if (isset($args['config'])) { $this->_config->setArray($args['config']); } if ($args['start_session']) { $this->startSession(); } if ($this->getConfigVar("prune_logs", "symphony")) { $this->pruneLogs(); } $this->_date =& new SymDate($this->getConfigVar("time_zone", "region"), $this->getConfigVar("date_format", "region"), $this->getConfigVar("dst", "region") == "yes" ? 1 : 0); parent::__construct(array("parent" => $this)); }
$template = new XMLElement('xsl:template'); $template->setAttribute('match', '/'); $instruction = new XMLElement('xsl:copy-of'); ## Namespaces foreach ($this->dsParamFILTERS as $name => $uri) { $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : NULL), $uri); } ## XPath $instruction->setAttribute('select', $this->dsParamXPATH); $template->appendChild($instruction); $stylesheet->appendChild($template); $stylesheet->setIncludeHeader(true); $xsl = $stylesheet->generate(true); $proc =& new XsltProcess(); $cache_id = md5($this->dsParamURL . serialize($this->dsParamFILTERS) . $this->dsParamXPATH); $cache = new Cacheable($this->_Parent->Database); $cachedData = $cache->check($cache_id); $writeToCache = false; $valid = true; $result = NULL; $creation = DateTimeObj::get('c'); if (!$cachedData || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) { if (Mutex::acquire($cache_id, 6, TMP)) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $this->dsParamURL); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; Mutex::release($cache_id, TMP); $xml = trim($xml);
function handle_involved($kill, $side, &$pilots, $sideAssignmentMap = array(), $completeInformation = FALSE) { // ------------------------------------------------------------------------- // FIX BATTLE REPORT a little by Evoke. Salvoxia // BEGIN // ------------------------------------------------------------------------- // we dont want our corp/alliance to show up on the enemy's side if ($side == 'e') { if (config::get('cfg_corpid')) { $corpId = config::get('cfg_corpid'); $corpId = $corpId[0]; $excludeWhere = "AND ind_crp_id != {$corpId}"; } elseif (config::get('cfg_allianceid')) { $allianceId = config::get('cfg_allianceid'); $allianceId = $allianceId[0]; $excludeWhere = "AND ind_all_id != {$allianceId}"; } else { $excludeWhere = ""; } } // we need to get all involved pilots, killlists dont supply them $qry = DBFactory::getDBQuery(); $sql = "select ind_plt_id AS ind_plt_id, ind_crp_id, ind_all_id, ind_sec_status, ind_shp_id, ind_wep_id, ind_dmgdone,\n typeName, plt_name, crp_name, all_name, scl_points, scl_id, scl_class\n from kb3_inv_detail\n left join kb3_invtypes on ind_wep_id=typeID\n left join kb3_pilots on ind_plt_id=plt_id\n left join kb3_corps on ind_crp_id=crp_id\n left join kb3_alliances on ind_all_id=all_id\n left join kb3_ships on ind_shp_id=shp_id\n left join kb3_ship_classes on shp_class=scl_id\n where ind_kll_id = " . $kill->getID() . " {$excludeWhere}\n order by ind_order"; $qry->execute($sql); while ($row = $qry->getRow()) { if (config::get('fleet_battles_mod_sideassign')) { // determine whether the pilot is member of an alliance if ($row["all_name"] == "None") { $entityType = "corp"; $entityId = $row["ind_crp_id"]; } else { $entityType = "alliance"; $entityId = $row["ind_all_id"]; } if (isset($sideAssignmentMap[$entityType][$entityId])) { $pilotSide = $sideAssignmentMap[$entityType][$entityId]; } else { $pilotSide = $side; } } else { $pilotSide = $side; } // check for manual side assignment for pilot $ship = Cacheable::factory('Ship', $row['ind_shp_id']); $shipc = Cacheable::factory('ShipClass', $row['scl_id']); // check for npc names (copied from pilot class) $pos = strpos($row['plt_name'], "#"); if ($pos !== false) { $name = explode("#", $row['plt_name']); $item = Item::getByID($name[2]); $row['plt_name'] = $item->getName(); } // dont set pods as ships for pilots we already have if (isset($pilots[$pilotSide][$row['ind_plt_id']])) { if ($row['scl_id'] == 18 || $row['scl_id'] == 2) { continue; } } // search for ships with the same id if (isset($pilots[$pilotSide][$row['ind_plt_id']]) && is_array($pilots[$pilotSide][$row['ind_plt_id']])) { foreach ($pilots[$pilotSide][$row['ind_plt_id']] as $id => $_ship) { if ($row['ind_shp_id'] == $_ship['sid']) { // we already got that pilot in this ship, continue $pilots[$pilotSide][$row['ind_plt_id']][0]["times"] += 1; // add up his damage done $pilots[$pilotSide][$row['ind_plt_id']][0]["damage"] += $row['ind_dmgdone']; continue 2; } } } if ($completeInformation) { $pilots[$pilotSide][$row['ind_plt_id']][] = array('name' => $row['plt_name'], 'plt_url' => edkURI::page("pilot_detail", $row["ind_plt_id"], "plt_id"), 'sid' => $row['ind_shp_id'], 'spic' => imageURL::getURL('Ship', $ship->getID(), 32), 'aid' => $row['ind_all_id'], 'ts' => strtotime($kill->getTimeStamp()), 'corp' => $row['crp_name'], 'alliance' => $row['all_name'], 'alliance_url' => edkURI::page("alliance_detail", $row['ind_all_id'], "all_id"), 'scl' => $row['scl_points'], 'ship' => $ship->getName(), 'shipClass' => $row['scl_class'], 'shipClassObject' => $shipc, 'weapon' => $row['itm_name'], 'cid' => $row['ind_crp_id'], 'crp_url' => edkURI::page("corp_detail", $row['ind_crp_id'], "crp_id"), 'times' => 1, 'damage' => $row['ind_dmgdone'], 'color' => getColorClassByClass($shipc)); } else { $pilots[$pilotSide][$row['ind_plt_id']] = 1; } } }
<?php /** * Cache objects that extend Cacheable. Use w/out altering the data modification method * All the caching is done OUTSIDE of the method that reads/computes the cached data */ require 'Cacheable.php'; Cacheable::$cacheDir = dirname(__FILE__) . '/cache'; // Configure the cache dir class obj_to_cache2 extends Cacheable { public $member1 = array('a' => 1); public $member2 = 'abc'; function changeDate($var) { echo "No cache! Heavy read here!..."; sleep(2); echo "done!\n"; // Lets say this is some heavy compyting here, and the results are written to member1 and 2 $this->member1[] = $var; $this->member2 .= $var; } } $obj = new obj_to_cache2(); $obj->cacheState = 'changed-str1'; if (!$obj->cacheRestore()) { $obj->changeDate('str1'); $obj->cacheStore(CacheExpire::create()->timeout(60)); } else { // Cache was hit! echo "Cache hit!\n";
public static function Load($action, $extra = []) { self::$param = $extra; return call_user_func([self::$extendpre, '__' . $action]); }
if (!defined("__IN_SYMPHONY__")) { die("<h2>Symphony Fatal Error</h2><p>You cannot directly access this file</p>"); } $table = null; $cache_sections = array($_REQUEST['handle']); switch (strtolower($_REQUEST['handle'])) { case "pages": $table = "tbl_pages"; break; case "customfields": $table = "tbl_customfields"; break; case "sections": $table = "tbl_sections"; break; } if ($table != NULL && is_array($_REQUEST['items']) && !empty($_REQUEST['items'])) { require_once LIBRARY . "/core/class.cacheable.php"; $cache = new Cacheable(array("db" => $db)); foreach ($_REQUEST['items'] as $id => $val) { $sql = "UPDATE {$table} SET `sortorder` = '{$val}' WHERE `id` = {$id}"; if ($db->query($sql)) { $xml->setAttribute("success", "true"); } else { $xml->setAttribute("success", "false"); } } $cache->flush_cache($cache_sections); } else { $xml->setAttribute("success", "false"); }
$url = edkURI::page('alliance_detail', $alls[0], 'all_id'); } header("Location: " . htmlspecialchars_decode($url)); die; } elseif (config::get('cfg_corpid')) { $corps = config::get('cfg_corpid'); /* @var $corp Corporation */ $corp = Cacheable::factory('Corporation', $corps[0]); if ($corp->getExternalID()) { $url = edkURI::page('corp_detail', $corp->getExternalID(), 'crp_ext_id'); } else { $url = edkURI::page('corp_detail', $corps[0], 'crp_id'); } header("Location: " . htmlspecialchars_decode($url)); die; } elseif (config::get('cfg_pilotid')) { $pilots = config::get('cfg_pilotid'); /* @var $pilot Pilot */ $pilot = Cacheable::factory('Pilot', $pilots[0]); if ($pilot->getExternalID()) { $url = edkURI::page('pilot_detail', $pilot->getExternalID(), 'plt_ext_id'); } else { $url = edkURI::page('pilot_detail', $pilots[0], 'plt_id'); } header("Location: " . htmlspecialchars_decode($url)); die; } else { header("Location: " . htmlspecialchars_decode(edkURI::page('about'))); die; } }
/** * Initialise the cachehandler. * * Sets a new cachehandler, choosing between memcache or filecache * depending on killboard settings. */ private static function init() { if (defined('DB_USE_MEMCACHE') && DB_USE_MEMCACHE == true) { self::$cachehandler = new CacheHandlerHashedMem(); } else { self::$cachehandler = new CacheHandlerHashed(); } }
/** * This function will compress data for storage in `tbl_cache`. * It is left to the user to define a unique hash for this data so that it can be * retrieved in the future. Optionally, a `$ttl` parameter can * be passed for this data. If this is omitted, it data is considered to be valid * forever. This function utilizes the Mutex class to act as a crude locking * mechanism. * * @see toolkit.Mutex * @throws DatabaseException * @param string $hash * The hash of the Cached object, as defined by the user * @param string $data * The data to be cached, this will be compressed prior to saving. * @param integer $ttl * A integer representing how long the data should be valid for in minutes. * By default this is null, meaning the data is valid forever * @param string $namespace * The namespace allows data to be grouped and saved so it can be * retrieved later. * @return boolean * If an error occurs, this function will return false otherwise true */ public function write($hash, $data, $ttl = null, $namespace = null) { if (!Mutex::acquire($hash, 2, TMP)) { return false; } $creation = time(); $expiry = null; $ttl = intval($ttl); if ($ttl > 0) { $expiry = $creation + $ttl * 60; } if (!($data = Cacheable::compressData($data))) { return false; } $this->delete($hash, $namespace); $this->Database->insert(array('hash' => $hash, 'creation' => $creation, 'expiry' => $expiry, 'data' => $data, 'namespace' => $namespace), 'tbl_cache'); Mutex::release($hash, TMP); return true; }
popup| <?php /** * @package EDK */ $kll_id = (int) edkURI::getArg('kll_id', 1); $kill = Cacheable::factory('Kill', $kll_id); $html = $kill->getRawMail(); event::call("killmail_popup", $html); $smarty->assign('rawMail', $html); echo $smarty->fetch(get_tpl("kill_mail"));
/** * Return a new object by ID. Will fetch from cache if enabled. * * @param mixed $id ID to fetch * @return Alliance */ static function getByID($id) { return Cacheable::factory(get_class(), $id); }
public function execute(array &$param_pool = null) { $result = new XMLElement($this->dsParamROOTELEMENT); $this->dsParamURL = $this->parseParamURL($this->dsParamURL); if (isset($this->dsParamXPATH)) { $this->dsParamXPATH = $this->__processParametersInString($this->dsParamXPATH, $this->_env); } $stylesheet = new XMLElement('xsl:stylesheet'); $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform')); $output = new XMLElement('xsl:output'); $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes')); $stylesheet->appendChild($output); $template = new XMLElement('xsl:template'); $template->setAttribute('match', '/'); $instruction = new XMLElement('xsl:copy-of'); // Namespaces if (isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS)) { foreach ($this->dsParamFILTERS as $name => $uri) { $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri); } } // XPath $instruction->setAttribute('select', $this->dsParamXPATH); $template->appendChild($instruction); $stylesheet->appendChild($template); $stylesheet->setIncludeHeader(true); $xsl = $stylesheet->generate(true); $cache_id = md5($this->dsParamURL . serialize($this->dsParamFILTERS) . $this->dsParamXPATH); $cache = new Cacheable(Symphony::Database()); $cachedData = $cache->read($cache_id); $writeToCache = false; $valid = true; $creation = DateTimeObj::get('c'); $timeout = isset($this->dsParamTIMEOUT) ? (int) max(1, $this->dsParamTIMEOUT) : 6; // Execute if the cache doesn't exist, or if it is old. if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) { if (Mutex::acquire($cache_id, $timeout, TMP)) { $ch = new Gateway(); $ch->init($this->dsParamURL); $ch->setopt('TIMEOUT', $timeout); $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*')); $data = $ch->exec(); $info = $ch->getInfoLast(); Mutex::release($cache_id, TMP); $data = trim($data); $writeToCache = true; // Handle any response that is not a 200, or the content type does not include XML, plain or text if ((int) $info['http_code'] !== 200 || !preg_match('/(xml|plain|text)/i', $info['content_type'])) { $writeToCache = false; $result->setAttribute('valid', 'false'); // 28 is CURLE_OPERATION_TIMEOUTED if ($info['curl_error'] == 28) { $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout))); } else { $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type']))); } return $result; // Handle where there is `$data` } elseif (strlen($data) > 0) { // If the XML doesn't validate.. if (!General::validateXML($data, $errors, false, new XsltProcess())) { $writeToCache = false; } // If the `$data` is invalid, return a result explaining why if ($writeToCache === false) { $element = new XMLElement('errors'); $result->setAttribute('valid', 'false'); $result->appendChild(new XMLElement('error', __('Data returned is invalid.'))); foreach ($errors as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $element->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($element); return $result; } // If `$data` is empty, set the `force_empty_result` to true. } elseif (strlen($data) == 0) { $this->_force_empty_result = true; } // Failed to acquire a lock } else { $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock, check that %s exists and is writable.', array('<code>Mutex</code>', '<code>' . TMP . '</code>')))); } // The cache is good, use it! } else { $data = trim($cachedData['data']); $creation = DateTimeObj::get('c', $cachedData['creation']); } // If `$writeToCache` is set to false, invalidate the old cache if it existed. if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) { $data = trim($cachedData['data']); $valid = false; $creation = DateTimeObj::get('c', $cachedData['creation']); if (empty($data)) { $this->_force_empty_result = true; } } // If `force_empty_result` is false and `$result` is an instance of // XMLElement, build the `$result`. if (!$this->_force_empty_result && is_object($result)) { $proc = new XsltProcess(); $ret = $proc->process($data, $xsl); if ($proc->isErrors()) { $result->setAttribute('valid', 'false'); $error = new XMLElement('error', __('Transformed XML is invalid.')); $result->appendChild($error); $element = new XMLElement('errors'); foreach ($proc->getError() as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $element->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($element); } elseif (strlen(trim($ret)) == 0) { $this->_force_empty_result = true; } else { if ($writeToCache) { $cache->write($cache_id, $data, $this->dsParamCACHE); } $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret)); $result->setAttribute('status', $valid === true ? 'fresh' : 'stale'); $result->setAttribute('creation', $creation); } } return $result; }
public function render_panel($context) { $config = $context['config']; switch ($context['type']) { case 'datasource_to_table': $ds = DatasourceManager::create($config['datasource'], NULL, false); if (!$ds) { $context['panel']->appendChild(new XMLElement('div', __('The Data Source with the name <code>%s</code> could not be found.', array($config['datasource'])))); return; } $param_pool = array(); $xml = $ds->grab($param_pool); if (!$xml) { return; } $xml = $xml->generate(); require_once TOOLKIT . '/class.xsltprocess.php'; $proc = new XsltProcess(); $data = $proc->process($xml, file_get_contents(EXTENSIONS . '/dashboard/lib/datasource-to-table.xsl')); $context['panel']->appendChild(new XMLElement('div', $data)); break; case 'rss_reader': require_once TOOLKIT . '/class.gateway.php'; require_once CORE . '/class.cacheable.php'; $cache_id = md5('rss_reader_cache' . $config['url']); $cache = new Cacheable(Administration::instance()->Database()); $data = $cache->check($cache_id); if (!$data) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $config['url']); $ch->setopt('TIMEOUT', 6); $new_data = $ch->exec(); $writeToCache = true; if ((int) $config['cache'] > 0) { $cache->write($cache_id, $new_data, $config['cache']); } $xml = $new_data; if (empty($xml) && $data) { $xml = $data['data']; } } else { $xml = $data['data']; } if (!$xml) { $xml = '<error>' . __('Error: could not retrieve panel XML feed.') . '</error>'; } require_once TOOLKIT . '/class.xsltprocess.php'; $proc = new XsltProcess(); $data = $proc->process($xml, file_get_contents(EXTENSIONS . '/dashboard/lib/rss-reader.xsl'), array('show' => $config['show'])); $context['panel']->appendChild(new XMLElement('div', $data)); break; case 'html_block': require_once TOOLKIT . '/class.gateway.php'; require_once CORE . '/class.cacheable.php'; $cache_id = md5('html_block_' . $config['url']); $cache = new Cacheable(Administration::instance()->Database()); $data = $cache->check($cache_id); if (!$data) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $config['url']); $ch->setopt('TIMEOUT', 6); $new_data = $ch->exec(); $writeToCache = true; if ((int) $config['cache'] > 0) { $cache->write($cache_id, $new_data, $config['cache']); } $html = $new_data; if (empty($html) && $data) { $html = $data['data']; } } else { $html = $data['data']; } if (!$html) { $html = '<p class="invalid">' . __('Error: could not retrieve panel HTML.') . '</p>'; } $context['panel']->appendChild(new XMLElement('div', $html)); break; case 'symphony_overview': $container = new XMLElement('div'); $dl = new XMLElement('dl'); $dl->appendChild(new XMLElement('dt', __('Website Name'))); $dl->appendChild(new XMLElement('dd', Symphony::Configuration()->get('sitename', 'general'))); $current_version = Symphony::Configuration()->get('version', 'symphony'); require_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init(); $ch->setopt('URL', 'https://api.github.com/repos/symphonycms/symphony-2/tags'); $ch->setopt('TIMEOUT', $timeout); $repo_tags = $ch->exec(); // tags request found if (is_array($repo_tags)) { $repo_tags = json_decode($repo_tags); $tags = array(); foreach ($repo_tags as $tag) { // remove tags that contain strings if (preg_match('/[a-zA]/i', $tag->name)) { continue; } $tags[] = $tag->name; } natsort($tags); rsort($tags); $latest_version = reset($tags); } else { $latest_version = $current_version; } $needs_update = version_compare($latest_version, $current_version, '>'); $dl->appendChild(new XMLElement('dt', __('Version'))); $dl->appendChild(new XMLElement('dd', $current_version . ($needs_update ? ' (<a href="http://getsymphony.com/download/releases/version/' . $latest_version . '/">' . __('Latest is %s', array($latest_version)) . "</a>)" : ''))); $container->appendChild(new XMLElement('h4', __('Configuration'))); $container->appendChild($dl); $entries = 0; foreach (SectionManager::fetch() as $section) { $entries += EntryManager::fetchCount($section->get('id')); } $dl = new XMLElement('dl'); $dl->appendChild(new XMLElement('dt', __('Sections'))); $dl->appendChild(new XMLElement('dd', (string) count(SectionManager::fetch()))); $dl->appendChild(new XMLElement('dt', __('Entries'))); $dl->appendChild(new XMLElement('dd', (string) $entries)); $dl->appendChild(new XMLElement('dt', __('Data Sources'))); $dl->appendChild(new XMLElement('dd', (string) count(DatasourceManager::listAll()))); $dl->appendChild(new XMLElement('dt', __('Events'))); $dl->appendChild(new XMLElement('dd', (string) count(EventManager::listAll()))); $dl->appendChild(new XMLElement('dt', __('Pages'))); $dl->appendChild(new XMLElement('dd', (string) count(PageManager::fetch()))); $container->appendChild(new XMLElement('h4', __('Statistics'))); $container->appendChild($dl); $context['panel']->appendChild($container); break; case 'markdown_text': $formatter = TextformatterManager::create($config['formatter']); $html = $formatter->run($config['text']); $context['panel']->appendChild(new XMLElement('div', $html)); break; } }
public function add(Cacheable $fs) { $this->annotations->merge($fs->getAnnotations()); $this->objs = array_merge($this->objs, $fs->objs); }
private function __importStep2Page() { // Store the CSV data in the cache table, so the CSV file will not be stored on the server $cache = new Cacheable(Symphony::Database()); // Get the nodes provided by this CSV file: $csv = new parseCSV(); $csv->auto($_FILES['csv-file']['tmp_name']); $cache->write('importcsv', serialize($csv), 60 * 60 * 24); // Store for one day $sectionID = $_POST['section']; // Generate the XML: $xml = new XMLElement('data', null, array('section-id' => $sectionID)); // Get the fields of this section: $fieldsNode = new XMLElement('fields'); $sm = new SectionManager($this); $section = $sm->fetch($sectionID); $fields = $section->fetchFields(); foreach ($fields as $field) { $fieldsNode->appendChild(new XMLElement('field', $field->get('label'), array('id' => $field->get('id')))); } $xml->appendChild($fieldsNode); $csvNode = new XMLElement('csv'); foreach ($csv->titles as $key) { $csvNode->appendChild(new XMLElement('key', $key)); } $xml->appendChild($csvNode); // Generate the HTML: $xslt = new XSLTPage(); $xslt->setXML($xml->generate()); $xslt->setXSL(EXTENSIONS . '/importcsv/content/step2.xsl', true); $this->Form->setValue($xslt->generate()); }
/** * * Get the size of the object-cache in bytes. * * @param string $backend * @return int */ private function getCacheSize($backend = 'file') { $size = 0; if ($backend === 'file') { if ($files = Cacheable::get_cache_files()) { foreach ($files as $file) { $size += $file->Size; } } return $size; } return 'Not available.'; }
/** * @param SimpleXMLElement $inv * @param Kill $kill * @param string $time YYYY-mm-dd hh:ss * @return boolean false on error */ private function processInvolved($inv, &$kill, $time) { if (!(int) $inv['shipTypeID'] && !(int) $inv['weaponTypeID'] && !(int) $inv['characterID'] && !(string) $inv['characterName']) { $this->parsemsg[] = "Involved party blank."; return false; } $npc = false; $ship = Ship::getByID((int) $inv['shipTypeID']); $weapon = Cacheable::factory('Item', (int) $inv['weaponTypeID']); $alliance = new Alliance(); if ((int) $inv['allianceID']) { $alliance = Alliance::add(strval($inv['allianceName']), (int) $inv['allianceID']); } else { if ((int) $inv['factionID']) { $alliance = Alliance::add(strval($inv['factionName']), (int) $inv['factionID']); } else { $alliance = Alliance::add("None"); } } // get alliance from corp if ship is any kind of tower $shipClassID = $ship->getClass()->getID(); if ($shipClassID == 35 || $shipClassID == 36 || $shipClassID == 37) { $corpByName = Corporation::lookup(strval($inv['corporationName'])); if ($corpByName) { $alliance = $corpByName->getAlliance(); } } $corp = Corporation::add(strval($inv['corporationName']), $alliance, $time, (int) $inv['corporationID']); $charid = (int) $inv['characterID']; $charname = (string) $inv['characterName']; // Allow for blank names for consistency with CCP API. if (preg_match("/(Mobile (Large|Medium|Small) Warp Disruptor I?I?|\\w+ Control Tower( \\w+)?)/", $charname)) { $charname = $inv['corporationName'] . ' - ' . $charname; $charid = 0; } else { if ($charname == "" && preg_match("/(Mobile \\w+ Warp|\\w+ Control Tower( \\w+)?)/", $weapon->getName())) { $charname = $inv['corporationName'] . ' - ' . $weapon->getName(); $charid = 0; } else { if ($charname == "" && !$charid) { // NPC ship $ship = Ship::lookup("Unknown"); $weapon = Item::getByID((int) $inv['shipTypeID']); $charname = $weapon->getName(); $npc = true; $charid = $weapon->getID(); } else { if ($charname == "" && $charid) { // Bugged kill $this->parsemsg[] = "Involved party has blank pilot name."; return false; } } } } $pilot = Pilot::add((string) $charname, $corp, $time, $charid); $iparty = new InvolvedParty($pilot->getID(), $corp->getID(), $alliance->getID(), (double) $inv['securityStatus'], $ship->getID(), $weapon->getID(), (int) $inv['damageDone']); $kill->addInvolvedParty($iparty); if ((int) $inv['finalBlow'] == 1) { $kill->setFBPilotID($pilot->getID()); } $this->npcOnly = $this->npcOnly && $npc; return true; }
/** * Helper function to build Cache information block * * @param XMLElement $wrapper * @param Cacheable $cache * @param string $cache_id */ public static function buildCacheInformation(XMLElement $wrapper, Cacheable $cache, $cache_id) { $cachedData = $cache->check($cache_id); if (is_array($cachedData) && !empty($cachedData) && time() < $cachedData['expiry']) { $a = Widget::Anchor(__('Clear now'), SYMPHONY_URL . getCurrentPage() . 'clear_cache/'); $wrapper->appendChild(new XMLElement('p', __('Cache expires in %d minutes. %s', array(($cachedData['expiry'] - time()) / 60, $a->generate(false))), array('class' => 'help'))); } else { $wrapper->appendChild(new XMLElement('p', __('Cache has expired or does not exist.'), array('class' => 'help'))); } }
$plt_id = (int) edkURI::getArg('i'); if ($plt_id) { $pilot = Cacheable::factory('Pilot', $plt_id); } else { $plt_ext_id = (int) edkURI::getArg('ext'); if ($plt_ext_id) { $pilot = new Pilot(0, $plt_id); $plt_id = $pilot->getID(); } else { $plt_id = edkURI::getArg('id'); if (!$plt_id) { errorPic('No pilot id specified.'); $pilot = new Pilot(); } else { if ($plt_id < 1000000) { $pilot = Cacheable::factory('Pilot', $plt_id); } else { $pilot = new Pilot(0, $plt_id); $plt_id = $pilot->getID(); } } } } if (!$plt_ext_id) { $plt_ext_id = $pilot->getExternalID(); } // If we still don't have an external ID then just use the internal for names. if (!$plt_ext_id) { $plt_ext_id = $plt_id; } if (!$pilot->exists()) {
public $member2 = 'abc'; function changeDate($var) { echo "No cache! Heavy read here!..."; sleep(2); echo "done!\n"; // Lets say this is some heavy compyting here, and the results are written to member1 and 2 $this->member1[] = $var; $this->member2 .= $var; } } // At a later stage, or another script $obj = new obj_to_cache(); if (!Cacheable::sCacheRestore($obj, 'changed-str1')) { $obj->changeDate('str1'); Cacheable::sCacheStore($obj, 'changed-str1', CacheExpire::create()->timeout(60)); } else { // Cache was hit! echo "Cache hit!\n"; } var_dump($obj); /** * Outputs (1st execute): * No cache! Heavy read here!...done! object(obj_to_cache)#1 (2) { ["member1"]=> array(2) { ["a"]=> int(1) [0]=>
/** * @deprecated * @return Item */ function getWeapon() { return Cacheable::factory('Item', $this->weaponid); }