Exemple #1
0
 function getSearcherValue($url, $searcher = "google")
 {
     $url = urlencode(preg_replace("#^http://#", "", $url));
     $searcherUrls = array('google' => 'http://www.google.com/search?hl=en&q=site%3A' . $url, 'googlebl' => 'http://www.google.com/search?hl=en&q=link%3A' . $url);
     $searcherPats = array('google' => "#</b> of (?:about )?<b>([\\d,]+)</b>#", 'googlebl' => "#</b> of (?:about )?<b>([\\d,]+)</b>#");
     if (!array_key_exists($searcher, $searcherUrls)) {
         $searcher = "google";
     }
     $sourceUrl = $searcherUrls[$searcher];
     $httpClient = new HttpClient();
     if ($this->extractionWay == 2) {
         $httpClient->additionalServerUrl = $this->additionalServerUrl;
     }
     $buff = $httpClient->getSiteContent($sourceUrl);
     if ($this->debug) {
         echo $buff;
     }
     if (!preg_match($searcherPats[$searcher], $buff, $m)) {
         $count = 0;
     } else {
         $count = str_replace(",", "", $m[1]);
         $count = intval($count);
     }
     return $count;
 }
 public function uploadContents($content)
 {
     if ($this->data['appkey'] === null) {
         throw new \InvalidArgumentException('appkey should not be null!');
     }
     if ($this->data['timestamp'] === null) {
         throw new \InvalidArgumentException('timestamp should not be null!');
     }
     if (!is_string($content)) {
         throw new \InvalidArgumentException('content should be a string!');
     }
     $post = array('appkey' => $this->data['appkey'], 'timestamp' => $this->data['timestamp'], 'content' => $content);
     $url = $this->host . $this->uploadPath;
     $postBody = json_encode($post);
     $sign = md5('POST' . $url . $postBody . $this->appMasterSecret);
     $url = $url . '?sign=' . $sign;
     $http = new HttpClient();
     $http->execute($url, $postBody);
     if ($http->httpCode === '0') {
         //time out
         throw new \UnexpectedValueException('Curl error number:' . $http->curlErrNo . ' , Curl error details:' . $http->curlErr . '\\r\\n');
     } elseif ($http->httpCode !== '200') {
         //we did send the notifition out and got a non-200 response
         throw new \UnexpectedValueException('http code:' . $http->httpCode . PHP_EOL . ' details:' . $http->result . '\\r\\n');
     }
     $returnData = json_decode($http->result, true);
     if ($returnData['ret'] === 'FAIL') {
         throw new \UnexpectedValueException('Failed to upload file, details:' . $http->result . '\\r\\n');
     } else {
         $this->data['file_id'] = $returnData['data']['file_id'];
     }
 }
Exemple #3
0
 /**
  * Handles the actual webhook, happens in two steps:
  *
  * - Retrieves the $webhook_id and $event_id
  *
  * - Uses the key and secret provided to fetch the event object and casts it to an array
  *
  * - Calls the callable function with the Event object
  */
 private function handleWebhook()
 {
     $identifier = $this->field('identifier');
     if ($identifier !== $this->identifier) {
         return;
     }
     $event_id = $this->field('event_id');
     $webhook_id = $this->field('webhook_id');
     if (!$event_id || !$webhook_id) {
         Log::info($this->patrol, 'Webhook ' . $this->identifier . ' has no event_id or webhook_id');
         return;
     }
     $httpClient = new HttpClient($this->patrol, 'GET', 'webhooks/' . $webhook_id . '/events/' . $event_id);
     $response = $httpClient->response();
     if (!$response) {
         Log::info($this->patrol, 'Retrieving webhook from ' . $httpClient->getUrl() . ' failed');
         return;
     }
     $data = $this->field($response, 'data');
     if (!$data) {
         Log::info($this->patrol, 'Event has invalid format to be processed: ' . print_r($response, true));
     }
     $callable = $this->callback;
     if (is_callable($callable)) {
         $callable($data);
     }
 }
