function action_add_template_vars($theme)
 {
     $username = Options::get('freshsurf__username');
     $password = Options::get('freshsurf__password');
     $count = Options::get('freshsurf__count');
     if ($username != '' && $password != '') {
         if (Cache::has('freshsurf__' . $username)) {
             $response = Cache::get('freshsurf__' . $username);
         } else {
             $request = new RemoteRequest("https://{$username}:{$password}@" . self::BASE_URL . "posts/recent?count={$count}", 'GET', 20);
             $request->execute();
             $response = $request->get_response_body();
             Cache::set('freshsurf__' . $username, $response);
         }
         $delicious = @simplexml_load_string($response);
         if ($delicious instanceof SimpleXMLElement) {
             $theme->delicious = $delicious;
         } else {
             $theme->delicious = @simplexml_load_string('<posts><post href="#" description="Could not load feed from delicious.  Is username/password correct?"/></posts>');
             Cache::expire('freshsurf__' . $username);
         }
     } else {
         $theme->delicious = @simplexml_load_string('<posts></posts>');
     }
 }
 /**
  * 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;
 }
 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;
 }
Beispiel #5
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);
 }
Beispiel #6
0
 /**
  * Execute the request. Populates result field.
  */
 public function execute()
 {
     $rr = new RemoteRequest($this->url, 'POST');
     $rr->add_header('Content-Type: text/xml;charset=utf-8');
     $rr->set_body($this->request_body);
     // should throw an error on failure
     $rr->execute();
     // in that case, we should never get here
     $this->result = xmlrpc_decode($rr->get_response_body());
 }
Beispiel #7
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;
     }
 }
Beispiel #8
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
  * @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();
 }
Beispiel #12
0
 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;
         }
     }
 }
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;
}
Beispiel #14
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;
     }
 }
 public function embed_gists($content)
 {
     $gists_regex = '/<script[^>]+src="(http:\\/\\/gist.github.com\\/[^"]+)"[^>]*><\\/script>/i';
     // remove gists from multiple-post templates
     if (Options::get('gistextras__removefrommultiple')) {
         if (!in_array(URL::get_matched_rule()->name, array('display_entry', 'display_page'))) {
             return preg_replace($gists_regex, '', $content);
         }
     }
     preg_match_all($gists_regex, $content, $gists);
     for ($i = 0, $n = count($gists[0]); $i < $n; $i++) {
         if (Options::get('gistextras__cachegists')) {
             if (Cache::has($gists[1][$i])) {
                 $gist = Cache::get($gists[1][$i]);
             } else {
                 if ($gist = RemoteRequest::get_contents($gists[1][$i])) {
                     $gist = $this->process_gist($gist);
                     Cache::set($gists[1][$i], $gist, 86400);
                     // cache for 1 day
                 }
             }
         } else {
             $gist = RemoteRequest::get_contents($gists[1][$i]);
             $gist = $this->process_gist($gist);
         }
         // replace the script tag
         $content = str_replace($gists[0][$i], $gist, $content);
     }
     return $content;
 }
 public function fetch_yahoo_tags($text)
 {
     $appID = 'UZuNQnrV34En.c9itu77sQrdjp.FQU81t8azZeE5YmWjRkP9wVlPg.CPIc8eLZT68GI-';
     $context = $text;
     $request = new RemoteRequest('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction', 'POST');
     $request->set_params(array('appid' => $appID, 'context' => $context));
     $tags = array();
     // Utils::debug($request->execute());
     if (!is_object($request->execute())) {
         $response = $request->get_response_body();
         $xml = new SimpleXMLElement($response);
         foreach ($xml->Result as $tag) {
             $tags[] = strval($tag);
         }
     }
     return $tags;
 }
Beispiel #17
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;
 }
