Esempio n. 1
1
 /**
  * @return array
  */
 public function getResults($offset, $itemCountPerPage)
 {
     $query = $this->createSearchQuery($offset, $itemCountPerPage);
     $adapter = new Http\Client\Adapter\Curl();
     $adapter->setOptions(array('curloptions' => array(CURLOPT_SSL_VERIFYPEER => false)));
     $client = new Http\Client();
     $client->setAdapter($adapter);
     $client->setMethod('GET');
     $client->setUri($this->getOptions()->getSearchEndpoint() . $query);
     $response = $client->send();
     if (!$response->isSuccess()) {
         throw new Exception\RuntimeException("Invalid response received from CloudSearch.\n" . $response->getContent());
     }
     $results = Json::decode($response->getContent(), Json::TYPE_ARRAY);
     $this->count = $results['hits']['found'];
     if (0 == $this->count) {
         return array();
     }
     if ($this->getOptions()->getReturnIdResults()) {
         $results = $this->extractResultsToIdArray($results);
     }
     foreach ($this->getConverters() as $converter) {
         $results = $converter->convert($results);
     }
     return $results;
 }
Esempio n. 2
0
 function setPostRut($ruts)
 {
     foreach ($ruts as $rut) {
         $busqueda[] = explode('-', $rut[0]);
     }
     echo '<pre>';
     print_r($busqueda);
     echo '</pre>';
     $client = new Client('http://reca.poderjudicial.cl/', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true));
     $headers = $client->getRequest()->getHeaders();
     $cookies = new Zend\Http\Cookies($headers);
     $client->setMethod('GET');
     $response = $client->send();
     $client->setUri('http://reca.poderjudicial.cl/RECAWEB/AtPublicoViewAccion.do?tipoMenuATP=1');
     $cookies->addCookiesFromResponse($response, $client->getUri());
     $response = $client->send();
     $client->setUri("http://reca.poderjudicial.cl/RECAWEB/AtPublicoDAction.do");
     foreach ($busqueda as $rut) {
         $parametros = array('actionViewBusqueda' => '2', 'FLG_Busqueda' => '2', 'FLG_User_Valid' => '0', 'TIP_Lengueta' => 'tdDos', 'COD_Competencia' => 'C', 'tribunal_aux' => '-1', 'username_aux' => '', 'password_aux' => '', 'aux_codlibro' => '', 'aux_rolinterno' => '', 'aux_eracausa' => '', 'aux_codcorte' => '', 'RUT_Cod_Competencia' => 'C', 'RUT_Rut' => $rut[0], 'RUT_Rut_Db' => $rut[1], 'RIT_Cod_Competencia' => '0', 'RIT_Tip_Causa' => '0', 'RIT_Rol_Interno' => '', 'RIT_Era_Causa' => '', 'corte_Cod_Tribunal' => '-1', 'corte_Cod_Libro' => '0', 'corte_Rol_Interno' => '', 'corte_Era_Causa' => '', 'OPC_Cod_Corte' => '-1', 'OPC_Cod_Tribunal' => '-1', 'username' => '', 'password' => '');
         $client->setParameterPost($parametros);
         echo '<pre>';
         print_r($parametros);
         echo '</pre>';
         $response = $client->setMethod('POST')->send();
         $data = $response->getContent();
         echo '<pre>';
         print_r($response->getContent());
         echo '</pre>';
         die;
         $rut = $rut[0] . '-' . $rut[1];
         $dom = new Query($data);
         $resultados = $dom->execute('#divRecursos tr');
         $rols = $this->busquedaRut($resultados, $rut);
     }
 }
Esempio n. 3
0
 /**
  * Fetch Links
  *
  * Fetches a set of links corresponding to an OpenURL
  *
  * @param string $openURL openURL (url-encoded)
  *
  * @return string         raw XML returned by resolver
  */
 public function fetchLinks($openURL)
 {
     // Make the call to SFX and load results
     $url = $this->baseUrl . '?sfx.response_type=multi_obj_detailed_xml&svc.fulltext=yes&' . $openURL;
     $feed = $this->httpClient->setUri($url)->send()->getBody();
     return $feed;
 }
 /**
  * Sets request handler
  *
  * @param \Zend\Http\Client $handler
  * @return RemoteCompiler
  */
 public function setRequestHandler($handler)
 {
     $this->requestHandler = $handler;
     $this->requestHandler->setUri($this->url)->setMethod($this->method);
     $this->requestHandler->getUri()->setPort($this->port);
     return $this;
 }