Exemple #4
0
 function getMetaDataAction()
 {
     $httpClient = new HttpClient();
     $metaData = $httpClient->getMetaValues($this->request->url);
     $this->set($metaData);
     $this->viewClass = "JsonView";
 }
 public function __construct(HttpUrl $claimedId, HttpClient $httpClient)
 {
     $this->claimedId = $claimedId->makeComparable();
     if (!$claimedId->isValid()) {
         throw new OpenIdException('invalid claimed id');
     }
     $this->httpClient = $httpClient;
     $response = $httpClient->send(HttpRequest::create()->setHeaderVar('Accept', self::HEADER_ACCEPT)->setMethod(HttpMethod::get())->setUrl($claimedId));
     if ($response->getStatus()->getId() != 200) {
         throw new OpenIdException('can\'t fetch document');
     }
     $contentType = $response->getHeader('content-type');
     if (mb_stripos($contentType, self::HEADER_CONT_TYPE) !== false) {
         $this->parseXRDS($response->getBody());
     } elseif ($response->hasHeader(self::HEADER_XRDS_LOCATION)) {
         $this->loadXRDS($response->getHeader(self::HEADER_XRDS_LOCATION));
     } else {
         $this->parseHTML($response->getBody());
     }
     if (!$this->server || !$this->server->isValid()) {
         throw new OpenIdException('bad server');
     } else {
         $this->server->makeComparable();
     }
     if (!$this->realId) {
         $this->realId = $claimedId;
     } elseif (!$this->realId->isValid()) {
         throw new OpenIdException('bad delegate');
     } else {
         $this->realId->makeComparable();
     }
 }
 static function reverse($latitude, $longitude)
 {
     if (!$latitude || !$longitude) {
         throw new \Exception('no coords set');
     }
     $temp = TempStore::getInstance();
     $key = 'GeonamesClient//' . $latitude . '/' . $longitude;
     $data = $temp->get($key);
     if ($data) {
         return unserialize($data);
     }
     $url = 'http://ws.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude;
     $http = new HttpClient($url);
     $data = $http->getBody();
     $xml = simplexml_load_string($data);
     //d($xml);
     $res = new GeoLookupResult();
     $res->country_code = strval($xml->timezone->countryCode);
     $res->country_name = strval($xml->timezone->countryName);
     $res->timezone = strval($xml->timezone->timezoneId);
     $res->sunrise = strval($xml->timezone->sunrise);
     $res->sunset = strval($xml->timezone->sunset);
     $temp->set($key, serialize($res), '1h');
     return $res;
 }
Exemple #7
0
 /**
  * Verifies a recaptcha
  *
  * @param $priv_key private recaptcha key
  * @return true on success
  */
 public function verify()
 {
     $error = ErrorHandler::getInstance();
     $conf = RecaptchaConfig::getInstance();
     if (empty($_POST['recaptcha_challenge_field']) || empty($_POST['recaptcha_response_field'])) {
         $error->add('No captcha answer given.');
         return false;
     }
     if (!$conf->getPublicKey() || !$conf->getPrivateKey()) {
         die('ERROR - Get Recaptcha API key at http://recaptcha.net/api/getkey');
     }
     $params = array('privatekey' => $conf->getPrivateKey(), 'remoteip' => client_ip(), 'challenge' => $_POST['recaptcha_challenge_field'], 'response' => $_POST['recaptcha_response_field']);
     $http = new HttpClient($this->api_url_verify);
     $res = $http->post($params);
     $answers = explode("\n", $res);
     if (trim($answers[0]) == 'true') {
         return true;
     }
     switch ($answers[1]) {
         case 'incorrect-captcha-sol':
             $e = 'Incorrect captcha solution';
             break;
         default:
             $e = 'untranslated error: ' . $answers[1];
     }
     $error->add($e);
     return false;
 }
 public function core_call($serialized_request)
 {
     $client = new HttpClient($this->domain);
     $client->setCookies($this->cookies);
     $client->post($this->location . "json/", $serialized_request);
     return $client->getContent();
 }
