Example #1
0
 public function fetch()
 {
     $remote_archive = new RemoteRequest($this->url);
     if (Error::is_error($remote_archive->execute())) {
         throw new Exception('Could not fetch archive at ' . $this->url);
     }
     // we should also check content-disposition for filename and the url as fallbacks.
     // some crazy people like to send application/octet-stream, weirdos!
     foreach (split("\n", $remote_archive->get_response_headers()) as $line) {
         if (substr_compare($line, 'Content-Type', 0, 12, true) == 0) {
             $content_type = $line;
             break;
         }
     }
     /* Get the MIME type and character set */
     preg_match('@Content-Type:\\s+([\\w/\\-+]+)(;\\s+charset=(\\S+))?@i', $content_type, $matches);
     if (isset($matches[1])) {
         $mime = $matches[1];
     } else {
         throw new Exception('Could not determine archive type');
     }
     $file = HabariPackages::tempnam();
     if (!file_put_contents($file, $remote_archive->get_response_body(), LOCK_EX)) {
         throw new Exception('Please make the directory ' . dirname($file) . ' writeable by the server');
     }
     $this->md5 = md5_file($file);
     $this->set_archive_reader($mime, $file);
     unset($remote_archive);
 }
 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;
     }
 }
Example #4
0
 /**
  * @todo the server should return all versions and let hpm decide which version to take
  */
 public static function update_packages($repo)
 {
     $client = new RemoteRequest($repo, 'GET');
     if (Error::is_error($client->execute())) {
         return false;
     }
     try {
         $packages = $client->get_response_body();
         //Utils::debug( $packages );
         $packages = new SimpleXMLElement($packages);
         $package_list = array();
         foreach ($packages->package as $package) {
             if (!$package['guid'] || !$package->versions) {
                 continue;
             }
             $new_package = (array) $package->attributes();
             $new_package = $new_package['@attributes'];
             $new_package['description'] = strval($package->description);
             $versions = array();
             //Utils::debug($package->versions);
             foreach ($package->versions->version as $version) {
                 $version = (array) $version->attributes();
                 $version = $version['@attributes'];
                 if (isset($version['habari_version']) && self::is_compatible($version['habari_version'])) {
                     $versions[$version['version']] = $version;
                 }
             }
             //Utils::debug( $new_package, $versions );
             uksort($versions, create_function('$a,$b', 'return version_compare($b,$a);'));
             $version = current($versions);
             if ($version) {
                 $new_package = array_merge($version, $new_package);
                 if ($old_package = HabariPackage::get($new_package['guid'])) {
                     if (isset($new_package['version']) && version_compare($new_package['version'], $old_package->version, '>')) {
                         if ($old_package->status == 'installed') {
                             $new_package['status'] = 'upgrade';
                         }
                         DB::update(DB::table('packages'), $new_package, array('guid' => $new_package['guid']));
                         $package_list[] = $old_package->id;
                     } else {
                         $package_list[] = $old_package->id;
                     }
                 } else {
                     DB::insert(DB::table('packages'), $new_package);
                     $package_list[] = DB::last_insert_id();
                 }
             }
         }
         Options::set('hpm__repo_version', Version::get_habariversion());
         return $package_list;
     } catch (Exception $e) {
         Utils::debug($e);
         return false;
     }
 }
 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();
 }
 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();
 }
 public function execute($method, $url, $headers, $body, $timeout)
 {
     $result = $this->_request($method, $url, $headers, $body, $timeout);
     if ($result && !Error::is_error($result)) {
         list($response_headers, $response_body) = $result;
         $this->response_headers = $response_headers;
         $this->response_body = $response_body;
         $this->executed = TRUE;
         return TRUE;
     } else {
         return $result;
     }
 }