Esempio n. 5
0
 /**
  * @param ProgressAdapter|null $progressAdapter
  */
 public function updateAddressFormats(ProgressAdapter $progressAdapter = null)
 {
     $localeDataUri = $this->options->getLocaleDataUri();
     $dataPath = $this->options->getDataPath();
     $locales = json_decode($this->httpClient->setUri($localeDataUri)->send()->getContent());
     foreach (scandir($dataPath) as $file) {
         if (fnmatch('*.json', $file)) {
             unlink($dataPath . '/' . $file);
         }
     }
     $countryCodes = isset($locales->countries) ? explode('~', $locales->countries) : [];
     $countryCodes[] = 'ZZ';
     if ($progressAdapter !== null) {
         $progressBar = new ProgressBar($progressAdapter, 0, count($countryCodes));
     }
     foreach ($countryCodes as $countryCode) {
         file_put_contents($dataPath . '/' . $countryCode . '.json', $this->httpClient->setUri($localeDataUri . '/' . $countryCode)->send()->getContent());
         if (isset($progressBar)) {
             $progressBar->next();
         }
     }
     if (isset($progressBar)) {
         $progressBar->finish();
     }
     // We clearly don't want the "ZZ" in the array!
     array_pop($countryCodes);
     $writer = new PhpArrayWriter();
     $writer->setUseBracketArraySyntax(true);
     $writer->toFile($this->options->getCountryCodesPath(), $countryCodes, false);
 }
Esempio n. 6
0
 /**
  * Fetch Links
  *
  * Fetches a set of links corresponding to an OpenURL
  *
  * @param string $openURL openURL (url-encoded)
  *
  * @return string         raw XML returned by resolver
  */
 public function fetchLinks($openURL)
 {
     // Make the call to SerialsSolutions and load results
     $url = $this->baseUrl . (substr($this->baseUrl, -1) == '/' ? '' : '/') . 'openurlxml?version=1.0&' . $openURL;
     $feed = $this->httpClient->setUri($url)->send()->getBody();
     return $feed;
 }
Esempio n. 7
0
 public function __construct($config)
 {
     if (!isset($config['yql_base_url'])) {
         throw new \InvalidArgumentException('Missing yql_base_url in config');
     }
     $this->client = new Client();
     $this->client->setUri($config['yql_base_url']);
     $this->client->setOptions(array('maxredirects' => 0, 'timeout' => 10));
 }
Esempio n. 8
0
 /**
  * {@inheritDoc}
  */
 public function getContent($url)
 {
     try {
         $response = $this->client->setUri($url)->send();
         $content = $response->isSuccess() ? $response->getBody() : null;
     } catch (\Exception $e) {
         $content = null;
     }
     return $content;
 }
Esempio n. 9
0
 /**
  * Call ja.is service and convert address to lat and lng
  *
  * @param string $address
  * @return object
  */
 public function request($address)
 {
     $response = $this->client->setUri("http://ja.is/kort/leit")->setMethod('GET')->setParameterGet(['q' => $address])->send();
     if ($response->getStatusCode() == 200) {
         $json = json_decode($response->getBody());
         return isset($json->items[0]->coordinates) ? (object) ['lat' => (double) $json->items[0]->coordinates->lat, 'lng' => (double) $json->items[0]->coordinates->lon] : (object) ['lat' => null, 'lng' => null];
     } else {
         return (object) ['lat' => null, 'lng' => null];
     }
 }
 /**
  * {@inheritDoc}
  */
 public function get($uri, array $headers = [])
 {
     $this->client->resetParameters();
     $this->client->setMethod('GET');
     $this->client->setHeaders(new Headers());
     $this->client->setUri($uri);
     if (!empty($headers)) {
         $this->injectHeaders($headers);
     }
     $response = $this->client->send();
     return new Response($response->getStatusCode(), $response->getBody(), $this->prepareResponseHeaders($response->getHeaders()));
 }
