Exemple #1
0
 private function getSpecificPois($latitude, $longitude)
 {
     $c = curl_init();
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-Gowalla-API-Key: ' . $this->apiKey));
     curl_setopt($c, CURLOPT_FOLLOWLOCATION, TRUE);
     $uri = new Uri('http://api.gowalla.com/spots');
     $uri->setQuery(array('lat' => (string) $latitude, 'lng' => (string) $longitude, 'radius' => (string) $this->radius));
     curl_setopt($c, CURLOPT_URL, (string) $uri);
     $result = curl_exec($c);
     curl_close($c);
     $json = json_decode($result);
     if ($json == FALSE) {
         throw new InvalidStateException('Malformed JSON response.');
     }
     $spots = $json->spots;
     $pois = array();
     foreach ($spots as $spot) {
         $poi = new Poi();
         $poi->name = $spot->name;
         $poi->address = $spot->address->locality;
         $poi->latitude = $spot->lat;
         $poi->longitude = $spot->lng;
         $poi->url = 'http://gowalla.com' . $spot->url;
         $id = explode('/', $spot->spot_categories[0]->url);
         $poi->imageUrl = GowallaCategoryImage::get($id[count($id) - 1]);
         $types = array();
         foreach ($spot->spot_categories as $category) {
             $types[] = $category->name;
         }
         $poi->types = implode(', ', $types);
         $pois[] = $poi;
     }
     return $pois;
 }
 protected function getFlightResults($searchid)
 {
     $c = curl_init();
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
     curl_setopt($c, CURLOPT_FOLLOWLOCATION, TRUE);
     $uri = new Uri('http://www.kayak.com/s/apibasic/flight');
     $uri->setQuery(array('searchid' => $searchid, 'c' => C, 'm' => M, 'd' => D, 's' => S, 'apimode' => APIMODE, "_sid_" => $this->getSessionId(), 'version' => VERSION));
     curl_setopt($c, CURLOPT_URL, (string) $uri);
     $result = curl_exec($c);
     curl_close($c);
     return $result;
 }
Exemple #3
0
 /**
  * Constructs absolute URL from PresenterRequest object.
  * @param  PresenterRequest
  * @param  Nette\Web\Uri
  * @return string|NULL
  */
 public function constructUrl(PresenterRequest $appRequest, Nette\Web\Uri $refUri)
 {
     $params = $appRequest->getParams();
     // presenter name
     $presenter = $appRequest->getPresenterName();
     if (strncasecmp($presenter, $this->module, strlen($this->module)) === 0) {
         $params[self::PRESENTER_KEY] = substr($presenter, strlen($this->module));
     } else {
         return NULL;
     }
     // remove default values; NULL values are retain
     foreach ($this->defaults as $key => $value) {
         if (isset($params[$key]) && $params[$key] == $value) {
             // intentionally ==
             unset($params[$key]);
         }
     }
     $uri = ($this->flags & self::SECURED ? 'https://' : 'http://') . $refUri->getAuthority() . $refUri->getPath();
     $sep = ini_get('arg_separator.input');
     $query = http_build_query($params, '', $sep ? $sep[0] : '&');
     if ($query != '') {
         // intentionally ==
         $uri .= '?' . $query;
     }
     return $uri;
 }
 private function canonicalizeDestination($destination)
 {
     // searching for any string that wikipedia knows
     $c = curl_init();
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
     curl_setopt($c, CURLOPT_USERAGENT, 'Travelbot 1.0 beta');
     curl_setopt($c, CURLOPT_FOLLOWLOCATION, TRUE);
     curl_setopt($c, CURLOPT_MAXREDIRS, 100);
     $uri = new Uri('http://en.wikipedia.org/w/api.php');
     $uri->setQuery(array('format' => 'json', 'action' => 'opensearch', 'search' => $destination, 'limit' => 5));
     curl_setopt($c, CURLOPT_URL, (string) $uri);
     $result = curl_exec($c);
     curl_close($c);
     $json = json_decode($result);
     if ($json === FALSE) {
         throw new InvalidStateException('Malformed JSON response.');
     }
     if (!isset($json[1][0])) {
         throw new ArticleException('Article not found.');
     }
     $destination = $json[1][0];
     // canonization (redirection to the final article)
     $c = curl_init();
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
     curl_setopt($c, CURLOPT_USERAGENT, 'Travelbot 1.0 beta');
     curl_setopt($c, CURLOPT_FOLLOWLOCATION, TRUE);
     curl_setopt($c, CURLOPT_MAXREDIRS, 100);
     $uri = new Uri('http://en.wikipedia.org/w/api.php');
     $uri->setQuery(array('format' => 'json', 'action' => 'query', 'titles' => $destination, 'redirects' => TRUE));
     curl_setopt($c, CURLOPT_URL, (string) $uri);
     $result = curl_exec($c);
     curl_close($c);
     $json = json_decode($result);
     if ($json === FALSE) {
         return $destination;
     }
     if (isset($json->query->redirects[0])) {
         return $json->query->redirects[0]->to;
     } else {
         if (isset($json->query->normalized[0])) {
             return String::capitalize($json->query->normalized[0]->to);
         }
     }
     return $destination;
 }