function shrink($url)
{
    $service = 'http://tinyurl.com/api-create.php?url=';
    $request = new RemoteRequest($service . urlencode($url), 'GET');
    $result = $request->execute();
    if (Error::is_error($result)) {
        throw $result;
    }
    $data = $request->get_response_body();
    if (Error::is_error($data)) {
        throw $data;
    }
    return $data;
}
Example #10
0
 /**
  * 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;
     }
 }
Example #11
0
 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;
 }
Example #12
0
 /**
  * Commit all of the changed info options to the database.
  * If this function is not called, then the options will not be written.
  *
  * @param mixed $metadata_key (optional) Key to use when writing info data.
  * @return bool True if the commit succeeded.
  */
 public function commit($metadata_key = null)
 {
     if (isset($metadata_key)) {
         $this->_key_value = $metadata_key;
     }
     // If the info is not already loaded, and the key value is empty,
     // then we don't have enough info to do the commit
     if (!$this->_loaded && empty($this->_key_value)) {
         return false;
     }
     // If there were no changes, do nothing and succeed.  Yay!
     if (!$this->_dirty) {
         return true;
     }
     foreach ((array) $this->__inforecord_array as $name => $record) {
         if (isset($record['changed']) && $record['changed']) {
             $value = $record['value'];
             if (is_array($value) || is_object($value)) {
                 $result = DB::update($this->_table_name, array($this->_key_name => $this->_key_value, 'name' => $name, 'value' => serialize($value), 'type' => 1), array('name' => $name, $this->_key_name => $this->_key_value));
             } else {
                 $result = DB::update($this->_table_name, array($this->_key_name => $this->_key_value, 'name' => $name, 'value' => $value, 'type' => 0), array('name' => $name, $this->_key_name => $this->_key_value));
             }
             if (Error::is_error($result)) {
                 $result->out();
             }
             $this->__inforecord_array[$name] = array('value' => $value);
         }
     }
     $this->_dirty = false;
     return true;
 }
Example #13
0
 /**
  * Actually execute the request.
  * On success, returns TRUE and populates the response_body and response_headers fields.
  * On failure, throws error.
  */
 public function execute()
 {
     $this->prepare();
     $result = $this->processor->execute($this->method, $this->url, $this->headers, $this->body, $this->timeout);
     if ($result && !Error::is_error($result)) {
         // XXX exceptions?
         $this->response_headers = $this->processor->get_response_headers();
         $this->response_body = $this->processor->get_response_body();
         $this->executed = TRUE;
         return TRUE;
     } else {
         // actually, processor->execute should throw an Error which would bubble up
         // we need a new Error class and error handler for that, though
         $this->executed = FALSE;
         return $result;
     }
 }
Example #14
0
 /**
  * Connect to the SMTP server by instantiating a SMTP object.
  *
  * @return mixed Returns a reference to the SMTP object on success, or
  *			   a Error containing a descriptive error message on
  *			   failure.
  *
  * @since  1.2.0
  * @access public
  */
 public function &getSMTPObject()
 {
     if (is_object($this->_smtp) !== false) {
         return $this->_smtp;
     }
     $this->_smtp = new SMTP($this->host, $this->port, $this->localhost);
     /* If we still don't have an SMTP object at this point, fail. */
     if (is_object($this->_smtp) === false) {
         throw Error::raise('Failed to create a SMTP object', self::ERROR_CREATE);
     }
     /* Configure the SMTP connection. */
     if ($this->debug) {
         $this->_smtp->setDebug(true);
     }
     /* Attempt to connect to the configured SMTP server. */
     if (Error::is_error($res = $this->_smtp->connect($this->timeout))) {
         $error = $this->_error('Failed to connect to ' . $this->host . ':' . $this->port, $res);
         throw Error::raise($error, self::ERROR_CONNECT);
     }
     /* Attempt to authenticate if authentication has been enabled. */
     if ($this->auth) {
         $method = is_string($this->auth) ? $this->auth : '';
         if (Error::is_error($res = $this->_smtp->auth($this->username, $this->password, $method))) {
             $error = $this->_error("{$method} authentication failure", $res);
             $this->_smtp->rset();
             throw Error::raise($error, self::ERROR_AUTH);
         }
     }
     return $this->_smtp;
 }
