/**
  * Handles performing a callback to the Salesforce auth server with the
  * provided authorisation code.
  *
  * @param string $code
  * @param string $state
  * @return SS_HTTPResponse
  * @throws SalesforceAuthException On authentication failure.
  */
 public function callback($code, $state)
 {
     $callback = new RestfulService(self::CALLBACK_URL, -1);
     $callback = $callback->request('', 'POST', array('code' => $code, 'grant_type' => 'authorization_code', 'client_id' => $this->getClientID(), 'client_secret' => $this->getClientSecret(), 'redirect_uri' => $this->getRedirectURL()));
     $callback = json_decode($callback->getBody());
     if (!$callback || !$callback->id) {
         throw new SalesforceAuthException('An invalid authorisation response was returned');
     }
     $id = new RestfulService($callback->id, -1);
     $id->setQueryString(array('oauth_token' => $callback->access_token));
     $id = json_decode($id->request()->getBody());
     if (!$id || !$id->email) {
         throw new SalesforceAuthException('An invalid identity response was returned');
     }
     /** @var Member $member */
     $member = Member::get()->filter('Email', $id->email)->first();
     if (!$member) {
         throw new SalesforceAuthException(sprintf('No member was found for the Salesforce email "%s"', $id->email));
     }
     $state = json_decode($state);
     $redirect = isset($state->redirect) ? $state->redirect : null;
     $member->logIn(!empty($state->remember));
     $member->extend('onSalesforceIdentify', $id);
     $response = new SS_HTTPResponse();
     if ($redirect && Director::is_site_url($redirect)) {
         return $response->redirect($redirect);
     }
     if ($redirect = Config::inst()->get('Security', 'default_login_dest')) {
         return $response->redirect($redirect);
     }
     return $response->redirect(Director::absoluteBaseURL());
 }
 public static function service()
 {
     $service = new RestfulService(Director::absoluteBaseURL() . 'api/v1', 0);
     $service->httpHeader('Accept: application/json');
     $service->httpHeader('Content-Type: application/json');
     return $service;
 }
 /**
  * Convert an address into a latitude and longitude.
  *
  * @param string $address The address to geocode.
  * @param string $region  An optional two letter region code.
  * @return array An associative array with lat and lng keys.
  */
 public static function address_to_point($address, $region = null)
 {
     // Get the URL for the Google API
     $url = Config::inst()->get('GoogleGeocoding', 'google_api_url');
     $key = Config::inst()->get('GoogleGeocoding', 'google_api_key');
     // Query the Google API
     $service = new RestfulService($url);
     $service->setQueryString(array('address' => $address, 'sensor' => 'false', 'region' => $region, 'key' => $key));
     if ($service->request()->getStatusCode() === 500) {
         $errorMessage = '500 status code, Are you sure your SSL certificates are properly setup? You can workaround this locally by setting CURLOPT_SSL_VERIFYPEER to "false", however this is not recommended for security reasons.';
         if (Director::isDev()) {
             throw new Exception($errorMessage);
         } else {
             user_error($errorMessage);
         }
         return false;
     }
     if (!$service->request()->getBody()) {
         // If blank response, ignore to avoid XML parsing errors.
         return false;
     }
     $response = $service->request()->simpleXML();
     if ($response->status != 'OK') {
         return false;
     }
     $location = $response->result->geometry->location;
     return array('lat' => (double) $location->lat, 'lng' => (double) $location->lng);
 }
 function testHttpErrorWithoutCache()
 {
     $connection = new RestfulService(Director::absoluteBaseURL(), 0);
     $response = $connection->request('RestfulServiceTest_Controller/httpErrorWithoutCache?usetestmanifest=1&flush=1');
     $this->assertEquals(400, $response->getStatusCode());
     $this->assertFalse($response->getCachedBody());
     $this->assertContains("<error>HTTP Error</error>", $response->getBody());
 }
 private function getForecast()
 {
     $url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q=Cebu%20City&mode=json&units=metric&cnt=7';
     // 1717512 = Cebu City
     $weather_service = new RestfulService($url);
     $weather = $weather_service->request();
     $weather_data = json_decode($weather->getBody(), true);
     return json_encode($weather_data);
 }