Esempio n. 11
0
 /**
  * Fetch an image from either a URL or the cache (as appropriate).
  *
  * @param string $url URL to fetch
  *
  * @return Response
  */
 public function fetch($url)
 {
     $file = $this->getCacheFile($url);
     $cacheAllowed = $this->onWhitelist($url);
     if (!$cacheAllowed || !($response = $this->fetchCache($file))) {
         $response = $this->client->setUri($url)->send();
         if ($cacheAllowed) {
             $this->setCache($file, $response);
         }
     }
     return $response;
 }
Esempio n. 12
0
 public static function query($api, $command, $options = null)
 {
     // Validate configuration
     if (!self::getApiKey()) {
         throw new \Exception('Echonest has not been configured');
     }
     $http = new Client();
     $http->setUri(self::$source . $api . '/' . $command);
     $http->setOptions(array('sslverifypeer' => false));
     $http->setMethod('GET');
     $format = 'json';
     if (is_array($options)) {
         $http->setUri(self::$source . $api . '/' . $command);
         $options['api_key'] = self::getApiKey();
         if (!isset($options['format'])) {
             $options['format'] = $format;
         } else {
             $format = $options['format'];
         }
         // Build query manually as $http->setParameterGet builds arrays properly:
         // echonest api is not standard :/
         // We need ?bucket=audio_summary&bucket=artist_discovery NOT ?bucket[0]=audio_summary&bucket[1]=artist_discovery
         //strip array indexes
         $http_query = preg_replace('/%5B[0-9]+%5D/simU', '', http_build_query($options));
         $http->setUri(self::$source . $api . '/' . $command . '?' . $http_query);
     } else {
         #options as a query string
         if (!$options) {
             throw new \Exception("The options must be an array or a non empty string");
         }
         if (!strpos($options, 'api_key')) {
             $options .= '&api_key=' . self::getApiKey();
         }
         #find format in query string
         preg_match('/format=([^&]+)&/', $options, $matches);
         if (is_array($matches)) {
             $format = $matches[1] ? $matches[1] : 'json';
         }
         $http->setUri(self::$source . $api . '/' . $command . '?' . $options);
     }
     $response = $http->send();
     #output response according to format
     if ($format == 'xml') {
         return simplexml_load_string($response->getBody());
     } else {
         return Json::decode($response->getBody());
     }
 }
Esempio n. 13
0
 public function pesquisaCep($strCEP)
 {
     $httpClient = new Client();
     $httpClient->setUri('http://webservice.kinghost.net/web_cep.php')->setParameterGet(array('auth' => $this->auth, 'formato' => 'json', 'cep' => $strCEP));
     $response = (object) json_decode($httpClient->send()->getBody(), true);
     return array('uf' => $response->uf, 'cidade' => $response->cidade, 'bairro' => $response->bairro, 'logradouro' => $response->logradouro, 'status' => $response->resultado ? true : false, 'message' => !$response->resultado ? 'CEP não encontrado' : '');
 }
 /**
  * @param MessageInterface|Message $message
  * @return mixed|void
  * @throws RuntimeException
  */
 public function send(MessageInterface $message)
 {
     $config = $this->getSenderOptions();
     $serviceURL = "http://letsads.com/api";
     $body = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><request></request>');
     $auth = $body->addChild('auth');
     $auth->addChild('login', $config->getUsername());
     $auth->addChild('password', $config->getPassword());
     $messageXML = $body->addChild('message');
     $messageXML->addChild('from', $config->getSender());
     $messageXML->addChild('text', $message->getMessage());
     $messageXML->addChild('recipient', $message->getRecipient());
     $client = new Client();
     $client->setMethod(Request::METHOD_POST);
     $client->setUri($serviceURL);
     $client->setRawBody($body->asXML());
     $client->setOptions(['sslverifypeer' => false, 'sslallowselfsigned' => true]);
     try {
         $response = $client->send();
     } catch (Client\Exception\RuntimeException $e) {
         throw new RuntimeException("Failed to send sms", null, $e);
     }
     try {
         $responseXML = new \SimpleXMLElement($response->getBody());
     } catch (\Exception $e) {
         throw new RuntimeException("Cannot parse response", null, $e);
     }
     if ($responseXML->name === 'error') {
         throw new RuntimeException("LetsAds return error (" . $responseXML->description . ')');
     }
 }
 /**
  * @return CasResult
  */
 public function validate()
 {
     try {
         $uri = $this->createValidateUri();
     } catch (Adapter\Exception\InvalidArgumentException $e) {
         return new CasResult(CasResult::FAILURE, '', array($e->getMessage()));
     }
     $this->httpClient->resetParameters();
     $this->httpClient->setUri($uri);
     try {
         $response = $this->httpClient->send();
     } catch (Http\Exception\RuntimeException $e) {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array($e->getMessage()));
     }
     if (!$response->isSuccess()) {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array('HTTP response did not indicate success.'), $response->getBody());
     }
     $body = $response->getBody();
     $explodedResponse = explode("\n", $body);
     if (count($explodedResponse) < 2) {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array('Got an invalid CAS 1.0 response.'), $body);
     }
     $status = $explodedResponse[0];
     $identity = $explodedResponse[1];
     if ($status !== 'yes') {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array('Authentication failed.'), $body);
     }
     return new CasResult(CasResult::SUCCESS, $identity, array(), $body);
 }