Exemple #9
0
 function parse($raw)
 {
     // TODO XmlReader should not handle HTTP protocol details
     if (is_url($raw)) {
         $url = $raw;
         $h = new HttpClient($url);
         //            $h->setCacheTime('30m');
         $raw = $h->getBody();
         //            d( $h->getResponseHeaders() );
         if ($h->getStatus() == 404) {
             // not found
             return false;
         }
         if ($h->getStatus() == 302) {
             $redir = $h->getResponseHeader('location');
             // echo "REDIRECT: ".$redir."\n";
             $h = new HttpClient($redir);
             //XXX: reuse previous client?
             $h->setCacheTime('30m');
             $url = $redir;
             $raw = $h->getBody();
         }
         // prepend XML header if nonexistent
         if (strpos($raw, '<?xml ') === false) {
             $raw = '<?xml version="1.0"?>' . $raw;
         }
     }
     if (!$this->xml($raw)) {
         if (isset($url)) {
             throw new \Exception("Failed to parse XML from " . $url);
         }
         throw new \Exception("Failed to parse XML");
     }
 }
function beacon_send_message($channel, $data)
{
    $url = '/1.0.0/' . get_option('beacon_api_key') . '/channels/' . $channel;
    $client = new HttpClient('api.beaconpush.com');
    $client->extra_request_headers = array('X-Beacon-Secret-Key: ' . get_option('beacon_secret_key'));
    $client->post($url, json_encode($data));
}
function http_get_file($url)
{
    $httpClient = new HttpClient("epub.cnki.net");
    $httpClient->get($url);
    $content = $httpClient->getContent();
    return $content;
}
 protected function _remoteCall($method, $params = null)
 {
     $uri = $this->reportServer;
     $cache_id = md5($this->objectName . $uri . $method . serialize($params));
     $cacheSvc = Openbiz::getService(CACHE_SERVICE, 1);
     $cacheSvc->init($this->objectName, $this->cacheLifeTime);
     if (substr($uri, strlen($uri) - 1, 1) != '/') {
         $uri .= '/';
     }
     $uri .= "ws.php/udc/CollectService";
     if ($cacheSvc->test($cache_id) && (int) $this->cacheLifeTime > 0) {
         $resultSetArray = $cacheSvc->load($cache_id);
     } else {
         try {
             $argsJson = urlencode(json_encode($params));
             $query = array("method={$method}", "format=json", "argsJson={$argsJson}");
             $httpClient = new HttpClient('POST');
             foreach ($query as $q) {
                 $httpClient->addQuery($q);
             }
             $headerList = array();
             $out = $httpClient->fetchContents($uri, $headerList);
             $cats = json_decode($out, true);
             $resultSetArray = $cats['data'];
             $cacheSvc->save($resultSetArray, $cache_id);
         } catch (Exception $e) {
             $resultSetArray = array();
         }
     }
     return $resultSetArray;
 }
Exemple #13
0
 /** @return array of VcardAddress objects */
 static function parse($data)
 {
     if (is_url($data)) {
         $http = new HttpClient($data);
         $data = $http->getBody();
         //FIXME check http client return code for 404
         if (strpos($data, 'BEGIN:VCARD') === false) {
             throw new \Exception('VcardReader->parse FAIL: cant parse vcard from ' . $http->getUrl());
             return false;
         }
     }
     $res = array();
     do {
         $m1 = 'BEGIN:VCARD';
         $m2 = 'END:VCARD';
         $p1 = strpos($data, $m1);
         $p2 = strpos($data, $m2);
         if ($p1 === false || $p2 === false) {
             break;
         }
         $part = substr($data, $p1, $p2 - $p1 + strlen($m2));
         $res[] = self::parseVcard($part);
         $data = substr($data, $p2 + strlen($m2));
     } while ($data);
     return $res;
 }