Example #15
0
 /**
  * Handles get requests for the dashboard
  * @todo update check should probably be cron'd and cached, not re-checked every load
  */
 public function get_dashboard()
 {
     // Not sure how best to determine this yet, maybe set an option on install, maybe do this:
     $firstpostdate = DB::get_value('SELECT min(pubdate) FROM {posts} WHERE status = ?', array(Post::status('published')));
     if (intval($firstpostdate) !== 0) {
         $firstpostdate = time() - $firstpostdate;
     }
     $this->theme->active_time = array('years' => floor($firstpostdate / 31556736), 'months' => floor($firstpostdate % 31556736 / 2629728), 'days' => round($firstpostdate % 2629728 / 86400));
     // get the active theme, so we can check it
     $active_theme = Themes::get_active();
     $active_theme = $active_theme->name . ':' . $active_theme->version;
     // if the active plugin list has changed, expire the updates cache
     if (Cache::has('dashboard_updates') && Cache::get('dashboard_updates_plugins') != Options::get('active_plugins')) {
         Cache::expire('dashboard_updates');
     }
     // if the theme version has changed, expire the updates cache
     if (Cache::has('dashboard_updates') && Cache::get('dashboard_updates_theme') != $active_theme) {
         Cache::expire('dashboard_updates');
     }
     /*
      * Check for updates to core and any hooked plugins
      * cache the output so we don't make a request every load but can still display updates
      */
     if (Cache::has('dashboard_updates')) {
         $this->theme->updates = Cache::get('dashboard_updates');
     } else {
         $updates = Update::check();
         if (!Error::is_error($updates)) {
             Cache::set('dashboard_updates', $updates);
             $this->theme->updates = $updates;
             // cache the set of plugins we just used to check for
             Cache::set('dashboard_updates_plugins', Options::get('active_plugins'));
             // cache the active theme we just used to check for
             Cache::set('dashboard_updates_theme', $active_theme);
         } else {
             $this->theme->updates = array();
         }
     }
     $this->theme->stats = array('author_count' => Users::get(array('count' => 1)), 'page_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('page'), 'status' => Post::status('published'))), 'entry_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('entry'), 'status' => Post::status('published'))), 'comment_count' => Comments::count_total(Comment::STATUS_APPROVED, FALSE), 'tag_count' => Tags::count_total(), 'page_draft_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('page'), 'status' => Post::status('draft'), 'user_id' => User::identify()->id)), 'entry_draft_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('entry'), 'status' => Post::status('draft'), 'user_id' => User::identify()->id)), 'unapproved_comment_count' => User::identify()->can('manage_all_comments') ? Comments::count_total(Comment::STATUS_UNAPPROVED, FALSE) : Comments::count_by_author(User::identify()->id, Comment::STATUS_UNAPPROVED), 'spam_comment_count' => User::identify()->can('manage_all_comments') ? Comments::count_total(Comment::STATUS_SPAM, FALSE) : Comments::count_by_author(User::identify()->id, Comment::STATUS_SPAM), 'user_entry_scheduled_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('any'), 'status' => Post::status('scheduled'), 'user_id' => User::identify()->id)));
     $this->fetch_dashboard_modules();
     // check for first run
     $u = User::identify();
     if (!isset($u->info->experience_level)) {
         $this->theme->first_run = true;
         $u->info->experience_level = 'user';
         $u->info->commit();
     } else {
         $this->theme->first_run = false;
     }
     $this->display('dashboard');
 }
Example #16
0
 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();
         }
     }
 }