Beispiel #18
0
 /**
  * Executes all cron jobs in the DB if there are any to run.
  *
  * @param boolean $async If true, allows execution to continue by making an asynchronous request to a cron URL
  */
 static function run_cron($async = false)
 {
     // check if it's time to run crons, and if crons are already running.
     $next_cron = HabariDateTime::date_create(Options::get('next_cron', 1));
     $time = HabariDateTime::date_create();
     if ($next_cron->int > $time->int || Options::get('cron_running') && Options::get('cron_running') > microtime(true)) {
         return;
     }
     // cron_running will timeout in 10 minutes
     // round cron_running to 4 decimals
     $run_time = microtime(true) + 600;
     $run_time = sprintf("%.4f", $run_time);
     Options::set('cron_running', $run_time);
     if ($async) {
         // Timeout is really low so that it doesn't wait for the request to finish
         $cronurl = URL::get('cron', array('time' => $run_time, 'asyncronous' => Utils::crypt(Options::get('GUID'))));
         $request = new RemoteRequest($cronurl, 'GET', 1);
         try {
             $request->execute();
         } catch (RemoteRequest_Timeout $e) {
             // the request timed out - we knew that would happen
         } catch (Exception $e) {
             // some other error occurred. log it.
             EventLog::log($e->getMessage(), 'err', 'crontab', 'habari', $e);
         }
     } else {
         // @todo why do we usleep() and why don't we just call act_poll_cron()?
         usleep(5000);
         if (Options::get('cron_running') != $run_time) {
             return;
         }
         $time = HabariDateTime::date_create();
         $crons = DB::get_results('SELECT * FROM {crontab} WHERE start_time <= ? AND next_run <= ? AND active != ?', array($time->sql, $time->sql, 0), 'CronJob');
         if ($crons) {
             foreach ($crons as $cron) {
                 $cron->execute();
             }
         }
         EventLog::log(_t('CronTab run completed.'), 'debug', 'crontab', 'habari', $crons);
         // set the next run time to the lowest next_run OR a max of one day.
         $next_cron = DB::get_value('SELECT next_run FROM {crontab} ORDER BY next_run ASC LIMIT 1', array());
         Options::set('next_cron', min(intval($next_cron), $time->modify('+1 day')->int));
         Options::set('cron_running', false);
     }
 }
 public function filter_send_mail($handled, $mail)
 {
     if (!$handled) {
         $headers = array('Accept: application/json', 'Content-Type: application/json', 'X-Postmark-Server-Token: ' . Options::get('postmark__apikey'));
         $data = array('To' => $mail['to'], 'subject' => $mail['subject'], 'TextBody' => $mail['message'], 'From' => $mail['headers']['From']);
         $rr = new RemoteRequest('http://api.postmarkapp.com/email', 'POST');
         $rr->set_body(json_encode($data));
         $rr->add_headers($headers);
         try {
             $rr->execute();
             EventLog::log(_t('Send message to %s via Postmark', array($mail['to'])), 'info', 'default', null, array($data, $headers));
             Session::notice(var_export($rr->get_response_headers(), 1));
         } catch (Exception $e) {
             EventLog::log(_t('Failed to send message to %s via Postmark', array($mail['to'])), 'err', 'default', null, array($e->getMessage(), $data, $headers));
             Session::error('There was a problem sending your message.  Please contact the site administrators directly.');
         }
     }
     return true;
 }
 public function action_plugin_act_serve_ga()
 {
     if (Cache::has('ga.js')) {
         $js = Cache::get('ga.js');
     } else {
         $js = RemoteRequest::get_contents('http://www.google-analytics.com/ga.js');
         Cache::set('ga.js', $js, 86400);
         // cache for 1 day
     }
     // Clean the output buffer, so we can output from the header/scratch
     ob_clean();
     header('Content-Type: application/javascript');
     echo $js;
 }
