/** * @see TwitterOAuth::http() * @author Naomichi Yamakita <*****@*****.**> */ public function http($uri, $method, $postData = NULL) { // TwitterOAuth::http() はレスポンスヘッダを書き換えてるため使用しない // (Mars_ResponseParser の動作に影響するため) $sender = new Mars_HttpRequestSender($uri); $sender->setUserAgent($this->useragent); $sender->setReadTimeout($this->connecttimeout); $sender->addHeader('Expect', ''); if (is_string($postData)) { parse_str($postData, $postData); } if ($method === 'POST') { $sender->setRequestMethod(Mars_HttpRequest::HTTP_POST); $sender->addParameters($postData); } else { if ($method === 'DELETE') { $sender->setRequestMethod(Mars_HttpRequest::HTTP_DELETE); if (sizeof($postData)) { $uri = $uri . '?' . OAuthUtil::build_http_query($postData); } } } $sender->setBaseURI($uri); $parser = $sender->send(); $this->http_code = $parser->getStatus(); $this->http_info = $parser->getRawHeader(); $this->url = $uri; return $parser->getContents(); }
private function execute($selected_call, $method_type, $params) { // the endpoint for your request $endpoint = "{$this->netdnarws_url}/{$this->alias}{$selected_call}"; //parse endpoint before creating OAuth request $parsed = parse_url($endpoint); if (array_key_exists("parsed", $parsed)) { parse_str($parsed['query'], $params); } //generate a request from your consumer require_once __DIR__ . '/OAuth/OAuthRequest.php'; $req_req = OAuthRequest::from_consumer_and_token($this->consumer, null, $method_type, $endpoint, $params); //sign your OAuth request using hmac_sha1 require_once __DIR__ . '/OAuth/OAuthSignatureMethod_HMAC_SHA1.php'; $sig_method = new OAuthSignatureMethod_HMAC_SHA1(); $req_req->sign_request($sig_method, $this->consumer, null); // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, $req_req); // return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Set SSL Verifyer off curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // set curl timeout curl_setopt($ch, CURLOPT_TIMEOUT, 60); // set curl custom request type if not standard if ($method_type != "GET" && $method_type != "POST") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method_type); } if ($method_type == "POST" || $method_type == "PUT" || $method_type == "DELETE") { require_once __DIR__ . '/OAuth/OAuthUtil.php'; $query_str = OAuthUtil::build_http_query($params); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:', 'Content-Length: ' . strlen($query_str))); curl_setopt($ch, CURLOPT_POSTFIELDS, $query_str); } // retrieve headers curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLINFO_HEADER_OUT, 1); //set user agent curl_setopt($ch, CURLOPT_USERAGENT, 'PHP NetDNA API Client'); // make call $result = curl_exec($ch); $headers = curl_getinfo($ch); $curl_error = curl_error($ch); // close curl resource to free up system resources curl_close($ch); // $json_output contains the output string $json_output = substr($result, $headers['header_size']); // catch errors if (!empty($curl_error) || empty($json_output)) { //throw new \NetDNA\RWSException("CURL ERROR: $curl_error, Output: $json_output", $headers['http_code'], null, $headers); return 'CURL ERROR: ' . $curl_error . ', Output: ' . $json_output; } return $json_output; }
public static function fetchQuery($query, $ts) { if (!$query) { return; } $dbr = wfGetDB(DB_SLAVE); $sql = "select min(ql_time_fetched) as ts from dedup.query_lookup where ql_query=" . $dbr->addQuotes($query); $res = $dbr->query($sql, __METHOD__); foreach ($res as $row) { $oldTs = $row->ts; } if ($oldTs > $ts) { $dbw = wfGetDB(DB_MASTER); $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes("exists") . "," . $dbw->addQuotes(wfTimestampNow()) . ")"; $dbw->query($sql, __METHOD__); return; } try { $cc_key = WH_YAHOO_BOSS_API_KEY; $cc_secret = WH_YAHOO_BOSS_API_SECRET; $url = "http://yboss.yahooapis.com/ysearch/web"; $args = array(); $args["q"] = $query; $args["format"] = "json"; $consumer = new OAuthConsumer($cc_key, $cc_secret); $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $url, $args); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL); $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args)); $ch = curl_init(); $headers = array($request->to_header()); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $rsp = curl_exec($ch); $results = json_decode($rsp); if ($results->bossresponse->responsecode == 200) { $n = 0; $dbw = wfGetDB(DB_MASTER); foreach ($results->bossresponse->web->results as $result) { $n++; $sql = "insert into dedup.query_lookup(ql_query,ql_url,ql_pos,ql_time_fetched) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes($result->url) . "," . $dbw->addQuotes($n) . "," . $dbw->addQuotes(wfTimestampNow()) . ")"; $dbw->query($sql, __METHOD__); } $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes('success') . "," . $dbw->addQuotes(wfTimestampNow()) . ")"; $dbw->query($sql, __METHOD__); } else { $dbw = wfGetDB(DB_MASTER); $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp, qll_timestamp, qll_comment) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes('badresponse') . "," . $dbw->addQuotes(wfTimestampNow()) . "," . $dbw->addQuotes("Response : " . ($results ? print_r($results, true) : '')); $dbw->query($sql, __METHOD__); } } catch (Exception $ex) { $dbw = wfGetDB(DB_MASTER); $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp, qll_comment) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes("exception") . "," . $dbw->addQuotes(wfTimestampNow()) . "," . $dbw->addQuotes($ex->getMessage()) . ")"; $dbw->query($sql, __METHOD__); } }
function post($url, $params = array(), $multi = false) { $query = ""; if ($multi) { $query = OAuthUtil::build_http_query_multi($params); } else { $query = OAuthUtil::build_http_query($params); } $response = $this->http($url, 'POST', $query, $multi); return $response; }
public function testBuildHttpQuery() { // Tests taken from // http://wiki.oauth.net/TestCases ("Normalize Request Parameters") $this->assertEquals('name=', OAuthUtil::build_http_query(array('name' => ''))); $this->assertEquals('a=b', OAuthUtil::build_http_query(array('a' => 'b'))); $this->assertEquals('a=b&c=d', OAuthUtil::build_http_query(array('a' => 'b', 'c' => 'd'))); $this->assertEquals('a=x%20y&a=x%21y', OAuthUtil::build_http_query(array('a' => array('x!y', 'x y')))); $this->assertEquals('x=a&x%21y=a', OAuthUtil::build_http_query(array('x!y' => 'a', 'x' => 'a'))); // Test taken from the Spec 9.1.1 $this->assertEquals('a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t', OAuthUtil::build_http_query(array('a' => '1', 'c' => 'hi there', 'f' => array(25, 50, 'a'), 'z' => array('p', 't')))); }
/** * Get the authorize URL * * @returns a string */ function getAuthorizeURL($response_type, $scope=null, $state=null, $display=null) { $params = array( 'client_id' => $this->client_id, 'response_type' => $response_type, 'redirect_uri' => $this->redirect_uri, ); if(!empty($scope)) $params['scope'] = $scope; if(!empty($state)) $params['state'] = $state; if(!empty($display)) $params['display'] = $display; $query = OAuthUtil::build_http_query($params); return $this->authorizeURL . "?{$query}"; }
public function makeSignedRequest($url, $fields) { if (isset($this->access_token)) { $params = array("nk_token" => $this->access_token, "fields" => $fields); $consumer = new OAuthConsumer($this->client_id, $this->client_secret); $req = OAuthRequest::from_consumer_and_token($consumer, null, 'GET', $url, $params); $req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, null); $auth_header = $req->to_header(); $options['headers'] = array($auth_header, 'Content-Type: application/json'); $url = $url . "?" . OAuthUtil::build_http_query($params); return $this->makeRequest($url, $options); } }
public function geocode($location = FALSE) { $args = $this->args(); $request = $this->authorize($args); $url = sprintf("%s?%s", $this->baseUrl, OAuthUtil::build_http_query($args)); $ch = curl_init(); $headers = array($request->to_header()); curl_setopt($ch, CURLOPT_ENCODING, "gzip"); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); return curl_exec($ch); }
function post($url, $params = array(), $multi = false) { $query = ""; if ($multi) { $query = OAuthUtil::build_http_query_multi($params); } else { $query = OAuthUtil::build_http_query($params); } $response = $this->http($url, 'POST', $query, $multi); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; }
public function testBuildHttpQuery() { // Tests taken from // http://wiki.oauth.net/TestCases ("Normalize Request Parameters") $this->assertEquals('name=', OAuthUtil::build_http_query(array('name' => ''))); $this->assertEquals('a=b', OAuthUtil::build_http_query(array('a' => 'b'))); $this->assertEquals('a=b&c=d', OAuthUtil::build_http_query(array('a' => 'b', 'c' => 'd'))); $this->assertEquals('a=x%20y&a=x%21y', OAuthUtil::build_http_query(array('a' => array('x!y', 'x y')))); $this->assertEquals('x=a&x%21y=a', OAuthUtil::build_http_query(array('x!y' => 'a', 'x' => 'a'))); // Test taken from the Spec 9.1.1 $this->assertEquals('a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t', OAuthUtil::build_http_query(array('a' => '1', 'c' => 'hi there', 'f' => array(25, 50, 'a'), 'z' => array('p', 't')))); // From issue 164, by hidetaka // Based on discussion at // http://groups.google.com/group/oauth/browse_thread/thread/7c698004be0d536/dced7b6c82b917b2?lnk=gst&q=sort# $this->assertEquals('x=200&x=25&y=B&y=a', OAuthUtil::build_http_query(array('x' => array(25, 200), 'y' => array('a', 'B')))); }
public function executeAuthorizeToken(sfWebRequest $request) { $this->token = $request->getParameter('oauth_token'); $this->information = $this->getTokenTable()->findByKeyString($this->token); $this->forward404Unless($this->information); if ($request->isMethod(sfWebRequest::POST)) { $url = $this->information->getCallbackUrl(); $params = array('oauth_token' => $this->token, 'oauth_verifier' => $this->information->getVerifier()); $query = (false === strpos($url, '?') ? '?' : '&') . OAuthUtil::build_http_query($params); $this->information->setIsActive(true); $this->information->save(); $this->redirectUnless('oob' === $url, $url . $query); return sfView::SUCCESS; } return sfView::INPUT; }
public static function fetchQueryFromYBoss($row) { $query = self::makeHowToQuery($row[KeywordIdeasCSV::KEY_KEYWORD]); if (empty($query)) { return; } $cc_key = WH_YAHOO_BOSS_API_KEY; $cc_secret = WH_YAHOO_BOSS_API_SECRET; $url = "http://yboss.yahooapis.com/ysearch/web"; $args = array(); $args["q"] = $query; $args["format"] = "json"; $consumer = new OAuthConsumer($cc_key, $cc_secret); $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $url, $args); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL); $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args)); $ch = curl_init(); $headers = array($request->to_header()); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $rsp = curl_exec($ch); $results = json_decode($rsp); $totalResults = 0; if ($results->bossresponse->responsecode == 200) { $totalResults = $results->bossresponse->web->totalresults; $titles = array(); foreach ($results->bossresponse->web->results as $idx => $result) { $title = self::getShortTitle($result->title); if (self::isHowToResult($title) == 1) { $csvRow = array(); $csvRow[self::KEY_POS_IN_RESULTS] = $idx; $csvRow[self::KEY_ORIG_TITLE] = $result->title; $csvRow[self::KEY_SHORT_TITLE] = $result->title; $csvRow[self::KEY_SHORT_TITLE] = $title; $csvRow[self::KEY_SITE] = self::getDomain($result->url); $csvRow[self::KEY_URL] = $result->url; $titles[] = $csvRow; } } } else { $err = "Error in fetching reults from boss for kw=[{$query}]. Resp code = " . $results->bossresponse->responsecode . "<br>\n"; } return array($err, $totalResults, $titles); }
/** * リクエストトークンの取得方法サンプル */ function howToGetRequestToken() { // // Google Data APIを利用する場合には"scope"パラメータが必須 // 参考:http://code.google.com/intl/ja/apis/accounts/docs/OAuth_ref.html#RequestToken // 参考:http://code.google.com/intl/ja/apis/gdata/faq.html#AuthScopes // $additional_param = array('scope' => 'https://www.google.com/calendar/feeds/'); // // request tokenを取得 // $req_token = OAuthWrapUtil::get_request_token($this->target_consumer, $additional_param); print $req_token . "\n"; // // user authorizatio url // $auth_url = OAuthWrapUtil::get_user_authorization_url($this->target_consumer); print $auth_url . '?' . OAuthUtil::build_http_query(array('oauth_token' => $req_token->key)) . "\n"; }
/** * builds the data one would send in a POST request */ public function to_postdata($raw = false) { if ($raw) { return $this->parameters; } else { return OAuthUtil::build_http_query($this->parameters); } }
/** * builds the data one would send in a POST request */ public function to_postdata($multi = false) { if ($multi) { return OAuthUtil::build_http_query_multi($this->parameters); } else { return OAuthUtil::build_http_query($this->parameters); } }
<?php require "OAuth.php"; $cc_key = "dj0yJmk9N1RzN3JpVzZwWlFDJmQ9WVdrOVpGUnJabGhITldVbWNHbzlNVEEyTnpBME16STJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD03Yg--"; $cc_secret = "fbce53c4c5357410c6be19d583274054d3832375"; $url = "http://yboss.yahooapis.com/ysearch/ads,web"; $args = array(); $args["q"] = "iphone"; $args["format"] = "json"; $args["ads.Partner"] = "domaindev_syn_boss46_ss_search"; $args["ads.Type"] = "ddc_nitrofinder_com"; $args["ads.count"] = "12"; //$args["ads.test"] = "true"; //$args["ads.url"] = "http://titanbrowser.com/search.php"; $consumer = new OAuthConsumer($cc_key, $cc_secret); $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $url, $args); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL); $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args)); $ch = curl_init(); $headers = array($request->to_header()); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $rsp = curl_exec($ch); $results = json_decode($rsp); print_r($results);
/** * builds the data one would send in a POST request */ public function to_postdata( $multi = false ) { //echo "multi=" . $multi . '`'; if( $multi ) return OAuthUtil::build_http_query_multi($this->parameters); else return OAuthUtil::build_http_query($this->parameters); }
/** * Executes render action * * @param sfWebRequest $request */ public function executeRender(sfWebRequest $request) { include_once sfConfig::get('sf_lib_dir') . '/vendor/OAuth/OAuth.php'; $this->memberApplication = Doctrine::getTable('MemberApplication')->findOneByApplicationAndMember($this->application, $this->member); $this->redirectUnless($this->memberApplication, '@application_info?id=' . $this->application->getId()); $views = $this->application->getViews(); $this->forward404Unless(isset($views['mobile']) && isset($views['mobile']['type']) && isset($views['mobile']['href']) && 'URL' === strtoupper($views['mobile']['type'])); $method = $request->isMethod(sfWebRequest::POST) ? 'POST' : 'GET'; $url = $request->getParameter('url', $views['mobile']['href']); $zendUri = Zend_Uri_Http::fromString($url); $queryString = $zendUri->getQuery(); $zendUri->setQuery(''); $zendUri->setFragment(''); $url = $zendUri->getUri(); $query = array(); parse_str($queryString, $query); $params = array('opensocial_app_id' => $this->application->getId(), 'opensocial_owner_id' => $this->member->getId()); $params = array_merge($query, $params); unset($params['lat']); unset($params['lon']); unset($params['geo']); if ($request->hasParameter('l') && $this->getUser()->hasFlash('op_opensocial_location')) { $method = 'p' == $request->getParameter('l') ? 'POST' : 'GET'; $location = unserialize($this->getUser()->getFlash('op_opensocial_location')); if (isset($location['lat']) && isset($location['lon']) && isset($location['geo'])) { $params['lat'] = $location['lat']; $params['lon'] = $location['lon']; $params['geo'] = $location['geo']; } } $consumer = new OAuthConsumer(opOpenSocialToolKit::getOAuthConsumerKey(), null, null); $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin(); $httpOptions = opOpenSocialToolKit::getHttpOptions(); // for BC 1.2 $isAutoConvert = sfConfig::get('op_opensocial_is_auto_convert_encoding', false); $client = new Zend_Http_Client(); if ('POST' !== $method) { $client->setMethod(Zend_Http_Client::GET); $url .= '?' . OAuthUtil::build_http_query($params); } else { $postParameters = $isAutoConvert ? $this->getPostParameters() : $_POST; $params = array_merge($params, $postParameters); $client->setMethod(Zend_Http_Client::POST); $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED); $client->setRawData(OAuthUtil::build_http_query($params)); } $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $url, $params); $oauthRequest->sign_request($signatureMethod, $consumer, null); $client->setConfig($httpOptions); $client->setUri($url); $client->setHeaders($oauthRequest->to_header()); $client->setHeaders(opOpenSocialToolKit::getProxyHeaders($request, sfConfig::get('op_opensocial_is_strip_uid', true))); if ($isAutoConvert) { $client->setHeaders('Accept-Charset: UTF-8'); } else { $client->setHeaders('Accept-Charset: Shift_JIS, UTF-8'); } try { $response = $client->request(); } catch (Zend_Http_Client_Exception $e) { $this->logMessage($e->getMessage(), 'err'); return sfView::ERROR; } if ($response->isSuccessful()) { $contentType = $response->getHeader('Content-Type'); if (preg_match('#^(text/html|application/xhtml\\+xml|application/xml|text/xml)#', $contentType, $match)) { if ($isAutoConvert) { $this->response->setContentType($match[0] . '; charset=Shift_JIS'); } else { $this->response->setContentType($contentType); } $rewriter = new opOpenSocialMobileRewriter($this); $this->response->setContent($rewriter->rewrite($response->getBody(), $contentType, $isAutoConvert)); } else { $this->response->setContentType($contentType); $this->response->setContent($response->getBody()); } if ('test' === $this->context->getConfiguration()->getEnvironment()) { return sfView::NONE; } $this->response->send(); exit; } elseif ($response->isRedirect() && ($location = $response->getHeader('location'))) { if (!Zend_Uri_Http::check($location)) { $uri = $client->getUri(); if (strpos($location, '?') !== false) { list($location, $query) = explode('?', $location, 2); } else { $query = ''; } $uri->setQuery($query); if (strpos($location, '/') === 0) { $uri->setPath($location); } else { $path = $uri->getPath(); $path = rtrim(substr($path, 0, strrpos($path, '/')), "/"); $uri->setPath($path . '/' . $location); } $location = $uri->getUri(); } $this->redirect('@application_render?id=' . $this->application->id . '&url=' . urlencode($location)); } return sfView::ERROR; }
function getIcons($word) { require __DIR__ . '/extensions/oauth.php'; require __DIR__ . '/../../bin/private/variables.php'; $url = "http://api.thenounproject.com/icons/" . $word; $args = array(); $args["limit"] = 10; $consumer = new OAuthConsumer($cc_key, $cc_secret); $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $url, $args); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL); $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args)); $ch = curl_init(); $headers = array($request->to_header()); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $rsp = curl_exec($ch); //$results = json_decode($rsp); //print_r($results); echo $rsp; }
/** * Query the GSA, return the results in XML. */ private function googleSearchResults($q, $start, $limit = 30, $gm_type = self::SEARCH_OTHER) { global $wgOut, $wgRequest, $wgUser, $wgMemc, $wgBogusQueries, $IP; $key = wfMemcKey("YahooBoss1", str_replace(" ", "-", $q), $start, $limit); $set_cache = true; $q = trim($q); if (in_array(strtolower($q), $wgBogusQueries)) { return null; } // All yahoo boss searches have host_id of 100 $host_id = 100; $cache = 0; $gm_tm_count = 0; $res = $wgMemc->get($key); if ($res) { $contents = $res; $set_cache = false; $cache = 1; } else { $cc_key = WH_YAHOO_BOSS_API_KEY; $cc_secret = WH_YAHOO_BOSS_API_SECRET; $url = "http://yboss.yahooapis.com/ysearch/web"; // Request spelling results for logged in search if ($gm_type == self::SEARCH_LOGGED_IN || $gm_type == self::SEARCH_LOGGED_OUT) { $url .= ",spelling"; } $args = array('q' => $q, 'format' => 'json', 'sites' => 'www.wikihow.com', 'start' => $start, 'count' => $limit); // Yahoo boss required OAuth 1.0 authentication require_once "{$IP}/extensions/wikihow/common/oauth/OAuth.php"; $consumer = new OAuthConsumer($cc_key, $cc_secret); $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $url, $args); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL); $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args)); $ch = curl_init(); $headers = array($request->to_header()); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $rsp = curl_exec($ch); $contents = null; $gm_tm_count = curl_getinfo($ch, CURLINFO_TOTAL_TIME); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($http_code != 200 || curl_errno($ch)) { $wgOut->addHTML("Sorry! An error was experienced while processing your search. Try refreshing the page or click <a href=\"{$wgRequest->getRequestURL()}\">here</a> to try again. "); //self::logSearch($q, $host_id, 0, 1, curl_errno($ch), $gm_tm_count, 0, $wgUser->getName(), $wgUser->getID(), 0, 0, $gm_type); curl_close($ch); return null; } else { $contents = json_decode($rsp, true); curl_close($ch); } } $num_results = $contents['totalresults'] ? $contents['totalresults'] : 0; //self::logSearch($q, $host_id, $cache, 0, 0, $gm_tm_count, 0, $wgUser->getName(), $wgUser->getId(), 0, $num_results, $gm_type); if ($set_cache) { $wgMemc->set($key, $contents, 3600); // 1 hour } if ($gm_type == self::SEARCH_LOGGED_IN || $gm_type == self::SEARCH_LOGGED_OUT) { $this->mSpelling = $contents['bossresponse']['spelling']; } $this->mResults = $contents['bossresponse']['web']; $this->mLast = $this->mStart + $this->mResults['count']; return $contents; }
/** * Metoda pozwalająca na bezpośrednie wywołanie dowolnego serwisu API NK, zwraca dane w postaci tablicy, odpowiadającej * formatowi danych wywoływanego serwisu. Zwróć uwagę, iż nie wszystkie serwisy opisane w ogólnej dokumentacji są otwarte * w publicznym API * * @since 1.0 * * @param $url * @param array $params * @param string $method * * @throws NKServiceHttpException|NKServiceMissingException|NKServiceMissingPermissionException|NKServiceInvalidParamsException * @return array */ public function call($url, $params = array(), $method = NKHttpClient::HTTP_GET) { $url = self::BASE_URL . $url; if (NKHttpClient::HTTP_GET == $method) { $body = null; $params = array_merge(array("nk_token" => $this->getTokenProvider()->getToken()), $params); $url_params = $params; } elseif (NKHttpClient::HTTP_POST == $method) { $body = json_encode($params); $params = array("nk_token" => $this->getTokenProvider()->getToken(), "oauth_body_hash" => base64_encode(hash('sha1', $body, true))); $url_params = array("nk_token" => $this->getTokenProvider()->getToken()); } else { throw new NKServiceInvalidParamsException("Unknown HTTP method to call"); } $request = OAuthRequest::from_consumer_and_token($this->getOAuthConsumer(), null, $method, $url, $params); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $this->getOAuthConsumer(), null); $url = $url . "?" . OAuthUtil::build_http_query($url_params); $this->debugOutput($url); $auth_header = $request->to_header(); $this->debugOutput($auth_header); $client = $this->getHttpClient(); try { $client->exec($url, array($auth_header, 'Content-Type: application/json; charset=utf8'), $method, $body); } catch (NKHttpClientException $e) { throw new NKServiceHttpException($e->getMessage(), $e->getCode()); } switch ($rc = $client->getResponseCode()) { case 0: throw new NKServiceHttpException("No HTTP request were executed"); break; case 200: break; case 404: throw new NKServiceMissingException("No such service"); break; case 401: case 403: throw new NKServiceMissingPermissionException("You need additional permissions to use this service ({$rc})"); break; default: throw new NKServiceHttpException("Invalid response HTTP code {$rc}"); break; } $data = json_decode($client->getResponse(), true); $this->debugOutput($data); return $data; }
/** * Make an HTTP request * * @return API results */ private function http($url, $method = "GET", $postfields = NULL) { $this->http_info = array(); $handle = curl_init(); /* Curl settings */ curl_setopt($handle, CURLOPT_HEADER, FALSE); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); curl_setopt($handle, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); curl_setopt($handle, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($handle, CURLOPT_USERAGENT, $this->useragent); curl_setopt($handle, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); if ($this->proxy_settings['behind_proxy']) { curl_setopt($ci, CURLOPT_PROXY, $this->proxy_settings['host']); curl_setopt($ci, CURLOPT_PROXYPORT, $this->proxy_settings['port']); curl_setopt($ci, CURLOPT_PROXYUSERPWD, "{$this->proxy_settings['user']}:{$this->proxy_settings['pass']}"); curl_setopt($ci, CURLOPT_PROXYTYPE, $this->proxy_settings['type']); curl_setopt($ci, CURLOPT_PROXYAUTH, $this->proxy_settings['auth']); } switch ($method) { case self::$METHOD_POST: curl_setopt($handle, CURLOPT_POST, TRUE); if (!empty($postfields)) { curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields); } break; case self::$METHOD_DELETE: curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE'); if (!empty($postfields)) { $url .= "?" . OAuthUtil::build_http_query($postfields); } break; } curl_setopt($handle, CURLOPT_URL, $url); $response = curl_exec($handle); $this->http_code = curl_getinfo($handle, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($handle)); $this->url = $url; curl_close($handle); return $response; }
/** * builds the data one would send in a POST request */ public function to_postdata($array = false) { return OAuthUtil::build_http_query($this->parameters, $array); }
private function getMyUrl() { $server_data = $this->getHttpRequest()->getServerData(); $url = true === isset($server_data["HTTPS"]) && 'on' == $server_data["HTTPS"] ? "https://" : "http://"; $url .= $server_data['HTTP_HOST'] . parse_url($server_data['REQUEST_URI'], PHP_URL_PATH); $params = parse_url($server_data['REQUEST_URI'], PHP_URL_QUERY); $strip = array('nkconnect_state', 'code', 'state', 'error', 'error_description'); if ($params) { $p = array(); foreach (OAuthUtil::parse_parameters($params) as $k => $v) { if (false === in_array($k, $strip)) { $p[$k] = $v; } } if (0 != count($p)) { $url .= '?' . OAuthUtil::build_http_query($p); } } return $url; }
/** * Executes render action * * @param sfWebRequest $request */ public function executeRender(sfWebRequest $request) { include_once sfConfig::get('sf_lib_dir') . '/vendor/OAuth/OAuth.php'; $this->memberApplication = Doctrine::getTable('MemberApplication')->findOneByApplicationAndMember($this->application, $this->member); $this->redirectUnless($this->memberApplication, '@application_info?id=' . $this->application->getId()); $views = $this->application->getViews(); $this->forward404Unless(isset($views['mobile']) && isset($views['mobile']['type']) && isset($views['mobile']['href']) && 'URL' === strtoupper($views['mobile']['type'])); $url = $request->getParameter('url', $views['mobile']['href']); $zendUri = Zend_Uri_Http::fromString($url); $queryString = $zendUri->getQuery(); $zendUri->setQuery(''); $zendUri->setFragment(''); $url = $zendUri->getUri(); $query = array(); parse_str($queryString, $query); $params = array('opensocial_app_id' => $this->application->getId(), 'opensocial_owner_id' => $this->member->getId()); $params = array_merge($query, $params); $method = $request->isMethod(sfWebRequest::POST) ? 'POST' : 'GET'; $consumer = new OAuthConsumer(opOpenSocialToolKit::getOAuthConsumerKey(), null, null); $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin(); $httpOptions = opOpenSocialToolKit::getHttpOptions(); $client = new Zend_Http_Client(); if ('POST' !== $method) { $client->setMethod(Zend_Http_Client::GET); $url .= '?' . OAuthUtil::build_http_query($params); } else { $params = array_merge($params, $request->getPostParameters()); $client->setMethod(Zend_Http_Client::POST); $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED); $client->setRawData(OAuthUtil::build_http_query($params)); } $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $url, $params); $oauthRequest->sign_request($signatureMethod, $consumer, null); $client->setConfig($httpOptions); $client->setUri($url); $client->setHeaders($oauthRequest->to_header()); $client->setHeaders(opOpenSocialToolKit::getProxyHeaders($request, sfConfig::get('op_opensocial_is_strip_uid', true))); $response = $client->request(); if ($response->isSuccessful()) { $contentType = $response->getHeader('Content-Type'); if (preg_match('#^(text/html|application/xhtml\\+xml|application/xml|text/xml)#', $contentType, $match)) { header('Content-Type: ' . $match[0] . '; charset=Shift_JIS'); echo opOpenSocialToolKit::rewriteBodyForMobile($this, $response->getBody()); exit; } else { header('Content-Type: ' . $response->getHeader('Content-Type')); echo $response->getBody(); exit; } } return sfView::ERROR; }
/** * Get the reponse * @param the url */ public function get_response($url, $method = "GET", $post_args = null) { // Basic setup $curl = curl_init(); curl_setopt($curl, CURLOPT_USERAGENT, 'Friendfeed/php'); if ($method == "POST") { $data = array(); curl_setopt($curl, CURLOPT_POST, count($post_args)); $data_string = OAuthUtil::build_http_query($post_args); curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string); } else { if ($method == "GET" && $post_args != null) { $url .= "?" . OAuthUtil::build_http_query($post_args); } } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, false); curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback')); curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback')); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // Execute, grab errors if (curl_exec($curl)) { $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE); } else { $this->response->error = array('code' => curl_errno($curl), 'message' => curl_error($curl)); } @curl_close($curl); if (isset($this->response->error)) { throw new Exception($this->response->error['code'] . ': ' . $this->response->error['message']); } else { if (!in_array($this->response->code, array(200, 204))) { throw new Exception(json_decode($this->response->body)->{'errorCode'}); } } return $this->response->body; }
function set_search_results($search_entry) { $cc_key = "dj0yJmk9SlhmUUg0d2xZeElpJmQ9WVdrOWNtaERNM0pUTnpJbWNHbzlNVGM0TXpreE1ESTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD1lMQ--"; $cc_secret = "3dc05893bab0fc05cbcff4c10c3da27d1a21140d"; $url = "http://yboss.yahooapis.com/ysearch/web"; $args = array(); $args["q"] = $search_entry->input_user_query; /*echo $args["q"];*/ $args["format"] = "xml"; $args["count"] = TOTAL_SEARCH_NO; /*$consumer = new OAuthConsumer($cc_key, $cc_secret);*/ $request = OAuthRequest::from_consumer_and_token($this->consumer, NULL, "GET", $url, $args); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $this->consumer, NULL); $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args)); $ch = curl_init(); $headers = array($request->to_header()); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); $rsp = curl_exec($ch); $counter = 0; $results = new SimpleXmlElement($rsp); /*print_r ($results);*/ //copying the $results properties that is want into the array_of_results foreach ($results->web->results->result as $node) { $this->array_of_results[$counter]->description = $node->abstract; $this->array_of_results[$counter]->display_url = $node->dispurl; $this->array_of_results[$counter]->title = $node->title; $this->array_of_results[$counter]->url = $node->url; $counter++; } }
function QUERY_EXPANSION($tokens) { if ($_POST['Stop_Words'] == 'Stop_Words_On') { //removal of remaining stop words $tokens = STOP_WORD_REMOVAL($tokens); } $thesaurus_key = '6c8539cf26065c0e0121bb0f25c135b5'; $root_url = 'http://words.bighugelabs.com/api/2/' . $thesaurus_key; if ($_POST['Spelling_Corrections'] == 'Spelling_Corrections_On') { require "OAuth.php"; //run spell check on tokens first. If I find a suggestion I replace that word with the suggestion foreach ($tokens as $token_key => $word) { $cc_key = "dj0yJmk9RDlrYWFpSHF2cE05JmQ9WVdrOWJXdE1OVTluTnpBbWNHbzlPRGsyTlRnd09UWXkmcz1jb25zdW1lcnNlY3JldCZ4PTQy"; $cc_secret = "814c4600b92636821fdbb6491af3db280df1ce21"; $url = "http://yboss.yahooapis.com/ysearch/spelling"; $args = array(); $args["q"] = urlencode('' . $word . ''); $args["format"] = "json"; $yahoo_session = curl_init(); $consumer = new OAuthConsumer($cc_key, $cc_secret); $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $url, $args); $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL); $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args)); $headers = array($request->to_header()); curl_setopt($yahoo_session, CURLOPT_HTTPHEADER, $headers); curl_setopt($yahoo_session, CURLOPT_URL, $url); curl_setopt($yahoo_session, CURLOPT_RETURNTRANSFER, TRUE); $spelling_suggestion = curl_exec($yahoo_session); $spelling_suggestion = json_decode($spelling_suggestion); //if a spelling suggestion was returned, replace the word with the suggestion if ($spelling_suggestion->bossresponse->spelling->count == '1') { echo 'Corrected the word: ' . $word . ' -- to: ' . $spelling_suggestion->bossresponse->spelling->results[0]->suggestion . '<br>'; $word = $spelling_suggestion->bossresponse->spelling->results[0]->suggestion; } $tokens[$token_key] = $word; //update the tokens array } } if ($_POST['Synonyms'] == 'Synonyms_On') { foreach ($tokens as $word) { $request = $root_url . '/' . $word . '/json'; $thesaurus_session = curl_init($request); curl_setopt($thesaurus_session, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec($thesaurus_session); $data = json_decode($data); //can't add the first synonym as this is the word itself $synonym = $data->noun->syn[1]; //don't add empty synonym to tokens if ($synonym != NULL) { echo 'Synonym Added: ' . $synonym . '<br>'; //$tokens[] = 'OR'; $tokens[] = $synonym; } } } if ($_POST['Stemming'] == 'Stemming_On') { $tokens = STEMMING($tokens); } if ($_POST['Hyphen_Expansion'] == 'Hyphen_Expansion_On') { foreach ($tokens as $word) { //if a hyphen was found between two words if (preg_match('/[\\w]+[\\s]*\\-[\\s]*[\\w]+/', $word)) { echo 'Hyphen Expanded to:' . '<br>'; $temp = preg_split('/([\\w]+)[\\s]*\\-[\\s]*([\\w]+)/i', $word, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $tokens[] = $temp[0]; $tokens[] = $temp[0] . $temp[1]; $tokens[] = $temp[1]; echo $temp[0] . '<br>'; echo $temp[0] . $temp[1] . '<br>'; echo $temp[1] . '<br>'; } } } return $tokens; }
/** * builds the data one would send in a POST request */ public function to_postdata() { return OAuthUtil::build_http_query($this->parameters); }
/** * Get data by twitter api url * * @param string $url * @param array $parameters * @param string $format * @return mixed */ private function _get($url, $parameters = array(), $format = 'json') { // Check for curl extension if (!extension_loaded('curl')) { return false; } if (!$this->oauth_setup) { $this->oauth_setup = true; if (!$this->params->get('oauth_token', '') || !$this->params->get('oauth_token_secret', '')) { $this->connection = false; } elseif (false != ($this->connection = modRokTwittieHelper::getOauth($this->params))) { $this->connection->useragent = $this->useragent; $this->connection->connecttimeout = $this->connecttimeout; $this->connection->timeout = $this->timeout; // verify credentials $this->connection->get('account/verify_credentials'); if ($this->connection->http_code != 200) { $this->connection = false; } } } if ($this->connection) { $this->connection->format = $format; $result = $this->connection->get($url, $parameters); if ($this->connection->http_code != 200) { return false; } } else { $ci = curl_init(); curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ci, CURLOPT_RETURNTRANSFER, true); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ci, CURLOPT_HEADER, false); curl_setopt($ci, CURLOPT_URL, $this->host . $url . '.' . $format. '?' . OAuthUtil::build_http_query($parameters)); $result = curl_exec($ci); $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); curl_close ($ci); if ($http_code != 200) { return false; } if ($format == 'json') { $result = json_decode($result); } } return $result; }