Example #1
0
 private function __construct()
 {
     // sanity check
     $siteUrl = get_option('siteurl');
     $layoutUrl = DAIQUIRI_URL . '/core/layout/';
     if (strpos($layoutUrl, $siteUrl) !== false) {
         echo '<h1>Error with theme</h1><p>Layout URL is below CMS URL.</p>';
         die(0);
     }
     // construct request
     require_once 'HTTP/Request2.php';
     $req = new HTTP_Request2($layoutUrl);
     $req->setConfig(array('ssl_verify_peer' => false, 'connect_timeout' => 2, 'timeout' => 3));
     $req->setMethod('GET');
     $req->addCookie("PHPSESSID", $_COOKIE["PHPSESSID"]);
     try {
         $response = $req->send();
         if (200 != $response->getStatus()) {
             echo '<h1>Error with theme</h1><p>HTTP request status != 200.</p>';
             die(0);
         }
     } catch (HTTP_Request2_Exception $e) {
         echo '<h1>Error with theme</h1><p>Error with HTTP request.</p>';
         die(0);
     }
     $body = explode('<!-- content -->', $response->getBody());
     if (count($body) == 2) {
         $this->_header = $body[0];
         $this->_footer = $body[1];
     } else {
         echo '<h1>Error with theme</h1><p>Malformatted layout.</p>';
         die(0);
     }
 }
Example #2
0
 /**
  * Make the GET request
  *
  * @throws BuildException
  */
 public function main()
 {
     if (!isset($this->url)) {
         throw new BuildException("Missing attribute 'url'");
     }
     if (!isset($this->dir)) {
         throw new BuildException("Missing attribute 'dir'");
     }
     $this->log("Fetching " . $this->url);
     $request = new HTTP_Request2($this->url);
     $response = $request->send();
     if ($response->getStatus() != 200) {
         throw new BuildException("Request unsuccessfull. Response from server: " . $response->getStatus() . " " . $response->getReasonPhrase());
     }
     $content = $response->getBody();
     if ($this->filename) {
         $filename = $this->filename;
     } elseif ($disposition = $response->getHeader('content-disposition') && 0 == strpos($disposition, 'attachment') && preg_match('/filename="([^"]+)"/', $disposition, $m)) {
         $filename = basename($m[1]);
     } else {
         $filename = basename(parse_url($this->url, PHP_URL_PATH));
     }
     if (!is_writable($this->dir)) {
         throw new BuildException("Cannot write to directory: " . $this->dir);
     }
     $filename = $this->dir . "/" . $filename;
     file_put_contents($filename, $content);
     $this->log("Contents from " . $this->url . " saved to {$filename}");
 }
Example #3
0
 public function erzData($zip = null, $type = null, $page = 1)
 {
     if ($type) {
         $url = 'http://openerz.herokuapp.com:80/api/calendar/' . $type . '.json';
     } else {
         $url = 'http://openerz.herokuapp.com:80/api/calendar.json';
     }
     //Http-request
     $request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
     $reqUrl = $request->getUrl();
     $pageSize = 10;
     $reqUrl->setQueryVariable('limit', $pageSize);
     $offset = ($page - 1) * $pageSize;
     $reqUrl->setQueryVariable('offset', $offset);
     if ($zip) {
         $reqUrl->setQueryVariable('zip', $zip);
     }
     try {
         $response = $request->send();
         // 200 ist für den Status ob ok ist 404 wäre zum Beispiel ein Fehler
         if ($response->getStatus() == 200) {
             return json_decode($response->getBody());
         }
     } catch (HTTP_Request2_Exception $ex) {
         echo $ex;
     }
     return null;
 }
 /**
  * {@inheritdoc }
  */
 public function sendRequest(\HTTP_Request2 $request)
 {
     if (array_key_exists($request->getMethod(), array_flip($this->getDisallowedMethods()))) {
         throw new NotAllowedMethodTypeException();
     }
     return parent::sendRequest($request);
 }
