コード例 #1
0
ファイル: functions_helper.php プロジェクト: jabouzi/belron
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();
}
コード例 #2
0
ファイル: Client.php プロジェクト: nojimage/twitter2mixivoice
    /**
     * GET Request
     *
     * @param $url
     * @param $datas
     * @return string
     */
    public function get_request($url, $datas = array())
    {
        $body = '';
        try {
            $url2 = new Net_URL2($url);
            foreach ($datas as $key => $val) {
                $url2->setQueryVariable($key, mb_convert_encoding($val, $this->response_encoding, 'UTF-8'), true);
            }

            $this->http->setURL($url2);
            $this->http->setMethod(HTTP_Request2::METHOD_GET);
            if (!empty($this->cookies)) {
                foreach ($this->cookies as $cookie) {
                    $this->http->addCookie($cookie['name'], $cookie['value']);
                }
            }

            $response = $this->http->send();

            if (count($response->getCookies())) {
                $this->cookies = $response->getCookies();
            }

            $body = mb_convert_encoding($response->getBody(), 'UTF-8', $this->response_encoding);

        } catch (Exception $e) {
            debug($e->getMessage());
        }

        return $body;
    }
コード例 #3
0
ファイル: Sakusui.php プロジェクト: riaf/Wozozo_Sakusui
 /**
  * さくら水産のランチ情報を取得する
  *
  * @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;
 }
コード例 #4
0
 public function testRawPostData()
 {
     $data = 'Nothing to see here, move along';
     $this->request->setMethod(HTTP_Request2::METHOD_POST)->setBody($data);
     $response = $this->request->send();
     $this->assertEquals($response->getBody(), $data);
 }
コード例 #5
0
ファイル: functions.php プロジェクト: vrtulka23/daiquiri
 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);
     }
 }
コード例 #6
0
 /**
  * Sends a request and returns a response
  *
  * @param CartRecover_Request $request
  * @return Cart_Recover_Response
  */
 public function sendRequest(CartRecover_Request $request)
 {
     $this->client->setUrl($request->getUri());
     $this->client->getUrl()->setQueryVariables($request->getParams());
     $this->client->setMethod($request->getMethod());
     $this->client->setHeader('Accept', 'application/json');
     $this->response = $this->client->send();
     if ($this->response->getHeader('Content-Type') != 'application/json') {
         throw new CartRecover_Exception_UnexpectedValueException("Unknown response format.");
     }
     $body = json_decode($this->response->getBody(), true);
     $response = new CartRecover_Response();
     $response->setRawResponse($this->response->getBody());
     $response->setBody($body);
     $response->setHeaders($this->response->getHeader());
     $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatus());
     return $response;
 }
コード例 #7
0
ファイル: Client.php プロジェクト: ryo88c/BEAR.Saturday
 /**
  * Http request
  *
  * @param string $method
  * @param string $url
  * @param array  $submit
  * @param string $formName
  *
  * @return HTTP_Request2_Response
  */
 public function request($method, $url, array $submit = array(), $formName = 'form')
 {
     $this->request = new HTTP_Request2();
     $url = new Net_URL2($url);
     $this->request->setMethod($method);
     if ($submit) {
         $submit = array_merge(array('_token' => '0dc59902014b6', '_qf__' . $formName => ''), $submit);
     }
     if ($submit && $method === 'POST') {
         $this->request->addPostParameter($submit);
     }
     if ($submit && $method === 'GET') {
         $url->setQueryVariables($submit);
     }
     $this->request->setUrl($url);
     $this->response = $this->request->send();
     return $this;
 }
コード例 #8
0
 /**
  * @link http://pear.php.net/bugs/bug.php?id=19233
  * @link http://pear.php.net/bugs/bug.php?id=15937
  */
 public function testPreventExpectHeader()
 {
     $fp = fopen(dirname(dirname(dirname(__FILE__))) . '/_files/bug_15305', 'rb');
     $observer = new HeaderObserver();
     $body = new HTTP_Request2_MultipartBody(array(), array('upload' => array('fp' => $fp, 'filename' => 'bug_15305', 'type' => 'application/octet-stream', 'size' => 16338)));
     $this->request->setMethod(HTTP_Request2::METHOD_POST)->setUrl($this->baseUrl . 'uploads.php')->setHeader('Expect', '')->setBody($body)->attach($observer);
     $response = $this->request->send();
     $this->assertNotContains('Expect:', $observer->headers);
     $this->assertContains('upload bug_15305 application/octet-stream 16338', $response->getBody());
 }