Esempio n. 16
0
 /**
  * Load image from URL, store in cache if requested, display if possible.
  *
  * @param string $url   URL to load image from
  * @param string $cache Boolean -- should we store in local cache?
  *
  * @return bool         True if image loaded, false on failure.
  */
 protected function processImageURL($url, $cache = true)
 {
     // Attempt to pull down the image:
     $result = $this->client->setUri($url)->send();
     if (!$result->isSuccess()) {
         $this->debug("Failed to retrieve image from " + $url);
         return false;
     }
     $image = $result->getBody();
     if ('' == $image) {
         return false;
     }
     // Figure out file paths -- $tempFile will be used to store the
     // image for analysis.  $finalFile will be used for long-term storage if
     // $cache is true or for temporary display purposes if $cache is false.
     $tempFile = str_replace('.jpg', uniqid(), $this->localFile);
     $finalFile = $cache ? $this->localFile : $tempFile . '.jpg';
     // Write image data to disk:
     if (!@file_put_contents($tempFile, $image)) {
         throw new \Exception("Unable to write to image directory.");
     }
     // Move temporary file to final location:
     if (!$this->validateAndMoveTempFile($image, $tempFile, $finalFile)) {
         return false;
     }
     // Display the image:
     $this->contentType = 'image/jpeg';
     $this->image = file_get_contents($finalFile);
     // If we don't want to cache the image, delete it now that we're done.
     if (!$cache) {
         @unlink($finalFile);
     }
     return true;
 }
Esempio n. 17
0
 /**
  * Make an API call
  *
  * @param string $method GET or POST
  * @param array  $params Parameters to send
  *
  * @return \SimpleXMLElement
  */
 protected function call($method = 'GET', $params = null)
 {
     if ($params) {
         $query = [];
         foreach ($params as $function => $value) {
             if (is_array($value)) {
                 foreach ($value as $additional) {
                     $additional = urlencode($additional);
                     $query[] = "{$function}={$additional}";
                 }
             } else {
                 $value = urlencode($value);
                 $query[] = "{$function}={$value}";
             }
         }
         $queryString = implode('&', $query);
     }
     $dbs = explode(',', $this->dbs);
     $dblist = '';
     foreach ($dbs as $db) {
         $dblist .= "&db=" . $db;
     }
     $this->debug('Connect: ' . print_r($this->base . '?' . $queryString . $dblist, true));
     // Send Request
     $this->client->resetParameters();
     $this->client->setUri($this->base . '?' . $queryString . $dblist);
     $result = $this->client->setMethod($method)->send();
     $body = $result->getBody();
     $xml = simplexml_load_string($body);
     $this->debug(print_r($xml, true));
     return $body;
 }
Esempio n. 18
0
 /**
  * This method is responsible for obtaining an image URL based on a name.
  *
  * @param string $imageName The image name to look up
  *
  * @return mixed            URL on success, false on failure
  */
 protected function getWikipediaImageURL($imageName)
 {
     $url = "http://{$this->lang}.wikipedia.org/w/api.php" . '?prop=imageinfo&action=query&iiprop=url&iiurlwidth=150&format=php' . '&titles=Image:' . urlencode($imageName);
     try {
         $result = $this->client->setUri($url)->setMethod('GET')->send();
     } catch (\Exception $e) {
         return false;
     }
     if (!$result->isSuccess()) {
         return false;
     }
     if ($response = $result->getBody()) {
         if ($imageinfo = unserialize($response)) {
             if (isset($imageinfo['query']['pages']['-1']['imageinfo'][0]['url'])) {
                 $imageUrl = $imageinfo['query']['pages']['-1']['imageinfo'][0]['url'];
             }
             // Hack for wikipedia api, just in case we couldn't find it
             //   above look for a http url inside the response.
             if (!isset($imageUrl)) {
                 preg_match('/\\"http:\\/\\/(.*)\\"/', $response, $matches);
                 if (isset($matches[1])) {
                     $imageUrl = 'http://' . substr($matches[1], 0, strpos($matches[1], '"'));
                 }
             }
         }
     }
     return isset($imageUrl) ? $imageUrl : false;
 }
