public function updateProductsAction()
 {
     $user = Auth::user();
     $config = Config::get('providers.' . $user->provider);
     $client = new \Guzzle\Http\Client();
     $headers = $config['headers'];
     array_walk($headers, function (&$value, $key) use($user) {
         $value = str_replace('{token}', $user->access_token, $value);
     });
     $request = $client->get(str_replace('{blog_id}', $user->blog_id, $config['mediaUri']));
     $request->setHeaders($headers);
     $request->getHeaders()->toArray();
     $response = $request->send();
     $images = $response->json()['media'];
     $products = [];
     foreach ($images as $image) {
         if (!($product = Product::where('image_id', '=', $image['id'])->first())) {
             $product = new Product();
             $product->image_id = $image['id'];
             $product->image = $image['link'];
             $user->products()->save($product);
             $products[] = $product;
         }
     }
     return Redirect::route('products');
 }
 private function updateAddon(ActiveRow $addon)
 {
     $this->writeln('Updating: ' . $addon->name);
     $github = $this->normalizeGithubUrl($addon->repository);
     if ($github) {
         $guzzle = new \Guzzle\Http\Client();
         try {
             $guzzle->get($github)->send();
             $this->db->table('addons_resources')->insert(array('addonId' => $addon->id, 'type' => 'github', 'resource' => $github));
         } catch (\Guzzle\Http\Exception\RequestException $e) {
             $this->writeln((string) $e);
         }
     }
     if ($addon->type === 'composer') {
         $version = $addon->related('versions')->order('id', 'DESC')->fetch();
         $composerData = Json::decode($version->composerJson);
         $packagist = $this->generatePackagistUrl($composerData->name);
         $guzzle = new \Guzzle\Http\Client();
         try {
             $guzzle->get($packagist . '.json')->send();
             $this->db->table('addons_resources')->insert(array('addonId' => $addon->id, 'type' => 'packagist', 'resource' => $packagist));
         } catch (\Guzzle\Http\Exception\RequestException $e) {
             $this->writeln((string) $e);
         }
     }
     if ($addon->demo) {
         $guzzle = new \Guzzle\Http\Client();
         try {
             $guzzle->get($addon->demo)->send();
             $this->db->table('addons_resources')->insert(array('addonId' => $addon->id, 'type' => 'demo', 'resource' => $addon->demo));
         } catch (\Guzzle\Http\Exception\RequestException $e) {
             $this->writeln((string) $e);
         }
     }
 }
示例#3
0
 public function get($options)
 {
     $url = $options['url'];
     $limit = array_key_exists('limit', $options) ? NumberHelper::makeNumeric($options['limit']) : null;
     $offset = array_key_exists('offset', $options) ? NumberHelper::makeNumeric($options['offset']) : 0;
     // Check to see if the response is cached
     $cachedResponse = craft()->fileCache->get($url);
     if ($cachedResponse) {
         return $cachedResponse;
     }
     try {
         $client = new \Guzzle\Http\Client();
         $request = $client->get($url);
         $response = $request->send();
         if (!$response->isSuccessful()) {
             return;
         }
         $items = $response->json();
         // Cache the response
         craft()->fileCache->set($url, $items);
         // Apply the limit and offset
         $items = array_slice($items, $offset, $limit);
         return $items;
     } catch (\Exception $e) {
         return;
     }
 }
 /**
  * @inheritDoc ITask::runStep()
  *
  * @param int $step
  *
  * @return bool
  */
 public function runStep($step)
 {
     // NOTE: Perhaps much of this should be moved into a service
     $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build();
     // Make the client
     $client = new \Guzzle\Http\Client();
     // Set the Accept header
     $client->setDefaultOption('headers/Accept', '*/*');
     // Loop the paths in this step
     foreach ($this->_paths[$step] as $path) {
         // Make the url, stripping 'site:' from the path if it exists
         $newPath = preg_replace('/site:/', '', $path, 1);
         $url = UrlHelper::getSiteUrl($newPath);
         // Create the GET request
         $request = $client->get($url);
         // Add it to the batch
         $batch->add($request);
     }
     // Flush the queue and retrieve the flushed items
     $requests = $batch->flush();
     // Log any exceptions
     foreach ($batch->getExceptions() as $e) {
         Craft::log('CacheMonster: an exception occurred: ' . $e->getMessage(), LogLevel::Error);
     }
     // Clear any exceptions
     $batch->clearExceptions();
     return true;
 }
 /**
  * 
  * @return \Guzzle\Http\Message\Request $request
  */
 public function getBaseRequest()
 {
     if (is_null($this->baseRequest)) {
         $client = new \Guzzle\Http\Client();
         $this->baseRequest = $client->get();
     }
     return $this->baseRequest;
 }
 /**
  * 
  * @return \Guzzle\Http\Message\Request $request
  */
 public function getBaseRequest()
 {
     if (is_null($this->baseRequest)) {
         $client = new \Guzzle\Http\Client();
         $client->addSubscriber(new \Guzzle\Plugin\History\HistoryPlugin());
         $this->baseRequest = $client->get();
     }
     return $this->baseRequest;
 }