Exemple #14
0
 /**
  * @dataProvider effectiveUrls
  */
 public function testEffectiveUrl($url, $expected, $params = array())
 {
     $http = new HttpClient();
     $http->get($url, $params);
     $this->assertEquals($expected, $http->getEffectiveUrl());
     $this->assertEquals($expected, $http->effectiveUrl);
 }
 protected function with($url, $data = '')
 {
     $date = date('r', time());
     $hash = md5($this->api_key . $url . $data . $date . $this->api_secret);
     $this->httpClient->setHttpHeaders(array('API-REQUEST-DATE' => $date, 'API-HMAC' => $hash));
     return $this->httpClient;
 }
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "post_to_server") {
         $file = base64_decode(AJXP_Utils::decodeSecureMagic($httpVars["file"]));
         $target = base64_decode($httpVars["parent_url"]) . "/plugins/editor.pixlr";
         $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file);
         $fData = array("tmp_name" => $tmp, "name" => urlencode(basename($file)), "type" => "image/jpg");
         $httpClient = new HttpClient("pixlr.com");
         //$httpClient->setDebug(true);
         $postData = array();
         $httpClient->setHandleRedirects(false);
         $params = array("referrer" => "AjaXplorer", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $target . "/fake_save_pixlr.php", "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($file)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source");
         $httpClient->postFile("/editor/", $params, "image", $fData);
         $loc = $httpClient->getHeader("location");
         header("Location:{$loc}");
     } else {
         if ($action == "retrieve_pixlr_image") {
             $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]);
             $url = $httpVars["new_url"];
             $urlParts = parse_url($url);
             $query = $urlParts["query"];
             $params = array();
             $parameters = parse_str($query, $params);
             $image = $params['image'];
             /*
             $type = $params['type'];
             $state = $params['state'];
             $filename = $params['title'];		
             */
             if (strpos($image, "pixlr.com") == 0) {
                 throw new AJXP_Exception("Invalid Referrer");
             }
             $headers = get_headers($image, 1);
             $content_type = explode("/", $headers['Content-Type']);
             if ($content_type[0] != "image") {
                 throw new AJXP_Exception("File Type");
             }
             $orig = fopen($image, "r");
             $target = fopen($destStreamURL . $file, "w");
             while (!feof($orig)) {
                 fwrite($target, fread($orig, 4096));
             }
             fclose($orig);
             fclose($target);
             header("Content-Type:text/plain");
             print $mess[115];
         }
     }
     return;
 }
Exemple #17
0
 /**
  * to config content data and send to target
  * @param array $data - content data in array
  *	(format like array(
  *		"first"=>array("value"=>"","color"=>""), 
  *		"remark"=>array("value"=>"","color"=>""))
  *	)
  * @return data received after posting
  */
 public function send($data)
 {
     $this->body['data'] = $data;
     $json = json_encode($this->body);
     $client = new HttpClient("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$this->access_token}");
     $client->setParameter($json);
     return $client->post();
 }
 function testJsonPost()
 {
     $http = new HttpClient('http://localhost/coredev_testserver/post_json.php');
     $http->setContentType('application/json');
     $http->setDebug(true);
     $res = $http->post(array('str' => 'abc 123'));
     $this->assertEquals($res, 'str=abc+123');
 }
 public static function getRate($from, $to)
 {
     $url = 'http://rate-exchange.appspot.com/currency?from=' . strtoupper($from) . '&to=' . strtoupper($to);
     $http = new HttpClient($url);
     $res = $http->getBody();
     $json = json_decode($res);
     return $json->rate;
 }
 public function message_put($proxy_at, $from, $body, $srv_addr, $srv_at, $mod_params)
 {
     $channelId = 1;
     $priority = 100;
     $text = $body;
     $url = 'http://botq.localhost/api/textMessage/' . $channelId . '/' . $priority . '/' . urlencode($text);
     $hc = new \HttpClient();
     $hc->request($url);
 }