コード例 #9
0
 /**
  * Make a request to the web2project api
  *
  * @access protected
  *
  * @param  string action to be called
  * @param  array of parameters to pass to service
  * @param  string http_method type. GET, POST, PUT, DELETE, HEAD
  * @param  string type of request to make. Valid values = json, xml, html, printr, php, cli
  * @param  array of post/put vars
  * @param  array of credentials. array('username' => 'username', 'password' => 'password');
  * @param  string the base url of the tests
  *
  * @return HTTP_Request2_Response the response
  */
 protected function makeRequest($action, $parameters, $http_method = 'GET', $post_array = null, $credentials = null, $url = 'http://w2p.api.frapi/', $type = 'json')
 {
     $url .= $action . '/';
     foreach ($parameters as $param_value) {
         $url .= $param_value . '/';
     }
     // Remove excess /
     $url = substr($url, 0, strlen($url) - 1);
     // add our type
     $url .= '.' . $type;
     $http_request = new HTTP_Request2($url);
     switch (strtoupper($http_method)) {
         case 'PUT':
             $http_request->setMethod(HTTP_Request2::METHOD_PUT);
             break;
         case 'POST':
             $http_request->setMethod(HTTP_Request2::METHOD_POST);
             break;
         case 'DELETE':
             $http_request->setMethod(HTTP_Request2::METHOD_DELETE);
             break;
         case 'HEAD':
             $http_request->setMethod(HTTP_Request2::METHOD_HEAD);
             break;
         case 'GET':
         default:
             break;
     }
     $url = $http_request->getUrl();
     if (is_null($credentials)) {
         $url->setQueryVariables(array('username' => 'admin', 'password' => 'passwd'));
     } else {
         $url->setQueryVariables(array('username' => $credentials['username'], 'password' => $credentials['password']));
     }
     if (!is_null($post_array) && count($post_array)) {
         foreach ($post_array as $key => $value) {
             $url->setQueryVariable($key, $value);
         }
     }
     return $http_request->send();
 }
コード例 #10
0
 protected static function post($url, $content)
 {
     $request = new HTTP_Request2($url);
     $request->setMethod(HTTP_Request2::METHOD_POST);
     foreach ($content as $name => $val) {
         $request->addPostParameter($name, $val);
     }
     $request->setConfig(array('ssl_verify_peer' => false));
     try {
         $response = $request->send();
         $body = $response->getBody();
         return $body;
     } catch (HTTP_Request2_Exception $e) {
         return false;
     }
 }
コード例 #11
0
ファイル: github.php プロジェクト: nsystem1/leaderboard
 public static function callback()
 {
     global $HTTP_CONFIG;
     //exchange the code you get for a access_token
     $code = $_GET['code'];
     $request = new HTTP_Request2(self::ACCESS_TOKEN_URL);
     $request->setMethod(HTTP_Request2::METHOD_POST);
     $request->setConfig($HTTP_CONFIG);
     $request->addPostParameter(['client_id' => GITHUB_APP_ID, 'client_secret' => GITHUB_APP_SECRET, 'code' => $code]);
     $request->setHeader('Accept', 'application/json');
     $response = $request->send();
     $response = json_decode($response->getBody());
     $access_token = $response->access_token;
     //Use this access token to get user details
     $request = new HTTP_Request2(self::USER_URL . '?access_token=' . $access_token, HTTP_Request2::METHOD_GET, $HTTP_CONFIG);
     $response = $request->send()->getBody();
     $userid = json_decode($response)->login;
     //get the userid
     //If such a user already exists in the database
     //Just log him in and don't touch the access_token
     $already_present_token = Token::get('github', $userid);
     if ($already_present_token) {
         $_SESSION['userid'] = $userid;
         redirect_to('/');
     }
     if (defined('GITHUB_ORGANIZATION')) {
         // perform the organization check
         $request = new HTTP_Request2(json_decode($response)->organizations_url . '?access_token=' . $access_token, HTTP_Request2::METHOD_GET, $HTTP_CONFIG);
         $response = $request->send()->getBody();
         //List of organizations
         $organizations_list = array_map(function ($repo) {
             return $repo->login;
         }, json_decode($response));
         if (in_array(GITHUB_ORGANIZATION, $organizations_list)) {
             $_SESSION['userid'] = $userid;
             Token::add('github', $userid, $access_token);
         } else {
             throw new Exception('You are not in the listed members.');
         }
     } else {
         $_SESSION['userid'] = $userid;
         Token::add('github', $userid, $access_token);
     }
     redirect_to('/');
 }