示例#7
0
 private function getGroupInfoFromGerrit(Git_RemoteServer_GerritServer $server, $group_name)
 {
     try {
         $response = $this->sendRequest($server, $this->guzzle_client->get($this->getGerritURL($server, '/groups/' . urlencode($group_name)), $this->getRequestOptions()));
         return $this->decodeGerritResponse($response->getBody(true));
     } catch (Exception $exception) {
         return false;
     }
 }
 function testQueueing()
 {
     $client = new \Guzzle\Http\Client();
     $client->getCurlMulti()->getEventDispatcher()->addSubscriber(new ConnectionLimit(2));
     $queueings = 0;
     $client->getEventDispatcher()->addListener('request.queued', function ($event) use(&$queueings) {
         $queueings++;
     });
     $dequeueings = 0;
     $client->getEventDispatcher()->addListener('request.dequeued', function ($event) use(&$dequeueings) {
         $dequeueings++;
     });
     $requests = array($client->get()->setResponse(new Response(200), true), $client->get()->setResponse(new Response(200), true), $client->get()->setResponse(new Response(200), true), $client->get()->setResponse(new Response(200), true));
     foreach ($client->send($requests) as $response) {
         $this->assertEquals(200, $response->getStatusCode(), "Status code");
     }
     $this->assertEquals(2, $queueings, "Queueings");
     $this->assertEquals(2, $dequeueings, "Dequeueings");
 }
 private function getTelizeData($ip)
 {
     $url = "/geip/" . $ip;
     $telizeClient = new \Guzzle\Http\Client("http://www.telize.com");
     $response = $telizeClient->get($url)->send();
     if (!$response->isSuccessful()) {
         return array();
     }
     $data = json_decode($response->getBody(), true);
     $data = array("ip" => $data['ip'], "country_code" => $data['country_code'], "country_name" => $data['country'], "latitude" => $data['latitude'], "longitude" => $data['longitude'], "cached" => false);
     return $data;
 }
示例#10
0
 /**
  * Use Craft's included Guzzle library to make an API request
  * 
  * @param  string $url  The URL to query
  * 
  * @return void
  */
 private function _curlRequest($url = '')
 {
     try {
         $client = new \Guzzle\Http\Client($url);
         $request = $client->get($url, array('Accept' => 'application/rss+xml', 'Accept' => 'application/rdf+xml', 'Accept' => 'application/xml', 'Accept' => 'text/xml'));
         $response = $request->send();
         return $response->getBody(true);
     } catch (\Exception $e) {
         FeederPlugin::log($e->getResponse(), LogLevel::Error, true);
         $response = $e->getResponse();
         return $response;
     }
 }
