コード例 #1
0
ファイル: correios.php プロジェクト: n0n3br/SGD
 function endereco(&$model, $cep)
 {
     if (!$this->_validaCep($cep, '-')) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     // Requisição
     $HttpSocket = new HttpSocket();
     $uri = array('scheme' => 'http', 'host' => 'www.correios.com.br', 'port' => 80, 'path' => '/encomendas/prazo/prazo.cfm');
     $data = array('resposta' => 'paginaCorreios', 'servico' => CORREIOS_SEDEX, 'cepOrigem' => $cep, 'cepDestino' => $cep, 'peso' => 1, 'MaoPropria' => 'N', 'valorDeclarado' => 0, 'avisoRecebimento' => 'N', 'Altura' => '', 'Comprimento' => '', 'Diametro' => '', 'Formato' => 1, 'Largura' => '', 'embalagem' => 116600055, 'valorD' => '');
     $retornoCorreios = $HttpSocket->post($uri, $data);
     if ($HttpSocket->response['status']['code'] != 200) {
         return ERRO_CORREIOS_FALHA_COMUNICACAO;
     }
     // Convertendo para o encoding da aplicação. Isto só funciona se a extensão multibyte estiver ativa
     $encoding = Configure::read('App.encoding');
     if (function_exists('mb_convert_encoding') && $encoding != null && strcasecmp($encoding, 'iso-8859-1') != 0) {
         $retornoCorreios = mb_convert_encoding($retornoCorreios, $encoding, 'ISO-8859-1');
     }
     // Checar se o conteúdo está lá e reduzir o escopo de busca dos valores
     if (!preg_match('/\\<b\\>CEP:\\<\\/b\\>(.*)\\<b\\>Prazo de Entrega/', $retornoCorreios, $matches)) {
         return ERRO_CORREIOS_CONTEUDO_INVALIDO;
     }
     $escopoReduzido = $matches[1];
     // Logradouro
     preg_match('/\\<b\\>Endere&ccedil;o:\\<\\/b\\>\\s*\\<\\/td\\>\\s*\\<td[^\\>]*>([^\\<]*)\\</', $escopoReduzido, $matches);
     $logradouro = $matches[1];
     // Bairro
     preg_match('/\\<b\\>Bairro:\\<\\/b\\>\\s*\\<\\/td\\>\\s*\\<td[^\\>]*>([^\\<]*)\\</', $escopoReduzido, $matches);
     $bairro = $matches[1];
     // Cidade e Estado
     preg_match('/\\<b\\>Cidade\\/UF:\\<\\/b\\>\\s*\\<\\/td\\>\\s*\\<td[^\\>]*>([^\\<]*)\\</', $escopoReduzido, $matches);
     list($cidade, $uf) = explode('/', $matches[1]);
     return compact('logradouro', 'bairro', 'cidade', 'uf');
 }
コード例 #2
0
 function admin_callback()
 {
     $endpoint = $this->request->query['openid_op_endpoint'];
     $query = array();
     $keys = array('openid.ns', 'openid.mode', 'openid.op_endpoint', 'openid.response_nonce', 'openid.return_to', 'openid.assoc_handle', 'openid.signed', 'openid.sig', 'openid.identity', 'openid.claimed_id', 'openid.ns.ext1', 'openid.ext1.mode', 'openid.ext1.type.firstname', 'openid.ext1.value.firstname', 'openid.ext1.type.email', 'openid.ext1.value.email', 'openid.ext1.type.lastname', 'openid.ext1.value.lastname');
     foreach ($keys as $key) {
         $underscoreKey = str_replace('.', '_', $key);
         if (isset($this->params['url'][$underscoreKey])) {
             $query[$key] = $this->params['url'][$underscoreKey];
         }
     }
     $query['openid.mode'] = 'check_authentication';
     $Http = new HttpSocket();
     $response = $Http->get($this->request->query['openid_op_endpoint'] . '?' . http_build_query($query));
     if (strpos($response, 'is_valid:true') === false) {
         return $this->redirect($this->Auth->loginAction);
     }
     $url = $this->params['url'];
     if (isset($url['openid_mode']) && $url['openid_mode'] == 'cancel') {
         return $this->redirect($this->Auth->redirect());
     }
     $user = array('id' => $url['openid_ext1_value_email'], 'name' => $url['openid_ext1_value_firstname'] . ' ' . $url['openid_ext1_value_lastname'], 'email' => $url['openid_ext1_value_email']);
     $this->__callback($user);
     $this->Session->write(AuthComponent::$sessionKey, $user);
     $this->set('redirect', $this->Auth->redirect());
 }