Exemple #5
0
 /**
  * Returns coordinates by given location string.
  * @param string
  * @return array	 	 
  */
 public function getCoordinates($location)
 {
     $c = curl_init();
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
     $uri = new Uri('http://maps.googleapis.com/maps/api/geocode/json');
     $uri->setQuery(array('address' => $location, 'sensor' => 'false'));
     curl_setopt($c, CURLOPT_URL, (string) $uri);
     $result = curl_exec($c);
     curl_close($c);
     // parsing json results
     $json = json_decode($result);
     if ($json == FALSE || $json->status != 'OK') {
         throw new InvalidStateException('Malformed JSON data.');
     }
     return array('latitude' => $json->results[0]->geometry->location->lat, 'longitude' => $json->results[0]->geometry->location->lng);
 }
Exemple #6
0
 public function getTripDirections($departure, $arrival)
 {
     // curl initialization
     $c = curl_init();
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
     curl_setopt($c, CURLOPT_FOLLOWLOCATION, TRUE);
     // using Nette\Web\Uri for escaping GET parameters
     $uri = new Uri('http://maps.googleapis.com/maps/api/directions/json');
     $uri->setQuery(array('origin' => $departure, 'destination' => $arrival, 'sensor' => 'false'));
     curl_setopt($c, CURLOPT_URL, (string) $uri);
     $result = curl_exec($c);
     curl_close($c);
     $json = json_decode($result);
     if ($json == FALSE || $json->status != 'OK') {
         throw new InvalidStateException('Malformed JSON response.');
     }
     return $json;
 }
Exemple #7
0
 public function getEvents($location, DateTime $date)
 {
     $c = curl_init();
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
     curl_setopt($c, CURLOPT_FOLLOWLOCATION, TRUE);
     // using Nette\Web\Uri for escaping GET parameters
     $uri = new Uri('http://api.eventful.com/rest/events/search');
     $uri->setQuery(array('user' => $this->user, 'password' => $this->password, 'app_key' => $this->key, 'location' => $location, 'within' => '10', 'units' => 'km'));
     curl_setopt($c, CURLOPT_URL, (string) $uri);
     $result = curl_exec($c);
     curl_close($c);
     $xml = @simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
     if ($xml == FALSE) {
         throw new InvalidStateException('Malformed XML response.');
     }
     $events = array();
     foreach ($xml->events->event as $xmlEvent) {
         $event = new Event();
         $event->setTitle((string) $xmlEvent->title)->setUrl((string) $xmlEvent->url)->setDescription((string) $xmlEvent->description)->setDate(DateTime::createFromFormat('Y-m-d H:i:s', (string) $xmlEvent->start_time))->setVenue(new Venue((string) $xmlEvent->venue_name, (string) $xmlEvent->venue_url))->setLatitude((string) $xmlEvent->latitude)->setLongitude((string) $xmlEvent->longitude);
         $events[] = $event;
     }
     return $events;
 }
	/**
	 * Constructs absolute URL from PresenterRequest object.
	 *
	 * @author   Jan Tvrdík
	 * @param    PresenterRequest
	 * @param    Uri
	 * @return   string|NULL       absolute URI or NULL
	 */
	public function constructUrl(PresenterRequest $appRequest, Uri $refUri)
	{
		if ($appRequest->getPresenterName() !== $this->presenter) return NULL;
		$params = $appRequest->getParams();
		if (!isset($params['page'])) return NULL;
		$page = $params['page'];

		if ($page === $this->homepage) {
			$page = '';
		} elseif (substr($page, ($pos = strrpos($page, '/') + 1)) === $this->defaultPage) {
			$page = substr($page, 0, $pos);
		}

		return $refUri->getBaseUri() . $page;
	}
