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>');
     }
 }
 /**
  * Post a status to service
  * @param string $svcurl Catenation of user server, API endpoints
  * @param string $notice The new status to post
  **/
 public function post_status($svcurl, $notice, $name, $pw)
 {
     $request = new RemoteRequest($svcurl, 'POST');
     $request->add_header(array('Authorization' => 'Basic ' . base64_encode("{$name}:{$pw}")));
     $request->set_body('source=habari&status=' . urlencode($notice));
     $request->execute();
 }
 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;
 }
Example #4
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);
 }
 /**
  * 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;
 }
Example #7
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());
 }
Example #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, array('Update', 'filter_unchanged'));
     } catch (Exception $e) {
         // catches any RemoteRequest errors or XML parsing problems, etc.
         // bubble up
         throw $e;
     }
 }
Example #9
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();
 }
Example #13
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;
}
Example #15
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 #16
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');
     }
 }
Example #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;
 }
Example #18
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;
         }
     }
 }
 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;
 }
Example #20
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);
     }
 }
Example #21
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;
         }
     }
 }
 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;
 }
 /**
  * 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;
     }
 }
Example #24
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);
     }
 }
Example #25
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;
		}
	}
Example #26
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();
 }
 /**
  * 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();
         }
     }
 }
Example #28
0
	$rr->set_params( array (
		'query' => 'var',
		'another' => 'variable',
	) );
	$res_get= $rr->execute();
	if ( $res_get === TRUE ) {
	 	$results[]= array( get_class( $processor ), $rr->get_response_headers(), substr( $rr->get_response_body(), 0 ) );
	}
	else {
		$results[]= array( get_class( $processor ), $res_get, );
	}

	$rr= new RemoteRequest( 'http://test.habariproject.org/post', 'POST' );
	$rr->__set_processor( $processor );
	$rr->set_body( 'If you can read this, the test was successful.' );
	$res_post= $rr->execute();
	if ( $res_post === TRUE ) {
	 	$results[]= array( get_class( $processor ), $rr->get_response_headers(), substr( $rr->get_response_body(), 0 ) );
	}
	else {
		$results[]= array( get_class( $processor ), $res_post, );
	}

	foreach ( $tests as $name => $group ) {
		print( "<h2>{$name}</h2>\n" );
		foreach ( $group as $test ) {
			$result= eval( 'return (' . $test . ');' );
			printf( "<p><strong>%s</strong> == ( %s )</p>\n", bs( $result ), var_export( $test, TRUE ) );

			Utils::debug( array_shift( $results ) );
			if ( ! $result ) {
Example #29
0
 /**
  * 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');
 }
Example #30
0
 /**
  * Static helper function to quickly fetch an URL, with semantics similar to
  * PHP's file_get_contents. Does not support
  *
  * Returns the content on success or false if an error occurred.
  *
  * @param string $url The URL to fetch
  * @param bool $use_include_path whether to search the PHP include path first (unsupported)
  * @param resource $context a stream context to use (unsupported)
  * @param int $offset how many bytes to skip from the beginning of the result
  * @param int $maxlen how many bytes to return
  * @return string description
  */
 public static function get_contents($url, $use_include_path = false, $context = null, $offset = 0, $maxlen = -1)
 {
     try {
         $rr = new RemoteRequest($url);
         if ($rr->execute() === true) {
             return $maxlen != -1 ? MultiByte::substr($rr->get_response_body(), $offset, $maxlen) : MultiByte::substr($rr->get_response_body(), $offset);
         } else {
             return false;
         }
     } catch (Exception $e) {
         // catch any exceptions to try and emulate file_get_contents() as closely as possible.
         // if you want more control over the errors, instantiate RemoteRequest manually
         return false;
     }
 }