Esempio n. 19
0
 /**
  * Call MetaLib X-server
  *
  * @param string $operation X-Server operation
  * @param array  $params    URL Parameters
  *
  * @return mixed simpleXMLElement
  * @throws \Exception
  */
 protected function call($operation, $params)
 {
     $this->debug("Call: {$this->host}: {$operation}: " . var_export($params, true));
     // Declare UTF-8 encoding so that SimpleXML won't encode characters.
     $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><x_server_request/>');
     $op = $xml->addChild($operation);
     $this->paramsToXml($op, $params);
     $this->client->resetParameters();
     $this->client->setUri($this->host);
     $this->client->setParameterPost(['xml' => $xml->asXML()]);
     $result = $this->client->setMethod('POST')->send();
     if (!$result->isSuccess()) {
         throw new \Exception($result->getBody());
     }
     $xml = $result->getBody();
     // Remove invalid XML fields (these were encountered in record Ppro853_304965
     // from FIN05707)
     $xml = preg_replace('/<controlfield tag="   ">.*?<\\/controlfield>/', '', $xml);
     if ($xml = simplexml_load_string($xml)) {
         $errors = $xml->xpath('//local_error | //global_error');
         if (!empty($errors)) {
             if ($errors[0]->error_code == 6026) {
                 throw new \Exception('Search timed out');
             }
             throw new \Exception($errors[0]->asXML());
         }
         $result = $xml;
     }
     return $result;
 }
Esempio n. 20
0
 public function indexAction()
 {
     $client = new HttpClient();
     $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
     $method = $this->params()->fromQuery('method', 'get');
     $client->setUri('http://api-rest/san-restful');
     switch ($method) {
         case 'get':
             $id = $this->params()->fromQuery('id');
             $client->setMethod('GET');
             $client->setParameterGET(array('id' => $id));
             break;
         case 'get-list':
             $client->setMethod('GET');
             break;
         case 'create':
             $client->setMethod('POST');
             $client->setParameterPOST(array('name' => 'samsonasik'));
             break;
         case 'update':
             $data = array('name' => 'ikhsan');
             $adapter = $client->getAdapter();
             $adapter->connect('localhost', 80);
             $uri = $client->getUri() . '?id=1';
             // send with PUT Method, with $data parameter
             $adapter->write('PUT', new \Zend\Uri\Uri($uri), 1.1, array(), http_build_query($data));
             $responsecurl = $adapter->read();
             list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
             $response = $this->getResponse();
             $response->getHeaders()->addHeaderLine('content-type', 'text/html; charset=utf-8');
             $response->setContent($content);
             return $response;
         case 'delete':
             $adapter = $client->getAdapter();
             $adapter->connect('localhost', 80);
             $uri = $client->getUri() . '?id=1';
             //send parameter id = 1
             // send with DELETE Method
             $adapter->write('DELETE', new \Zend\Uri\Uri($uri), 1.1, array());
             $responsecurl = $adapter->read();
             list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
             $response = $this->getResponse();
             $response->getHeaders()->addHeaderLine('content-type', 'text/html; charset=utf-8');
             $response->setContent($content);
             return $response;
     }
     //if get/get-list/create
     $response = $client->send();
     if (!$response->isSuccess()) {
         // report failure
         $message = $response->getStatusCode() . ': ' . $response->getReasonPhrase();
         $response = $this->getResponse();
         $response->setContent($message);
         return $response;
     }
     $body = $response->getBody();
     $response = $this->getResponse();
     $response->setContent($body);
     return $response;
 }
 /**
  * Make a remote call to freegeoip.net to detect country of current customer session and store it into session
  *
  * @return $this
  */
 public function saveVisitorData($observer)
 {
     $clientIP = $this->_request->getClientIp();
     $httpClient = new Client();
     $clientIP = $this->getRandomeIp($clientIP);
     $uri = self::URL_GEO_IP_SITE . $clientIP;
     $httpClient->setUri($uri);
     $httpClient->setOptions(array('timeout' => 30));
     try {
         $response = JsonDecoder::decode($httpClient->send()->getBody());
         $this->_customerSession->setVisitorData($response);
         //save to database
         $currenttime = date('Y-m-d H:i:s');
         $model = $this->_objectManager->create('Bluecom\\Freegeoip\\Model\\Visitor');
         $model->setData('visitor_ip', $response->ip);
         $model->setData('country_code', $response->country_code);
         $model->setData('country_name', $response->country_name);
         $model->setData('region_code', $response->region_code);
         $model->setData('region_name', $response->region_name);
         $model->setData('city', $response->city);
         $model->setData('zip_code', $response->zip_code);
         $model->setData('latitude', $response->latitude);
         $model->setData('longitude', $response->longitude);
         $model->setData('metro_code', $response->metro_code);
         $model->setData('browser', $_SERVER['HTTP_USER_AGENT']);
         $model->setData('os', php_uname());
         $model->setData('created', $currenttime);
         $model->save();
     } catch (\Exception $e) {
         $this->_logger->critical($e);
     }
     return $this;
 }
 /**
  *
  * @param string $uri
  * @return \Zend\Http\Client
  */
 protected function getHttpClient($uri)
 {
     $client = new Client();
     $client->setUri($uri);
     $client->setOptions(['maxredirects' => 5, 'timeout' => 30])->setHeaders(['Accept-encoding' => 'gzip,deflate', 'X-Powered-By: OClient']);
     return $client;
 }