Example #17
0
 /**
  * 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');
 }
Example #18
0
 /**
  * Applies the option value to the options table
  * @param string $name Name of the option to set
  * @param mixed $value Value to set
  **/
 public function __set($name, $value)
 {
     if (!isset($this->options)) {
         $this->get_all_options();
     }
     $value = Plugins::filter('option_set_value', $value, $name, isset($this->options[$name]) ? $this->options[$name] : null);
     $this->options[$name] = $value;
     if (is_array($value) || is_object($value)) {
         $result = DB::update(DB::table('options'), array('name' => $name, 'value' => serialize($value), 'type' => 1), array('name' => $name));
     } else {
         $result = DB::update(DB::table('options'), array('name' => $name, 'value' => $value, 'type' => 0), array('name' => $name));
     }
     if (Error::is_error($result)) {
         $result->out();
         die;
     }
 }
 /**
  * Upload a photo
  *
  * @param string $file_url Temporary URL of uploaded file
  * @param string $album The album id
  * @param string title The title of the photo
  * @return mixed An xml string of the result or false on error
  */
 public function upload_photo($file_url, $album, $title, $summary)
 {
     $photo .= 'Media multipart posting' . "\n";
     $photo .= '--END_OF_PART' . "\n";
     $photo .= 'Content-Type: application/atom+xml' . "\n\n";
     // need two end of lines
     $photo .= '<entry xmlns="http://www.w3.org/2005/Atom">' . "\n";
     $photo .= '<title>' . $title . '</title>' . "\n";
     $photo .= '<summary>' . $summary . '</summary>' . "\n";
     $photo .= '<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>' . "\n";
     $photo .= '</entry>' . "\n";
     $photo .= '--END_OF_PART' . "\n";
     $photo .= 'Content-Type: image/jpeg' . "\n\n";
     // need to end of lines
     $photo .= file_get_contents($file_url);
     $photo .= "\n" . '--END_OF_PART--' . "\n";
     $result = $this->call(PicasaAPI::$QUERY_URLS['picasa'] . "/album/" . $album, array('method' => 'POST', 'http_headers' => array('Content-Type' => 'multipart/related; boundary="END_OF_PART"', 'MIME-version' => '1.0')), $photo);
     if (Error::is_error($result)) {
         return $result->get();
     } else {
         return "Photo successfuly uploaded";
     }
 }
Example #20
0
	function photosUploadCheckTickets( $tickets )
	{
		if ( is_array( $tickets ) ){
			foreach( $tickets as $key => $value ){
				if ( $key ){
					$params['tickets'] .= ' ';
				}
				$params['tickets'] .= $value;
			}
		}
		else{
			$params['tickets'] = $tickets;
		}

		$xml = $this->call( 'flickr.photos.upload.checkTickets', $params );
		if ( Error::is_error( $xml ) ){
			throw $xml;
		}

		foreach( $xml->uploader->ticket as $ticket ){
			foreach( $ticket->attributes() as $key => $value ){
				$uptick[(string)$ticket['id']][$key] = (string)$value;
			}
		}
		return $uptick;
	}
 /**
  * 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();
         }
     }
 }
 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());
 }
 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;
 }
Example #24
0
 private function fetch($relative_url, $response_format = 'php')
 {
     $request = new RemoteRequest(self::API_URL . $relative_url . '.' . $response_format, 'GET', 20);
     $result = $request->execute();
     if (Error::is_error($result)) {
         throw $result;
     }
     $response = $request->get_response_body();
     switch ($response_format) {
         case 'php':
             try {
                 if ($response_array = unserialize($response)) {
                     return $response_array;
                 }
             } catch (Exception $e) {
                 Session::error('Problem with response from Vimeo.', 'Vimeo');
                 return false;
             }
             break;
         default:
             //TODO: Implement the other formats (xml, json).
             Session::error('Output format is not supported.', 'Vimeo');
             return false;
             break;
     }
 }
Example #25
0
 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();
         }
     }
 }
 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;
 }
Example #27
0
 /**
  * Applies the option value to the options table
  * @param string $name Name of the option to set
  * @param mixed $value Value to set
  **/
 public function __set($name, $value)
 {
     if (!isset($this->options)) {
         $this->get_all_options();
     }
     // if the option already exists and has the same value, there is nothing to update and we shouldn't waste a db hit
     // i can't think of any negative implications of this, but that's no guarantee
     if (isset($this->options[$name]) && $this->options[$name] == $value) {
         return;
     }
     $value = Plugins::filter('option_set_value', $value, $name, isset($this->options[$name]) ? $this->options[$name] : null);
     $this->options[$name] = $value;
     // we now serialize everything, not just arrays and objects
     $result = DB::update(DB::table('options'), array('name' => $name, 'value' => serialize($value), 'type' => 1), array('name' => $name));
     if (Error::is_error($result)) {
         $result->out();
         die;
     }
 }
 /**
  * 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');
 }