示例#6
0
 /**
  * Convert an address into a latitude and longitude.
  *
  * @param  string $address The address to geocode.
  * @param  string $region  An optional two letter region code.
  * @return array An associative array with lat and lng keys.
  */
 public static function address_to_point($address, $region = null)
 {
     $service = new RestfulService(self::API_URL);
     $service->setQueryString(array('address' => $address, 'sensor' => 'false', 'region' => $region));
     $response = $service->request()->simpleXML();
     if ($response->status != 'OK') {
         return false;
     }
     $location = $response->result->geometry->location;
     return array('lat' => (double) $location->lat, 'lng' => (double) $location->lng);
 }
 function embed(array $arguments)
 {
     $rest = new RestfulService("http://noembed.com/embed?url=" . urlencode($arguments['link']));
     $request = $rest->request();
     $php = json_decode($request->getBody());
     if (class_exists(ArrayList)) {
         return new ArrayList($php);
     } else {
         return new ArrayData($php);
     }
 }
 /**
  * Tell Facebook to re-scrape this URL, if it is accessible to the public
  * 
  * @return RestfulService_Response
  */
 public function clearFacebookCache()
 {
     if ($this->owner->hasMethod('AbsoluteLink')) {
         $anonymousUser = new Member();
         if ($this->owner->can("View", $anonymousUser)) {
             $fetch = new RestfulService('https://graph.facebook.com/');
             $fetch->setQueryString(array('id' => $this->owner->AbsoluteLink(), 'scrape' => true));
             return $fetch->request();
         }
     }
 }
 public function GetMemberFromAPI()
 {
     //make connection
     $expiry = 1;
     $fetch = new RestfulService('https://randomuser.me/api/', $expiry);
     //make request
     $results = $fetch->request();
     //decode request
     $results_decoded = json_decode($results->getBody());
     //if there is a response
     return $results_decoded;
 }
 function RssItems($limit = 10)
 {
     $feed = new RestfulService('http://pipes.yahoo.com/pipes/pipe.run?_id=7479b77882a68cdf5a7143374b51cf30&_render=rss', 7200);
     $feedXML = $feed->request()->getBody();
     // Extract items from feed
     $result = $feed->getValues($feedXML, 'channel', 'item');
     foreach ($result as $item) {
         $item->pubDate = date("D, M jS Y", strtotime($item->pubDate));
     }
     // Return items up to limit
     return $result->getRange(0, $limit);
 }
	function testPostData() {
		$connection = new RestfulService(Director::absoluteBaseURL(), 0);
		$test1params = array(
			'test1a' => mktime(),
			'test1b' => mt_rand(),
			'test1c' => 'And now for a string test'
		);
		$test1 = $connection->request('RestfulServiceTest_Controller/?usetestmanifest=1&flush=1', 'POST', $test1params)->getBody();
		foreach ($test1params as $key => $value) {
			$this->assertContains("<request_item name=\"$key\">$value</request_item>", $test1);
			$this->assertContains("<post_item name=\"$key\">$value</post_item>", $test1);
		}
	}
 public function _write($event)
 {
     if (!$this->_formatter) {
         $formatter = new LogErrorBugzScoutFormatter();
         $this->setFormatter($formatter);
     }
     $formattedData = $this->_formatter->format($event);
     $this->description = $formattedData['subject'];
     $this->extra = $formattedData['data'];
     $cache_expiry = 1;
     $request = new RestfulService($this->host . "/scoutSubmit.asp", $cache_expiry);
     $params = array('ScoutUserName' => $this->scoutUserName, 'ScoutProject' => $this->scoutProject, 'ScoutArea' => $this->scoutArea, 'Description' => $this->description, 'Extra' => $this->extra);
     $conn = $request->request(null, 'POST', $params, null, array(CURLOPT_CONNECTTIMEOUT => 10));
 }
 public function get($address)
 {
     $query = array('address' => $address, 'key' => $_ENV['GOOGLE_API_KEY']);
     $service = new RestfulService(self::BASE_URL, 60);
     $service->checkErrors = false;
     $service->setQueryString($query);
     $res = $service->request();
     $data = json_decode($res->getBody(), true);
     if (!isset($data['status']) || $data['status'] !== "OK") {
         return false;
     } else {
         return $data['results']['0'];
     }
 }