Beispiel #21
0
 /**
  * Executes all cron jobs in the DB if there are any to run.
  *
  * @param boolean $async If true, allows execution to continue by making an asynchronous request to a cron URL
  */
 static function run_cron($async = false)
 {
     // check if it's time to run crons, and if crons are already running.
     $next_cron = HabariDateTime::date_create(Options::get('next_cron'));
     $time = HabariDateTime::date_create();
     if ($next_cron->int > $time->int || Options::get('cron_running') && Options::get('cron_running') > microtime(true)) {
         return;
     }
     // cron_running will timeout in 10 minutes
     // round cron_running to 4 decimals
     $run_time = microtime(true) + 600;
     $run_time = sprintf("%.4f", $run_time);
     Options::set('cron_running', $run_time);
     if ($async) {
         // Timeout is really low so that it doesn't wait for the request to finish
         $cronurl = URL::get('cron', array('time' => $run_time, 'asyncronous' => Utils::crypt(Options::get('guid'))));
         $request = new RemoteRequest($cronurl, 'GET', 1);
         $request->execute();
     } else {
         usleep(5000);
         if (Options::get('cron_running') != $run_time) {
             return;
         }
         $time = HabariDateTime::date_create();
         $crons = DB::get_results('SELECT * FROM {crontab} WHERE start_time <= ? AND next_run <= ?', array($time->sql, $time->sql), 'CronJob');
         if ($crons) {
             foreach ($crons as $cron) {
                 $cron->execute();
             }
         }
         // set the next run time to the lowest next_run OR a max of one day.
         $next_cron = DB::get_value('SELECT next_run FROM {crontab} ORDER BY next_run ASC LIMIT 1', array());
         Options::set('next_cron', min(intval($next_cron), $time->modify('+1 day')->int));
         Options::set('cron_running', false);
     }
 }
 public function get_technorati_stats()
 {
     $technorati_stats = array();
     $technorati_url = 'http://api.technorati.com/bloginfo?key=' . Options::get('technorati__apikey') . '&url=' . Site::get_url('habari');
     $response = RemoteRequest::get_contents($technorati_url);
     if ($response !== FALSE) {
         $xml = new SimpleXMLElement($response);
         if (isset($xml->document->result->weblog)) {
             $technorati_inbound_blogs = (int) $xml->document->result->weblog[0]->inboundblogs;
             $technorati_inbound_links = (int) $xml->document->result->weblog[0]->inboundlinks;
             $technorati_rank = (int) $xml->document->result->weblog[0]->rank;
             $technorati_stats['Rank'] = $technorati_rank;
             $technorati_stats['Inbound Links'] = $technorati_inbound_links;
             $technorati_stats['Inbound Blogs'] = $technorati_inbound_blogs;
         }
     }
     return $technorati_stats;
 }