Exemple #9
0
	/**
	 * Constructs absolute URL from PresenterRequest object.
	 * @param  PresenterRequest
	 * @param  Nette\Web\Uri
	 * @return string|NULL
	 */
	public function constructUrl(PresenterRequest $appRequest, Nette\Web\Uri $refUri)
	{
		if ($this->flags & self::ONE_WAY) {
			return NULL;
		}

		$params = $appRequest->getParams();
		$metadata = $this->metadata;

		$presenter = $appRequest->getPresenterName();
		$params[self::PRESENTER_KEY] = $presenter;

		if (isset($metadata[self::MODULE_KEY])) { // try split into module and [submodule:]presenter parts
			$module = $metadata[self::MODULE_KEY];
			if (isset($module['fixity']) && strncasecmp($presenter, $module[self::VALUE] . ':', strlen($module[self::VALUE]) + 1) === 0) {
				$a = strlen($module[self::VALUE]);
			} else {
				$a = strrpos($presenter, ':');
			}
			if ($a === FALSE) {
				$params[self::MODULE_KEY] = '';
			} else {
				$params[self::MODULE_KEY] = substr($presenter, 0, $a);
				$params[self::PRESENTER_KEY] = substr($presenter, $a + 1);
			}
		}

		foreach ($metadata as $name => $meta) {
			if (!isset($params[$name])) continue; // retains NULL values

			if (isset($meta['fixity'])) {
				if (is_scalar($params[$name]) && strcasecmp($params[$name], $meta[self::VALUE]) === 0) {
					// remove default values; NULL values are retain
					unset($params[$name]);
					continue;

				} elseif ($meta['fixity'] === self::CONSTANT) {
					return NULL; // missing or wrong parameter '$name'
				}
			}

			if (!is_scalar($params[$name])) {

			} elseif (isset($meta['filterTable2'][$params[$name]])) {
				$params[$name] = $meta['filterTable2'][$params[$name]];

			} elseif (isset($meta[self::FILTER_OUT])) {
				$params[$name] = call_user_func($meta[self::FILTER_OUT], $params[$name]);
			}

			if (isset($meta[self::PATTERN]) && !preg_match($meta[self::PATTERN], rawurldecode($params[$name]))) {
				return NULL; // pattern not match
			}
		}

		// compositing path
		$sequence = $this->sequence;
		$brackets = array();
		$required = 0;
		$uri = '';
		$i = count($sequence) - 1;
		do {
			$uri = $sequence[$i] . $uri;
			if ($i === 0) break;
			$i--;

			$name = $sequence[$i]; $i--; // parameter name

			if ($name === ']') { // opening optional part
				$brackets[] = $uri;

			} elseif ($name[0] === '[') { // closing optional part
				$tmp = array_pop($brackets);
				if ($required < count($brackets) + 1) { // is this level optional?
					if ($name !== '[!') { // and not "required"-optional
						$uri = $tmp;
					}
				} else {
					$required = count($brackets);
				}

			} elseif ($name[0] === '?') { // "foo" parameter
				continue;

			} elseif (isset($params[$name]) && $params[$name] != '') { // intentionally ==
				$required = count($brackets); // make this level required
				$uri = $params[$name] . $uri;
				unset($params[$name]);

			} elseif (isset($metadata[$name]['fixity'])) { // has default value?
				$uri = $metadata[$name]['defOut'] . $uri;

			} else {
				return NULL; // missing parameter '$name'
			}
		} while (TRUE);


		// build query string
		if ($this->xlat) {
			$params = self::renameKeys($params, $this->xlat);
		}

		$sep = ini_get('arg_separator.input');
		$query = http_build_query($params, '', $sep ? $sep[0] : '&');
		if ($query != '') $uri .= '?' . $query; // intentionally ==

		// absolutize path
		if ($this->type === self::RELATIVE) {
			$uri = '//' . $refUri->getAuthority() . $refUri->getBasePath() . $uri;

		} elseif ($this->type === self::PATH) {
			$uri = '//' . $refUri->getAuthority() . $uri;
		}

		if (strpos($uri, '//', 2) !== FALSE) {
			return NULL; // TODO: implement counterpart in match() ?
		}

		$uri = ($this->flags & self::SECURED ? 'https:' : 'http:') . $uri;

		return $uri;
	}
