Ejemplo n.º 1
0
 function save($data)
 {
     if (!$data['GA_optin']) {
         trigger_error('did not opt to join');
         return true;
     }
     $options = $this->getOptions();
     $request = new HTTP_Request($options['hostname'] . '/offsite-join.tcl');
     $request->setMethod(HTTP_REQUEST_METHOD_POST);
     $request->addPostData('domain', $options['domain']);
     if ($options['source']) {
         $request->addPostData('source', $options['source']);
     }
     if ($options['update']) {
         $request->addPostData('update', $options['update']);
     }
     foreach ($this->translate($data) as $name => $value) {
         $request->addPostData($name, $value);
     }
     if (!PEAR::isError($request->sendRequest())) {
         $message = trim($request->getResponseBody());
         if ('OK' == $message) {
             return true;
         } else {
             $this->ERROR = $message;
             trigger_error($message);
             return false;
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Retrieves data from cache, if it's there.  If it is, but it's expired,
  * it performs a conditional GET to see if the data is updated.  If it
  * isn't, it down updates the modification time of the cache file and
  * returns the data.  If the cache is not there, or the remote file has been
  * modified, it is downloaded and cached.
  *
  * @param string URL of remote file to retrieve
  * @param int Length of time to cache file locally before asking the server
  *            if it changed.
  * @return string File contents
  */
 function retrieveFile($url, $cacheLength, $cacheDir)
 {
     $cacheID = md5($url);
     $cache = new Cache_Lite(array("cacheDir" => $cacheDir, "lifeTime" => $cacheLength));
     if ($data = $cache->get($cacheID)) {
         return $data;
     } else {
         // we need to perform a request, so include HTTP_Request
         include_once 'HTTP/Request.php';
         // HTTP_Request has moronic redirect "handling", turn that off (Alexey Borzov)
         $req = new HTTP_Request($url, array('allowRedirects' => false));
         // if $cache->get($cacheID) found the file, but it was expired,
         // $cache->_file will exist
         if (isset($cache->_file) && file_exists($cache->_file)) {
             $req->addHeader('If-Modified-Since', gmdate("D, d M Y H:i:s", filemtime($cache->_file)) . " GMT");
         }
         $req->sendRequest();
         if (!($req->getResponseCode() == 304)) {
             // data is changed, so save it to cache
             $data = $req->getResponseBody();
             $cache->save($data, $cacheID);
             return $data;
         } else {
             // retrieve the data, since the first time we did this failed
             if ($data = $cache->get($cacheID, 'default', true)) {
                 return $data;
             }
         }
     }
     Services_ExchangeRates::raiseError("Unable to retrieve file {$url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED);
     return false;
 }
Ejemplo n.º 3
0
 /**
  * Sets the input xml file to be parsed
  *
  * @access  public
  * @param   string  $file  Filename(full path)
  * @return  mixed   True on success or error on failure
  */
 function setInputFile($file)
 {
     require_once PEAR_PATH . 'HTTP/Request.php';
     $httpRequest = new HTTP_Request($file, $this->_params);
     $httpRequest->setMethod(HTTP_REQUEST_METHOD_GET);
     $resRequest = $httpRequest->sendRequest();
     if (PEAR::isError($resRequest)) {
         return $resRequest;
     } elseif ($httpRequest->getResponseCode() != 200) {
         return $this->raiseError('HTTP response error', HTTP_REQUEST_ERROR_RESPONSE);
     }
     $data = trim($httpRequest->getResponseBody());
     if (version_compare(PHP_VERSION, '5.0.0', '<')) {
         if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $data, $matches)) {
             $srcenc = strtoupper($matches[1]);
             if (!in_array($srcenc, $this->_validEncodings)) {
                 if (function_exists('iconv')) {
                     $data = @iconv($srcenc, 'UTF-8', $data);
                 } elseif (function_exists('mb_list_encodings') && in_array($srcenc, array_map('strtoupper', mb_list_encodings()))) {
                     $data = @mb_convert_encoding($data, 'UTF-8', $srcenc);
                 }
             }
         }
     }
     $this->setInputString($data);
     return true;
 }
Ejemplo n.º 4
0
 /**
  * getRSS
  * 
  * @access protected
  */
 protected function getrss($url)
 {
     require_once 'HTTP/Request.php';
     $req = new HTTP_Request($url, array('timeout' => 4, 'readTimeout' => array(4, 0)));
     $result = $req->sendRequest();
     if (PEAR::isError($result)) {
         $mes = htmlspecialchars($result->getMessage());
         return "<p class=\"warning\">RSSを読み込めません({$mes})。</p>";
     }
     $xml = @simplexml_load_string($req->getResponseBody());
     if ($xml === false) {
         return '<p class="warning">RSSを解釈できません。</p>';
     }
     $ret[] = '<ul class="plugin_rss">';
     foreach ($xml->item as $item) {
         /**
          * Namespace付きの子要素を取得
          * この場合、<dc:date>要素が対象
          */
         $dc = $item->children('http://purl.org/dc/elements/1.1/');
         $date = isset($dc->date) ? '&nbsp;(' . date('Y-m-d H:i', strtotime($dc->date)) . ')' : '';
         $_link = htmlspecialchars($item->link);
         $_title = htmlspecialchars(mb_convert_encoding($item->title, 'UTF-8', 'auto'));
         $line = '<li>';
         $line .= "<a href=\"{$_link}\">{$_title}</a>" . $date;
         $line .= '</li>';
         $ret[] = $line;
     }
     $ret[] = '</ul>';
     return join("\n", $ret);
 }
Ejemplo n.º 5
0
 function fetchData($username, $password)
 {
     switch ($this->options['cryptType']) {
         case 'blowfish':
             include_once 'Crypt/Blowfish.php';
             $bf = new Crypt_Blowfish($this->options['cryptKey']);
             $password = $bf->encrypt($password);
             $password = base64_encode($password);
             break;
         default:
             if (function_exists($this->options['cryptType'])) {
                 $password = $this->options['cryptType']($password);
             }
             break;
     }
     $req = new HTTP_Request();
     $req->setURL($this->options['URL']);
     $req->setMethod(HTTP_REQUEST_METHOD_GET);
     $req->addQueryString($this->options['usernameKey'], $username);
     $req->addQueryString($this->options['passwordKey'], $password);
     if (!PEAR::isError($req->sendRequest())) {
         $response = $req->getResponseBody();
     } else {
         return false;
     }
     $unserializer = new XML_Unserializer();
     if ($unserializer->unserialize($response)) {
         $this->result_value = $unserializer->getUnserializedData();
         if ($this->result_value[$this->options['resultKey']] == $this->options['correctValue']) {
             return true;
         }
     }
     return false;
 }
 /**
  * versionCheck - Get the most current version of nterchange and cache the result.
  *
  * @return 	array 	Information about the newest version of nterchange.
  **/
 function versionCheck()
 {
     require_once 'Cache/Lite.php';
     $options = array('cacheDir' => CACHE_DIR . '/ntercache/', 'lifeTime' => $this->check_version_interval);
     $cache = new Cache_Lite($options);
     $yaml = $cache->get($this->cache_name, $this->cache_group);
     if (empty($yaml)) {
         include_once 'HTTP/Request.php';
         $req = new HTTP_Request($this->check_version_url);
         if (!PEAR::isError($req->sendRequest())) {
             $yaml = $req->getResponseBody();
             $cached = $cache->save($yaml, $this->cache_name, $this->cache_group);
             if ($cached == true) {
                 NDebug::debug('Version check - data is from the web and is now cached.', N_DEBUGTYPE_INFO);
             } else {
                 NDebug::debug('Version check - data is from the web and is NOT cached.', N_DEBUGTYPE_INFO);
             }
         }
     } else {
         NDebug::debug('Version check - data is from the cache.', N_DEBUGTYPE_INFO);
     }
     require_once 'vendor/spyc.php';
     $newest_version_info = @Spyc::YAMLLoad($yaml);
     return $newest_version_info;
 }
Ejemplo n.º 7
0
 public function shorten($url, $text)
 {
     $req = new HTTP_Request($this->apiurl . '?url=' . urlencode($url) . "&text=" . urlencode($text) . "&maxchars=120");
     if (!PEAR::isError($req->sendRequest())) {
         return json_decode($req->getResponseBody(), true);
     }
     return "";
 }
Ejemplo n.º 8
0
 public function shorten($url)
 {
     $req = new HTTP_Request($this->apiurl . urlencode($url));
     if (!PEAR::isError($req->sendRequest())) {
         return $req->getResponseBody();
     }
     return "";
 }
Ejemplo n.º 9
0
 /**
  * @throws BadRequestException
  * @param  $method
  * @param  $args
  * @return mixed
  */
 public function call($method, $args)
 {
     $req = new HTTP_Request($this->conf->endpoint . $method);
     $req->setMethod('POST');
     $args['app_id'] = $this->conf->app_id;
     foreach ($args as $key => $value) {
         $req->addPostData($key, $value);
     }
     $sig = sign($args, $this->conf->key);
     $req->addPostData('signature', $sig['signature']);
     $req->addPostData('time', $sig['time']);
     $req->sendRequest();
     if ($req->getResponseCode() != 200) {
         throw new BadRequestException($req->getResponseBody());
     }
     return json_decode($req->getResponseBody());
 }
Ejemplo n.º 10
0
 /**
  * Helper function to fetch HTTP-URLs
  *
  * @param string $url
  * @return string
  * @todo Error handling is missing
  */
 protected function _fetch($url)
 {
     require_once S9Y_PEAR_PATH . 'HTTP/Request.php';
     $request = new HTTP_Request($url);
     $request->setMethod(HTTP_REQUEST_METHOD_GET);
     $request->sendRequest();
     return $request->getResponseBody();
 }
 function doSearch($url)
 {
     $req = new HTTP_Request($url);
     $req->sendRequest();
     $contents = $req->getResponseBody();
     if (!xml_parse($this->_parser, $contents)) {
         die(sprintf('XML error: %s at line %d', xml_error_string(xml_get_error_code($this->_parser)), xml_get_current_line_number($this->_parser)));
     }
     xml_parser_free($this->_parser);
 }
 /**
  * serendipity_plugin_zooomr::getURL()
  * downloads the content from an URL and returns it as a string
  *
  * @author Stefan Lange-Hegermann
  * @since 02.08.2006
  * @param string $url URL to get
  * @return string downloaded Data from "$url"
  */
 function get_url($url)
 {
     require_once S9Y_PEAR_PATH . 'HTTP/Request.php';
     $req = new HTTP_Request($url);
     if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') {
         $store = file_get_contents($url);
     } else {
         $store = $req->getResponseBody();
     }
     return $store;
 }
Ejemplo n.º 13
0
 function sendRequest($return_body = true)
 {
     $this->Response = $this->HttpRequest->sendRequest();
     $this->code = $this->HttpRequest->getResponseCode();
     if (PEAR::isError($this->Response)) {
         $this->error = $this->Response->getMessage();
         return false;
     } else {
         return $return_body ? $this->HttpRequest->getResponseBody() : true;
     }
 }
Ejemplo n.º 14
0
 /**
  * 投稿するためのURL取得
  */
 protected function getPostUrl()
 {
     $hr = new HTTP_Request($this->atomapi_url);
     $hr->addHeader('X-WSSE', $this->wsse);
     $hr->addHeader('Accept', 'application/x.atom+xml, application/xml, text/xml, */*');
     $hr->addHeader('Authorization', 'WSSE profile="UsernameToken"');
     $hr->addHeader('Content-Type', 'application/x.atom+xml');
     $hr->sendRequest();
     $res = $hr->getResponseBody();
     $xml = simplexml_load_string($res);
     return (string) $xml->link[0]->attributes()->href;
 }
Ejemplo n.º 15
0
 /**
  *
  */
 function getURL($url)
 {
     require_once PEAR_PATH . 'HTTP/Request.php';
     $httpRequest = new HTTP_Request($url);
     $httpRequest->setMethod(HTTP_REQUEST_METHOD_GET);
     $resRequest = $httpRequest->sendRequest();
     if (!PEAR::isError($resRequest) && $httpRequest->getResponseCode() == 200) {
         $data = $httpRequest->getResponseBody();
     } else {
         $data = @file_get_contents($url);
     }
     return $data;
 }
Ejemplo n.º 16
0
 /**
  * @param $values
  *
  * @return bool
  */
 public static function checkAddress(&$values)
 {
     if (self::$_disabled) {
         return FALSE;
     }
     if (!isset($values['street_address']) || !isset($values['city']) && !isset($values['state_province']) && !isset($values['postal_code'])) {
         return FALSE;
     }
     $userID = Civi::settings()->get('address_standardization_userid');
     $url = Civi::settings()->get('address_standardization_url');
     if (empty($userID) || empty($url)) {
         return FALSE;
     }
     $address2 = str_replace(',', '', $values['street_address']);
     $XMLQuery = '<AddressValidateRequest USERID="' . $userID . '"><Address ID="0"><Address1>' . CRM_Utils_Array::value('supplemental_address_1', $values, '') . '</Address1><Address2>' . $address2 . '</Address2><City>' . $values['city'] . '</City><State>' . $values['state_province'] . '</State><Zip5>' . $values['postal_code'] . '</Zip5><Zip4>' . CRM_Utils_Array::value('postal_code_suffix', $values, '') . '</Zip4></Address></AddressValidateRequest>';
     require_once 'HTTP/Request.php';
     $request = new HTTP_Request();
     $request->setURL($url);
     $request->addQueryString('API', 'Verify');
     $request->addQueryString('XML', $XMLQuery);
     $response = $request->sendRequest();
     $session = CRM_Core_Session::singleton();
     $code = $request->getResponseCode();
     if ($code != 200) {
         $session->setStatus(ts('USPS Address Lookup Failed with HTTP status code: %1', array(1 => $code)));
         return FALSE;
     }
     $responseBody = $request->getResponseBody();
     $xml = simplexml_load_string($responseBody);
     if (is_null($xml) || is_null($xml->Address)) {
         $session->setStatus(ts('Your USPS API Lookup has Failed.'));
         return FALSE;
     }
     if ($xml->Number == '80040b1a') {
         $session->setStatus(ts('Your USPS API Authorization has Failed.'));
         return FALSE;
     }
     if (array_key_exists('Error', $xml->Address)) {
         $session->setStatus(ts('Address not found in USPS database.'));
         return FALSE;
     }
     $values['street_address'] = (string) $xml->Address->Address2;
     $values['city'] = (string) $xml->Address->City;
     $values['state_province'] = (string) $xml->Address->State;
     $values['postal_code'] = (string) $xml->Address->Zip5;
     $values['postal_code_suffix'] = (string) $xml->Address->Zip4;
     if (array_key_exists('Address1', $xml->Address)) {
         $values['supplemental_address_1'] = (string) $xml->Address->Address1;
     }
     return TRUE;
 }
Ejemplo n.º 17
0
function sendNotification($message, $regId)
{
    $apikey = "AIzaSyDh3_C0r5OxdGGHN516XleJ1G_-aAMxEC4";
    $rq = new HTTP_Request("https://android.googleapis.com/gcm/send");
    $rq->setMethod(HTTP_REQUEST_METHOD_POST);
    $rq->addHeader("Authorization", "key=" . $apikey);
    $rq->addPostData("registration_id", $regId);
    $rq->addPostData("collapse_key", "1");
    $rq->addPostData("data.message", $message);
    if (!PEAR::isError($rq->sendRequest())) {
        print "\n" . $rq->getResponseBody();
    } else {
        print "\nError has occurred";
    }
}
Ejemplo n.º 18
0
 private function call($method, $args, $include_api_key = true)
 {
     $host = "rest.akismet.com";
     if ($include_api_key) {
         $host = "{$this->api_key}.{$host}";
     }
     $url = "http://{$host}/1.1/{$method}";
     $req = new HTTP_Request($url, array("method" => "POST"));
     $req->addHeader("User-Agent", "Cyberspace-Networks/" . PA_VERSION);
     foreach ($args as $k => $v) {
         $req->addPostData($k, $v);
     }
     $req->sendRequest();
     return $req->getResponseBody();
 }
Ejemplo n.º 19
0
 /**
  * @param $uri
  *
  * @return SimpleXMLElement
  * @throws Exception
  */
 public static function makeAPICall($uri)
 {
     require_once 'HTTP/Request.php';
     $params = array('method' => HTTP_REQUEST_METHOD_GET, 'allowRedirects' => FALSE);
     $request = new HTTP_Request(self::$_apiURL . $uri, $params);
     $result = $request->sendRequest();
     if (PEAR::isError($result)) {
         CRM_Core_Error::fatal($result->getMessage());
     }
     if ($request->getResponseCode() != 200) {
         CRM_Core_Error::fatal(ts('Invalid response code received from Sunlight servers: %1', array(1 => $request->getResponseCode())));
     }
     $string = $request->getResponseBody();
     return simplexml_load_string($string);
 }
Ejemplo n.º 20
0
 function process($table, $data)
 {
     $req = new HTTP_Request($this->api_url);
     $req->setMethod(HTTP_REQUEST_METHOD_GET);
     foreach ($data as $key => $val) {
         $req->addQueryString($key, $val);
     }
     $req->addQueryString('org', trim($this->org_id));
     $req->addQueryString('table', $table);
     if (!PEAR::isError($req->sendRequest())) {
         $out = $req->getResponseBody();
     } else {
         $out = null;
     }
     return $out;
 }
Ejemplo n.º 21
0
 /**
  * Fire request via HTTP to the Flickr API
  *
  * @param array $arguments List of query string pairs
  * @return array
  */
 public function sendRequest(array $arguments)
 {
     $params = '';
     foreach ($arguments as $key => $argument) {
         $params .= "{$key}=" . urlencode($argument) . "&";
     }
     $url = $this->_url . "?" . $params;
     require_once S9Y_PEAR_PATH . 'HTTP/Request.php';
     $request = new HTTP_Request($url);
     $request->setMethod(HTTP_REQUEST_METHOD_GET);
     $request->sendRequest();
     $response = unserialize($request->getResponseBody());
     if ($response['stat'] != 'ok') {
         throw new Exception($response['message'], $response['code']);
     }
     return $response;
 }
 function getXMLArray($file, $forced_encoding = null)
 {
     require_once (defined('S9Y_PEAR_PATH') ? S9Y_PEAR_PATH : S9Y_INCLUDE_PATH . 'bundled-libs/') . 'HTTP/Request.php';
     $req = new HTTP_Request($file);
     if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') {
         if (ini_get("allow_url_fopen")) {
             $data = file_get_contents($file);
         } else {
             $data = "";
         }
     } else {
         $data = $req->getResponseBody();
     }
     if (trim($data) == '') {
         return false;
     }
     return $this->parseXML($data, $forced_encoding);
 }