Beispiel #23
0
 function fetch($method, $params = array(), $tokenize = false, $debug = false)
 {
     $url = $this->endpoint;
     $url .= '?method=' . strtolower($method);
     foreach ($params as $key => $val) {
         $url .= '&' . $key . '=' . $val;
     }
     $url .= '&api_key=' . $this->key;
     if ($debug) {
         print_r($url);
     }
     $contents = RemoteRequest::get_contents($url);
     $data = new SimpleXMLElement($contents);
     if ($data['status'] == 'ok') {
         return $data;
     } else {
         return FALSE;
     }
 }
 /**
  * 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;
     }
 }
Beispiel #25
0
 private function call($action, DefensioParams $params)
 {
     $client = new RemoteRequest($this->build_url($action), 'POST');
     $client->set_postdata($params->get_post_data());
     if ($client->execute()) {
         if (self::get_http_status($client->get_response_headers()) == '401') {
             throw new Exception('Invalid/Unauthorized API Key');
         }
         $response = new DefensioResponse($client->get_response_body());
         unset($client);
         return $response;
     } else {
         throw new Exception('Server Not Responding');
     }
 }
 public function action_block_content_textlinkads($block)
 {
     if (!Cache::has('textlinkads')) {
         $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
         $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
         $inventory_key = 'NYWSW7HTCIN307VV7BBD';
         $tla_uri = 'http://www.text-link-ads.com/xml.php?inventory_key=' . $inventory_key . '&referer=' . urlencode($request_uri) . '&user_agent=' . urlencode($user_agent);
         Cache::set('textlinkads', RemoteRequest::get_contents($tla_uri));
         Utils::debug('Cache set');
     }
     $xml = new SimpleXMLElement(Cache::get('textlinkads'));
     $links = array();
     foreach ($xml->Link as $link) {
         $ad = new StdClass();
         $ad->before = (string) $link->BeforeText;
         $ad->after = (string) $link->AfterText;
         $ad->text = (string) $link->Text;
         $ad->url = (string) $link->URL;
         $links[(string) $link->LinkID] = $ad;
     }
     $block->links = $links;
 }
Beispiel #27
0
 /**
  * Allow method overloading for this class.
  * This method allows any method name to be called on this object.  The method
  * called is the method called via RPC, within the scope defined in $this->scope.
  *
  * @param string $fname The function name to call
  * @param array $args An array of arguments that were called with the function
  * @return array The result array
  */
 public function __call($fname, $args)
 {
     if ($this->scope != '') {
         $rpc_method = "{$this->scope}.{$fname}";
     } else {
         $rpc_method = $fname;
     }
     $rpx = new SimpleXMLElement('<methodCall/>');
     $rpx->addChild('methodName', $rpc_method);
     if (count($args) > 0) {
         $params = $rpx->addchild('params');
         foreach ($args as $arg) {
             $param = $params->addchild('param');
             XMLRPCUtils::encode_arg($param, $arg);
         }
     }
     $request = new RemoteRequest($this->entrypoint, 'POST');
     $request->add_header('Content-Type: text/xml;charset=utf-8');
     $request->set_body($rpx->asXML());
     $request->execute();
     if ($request->executed()) {
         $response = $request->get_response_body();
         // @todo this should use the MultiByte class, not directly call mb_string functions
         $enc = mb_detect_encoding($response);
         $responseutf8 = mb_convert_encoding($response, 'UTF-8', $enc);
         try {
             // @todo this should use libxml_use_internal_errors() instead of trying to hide the PHP warning see the plugin info parsing code for an example
             $bit = ini_get('error_reporting');
             error_reporting($bit && !E_WARNING);
             $responsexml = new SimpleXMLElement($responseutf8);
             error_reporting($bit);
             $tmp = $responsexml->xpath('//params/param/value');
             if (!($responsestruct = reset($tmp))) {
                 $tmp = $responsexml->xpath('//fault/value');
                 if (!($responsestruct = reset($tmp))) {
                     throw new Exception(_t('Invalid XML response.'));
                 }
             }
             return XMLRPCUtils::decode_args($responsestruct);
         } catch (Exception $e) {
             //Utils::debug( $response, $e );
             error_reporting($bit);
             return false;
         }
     }
 }
Beispiel #28
0
 /**
  * Allow method overloading for this class.
  * This method allows any method name to be called on this object.  The method
  * called is the method called via RPC, within the scope defined in $this->scope.
  *
  * @param string $fname The function name to call
  * @param array $args An array of arguments that were called with the function
  * @return array The result array
  */
 public function __call($fname, $args)
 {
     if ($this->scope != '') {
         $rpc_method = "{$this->scope}.{$fname}";
     } else {
         $rpc_method = $fname;
     }
     $rpx = new SimpleXMLElement('<methodCall/>');
     $rpx->addChild('methodName', $rpc_method);
     if (count($args) > 0) {
         $params = $rpx->addchild('params');
         foreach ($args as $arg) {
             $param = $params->addchild('param');
             XMLRPCUtils::encode_arg($param, $arg);
         }
     }
     $request = new RemoteRequest($this->entrypoint, 'POST');
     $request->add_header('Content-Type: text/xml');
     $request->set_body($rpx->asXML());
     $request->execute();
     if ($request->executed()) {
         $response = $request->get_response_body();
         $enc = mb_detect_encoding($response);
         $responseutf8 = mb_convert_encoding($response, 'UTF-8', $enc);
         try {
             $bit = ini_get('error_reporting');
             error_reporting($bit && !E_WARNING);
             $responsexml = new SimpleXMLElement($responseutf8);
             error_reporting($bit);
             $tmp = $responsexml->xpath('//params/param/value');
             if (!($responsestruct = reset($tmp))) {
                 $tmp = $responsexml->xpath('//fault/value');
                 if (!($responsestruct = reset($tmp))) {
                     throw new Exception(_t('Invalid XML response.'));
                 }
             }
             return XMLRPCUtils::decode_args($responsestruct);
         } catch (Exception $e) {
             //Utils::debug($response, $e);
             error_reporting($bit);
             return false;
         }
     }
 }