コード例 #3
0
 protected function _request($method, $params = array(), $request = array())
 {
     // preparing request
     $query = Hash::merge(array('method' => $method, 'format' => 'json'), $params);
     $request = Hash::merge($this->_request, array('uri' => array('query' => $query)), $request);
     // Read cached GET results
     if ($request['method'] == 'GET') {
         $cacheKey = $this->_generateCacheKey();
         $results = Cache::read($cacheKey);
         if ($results !== false) {
             return $results;
         }
     }
     // createding http socket object with auth configuration
     $HttpSocket = new HttpSocket();
     $HttpSocket->configAuth('OauthLib.Oauth', array('Consumer' => array('consumer_token' => $this->_config['key'], 'consumer_secret' => $this->_config['secret']), 'Token' => array('token' => $this->_config['token'], 'secret' => $this->_config['secret2'])));
     // issuing request
     $response = $HttpSocket->request($request);
     // olny valid response is going to be parsed
     if ($response->code != 200) {
         if (Configure::read('debugApis')) {
             debug($request);
             debug($response->body);
         }
         return false;
     }
     // parsing response
     $results = $this->_parseResponse($response);
     // cache and return results
     if ($request['method'] == 'GET') {
         Cache::write($cacheKey, $results);
     }
     return $results;
 }
コード例 #4
0
ファイル: update_controller.php プロジェクト: rchavik/20Couch
 function download()
 {
     $result = array('success' => true, 'error' => null);
     $home = Configure::read('20Couch.home');
     App::import('Core', array('HttpSocket', 'File'));
     $Http = new HttpSocket();
     $Setting = ClassRegistry::init('Setting');
     $url = sprintf('%s/registrations/direct/%s/' . Configure::read('Update.file'), $home, $Setting->find('value', 'registration_key'));
     $latest = $Http->get($url);
     if ($latest === false || $Http->response['status']['code'] != 200) {
         if ($Http->response['status']['code'] == 401) {
             $msg = 'Invalid registration key';
         } else {
             $msg = 'Unable to retrieve latest file from ' . $home;
         }
         $this->log($url);
         $this->log($Http->response);
         $result = array('success' => false, 'error' => $msg);
         $this->set('result', $result);
         return;
     }
     $File = new File(TMP . Configure::read('Update.file'), false);
     $File->write($latest);
     $File->close();
     $latestChecksum = trim($Http->get($home . '/checksum'));
     $yourChecksum = sha1_file(TMP . Configure::read('Update.file'));
     if ($yourChecksum != $latestChecksum) {
         $result = array('success' => false, 'error' => 'Checksum doesn\'t match (' . $yourChecksum . ' vs ' . $latestChecksum . ')');
         $this->set('result', $result);
         return;
     }
     $result = array('success' => true, 'error' => null);
     $this->set('result', $result);
 }