Ejemplo n.º 23
0
 /**
  * @brief rss 주소로 부터 내용을 받아오는 함수
  *
  * tistory 의 경우 원본 주소가 location 헤더를 뿜는다.(내용은 없음) 이를 해결하기 위한 수정
  **/
 function rss_request($rss_url)
 {
     // request rss
     $rss_url = Context::convertEncodingStr($rss_url);
     $URL_parsed = parse_url($rss_url);
     if (strpos($URL_parsed["host"], 'naver.com')) {
         $rss_url = iconv('UTF-8', 'euc-kr', $rss_url);
     }
     $rss_url = str_replace(array('%2F', '%3F', '%3A', '%3D', '%3B', '%26'), array('/', '?', ':', '=', ';', '&'), urlencode($rss_url));
     $URL_parsed = parse_url($rss_url);
     $host = $URL_parsed["host"];
     $port = $URL_parsed["port"];
     if ($port == 0) {
         $port = 80;
     }
     $path = $URL_parsed["path"];
     if ($URL_parsed["query"] != '') {
         $path .= "?" . $URL_parsed["query"];
     }
     $oReqeust = new HTTP_Request($rss_url);
     $oReqeust->addHeader('Content-Type', 'application/xml');
     $oReqeust->addHeader('User-agent', 'RSS Reader Widget (XE ' . __ZBXE_VERSION__ . ' (http://www.xpressengine.com); PEAR HTTP_Request class (http://pear.php.net))');
     $oReqeust->setMethod('GET');
     $user = $URL_parsed["user"];
     $pass = $URL_parsed["pass"];
     if ($user) {
         $oReqeust->setBasicAuth($user, $pass);
     }
     $oResponse = $oReqeust->sendRequest();
     if (PEAR::isError($oResponse)) {
         return;
     }
     $header = $oReqeust->getResponseHeader();
     if ($header['location']) {
         return $this->rss_request(trim($header['location']));
     } else {
         return $oReqeust->getResponseBody();
     }
 }