Exemple #21
0
 public function send($content)
 {
     $data = array("touser" => $this->openid, "msgtype" => "text", "text" => array("content" => urlencode($content)));
     $data = urldecode(json_encode($data));
     $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$this->access_token}";
     $client = new HttpClient($url);
     $client->setParameter($data);
     return $client->post();
 }
Exemple #22
0
 /**
  * Set Google authentication credentials.
  * Must be done before trying to do any Google Data operations that
  * require authentication.
  * For example, viewing private data, or posting or deleting entries.
  *
  * @param string $email
  * @param string $password
  * @param string $service
  * @param \Zend\GData\HttpClient $client
  * @param string $source
  * @param string $loginToken The token identifier as provided by the server.
  * @param string $loginCaptcha The user's response to the CAPTCHA challenge.
  * @param string $accountType An optional string to identify whether the
  * account to be authenticated is a google or a hosted account. Defaults to
  * 'HOSTED_OR_GOOGLE'. See: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Request
  * @throws \Zend\GData\App\AuthException
  * @throws \Zend\GData\App\HttpException
  * @throws \Zend\GData\App\CaptchaRequiredException
  * @return \Zend\GData\HttpClient
  */
 public static function getHttpClient($email, $password, $service = 'xapi', HttpClient $client = null, $source = self::DEFAULT_SOURCE, $loginToken = null, $loginCaptcha = null, $loginUri = self::CLIENTLOGIN_URI, $accountType = 'HOSTED_OR_GOOGLE')
 {
     if (!($email && $password)) {
         throw new App\AuthException('Please set your Google credentials before trying to ' . 'authenticate');
     }
     if ($client == null) {
         $client = new HttpClient();
     }
     // Build the HTTP client for authentication
     $client->setUri($loginUri);
     $client->setMethod('POST');
     $useragent = $source . ' Zend_Framework_Gdata/' . \Zend\Version::VERSION;
     $client->setOptions(array('maxredirects' => 0, 'strictredirects' => true, 'useragent' => $useragent));
     $client->setEncType('multipart/form-data');
     $postParams = array('accountType' => $accountType, 'Email' => (string) $email, 'Passwd' => (string) $password, 'service' => (string) $service, 'source' => (string) $source);
     if ($loginToken || $loginCaptcha) {
         if ($loginToken && $loginCaptcha) {
             $postParams += array('logintoken' => (string) $loginToken, 'logincaptcha' => (string) $loginCaptcha);
         } else {
             throw new App\AuthException('Please provide both a token ID and a user\'s response ' . 'to the CAPTCHA challenge.');
         }
     }
     $client->setParameterPost($postParams);
     // Send the authentication request
     // For some reason Google's server causes an SSL error. We use the
     // output buffer to supress an error from being shown. Ugly - but works!
     ob_start();
     try {
         $response = $client->send();
     } catch (\Zend\Http\Client\Exception\ExceptionInterface $e) {
         throw new App\HttpException($e->getMessage(), $e);
     }
     ob_end_clean();
     // Parse Google's response
     $goog_resp = array();
     foreach (explode("\n", $response->getBody()) as $l) {
         $l = rtrim($l);
         if ($l) {
             list($key, $val) = explode('=', rtrim($l), 2);
             $goog_resp[$key] = $val;
         }
     }
     if ($response->getStatusCode() == 200) {
         $client->setClientLoginToken($goog_resp['Auth']);
         $useragent = $source . ' Zend_Framework_Gdata/' . \Zend\Version::VERSION;
         $client->setOptions(array('strictredirects' => true, 'useragent' => $useragent));
         return $client;
     } elseif ($response->getStatusCode() == 403) {
         // Check if the server asked for a CAPTCHA
         if (array_key_exists('Error', $goog_resp) && $goog_resp['Error'] == 'CaptchaRequired') {
             throw new App\CaptchaRequiredException($goog_resp['CaptchaToken'], $goog_resp['CaptchaUrl']);
         } else {
             throw new App\AuthException('Authentication with Google failed. Reason: ' . (isset($goog_resp['Error']) ? $goog_resp['Error'] : 'Unspecified.'));
         }
     }
 }