コード例 #5
0
 function index()
 {
     App::import('Core', 'HttpSocket');
     $HttpSocketPr = new HttpSocket();
     // 		$results = $HttpSocketPr->get('https://www.google.com.mx/search', 'q=php');
     $HttpSocketPr->get('http://anonymouse.org/cgi-bin/anon-www.cgi/http://187.141.67.234/projections/users/login');
     // 		returns html for Google's search results for the query "cakephp"
     if (!empty($HttpSocketPr->response['cookies']['CAKEPHP']['path']) and $HttpSocketPr->response['cookies']['CAKEPHP']['path'] === '/projections') {
         debug($HttpSocketPr->response['cookies']);
         var_dump('Projections External site is OK');
     } else {
         var_dump('Projections External site is Down');
     }
     $HttpSocketGst = new HttpSocket();
     $HttpSocketGst->get('http://anonymouse.org/cgi-bin/anon-www.cgi/http://187.141.67.234/gst/users/login');
     if (!empty($HttpSocketGst->response['cookies']['CAKEPHP']['path']) and $HttpSocketGst->response['cookies']['CAKEPHP']['path'] === '/gst') {
         debug($HttpSocketGst->response['cookies']);
         var_dump('Gst External site is OK');
     } else {
         var_dump('Gst External site is Down');
     }
     // 		$HttpSocketFm = new HttpSocket();
     // 		$HttpSocketFm->get('http://localhost/smb/class/filemanager/filemanager.php');
     //
     // 		$this->set('fm',$HttpSocketFm->response['body']);
     $this->FieldView->recursive = 0;
     $this->set('fieldViews', $this->paginate());
 }
コード例 #6
0
 function sendSMS($phone, $message)
 {
     App::uses('HttpSocket', 'Network/Http');
     $HttpSocket = new HttpSocket();
     $results = $HttpSocket->post('http://mobileautomatedsystems.com/index.php?option=com_spc&comm=spc_api', array('username' => 'noibilism', 'password' => 'noheeb', 'sender' => 'NASFAT', 'recipient' => $phone, 'message' => $message));
     return $results;
 }
コード例 #7
0
 public function getStatus($code)
 {
     App::import('Core', 'HttpSocket');
     $HttpSocket = new HttpSocket(array('timeout' => $this->timeout));
     $response = $HttpSocket->get($this->pgURI . $code, "email={$__config['email']}&token={$__config['token']}");
     return $this->__status($response);
 }
コード例 #8
0
ファイル: http_socket_lib.php プロジェクト: robksawyer/tools
 /**
  * fetches url with curl if available
  * fallbacks: cake and php
  * note: expects url with json encoded content
  * @access private
  **/
 public function fetch($url, $agent = 'cakephp http socket lib')
 {
     if ($this->use['curl'] && function_exists('curl_init')) {
         $this->debug = 'curl';
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_USERAGENT, $agent);
         $response = curl_exec($ch);
         $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         curl_close($ch);
         if ($status != '200') {
             $this->setError('Error ' . $status);
             return false;
         }
         return $response;
     } elseif ($this->use['cake'] && App::import('Core', 'HttpSocket')) {
         $this->debug = 'cake';
         $HttpSocket = new HttpSocket(array('timeout' => 5));
         $response = $HttpSocket->get($url);
         if (empty($response)) {
             //TODO: status 200?
             return false;
         }
         return $response;
     } elseif ($this->use['php'] || true) {
         $this->debug = 'php';
         $response = file_get_contents($url, 'r');
         //TODO: status 200?
         if (empty($response)) {
             return false;
         }
         return $response;
     }
 }
コード例 #9
0
ファイル: CensorshipModeTest.php プロジェクト: k1low/postman
 /**
  * test_Censorship
  *
  */
 public function test_Censorship()
 {
     $hash = $this->hash;
     $to = 'to+' . $hash . '@mailback.me';
     Configure::write('Postman.censorship.mode', true);
     Configure::write('Postman.censorship.config', array('transport' => 'Smtp', 'from' => array('form@mailback.me' => 'from'), 'to' => $to, 'host' => 'mail.mailback.me', 'port' => 25, 'timeout' => 30, 'log' => false, 'charset' => 'utf-8', 'headerCharset' => 'utf-8'));
     $message = 'Censored';
     $expect = $message;
     $this->email->subject('メールタイトル');
     $this->email->send($expect);
     sleep(15);
     $url = 'http://mailback.me/to/' . $hash . '.body';
     App::uses('HttpSocket', 'Network/Http');
     $HttpSocket = new HttpSocket();
     $results = $HttpSocket->get($url, array());
     $body = trim(str_replace(array("\r\n", "\n", ' '), '', $results->body));
     $message = trim(str_replace(array("\r\n", "\n", ' '), '', $message));
     $this->assertIdentical($results->code, '200');
     $this->assertIdentical($body, $message);
     // CC
     $ccUrl = 'http://mailback.me/to/unknown-cc-' . $hash . '.body';
     $results = $HttpSocket->get($ccUrl, array());
     $this->assertContains('404', $results->body);
     // BCC
     $bccUrl = 'http://mailback.me/to/unknown-bcc-' . $hash . '.body';
     $results = $HttpSocket->get($bccUrl, array());
     $this->assertContains('404', $results->body);
 }