Ejemplo n.º 24
0
 /**
  * Retrieve Free/Busy data for the specified resource.
  *
  * @param string $resource Fetch the Free/Busy data for this resource.
  *
  * @return Horde_Icalendar_Vfreebusy The Free/Busy data.
  */
 public function get($resource)
 {
     global $conf;
     $url = self::getUrl($resource);
     Horde::log(sprintf('Freebusy URL for resource %s is %s', $resource, $url), 'DEBUG');
     list($user, $domain) = explode('@', $resource);
     if (empty($domain)) {
         $domain = $conf['kolab']['filter']['email_domain'];
     }
     /**
      * This section matches Kronolith_Freebusy and should be merged with it
      * again in a single Horde_Freebusy module.
      */
     $options = array('method' => 'GET', 'timeout' => 5, 'allowRedirects' => true);
     if (!empty($conf['http']['proxy']['proxy_host'])) {
         $options = array_merge($options, $conf['http']['proxy']);
     }
     $http = new HTTP_Request($url, $options);
     $http->setBasicAuth($conf['kolab']['filter']['calendar_id'] . '@' . $domain, $conf['kolab']['filter']['calendar_pass']);
     @$http->sendRequest();
     if ($http->getResponseCode() != 200) {
         throw new Horde_Kolab_Resource_Exception(sprintf('Unable to retrieve free/busy information for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY);
     }
     $vfb_text = $http->getResponseBody();
     // Detect the charset of the iCalendar data.
     $contentType = $http->getResponseHeader('Content-Type');
     if ($contentType && strpos($contentType, ';') !== false) {
         list(, $charset, ) = explode(';', $contentType);
         $vfb_text = Horde_String::convertCharset($vfb_text, trim(str_replace('charset=', '', $charset)), 'UTF-8');
     }
     $iCal = new Horde_Icalendar();
     $iCal->parsevCalendar($vfb_text, 'VCALENDAR');
     $vfb =& $iCal->findComponent('VFREEBUSY');
     if ($vfb === false) {
         throw new Horde_Kolab_Resource_Exception(sprintf('Invalid or no free/busy information available for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY);
     }
     $vfb->simplify();
     return $vfb;
 }
Ejemplo n.º 25
0
 function willRequest($request)
 {
     // お気に入り作成をフックする
     if (preg_match("|^/favorites/create/(\\d+)|", $this->server->request['path'], $match)) {
         $id = $match[1];
         $url = $this->server->config['Twitter']['api'];
         $url .= '/status/show/' . $id . '.json';
         $req = new HTTP_Request($url);
         if (isset($_SERVER["PHP_AUTH_USER"])) {
             $req->setBasicAuth($_SERVER["PHP_AUTH_USER"], @$_SERVER["PHP_AUTH_PW"]);
         }
         $result = $req->sendRequest();
         if (PEAR::isError($result)) {
             return;
         }
         if ($req->getResponseCode() != 200) {
             return;
         }
         $json = json_decode($req->getResponseBody());
         $title = $json->text;
         $href = 'http://twitter.com/' . $json->user->screen_name . '/status/' . $id;
         $created = date('Y-m-d\\TH:i:s\\Z');
         $nonce = pack('H*', sha1(md5(time())));
         $pass_digest = base64_encode(pack('H*', sha1($nonce . $created . $this->server->config['Plugin']['HatenaBookmark']['password'])));
         $wsse = 'UsernameToken Username="******", ';
         $wsse .= 'PasswordDigest="' . $pass_digest . '", ';
         $wsse .= 'Nonce="' . base64_encode($nonce) . '",';
         $wsse .= 'Created="' . $created . '"';
         $req = new HTTP_Request('http://b.hatena.ne.jp/atom/post');
         $req->setMethod(HTTP_REQUEST_METHOD_POST);
         $req->addHeader('WWW-Authenticate', 'WSSE profile="UsernameToken"');
         $req->addHeader('X-WSSE', $wsse);
         $req->addHeader('Content-Type', 'application/x.atom+xml');
         $xml = '<?xml version="1.0" encoding="utf-8"?>' . '<entry xmlns="http://purl.org/atom/ns#">' . '<title>' . $title . '</title>' . '<link rel="related" type="text/html" href="' . $href . '" />' . '<summary type="text/plain"></summary>' . '</entry>';
         $req->addRawPostData($xml);
         $req->sendRequest();
     }
     return $request;
 }
Ejemplo n.º 26
0
 /**
  *  preprocess Index action.
  *
  *  @access    public
  *  @return    string  Forward name (null if no errors.)
  */
 function prepare()
 {
     if ($this->af->validate() == 0) {
         $url = sprintf('%s/repository.sphp', rtrim($this->af->get('repository_url'), '/'));
         require_once 'HTTP/Request.php';
         $req = new HTTP_Request($url);
         $req->sendRequest();
         if ($req->getResponseCode() == '200') {
             $data = $req->getResponseBody();
             $ret = @unserialize($data);
             if (is_array($ret)) {
                 $this->af->setApp('repository_data', $ret);
                 $cache_file = $this->backend->ctl->repositoryURL2CacheFile($url);
                 file_put_contents($cache_file, $data);
                 chmod($cache_file, 0666);
                 return null;
             }
         }
     }
     $this->ae->add('repository_url', _('The repository is not available!'));
     return 'json_error';
 }
Ejemplo n.º 27
0
/**
* Get the Pingback URL for a given URL
*
* @param    string  $url    URL to get the Pingback URL for
* @return   string          Pingback URL or empty string
*
*/
function PNB_getPingbackUrl($url)
{
    require_once 'HTTP/Request.php';
    $retval = '';
    $req = new HTTP_Request($url);
    $req->setMethod(HTTP_REQUEST_METHOD_HEAD);
    $req->addHeader('User-Agent', 'glFusion/' . GVERSION);
    $response = $req->sendRequest();
    if (PEAR::isError($response)) {
        COM_errorLog('Pingback (HEAD): ' . $response->getMessage());
        return false;
    } else {
        $retval = $req->getResponseHeader('X-Pingback');
    }
    if (empty($retval)) {
        // search for <link rel="pingback">
        $req = new HTTP_Request($url);
        $req->setMethod(HTTP_REQUEST_METHOD_GET);
        $req->addHeader('User-Agent', 'glFusion/' . GVERSION);
        $response = $req->sendRequest();
        if (PEAR::isError($response)) {
            COM_errorLog('Pingback (GET): ' . $response->getMessage());
            return false;
        } elseif ($req->getResponseCode() == 200) {
            $body = $req->getResponseBody();
            // only search for the first match - it doesn't make sense to have
            // more than one pingback URL
            $found = preg_match("/<link rel=\"pingback\"[^>]*href=[\"']([^\"']*)[\"'][^>]*>/i", $body, $matches);
            if ($found === 1 && !empty($matches[1])) {
                $url = str_replace('&amp;', '&', $matches[1]);
                $retval = urldecode($url);
            }
        } else {
            COM_errorLog('Pingback (GET): Got HTTP response code ' . $req->getResponseCode() . " when requesting {$url}");
            return false;
        }
    }
    return $retval;
}
 function GetXMLTree($file)
 {
     require_once S9Y_PEAR_PATH . 'HTTP/Request.php';
     serendipity_request_start();
     $req = new HTTP_Request($file);
     if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') {
         $data = file_get_contents($file);
     } else {
         // Fetch file
         $data = $req->getResponseBody();
     }
     serendipity_request_end();
     // Global replacements
     // by: waldo@wh-e.com - trim space around tags not within
     $data = preg_replace('@>[[:space:]]+<@', '><', $data);
     // Flatten the input opml file to not have nested categories
     $data = preg_replace('@<outline[^>]+[^/]>@imsU', '', $data);
     $data = str_replace('</outline>', '', $data);
     // XML functions
     $xml_string = '<?xml version="1.0" encoding="UTF-8" ?>';
     if (preg_match('@(<\\?xml.+\\?>)@imsU', $data, $xml_head)) {
         $xml_string = $xml_head[1];
     }
     $encoding = 'UTF-8';
     if (preg_match('@encoding="([^"]+)"@', $xml_string, $xml_encoding)) {
         $encoding = $xml_encoding[1];
     }
     $p = xml_parser_create($encoding);
     // by: anony@mous.com - meets XML 1.0 specification
     @xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
     xml_parser_set_option($p, XML_OPTION_TARGET_ENCODING, LANG_CHARSET);
     xml_parse_into_struct($p, $data, $vals, $index);
     xml_parser_free($p);
     $i = 0;
     $tree = array();
     $tree[] = array('tag' => $vals[$i]['tag'], 'attributes' => $vals[$i]['attributes'], 'value' => $vals[$i]['value'], 'children' => $this->GetChildren($vals, $i));
     return $tree;
 }
Ejemplo n.º 29
0
function post($img_index)
{
    global $image_files;
    $url = 'http://twitter.com/account/update_profile_image.json';
    $file_name = $image_files[$img_index];
    if (!file_exists($file_name)) {
        result('画像ファイル名が不正です。');
    }
    $pathinfo = pathinfo($file_name);
    $extension = strtolower($pathinfo['extension']);
    switch ($extension) {
        case 'png':
        case 'gif':
            // do nothing.
            break;
        case 'jpeg':
        case 'jpg':
            $extension = 'jpg';
            break;
        default:
            result('画像の拡張子が不正です。');
    }
    $request = new HTTP_Request($url);
    $request->setMethod(HTTP_REQUEST_METHOD_POST);
    $request->setBasicAuth(USERNAME, PASSWORD);
    $result = $request->addFile('image', $file_name, "image/{$extension}");
    if (PEAR::isError($result)) {
        result($result->getMessager());
    }
    $response = $request->sendRequest();
    if (PEAR::isError($response)) {
        result($response->getMessage());
    }
    $body = $request->getResponseBody();
    return true;
}
Ejemplo n.º 30
0
 /**
  * Extract terms from the Solr index.
  *
  * @param string $field					 Field to extract terms from
  * @param string $start					 Starting term to extract (blank for beginning
  * of list)
  * @param int		$limit					 Maximum number of terms to return (-1 for no
  * limit)
  * @param bool	 $returnSolrError Should we fail outright on syntax error
  * (false) or treat it as an empty result set with an error key set (true)?
  *
  * @return array									Associative array parsed from Solr JSON
  * response; meat of the response is in the ['terms'] element, which contains
  * an index named for the requested term, which in turn contains an associative
  * array of term => count in index.
  * @access public
  */
 public function getTerms($field, $start, $limit, $returnSolrError = false)
 {
     $this->client->setMethod('GET');
     $this->client->setURL($this->host . '/term');
     $this->client->addQueryString('terms', 'true');
     $this->client->addQueryString('terms.fl', $field);
     $this->client->addQueryString('terms.lower.incl', 'false');
     $this->client->addQueryString('terms.lower', $start);
     $this->client->addQueryString('terms.limit', $limit);
     $this->client->addQueryString('terms.sort', 'index');
     $this->client->addQueryString('wt', 'json');
     $result = $this->client->sendRequest();
     if (!PEAR_Singleton::isError($result)) {
         // Process the JSON response:
         $data = $this->_process($this->client->getResponseBody(), $returnSolrError);
         // Tidy the data into a more usable format:
         if (isset($data['terms'])) {
             $data['terms'] = array($data['terms'][0] => $this->_processTerms($data['terms'][1]));
         }
         return $data;
     } else {
         return $result;
     }
 }