Esempio n. 23
0
 public function citation()
 {
     parent::results();
     $style = $this->request->getParam("style", false, "mla");
     $items = array();
     $results = $this->response->get("results");
     // header("Content-type: application/json");
     $x = 1;
     foreach ($results->getRecords() as $result) {
         $id = "ITEM={$x}";
         $record = $result->getXerxesRecord()->toCSL();
         $record["id"] = $id;
         $items[$id] = $record;
         $x++;
     }
     $json = json_encode(array("items" => $items));
     // header("Content-type: application/json"); echo $json; exit;
     $url = "http://127.0.0.1:8085?responseformat=html&style={$style}";
     $client = new Client();
     $client->setUri($url);
     $client->setHeaders("Content-type: application/json");
     $client->setHeaders("Expect: nothing");
     $client->setRawData($json)->setEncType('application/json');
     $response = $client->request('POST')->getBody();
     echo $response;
     exit;
 }
 /**
  * @dataProvider providerHellCookies()
  */
 public function testZendClient($url)
 {
     $client = new Zend_Http_Client();
     $client->setUri($url);
     //$response = $client->request();
     $this->markTestIncomplete('This test has not been implemented yet.');
 }
Esempio n. 25
0
 /**
  * Fetch Links
  *
  * Fetches a set of links corresponding to an OpenURL
  *
  * @param string $openURL openURL (url-encoded)
  *
  * @return string         raw XML returned by resolver
  */
 public function fetchLinks($openURL)
 {
     // Unfortunately the EZB-API only allows OpenURL V0.1 and
     // breaks when sending a non expected parameter (like an ISBN).
     // So we do have to 'downgrade' the OpenURL-String from V1.0 to V0.1
     // and exclude all parameters that are not compliant with the EZB.
     // Parse OpenURL into associative array:
     $tmp = explode('&', $openURL);
     $parsed = [];
     foreach ($tmp as $current) {
         $tmp2 = explode('=', $current, 2);
         $parsed[$tmp2[0]] = $tmp2[1];
     }
     // Downgrade 1.0 to 0.1
     if ($parsed['ctx_ver'] == 'Z39.88-2004') {
         $openURL = $this->downgradeOpenUrl($parsed);
     }
     // make the request IP-based to allow automatic
     // indication on institution level
     $openURL .= '&pid=client_ip%3D' . $_SERVER['REMOTE_ADDR'];
     // Make the call to the EZB and load results
     $url = $this->baseUrl . '?' . $openURL;
     $feed = $this->httpClient->setUri($url)->send()->getBody();
     return $feed;
 }