示例#11
0
文件: Http.php 项目: pnomolos/phitly
 protected function _get($method, $opts = array())
 {
     $opts += array('query' => array(), 'timeout' => 0);
     $opts['query'] = array_merge($opts['query'], $this->default_query_opts);
     $url = ltrim($method, '/') . (!strpos($method, '?') ? '?' : '&') . http_build_query($opts['query']);
     $client = new \Guzzle\Http\Client($this->base_uri);
     $request = $client->get($url);
     if ($opts['timeout']) {
         $request->getCurlOptions()->set(CURLOPT_TIMEOUT, $opts['timeout']);
     }
     $response = $request->send();
     return json_decode(json_encode($response->json()));
 }
示例#12
0
 /**
  * Reads data from a file or URL data can be parsed as PHP
  * 
  * <code>
  * // possible resource examples
  * $resource = 'http://path/to/resource'; // URL that points to the resource
  * $resource = 'path/to/file';            // File that contains the resource
  * $resource = 'some string';             // string in the expected format
  * $resource = ['some' => 'array'];       // array
  * $resource = ?                          // some other format as long there is a suitable plugin
  * 
  * // In the cases of URLs, files and strings the resource can also be be parsed, see options below
  * 
  * $options = [
  *   'parse_file'      => true,     // accept files as parameter
  *   'parse_php'       => false,    // evaluate PHP code in a file, means also to
  *                                  // parse code treated with serialize() to an array.
  *                                  // Code serialized with json_encode() are always allowed
  *                                  // NOTE: Use this with only when you are sure about the source!
  *   'expected_format' => null,     // string|array by default computed from the name of the calling function 
  *                                  // triggered within the restrictions above
  *   'parse_url'       => true,     // accept URLs as parameter
  *   'use_cache'       => true,     // URL resources are cached for a short while by default to avoid HTTP requests
  *   'cache_dir'       => null,     // default: rtrim(sys_get_temp_dir(), '/') . '/PHP_Jig/Converter/' . session_id()
  * ];
  * 
  * // $options will be merged with those in the constructor and those sent to the function
  * </code>
  * 
  * @param mixed $resource
  * @param array $options
  * @return mixed
  * @todo garbage collection for cached resources
  */
 protected static function getRealResource($resource, $options = [])
 {
     $options = array_merge(['parse_php' => false, 'parse_file' => true, 'parse_url' => true, 'use_cache' => true, 'expected_format' => null, 'cache_dir' => rtrim(sys_get_temp_dir(), '/') . '/PHP_Jig/Converter/' . session_id()], $options);
     // compute expected format
     if (is_null($options['expected_format'])) {
         $matches = [];
         preg_match('~^from(?<expected_format>[\\w]+)$~', strtolower(debug_backtrace()[1]['function']), $matches);
         if (empty($matches['expected_format']) || !in_array($matches['expected_format'], ['string', 'array'])) {
             $options['expected_format'] = 'string';
         } else {
             $options['expected_format'] = $matches['expected_format'];
         }
     }
     // - Resource cannot be a file or a URL or they are both disallowed
     if (!is_string($resource) || !$options['parse_url'] && !$options['parse_file']) {
         return $resource;
     }
     $cacheFile = $options['cache_dir'] . '/' . session_id() . '/' . md5($resource);
     // - Resource might be cached
     if ($options['use_cache'] && is_readable($cacheFile)) {
         return FileCache::read($cacheFile);
     }
     // - Resource might be an URL
     if ($options['parse_url'] && false === strpos($resource, "\n") && false !== strpos($resource, '://')) {
         $client = new \Guzzle\Http\Client($resource);
         $request = $client->get();
         $response = $request->send();
         $resource = (string) $response->getBody();
         if ($options['expected_format'] === 'array') {
             $resource = self::unserializeResource($resource, $options['parse_php']);
         }
         if ($options['use_cache']) {
             FileCache::write($cacheFile, $resource, '+1minute');
         }
         return $resource;
     }
     // - Resource might be a file
     if ($options['parse_file'] && false === strpos($resource, "\n") && is_readable($resource)) {
         if ($options['parse_php']) {
             ob_start();
             require $resource;
             $resource = ob_get_contents();
             ob_end_flush();
         }
         $resource = file_get_contents($resource);
         return $options['expected_format'] === 'array' ? self::unserializeResource($resource) : $resource;
     }
     // - Resource is neither file nor URL
     return $resource;
 }