Exemple #10
0
 /**
  * PresenterRequest/URL factory.
  * @param  PresenterComponent  base
  * @param  string   destination in format "[[module:]presenter:]action" or "signal!" or "this"
  * @param  array    array of arguments
  * @param  string   forward|redirect|link
  * @return string   URL
  * @throws InvalidLinkException
  * @internal
  */
 protected final function createRequest($component, $destination, array $args, $mode)
 {
     // note: createRequest supposes that saveState(), run() & tryCall() behaviour is final
     // cached services for better performance
     static $presenterLoader, $router, $refUri;
     if ($presenterLoader === NULL) {
         $presenterLoader = $this->getApplication()->getPresenterLoader();
         $router = $this->getApplication()->getRouter();
         $refUri = new Nette\Web\Uri($this->getHttpRequest()->getUri());
         $refUri->setPath($this->getHttpRequest()->getUri()->getScriptPath());
     }
     $this->lastCreatedRequest = $this->lastCreatedRequestFlag = NULL;
     // PARSE DESTINATION
     // 1) fragment
     $a = strpos($destination, '#');
     if ($a === FALSE) {
         $fragment = '';
     } else {
         $fragment = substr($destination, $a);
         $destination = substr($destination, 0, $a);
     }
     // 2) ?query syntax
     $a = strpos($destination, '?');
     if ($a !== FALSE) {
         parse_str(substr($destination, $a + 1), $args);
         // requires disabled magic quotes
         $destination = substr($destination, 0, $a);
     }
     // 3) URL scheme
     $a = strpos($destination, '//');
     if ($a === FALSE) {
         $scheme = FALSE;
     } else {
         $scheme = substr($destination, 0, $a);
         $destination = substr($destination, $a + 2);
     }
     // 4) signal or empty
     if (!$component instanceof Presenter || substr($destination, -1) === '!') {
         $signal = rtrim($destination, '!');
         $a = strrpos($signal, ':');
         if ($a !== FALSE) {
             $component = $component->getComponent(strtr(substr($signal, 0, $a), ':', '-'));
             $signal = (string) substr($signal, $a + 1);
         }
         if ($signal == NULL) {
             // intentionally ==
             throw new InvalidLinkException("Signal must be non-empty string.");
         }
         $destination = 'this';
     }
     if ($destination == NULL) {
         // intentionally ==
         throw new InvalidLinkException("Destination must be non-empty string.");
     }
     // 5) presenter: action
     $current = FALSE;
     $a = strrpos($destination, ':');
     if ($a === FALSE) {
         $action = $destination === 'this' ? $this->action : $destination;
         $presenter = $this->getName();
         $presenterClass = get_class($this);
     } else {
         $action = (string) substr($destination, $a + 1);
         if ($destination[0] === ':') {
             // absolute
             if ($a < 2) {
                 throw new InvalidLinkException("Missing presenter name in '{$destination}'.");
             }
             $presenter = substr($destination, 1, $a - 1);
         } else {
             // relative
             $presenter = $this->getName();
             $b = strrpos($presenter, ':');
             if ($b === FALSE) {
                 // no module
                 $presenter = substr($destination, 0, $a);
             } else {
                 // with module
                 $presenter = substr($presenter, 0, $b + 1) . substr($destination, 0, $a);
             }
         }
         $presenterClass = $presenterLoader->getPresenterClass($presenter);
     }
     // PROCESS SIGNAL ARGUMENTS
     if (isset($signal)) {
         // $component must be IStatePersistent
         $reflection = new PresenterComponentReflection(get_class($component));
         if ($signal === 'this') {
             // means "no signal"
             $signal = '';
             if (array_key_exists(0, $args)) {
                 throw new InvalidLinkException("Unable to pass parameters to 'this!' signal.");
             }
         } elseif (strpos($signal, self::NAME_SEPARATOR) === FALSE) {
             // TODO: AppForm exception
             // counterpart of signalReceived() & tryCall()
             $method = $component->formatSignalMethod($signal);
             if (!$reflection->hasCallableMethod($method)) {
                 throw new InvalidLinkException("Unknown signal '{$signal}', missing handler {$reflection->name}::{$method}()");
             }
             if ($args) {
                 // convert indexed parameters to named
                 self::argsToParams(get_class($component), $method, $args);
             }
         }
         // counterpart of IStatePersistent
         if ($args && array_intersect_key($args, $reflection->getPersistentParams())) {
             $component->saveState($args);
         }
         if ($args && $component !== $this) {
             $prefix = $component->getUniqueId() . self::NAME_SEPARATOR;
             foreach ($args as $key => $val) {
                 unset($args[$key]);
                 $args[$prefix . $key] = $val;
             }
         }
     }
     // PROCESS ARGUMENTS
     if (is_subclass_of($presenterClass, __CLASS__)) {
         if ($action === '') {
             $action = $presenterClass::$defaultAction;
         }
         $current = ($action === '*' || $action === $this->action) && $presenterClass === get_class($this);
         // TODO
         $reflection = new PresenterComponentReflection($presenterClass);
         if ($args || $destination === 'this') {
             // counterpart of run() & tryCall()
             /**/
             $method = $presenterClass::formatActionMethod($action);
             /**/
             /*5.2* $method = call_user_func(array($presenterClass, 'formatActionMethod'), $action);*/
             if (!$reflection->hasCallableMethod($method)) {
                 /**/
                 $method = $presenterClass::formatRenderMethod($action);
                 /**/
                 /*5.2* $method = call_user_func(array($presenterClass, 'formatRenderMethod'), $action);*/
                 if (!$reflection->hasCallableMethod($method)) {
                     $method = NULL;
                 }
             }
             // convert indexed parameters to named
             if ($method === NULL) {
                 if (array_key_exists(0, $args)) {
                     throw new InvalidLinkException("Unable to pass parameters to action '{$presenter}:{$action}', missing corresponding method.");
                 }
             } elseif ($destination === 'this') {
                 self::argsToParams($presenterClass, $method, $args, $this->params);
             } else {
                 self::argsToParams($presenterClass, $method, $args);
             }
         }
         // counterpart of IStatePersistent
         if ($args && array_intersect_key($args, $reflection->getPersistentParams())) {
             $this->saveState($args, $reflection);
         }
         $globalState = $this->getGlobalState($destination === 'this' ? NULL : $presenterClass);
         if ($current && $args) {
             $tmp = $globalState + $this->params;
             foreach ($args as $key => $val) {
                 if ((string) $val !== (isset($tmp[$key]) ? (string) $tmp[$key] : '')) {
                     $current = FALSE;
                     break;
                 }
             }
         }
         $args += $globalState;
     }
     // ADD ACTION & SIGNAL & FLASH
     $args[self::ACTION_KEY] = $action;
     if (!empty($signal)) {
         $args[self::SIGNAL_KEY] = $component->getParamId($signal);
         $current = $current && $args[self::SIGNAL_KEY] === $this->getParam(self::SIGNAL_KEY);
     }
     if (($mode === 'redirect' || $mode === 'forward') && $this->hasFlashSession()) {
         $args[self::FLASH_KEY] = $this->getParam(self::FLASH_KEY);
     }
     $this->lastCreatedRequest = new PresenterRequest($presenter, PresenterRequest::FORWARD, $args, array(), array());
     $this->lastCreatedRequestFlag = array('current' => $current);
     if ($mode === 'forward') {
         return;
     }
     // CONSTRUCT URL
     $uri = $router->constructUrl($this->lastCreatedRequest, $refUri);
     if ($uri === NULL) {
         unset($args[self::ACTION_KEY]);
         $params = urldecode(http_build_query($args, NULL, ', '));
         throw new InvalidLinkException("No route for {$presenter}:{$action}({$params})");
     }
     // make URL relative if possible
     if ($mode === 'link' && $scheme === FALSE && !$this->absoluteUrls) {
         $hostUri = $refUri->getHostUri();
         if (strncmp($uri, $hostUri, strlen($hostUri)) === 0) {
             $uri = substr($uri, strlen($hostUri));
         }
     }
     return $uri . $fragment;
 }
Exemple #11
0
 private function getSignature(Uri $absoluteUri)
 {
     $uri = new Uri($absoluteUri->path . $absoluteUri->query);
     $uri->setQuery(array('sensor' => 'false', 'client' => $this->clientID));
     return hash_hmac('sha1', $uri->path . '?' . $uri->query, $this->key);
 }