コード例 #12
0
 /**
  * Fetches the HTML to be parsed
  *
  * @param string $url A valid URL to fetch
  *
  * @return string Return contents from URL (usually HTML)
  *
  * @throws Services_Mailman_Exception
  */
 protected function fetch($url)
 {
     $url = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);
     if (!$url) {
         throw new Services_Mailman_Exception('Invalid URL', Services_Mailman_Exception::INVALID_URL);
     }
     try {
         $this->request->setUrl($url);
         $this->request->setMethod('GET');
         $html = $this->request->send()->getBody();
     } catch (HTTP_Request2_Exception $e) {
         throw new Services_Mailman_Exception($e, Services_Mailman_Exception::HTML_FETCH);
     }
     if (strlen($html) > 5) {
         return $html;
     }
     throw new Services_Mailman_Exception('Could not fetch HTML', Services_Mailman_Exception::HTML_FETCH);
 }
コード例 #13
0
 /**
  * 記事を投稿する.
  *
  * @param string $title 記事タイトル
  * @param string $text 記事本文
  * @param string $category 記事カテゴリ
  * @return string $res 結果
  */
 public function postArticle($title, $text, $category)
 {
     try {
         $req = new HTTP_Request2();
         $req->setUrl(self::ROOT_END_POINT . $this->liveDoorId . "/" . self::END_POINT_TYPE_ARTICLE);
         $req->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false));
         $req->setMethod(HTTP_Request2::METHOD_POST);
         $req->setAuth($this->liveDoorId, $this->atomPubPassword);
         $req->setBody($this->createBody($title, $text, $category));
         $req->setHeader('Expect', '');
         $res = $req->send();
     } catch (HTTP_Request2_Exception $e) {
         die($e->getMessage());
     } catch (Exception $e) {
         die($e->getMessage());
     }
     return $res;
 }
コード例 #14
0
ファイル: Webhook.php プロジェクト: nickel715/phorkie
 /**
  * Call webhook URLs with our payload
  */
 public function send($event, Repository $repo)
 {
     if (count($this->config) == 0) {
         return;
     }
     /* slightly inspired by
        https://help.github.com/articles/post-receive-hooks */
     $payload = (object) array('event' => $event, 'author' => array('name' => $_SESSION['name'], 'email' => $_SESSION['email']), 'repository' => array('name' => $repo->getTitle(), 'url' => $repo->getLink('display', null, true), 'description' => $repo->getDescription(), 'owner' => $repo->getOwner()));
     foreach ($this->config as $url) {
         $req = new \HTTP_Request2($url);
         $req->setMethod(\HTTP_Request2::METHOD_POST)->setHeader('Content-Type: application/vnd.phorkie.webhook+json')->setBody(json_encode($payload));
         try {
             $response = $req->send();
             //FIXME log response codes != 200
         } catch (HTTP_Request2_Exception $e) {
             //FIXME log exceptions
         }
     }
 }
コード例 #15
0
 /**
  * Send a POST request to the specified URL with the specified payload.
  * @param string $url
  * @param string $data
  * @return string Remote data
  **/
 public function sendPOST($url, $data = array())
 {
     $data['_fake_status'] = '200';
     // Send the actual request.
     $this->instance->setHeader('User-Agent', sprintf(Imgur::$user_agent, Imgur::$key));
     $this->instance->setMethod('POST');
     $this->instance->setUrl($url);
     foreach ($data as $k => $v) {
         $this->instance->addPostParameter($k, $v);
     }
     try {
         /** @var HTTP_Request2_Response */
         $response = $this->instance->send();
         return $response->getBody();
     } catch (HTTP_Request2_Exception $e) {
         throw new Imgur_Exception("HTTP Request Failure", null, $e);
     } catch (Exception $e) {
         throw new Imgur_Exception("Unknown Failure during HTTP Request", null, $e);
     }
 }
コード例 #16
0
 public static function requestToPostMethod($argURL, $argParams = NULL, $argFiles = NULL, $argTimeOut = 60)
 {
     $HttpRequestObj = new HTTP_Request2();
     $urls = parse_url($argURL);
     if (isset($urls["user"]) && isset($urls["pass"])) {
         $HttpRequestObj->setAuth($urls["user"], $urls["pass"]);
     }
     if (isset($urls["port"])) {
         $url = $urls["scheme"] . '://' . $urls["host"] . ':' . $urls["port"];
     } else {
         $url = $urls["scheme"] . '://' . $urls["host"];
     }
     if (isset($urls["path"])) {
         $url .= $urls["path"];
     }
     $HttpRequestObj->setUrl($url);
     $HttpRequestObj->setMethod(HTTP_Request2::METHOD_POST);
     if ('https' === $urls["scheme"]) {
         $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut, 'adapter' => 'HTTP_Request2_Adapter_Curl', 'ssl_verify_peer' => FALSE, 'ssl_verify_host' => FALSE));
     } else {
         $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut));
     }
     if (is_array($argParams)) {
         foreach ($argParams as $key => $value) {
             $HttpRequestObj->addPostParameter($key, $value);
         }
     }
     // ファイルをアップロードする場合
     if (is_array($argFiles)) {
         foreach ($argFiles as $key => $value) {
             $HttpRequestObj->addUpload($key, $value);
         }
     }
     // リクエストを送信
     $response = $HttpRequestObj->send();
     // レスポンスのボディ部を表示
     return $response;
 }
