private function get_incoming_links() { $links = array(); try { $search = new RemoteRequest('http://blogsearch.google.com/blogsearch_feeds?scoring=d&num=10&output=atom&q=link:' . Site::get_url('habari')); $search->set_timeout(5); $result = $search->execute(); if (Error::is_error($result)) { throw $result; } $response = $search->get_response_body(); if (mb_detect_encoding($response, 'UTF-8', true)) { $xml = new SimpleXMLElement($response); foreach ($xml->entry as $entry) { //<!-- need favicon discovery and caching here: img class="favicon" src="http://skippy.net/blog/favicon.ico" alt="favicon" / --> $links[] = array('href' => (string) $entry->link['href'], 'title' => (string) $entry->title); } } else { EventLog::log(_t('The response had non-UTF-8 characters'), 'err', 'plugin'); } } catch (Exception $e) { $links['error'] = $e->getMessage(); } return $links; }
/** * Return a user's favorited video feed * * @param string YouTube username * * @return ?? * */ public static function favorites($user) { $url = self::YOUTUBE_BASE . 'users/' . $user . '/favorites'; $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw $result; } $response = $call->get_response_body(); try { $xml = new SimpleXMLElement($response); $videos = array(); foreach ($xml->entry as $entry) { $video = array(); $video['id'] = $entry->id; $video['url'] = self::flash_url($entry); $video['thumbnail_url'] = self::thumbnail_url($entry); $video['title'] = self::title($entry); $videos[] = $video; } return new YouTube($videos); } catch (Exception $e) { Session::error('Currently unable to connect to YouTube.', 'YouTube API'); // Utils::debug($url, $response); return false; } }
public function filter_rssblocks_update($success, $force = false) { EventLog::log('Running rrsblocks update'); $blocks = DB::get_results('SELECT b.* FROM {blocks} b WHERE b.type = ?', array('rssblock'), 'Block'); Plugins::act('get_blocks', $blocks); $success = true; foreach ($blocks as $block) { $cachename = array('rssblock', md5($block->feed_url)); if ($force || Cache::expired($cachename)) { $r = new RemoteRequest($block->feed_url); $r->set_timeout(10); $r->execute(); $feed = $r->get_response_body(); try { if (is_string($feed)) { new SimpleXMLElement($feed); // This throws an exception if the feed isn't valid Cache::set($cachename, $feed, 3600, true); } } catch (Exception $e) { $success = false; } } } Session::notice('ran rssblocks update'); return $success; }
/** * Perform a check of all beaconids. * Notifies update_check plugin hooks when checking so that they can add their beaconids to the list. * @return array An array of update beacon information for components that have updates * @throws \Exception */ public static function check() { try { // get a local version of the instance to save typing $instance = self::instance(); // load beacons self::register_beacons(); // setup the remote request $request = new RemoteRequest(self::UPDATE_URL, 'POST'); // add all the beacon versions as parameters $request->set_params(Utils::array_map_field($instance->beacons, 'version')); // we're not desperate enough to wait too long $request->set_timeout(5); // execute the request $result = $request->execute(); // grab the body of the response, which has our xml in it $update_data = $request->get_response_body(); // i don't know why we hold the XML in a class variable, but we'll keep doing that in this rewrite $instance->update = new \SimpleXMLElement($update_data); foreach ($instance->update as $beacon) { $beacon_id = (string) $beacon['id']; $beacon_url = (string) $beacon['url']; $beacon_type = isset($beacon['type']) ? (string) $beacon['type'] : 'addon'; // do we have this beacon? if not, don't process it // even though we POST all our beacons to the update script right now, it still hands back the whole list if (empty($instance->beacons[$beacon_id])) { continue; } // add the beacon's basic info $instance->beacons[$beacon_id]['id'] = $beacon_id; $instance->beacons[$beacon_id]['url'] = $beacon_url; $instance->beacons[$beacon_id]['type'] = $beacon_type; foreach ($beacon->update as $update) { // pick out and cast all the values from the XML $u = array('severity' => (string) $update['severity'], 'version' => (string) $update['version'], 'date' => isset($update['date']) ? (string) $update['date'] : '', 'url' => isset($update['url']) ? (string) $update['url'] : '', 'text' => (string) $update); // if the remote update info version is newer... we want all newer versions if (version_compare($u['version'], $instance->beacons[$beacon_id]['version']) > 0) { // if this version is more recent than all the other versions if (!isset($instance->beacons[$beacon_id]['latest_version']) || version_compare($u['version'], $instance->beacons[$beacon_id]['latest_version']) > 0) { // set this as the latest version $instance->beacons[$beacon_id]['latest_version'] = $u['version']; } // add the version to the list $instance->beacons[$beacon_id]['updates'][$u['version']] = $u; } } } // return an array of beacons that have updates return array_filter($instance->beacons, Method::create('\\Habari\\Update', 'filter_unchanged')); } catch (\Exception $e) { // catches any RemoteRequest errors or XML parsing problems, etc. // bubble up throw $e; } }
private static function get_external_content($url) { // Get JSON content via Twitter API $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Twitter.', 'twitterlitte')); } return $call->get_response_body(); }
private static function get_external_content($url) { // Get PHP serialized object from Flickr $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Flickr.', 'flickrfeed')); } return $call->get_response_body(); }
private static function get_external_content($url) { // Get JSON content via Delicious API $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw new Exception(_t('Unable to contact Delicious.', 'deliciousfeed')); } return $call->get_response_body(); }
function call($method, $args = array()) { $args = array_merge(array('method' => $method, 'api_key' => $this->key), $args); ksort($args); $args = array_merge($args, array('api_sig' => $this->sign($args))); ksort($args); if ($method == 'upload') { $req = curl_init(); $args['api_key'] = $this->key; $photo = $args['photo']; $args['photo'] = '@' . $photo; curl_setopt($req, CURLOPT_URL, $this->uploadendpoint); curl_setopt($req, CURLOPT_TIMEOUT, 0); // curl_setopt($req, CURLOPT_INFILESIZE, filesize($photo)); // Sign and build request parameters curl_setopt($req, CURLOPT_POSTFIELDS, $args); curl_setopt($req, CURLOPT_CONNECTTIMEOUT, $this->conntimeout); curl_setopt($req, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($req, CURLOPT_HEADER, 0); curl_setopt($req, CURLOPT_RETURNTRANSFER, 1); $this->_http_body = curl_exec($req); if (curl_errno($req)) { throw new Exception(curl_error($req)); } curl_close($req); $xml = simplexml_load_string($this->_http_body); $this->xml = $xml; return $xml; } else { $url = $this->endpoint . implode('&', $this->encode($args)); $call = new RemoteRequest($url); $call->set_timeout(5); try { $result = $call->execute(); } catch (RemoteRequest_Timeout $t) { Session::error('Currently unable to connect to Flickr.', 'flickr API'); return false; } catch (Exception $e) { // at the moment we're using the same error message, though this is more catastrophic Session::error('Currently unable to connect to Flickr.', 'flickr API'); return false; } $response = $call->get_response_body(); try { $xml = new SimpleXMLElement($response); return $xml; } catch (Exception $e) { Session::error('Unable to process Flickr response.', 'flickr API'); return false; } } }
/** * Perform a check of all beaconids. * Notifies update_check plugin hooks when checking so that they can add their beaconids to the list. * @return array An array of update beacon information for components that have updates */ public static function check() { try { $instance = self::instance(); if (count($instance->beacons) == 0) { Update::add('Habari', '7a0313be-d8e3-11db-8314-0800200c9a66', Version::get_habariversion()); Plugins::act('update_check'); } $request = new RemoteRequest(UPDATE_URL, 'POST'); $request->set_params(array_map(create_function('$a', 'return $a["version"];'), $instance->beacons)); $request->set_timeout(10); $result = $request->execute(); if (Error::is_error($result)) { throw $result; } $updatedata = $request->get_response_body(); if (Error::is_error($updatedata)) { throw $updatedata; } $instance->update = new SimpleXMLElement($updatedata); foreach ($instance->update as $beacon) { $beaconid = (string) $beacon['id']; foreach ($beacon->update as $update) { // Do we have this beacon? If not, don't process it. if (empty($instance->beacons[$beaconid])) { continue; } // If the remote update info version is newer... if (version_compare($update['version'], $instance->beacons[$beaconid]['version']) > 0) { // If this version is more recent than all other newer versions... if (empty($instance->beacons[$beaconid]['latest_version']) || version_compare((string) $update['version'], $instance->beacons[$beaconid]['latest_version']) > 0) { $instance->beacons[$beaconid]['latest_version'] = (string) $update['version']; } if (isset($instance->beacons[$beaconid]['severity'])) { $instance->beacons[$beaconid]['severity'][] = (string) $update['severity']; array_unique($instance->beacons[$beaconid]['severity']); } else { $instance->beacons[$beaconid]['severity'] = array((string) $update['severity']); } $instance->beacons[$beaconid]['url'] = (string) $beacon['url']; $instance->beacons[$beaconid]['changes'][(string) $update['version']] = (string) $update; } } } return array_filter($instance->beacons, array('Update', 'filter_unchanged')); } catch (Exception $e) { return $e; } }
public function shorten($url) { $params = array('login' => $this->username, 'apiKey' => $this->apiKey, 'format' => $this->format, 'longUrl' => $url); $reqUrl = $this->endpoint . '/shorten?' . http_build_query($params); $call = new RemoteRequest($reqUrl); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw $result; } $response = $call->get_response_body(); $data = json_decode($response); if ($data === null) { throw new Exception("Could not communicate with bit.ly API"); } return $data; }
/** * Execute a call to the Picasa Service * * @param $url string The destination url * @param $args array Optional Extra arguments * @param $post_data Optional Post data * @return mixed false on error or xml string */ public function call($url, $args = array(), $post_data = '') { $token = Options::get('picasa_token_' . User::identify()->id); $default_args = array('method' => 'GET'); $args = array_merge($default_args, $args); $request = new RemoteRequest($url, $args['method']); // set authorisation header $request->add_header(array("Authorization" => "AuthSub token=" . $token)); // add extra headers if (isset($args['http_headers'])) { foreach ($args['http_headers'] as $key => $value) { $request->add_header(array($key => $value)); } } if ($post_data != '') { $request->set_body($post_data); } $request->set_timeout(30); // execute request $result = $request->execute(); if (Error::is_error($result)) { return $result; } // get the response if executed if ($request->executed()) { $response = $request->get_response_body(); } if (!$response) { return Error::raise('API call failure', E_USER_WARNING); } // parse the result try { $xml = new SimpleXMLElement($response); return $xml; } catch (Exception $e) { Session::error('Currently unable to connect to the Picasa API.', 'Picasa API'); return false; } }
function call($method, $args = array()) { $args = array_merge(array('method' => $method, 'api_key' => $this->key), $args); ksort($args); $args = array_merge($args, array('api_sig' => $this->sign($args))); ksort($args); $call = new RemoteRequest($this->endpoint, 'POST'); $args['api_key'] = $this->key; if ($method == 'upload') { $call = new RemoteRequest($this->uploadendpoint, 'POST'); if (is_file($args['photo'])) { // we have a valid file and filename $call->set_file('photo', $args['photo']); unset($args['photo']); } } $call->set_timeout($this->conntimeout); $call->set_postdata($args); try { $result = $call->execute(); } catch (RemoteRequest_Timeout $t) { Session::error('Currently unable to connect to Flickr.', 'flickr API'); return false; } catch (Exception $e) { // at the moment we're using the same error message, though this is more catastrophic Session::error('Currently unable to connect to Flickr.', 'flickr API'); return false; } $response = $call->get_response_body(); try { $xml = new SimpleXMLElement($response); return $xml; } catch (Exception $e) { Session::error('Unable to process Flickr response.', 'flickr API'); return false; } }
/** * Retrieve tweets * @return array notices The tweets to display in the theme template or block */ public function tweets($username, $hide_replies = false, $limit = 5, $cache = 60, $linkify_urls = false, $hashtags_query = 'http://hashtags.org/search?query=') { $notices = array(); if ($username != '') { $twitter_url = 'http://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name=' . urlencode($username) . '&'; // We only need to get a single tweet if we're hiding replies (otherwise we can rely on the maximum returned and hope there's a non-reply) if (!$hide_replies && $limit) { $twitter_url .= 'count=' . $limit . '&'; } if (Cache::has('twitter_notices')) { $notices = Cache::get('twitter_notices'); } else { try { $r = new RemoteRequest($twitter_url); $r->set_timeout(10); $r->execute(); $response = $r->get_response_body(); $xml = @new SimpleXMLElement($response); // Check we've got a load of statuses returned if ($xml->getName() === 'statuses') { foreach ($xml->status as $status) { if (!$hide_replies || strpos($status->text, '@') === FALSE) { $notice = (object) array('text' => (string) $status->text, 'time' => (string) $status->created_at, 'image_url' => (string) $status->user->profile_image_url, 'id' => (int) $status->id, 'permalink' => 'http://twitter.com/' . $username . '/status/' . (string) $status->id); $notices[] = $notice; if ($hide_replies && count($notices) >= $limit) { break; } } else { // it's a @. Keep going. } } if (!$notices) { $notice = (object) array('text' => _t('No non-replies replies available from Twitter.', 'twitter'), 'time' => '', 'image_url' => ''); } } else { if ($xml->getName() === 'error') { $notice = (object) array('text' => (string) $xml, 'time' => '', 'image_url' => ''); } else { $notice = (object) array('text' => 'Received unexpected XML from Twitter.', 'time' => '', 'image_url' => ''); } } } catch (Exception $e) { EventLog::log(_t('Twitter error: %1$s', array($e->getMessage()), 'twitter'), 'err', 'plugin', 'twitter'); $notice = (object) array('text' => 'Unable to contact Twitter.', 'time' => '', 'image_url' => ''); } if (!$notices) { $notices[] = $notice; } // Cache (even errors) to avoid hitting rate limit. Cache::set('twitter_notices', $notices, $cache !== false ? $cache : Twitter::DEFAULT_CACHE_EXPIRE); // , true ); } } else { $notice = (object) array('text' => _t('Please set your username in the <a href="%s">Twitter plugin config</a>', array(URL::get('admin', 'page=plugins&configure=' . $this->plugin_id . '&configaction=Configure') . '#plugin_' . $this->plugin_id), 'twitter'), 'time' => '', 'image_url' => ''); $notices[] = $notice; } if ($linkify_urls != FALSE) { foreach ($notices as $notice) { /* link to all http: */ $notice->text = preg_replace('%https?://\\S+?(?=(?:[.:?"!$&\'()*+,=]|)(?:\\s|$))%i', "<a href=\"\$0\">\$0</a>", $notice->text); /* link to usernames */ $notice->text = preg_replace("/(?<!\\w)@([\\w-_.]{1,64})/", "@<a href=\"http://twitter.com/\$1\">\$1</a>", $notice->text); /* link to hashtags */ $notice->text = preg_replace('/(?<!\\w)#((?>\\d{1,64}|)[\\w-.]{1,64})/', "<a href=\"" . $hashtags_query . "\$1\">#\$1</a>", $notice->text); } } return $notices; }
public function theme_flickrfill_bydate($theme, $post1date, $post2date) { $this->person_id = Options::get('flickrfill__person'); $this->size = Options::get('flickrfill__size'); $this->number = Options::get('flickrfill__number'); $feed_url = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&format=rest&api_key=39b1bcf1b0c84a24435677252085d436&user_id=' . $this->person_id . '&min_taken_date=' . $post2date . '&max_taken_date=' . $post1date . '&sort=interestingness-desc&media=photos&per_page=' . $this->number; if (Cache::has($feed_url)) { $response = Cache::get($feed_url); } if (!Cache::has($feed_url) || Cache::expired($feed_url)) { // Cache::expired() is a 0.7 feature. $request = new RemoteRequest($feed_url); $request->set_timeout(5); $result = $request->execute(); if (Error::is_error($result)) { EventLog::log('Error getting photo from Flickr', 'err', 'default', 'habari'); } else { $response = $request->get_response_body(); } } $output = ''; $xml = new SimpleXMLElement($response); if (!$xml) { return 'no xml'; } $output .= '<div class="flickrfill">'; foreach ($xml->photos->photo as $photo) { if (!$photo) { return; } if (!$photo['id']) { return; } $output .= '<a href="http://www.flickr.com/photos/' . $this->person_id . '/' . $photo['id'] . '"><img class="flickrfeedimg" src="http://farm' . $photo['farm'] . '.static.flickr.com/' . $photo['server'] . '/' . $photo['id'] . '_' . $photo['secret'] . $this->size . '.jpg"></a>'; } $output .= '</div>'; return $output; }
/** * Add last Jaiku status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_jaiku($theme, $params = array()) { $params = array_merge($this->config, $params); $cache_name = $this->class_name . '__' . md5(serialize($params)); if ($params['username'] != '') { if (Cache::has($cache_name)) { $theme->presences = Cache::get($cache_name); } else { if ($params['limit'] == 1) { $url = 'http://' . $params['username'] . '.jaiku.com/presence/last/json'; } else { $url = 'http://' . $params['username'] . '.jaiku.com/feed/json'; } try { // Get JSON content via Jaiku API $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Jaiku.', $this->class_name)); } $response = $call->get_response_body(); // Decode JSON $obj = json_decode($response); if (!$obj instanceof stdClass) { // Response is not JSON throw Error::raise(_t('Response is not correct, maybe Jaiku server is down or API is changed.', $this->class_name)); } $serial = property_exists($obj, 'stream') ? serialize($obj->stream) : serialize($obj); // Convert stdClass to JaikuPresence and JaikuUser $serial = str_replace('s:4:"user";O:8:"stdClass":', 's:4:"user";O:9:"JaikuUser":'******'O:8:"stdClass":', 'O:13:"JaikuPresence":', $serial); $presences = unserialize($serial); // Pass $presences to $theme if (is_array($presences)) { $theme->presences = array_slice($presences, 0, $params['limit']); } else { $theme->presences = array($presences); } // Do cache Cache::set($cache_name, $theme->presences, $params['cache']); } catch (Exception $e) { $theme->presences = $e->getMessage(); } } } else { $theme->presences = _t('Please set your username in the Jaiku plugin config.', $this->class_name); } return $theme->fetch('jaiku'); }
private function load_feeds($params = array()) { $cache_name = $this->class_name . '__' . md5(serialize($params)); if (Cache::has($cache_name)) { // Read from cache return Cache::get($cache_name); } else { $url = 'http://feeds.delicious.com/v2/json/' . $params['user_id']; if ($params['tags']) { $url .= '/' . urlencode($params['tags']); } $url .= '?count=' . $params['num_item']; try { // Get JSON content via Delicious API $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Delicious.', $this->class_name)); } $response = $call->get_response_body(); // Decode JSON $deliciousfeed = json_decode($response); if (!is_array($deliciousfeed)) { // Response is not JSON throw Error::raise(_t('Response is not correct, maybe Delicious server is down or API is changed.', $this->class_name)); } else { // Transform to DeliciousPost objects $serial = serialize($deliciousfeed); $serial = str_replace('O:8:"stdClass":', 'O:13:"DeliciousPost":', $serial); $deliciousfeed = unserialize($serial); } // Do cache Cache::set($cache_name, $deliciousfeed, $params['cache_expiry']); return $deliciousfeed; } catch (Exception $e) { return $e->getMessage(); } } }
private function load_feeds($params = array()) { $cache_name = $this->class_name . '__' . md5(serialize($params)); if (Cache::has($cache_name)) { // Read from cache return Cache::get($cache_name); } else { switch ($params['type']) { case 'user': $url = 'http://api.flickr.com/services/feeds/photos_public.gne?id=' . $params['user_id'] . '&tags=' . $params['tags'] . '&format=php_serial'; break; case 'friends': $url = 'http://api.flickr.com/services/feeds/photos_friends.gne?user_id=' . $params['user_id'] . '&format=php_serial'; break; case 'faves': $url = 'http://api.flickr.com/services/feeds/photos_faves.gne?id=' . $params['user_id'] . '&format=php_serial'; break; case 'group': $url = 'http://api.flickr.com/services/feeds/groups_pool.gne?id=' . $params['user_id'] . '&format=php_serial'; break; default: $url = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=' . $params['tags'] . '&format=php_serial'; break; } try { // Get PHP serialized object from Flickr $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Flickr.', $this->class_name)); } // Unserialize and manipulate the data $flickrfeed = unserialize($call->get_response_body()); $flickrfeed = array_slice($flickrfeed['items'], 0, $params['num_item']); // Photo size foreach ($flickrfeed as &$image) { switch ($params['size']) { case 'thumbnail': $image['image_url'] = str_replace('_m.jpg', '_t.jpg', $image['m_url']); break; case 'small': $image['image_url'] = $image['m_url']; break; case 'medium': $image['image_url'] = $image['l_url']; break; case 'large': $image['image_url'] = str_replace('_m.jpg', '_b.jpg', $image['m_url']); break; case 'original': $image['image_url'] = $image['photo_url']; break; default: $image['image_url'] = $image['t_url']; break; } } // Do cache Cache::set($cache_name, $flickrfeed, $params['cache_expiry']); return $flickrfeed; } catch (Exception $e) { return $e->getMessage(); } } }
/** * filter_dash_module_trac_tickets * Gets the latest entries module * @param string $module * @return string The contents of the module */ public function filter_dash_module_my_tickets($module) { //add assets when module is on page Stack::add('admin_footer_javascript', 'http://yui.yahooapis.com/3.2.0/build/yui/yui.js'); Stack::add('admin_footer_javascript', Site::get_url('user') . '/plugins/tracdashmodule/tracdashmodule.js'); $items = false; $cache = false; //get rss feeds from admin configuration $trac_query = Options::get('tracdashmodule__trac_query'); //if multiple then join $trac_query = count($trac_query) > 1 ? implode('","', $trac_query) : $trac_query[0]; //yql query to extract what we want from feeds & return json $query = "http://query.yahooapis.com/v1/public/yql?q=select%20link%2Ctitle%20from%20rss%20where%20url%20in(%22" . urlencode($trac_query) . "%22)&format=json&diagnostics=false"; try { $r = new RemoteRequest($query); $r->set_timeout(10); $r->execute(); $response = $r->get_response_body(); $json = json_decode($response, 1); $items = $json['query']['results']['item']; } catch (Exception $e) { //if request failed, then check cache to show last group of tickets if (Cache::has('my_tickets')) { $items = Cache::get('my_tickets'); } //log error EventLog::log(_t('TracDashModule error: %1$s', array($e->getMessage()), 'tracdashmodule'), 'err', 'plugin', 'tracdashmodule'); $item = (object) array('text' => 'Unable to fetch Trac Tickets.', 'time' => '', 'image_url' => ''); if (!$items) { $items[] = $item; } } //end catch // Cache (even errors) to avoid hitting rate limit. We only use the cache as fallback when api fails Cache::set('my_tickets', $items, $cache !== false ? $cache : 9000); // , true ); $html = '<ul class="trac">'; foreach ($items as $k => $v) { $html .= '<li class="item"><a class="minor" href="' . $v['link'] . '">' . $v['title'] . '</a></li>'; } $html .= '</ul>'; $module['title'] == 'Trac Module'; $module['content'] = $html; return $module; }
public static function zima($url) { $call = new RemoteRequest('http://zi.ma/'); $call->set_params(array('module' => 'ShortURL', 'file' => 'Add', 'mode' => 'API', 'url' => $url)); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } return trim($call->get_response_body()); }
/** * Add last Twitter status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_twitter($theme) { $notices = array(); if (Options::get('twitter__show') && Options::get('twitter__username') != '') { $twitter_url = 'http://twitter.com/statuses/user_timeline/' . urlencode(Options::get('twitter__username')) . '.xml'; // We only need to get a single tweet if we're hiding replies (otherwise we can rely on the maximum returned and hope there's a non-reply) if (!Options::get('twitter__hide_replies') && Options::get('twitter__limit')) { $twitter_url .= '?count=' . Options::get('twitter__limit'); } if (Cache::has('twitter_notices')) { $notices = Cache::get('twitter_notices'); } else { try { $r = new RemoteRequest($twitter_url); $r->set_timeout(10); $r->execute(); $response = $r->get_response_body(); $xml = @new SimpleXMLElement($response); // Check we've got a load of statuses returned if ($xml->getName() === 'statuses') { foreach ($xml->status as $status) { if (!Options::get('twitter__hide_replies') || strpos($status->text, '@') === false) { $notice = (object) array('text' => (string) $status->text, 'time' => (string) $status->created_at, 'image_url' => (string) $status->user->profile_image_url); $notices[] = $notice; if (Options::get('twitter__hide_replies') && count($notices) >= Options::get('twitter__limit')) { break; } } else { // it's a @. Keep going. } } if (!$notices) { $notice = (object) array('text' => 'No non-replies replies available from Twitter.', 'time' => '', 'image_url' => ''); } } else { if ($xml->getName() === 'error') { $notice = (object) array('text' => (string) $xml, 'time' => '', 'image_url' => ''); } else { $notice = (object) array('text' => 'Received unexpected XML from Twitter.', 'time' => '', 'image_url' => ''); } } } catch (Exception $e) { $notice = (object) array('text' => 'Unable to contact Twitter.', 'time' => '', 'image_url' => ''); } if (!$notices) { $notices[] = $notice; } // Cache (even errors) to avoid hitting rate limit. Cache::set('twitter_notices', $notices, Options::get('twitter__cache'), true); } } else { $notice = (object) array('text' => _t('Please set your username in the <a href="%s">Twitter plugin config</a>', array(URL::get('admin', 'page=plugins&configure=' . $this->plugin_id . '&configaction=Configure') . '#plugin_' . $this->plugin_id), 'twitter'), 'time' => '', 'image_url' => ''); $notices[] = $notice; } if (Options::get('twitter__linkify_urls') != FALSE) { foreach ($notices as $notice) { /* link to all http: */ $notice->text = preg_replace('%https?://\\S+?(?=(?:[.:?"!$&\'()*+,=]|)(?:\\s|$))%i', "<a href=\"\$0\">\$0</a>", $notice->text); /* link to usernames */ $notice->text = preg_replace("/(?<!\\w)@([\\w-_.]{1,64})/", "@<a href=\"http://twitter.com/\$1\">\$1</a>", $notice->text); /* link to hashtags */ $notice->text = preg_replace('/(?<!\\w)#((?>\\d{1,64}|)[\\w-.]{1,64})/', "<a href=\"" . Options::get('twitter__hashtags_query') . "\$1\">#\$1</a>", $notice->text); } } $theme->tweets = $notices; return $theme->fetch('tweets'); }
private function get_lastrecent($block = null) { $name = $block ? $block->title : 'legacy'; $user = $block ? $block->user : $this->user; $limit = $block ? $block->limit : $this->limit; $size = $block ? (int) $block->size : $this->images; if (Cache::has('lastrecent__' . $name)) { $recent = Cache::get('lastrecent__' . $name); } else { try { $last = new RemoteRequest('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&api_key=' . $this->api_key . '&user='******'&limit=' . $limit); $last->set_timeout(5); $result = $last->execute(); if (Error::is_error($result)) { throw $result; } $response = $last->get_response_body(); $xml = new SimpleXMLElement($response); $recent = array(); foreach ($xml->recenttracks->track as $track) { $recent[] = array('name' => (string) $track->name, 'url' => (string) $track->url, 'image' => (string) $track->image[$size], 'artist' => (string) $track->artist, 'album' => (string) $track->album, 'date' => (string) $track->date); } Cache::set('lastrecent__' . $name, $recent, $this->cache_expiry); } catch (Exception $e) { $recent['error'] = $e->getMessage(); } } return $recent; }
/** * Get the brightkite feed for our user_id **/ private function load_bk_info($params = array()) { $cache_name = $this->class_name . '__' . md5(serialize($params)); if (Cache::has($cache_name)) { // Read from the cache return Cache::get($cache_name); } else { // Time to fetch it. $url = 'http://brightkite.com/people/' . $params['user_id'] . '.json'; try { $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Brightkite.', $this->class_name)); } $response = $call->get_response_body(); // Decode the JSON $bkdata = json_decode($response, true); if (!is_array($bkdata)) { // Response is not JSON throw Error::raise(_t('Response is not correct, maybe Brightkite server is down or API changed.', $this->class_name)); } // Do cache Cache::set($cache_name, $bkdata, $params['cache_expiry']); return $bkdata; } catch (Exception $e) { return $e->getMessage(); } } }
/** * Add last Audioscrobbler status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_audioscrobbler($theme, $params = array()) { $params = array_merge($this->config, $params); $cache_name = $this->class_name . '__' . md5(serialize($params)); if ($params['username'] != '') { $track_url = 'http://ws.audioscrobbler.com/1.0/user/' . urlencode($params['username']) . '/recenttracks.xml'; if (Cache::has($cache_name)) { $xml = new SimpleXMLElement(Cache::get($cache_name)); $theme->track = $xml->track; } else { try { // Get XML content via Audioscrobbler API $call = new RemoteRequest($track_url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Last.fm.', $this->class_name)); } $response = $call->get_response_body(); // Parse XML content $xml = new SimpleXMLElement($response); $theme->track = $xml->track; Cache::set($cache_name, $response, $params['cache']); } catch (Exception $e) { $theme->track = $e->getMessage(); } } } else { $theme->track = _t('Please set your username in the Audioscrobbler plugin config.', $this->class_name); } return $theme->fetch('audioscrobbler'); }