コード例 #10
0
 function sendSMS($phone, $message)
 {
     App::uses('HttpSocket', 'Network/Http');
     $HttpSocket = new HttpSocket();
     $results = $HttpSocket->post('http://www.mobileautomatedsystems.com/components/com_spc/smsapi.php', array('username' => 'noibilism', 'password' => 'noheeb', 'sender' => 'ZEO Ifo', 'recipient' => $phone, 'message' => $message));
     return $results;
 }
コード例 #11
0
 function main()
 {
     App::import('HttpSocket');
     $site = isset($this->args['0']) ? $this->args['0'] : null;
     while (empty($site)) {
         $site = $this->in("What site would you like to crawl?");
         if (!empty($site)) {
             break;
         }
         $this->out("Try again.");
     }
     $Socket = new HttpSocket();
     $links = array();
     $start = 0;
     $num = 100;
     do {
         $r = $Socket->get('http://www.google.com/search', array('hl' => 'en', 'as_sitesearch' => $site, 'num' => $num, 'filter' => 0, 'start' => $start));
         if (!preg_match_all('/href="([^"]+)" class="?l"?/is', $r, $matches)) {
             die($this->out('Error: Could not parse google results'));
         }
         $links = array_merge($links, $matches[1]);
         $start = $start + $num;
     } while (count($matches[1]) >= $num);
     $links = array_unique($links);
     $this->out(sprintf('-> Found %d links on google:', count($links)));
     $this->hr();
     $this->out(join("\n", $links));
 }
コード例 #12
0
ファイル: MetatagShell.php プロジェクト: luizjam/docs
 /**
  * Reads all the files in a directory and process them to extract the description terms
  *
  * @return void
  */
 public function main()
 {
     $url = 'http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction';
     $dir = $this->in('Please input the full path to the documentation folder (including the language directory)');
     if (!is_dir($dir) && !is_file($dir . DS . 'index.rst')) {
         throw new Exception('Invalid directory, please input the full path to one of the language directories for the docs repo');
     }
     $files = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)), '/\\.rst$/');
     foreach ($files as $item) {
         if ($item->isDir()) {
             continue;
         }
         $request = new HttpSocket();
         $content = file($item->getRealPath());
         $data = array('appid' => 'rrLaMQjV34HtIOsgPxf597DEP9KFoUzWybkmb4USJMPA89aCMWjjPFlnF3lD5ys-', 'query' => 'cakephp ' . $content[0], 'output' => 'json', 'context' => file_get_contents($item->getRealPath()));
         $result = $request->post('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction', $data);
         $keywords = json_decode($result->body);
         $keywords = $keywords->ResultSet->Result;
         $meta = $this->generateMeta($keywords, str_replace("\n", '', $content[0]));
         $fh = fopen($item->getRealPath(), 'a');
         fwrite($fh, "\n\n" . $meta);
         fclose($fh);
         $this->out('<success>Processed</success> ' . $item->getRealPath());
     }
 }