コード例 #17
0
 function request($method, $url, $token, $params, $file)
 {
     $req = new HTTP_Request2($url);
     $req->setMethod($method == "get" ? 'GET' : 'POST');
     $req->setHeader("X-Gallery-Request-Method", $method);
     if ($token) {
         $req->setHeader("X-Gallery-Request-Key", $token);
     }
     foreach ($params as $key => $value) {
         $req->addPostParameter($key, is_string($value) ? $value : json_encode($value));
     }
     if ($file) {
         $req->addUpload("file", $file, basename($file), mime_content_type($file));
     }
     $response = $req->send();
     $status = $response->getStatus();
     switch ($status) {
         case 200:
         case 201:
             return json_decode($response->getBody());
         case 403:
             throw new Gallery3_Forbidden_Exception($response->getBody(), $status);
         default:
             throw new Gallery3_Exception($response->getBody(), $status);
     }
 }
コード例 #18
0
ファイル: API.php プロジェクト: cloudcontrol/phpcclib
 /**
  * we use the Pear::\HTTP_Request2 for all the heavy HTTP protocol lifting.
  *
  * @param string $resource api-resource
  * @param string $method request method [default:"GET"]
  * @param array $data request data as associative array [default:array()]
  * @param array $headers optional request header [default:array()]
  *
  * @throws ConnectionException
  * @throws BadRequestError
  * @throws UnauthorizedError
  * @throws ForbiddenError
  * @throws ConflictDuplicateError
  * @throws GoneError
  * @throws InternalServerError
  * @throws NotImplementedError
  * @throws ThrottledError
  * @throws CCException
  *
  * @return string json encoded servers response
  */
 private function _request($resource, $method = \HTTP_Request2::METHOD_GET, $data = array(), $headers = array())
 {
     $url = $this->_url . $resource;
     $request = new \HTTP_Request2($url);
     $request->setConfig(array('ssl_verify_peer' => API::SSL_VERIFY_PEER, 'ssl_cafile' => realpath(dirname(__FILE__)) . '/cacert.pem'));
     $methods = array('options' => \HTTP_Request2::METHOD_OPTIONS, 'get' => \HTTP_Request2::METHOD_GET, 'head' => \HTTP_Request2::METHOD_HEAD, 'post' => \HTTP_Request2::METHOD_POST, 'put' => \HTTP_Request2::METHOD_PUT, 'delete' => \HTTP_Request2::METHOD_DELETE, 'trace' => \HTTP_Request2::METHOD_TRACE, 'connect' => \HTTP_Request2::METHOD_CONNECT);
     $request->setMethod($methods[strtolower($method)]);
     #
     # If the current API instance has a valid token we add the Authorization
     # header with the correct token.
     #
     # In case we do not have a valid token but email and password are
     # provided we automatically use them to add a HTTP Basic Authenticaion
     # header to the request to create a new token.
     #
     if ($this->_token) {
         $headers['Authorization'] = sprintf('cc_auth_token="%s"', $this->_token);
     } else {
         if ($this->_email && $this->_password) {
             $request->setAuth($this->_email, $this->_password, \HTTP_Request2::AUTH_BASIC);
         }
     }
     #
     # The API expects the body to be urlencoded. If data was passed to
     # the request method we therefore use urlencode from urllib.
     #
     if (!empty($data)) {
         if ($request->getMethod() == \HTTP_Request2::METHOD_GET) {
             $url = $request->getUrl();
             $url->setQueryVariables($data);
         } else {
             // works with post and put
             $request->addPostParameter($data);
             $request->setBody(http_build_query($data));
         }
     }
     #
     # We set the User-Agent Header to pycclib and the local version.
     # This enables basic statistics about still used pycclib versions in
     # the wild.
     #
     $headers['User-Agent'] = sprintf('phpcclib/%s', $this->_version);
     #
     # The API expects PUT or POST data to be x-www-form-urlencoded so we
     # also set the correct Content-Type header.
     #
     if (strtoupper($method) == 'PUT' || strtoupper($method) == 'POST') {
         $headers['Content-Type'] = 'application/x-www-form-urlencoded';
     }
     #
     # We also set the Content-Length and Accept-Encoding headers.
     #
     //$headers['Content-Length'] = strlen($body);
     $headers['Accept-Encoding'] = 'compress, gzip';
     #
     # Finally we fire the actual request.
     #
     foreach ($headers as $k => $v) {
         $request->setHeader(sprintf('%s: %s', $k, $v));
     }
     for ($i = 1; $i < 6; $i++) {
         try {
             $response = $request->send();
             return $this->_return($response);
         } catch (\HTTP_Request2_Exception $e) {
             # if we could not reach the API we wait 1s and try again
             sleep(1);
             # if we tried for the fifth time we give up - and cry a little
             if ($i == 5) {
                 throw new ConnectionException('Could not connect to API...');
             }
         }
     }
 }