function getRss($url, $port, $timeout)
{
    $results = array('rss' => array(), 'error' => "");
    try {
        $request = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
        $request->setConfig("connect_timeout", $timeout);
        $request->setConfig("timeout", $timeout);
        $request->setHeader("user-agent", $_SERVER['HTTP_USER_AGENT']);
        $response = $request->send();
        if ($response->getStatus() == 200) {
            // パース
            $body = $response->getBody();
            if (substr($body, 0, 5) == "<?xml") {
                $results['rss'] = new MagpieRSS($body, "UTF-8");
            } else {
                throw new Exception("Not xml data");
            }
        } else {
            throw new Exception("Server returned status: " . $response->getStatus());
        }
    } catch (HTTP_Request2_Exception $e) {
        $results['error'] = $e->getMessage();
    } catch (Exception $e) {
        $results['error'] = $e->getMessage();
    }
    // タイムアウト戻し
    ini_set('default_socket_timeout', $oldtimeout);
    return $results;
}
Example #6
0
 public function testSetRequest()
 {
     $newswire = new Newswire('apikey');
     $req = new \HTTP_Request2();
     $req->setAdapter('mock');
     $this->assertInstanceOf('PEAR2\\Services\\NYTimes\\Newswire', $newswire->accept($req));
 }
 /**
  * Sets up the fixture, for example, open a network connection.
  * This method is called before a test is executed.
  *
  * @return void
  */
 protected function setUp()
 {
     $this->mock = new HTTP_Request2_Adapter_Mock();
     $request = new HTTP_Request2();
     $request->setAdapter($this->mock);
     $this->validator = new Services_W3C_CSSValidator($request);
 }
Example #8
0
 public function getLanguagesFromTransifex()
 {
     $request = new HTTP_Request2('http://*****:*****@www.transifex.net/api/2/project/gaiaehr/resource/All/?details', HTTP_Request2::METHOD_GET);
     $r = $request->send()->getBody();
     $r = json_decode($r, true);
     return array('langs' => $r['available_languages']);
 }
Example #9
0
 /**
  * さくら水産のランチ情報を取得する
  *
  * @return array | false
  */
 public function fetchLunchMenus()
 {
     $menus = array();
     $today = new DateTime();
     $request = new HTTP_Request2();
     $request->setMethod(HTTP_Request2::METHOD_GET);
     $request->setUrl(self::LUNCHMENU_URL);
     try {
         $response = $request->send();
         if (200 == $response->getStatus()) {
             $dom = new DOMDocument();
             @$dom->loadHTML($response->getBody());
             $xml = simplexml_import_dom($dom);
             foreach ($xml->xpath('//table/tr') as $tr) {
                 if (preg_match('/(\\d+)月(\\d+)日/', $tr->td[0]->div, $matches)) {
                     $dateinfo = new DateTime(sprintf('%04d-%02d-%02d', $today->format('Y'), $matches[1], $matches[2]));
                     $_menus = array();
                     foreach ($tr->td[1]->div->strong as $strong) {
                         $_menus[] = (string) $strong;
                     }
                     $menus[$dateinfo->format('Y-m-d')] = $_menus;
                 }
             }
         }
     } catch (HTTP_Request2_Exception $e) {
         // HTTP Error
         return false;
     }
     return $menus;
 }
Example #10
0
 /**
  * Calculates length of the request body, adds proper headers
  *
  * @param    array   associative array of request headers, this method will
  *                   add proper 'Content-Length' and 'Content-Type' headers
  *                   to this array (or remove them if not needed)
  */
 protected function calculateRequestLength(&$headers)
 {
     $this->requestBody = $this->request->getBody();
     if (is_string($this->requestBody)) {
         $this->contentLength = strlen($this->requestBody);
     } elseif (is_resource($this->requestBody)) {
         $stat = fstat($this->requestBody);
         $this->contentLength = $stat['size'];
         rewind($this->requestBody);
     } else {
         $this->contentLength = $this->requestBody->getLength();
         $headers['content-type'] = 'multipart/form-data; boundary=' . $this->requestBody->getBoundary();
         $this->requestBody->rewind();
     }
     if (in_array($this->request->getMethod(), self::$bodyDisallowed) || 0 == $this->contentLength) {
         // No body: send a Content-Length header nonetheless (request #12900),
         // but do that only for methods that require a body (bug #14740)
         if (in_array($this->request->getMethod(), self::$bodyRequired)) {
             $headers['content-length'] = 0;
         } else {
             unset($headers['content-length']);
             // if the method doesn't require a body and doesn't have a
             // body, don't send a Content-Type header. (request #16799)
             unset($headers['content-type']);
         }
     } else {
         if (empty($headers['content-type'])) {
             $headers['content-type'] = 'application/x-www-form-urlencoded';
         }
         $headers['content-length'] = $this->contentLength;
     }
 }