コード例 #13
0
 /**
  * Sends out email via Mandrill
  *
  * @return array Return the Mandrill
  */
 public function send(CakeEmail $email)
 {
     // CakeEmail
     $this->_cakeEmail = $email;
     $this->_config = $this->_cakeEmail->config();
     $this->_headers = $this->_cakeEmail->getHeaders(array('from', 'to', 'cc', 'bcc', 'replyTo', 'subject'));
     // Setup connection
     $this->__mandrillConnection =& new HttpSocket();
     // Build message
     $message = $this->__buildMessage();
     // Build request
     $request = $this->__buildRequest();
     if (isset($this->_config['mandrillTemplate']) && !empty($this->_config['mandrillTemplate'])) {
         $message_send_uri = $this->_config['uri'] . "messages/send-template.json";
     } else {
         $message_send_uri = $this->_config['uri'] . "messages/send.json";
     }
     // Send message
     try {
         $returnMandrill = $this->__mandrillConnection->post($message_send_uri, json_encode($message), $request);
         // Return data
         $result = json_decode($returnMandrill, true);
         $headers = $this->_headersToString($this->_headers);
         return array_merge(array('Mandrill' => $result), array('headers' => $headers, 'message' => $message));
     } catch (Exception $e) {
         return false;
     }
 }
 public function wpp_hash($method = null, $nvp = null)
 {
     $HttpSocket = new HttpSocket();
     $required_nvp = 'METHOD=' . $method;
     $required_nvp .= '&VERSION=' . Configure::read('Paypal.version');
     $required_nvp .= '&USER=' . Configure::read('Paypal.username');
     $required_nvp .= '&PWD=' . Configure::read('Paypal.password');
     $required_nvp .= '&SIGNATURE=' . Configure::read('Paypal.signature');
     debug($required_nvp);
     die;
     $http_responder = $HttpSocket->post(Configure::read('Paypal.endpoint'), $required_nvp . $nvp);
     if (!$http_responder) {
         throw new BadRequestException($method . 'failed: ' . $http_responder['reasonPhrase']);
     }
     $responder = explode('&', $http_responder);
     $parsed_response = array();
     foreach ($responder as $response) {
         $response_array = explode('=', $response);
         if (count($response_array) >= 1) {
             $parsed_response[$response_array[0]] = urldecode($response_array[1]);
         }
     }
     if (count($parsed_response) < 1 || !array_key_exists('ACK', $parsed_response)) {
         throw new BadRequestException('Invalid HTTP Response for POST request (' . $required_nvp . $nvp . ') to ' . Configure::read('Paypal.endpoint'));
     }
     return $parsed_response;
 }
コード例 #15
0
 protected function _request($path, $request = array())
 {
     // preparing request
     $request = Hash::merge($this->_request, $request);
     $request['uri']['path'] .= $path;
     if (isset($request['uri']['query'])) {
         $request['uri']['query'] = array_merge(array('access_token' => $this->_config['token']), $request['uri']['query']);
     } else {
         $request['uri']['query'] = array('access_token' => $this->_config['token']);
     }
     // createding http socket object for later use
     $HttpSocket = new HttpSocket(array('ssl_verify_host' => false));
     // issuing request
     $response = $HttpSocket->request($request);
     // olny valid response is going to be parsed
     if (substr($response->code, 0, 1) != 2) {
         if (Configure::read('debugApis')) {
             debug($request);
             debug($response->body);
             die;
         }
         return false;
     }
     // parsing response
     $results = $this->_parseResponse($response);
     if (isset($results['data'])) {
         return $results['data'];
     }
     return $results;
 }
コード例 #16
0
ファイル: ProxyController.php プロジェクト: hungnt88/5stars-1
 public function index() {
     $HttpSocket = new HttpSocket ();
     
     if (sizeof ( $this->params ['pass'] [0] ) != 1) {
         throw new InvalidArgumentException ();
     }
     if (! empty ( $_SERVER ['PHP_AUTH_USER'] ) && ! empty ( $_SERVER ['PHP_AUTH_PW'] )) {
         $HttpSocket->configAuth ( 'Basic', $_SERVER ['PHP_AUTH_USER'], $_SERVER ['PHP_AUTH_PW'] );
     } elseif (isset ( $this->CurrentUser )) {
         $HttpSocket->configAuth ( 'Basic', $this->Session->read ( 'Auth.User.Login' ), $this->Session->read ( 'Auth.User.Password' ) );
     }
     
     $this->response->type ( 'json' );
     
     $request = array (
         'method' => env ( 'REQUEST_METHOD' ),
         'body' => $this->request->data,
         'uri' => array (
             'scheme' => Configure::read ( 'Api.scheme' ),
             'host' => Configure::read ( 'Api.host' ),
             'port' => 80,
             'path' => Configure::read ( 'Api.path' ) . $this->params ['pass'] [0],
             'query' => $this->params->query 
         ) 
     );
     
     $response = $HttpSocket->request ( $request );
     $this->response->statusCode ( $response->code );
     $this->response->body ( $response->body );
     return $this->response;
 }