Exemple #23
0
 public static final function sendSms($path, $apikey, $encoded_text, $mobile, $tpl_id = '', $encoded_tpl_value = '')
 {
     $client = new HttpClient(self::HOST);
     $client->setDebug(false);
     if (!$client->post($path, array('apikey' => $apikey, 'text' => $encoded_text, 'mobile' => $mobile, 'tpl_id' => $tpl_id, 'tpl_value' => $encoded_tpl_value))) {
         return '-10000';
     } else {
         return self::__replyResult($client->getContent());
     }
 }
Exemple #24
0
 /**
  * @param Feed $feed
  */
 public function processFeed($feed)
 {
     $http = new \HttpClient();
     $body = $http->get($this->url);
     if ($body !== false) {
         $this->parseBody($body, $feed);
     } elseif ($this->showErrors) {
         $feed->addItem(['title' => $http->lastError, 'link' => $this->url]);
     }
 }
 /**
  * Just an helper to use HttPClient as default EastRdf_default_client)
  */
 public static function useIdentity($username = null, $password = null, $timeout = null)
 {
     $httpClient = \EasyRdf_Http::getDefaultHttpClient();
     // if current default http client does not provide setAuth use a new instance of HttpClient
     if (!($httpClient instanceof \Zend_Http_Client or $httpClient instanceof HttpClient)) {
         $httpClient = new HttpClient(null, array('maxredirects' => 5, 'useragent' => 'BOTK HttpClient', 'timeout' => ini_get('max_execution_time') || 30));
     }
     $httpClient->setAuth($username, $password);
     return \EasyRdf_Http::setDefaultHttpClient($httpClient);
 }
 /**
  * Adds static header(s) to the HTTP request headers
  *
  * @param HttpClient $request HTTP channel object.
  * 
  * @return \HTTP_Request2
  */
 public function handleRequest($request)
 {
     foreach ($this->_headers as $key => $value) {
         $headers = $request->getHeaders();
         if (!array_key_exists($key, $headers)) {
             $request->setHeader($key, $value);
         }
     }
     return $request;
 }
Exemple #27
0
 function sendMessage($msgInfo)
 {
     $clientt = new HttpClient(FEYIN_HOST, FEYIN_PORT);
     if (!$clientt->post('/api/sendMsg', $msgInfo)) {
         //提交失败
         return 'faild';
     } else {
         return $clientt->getContent();
     }
 }
Exemple #28
0
function apiPost($baseData, $url, $parameters, $private)
{
    $nonce = substr(md5(microtime()), 0, 6);
    $url = $baseData["path"] . $url;
    $msg = "{$url}:{$nonce}:{$private}";
    $hash = $nonce . ":" . hash_hmac("sha256", $msg, $parameters["auth_token"]);
    $client = new HttpClient($baseData["host"]);
    $parameters["auth_hash"] = $hash;
    $client->post($url, $parameters);
    return $client;
}
Exemple #29
0
 /**
  * {@inheritdoc}
  */
 public function valid()
 {
     if (!isset($this->result[$this->offset]) && $this->offset < $this->max) {
         ++$this->current;
         $url = preg_replace('/page=[0-9]+/', 'page=' . $this->current, $this->url);
         $result = $this->client->request($this->method, $url, $this->params);
         $this->result = array_merge($this->result, $result[$this->key]);
         return true;
     }
     return $this->offset < $this->max;
 }
Exemple #30
0
function testSvc($url, $query = null, $cookie = null)
{
    $httpClient = new HttpClient('POST');
    $httpClient->setCookie($cookie);
    foreach ($query as $q) {
        $httpClient->addQuery($q);
    }
    $headerList = array();
    $out = $httpClient->fetchContents($url, $headerList, false);
    return $out;
}