Example #11
0
function send_post_data($url, $data)
{
    require_once 'HTTP/Request2.php';
    $request = new HTTP_Request2($url);
    $request->setMethod(HTTP_Request2::METHOD_POST)->addPostParameter($data);
    return $request->send();
}
Example #12
0
function twipic($f, $a, $b, $m)
{
    $twitpic_api = "";
    $consumer_key = "";
    $consumer_secret = "";
    $access_token = $a;
    $access_token_secret = $b;
    $imagepath = $f;
    $message = $me;
    $consumer = new HTTP_OAuth_Consumer($consumer_key, $consumer_secret);
    $consumer->setToken($access_token);
    $consumer->setTokenSecret($access_token_secret);
    $http_request = new HTTP_Request2();
    $http_request->setConfig('ssl_verify_peer', false);
    $consumer_request = new HTTP_OAuth_Consumer_Request();
    $consumer_request->accept($http_request);
    $consumer->accept($consumer_request);
    $resp = $consumer->sendRequest('https://api.twitter.com/1.1/account/verify_credentials.json', array(), HTTP_Request2::METHOD_GET);
    $headers = $consumer->getLastRequest()->getHeaders();
    $http_request->setHeader('X-Auth-Service-Provider', 'https://api.twitter.com/1.1/account/verify_credentials.json');
    $http_request->setHeader('X-Verify-Credentials-Authorization', $headers['authorization']);
    $http_request->setUrl('http://api.twitpic.com/2/upload.json');
    $http_request->setMethod(HTTP_Request2::METHOD_POST);
    $http_request->addPostParameter('key', $twitpic_api);
    $http_request->addPostParameter('message', $m);
    $http_request->addUpload('media', $imagepath);
    $resp = $http_request->send();
    $body = $resp->getBody();
    $body = json_decode($body, true);
    return $body;
}
 /**
  * Sets the common headers required by CloudFront API
  * @param HTTP_Request2 $req
  */
 private function setRequestHeaders(HTTP_Request2 $req)
 {
     $date = gmdate("D, d M Y G:i:s T");
     $req->setHeader("Host", 'cloudfront.amazonaws.com');
     $req->setHeader("Date", $date);
     $req->setHeader("Authorization", $this->generateAuthKey($date));
     $req->setHeader("Content-Type", "text/xml");
 }
 public function testConfigurationViaProperties()
 {
     $trace = new TraceHttpAdapter();
     $this->copyTasksAddingCustomRequest('config-properties', 'recipient', $this->createRequest($trace));
     $this->executeTarget('recipient');
     $request = new HTTP_Request2(null, 'GET', array('proxy' => 'http://localhost:8080/', 'max_redirects' => 9));
     $this->assertEquals($request->getConfig(), $trace->requests[0]['config']);
 }
 protected function addHttpMock(Net_WebFinger $wf)
 {
     $this->adapter = new HTTP_Request2_Adapter_LogMock();
     $req = new HTTP_Request2();
     $req->setAdapter($this->adapter);
     $wf->setHttpClient($req);
     return $this;
 }
Example #16
0
 public function testBug17826()
 {
     $adapter = new HTTP_Request2_Adapter_Socket();
     $request1 = new HTTP_Request2($this->baseUrl . 'redirects.php?redirects=2');
     $request1->setConfig(array('follow_redirects' => true, 'max_redirects' => 3))->setAdapter($adapter)->send();
     $request2 = new HTTP_Request2($this->baseUrl . 'redirects.php?redirects=2');
     $request2->setConfig(array('follow_redirects' => true, 'max_redirects' => 3))->setAdapter($adapter)->send();
 }
Example #17
0
 /**
  * @param string $user
  * @param string $apiKey
  *
  * @return Request2
  */
 public function getRequest($user, $apiKey)
 {
     if ($this->req === null) {
         $this->req = new Request2();
         $this->req->setAdapter('curl')->setHeader('user-agent', 'Services_Librato');
     }
     $this->req->setAuth($user, $apiKey);
     return $this->req;
 }