示例#13
0
 protected function attemptAuthentication(Request $request)
 {
     $client = new \Guzzle\Http\Client('https://github.com/login/oauth/access_token');
     $req = $client->post('', null, ['client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'code' => $request->query->get('code')])->setHeader('Accept', 'application/json');
     $res = $req->send()->json();
     $access_token = $res['access_token'];
     $client = new \Guzzle\Http\Client('https://api.github.com');
     $req = $client->get('/user');
     $req->getQuery()->set('access_token', $access_token);
     $res = $req->send()->json();
     $email = $res['email'];
     $token = new GithubUserToken();
     $token->setCredentials($email);
     return $this->authenticationManager->authenticate($token);
 }
示例#14
0
 /**
  * Retrieve access token
  * 
  * @param Collection $config
  * 
  * @return string
  */
 protected static function retrieveAccessToken(Collection $config)
 {
     $client = new \Guzzle\Http\Client($config->get('oauth2_token'));
     $request = $client->get();
     $query = $request->getQuery();
     $query->set('grant_type', $config->get('grant_type'));
     $query->set('client_id', $config->get('client_id'));
     $query->set('client_secret', $config->get('client_secret'));
     $query->set('api_key', $config->get('api_key'));
     try {
         $response = $request->send();
         $json = $response->json();
     } catch (\Guzzle\Http\Exception\BadResponseException $ex) {
         throw new \Exception('Bad authentification, please check your oauth settings');
     }
     return $json['access_token'];
 }
 public function retrieveCurrencies()
 {
     $client = new Guzzle\Http\Client($this->config()->base_url);
     try {
         $request = $client->get($this->config()->path);
         $response = $request->send();
     } catch (Guzzle\Http\RequestException $e) {
         $this->currencies = array();
         throw new Exception($e->getMessage());
     }
     $xml = $response->xml();
     $currencies = array();
     foreach ($xml->Cube->Cube->Cube as $currency) {
         $currencies[(string) $currency['currency']] = (double) $currency['rate'];
     }
     return $currencies;
 }
 public function geocode($address)
 {
     if (is_array($address)) {
         $address = implode(' ', $address);
     }
     $encodedAddress = urlencode($address);
     $url = $this->url . '?address=' . $encodedAddress;
     $expires = date('Y-m-d H:i:s', time() - $this->expirationLength * 24 * 60 * 60);
     $results = GoogleMaps_GeocoderCacheRecord::model()->find('query = :query AND dateCreated >= :date', array(':query' => $encodedAddress, ':date' => $expires));
     if ($results) {
         return json_decode($results->response);
     }
     $client = new \Guzzle\Http\Client();
     $response = $client->get($url);
     $response->send();
     $response = (string) $response->getResponse()->getBody();
     $this->cacheResponse($encodedAddress, $response);
     return json_decode($response);
 }
示例#17
0
 /**
  * Получить Token ID
  * @return str Token
  */
 public static function getToken($vkontakteCode)
 {
     if ($vkontakteCode) {
         self::$code = $vkontakteCode;
     }
     $vkontakteAccessToken = COption::GetOptionString("grain.customsettings", "vk_token");
     if (!empty(self::$code) && !$vkontakteAccessToken) {
         /*$sUrl = 'https://oauth.vk.com/access_token?client_id='.self::$client_id.'&client_secret='.self::$client_secret.
               '&redirect_uri=http://www.megatv.su/cron/vk.php&code='.self::$code;
           $oResponce = json_decode(file_get_contents($sUrl), true);*/
         $client = new \Guzzle\Http\Client();
         $params = array("client_id" => self::$client_id, "client_secret" => self::$client_secret, "v" => "5.50", "redirect_uri" => "http://www.megatv.su/cron/vk.php", "code" => self::$code);
         $request = $client->get("https://oauth.vk.com/access_token" . '?' . http_build_query($params));
         $data = $request->send()->json();
         COption::SetOptionString("grain.customsettings", "vk_token", $oResponce["access_token"]);
         self::$token = $data["access_token"];
     } else {
         self::$token = $vkontakteAccessToken;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function execute(BlockContextInterface $blockContext, Response $response = null)
 {
     $tweet = $blockContext->getSetting('tweet');
     if (($uriMatched = preg_match(self::TWEET_URL_PATTERN, $tweet)) || preg_match(self::TWEET_ID_PATTERN, $tweet)) {
         // We matched an URL or an ID, we'll need to ask the API
         if (class_exists('Guzzle\\Http\\Client') === false) {
             throw new \RuntimeException('The guzzle http client library is required to call the Twitter API. Make sure to add guzzle/guzzle to your composer.json.');
         }
         // TODO cache API result
         $client = new \Guzzle\Http\Client();
         $client->setConfig(array('curl.options' => array(CURLOPT_CONNECTTIMEOUT_MS => 1000)));
         try {
             $request = $client->get($this->buildUri($uriMatched, $blockContext->getSettings()));
             $apiTweet = json_decode($request->send()->getBody(true), true);
             $tweet = $apiTweet['html'];
         } catch (CurlException $e) {
             // log error
         }
     }
     return $this->renderResponse($blockContext->getTemplate(), array('block' => $blockContext->getBlock(), 'tweet' => $tweet), $response);
 }
 public function getConversion($from = 'EUR', $to = 'USD', $amount = 1)
 {
     $path = craft()->path->getStoragePath() . 'currency/';
     $cache = $path . $from . '-' . $to;
     if (!is_dir($path)) {
         mkdir($path);
     }
     if (file_exists($cache) && filemtime($cache) > time() - 60 * 60 * 24) {
         return $amount * file_get_contents($cache);
     }
     $url = '/d/quotes.csv?s=' . $from . $to . '=X&f=l1';
     $client = new \Guzzle\Http\Client('http://download.finance.yahoo.com');
     $response = $client->get($url)->send();
     if ($response->isSuccessful()) {
         $exchange = trim($response->getBody());
         file_put_contents($cache, $exchange);
         return $amount * $exchange;
     } else {
         return false;
     }
 }
 public function serveAsset(array $options = array())
 {
     if (isset($options['id'])) {
         if (!$this->_asset or $this->_asset->id != $options['id'] or !$this->_asset instanceof AssetFileModel) {
             $this->_asset = craft()->assets->getFileById($options['id']);
             if (!$this->_asset) {
                 throw new Exception(Craft::t("Unable to find asset"));
             }
         }
         $sendFile = false;
         if ($this->_asset->source->type == 'Local') {
             $sourcePath = $this->_asset->source->sourceType->getBasePath();
             $folderPath = $this->_asset->getFolder()->path;
             $path = $sourcePath . $folderPath . $this->_asset->filename;
             if (IOHelper::fileExists($path)) {
                 $content = IOHelper::getFileContents($path);
                 $sendFile = true;
             }
         } else {
             $path = $this->_asset->url;
             $client = new \Guzzle\Http\Client();
             $response = $client->get($this->_asset->url)->send();
             if ($response->isSuccessful()) {
                 $content = $response->getBody();
                 $sendFile = true;
             }
         }
         if ($sendFile) {
             if (isset($options['forceDownload']) and !$options['forceDownload']) {
                 $extraParams = array('forceDownload' => false);
             } else {
                 $extraParams = array('forceDownload' => true);
             }
             craft()->request->sendFile($path, $content, $extraParams);
         } else {
             throw new Exception(Craft::t("Unable to serve file"));
         }
     }
 }
示例#21
0
 /**
  * Save remote photo
  *
  * @param string $photoUrl
  * @param UserModel $user
  *
  * @return bool
  */
 public function saveRemotePhoto($photoUrl, UserModel $user)
 {
     $filename = 'photo';
     $tempPath = craft()->path->getTempPath() . 'social/userphotos/' . $user->email . '/';
     IOHelper::createFolder($tempPath);
     $tempFilepath = $tempPath . $filename;
     $client = new \Guzzle\Http\Client();
     $response = $client->get($photoUrl)->setResponseBody($tempPath . $filename)->send();
     $extension = substr($response->getContentType(), strpos($response->getContentType(), "/") + 1);
     IOHelper::rename($tempPath . $filename, $tempPath . $filename . '.' . $extension);
     craft()->users->deleteUserPhoto($user);
     $image = craft()->images->loadImage($tempPath . $filename . '.' . $extension);
     $imageWidth = $image->getWidth();
     $imageHeight = $image->getHeight();
     $dimension = min($imageWidth, $imageHeight);
     $horizontalMargin = ($imageWidth - $dimension) / 2;
     $verticalMargin = ($imageHeight - $dimension) / 2;
     $image->crop($horizontalMargin, $imageWidth - $horizontalMargin, $verticalMargin, $imageHeight - $verticalMargin);
     craft()->users->saveUserPhoto($filename . '.' . $extension, $image, $user);
     IOHelper::deleteFile($tempPath . $filename . '.' . $extension);
     return true;
 }
 protected function _makeRequest($url)
 {
     try {
         $cached = craft()->cache->get($url);
         if ($cached) {
             return $cached;
         } else {
             $client = new \Guzzle\Http\Client();
             $request = $client->get($url);
             $request->addHeader('Authorization', 'Bearer ' . $this->oAuthToken);
             $response = $request->send();
             if (!$response->issuccessful()) {
                 return;
             }
             $output = $response->json();
             craft()->cache->set($url, $output, $this->cacheDuration);
             return $output;
         }
     } catch (\Exception $e) {
         throw $e;
     }
 }
 public function route($options)
 {
     $url = $this->getUrl($options);
     $client = new \Guzzle\Http\Client();
     $response = $client->get($url);
     $response->send();
     $response = (string) $response->getResponse()->getBody();
     return new GoogleMaps_DirectionsModel(array_merge((array) json_decode($response), array('options' => $options)));
     /*
         	$encodedAddress = urlencode($address);
         	
         	$url = $this->url.'?address='.$encodedAddress;
     
         	$expires = date('Y-m-d H:i:s', time() - $this->expirationLength * 24 * 60 * 60);
     
         	$results = GoogleMaps_GeocoderCacheRecord::model()->find('query = :query AND dateCreated >= :date', array(
         		':query' => $encodedAddress,
         		':date' => $expires
         	));
     
         	if($results)
         	{
         		return json_decode($results->response);
         	}
     
         	$client = new \Guzzle\Http\Client;
         	
         	$response = $client->get($url);
     
         	$response->send();
     
         	$response = (string) $response->getResponse()->getBody();
     
         	$this->cacheResponse($encodedAddress, $response);
     
         	return json_decode($response);
     */
 }
 /**
  * send request to Youtrack api, dosnt check the cache. Use the rest function in this class instead
  * @param string $url request url
  * @param string $postOrGet get|post|put request type
  * @param array $headers
  * @param string $body
  * @param array $options
  * @return object request object
  */
 function restResponse($url, $postOrGet = 'get', $headers = null, $body = null, $options = null)
 {
     $client = new \Guzzle\Http\Client();
     $authenticationAndSecurity = new authenticationAndSecurity();
     $authentication = $authenticationAndSecurity->getAuthentication();
     if ($authentication['type'] !== 'password' && $authentication['type'] !== 'cookie' && $authentication['type'] !== 'file') {
         echo 'authentication type unknown. please check its set in the customSettings.php file';
         return;
     }
     if (!isset($options)) {
         if ($authentication['type'] === 'password') {
             $options = ['auth' => [$authentication['details']['user'], $authentication['details']['password']]];
         } else {
             $options = [];
         }
     }
     if ($postOrGet === 'get') {
         $request = $client->get($url, $headers, $options);
     } elseif ($postOrGet === 'post') {
         $request = $client->post($url, $headers, $body, $options);
     } elseif ($postOrGet === 'put') {
         $request = $client->put($url, $headers, $body, $options);
     }
     //        if( $postOrGet === 'put' && isset($headers) ){
     //            foreach($headers as $key => $value){
     //                $request->addHeader($key,$value);
     //            }
     //        }
     if ($authentication['type'] === 'cookie' && $authentication['details']) {
         foreach ($authentication['details'] as $singleCookie) {
             foreach ($singleCookie as $cookieName => $cookieValue) {
                 $request->addCookie($cookieName, $cookieValue);
             }
         }
     }
     $request->send();
     return $request;
 }
 public function generate(GoogleMaps_StaticMapModel $data, $options = array())
 {
     $basePath = craft()->config->get('staticMapCachePath', 'googlemaps');
     $baseUrl = craft()->config->get('staticMapCacheUrl', 'googlemaps');
     $url = $this->url . '?' . $data->getParameters();
     if ($this->expirationLength) {
         $expires = date('Y-m-d H:i:s', time() - $this->expirationLength * 24 * 60 * 60);
     } else {
         $expires = '0000-00-00 00:00:00';
     }
     $record = GoogleMaps_StaticMapRecord::model()->find('query = :query AND dateCreated >= :date', array(':query' => $data->getParameters(), ':date' => $expires));
     if ($record && $record->cachedFileExists()) {
         return $record->getCachedUrl();
     }
     if ($basePath && $baseUrl) {
         $basePath = rtrim($basePath, '/') . '/';
         $baseUrl = rtrim($baseUrl, '/') . '/';
         $client = new \Guzzle\Http\Client();
         $response = $client->get($url);
         $response->send();
         $rawdata = (string) $response->getResponse()->getBody();
         IOHelper::ensureFolderExists($basePath);
         $filename = md5($basePath . time()) . '.' . $data->format;
         $fullpath = $basePath . $filename;
         if (file_exists($fullpath)) {
             unlink($fullpath);
         }
         $fp = fopen($fullpath, 'x');
         fwrite($fp, $rawdata);
         fclose($fp);
         $record = new GoogleMaps_StaticMapRecord();
         $record->query = $data->getParameters();
         $record->filename = $filename;
         $record->save();
         return $baseUrl . $filename;
     }
     return $url;
 }
示例#26
0
 /**
  * News.
  */
 function dashboardnews(Silex\Application $app)
 {
     global $bolt_version, $app;
     $news = $app['cache']->get('dashboardnews', 7200);
     // Two hours.
     $name = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
     // If not cached, get fresh news..
     if ($news == false) {
         $app['log']->add("News: fetch from remote server..", 1);
         $driver = !empty($app['config']['general']['database']['driver']) ? $app['config']['general']['database']['driver'] : 'sqlite';
         $url = sprintf('http://news.bolt.cm/?v=%s&p=%s&db=%s&name=%s', $bolt_version, phpversion(), $driver, base64_encode($name));
         $guzzleclient = new \Guzzle\Http\Client($url);
         $news = $guzzleclient->get("/")->send()->getBody(true);
         $news = json_decode($news);
         // For now, just use the most current item.
         $news = current($news);
         $app['cache']->set('dashboardnews', $news);
     } else {
         $app['log']->add("News: get from cache..", 1);
     }
     $body = $app['twig']->render('dashboard-news.twig', array('news' => $news));
     return new Response($body, 200, array('Cache-Control' => 's-maxage=3600, public'));
 }
示例#27
0
 /**
  * News.
  */
 public function dashboardnews(Silex\Application $app)
 {
     $news = $app['cache']->fetch('dashboardnews');
     // Two hours.
     $name = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
     // If not cached, get fresh news..
     if ($news == false) {
         $app['log']->add("News: fetch from remote server..", 1);
         $driver = $app['config']->get('general/database/driver', 'sqlite');
         $url = sprintf('http://news.bolt.cm/?v=%s&p=%s&db=%s&name=%s', rawurlencode($app->getVersion()), phpversion(), $driver, base64_encode($name));
         $curlOptions = array('CURLOPT_CONNECTTIMEOUT' => 5);
         // If there's a proxy ...
         if ($app['config']->get('general/httpProxy')) {
             $curlOptions['CURLOPT_PROXY'] = $app['config']->get('general/httpProxy/host');
             $curlOptions['CURLOPT_PROXYTYPE'] = 'CURLPROXY_HTTP';
             $curlOptions['CURLOPT_PROXYUSERPWD'] = $app['config']->get('general/httpProxy/user') . ':' . $app['config']->get('general/httpProxy/password');
         }
         $guzzleclient = new \Guzzle\Http\Client($url, array('curl.options' => $curlOptions));
         try {
             $newsData = $guzzleclient->get("/")->send()->getBody(true);
             $news = json_decode($newsData);
             if ($news) {
                 // For now, just use the most current item.
                 $news = current($news);
                 $app['cache']->save('dashboardnews', $news, 7200);
             } else {
                 $app['log']->add("News: got invalid JSON feed", 1);
             }
         } catch (RequestException $re) {
             $app['log']->add("News: got exception: " . $re->getMessage(), 1);
         }
     } else {
         $app['log']->add("News: get from cache..", 1);
     }
     $body = $app['render']->render('dashboard-news.twig', array('news' => $news));
     return new Response($body, 200, array('Cache-Control' => 's-maxage=3600, public'));
 }
示例#28
0
 /**
  * Checks whether a file exists or not. This method only works for public resources, private resources will throw
  * a 403 error exception.
  * @param string $name the name of the file
  * @param string $folder the folder insight
  * @return boolean
  */
 public function fileExists($name, $folder = null)
 {
     $http = new \Guzzle\Http\Client();
     try {
         $response = $http->get($this->getUrl(!empty($folder) ? $folder . '/' . $name : $name))->send();
     } catch (ClientErrorResponseException $e) {
         return false;
     }
     return $response->isSuccessful();
 }
示例#29
0
 /**
  * Create plain and presigned URLs for an object
  *
  * @depends testCreatePresignedUrl
  * @example Aws\S3\S3Client::getObjectUrl
  */
 public function testGetObjectUrl()
 {
     $this->client->waitUntil('BucketExists', array('Bucket' => $this->bucket));
     $client = $this->client;
     $bucket = $this->bucket;
     // @begin
     // Get a plain URL for an Amazon S3 object
     $plainUrl = $client->getObjectUrl($bucket, 'data.txt');
     // > https://my-bucket.s3.amazonaws.com/data.txt
     // Get a pre-signed URL for an Amazon S3 object
     $signedUrl = $client->getObjectUrl($bucket, 'data.txt', '+10 minutes');
     // > https://my-bucket.s3.amazonaws.com/data.txt?AWSAccessKeyId=[...]&Expires=[...]&Signature=[...]
     // Create a vanilla Guzzle HTTP client for accessing the URLs
     $http = new \Guzzle\Http\Client();
     // Try to get the plain URL. This should result in a 403 since the object is private
     try {
         $response = $http->get($plainUrl)->send();
     } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
         $response = $e->getResponse();
     }
     echo $response->getStatusCode();
     // > 403
     // Get the contents of the object using the pre-signed URL
     $response = $http->get($signedUrl)->send();
     echo $response->getBody();
     // > Hello!
     // @end
     $this->assertEquals('403Hello!', $this->getActualOutput());
 }
 /**
  * Calls the rabbitmq management api /api/<vhost>/queues endpoint to list the available queues.
  *
  * @see http://hg.rabbitmq.com/rabbitmq-management/raw-file/3646dee55e02/priv/www-api/help.html
  *
  * @return array
  */
 protected function getApiQueueStatus()
 {
     if (class_exists('Guzzle\\Http\\Client') === false) {
         throw new \RuntimeException('The guzzle http client library is required to run rabbitmq health checks. Make sure to add guzzle/guzzle to your composer.json.');
     }
     $client = new \Guzzle\Http\Client();
     $client->setConfig(array('curl.options' => array(CURLOPT_CONNECTTIMEOUT_MS => 3000)));
     $request = $client->get(sprintf('%s/queues', $this->settings['console_url']));
     $request->setAuth($this->settings['user'], $this->settings['pass']);
     return json_decode($request->send()->getBody(true), true);
 }