コード例 #17
0
 public function decrypt()
 {
     while (empty($md5)) {
         $md5 = $this->in('Ingrese el Hash a buscar');
     }
     $HttpSocket = new HttpSocket();
     $md5 = trim($md5);
     if (strlen($md5) !== 32) {
         return $this->out('Hash invalido');
     }
     $matches = array();
     $html = $HttpSocket->get($this->_url);
     $pattern = '/<input type="hidden" name="a" value="(.*)">/Uis';
     preg_match_all($pattern, $html->body, $matches, PREG_SET_ORDER);
     if (empty($matches[0][1])) {
         return $this->out('El servidor no responde');
     }
     $a = $matches[0][1];
     $rest = $this->postDataViaCurl($HttpSocket, $md5, $a);
     do {
         $this->out('..');
         sleep(1);
     } while ($rest->code === null);
     $returnArray = array();
     $pattern2 = '/Found (.*) <b>(.*)<\\/b><\\/span>/Uis';
     preg_match_all($pattern2, $rest, $returnArray, PREG_SET_ORDER);
     if (empty($returnArray[0][2])) {
         return $this->out('El servidor no responde');
     }
     $nt = trim(strip_tags($returnArray[0][2]));
     if (empty($nt)) {
         return false;
     }
     $this->out('Contraseña desencriptada: <info>' . $nt . '</info>');
 }
コード例 #18
0
 protected function _request($path, $request = array())
 {
     // preparing request
     $request = Hash::merge($this->_request, $request);
     $request['uri']['path'] .= $path;
     // Read cached GET results
     if ($request['method'] == 'GET') {
         $cacheKey = $this->_generateCacheKey();
         $results = Cache::read($cacheKey);
         if ($results !== false) {
             return $results;
         }
     }
     // createding http socket object for later use
     $HttpSocket = new HttpSocket();
     // issuing request
     $response = $HttpSocket->request($request);
     // olny valid response is going to be parsed
     if (substr($response->code, 0, 1) != 2) {
         if (Configure::read('debugApis')) {
             debug($request);
             debug($response->body);
         }
         return false;
     }
     // parsing response
     $results = $this->_parseResponse($response);
     // cache and return results
     if ($request['method'] == 'GET') {
         Cache::write($cacheKey, $results);
     }
     return $results;
 }
コード例 #19
0
 public function maestro($key = null)
 {
     if ($key != 'secret') {
         die('sorry');
     }
     App::uses('HttpSocket', 'Network/Http');
     $httpSocket = new HttpSocket();
     $yesterday = date("Y-m-d H:i:s", strtotime("-1 day"));
     // print_r($yesterday);
     // die;
     $products = $this->Product->find('all', array('recursive' => -1, 'conditions' => array('Product.user_id' => 11, 'Product.active' => 1, 'Product.stock_updated <' => $yesterday), 'order' => 'RAND()', 'limit' => 20));
     foreach ($products as $product) {
         //sleep(1);
         $response = $httpSocket->get('https://www.maestrolico.com/api/checkstockstatus.asp?distributorid=117&productid=' . $product['Product']['vendor_sku']);
         echo '<br /><hr><br />';
         echo $product['Product']['name'] . ' - ' . $product['Product']['vendor_sku'];
         echo '<br /><br />';
         debug($response['body']);
         $update = explode('|', $response['body']);
         debug($update);
         debug(date('H:i:s'));
         $data['Product']['id'] = $product['Product']['id'];
         $data['Product']['stock'] = $update[1];
         $data['Product']['stock_updated'] = date('Y-m-d H:i:s');
         $this->Product->save($data, false);
     }
     die('end');
 }
コード例 #20
0
 /**
  * _get()
  *
  * @param mixed $url
  * @param mixed $params
  * @return string
  */
 protected function _get($url, $params)
 {
     $Socket = new HttpSocket();
     $response = $Socket->get($url, $params);
     //$file = TMP . Inflector::slug($url) . '.json';
     //file_put_contents($file, $response->body);
     return isset($response->body) ? $response->body : '';
 }