示例#14
0
 private function callAPI($data)
 {
     $config = $this->getConfig();
     $authentication = $config['authentication'];
     $endpoint = $config['endpoint'];
     $auth = array('USER' => $authentication['username'], 'PWD' => $authentication['password'], 'SIGNATURE' => $authentication['signature']);
     $data = array_merge($auth, $data);
     $conn = new RestfulService($endpoint, 0);
     //REST connection that will expire immediately
     $conn->httpHeader('Accept: application/xml');
     $conn->httpHeader('Content-Type: application/x-www-form-urlencoded');
     $response = $conn->request('', 'POST', http_build_query($data));
     return $response;
 }
 /**
  * Convert an address into a latitude and longitude.
  *
  * @param string $address The address to geocode.
  * @param string $region  An optional two letter region code.
  * @return array An associative array with lat and lng keys.
  */
 public static function address_to_point($address, $region = null)
 {
     // Get the URL for the Google API
     $url = Config::inst()->get('GoogleGeocoding', 'google_api_url');
     $key = Config::inst()->get('GoogleGeocoding', 'google_api_key');
     // Query the Google API
     $service = new RestfulService($url);
     $service->setQueryString(array('address' => $address, 'sensor' => 'false', 'region' => $region, 'key' => $key));
     $response = $service->request()->simpleXML();
     if ($response->status != 'OK') {
         return false;
     }
     $location = $response->result->geometry->location;
     return array('lat' => (double) $location->lat, 'lng' => (double) $location->lng);
 }
 public function send($id, $mql, $debug = false)
 {
     if ($debug) {
         error_log('Sending MQL to Freebase for id ' . $id);
     }
     return parent::send(self::SERVICE_BASE_URI . $mql, null, $debug);
 }
 function __construct()
 {
     if (!self::$username || !self::$apiKey) {
         user_error('Bitly username and api key not supplied.', E_USER_WARNING);
     }
     parent::__construct(self::$address);
 }
示例#18
0
	/**
	 * Sets default proxy settings for outbound RestfulService connections
	 *
	 * @param string $proxy The URL of the proxy to use.
	 * @param int $port Proxy port
	 * @param string $user The proxy auth user name
	 * @param string $password The proxy auth password
	 * @param boolean $socks Set true to use socks5 proxy instead of http
	 */
	static function set_default_proxy($proxy, $port = 80, $user = "", $password = "", $socks = false) {
		self::$default_proxy = array(
			CURLOPT_PROXY => $proxy,
			CURLOPT_PROXYUSERPWD => "{$user}:{$password}",
			CURLOPT_PROXYPORT => $port,
			CURLOPT_PROXYTYPE => ($socks ? CURLPROXY_SOCKS5 : CURLPROXY_HTTP)
		);
	}
示例#19
0
 public function randomUser()
 {
     //Create a new restful service with APi webservice link - aggregate data
     $service = new RestfulService('https://randomuser.me/api/');
     //sending request
     $response = $service->request('');
     // 200 OK -The request has succeeded
     if ($response && $response->getStatusCode() == 200) {
         // json_decode returns a PHP array of objects,
         $data = json_decode($response->getBody());
         // Array data structure consisting of a collection of elements
         // put data into array data ready for template
         $randomUser = new ArrayData($data->results[0]->user);
     }
     //return the data - put in template - template to show in front end
     return $randomUser;
 }
 /**
  * Makes a request to the RESTful server, and return a {@link RestfulService_Response} object for parsing of the result.
  * @return {VidyardService_Response} If curl request produces error, the returned response's status code will be 500
  */
 public function request($subURL = '', $method = 'GET', $data = null, $headers = null, $curlOptions = array())
 {
     $finalHeaders = array('Accept: application/json');
     if (is_array($headers)) {
         $finalHeaders = array_merge($headers, $finalHeaders);
     }
     return parent::request($subURL, $method, $data, $finalHeaders, $curlOptions);
 }