Esempio n. 26
0
File: OVH.php Progetto: pontifex/sms
 /**
  * @param Struct\SMS $item
  * @return Client
  */
 protected function makeClient(Struct\SMS $item)
 {
     $client = new Client();
     $client->setUri($this->prepareUrl($item));
     $client->setMethod('GET');
     return $client;
 }
Esempio n. 27
0
 /**
  * Submit REST Request
  *
  * @param string $method  HTTP Method to use: GET or POST
  * @param array  $params  An array of parameters for the request
  * @param bool   $process Should we convert the MARCXML?
  *
  * @return string|SimpleXMLElement The response from the XServer
  */
 protected function call($method = 'GET', $params = null, $process = true)
 {
     if ($params) {
         $query = ['version=' . $this->sruVersion];
         foreach ($params as $function => $value) {
             if (is_array($value)) {
                 foreach ($value as $additional) {
                     $additional = urlencode($additional);
                     $query[] = "{$function}={$additional}";
                 }
             } else {
                 $value = urlencode($value);
                 $query[] = "{$function}={$value}";
             }
         }
         $queryString = implode('&', $query);
     }
     $this->debug('Connect: ' . print_r($this->host . '?' . $queryString, true));
     // Send Request
     $this->client->resetParameters();
     $this->client->setUri($this->host . '?' . $queryString);
     $result = $this->client->setMethod($method)->send();
     $this->checkForHttpError($result);
     // Return processed or unprocessed response, as appropriate:
     return $process ? $this->process($result->getBody()) : $result->getBody();
 }
Esempio n. 28
0
 function PlanJSONManager($action, $url, $requestjson, $uid)
 {
     $request = new Request();
     $request->getHeaders()->addHeaders(array('Content-Type' => 'application/json; charset=UTF-8'));
     //$url="";
     try {
         $request->setUri($url);
         $request->setMethod($action);
         $client = new Client();
         if ($action == 'PUT' || $action == 'POST') {
             $client->setUri($url);
             $client->setMethod($action);
             $client->setRawBody($requestjson);
             $client->setEncType('application/json');
             $response = $client->send();
             return $response;
         } else {
             $response = $client->dispatch($request);
             //var_dump(json_decode($response->getBody(),true));
             return $response;
         }
     } catch (\Exception $e) {
         $e->getTrace();
     }
     return null;
 }
Esempio n. 29
0
 /**
  * @return Model\File[]
  * @throws \Zend_Http_Client_Exception
  */
 private function _upload()
 {
     $this->_client->setUri(implode('/', [self::getConfig()['uri'], 'file/upload']));
     $this->_client->setMethod('POST');
     $filesInfo = json_decode($this->_client->send()->getBody(), true);
     return $this->_convertFilesInfoToObject($filesInfo);
 }
Esempio n. 30
0
 /**
  * Get a read-stream for a file
  *
  * @param $path
  * @return array|bool
  */
 public function readStream($path)
 {
     $headers = ['User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'], 'custom' => 'cust'];
     $stream = \GuzzleHttp\Stream\Stream::factory('contents...');
     $client = new \GuzzleHttp\Client(['headers' => $headers]);
     $resource = fopen('a.gif', 'r');
     $request = $client->put($this->api_url . 'upload', ['body' => $resource]);
     prn($client, $request);
     echo $request->getBody();
     exit;
     $location = $this->applyPathPrefix($path);
     $this->client->setMethod('PUT');
     $this->client->setUri($this->api_url . 'upload');
     $this->client->setParameterPost(array_merge($this->auth_param, ['location' => $location]));
     //        $this->client
     //            //->setHeaders(['path: /usr/local....'])
     //            ->setFileUpload('todo.txt','r')
     //            ->setRawData(fopen('todo.txt','r'));
     $fp = fopen('todo.txt', "r");
     $curl = $this->client->getAdapter();
     $curl->setCurlOption(CURLOPT_PUT, 1)->setCurlOption(CURLOPT_RETURNTRANSFER, 1)->setCurlOption(CURLOPT_INFILE, $fp)->setCurlOption(CURLOPT_INFILESIZE, filesize('todo.txt'));
     //  prn($curl->setOutputStream($fp));
     $response = $this->client->send();
     prn($response->getContent(), json_decode($response->getContent()));
     exit;
 }