コード例 #21
0
ファイル: campfire.php プロジェクト: joebeeson/campfire
 /**
  * Performs an API request to Basecamp
  * @param string $url
  * @param string $method
  * @param array $options
  * @return string
  * @access protected
  */
 protected function _request($url, $method = 'GET', $options = array())
 {
     // Extract our settings and create our HttpSocket
     extract($this->settings);
     $socket = new HttpSocket();
     // Build, execute and return the response
     return $socket->request(am(array('method' => $method, 'uri' => array('scheme' => 'http', 'host' => $account . '.' . 'campfirenow.com', 'path' => $url, 'user' => $token, 'pass' => 'X'), 'auth' => array('method' => 'Basic', 'user' => $token, 'pass' => 'X'), 'header' => array('User-Agent' => 'CakePHP CampfireComponent')), $options));
 }
コード例 #22
0
 public function testPostViaSocket()
 {
     $url = 'https://www.sofort.com/payment/notAvailable';
     $SofortLibHttpSocket = new HttpSocket($url);
     $SofortLibHttpSocket->post('test');
     $httpCode = $SofortLibHttpSocket->getHttpCode();
     $this->assertTrue($httpCode['code'] === 404);
     $this->assertTrue($httpCode['message'] === '<errors><error><code>0404</code><message>URL not found ' . $url . '</message></error></errors>');
 }
コード例 #23
0
 /**
  * Method of API
  *
  * @return HttpSocketResponse
  */
 public function api()
 {
     $args = func_get_args();
     $url = implode('/', array(self::URL, 'api', array_shift($args))) . ".json";
     do {
         $data = array_merge($this->settings, array_shift($args));
     } while ($args);
     return $this->http->post($url, $data);
 }
コード例 #24
0
ファイル: scvngr_source.php プロジェクト: hfitzgerald/bww
 /**
  * Issues request and returns response as an array decoded according to the
  * response's content type if the response code is 200, else triggers the
  * $model->onError() method (if it exists) and finally returns false.
  *
  * @param mixed $model Either a CakePHP model with a request property, or an
  * array in the format expected by HttpSocket::request or a string which is a
  * URI.
  * @return mixed The response or false
  */
 public function request(&$model)
 {
     if (is_object($model)) {
         $request = $model->request;
     } elseif (is_array($model)) {
         $request = $model;
     } elseif (is_string($model)) {
         $request = array('uri' => $model);
     }
     // Remove unwanted elements from request array
     $request = array_intersect_key($request, $this->Http->request);
     // Issues request
     $response = $this->Http->request($request);
     // Get content type header
     $contentType = $this->Http->response['header']['Content-Type'];
     // Extract content type from content type header
     if (preg_match('/^([a-z0-9\\/\\+]+);\\s*charset=([a-z0-9\\-]+)/i', $contentType, $matches)) {
         $contentType = $matches[1];
         $charset = $matches[2];
     }
     // Decode response according to content type
     switch ($contentType) {
         case 'application/xml':
         case 'application/atom+xml':
         case 'application/rss+xml':
             // If making multiple requests that return xml, I found that using the
             // same Xml object with Xml::load() to load new responses did not work,
             // consequently it is necessary to create a whole new instance of the
             // Xml class. This can use a lot of memory so we have to manually
             // garbage collect the Xml object when we've finished with it, i.e. got
             // it to transform the xml string response into a php array.
             App::import('Core', 'Xml');
             $Xml = new Xml($response);
             $response = $Xml->toArray(false);
             // Send false to get separate elements
             $Xml->__destruct();
             $Xml = null;
             unset($Xml);
             break;
         case 'application/json':
         case 'text/javascript':
             $response = json_decode($response, true);
             break;
     }
     if (is_object($model)) {
         $model->response = $response;
     }
     // Check response status code for success or failure
     if (substr($this->Http->response['status']['code'], 0, 1) != 2) {
         if (is_object($model) && method_exists($model, 'onError')) {
             $model->onError();
         }
         return false;
     }
     return $response;
 }