コード例 #19
0
 /**
  * Sends request
  *
  * @param string  $service
  * @param array   $params
  * @return array  json_decoded body
  **/
 private function execute($service, $queryString)
 {
     $request = new HTTP_Request2();
     try {
         $request->setMethod($this->httpMethod);
         $request->setHeader('Referer', $this->getHttpReferer());
         $url = self::$apiUrl . $service . '?v=1.0';
         if (isset($this->apiKey)) {
             $url .= '&key=' . $this->apiKey . '&';
         } else {
             $url .= '&';
         }
         $request->setUrl($url . substr($queryString, 0, -1));
         $response = $request->send();
         if ($response->getStatus() != 200) {
             throw new Services_Google_Translate_Exception('HTTP Error: ' . $response->getReasonPhrase());
         }
     } catch (HTTP_Request2_Exception $e) {
         throw new Services_Google_Translate_Exception($e->getMessage());
     }
     $decodedResponse = $this->decodeBody($request->send()->getBody());
     return $decodedResponse;
 }
コード例 #20
0
ファイル: vivvo_ga.php プロジェクト: ahanjir07/vivvo-dev
 /**
  * The actual method for sending requests
  *
  * @param	string	$url
  * @param	array	$headers
  * @param	array	$params
  * @return	HTTP_Request2_Response
  */
 protected function send($method, $url, array $params = array(), array $headers = array())
 {
     $headers['GData-Version'] = '2';
     $headers['User-Agent'] = 'Vivvo/' . VIVVO_VERSION . ' (' . self::$request_adapter . ') PHP/' . PHP_VERSION;
     $request = new HTTP_Request2($url);
     $request->setAdapter(self::$request_adapter);
     $request->setConfig('ssl_verify_peer', false);
     $request->setConfig('follow_redirects', true);
     $request->setHeader($headers);
     $request->setMethod($method);
     if ($method == HTTP_Request2::METHOD_POST) {
         $request->addPostParameter($params);
     }
     return $request->send();
 }