Beispiel #29
0
	/**
	 * Send a single Pingback
	 * @param string $source_uri The URI source of the ping (here)
	 * @param string $target_uri The URI destination of the ping (there, the site linked to in the content)
	 * @param Post $post The post	object that is initiating the ping, used to track the pings that were sent
	 * @todo If receive error code of already pinged, add to the successful.
	 */
	public function send_pingback( $source_uri, $target_uri, $post = NULL )
	{
		// RemoteRequest makes it easier to retrieve the headers.
		try {
			$rr = new RemoteRequest( $target_uri );
			$rr->execute();
			if ( ! $rr->executed() ) {
				return false;
			}
		}
		catch ( Exception $e ) {
			// log the pingback error
			EventLog::log( _t( 'Unable to retrieve target, can\'t detect pingback endpoint. (Source: %1$s | Target: %2$s)', array( $source_uri, $target_uri ) ), 'err', 'Pingback' );
			return false;
		}

		$headers = $rr->get_response_headers();
		$body = $rr->get_response_body();

		// Find a Pingback endpoint.
		if ( isset( $headers['X-Pingback'] ) ) {
			$pingback_endpoint = $headers['X-Pingback'];
		}
		elseif ( preg_match( '/<link rel="pingback" href="([^"]+)" ?\/?'.'>/is', $body, $matches ) ) {
			$pingback_endpoint = $matches[1];
		}
		else {
			// No Pingback endpoint found.
			return false;
		}

		try {
			$response = XMLRPCClient::open( $pingback_endpoint )->pingback->ping( $source_uri, $target_uri );
		}
		catch ( Exception $e ) {
			EventLog::log( _t( 'Invalid Pingback endpoint - %1$s (Source: %2$s | Target: %3$s)', array( $pingback_endpoint, $source_uri, $target_uri ) ), 'err', 'Pingback' );
			return false;
		}

		if ( isset( $response->faultString ) ) {
			EventLog::log( _t( 'Pingback error: %1$s - %2$s (Source: %3$s | Target: %4$s)', array( $response->faultCode, $response->faultString, $source_uri, $target_uri ) ), 'err', 'Pingback' );
			return false;
		}
		else {
			// The pingback has been registered and is stored as a successful pingback.
			if ( is_object( $post ) ) {
				if ( isset( $post->info->pingbacks_successful ) ) {
					$pingbacks_successful = $post->info->pingbacks_successful;
					$pingbacks_successful[]= $target_uri;
					$post->info->pingbacks_successful = $pingbacks_successful;
				}
				else {
					$post->info->pingbacks_successful = array( $target_uri );
				}
				$post->info->commit();
			}
			return true;
		}
	}
Beispiel #30
0
 /**
  * AWS ItemLookup
  *
  * @access private
  * @param string $asin
  * @return string
  */
 private function item_lookup($asin)
 {
     $url = 'http://ecs.amazonaws.' . Options::get('amazon__country') . '/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=' . $this->access_key . '&Operation=ItemLookup&ResponseGroup=Large&ItemId=' . $asin;
     $associate_tag = Options::get('amazon__associate_tag');
     if (!empty($associate_tag)) {
         $url .= '&AssociateTag=' . $associate_tag;
     }
     $request = new RemoteRequest($url, 'GET');
     if ($request->execute() === false) {
         return false;
     }
     return $request->get_response_body();
 }