コード例 #25
0
ファイル: ClientController.php プロジェクト: trice4/BlogTest
 public function request_delete($id)
 {
     $link = Router::url('/', true) . 'rest_posts/' . $id . '.json';
     $data = null;
     $httpSocket = new HttpSocket();
     $response = $httpSocket->delete($link, $data);
     $this->set('response_code', $response->code);
     $this->set('response_body', $response->body);
     $this->render('/Client/request_response');
 }
コード例 #26
0
ファイル: twitter.php プロジェクト: shin1x1/findTwitter
 /**
  * paginate
  *
  * @param  mixed $conditions
  * @param  mixed $fields
  * @param  mixed $order
  * @param  integer $limit
  * @param  integer $page
  * @param  integer $recursive
  * @param  array $extract
  * @return array
  */
 public function paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra)
 {
     $HttpSocket = new HttpSocket();
     $query = array('q' => Set::extract('q', $conditions), 'page' => $page, 'rpp' => $limit, 'lang' => Set::extract('lang', $conditions));
     $ret = $HttpSocket->get(self::API_SEARCH, $query);
     if ($ret) {
         $Xml = new Xml($ret);
         return $Xml->toArray();
     }
     return array();
 }
コード例 #27
0
 /**
  * Makes an HTTP request using HttpSocket.
  *
  * @param string $url The URL to make the request to
  * @param array $params The parameters to use for the POST body
  * @param CurlHandler $ch Initialized curl handle. (Hopefully this is never used...)
  *
  * @return string The response text
  */
 protected function makeRequest($url, $params, $ch = null)
 {
     App::import('Core', 'HttpSocket');
     $HttpSocket = new HttpSocket();
     $result = $HttpSocket->post($url, $params);
     if ($result === false || $HttpSocket->response['status']['code'] != '200') {
         $execption = new FacebookApiException(array('error_code' => $HttpSocket->response['status']['code'], 'error' => array('message' => $HttpSocket->response['status']['reason-phrase'], 'type' => 'HttpSocketException')));
         throw $execption;
     }
     return $result;
 }
コード例 #28
0
ファイル: peer.php プロジェクト: busytoby/gitrbug
 function greet($peer_address = null, $peer_port = null, $data = array())
 {
     if (!$peer_address || !$peer_port) {
         return true;
     }
     App::import('Core', 'HttpSocket');
     $HttpSocket = new HttpSocket();
     $req = array('method' => 'POST', 'uri' => array('scheme' => 'http', 'host' => $peer_address, 'port' => $peer_port, 'path' => '/peers/hello'), 'header' => array('User-Agent' => 'Gitrbug/0.2'), 'body' => array('data' => $data));
     $res = $HttpSocket->request($req);
     return json_decode($res, true);
 }
コード例 #29
0
 public function request_delete($id)
 {
     // remotely post the information to the server
     $link = "http://" . $_SERVER['HTTP_HOST'] . $this->webroot . 'rest_tasks/' . $id . '.json';
     $data = null;
     $httpSocket = new HttpSocket();
     $response = $httpSocket->delete($link, $data);
     $this->set('response_code', $response->code);
     $this->set('response_body', $response->body);
     $this->render('/Client/request_response');
 }
コード例 #30
0
ファイル: Feedback.php プロジェクト: port80labs/Boxmeup
 /**
  * Creates a github issue with title and body in configured project.
  *
  * @param string $title
  * @param string $body
  * @throws BadRequestException
  */
 public function githubIssue($type, $title, $body)
 {
     $socket = new HttpSocket();
     $url = static::GITHUB_URL . '/repos/' . Configure::read('Feedback.github.project') . '/issues';
     $data = json_encode(array('title' => $title, 'body' => $body, 'labels' => array_merge(array($type), Configure::read('Feedback.github.labels'))));
     $result = $socket->post($url, $data, array('header' => array('Authorization' => 'token ' . Configure::read('Feedback.github.auth_token'))));
     if (!in_array((int) $result->code, array(200, 201, 202, 203, 204, 205, 206))) {
         throw new BadRequestException('Error entering feedback.');
     }
     $body = json_decode($result->body, true);
     return $body['html_url'];
 }