Example #18
0
 public static function update($userid)
 {
     global $HTTP_CONFIG;
     $username = Token::get(self::name, $userid);
     $request = new HTTP_Request2('http://open.dapper.net/transform.php?dappName=CodeChefProblemsSolved&transformer=JSON&v_username=' . $username);
     $request->setConfig($HTTP_CONFIG);
     $response = $request->send()->getBody();
     $score = json_decode($response)->fields->solved[32]->value;
     Score::update(self::name, $userid, $score);
 }
 private function etcd_get($url, $base = false)
 {
     $base = $base === false ? $this->etcd_base : $base;
     /* Get some key from etcd */
     $etcd_url = explode(",", getenv("ETCDCTL_PEERS"))[0] . "/v2/keys" . $base . $url;
     require_once 'HTTP/Request2.php';
     $request = new HTTP_Request2($etcd_url, HTTP_Request2::METHOD_GET);
     $res = $request->send();
     return json_decode($res->getBody());
 }
Example #20
0
 /**
  * @expectedException Services_Yadis_Exception
  * @expectedExceptionMessage Invalid response to Yadis protocol received: A test error
  */
 public function testGetException()
 {
     $httpMock = new HTTP_Request2_Adapter_Mock();
     $httpMock->addResponse(new HTTP_Request2_Exception('A test error', 500));
     $http = new HTTP_Request2();
     $http->setAdapter($httpMock);
     $sy = new Services_Yadis('http://example.org/openid');
     $sy->setHttpRequest($http);
     $xrds = $sy->discover();
 }
Example #21
0
 public static function update($userid)
 {
     global $HTTP_CONFIG;
     $username = Token::get(self::name, $userid);
     $request = new HTTP_Request2('https://hacker-news.firebaseio.com/v0/user/' . $username . '.json');
     $request->setConfig($HTTP_CONFIG);
     $response = $request->send()->getBody();
     $karma = json_decode($response)->karma;
     Score::update(self::name, $userid, $karma);
 }
Example #22
0
 public static function update($userid)
 {
     global $HTTP_CONFIG;
     $twitterScreenName = Token::get(self::name, $userid);
     $request = new HTTP_Request2('https://api.twitter.com/1/users/show.json?screen_name=' . $twitterScreenName);
     $request->setConfig($HTTP_CONFIG);
     $response = $request->send()->getBody();
     $followers_count = json_decode($response)->followers_count;
     Score::update(self::name, $userid, $followers_count);
     //Update in database
 }
Example #23
0
 public static function update($userid)
 {
     global $HTTP_CONFIG;
     $lastFMUsername = Token::get(self::name, $userid);
     $request = new HTTP_Request2('http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user='******'&api_key=' . LASTFM_APP_ID . '&format=json');
     $request->setConfig($HTTP_CONFIG);
     $response = $request->send()->getBody();
     $playcount = trim(json_decode($response)->user->playcount);
     Score::update(self::name, $userid, $playcount);
     //Update in database
 }
Example #24
0
 public function send($mobile, $content)
 {
     $data = array('u' => $this->conf['u'], 'p' => md5($this->conf['p']), 'm' => $mobile, 'c' => $content . $this->conf['sign']);
     $http = new HTTP_Request2($this->conf['apiUriPrefix'] . 'sms', HTTP_Request2::METHOD_POST);
     $http->addPostParameter($data);
     $r = $http->send()->getBody();
     if ($r != 0) {
         throw new Services_Sms_Exception($r);
     }
     return true;
 }
Example #25
0
 public static function update($userid)
 {
     global $HTTP_CONFIG;
     $id = Token::get(self::name, $userid);
     $request = new HTTP_Request2('https://api.stackexchange.com/2.1/users/' . $id . '?site=askubuntu&key=' . STACKEXCHANGE_KEY);
     $request->setConfig($HTTP_CONFIG);
     $response = $request->send()->getBody();
     $reputation = json_decode($response)->items[0]->reputation;
     Score::update(self::name, $userid, $reputation);
     //Update in database
 }
Example #26
0
 public function OXreqPUTforSendMail($url, $QueryVariables, $PutData, $returnResponseObject = false)
 {
     $QueryVariables['timezone'] = 'UTC';
     # all times are UTC,
     $request = new HTTP_Request2(OX_SERVER . $url, HTTP_Request2::METHOD_PUT);
     $request->setHeader('Content-type: text/javascript; charset=utf-8');
     $url = $request->getUrl();
     $url->setQueryVariables($QueryVariables);
     $request->setBody(utf8_encode($PutData));
     return $this->OXreq($request, $returnResponseObject);
 }