示例#21
0
 function ImportSpeakersFromSched()
 {
     $feed = new RestfulService('http://openstacksummitoctober2015tokyo.sched.org/api/role/export?api_key=47dfbdc49d82ff16669df259952656fa&role=speaker&format=xml&fields=username,name,email', 7200);
     $feedXML = $feed->request()->getBody();
     $feedXML = preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $feedXML);
     $results = $feed->getValues($feedXML, 'speaker');
     // A new import overwrites previous data.
     // The table is trucated to remove previous entries and avoid duplicates.
     DB::Query("TRUNCATE SchedSpeaker");
     foreach ($results as $item) {
         $Speaker = new SchedSpeaker();
         $Speaker->username = $item->username;
         $Speaker->email = $item->email;
         $Speaker->name = $item->name;
         $Speaker->write();
     }
     echo "Speakers imported successfully.";
 }
 public function send($text, $format = null, $debug = false)
 {
     $format = is_null($format) ? $this->format : $format;
     $params = $this->prepare($text, $format, $debug);
     if ($debug) {
         error_log('Sending text to Zemanta for analysis in ' . $format . ' format');
     }
     return parent::send(self::SERVICE_BASE_URI, $params, $debug);
 }
 public function getEvents($calendarId = '*****@*****.**', $options = array())
 {
     $detaults = array('key' => $_ENV['GOOGLE_API_KEY'], 'maxResults' => 1000, 'singleEvents' => 'true', 'orderBy' => 'startTime', 'timeMax' => date(DateTime::RFC3339, strtotime('+90 days')), 'timeMin' => date(DateTime::RFC3339, strtotime('-1 day')), 'pageToken' => null);
     $query = array_merge($detaults, $options);
     // Remove null values
     foreach ($query as $key => $value) {
         if ($value === null) {
             unset($query[$key]);
         }
     }
     $url = self::BASE_URL . "{$calendarId}/events";
     $service = new RestfulService($url, 60);
     $service->checkErrors = false;
     $service->setQueryString($query);
     $res = $service->request();
     $data = Convert::json2array($res->getBody());
     return $data;
 }
