/** * Returns details on a movie * * @param $movie_id TMDB id */ public function getInfo($movie_id) { if (!self::probeId($movie_id)) { throw new \Exception('not a tmdb id'); } if ($this->cache_results) { $temp = TempStore::getInstance(); $key = 'TheMovieDbClient/info//' . $movie_id; $data = $temp->get($key); if ($data) { return unserialize($data); } } $url = 'http://api.themoviedb.org/3/movie/' . $movie_id . '?language=' . $this->language . '&api_key=' . $this->api_key; $http = new HttpClient($url); $data = $http->getBody(); if ($http->getStatus() != 200) { d('TheMovieDbClient getInfo server error: ' . $http->getStatus()); d($http->getResponseHeaders()); return false; } $res = Json::decode($data); if ($this->cache_results) { $temp->set($key, serialize($res), '24h'); } return $res; }
static function reverse($latitude, $longitude) { if (!$latitude || !$longitude) { throw new \Exception('no coords set'); } $temp = TempStore::getInstance(); $key = 'GeonamesClient//' . $latitude . '/' . $longitude; $data = $temp->get($key); if ($data) { return unserialize($data); } $url = 'http://ws.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude; $http = new HttpClient($url); $data = $http->getBody(); $xml = simplexml_load_string($data); //d($xml); $res = new GeoLookupResult(); $res->country_code = strval($xml->timezone->countryCode); $res->country_name = strval($xml->timezone->countryName); $res->timezone = strval($xml->timezone->timezoneId); $res->sunrise = strval($xml->timezone->sunrise); $res->sunset = strval($xml->timezone->sunset); $temp->set($key, serialize($res), '1h'); return $res; }
public static function fromFile($file) { if (!file_exists($file)) { return false; } $fsize = filesize($file); if ($fsize < 65536) { return false; } $temp = TempStore::getInstance(); $key = 'videohash/' . $file; $hash = $temp->get($key); if ($hash) { return $hash; } $handle = fopen($file, 'rb'); $hash = array(3 => 0, 2 => 0, 1 => $fsize >> 16 & 0xffff, 0 => $fsize & 0xffff); for ($i = 0; $i < 8192; $i++) { $hash = self::AddUINT64($hash, $handle); } $offset = $fsize - 65536; fseek($handle, $offset > 0 ? $offset : 0, SEEK_SET); for ($i = 0; $i < 8192; $i++) { $hash = self::AddUINT64($hash, $handle); } fclose($handle); $res = sprintf("%04x%04x%04x%04x", $hash[3], $hash[2], $hash[1], $hash[0]); //echo "CALCULATED HASH ".$res." for ".$file."\n"; $temp->set($key, $res); return $res; }
/** @return a StockQuoteResult object */ static function getNasdaq($symbol) { $code = strtolower($symbol); $temp = TempStore::getInstance(); $key = 'StockClient/nasdaq//' . $symbol; $data = $temp->get($key); if ($data) { return unserialize($data); } $res = StockClientYahoo::getNasdaq($symbol); if ($res) { $temp->set($key, serialize($res), '10m'); } return $res; }
static function geocode($place, $country = '') { $text = $country ? $place . ',' . $country : $place; $temp = TempStore::getInstance(); $key = 'YahooQueryClient/geocode//' . $text; $data = $temp->get($key); if ($data) { return unserialize($data); } $q = urlencode('select * from geo.places where text="' . $text . '"'); $url = 'http://query.yahooapis.com/v1/public/yql?q=' . $q . '&format=json'; $x = Json::decode($url); //XXX: instead return all results as array of YahooGeocodeResult objects? if ($x->query->count > 1) { $item = $x->query->results->place[0]; } else { $item = $x->query->results->place; } $res = new YahooGeocodeResult(); $res->name = $item->name; $res->country = $item->country->code; /* XXX TODO: parse admin1, admin2: admin1: { * code: "" * type: "County" * content: "Jamtland" } admin2: { * code: "" * type: "Municipality" * content: "Härjedalen" } */ $res->woeid = $item->woeid; $res->area = new \StdClass(); $res->area->center = new YahooQueryCoordinate($item->centroid->latitude, $item->centroid->longitude); $res->area->sw = new YahooQueryCoordinate($item->boundingBox->southWest->latitude, $item->boundingBox->southWest->longitude); $res->area->ne = new YahooQueryCoordinate($item->boundingBox->northEast->latitude, $item->boundingBox->northEast->longitude); //XXX this is a ugly hack until yahoo returns timezone with their response $geoname = GeonamesClient::reverse($item->centroid->latitude, $item->centroid->longitude); $res->timezone = $geoname->timezone; $temp->set($key, serialize($res)); return $res; }
static function shorten($input_url) { $temp = TempStore::getInstance(); $res = $temp->get('goo.gl/' . $input_url); if ($res) { return $res; } $api_key = ''; $http = new HttpClient('https://www.googleapis.com/urlshortener/v1/url'); $http->setContentType('application/json'); $res = $http->post(Json::encode(array('longUrl' => $input_url, 'key' => $api_key))); $res = Json::decode($res); if (isset($res->error)) { d($res->error->errors); throw new \Exception('Error code ' . $res->error->code . ': ' . $res->error->message); } $temp->set('goo.gl/' . $input_url, $res->id); return $res->id; }
public static function getRate($from, $to, $cache_time = '') { $from = strtoupper($from); $to = strtoupper($to); if (!self::isKnownCurrency($from) || !self::isKnownCurrency($to)) { throw new \Exception('unknown currency'); } if ($cache_time) { $key = 'currency/' . $from . '/' . $to; $temp = TempStore::getInstance(); $rate = $temp->get($key); if ($rate) { return $rate; } } $rate = CurrencyFetcherGoogle::getRate($from, $to); if ($cache_time) { $temp->set($key, $rate, $cache_time); } return $rate; }
function getByISBN($isbn) { if (!Isbn::isValid($isbn)) { throw new \Exception('invalid isbn'); } $isbn = str_replace(' ', '', $isbn); $isbn = str_replace('-', '', $isbn); if ($this->use_cache) { $temp = TempStore::getInstance(); $key = 'IsbnDbClient/isbn/' . $isbn; $res = $temp->get($key); if ($res) { return unserialize($res); } } $url = 'http://isbndb.com/api/books.xml' . '?access_key=' . $this->api_key . '&index1=isbn' . '&value1=' . $isbn; $http = new HttpClient($url); $data = $http->getBody(); $xml = simplexml_load_string($data); $attrs = $xml->BookList; if ($attrs['total_results'] == 0) { return false; } $d = $xml->BookList->BookData; $attrs = $d->attributes(); if (!$attrs) { throw new \Exception('no attrs'); } $book = new BookResource(); $book->title = strval($d->Title); $book->authors = strval($d->AuthorsText); $book->publisher = strval($d->PublisherText); $book->isbn10 = strval($attrs['isbn']); $book->isbn13 = strval($attrs['isbn13']); if ($this->use_cache) { $temp->set($key, serialize($book), '24h'); } return $book; }
public function render() { //available variables in the scope of the view if (class_exists('\\cd\\ErrorHandler')) { $error = ErrorHandler::getInstance(); } if (class_exists('\\cd\\SessionHandler')) { $session = SessionHandler::getInstance(); } if (class_exists('\\cd\\SqlHandler')) { $db = SqlHandler::getInstance(); } if (class_exists('\\cd\\XhtmlHeader')) { $header = XhtmlHeader::getInstance(); } if (class_exists('\\cd\\XmlDocumentHandler')) { $page = XmlDocumentHandler::getInstance(); } if (class_exists('\\cd\\LocaleHandler')) { $locale = LocaleHandler::getInstance(); } if (class_exists('\\cd\\TempStore')) { $temp = TempStore::getInstance(); } // make reference to calling object available in the namespace of the view $caller = $this->caller; $file = $page->getCoreDevPath() . $this->template; if (!file_exists($file)) { // if not built in view, look in app dir $file = $this->template; if (!file_exists($file)) { throw new \Exception('cannot find ' . $this->template); } } ob_start(); require $file; return ob_get_clean(); }
public static function reverse($latitude, $longitude, $api_key = '') { $temp = TempStore::getInstance(); $key = 'googlemaps/reverse//' . $latitude . '/' . $longitude; $data = $temp->get($key); if ($data) { return unserialize($data); } $url = 'http://maps.googleapis.com/maps/api/geocode/json' . '?sensor=false' . ($api_key ? '&key=' . $api_key : '') . '&latlng=' . $latitude . ',' . $longitude; $json = Json::decode($url); if ($json->status != "OK") { return false; } $item = $json->results[0]; //d($item); $res = new GeoLookupResult(); //$res->accuracy = $item->AddressDetails->Accuracy; $res->description = $item->formatted_address; //$res->country_code = $item->AddressDetails->Country->CountryNameCode; //$res->country_name = $item->AddressDetails->Country->CountryName; $temp->set($key, serialize($res)); return $res; }
/** * @param place, city or Yahoo WOEID of location */ function getWeather($place, $country = '') { if (self::isWoeid($place)) { $woeid = $place; } else { $x = YahooQueryClient::geocode($place, $country); if (!$x->woeid) { throw new \Exception('location not found'); } $woeid = $x->woeid; } $temp = TempStore::getInstance(); $key = 'WeatherClient//' . $woeid; $data = $temp->get($key); if ($data) { return unserialize($data); } $url = 'http://weather.yahooapis.com/forecastrss' . '?w=' . $woeid . '&u=c'; // unit = celcius $this->parse($url); $items = $this->getItems(); if (count($items) != 1) { throw new \Exception('unexpected number of results'); } if (!$this->city) { return false; } $res = new WeatherResult(); $res->city = $this->city; $res->region = $this->region; $res->country = $this->country; //XXXX what is the unit types? $res->wind_chill = $this->wind_chill; $res->wind_direction = $this->wind_direction; $res->wind_speed = $this->wind_speed; $res->coord_lat = $this->coord_lat; $res->coord_long = $this->coord_long; $res->time = $this->time; $res->visibility = $this->visibility; $res->celcius = $this->celcius; $locale = LocaleHandler::getInstance(); $res->skycond = $locale->getSkycondition($this->skycond); $temp->set($key, serialize($res), '1h'); return $res; }
<?php /** * Shows detailed information of all connected memcached servers, which is used by the TempStore class */ namespace cd; $tempstore_div = 'tss_' . mt_rand(); echo ' | ' . ahref_js('cache', "return toggle_el('" . $tempstore_div . "')") . ' '; $temp = TempStore::getInstance(); $css = 'display:none;' . 'overflow:auto;' . 'padding:4px;' . 'border:#000 1px solid;'; echo '<div id="' . $tempstore_div . '" style="' . $css . '">'; require 'redis.php'; require 'memcached.php'; echo '</div>';
/** * Fetches the data of the web resource * uses HTTP AUTH if username is set * * @param $post_params array of key->val pairs of POST parameters to send */ private function get($post_params = array(), $head_only = false) { if (!$this->Url->get()) { throw new \Exception('Must set url'); } $temp = TempStore::getInstance(); if (!$this->username && empty($post_params) && $this->cache_time && !$head_only) { $key_head = 'HttpClient/head//' . sha1($this->Url->get()); $key_full = 'HttpClient/full//' . sha1($this->Url->get()); $full = $temp->get($key_full); if ($full) { $this->parseResponse($full); return $this->body; } } if ($this->debug) { curl_setopt($this->ch, CURLOPT_VERBOSE, true); } curl_setopt($this->ch, CURLOPT_URL, $this->Url->get()); if ($this->content_type) { $this->addRequestHeader('Content-Type: ' . $this->content_type); } $this->addRequestHeader('Accept-Encoding: gzip,deflate'); $this->addRequestHeader('Expect:'); // HACK to disable cURL default to send "100-continue" if ($this->Url->getScheme() == 'https') { curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); } curl_setopt($this->ch, CURLOPT_COOKIESESSION, 1); /// to disable curl:s internal cookie handling curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->connection_timeout); curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $this->connection_timeout); curl_setopt($this->ch, CURLOPT_USERAGENT, $this->user_agent); curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt($this->ch, CURLOPT_MAXREDIRS, 0); curl_setopt($this->ch, CURLOPT_HEADER, 1); curl_setopt($this->ch, CURLOPT_NOBODY, $head_only); curl_setopt($this->ch, CURLOPT_TIMEOUT, 30); curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); if ($this->referer) { curl_setopt($this->ch, CURLOPT_REFERER, $this->referer); } if ($this->auth_method) { switch ($this->auth_method) { case 'basic': $key = base64_encode($this->username . ':' . $this->password); $this->addRequestHeader('Authorization: basic ' . $key); break; /* case 'NTLM': //DONT WORK PROPERLY, 2010-10-20 curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); //for "Server: Microsoft-IIS/5.0" curl_setopt($this->ch, CURLOPT_USERPWD, $this->username.':'.$this->password); curl_setopt($this->ch, CURLOPT_MAXREDIRS, 3); break; */ /* case 'NTLM': //DONT WORK PROPERLY, 2010-10-20 curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); //for "Server: Microsoft-IIS/5.0" curl_setopt($this->ch, CURLOPT_USERPWD, $this->username.':'.$this->password); curl_setopt($this->ch, CURLOPT_MAXREDIRS, 3); break; */ default: throw new \Exception('unhandled auth method ' . $this->auth_method); } } curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->request_headers); if ($this->cookies) { if ($this->debug) { echo 'http->get() sending cookies: ' . $this->encodeCookies() . ln(); } curl_setopt($this->ch, CURLOPT_COOKIE, $this->encodeCookies()); } if (!empty($post_params)) { if ($this->debug) { echo 'http->post() ' . $this->Url->get() . ' ... '; } if (is_array($post_params)) { $var = http_build_query($post_params); } else { $var = $post_params; } if ($this->debug) { echo 'BODY: ' . $var . ' (' . strlen($var) . ' bytes)' . ln(); } // NOTE need to specify custom request "POST", in order to allow POST:ing with any Content-Type curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'POST'); // TODO also set 'Content-Length: ' . strlen($var)) curl_setopt($this->ch, CURLOPT_POSTFIELDS, $var); } else { if ($this->debug) { echo 'http->get() ' . $this->Url->get() . ' ... ' . ln(); } } $res = curl_exec($this->ch); if ($this->debug) { echo 'Got ' . strlen($res) . ' bytes' . ln(); } //, showing first 2000:".ln(); d( substr($res,0,2000) ); $this->parseResponse($res); if (!$this->username && empty($post_params) && $this->cache_time && !$head_only) { $temp->set($key_head, serialize($this->response_headers), $this->cache_time); $temp->set($key_full, $res, $this->cache_time); } return $this->body; }
/** * tvrage.com returns max 20 results * * @return list of matching show names & tvrage.com id:s */ function searchShows($query) { if (!$query) { return false; } $temp = TempStore::getInstance(); $key = 'TvRageClient/shows/' . $query; $res = $temp->get($key); if ($res) { return unserialize($res); } $url = 'http://services.tvrage.com/feeds/full_search.php?show=' . urlencode($query); $this->setUrl($url); if ($this->api_key) { $this->Url->setParam('key', $this->api_key); } $data = $this->getBody(); $xml = simplexml_load_string($data); $res = array(); foreach ($xml->show as $s) { $show = new TvShow(); $show->id = strval($s->showid); $show->name = strval($s->name); $show->country = strval($s->country); $show->started = sql_date(self::parseDate(strval($s->started))); $show->ended = sql_date(self::parseDate(strval($s->ended))); $show->status = self::parseStatus($s->status, $show->started, $show->ended); $show->store(); $res[] = $show; } $temp->set($key, serialize($res), '24h'); return $res; }
/** */ function getAlbumCovers($artist, $album) { $temp = TempStore::getInstance(); $key = 'LastFmClient/covers//' . $artist . '/' . $album; $data = $temp->get($key); if ($data) { return unserialize($data); } $xml = $this->query('album.getInfo', array('artist' => $artist, 'album' => $album, 'lang' => $this->language)); if (isset($xml->error)) { // eg: "Album not found" return false; } $images = array(); foreach ($xml->album->image as $i) { $attrs = $i->attributes(); $image = new ImageResource(); $image->type = strval($attrs['size']); $image->setUrl(strval($i)); $images[] = $image; } $temp->set($key, serialize($images)); return $images; }