public function loadCachedCategories() { if ($this->cache) { $result = $this->cache->fetch($this->cacheKey); if (isset($result['categories']) && isset($result['parentChildIds'])) { $this->categories = $result['categories']; foreach ($this->categories as $cat) { $cat->setCategoryManager($this); } $this->parentChildIds = $result['parentChildIds']; } } }
public static function cacheTree($path, $force = false) { // split path into array if (is_string($path)) { $path = Site::splitPath($path); } // check if this tree has already been cached $cacheKey = 'cacheTree:' . implode('/', $path); if (!Site::$autoPull || !$force && Cache::fetch($cacheKey)) { return 0; } Cache::store($cacheKey, true); // get tree map from parent $remoteTree = Emergence::resolveCollectionFromParent($path); if (!$remoteTree) { return 0; } $filesResolved = 0; $startTime = time(); foreach ($remoteTree['files'] as $remotePath => $remoteFile) { $node = Site::resolvePath($remotePath); if ($node && $node->Timestamp >= $startTime) { $filesResolved++; } } return $filesResolved; }
private function _verifySign($domain, $text, $sign) { include_once KFL_DIR . '/Libs/Cache.class.php'; $filename = $domain . ".txt"; $cache = new Cache(86400 * 300, 0); $cache->setCacheStore("file"); // or memcache $cache->setCacheDir(APP_TEMP_DIR); $cache->setCacheFile($filename); if ($cache->isCached()) { $client = unserialize($cache->fetch()); } else { require_once 'ClientModel.class.php'; $ClientModel = new ClientModel(); $client = $ClientModel->getClientByName($domain); if ($client) { $cache->save(serialize($client)); } else { return false; } } $this->_private_key = $client['private_key']; if (hmac($this->_private_key, $text, 'sha1') == $sign) { return true; } else { return false; } }
public function fetchCache() { $this->pocDispatcher->dispatch(PocEventNames::FUNCTION_FETCHCACHE_BEGINNING, new BaseEvent($this)); $this->output = $this->cache->fetch($this->hasher->getKey()); if ($this->output) { $this->pocDispatcher->dispatch(PocEventNames::GET_OUTPUT_FROM_CACHE, new BaseEvent($this)); } }
public function __construct($filter, $start, $count) { $cache = new Cache('note_list', false); if (!($metaList = $cache->fetch(compact('filter', 'start', 'count')))) { $metaList = Evernote::_noteStore()->findNotesMetadata(AUTH_TOKEN, $filter, $start, $count, new EDAM\NoteStore\NotesMetadataResultSpec()); $cache->store($metaList); } $this->_metaList = $metaList; $this->total = $metaList->totalNotes; }
public function load($token) { if (!empty($token)) { $cache = new Cache('user'); if (!($user = $cache->fetch($token))) { $user = self::_userStore()->getUser($token); $cache->store($user); } $this->user = $user; } return $this; }
public static function getByHandle($collectionID, $handle) { $cacheKey = static::getCacheKey($collectionID, $handle); if (false === ($record = Cache::fetch($cacheKey))) { $record = DB::oneRecord('SELECT * FROM `%s` WHERE CollectionID = %u AND Handle = "%s" ORDER BY ID DESC LIMIT 1', array(static::$tableName, $collectionID, DB::escape($handle))); // don't cache the temporary "Phantom" records created as placeholders during write if ($record['Status'] != 'Phantom') { Cache::store($cacheKey, $record); } } return $record ? new static($record['Handle'], $record) : null; }
public function load($guid) { if (!empty($guid)) { $cache = new Cache('notebook'); if (!($notebook = $cache->fetch($guid))) { $notebook = self::_noteStore()->getNotebook(AUTH_TOKEN, $guid); $cache->store($notebook); } $this->notebook = $notebook; } return $this; }
/** * Loads a HTTP resource. * * @param string $url * @param array $parameters * * @return array */ public function loadResource($url, $parameters) { $signature = $this->createSignature($url, $parameters); if ($this->cache->contains($signature)) { return $this->cache->fetch($signature); } $parameters['format'] = 'json'; $parameters['api_key'] = $this->config->getApiKey(); $url = $this->config->getApiEndpoint() . $this->buildQueryUrl($url, $parameters); $response = $this->guzzle->request('GET', $url); $body = $this->processResponse($response); $this->cache->save($signature, $body['results']); return $body['results']; }
function Dwoo_Plugin_rss(Dwoo_Core $dwoo, $feed, $assign = 'rss_items', $limit = 5, $cacheTime = 60) { $cacheKey = 'rss:' . $feed; if (false === ($rss = Cache::fetch($cacheKey))) { $rss = new RssReader(); $rss->load($feed); Cache::store($cacheKey, $rss, $cacheTime); } if ($limit) { $dwoo->assignInScope(array_slice($rss->getItems(), 0, $limit), $assign); } else { $dwoo->assignInScope($rss->getItems(), $assign); } return ''; }
public static function getSourceCode($minifier, $cacheHashOrSourceReport, $skipCache = false) { $cacheHash = is_string($cacheHashOrSourceReport) ? $cacheHashOrSourceReport : $cacheHashOrSourceReport['hash']; $cacheKey = "{$minifier}:{$cacheHash}"; if (!$skipCache && ($code = Cache::fetch($cacheKey))) { return $code; } if (is_array($cacheHashOrSourceReport) && is_array($cacheHashOrSourceReport['files'])) { $code = ''; foreach ($cacheHashOrSourceReport['files'] as $path => $fileData) { $code .= $minifier::minify(file_get_contents(SiteFile::getRealPathByID($fileData['ID']))); } Cache::store($cacheKey, $code); return $code; } return null; }
/** Retrieve from cache; or save SQL query results to cache if not previously executed @param $_cmd string @param $_bind mixed @param $_id string @param $_ttl integer @private **/ private static function sqlCache($_cmd, $_bind = NULL, $_id = 'DB', $_ttl = 0) { $_hash = 'sql.' . F3::hashCode($_cmd); $_db =& F3::$global[$_id]; $_cached = Cache::cached($_hash); if ($_cached && time() - $_cached['time'] < $_ttl) { // Gather cached SQL queries for profiler F3::$global['PROFILE'][$_id]['cache'][$_cmd]++; // Retrieve from cache $_db = Cache::fetch($_hash); } else { self::sqlExec($_cmd, NULL, $_id); if (!F3::$global['ERROR']) { // Save to cache unset($_db['pdo'], $_db['query']); Cache::store($_hash, $_db); } } }
/** Retrieve from cache; or save SQL query results to cache if not previously executed @param $_cmd string @param $_bind mixed @param $_id string @param $_ttl integer @private **/ private static function sqlCache($_cmd, $_bind = NULL, $_id = 'DB', $_ttl = 0) { $_hash = 'sql.' . F3::hashCode($_cmd); $_db =& F3::$global[$_id]; $_cached = Cache::cached($_hash); if ($_cached && time() - $_cached['time'] < $_ttl) { // Gather cached SQL queries for profiler F3::$global['PROFILE'][$_id]['cache'][$_cmd]++; // Retrieve from cache, unserialize, and restore DB variable $_db = unserialize(gzinflate(Cache::fetch($_hash))); } else { self::sqlExec($_cmd, NULL, $_id); if (!F3::$global['ERROR']) { // Serialize, compress and cache unset($_db['pdo'], $_db['query']); Cache::store($_hash, gzdeflate(serialize($_db))); } } }
public static function getFeedData($url, $cacheKey = false, $cacheTime = null) { if ($cacheTime === null) { $cacheTime = static::$defaultCacheTime; } // get context if (!isset(static::$_streamContext)) { static::$_streamContext = stream_context_create(array('http' => array('timeout' => static::$requestTimeout))); } $failureKey = 'fail:' . $cacheKey; if (!($twitterData = Cache::fetch($cacheKey)) && !Cache::fetch($failureKey)) { $twitterData = @json_decode(@file_get_contents($url, false, static::$_streamContext), true); if (empty($twitterData)) { Cache::store($failureKey, true, static::$failureDelay); } Cache::store($cacheKey, $twitterData, $cacheTime); } return $twitterData ? $twitterData : false; }
function weather($code) { $code = str_replace('-', ' ', $code); $code = urlencode($code); $cache = new Cache(); $cache_name = 'weather_' . $code; $xml = ''; $use_errors = libxml_use_internal_errors(true); if (!($xml = simplexml_load_string($cache->fetch($cache_name)))) { $result = @file_get_contents('http://api.openweathermap.org/data/2.5/forecast/daily?q=' . $code . ',uk&mode=xml&units=metric&cnt=7'); if (!$result) { return false; } $cache->store($cache_name, $result, 86000); $xml = simplexml_load_string($result); } libxml_clear_errors(); libxml_use_internal_errors($use_errors); return $xml; }
public function lookupEpisode($seriesid, $show) { //http://www.thetvdb.com/api/5F84ECB91B42D719/series/78804/default/1/1 $season = ltrim(str_replace('S', '', $show['season']), '0'); $ep = ltrim(str_replace('E', '', $show['episode']), '0'); $cache = new Cache(); $apiresponse = false; $url = $this->MIRROR . '/api/' . self::APIKEY . '/series/' . $seriesid . '/default/' . $season . "/" . $ep; if ($cache->exists($url)) { $apiresponse = $cache->fetch($url); } if (!$apiresponse) { $apiresponse = getUrl($url); } if ($apiresponse) { $TheTVDBAPIXML = @simplexml_load_string($apiresponse); if (!$TheTVDBAPIXML) { return false; } $cache->store($url, $apiresponse); return array('id' => (string) $TheTVDBAPIXML->Episode->id, 'summary' => (string) $TheTVDBAPIXML->Episode->Overview, 'name' => (string) $TheTVDBAPIXML->Episode->EpisodeName, 'director' => (string) $TheTVDBAPIXML->Episode->Director, 'epabsolute' => (string) $TheTVDBAPIXML->Episode->absolute_number, 'writer' => (string) $TheTVDBAPIXML->Episode->Writer, 'gueststars' => (string) $TheTVDBAPIXML->Episode->GuestStars, 'rating' => (int) $TheTVDBAPIXML->Episode->Rating, 'airdate' => (string) $TheTVDBAPIXML->Episode->FirstAired, 'season' => $season, 'number' => (string) $TheTVDBAPIXML->Episode->EpisodeNumber); } return false; }
function Dwoo_Plugin_facebook(Dwoo $dwoo, $page, $assign = 'fbFeed', $limit = 5, $since = false, $cacheTime = 60, $acessToken = '207886205923030|XNMhiHAb8MQp6KmSSIzfd3QH560') { $url = 'https://graph.facebook.com/' . urlencode($page) . '/feed?access_token=' . urlencode($acessToken); $cacheKey = 'fbFeed:' . $page; if ($limit) { $url .= '&limit=' . urlencode($limit); $cacheKey .= ';limit:' . $limit; } if ($since) { $url .= '&since=' . urlencode($since); $cacheKey .= ';since:' . $since; } if (false === ($result = Cache::fetch($cacheKey))) { $data = file_get_contents($url); $result = $data ? json_decode($data, true) : null; Cache::store($cacheKey, $result, $cacheTime); } if (!empty($result['data']) && is_array($result['data'])) { $dwoo->assignInScope($result['data'], $assign); } else { $dwoo->assignInScope(array(), $assign); } return ''; }
public static function getCache($id = null) { $class = get_called_class(); $cache = constant('Cache::' . strtoupper($class)); if (Cache::hasCache(strtolower($cache))) { $primary = constant($class . '::PRIMARY'); if (empty($id)) { $id = $this->{$primary}; } $object = Cache::fetch($cache, $id); if (is_null($object)) { $method = 'selectBy' . str_replace(' ', '', ucwords(str_replace('_', ' ', $primary))); $object = call_user_func($class . '::get()->' . $method, $id); if (!empty($object->{$primary})) { Cache::store($cache, $object, $id); } } return $object; } return null; }
/** * Read user account * * @param integer [$user_id] The ID of the user to read * @return array|boolean */ public function read_user($user_id) { // Fetch cached copy of user details and return if ($user_details = Cache::fetch('user_' . $user_id)) { return $user_details; } // Read details from database if (!($stmt = Database::instance()->prepare("select `id`, `group_id`, `created`, `updated`, `{$this->config->username_field}` from {$this->config->user_table} where `id` = ?"))) { return false; } $stmt->bind_param('i', $user_id); $stmt->execute(); $stmt->bind_result($id, $group_id, $created, $updated, $username); $stmt->fetch(); $user_details = array('id' => $id, 'created' => $created, 'updated' => $updated, $this->config->username_field => $username); $stmt->close(); // Read group details $user_details['group'] = $this->read_groups($group_id); // Cache user details Cache::store('user_' . $user_id, $user_details); return $user_details; }
protected function _init() { # init _data $data = array(); if (preg_match("#<pre>(.*)</pre>#ms", $this->note->content, $matches)) { if (preg_match_all("#(\\w+):(.*)\n#", rtrim($matches[1]) . "\n", $matches)) { foreach ($matches[1] as $key => $field) { if ($value = $matches[2][$key]) { if ($this->{$field} instanceof Types\Set) { $this->{$field}->add(explode(',', $value)); } else { $data[$field] = $value; } } } } } $this->_data = str_replace(array('\\\\', '\\n'), array("\\", "\n"), $data); # init _tags if (!empty($this->note->tagGuids)) { $cache = new Cache('note_tag'); foreach ($this->note->tagGuids as $guid) { if (!($tag = $cache->fetch($guid))) { $tag = self::_noteStore()->getTag(AUTH_TOKEN, $guid); $cache->store($tag); } $this->tags->add($tag->name); $this->_tags[$tag->guid] = $tag->name; } } return $this; }
/** Send HTTP/S request to another host; Forward headers received (if QUIET variable is FALSE) and return content; Respect HTTP 30x redirects if last argument is TRUE @return mixed @param $_pattern string @param $_query string @param $_reqhdrs array @param $_follow boolean @public **/ public static function http($_pattern, $_query = '', $_reqhdrs = array(), $_follow = TRUE) { // Check if valid route pattern list($_method, $_route) = F3::checkRoute($_pattern); // Content divider $_div = chr(0); // Determine if page is in cache $_hash = 'url.' . F3::hashCode($_pattern); $_cached = Cache::cached($_hash); if ($_cached) { // Retrieve from cache $_buffer = Cache::fetch($_hash); $_rcvhdrs = strstr($_buffer, $_div, TRUE); $_response = substr(strstr($_buffer, $_div), 1); // Find out if cache is stale $_expires = NULL; foreach (explode(self::EOL, $_rcvhdrs) as $_hdr) { if (preg_match('/^' . F3::HTTP_Expires . ':(.+)/', $_hdr, $_match)) { $_expires = strtotime($_match[1]); break; } } if (!is_null($_expires) && time() < $_expires) { // Cached page is still fresh foreach (explode(self::EOL, $_rcvhdrs) as $_hdr) { F3::$global['HEADERS'][] = $_hdr; if (preg_match('/' . F3::HTTP_Content . '/', $_hdr)) { // Forward HTTP header header($_hdr); } } return $_response; } } $_url = parse_url($_route); if (!$_url['path']) { // Set to Web root $_url['path'] = '/'; } if ($_method != 'GET') { if ($_url['query']) { // Non-GET method; Query is distinct from URI $_query = $_url['query']; $_url['query'] = ''; } } else { if ($_query) { // GET method; Query is integral part of URI $_url['query'] = $_query; $_query = ''; } } // Set up host name and TCP port for socket connection if (preg_match('/https/', $_url['scheme'])) { if (!$_url['port']) { $_url['port'] = 443; } $_target = 'ssl://' . $_url['host'] . ':' . $_url['port']; } else { if (!$_url['port']) { $_url['port'] = 80; } $_target = $_url['host'] . ':' . $_url['port']; } $_socket = @fsockopen($_target, $_url['port'], $_errno, $_text); if (!$_socket) { // Can't establish connection trigger_error($_text); return FALSE; } // Send HTTP request fputs($_socket, $_method . ' ' . $_url['path'] . ($_url['query'] ? '?' . $_url['query'] : '') . ' ' . 'HTTP/1.0' . self::EOL . F3::HTTP_Host . ': ' . $_url['host'] . self::EOL . F3::HTTP_Agent . ': Mozilla/5.0 (' . 'compatible;' . F3::TEXT_AppName . ' ' . F3::TEXT_Version . ')' . self::EOL . ($_reqhdrs ? implode(self::EOL, $_reqhdrs) . self::EOL : '') . ($_method != 'GET' ? 'Content-Type: ' . 'application/x-www-form-urlencoded' . self::EOL . 'Content-Length: ' . strlen($_query) . self::EOL : '') . F3::HTTP_AcceptEnc . ': gzip' . self::EOL . ($_cached ? F3::HTTP_Cache . ': max-age=86400' . self::EOL : '') . F3::HTTP_Connect . ': close' . self::EOL . self::EOL . $_query . self::EOL . self::EOL); $_found = FALSE; $_expires = FALSE; $_gzip = FALSE; // Set connection timeout parameters stream_set_blocking($_socket, TRUE); stream_set_timeout($_socket, ini_get('default_socket_timeout')); $_info = stream_get_meta_data($_socket); // Get headers and response while (!feof($_socket) && !$_info['timed_out']) { $_response .= fgets($_socket, 4096); // MDFK97 $_info = stream_get_meta_data($_socket); if (!$_found) { $_rcvhdrs = strstr($_response, self::EOL . self::EOL, TRUE); if ($_rcvhdrs) { $_found = TRUE; if (PHP_SAPI != 'cli' && !headers_sent()) { ob_start(); if ($_follow && preg_match('/HTTP\\/1\\.\\d\\s30\\d/', $_rcvhdrs)) { // Redirection preg_match('/' . F3::HTTP_Location . ':\\s*(.+?)/', $_rcvhdrs, $_loc); return self::http($_method . ' ' . $_loc[1], $_query, $_reqhdrs); } foreach (explode(self::EOL, $_rcvhdrs) as $_hdr) { F3::$global['HEADERS'][] = $_hdr; if (!F3::$global['QUIET'] && preg_match('/' . F3::HTTP_Content . '/', $_hdr)) { // Forward HTTP header header($_hdr); } elseif (preg_match('/^' . F3::HTTP_Encoding . ':\\s*.*gzip/', $_hdr)) { // Uncompress content $_gzip = TRUE; } elseif (preg_match('/^' . F3::HTTP_Expires . ':\\s*.+/', $_hdr)) { // Cache this page $_expires = TRUE; } } ob_end_flush(); if ($_flag) { Cache::store($_hash, $_rcvhdrs . $_div . $_response); } } // Split content from HTTP response headers $_response = substr(strstr($_response, self::EOL . self::EOL), 4); } } } fclose($_socket); if ($_info['timed_out']) { trigger_error(self::TEXT_Timeout); return FALSE; } if (PHP_SAPI != 'cli' && !headers_sent()) { if ($_gzip) { $_response = gzinflate(substr($_response, 10)); } if ($_expires) { Cache::store($_hash, $_rcvhdrs . $_div . $_response); } } // Return content return $_response; }
/** * Perform a single query * * @param string $query * @param bool $useCache * @param string|int $cacheTTL * @return bool|array */ public function query($query, $useCache = false, $cacheTTL = '') { if ($query == "") { return false; } if ($useCache) { $cache = new Cache(); if ($cache->enabled && $cache->exists($query)) { $ret = $cache->fetch($query); if ($ret !== false) { return $ret; } } } $result = self::$instance->query($query)->fetchAll(); if ($result === false || $result === true) { return array(); } if ($useCache) { if ($cache->enabled) { $cache->store($query, $result, $cacheTTL); } } return $result; }
/** * Query the indexer directly. Returns an array of the results, unless * there was an error in which case ``false`` is returned. However, if * Sphinx returns an "invalid query" error (1064), then an empty result * array is returned. Note that an empty "result array" is not the same as * an empty array and will instead look like:: * * array({"_totalrows": 0}) * * If ``$lookupQuery`` is an empty string, then the results returned will * be the data from the index--this is not guaranteed to be the most recent * data that is in the MySQL database. If you absolutely need the most * recent data from MySQL, then ``$lookupQuery`` should be a valid SQL * query that has contains "releases.ID IN (%s)". * * @param string $sphinxQuery The raw SphinxQL query. * @param string $lookupQuery The SQL to use to lookup the results. * @param bool/int $useCache The ttl to store the item in the cache. * @return array|false */ public function searchDirect($sphinxQuery, $lookupQuery = "", $useCache = false) { $cache = new Cache(); if ($useCache !== false && $cache->enabled && $cache->exists($sphinxQuery)) { $ret = $cache->fetch($sphinxQuery); if ($ret !== false) { return $ret; } } // Connect to Sphinx $hostport = explode(":", $this->site->sphinxserverhost); $sdb = mysqli_connect($hostport[0], "root", "", "", $hostport[1]); if (!$sdb) { // Couldn't connect to Sphinx. return false; } // Get the results from Sphinx. $lev = error_reporting(); error_reporting(0); $result = mysqli_query($sdb, $sphinxQuery); error_reporting($lev); $error = mysqli_error($sdb); // A 1064 error means that the query is invalid, so we don't care // about that. if ($error && mysqli_errno($sdb) != 1064) { // All other errors we will considered a failure. return false; } // Get the query metadata. $meta = array(); $mresult = mysqli_query($sdb, "SHOW META"); if (!$mresult) { return false; } while ($row = mysqli_fetch_row($mresult)) { $meta[$row[0]] = $row[1]; } $results = array(); if ($result) { while ($row = mysqli_fetch_assoc($result)) { if ($lookupQuery) { // Save the IDs for a batch lookup. $results[] = $row["id"]; } else { $results[] = $row; } } } if ($lookupQuery && count($results) > 0) { $ndb = new DB(); $sql = sprintf($lookupQuery, implode(",", $results)); $result = $ndb->queryDirect($sql); if ($result) { $results = array(); while ($row = $ndb->getAssocArray($result)) { $results[] = $row; } } } $count = 0; if (count($results) > 0 && array_key_exists("total", $meta)) { $count = (int) $meta["total_found"]; $results[0]["_totalrows"] = $count > MAX_MATCHES ? MAX_MATCHES : $count; } if ($useCache !== false && $cache->enabled) { $cache->store($sphinxQuery, $results, $useCache); } return $results; }
} $pageData['currentMeetup'] = $currentMeetup; $pageData['nextMeetup'] = $nextMeetup; $pageData['futureMeetups'] = $meetups; // projects $pageData['projectsTotal'] = Laddr\Project::getCount(); $pageData['projectsTags']['byTech'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "tech.%"'), 'itemConditions' => array('ContextClass' => Laddr\Project::getStaticRootClass()))); $pageData['projectsTags']['byTopic'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "topic.%"'), 'itemConditions' => array('ContextClass' => Laddr\Project::getStaticRootClass()))); $pageData['projectsTags']['byEvent'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "event.%"'), 'itemConditions' => array('ContextClass' => Laddr\Project::getStaticRootClass()))); $pageData['projectsStages'] = Laddr\Project::getStagesSummary(); // members $pageData['membersTotal'] = Emergence\People\Person::getCount(); $pageData['membersTags']['byTech'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "tech.%"'), 'itemConditions' => array('ContextClass' => Emergence\People\Person::getStaticRootClass()))); $pageData['membersTags']['byTopic'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "topic.%"'), 'itemConditions' => array('ContextClass' => Emergence\People\Person::getStaticRootClass()))); // build activity stream if (!($pageData['activity'] = Cache::fetch('home-activity'))) { $existingTables = \DB::allValues('table_name', 'SELECT table_name FROM information_schema.TABLES WHERE TABLE_SCHEMA = SCHEMA()'); $activityQueries = []; if (in_array(Emergence\CMS\AbstractContent::$tableName, $existingTables)) { $activityQueries[] = sprintf('SELECT' . ' ID, Class, Published AS Timestamp' . ' FROM `%s`' . ' WHERE' . ' Class = "%s" AND' . ' Visibility = "Public" AND' . ' Status = "Published" AND' . ' (Published IS NULL OR Published <= CURRENT_TIMESTAMP)', Emergence\CMS\AbstractContent::$tableName, DB::escape(Emergence\CMS\BlogPost::class)); } if (in_array(Laddr\ProjectUpdate::$tableName, $existingTables)) { $activityQueries[] = sprintf('SELECT ID, Class, Created AS Timestamp FROM `%s`', Laddr\ProjectUpdate::$tableName); } if (in_array(Laddr\ProjectBuzz::$tableName, $existingTables)) { $activityQueries[] = sprintf('SELECT ID, Class, Published AS Timestamp FROM `%s`', Laddr\ProjectBuzz::$tableName); } if (count($activityQueries)) { $pageData['activity'] = array_map(function ($result) { return $result['Class']::getByID($result['ID']); }, DB::allRecords(implode(' UNION ', $activityQueries) . ' ORDER BY Timestamp DESC LIMIT 10'));
public function fetchCache($key) { $cache = new Cache(); if ($cache->enabled && $cache->exists($key)) { $ret = $cache->fetch($key); if ($ret !== false) { return $ret; } } return false; }
/** Intercept calls to static methods of non-F3 classes and proxy for the called class if found in the autoload folder @return mixed @param $_func string @param $_args array @public **/ public static function __callStatic($_func, array $_args) { foreach (explode('|', self::$global['AUTOLOAD']) as $_auto) { foreach (glob(realpath($_auto) . '/*.php') as $_file) { $_class = strstr(basename($_file), '.php', TRUE); $_hash = 'reg.' . self::hashCode(strtolower($_class)); $_cached = Cache::cached($_hash); $_methods = array(); if (!$_cached || $_cached['time'] < filemtime($_file)) { if (!in_array(self::fixSlashes($_file), array_map('self::fixSlashes', get_included_files()))) { include $_file; } if (class_exists($_class, FALSE)) { // Update cache $_methods = array_map('strtolower', get_class_methods($_class)); Cache::store($_hash, $_methods); } } else { // Retrieve from cache $_methods = Cache::fetch($_hash); } if (in_array(strtolower($_func), $_methods)) { // Execute onLoad method if defined if (in_array('onload', $_methods)) { call_user_func(array($_class, 'onload')); self::$global['LOADED'][] = strtolower($_class); } // Proxy for method in autoload class return call_user_func_array(array($_class, $_func), $_args); } } } self::$global['CONTEXT'] = __CLASS__ . '::' . $_func; trigger_error(self::TEXT_Method); return FALSE; }
public static function getRecordByHandle($handle, $parentID = null, $remote = false, $includeDeleted = false) { // build cache key and query conditions $cacheKey = static::getCacheKey($handle, $parentID, $remote); $where = array(); if ($parentID) { $where[] = sprintf('ParentID = %u', $parentID); } else { $where[] = sprintf('Site = "%s"', $remote ? 'Remote' : 'Local'); $where[] = 'ParentID IS NULL'; } $where[] = sprintf('Handle = "%s"', DB::escape($handle)); if (!$includeDeleted) { $where[] = 'Status = "Normal"'; } else { $cacheKey .= '?deleted'; } // attempt to get from cache if (false !== ($record = Cache::fetch($cacheKey))) { return $record; } // query and cache $record = DB::oneRecord('SELECT * FROM `%s` WHERE (%s) ORDER BY ID DESC LIMIT 1', array(static::$tableName, implode(') AND (', $where))); Cache::store($cacheKey, $record); return $record; }
public static function mapDependentCacheKey($recordID, $cacheKey) { $cacheMapKey = sprintf('ar/%s/m/%s', static::$tableName, $recordID); $cacheMap = Cache::fetch($cacheMapKey); if (is_array($cacheMap)) { if (!in_array($cacheKey, $cacheMap)) { $cacheMap[] = $cacheKey; } } else { $cacheMap = array($cacheKey); } Cache::store($cacheMapKey, $cacheMap); }
public function getMicroloader($mode = 'production', $debug = null) { $debug = $debug === null ? !empty($_GET['jsdebug']) : $debug; $cacheKey = "app/{$this->_name}/microloader/{$mode}"; if ($debug || !($code = Cache::fetch($cacheKey))) { $node = static::getAsset("microloaders/{$mode}.js"); $code = $node ? file_get_contents($node->RealPath) : ''; if (!$debug) { $code = JSMin::minify($code); Cache::store($cacheKey, $code); } } return $code; }
public static function loadConfig($className) { $cacheKey = 'class-config:' . $className; if (!($configFileIds = Cache::fetch($cacheKey))) { $configFileIds = array(); // look for primary config file if ($lastNsPos = strrpos($className, '\\')) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); $path = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } else { $path = ''; } $path .= str_replace('_', DIRECTORY_SEPARATOR, $className); $configFileNode = Site::resolvePath("php-config/{$path}.config.php"); // Fall back on looking for Old_School_Underscore_Namespacing in root if (!$configFileNode && empty($namespace) && $path != $className) { $configFileNode = Site::resolvePath("php-config/{$className}.config.php"); } if ($configFileNode && $configFileNode->MIMEType == 'application/php') { $configFileIds[] = $configFileNode->ID; } // look for composite config files $collectionPath = "php-config/{$path}.config.d"; Emergence_FS::cacheTree($collectionPath); foreach (Emergence_FS::getAggregateChildren($collectionPath) as $filename => $node) { if ($node->Type == 'application/php') { $configFileIds[] = $node->ID; } } Cache::store($cacheKey, $configFileIds); } foreach ($configFileIds as $id) { require SiteFile::getRealPathByID($id); } }