/** * Save data to cache. * * @param string $key Data to save as. * @param mixed $value Data to save. * @param boolean $db Cache to database. * * @return void */ public static function saveData($key, $value, $db = false) { $cache = Cache::getInstance(); $cache->data[$key] = $value; if ($key != 'ModelCachingFields' && $db && Config::getSetting('cache_to_database', false, false) && Clockwork::isModuleLoaded('Data/Database')) { $lifespan = $db === true ? 0 : $db; if (($obj = Caching::create($key, '*`key`')) === false) { $obj = new Caching(); } $obj->set('key', $key)->set('value', serialize($value))->set('object', is_object($value) ? get_class($value) : '')->set('lifespan', $lifespan)->save(); } }
/** * __construct function. * * Loads dependencies and sets cache directory, status and expiry time. * * @access public * @param mixed $config * @param mixed $cache_dir * @return void */ public function __construct($request, $config, $cache_dir) { parent::__construct($config, $cache_dir); $this->request = $request; $this->status = $this->config->defaults['page_caching']['status']; $this->expiry = $this->config->defaults['page_caching']['expiry']; }
/** * This method searches the IMDB (using the unofficial API) for the passed in film title. I return the entire SimpleXML Object * WARNING this web service is in hot water with Amazon owner of IMDB so I am moving away from it towards Rotten Tomatoes * * @param string * @return SimpleXML Object */ protected function searchIMDBForFilm($filmTitle) { $movieInfo = NULL; // A lot of people have wanted to search or scrape the IMDB with an API or PHP. Amazon owns the website so it is possible some of this // data is in the main Amazon Product Advertising API. I've already noticed how Wikipedia and Rotten Tomatoes occaisionally have the same // exact text. // The default is to return data in JSON format, but XML is also supported. Here is what a query URL should look like: // http://www.imdbapi.com/?t=True Grit&y=1969 // spaces need to be encoded. // This works well as I always pass in titles of films that I've already found in Rotten Tomatoes, this isn't an official precondition and // I should probably cache this just like so much other data. // first check that we don't have a local cached version, no reason to get lazy $properFileName = preg_replace("/[^a-zA-Z0-9]/", "", $filmTitle); if (strlen($properFileName) > 0) { $myCache = new Caching("./MashupCache/IMDB/", $properFileName); if ($myCache->needToRenewData()) { try { $encodedTitle = urlencode($filmTitle); $queryURL = 'http://www.omdbapi.com/?t=' . $encodedTitle . '&plot=full'; // I prefer the long version of the plot $queryResult = fetchThisURL($queryURL); $movieInfo = json_decode($queryResult); } catch (Exception $e) { echo $e->getMessage(); } $serializedObject = serialize($movieInfo); $myCache->saveSerializedDataToFile($serializedObject); } else { // It doesn't need to be renewed so use local copy $movieInfo = $myCache->getUnserializedData(); } } /* // We need to see if this method is still reliable, given Amazon's litigation. Works but not for posters. print("<pre>"); print_r($movieInfo); print("</pre>"); */ return $movieInfo; }
/** * Директива @endcache * * @return string */ public function endCache() { return $this->cache->put($this->getKey(), ob_get_clean()); }
/** * This method searches the iTunes store and returns the artist page, or best guess at the product page. * * @param array * @return Simple XML object */ protected function getResultsFromITunesForSourceOfQuotation($quotation) { // This method replaces getArtistResultsFromITunes() but follows the basic technique caching the results. $iTunesInfo = null; $strippedSource = $quotation[0]; $strippedSource = preg_replace("/[^a-zA-Z0-9]/", "", $strippedSource); if (is_string($quotation[0]) && strlen($strippedSource) > 0) { $myCache = new Caching("./MashupCache/iTunes/", $strippedSource); if ($myCache->needToRenewData()) { try { // Now we will have a three or more pronged approach, just like many methods in this class if ($this->isFromFilm($quotation)) { // Here we want media to be movie $formattedSource = str_replace(' ', '+', $quotation[0]); $iTunesSearchString = 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=' . $formattedSource . '&entity=movie&media=movie'; } else { if ($this->isFromSong($quotation) || $this->isFromMusician($quotation)) { // This can be the same give or take as the parent class, searching for an artist page. $formattedArtistString = str_replace(' ', '+', $quotation[0]); $iTunesSearchString = 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=' . $formattedArtistString . '&entity=musicArtist'; } else { // This is going to be less likely to return results from the iTunes store, but it has so much stuff now so who knows // Going to go with media of type ebook $formattedSource = str_replace(' ', '+', $quotation[0]); $iTunesSearchString = 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=' . $formattedSource . '&entity=ebook&media=ebook'; } } $searchResult = fetchThisURL($iTunesSearchString); $iTunesInfo = json_decode($searchResult); } catch (Exception $e) { echo $e->getMessage(); } $serializedObject = serialize($iTunesInfo); $myCache->saveSerializedDataToFile($serializedObject); } else { // It doesn't need to be renewed so use local copy of array $iTunesInfo = $myCache->getUnserializedData(); } } else { throw new Exception('Incorrect data type passed to getResultsFromITunesForSourceOfQuotation()'); } return $iTunesInfo; }
<?php list($usec, $sec) = explode(' ', microtime()); $time = (double) $usec + (double) $sec; require_once 'class.Caching.php'; $cache = new Caching('localhost', 'root', 'kronos', 'ocarina2', '/var/www/htdocs/caching/cache/'); $getNews = $cache->get('SELECT * FROM news LIMIT 10'); foreach ($getNews as $v) { echo $v->titolo . '<br />'; } echo 'Count: ' . $cache->count('SELECT * FROM news LIMIT 10') . '<br /><br />'; list($usec, $sec) = explode(' ', microtime()); $time = (double) $usec + (double) $sec - $time; echo "Time: {$time}"; // Average ~= 0.003 /* Wait... */ echo '<br />--------------------------------<br />'; unset($time); unset($cache); unset($getNews); /* Go! */ list($usec, $sec) = explode(' ', microtime()); $time = (double) $usec + (double) $sec; mysql_selectdb('ocarina2', mysql_connect('localhost', 'root', 'kronos')); $query = mysql_query('SELECT * FROM news LIMIT 10'); $getNews = array(); while ($fetch = mysql_fetch_object($query)) { array_push($getNews, $fetch); } foreach ($getNews as $v) { echo $v->titolo . '<br />';
/** * This method I created as part of my favourite or loved tracks mashup. The code is for creating an instance of this * class populated by the albums that correspond to a user's loved tracks in last.fm. By putting the code here as a static method * future users of this class can populate their music collection with this info too. * * In the array I also put the track name and the url on Last.fm, I used non-numeric indices for this extra data. * * @return musicCollection */ public static function collectionFromLovedTracks() { $lovedTracksInfo = array(); $myLovedTracks = musicCollection::getLovedTracksFor(myInfo::MY_LAST_FM_USER_NAME); // New Caching Code $strippedUserName = preg_replace("/[^a-zA-Z0-9]/", "", myInfo::MY_LAST_FM_USER_NAME); if (strlen($strippedUserName) > 0) { $strippedUserName = $strippedUserName . 'LovedTracks'; $myCache = new Caching("./MashupCache/LovedTracks/", $strippedUserName); if ($myCache->needToRenewData()) { $lovedTracksCount = count($myLovedTracks); $artistName = ''; $albumTitle = ''; $songTitle = ''; $songURL = ''; $i = 0; while ($i < $lovedTracksCount) { // Need album titles $formattedSongTitle = str_replace(' ', '+', $myLovedTracks[$i]['name']); // http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=song+title&entity=musicTrack $iTunesSearch = 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=' . $formattedSongTitle . '&media=music&entity=musicTrack&attribute=musicTrackTerm'; $iTunesSearchResults = fetchThisURL($iTunesSearch); $iTunesResults = json_decode($iTunesSearchResults); $artistName = $myLovedTracks[$i]['artist']['name']; $songTitle = $myLovedTracks[$i]['name']; $songURL = 'http://' . $myLovedTracks[$i]['url']; // This should solve some linking issues... if ($iTunesResults->resultCount > 0) { $j = 0; $foundAlbum = false; while ($j < $iTunesResults->resultCount && !$foundAlbum) { if (strcmp($iTunesResults->results[$j]->artistName, $myLovedTracks[$i]['artist']['name']) == 0) { $albumTitle = $iTunesResults->results[$j]->collectionName; $foundAlbum = true; } $j++; } // if we don't find one, such as in the case of Tom Waits "Looking for the heart of Saturday Night" , we are end up with the wrong data... if (!$foundAlbum) { // This is necessary $albumTitle = ''; } } else { $albumTitle = ''; } $lovedTracksInfo[$i] = array(0 => $artistName, 1 => $albumTitle, 'songTitle' => $songTitle, 'songURL' => $songURL); $i++; } $reformatedTracks = serialize($lovedTracksInfo); $myCache->saveSerializedDataToFile($reformatedTracks); } else { // It doesn't need to be renewed so use local copy of array $lovedTracksInfo = $myCache->getUnserializedData(); } } return new musicCollection($lovedTracksInfo); }
private function getReleaseFromMusicBrainz($albumASIN) { //ASIN's are unique and don't have spaces or garbage characters, hooray! $myCache = new Caching("./MashupCache/MusicBrainz/", $albumASIN); if ($myCache->needToRenewData()) { try { $args = array("asin" => $albumASIN); $releaseFilter = new phpBrainz_ReleaseFilter($args); $releaseResults = $this->theBrainz->findRelease($releaseFilter); // It says this returns an array! if (!empty($releaseResults)) { // Not all phpBrainz_Release Objects are created equal // This is maybe why I'm not getting tracks... $trackIncludes = array("artist", "discs", "tracks"); // I need the musicbrainz ID for the release I just found... $mbid = $releaseResults[0]->getId(); $musicBrainzRelease = $this->theBrainz->getRelease($mbid, $trackIncludes); // This gets better results from MusicBrainz.org } else { $musicBrainzRelease = $releaseResults; // This is a new idea and may just be a waste of time without having found tracks... } } catch (Exception $e) { echo $e->getMessage(); } $serializedObject = serialize($musicBrainzRelease); $myCache->saveSerializedDataToFile($serializedObject); } else { // It doesn't need to be renewed so use local copy of array $musicBrainzRelease = $myCache->getUnserializedData(); } return $musicBrainzRelease; }
/** * Cache HTML without checking for database updates * * This function caches blocks of HTML code * * @param int $timeout timeout in minutes before cache file is deleted * @param string $html block of HTML to cache * @param string $label name to identify the cached file * @return bool */ public function cacheHTML($timeout = 0, $html = '', $label = '') { $caching = Caching::instance(); return $caching->cacheHTML($this, $timeout, $html, $label); }
<?php /** * * "3 last months Browsers stats" from Statcounter ( http://gs.statcounter.com/ ) * Widget for Panic's Status Board * Developer: Christophe VERGNE * **/ header('Content-type: application/json'); // #Cache use (optionnal) if (file_exists('./cacheClass.php')) { require_once './cacheClass.php'; $oCache = new Caching(); $fileCache = $oCache->getCache("_gs"); } // #If no cache if (!isset($fileCache) || !$fileCache) { // #Date range $gs_dateFrom = date('Y-m', strtotime('3 months ago')); $gs_dateTo = date('Y-m', strtotime('1 month ago')); // #"API" uri $gs_Uri = 'http://gs.statcounter.com/chart.php?bar=1&statType_hidden=browser_version_partially_combined®ion_hidden=ww&granularity=monthly&statType=Browser%20Version%20(Partially%20Combined)®ion=Worldwide&fromMonthYear=' . $gs_dateFrom . '&toMonthYear=' . $gs_dateTo; $result = array('graph' => array('title' => 'Browser Versions', 'type' => 'bar', 'yAxis' => array('units' => array('suffix' => '%')))); // #Data limit $limit = 5; if (isset($_GET['limit'])) { $limit = intval($_GET['limit']); } $current = 1; // #Parse data
/** * __construct function. * * Loads dependencies and sets cache directory, status and expiry time. * * @access public * @param mixed $config * @param mixed $cache_dir * @return void */ public function __construct($config, $cache_dir) { parent::__construct($config, $cache_dir); $this->status = $this->config->defaults['fragment_caching']['status']; $this->expiry = $this->config->defaults['fragment_caching']['expiry']; }
private function getXMLFromAmazon($dvdTitle, $director) { if (strcmp($director, "various") != 0) { $strippedDVDTitle = $dvdTitle . "-" . $director; $strippedDVDTitle = preg_replace("/[^a-zA-Z0-9]/", "", $strippedDVDTitle); } else { $strippedDVDTitle = preg_replace("/[^a-zA-Z0-9]/", "", $dvdTitle); } if (strlen($strippedDVDTitle) > 0) { $myCache = new Caching("./MashupCache/Amazon/", $strippedDVDTitle, 'xml'); if ($myCache->needToRenewData() && strcmp($director, "various") != 0) { try { $result = $this->amazonAPI->getDVDCoverByTitleAndDirector($dvdTitle, $director); } catch (Exception $e) { echo $e->getMessage(); } $myCache->saveXMLToFile($result); // Save new data before we return it to the caller of the method } else { if ($myCache->needToRenewData()) { try { $result = $this->amazonAPI->getDVDCoverByTitle($dvdTitle); } catch (Exception $e) { echo $e->getMessage(); } $myCache->saveXMLToFile($result); // Save new data before we return it to the caller of the method } else { // It doesn't need to be renewed so use local copy $result = $myCache->getLocalXML(); } } } else { throw new Exception('Incorrect data type passed to getXMLFromAmazon()'); } return $result; }
/** * Cache HTML without checking for database updates * * This function caches blocks of HTML code * * @param int $timeout timeout in minutes before cache file is deleted * @param string $html block of HTML to cache * @param string $label name to identify the cached file * @return bool */ public function cacheHTML($timeout = 0, $html = '', $label = '') { require_once LIBS . 'Caching.php'; $caching = new Caching(); return $caching->cacheHTML($this, $timeout, $html, $label); }