Example #27
0
function getContents($url, $start = 0, $userAgent = null)
{
    if ($start > 0) {
        $url .= "&start={$start}";
    }
    $http = new HTTP_Request2($url);
    $http->setAdapter('curl');
    if ($userAgent !== null) {
        $http->setHeader('User-Agent', $userAgent);
    }
    return $http->send();
}
Example #28
0
 public function send($mobile, $content)
 {
     $data = array('sname' => $this->conf['sname'], 'spwd' => $this->conf['spwd'], 'scorpid' => $this->conf['scorpid'], 'sprdid' => $this->conf['sprdid'], 'sdst' => $mobile, 'smsg' => $content . $this->conf['sign']);
     $http = new HTTP_Request2($this->conf['apiUriPrefix'] . '/g_Submit', HTTP_Request2::METHOD_POST);
     $http->addPostParameter($data);
     $r = $http->send()->getBody();
     $tmp = $this->filter($r);
     if ($tmp['State'] != 0) {
         throw new Services_Sms_Exception($r);
     }
     return true;
 }
Example #29
0
/**
 * Send an HTTP HEAD request for the given URL
 *
 * @param    string $url          URL to request
 * @param    string $errorMessage error message, if any (on return)
 * @return   int                  HTTP response code or 777 on error
 */
function doHeadRequest($url, &$errorMessage)
{
    $req = new HTTP_Request2($url, HTTP_Request2::METHOD_HEAD);
    $req->setHeader('User-Agent', 'Geeklog/' . VERSION);
    try {
        $response = $req->send();
        return $response->getStatus();
    } catch (HTTP_Request2_Exception $e) {
        $errorMessage = $e->getMessage();
        return 777;
    }
}
Example #30
0
 /**
  * リソースリクエスト実行
  *
  * リモートURLにアクセスしてRSSだったら配列に、
  * そうでなかったらHTTP Body文字列をリソースとして扱います。
  *
  * @return BEAR_Ro
  * @throws BEAR_Resource_Execute_Exception
  */
 public function request()
 {
     $reqMethod = array();
     $reqMethod[BEAR_Resource::METHOD_CREATE] = HTTP_Request2::METHOD_POST;
     $reqMethod[BEAR_Resource::METHOD_READ] = HTTP_Request2::METHOD_GET;
     $reqMethod[BEAR_Resource::METHOD_UPDATE] = HTTP_Request2::METHOD_PUT;
     $reqMethod[BEAR_Resource::METHOD_DELETE] = HTTP_Request2::METHOD_DELETE;
     assert(isset($reqMethod[$this->_config['method']]));
     try {
         // 引数以降省略可能  config で proxy とかも設定可能
         $request = new HTTP_Request2($this->_config['uri'], $reqMethod[$this->_config['method']]);
         $request->setHeader("user-agent", 'BEAR/' . BEAR::VERSION);
         $request->setConfig("follow_redirects", true);
         if ($this->_config['method'] === BEAR_Resource::METHOD_CREATE || $this->_config['method'] === BEAR_Resource::METHOD_UPDATE) {
             foreach ($this->_config['values'] as $key => $value) {
                 $request->addPostParameter($key, $value);
             }
         }
         $response = $request->send();
         $code = $response->getStatus();
         $headers = $response->getHeader();
         if ($code == 200) {
             $body = $response->getBody();
         } else {
             $info = array('code' => $code, 'headers' => $headers);
             throw $this->_exception($response->getBody(), $info);
         }
     } catch (HTTP_Request2_Exception $e) {
         throw $this->_exception($e->getMessage());
     } catch (Exception $e) {
         throw $this->_exception($e->getMessage());
     }
     $rss = new XML_RSS($body, 'utf-8', 'utf-8');
     PEAR::setErrorHandling(PEAR_ERROR_RETURN);
     // @todo Panda::setPearErrorHandling(仮称)に変更しエラーを画面化しないようにする
     $rss->parse();
     $items = $rss->getItems();
     if (is_array($items) && count($items) > 0) {
         $body = $items;
         $headers = $rss->getChannelInfo();
         $headers['type'] = 'rss';
     } else {
         $headers['type'] = 'string';
         $body = array($body);
     }
     // UTF-8に
     $encode = mb_convert_variables('UTF-8', 'auto', $body);
     $ro = BEAR::factory('BEAR_Ro')->setBody($body)->setHeaders($headers);
     /* @var $ro BEAR_Ro */
     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('Panda', 'onPearError'));
     return $ro;
 }