コード例 #21
0
//header("Content-Type: application/json; charset=utf-8");
header("Content-Type: text; charset=utf-8");
$json_string = file_get_contents('php://input');
$obj = json_decode($json_string, false);
//get Params
$url = $obj->url;
$method = $obj->method;
$header = (array) $obj->headers;
$body = $obj->body;
try {
    // リクエスト作成
    $request = new HTTP_Request2();
    $request->setHeader($header);
    $request->setUrl($url);
    if ($method == 'GET') {
        $request->setMethod(HTTP_Request2::METHOD_GET);
    } elseif ($method == 'POST') {
        $request->setMethod(HTTP_Request2::METHOD_POST);
    } elseif ($method == 'PUT') {
        $request->setMethod(HTTP_Request2::METHOD_PUT);
    } elseif ($method == 'DELETE') {
        $request->setMethod(HTTP_Request2::METHOD_DELETE);
    } else {
        die;
    }
    $request->setBody(trim($body));
    $request->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false));
    // レスポンス取得
    $response = $request->send();
    // HTTP_Request2のエラーを表示
} catch (HTTP_Request2_Exception $e) {
コード例 #22
0
ファイル: daiquiri.php プロジェクト: adrpar/daiquiri
function daiquiri_auto_login()
{
    if (!is_user_logged_in()) {
        // check which user is logged in into daiquiri right now
        $userUrl = DAIQUIRI_URL . '/auth/account/show/';
        require_once 'HTTP/Request2.php';
        $req = new HTTP_Request2($userUrl);
        $req->setConfig(array('ssl_verify_peer' => false, 'connect_timeout' => 2, 'timeout' => 3));
        $req->setMethod('GET');
        $req->addCookie("PHPSESSID", $_COOKIE["PHPSESSID"]);
        $req->setHeader('Accept: application/json');
        try {
            $response = $req->send();
            $status = $response->getStatus();
            $body = $response->getBody();
        } catch (HTTP_Request2_Exception $e) {
            echo '<h1>Error with daiquiri auth</h1><p>Error with HTTP request.</p>';
            die(0);
        }
        if ($status == 403) {
            if (is_user_logged_in()) {
                wp_clear_auth_cookie();
                wp_redirect($_SERVER['REQUEST_URI']);
                exit;
            }
        } else {
            if ($status == 200) {
                // decode the non empty json to the remote user array
                $remoteUser = json_decode($response->getBody());
                $daiquiriUser = array();
                foreach (array('id', 'username', 'email', 'role') as $key) {
                    if (isset($remoteUser->row->{$key})) {
                        $daiquiriUser[$key] = $remoteUser->row->{$key};
                    }
                }
                foreach (array('firstname', 'lastname', 'website') as $key) {
                    if (isset($remoteUser->row->details->{$key})) {
                        $daiquiriUser[$key] = $remoteUser->row->details->{$key};
                    }
                }
                // create/update the wordpress user to match the daiquiri user
                // the id in daiquiri maps to the user_login in wp
                // the username in daiquiri maps to the user_nicename in wp
                $wpUser = array('user_login' => $daiquiriUser['id'], 'user_nicename' => $daiquiriUser['username'], 'user_pass' => 'foo', 'user_email' => $daiquiriUser['email']);
                // get the role of the user
                if ($daiquiriUser['role'] === 'admin') {
                    $wpUser['role'] = 'administrator';
                } else {
                    if ($daiquiriUser['role'] === 'manager') {
                        $wpUser['role'] = 'editor';
                    } else {
                        if (defined('DAIQUIRI_AUTHOR_ROLE') && $daiquiriUser['role'] === DAIQUIRI_AUTHOR_ROLE) {
                            $wpUser['role'] = 'author';
                        } else {
                            if (defined('DAIQUIRI_CONTRIBUTOR_ROLE') && $daiquiriUser['role'] === DAIQUIRI_CONTRIBUTOR_ROLE) {
                                $wpUser['role'] = 'contributor';
                            } else {
                                $wpUser['role'] = 'subscriber';
                            }
                        }
                    }
                }
                // get the name and the other credentials
                if (isset($daiquiriUser['firstname'])) {
                    $wpUser['first_name'] = $daiquiriUser['firstname'];
                }
                if (isset($daiquiriUser['lastname'])) {
                    $wpUser['last_name'] = $daiquiriUser['lastname'];
                }
                if (isset($daiquiriUser['website'])) {
                    $wpUser['user_url'] = $daiquiriUser['website'];
                }
                if (isset($wpUser['first_name']) && isset($wpUser['last_name'])) {
                    $wpUser['display_name'] = $wpUser['first_name'] . ' ' . $wpUser['last_name'];
                }
                // update or create the user in the wordpress db
                $storedUser = get_user_by('login', $wpUser['user_login']);
                if ($storedUser === false) {
                    // create a new user in the wordpress db
                    $status = wp_insert_user($wpUser);
                } else {
                    // update the user in the wordpress database
                    $wpUser['ID'] = $storedUser->ID;
                    $status = wp_update_user($wpUser);
                }
                if (is_int($status)) {
                    $userId = $status;
                } else {
                    echo '<h1>Error with auth</h1>';
                    var_dump($status);
                    exit;
                }
                // log in the newly created or updated user
                $user = get_userdata($userId);
                wp_set_current_user($user->ID, $user->user_login);
                wp_set_auth_cookie($user->ID);
                do_action('wp_login', $user->user_login);
            } else {
                echo '<h1>Error with auth</h1><p>HTTP request status != 200.</p>';
                die(0);
            }
        }
    }
}
コード例 #23
0
 /**
  * Получить синоним карточки
  * 
  * @param type $card
  * @param type $sum
  * @return type
  */
 public function getDestinationCardSynonim($card, $sum)
 {
     $request = new HTTP_Request2('https://paymentcard.yamoney.ru/gates/card/storeCard');
     $request->setMethod(HTTP_Request2::METHOD_POST)->addPostParameter(array('skr_destinationCardNumber' => $card, 'sum' => $sum, 'skr_errorUrl' => '', 'skr_successUrl' => ''));
     //@todo: непонятно почему я должен указывать расположение сертификата поумолчанию, например crul его видит
     $request->setConfig(array('ssl_cafile' => '/etc/pki/tls/certs/ca-bundle.crt'));
     $response = $request->send();
     $header = $response->getHeader();
     $query = parse_url($header['location'], PHP_URL_QUERY);
     $results = array();
     parse_str($query, $results);
     return isset($results['skr_destinationCardSynonim']) ? $results['skr_destinationCardSynonim'] : false;
 }
コード例 #24
0
 /**
  * 
  * @param type $method
  * @param string $url
  * @return \HTTP_Request2
  */
 protected function createClient($method = 'GET', $urlPart = null)
 {
     $url = $this->url . $this->requestPath;
     if ($urlPart) {
         $url .= '/' . $urlPart;
     }
     $request = new HTTP_Request2();
     $request->setMethod($method);
     $request->setURL($url);
     $request->setConfig(array('ssl_verify_peer' => false));
     return $request;
 }
コード例 #25
0
 /**
  * Sets request's HTTP method. You can use \HTTP_Request2 constants like
  * Resources::HTTP_GET or strings like 'GET'.
  * 
  * @param string $method request's HTTP method.
  * 
  * @return none
  */
 public function setMethod($method)
 {
     $this->_request->setMethod($method);
 }
コード例 #26
0
ファイル: Request2Test.php プロジェクト: brucewu16899/1.6.x
 public function testPostParametersPrecedeSetBodyForPost()
 {
     $req = new HTTP_Request2('http://www.example.com/', HTTP_Request2::METHOD_POST);
     $req->setBody('Request body');
     $req->addPostParameter('foo', 'bar');
     $this->assertEquals('foo=bar', $req->getBody());
     $req->setMethod(HTTP_Request2::METHOD_PUT);
     $this->assertEquals('Request body', $req->getBody());
 }
コード例 #27
0
ファイル: MailingList.php プロジェクト: tothi/php-mailinglist
 public function delete_mailinglist($list)
 {
     $req = new HTTP_Request2($this->url . "/com/delmailinglistnow");
     $req->setMethod(HTTP_Request2::METHOD_POST);
     $req->getUrl()->setQueryVariables($this->auth);
     $req->addPostParameter(array('modu' => $list));
     $resp = $req->send();
     // refresh lists in class
     $this->get_mailinglists();
 }
コード例 #28
0
ファイル: estraierpure.php プロジェクト: bermi/akelos
 /**
  * Perform an interaction of a URL.
  *
  * @param   string  $url        A URL.
  * @param   string  $pxhost     The host name of a proxy.
  *                              If it is `null', it is not used.
  * @param   int     $pxport     The port number of the proxy.
  * @param   int     $outsec     Timeout in seconds.
  *                              If it is negative, it is not used.
  * @param   array   $reqheads   An array of extension headers.
  *                              If it is `null', it is not used.
  * @param   string  $reqbody    The pointer of the entitiy body of request.
  *                              If it is `null', "GET" method is used.
  * @param   object  $res    EstraierPure_Response
  *                          an object into which headers and
  *                          the entity body of response are stored.
  *                          If it is `null', it is not used.
  * @return  int     The status code of the response.
  *                  On error, returns PEAR_Error.
  * @access  public
  * @static
  * @uses    PEAR
  * @uses    HTTP_Request2
  */
 static function shuttle_url($url, $pxhost = null, $pxport = null, $outsec = -1, $reqheads = null, $reqbody = null, $res = null)
 {
     // HTTPS checking disabled.
     /*$https = preg_match('!^https://!i', $url);
       if ($https && !extension_loaded('openssl')) {
           $err = PEAR::raiseError('HTTPS is not supported.');
           self::push_error($err);
           return $err;
       }*/
     if (is_null($reqheads)) {
         $reqheads = array();
     }
     $reqheads['User-Agent'] = sprintf('EstraierPure/%s (for PHP 5.1)', ESTRAIERPURE_VERSION);
     if (ESTRAIERPURE_USE_HTTP_STREAM) {
         // {{{ using stream functions
         // set request parameters
         $params = array('http' => array());
         if (is_null($reqbody)) {
             $params['http']['method'] = 'GET';
         } else {
             $params['http']['method'] = 'POST';
             $params['http']['content'] = $reqbody;
             $reqheads['Content-Length'] = strlen($reqbody);
         }
         if (!is_null($pxhost)) {
             /*if ($https && version_compare(phpversion(), '5.1.0', 'lt')) {
                   $err = PEAR::raiseError('HTTPS proxies are not supported.');
                   self::push_error($err);
                   return $err;
               }*/
             $params['http']['proxy'] = sprintf('tcp://%s:%d', $pxhost, $pxport);
         }
         $params['http']['header'] = '';
         foreach ($reqheads as $key => $value) {
             $params['http']['header'] .= sprintf("%s: %s\r\n", $key, $value);
         }
         $context = stream_context_create($params);
         // open a stream and send the request
         $fp = fopen($url, 'r', false, $context);
         if (!$fp) {
             $err = PEAR::raiseError(sprintf('Cannot connect to %s.', $url));
             self::push_error($err);
             return $err;
         }
         if ($outsec >= 0) {
             stream_set_timeout($fp, $outsec);
         }
         // process the response
         $meta_data = stream_get_meta_data($fp);
         if (strcasecmp($meta_data['wrapper_type'], 'cURL') == 0) {
             $errmsg = 'EstraierPure does not work with the cURL' . ' HTTP stream wrappers, please use PEAR::HTTP_Request2.';
             $err = PEAR::raiseError($errmsg);
             self::push_error($err);
             return $err;
         }
         if (!empty($meta_data['timed_out'])) {
             $err = PEAR::raiseError('Connection timed out.');
             self::push_error($err);
             return $err;
         }
         $first_header = array_shift($meta_data['wrapper_data']);
         if (!preg_match('!^HTTP/(.+?) (\\d+) ?(.*)!', $first_header, $matches)) {
             $err = PEAR::raiseError('Malformed response.');
             self::push_error($err);
             return $err;
         }
         $code = intval($matches[2]);
         if ($res instanceof EstraierPure_Response) {
             if ($res->save_heads) {
                 foreach ($meta_data['wrapper_data'] as $header) {
                     list($name, $value) = explode(':', $header, 2);
                     $res->add_head(strtolower($name), ltrim($value));
                 }
             }
             if ($res->save_body) {
                 $res->set_body(stream_get_contents($fp));
             }
         }
         // close the stream
         fclose($fp);
         // }}}
     } else {
         // {{{{ using PEAR::HTTP_Request2
         // set request parameters
         $params = array();
         $params['requestHeaders'] = $reqheads;
         if (isset($params['requestHeaders']['Content-Type'])) {
             unset($params['requestHeaders']['Content-Type']);
             $params['requestHeaders']['content-type'] = $reqheads['Content-Type'];
         }
         if (!is_null($pxhost)) {
             $params['proxy_host'] = $pxhost;
             $params['proxy_port'] = $pxport;
         }
         if ($outsec >= 0) {
             $params['timeout'] = floatval($outsec);
             $params['readTimeout'] = array($outsec, 0);
         }
         // create an instance of HTTP_Request2
         $req = new HTTP_Request2($url, $params);
         if (is_null($reqbody)) {
             $req->setMethod('GET');
         } else {
             $req->setMethod('POST');
             $req->setBody($reqbody);
         }
         // send the request
         $err = $req->sendRequest(is_object($res) && !empty($res->save_body));
         if (PEAR::isError($err)) {
             self::push_error($err);
             return $err;
         }
         $code = $req->getResponseCode();
         // process the response
         if ($res instanceof EstraierPure_Response) {
             if ($res->save_heads) {
                 $res->set_heads($req->getResponseHeader());
             }
             if ($res->save_body) {
                 $res->set_body($req->getResponseBody());
             }
         }
         // }}}
     }
     return $code;
 }
コード例 #29
0
 /**
 * Get HTTP request response header string
 *
 * @param string $url target URL
 * @return string
 * @author Naoki Sawada
 */
 private function getHttpResponseHeader($url)
 {
     if (function_exists('curl_exec')) {
         $c = curl_init();
         curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'HEAD');
         curl_setopt($c, CURLOPT_HEADER, 1);
         curl_setopt($c, CURLOPT_NOBODY, true);
         curl_setopt($c, CURLOPT_URL, $url);
         $res = curl_exec($c);
     } else {
         require_once 'HTTP/Request2.php';
         try {
             $request2 = new HTTP_Request2();
             $request2->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false));
             $request2->setUrl($url);
             $request2->setMethod(HTTP_Request2::METHOD_HEAD);
             $result = $request2->send();
             $res = array();
             $res[] = 'HTTP/' . $result->getVersion() . ' ' . $result->getStatus() . ' ' . $result->getReasonPhrase();
             foreach ($result->getHeader() as $key => $val) {
                 $res[] = $key . ': ' . $val;
             }
             $res = join("\r\n", $res);
         } catch (HTTP_Request2_Exception $e) {
             $res = '';
         } catch (Exception $e) {
             $res = '';
         }
     }
     return $res;
 }
コード例 #30
0
ファイル: http.inc.php プロジェクト: robinpaulson/dataserver
 public function delete($url, $headers = array(), $auth = false)
 {
     $req = new HTTP_Request2($url);
     $req->setMethod(HTTP_Request2::METHOD_DELETE);
     $req->setHeader($headers);
     if ($auth) {
         $req->setAuth($auth['username'], $auth['password']);
     }
     //$req->setConfig('ssl_verify_peer', false);
     $response = $req->send();
     return $response;
 }