示例#24
0
 public function process($data)
 {
     //parent::process($data);
     $authentication = self::get_authentication();
     $this->postData = array();
     $this->postData['USER'] = $authentication['username'];
     $this->postData['PWD'] = $authentication['password'];
     $this->postData['SIGNATURE'] = $authentication['signature'];
     // $this->postData['VERSION'] = self::PAYPAL_VERSION;
     // $this->postData['VERSION'] = '64';
     $this->postData['VERSION'] = '72.0';
     $this->postData['PAYMENTACTION'] = self::get_action();
     // $this->postData['AMT'] = $data['Amount'];
     // $this->postData['CURRENCY'] = $data['Currency'];
     $this->postData['PAYMENTREQUEST_0_AMT'] = $data['Amount'];
     $this->postData['PAYMENTREQUEST_0_CURRENCYCODE'] = $data['Currency'];
     $this->postData['METHOD'] = 'SetExpressCheckout';
     $this->postData['RETURNURL'] = $this->returnURL;
     $this->postData['CANCELURL'] = $this->returnURL;
     SS_Log::log(new Exception(print_r($this->postData, true)), SS_Log::NOTICE);
     $paystation = new RestfulService(self::get_url(), 0);
     //REST connection that will expire immediately
     $paystation->httpHeader('Accept: application/xml');
     $paystation->httpHeader('Content-Type: application/x-www-form-urlencoded');
     $response = $paystation->request('', 'POST', http_build_query($this->postData));
     // $endpoint = self::get_url();
     // $data = http_build_query($this->postData);
     // $service = new RestfulService($endpoint);
     // $response = $service->request(null, 'POST', $this->postData);
     //$response = $this->postPaymentData($this->postData);
     SS_Log::log(new Exception(print_r($response, true)), SS_Log::NOTICE);
     if ($response->getStatusCode() != '200') {
         return new PaymentGateway_Failure($response);
     } else {
         if ($token = $this->getToken($response)) {
             // If Authorization successful, redirect to PayPal to complete the payment
             Controller::curr()->redirect(self::get_paypal_redirect_url() . "?cmd=_express-checkout&token={$token}");
         } else {
             // Otherwise, return failure message
             $errorList = $this->getErrors($response);
             return new PaymentGateway_Failure(null, null, $errorList);
         }
     }
 }
 public function __construct($sub = false, $header = null, $expiry = -1)
 {
     parent::__construct('https://api.instagram.com/', $expiry);
     $this->clientID = Config::inst()->get('Instagram', 'clientID');
     $this->clientSecret = Config::inst()->get('Instagram', 'clientSecret');
     $this->config = SiteConfig::current_site_config();
     if ($sub) {
         $this->access_token = $sub->AccessToken;
     } else {
         $this->access_token = false;
     }
 }
 public function setQueryString($params = NULL)
 {
     /*
      * Required API GET params
      */
     $req = array('pshid' => $this->pshid, 'jbd' => $this->jbd, 'ssty' => 2, 'cflg' => 'r', 'clip' => $_SERVER['REMOTE_ADDR']);
     if ($params) {
         $params = array_merge($req, $params);
     } else {
         $params = $req;
     }
     parent::setQueryString($params);
 }
 private function updateModuleIndex()
 {
     $modules = StreamLineSiteStatusModule::get();
     $base_url = 'https://api.github.com/repos/';
     foreach ($modules as $module) {
         preg_match('#https:\\/\\/github.com\\/([^\\.]+)\\.git#', $module->Git, $matches);
         $url = $base_url . $matches[1];
         $client = new RestfulService($url);
         $tag_request = $client->request('/tags', 'GET');
         $tags = json_decode($tag_request->getBody(), true);
         $versions = array();
         foreach ($tags as $tag) {
             $versions[] = $tag['name'];
         }
         $latest_version = null;
         foreach ($versions as $version) {
             if (!preg_match('#(alpha|beta|rc|dev|a|b)#', $version)) {
                 $version = preg_replace('#(patch[0-9]+)#', '', $version);
                 $version = str_replace(array('-', 'v'), '', $version);
                 if (version_compare($version, $module->CurrentVersion, '>')) {
                     if (empty($latest_version)) {
                         $latest_version = $version;
                     } else {
                         if (version_compare($version, $latest_version, '>')) {
                             $latest_version = $version;
                         }
                     }
                 }
             }
         }
         if (empty($latest_version)) {
             $latest_version = $module->CurrentVersion;
         }
         $module->LatestVersion = $latest_version;
         $module->UpToDate = $module->CurrentVersion == $module->LatestVersion ? true : false;
         $module->write();
     }
 }
 public function __construct()
 {
     if (!$this->prepared) {
         if (!defined('YOUTUBE_API_KEY')) {
             define('YOUTUBE_API_KEY', SiteConfig::current_site_config()->YoutubeApiKey);
         }
         if (YOUTUBE_API_KEY == '') {
             user_error('Please specify a valid Youtube Api Key in the site config.', E_USER_ERROR);
         }
         // Create the service
         $this->service = RestfulService::create('https://www.googleapis.com/youtube/v3/');
         $this->prepared = true;
     }
 }
 public function getLicenceText()
 {
     $licence = $this->owner->Licence()->URI;
     if (!$licence) {
         $licence = SiteConfig::current_site_config()->Licence()->URI;
     }
     $licence_url = $this->owner->config()->get('api_url') . $this->owner->config()->get('api_version') . '/details?license-uri=' . $licence;
     $expiry = 7 * (24 * 60 * 60);
     $request = RestfulService::create($licence_url, $expiry)->request()->getBody();
     $pattern = "/<html ?.*>(.*)<\\/html>/";
     preg_match($pattern, $request, $matches);
     if ($matches) {
         return $matches[0];
     }
 }
示例#30
0
 function request($url = '', $format = 'xml', $params = null, $method = "GET", $data = null, $headers = null)
 {
     $query_string_params = array();
     // add additional parameters if necessary
     if (!is_null($params) && is_array($params)) {
         $query_string_params = $params;
     }
     // set proper format request
     if ($this->format_as_extension) {
         $this->baseURL .= '.' . $format;
     } else {
         $query_string_params['format'] = $format;
     }
     // add the url as parameter, oembed-style
     $query_string_params['url'] = $url;
     $this->setQueryString($query_string_params);
     return parent::request('', $method, $data, $headers);
 }