function testGetData() { $connection = new RestfulService(Director::absoluteBaseURL()); $test1params = array('test1a' => 4352655636.76543, 'test1b' => '$&+,/:;=?@#"\'%', 'test1c' => 'And now for a string test'); $connection->setQueryString($test1params); $test1 = $connection->request('RestfulServiceTest_Controller?usetestmanifest=1&flush=1')->getBody(); foreach ($test1params as $key => $value) { $this->assertContains("<request_item name=\"{$key}\">{$value}</request_item>", $test1); $this->assertContains("<get_item name=\"{$key}\">{$value}</get_item>", $test1); } $connection->setQueryString(array()); $test2params = array('test2a' => 767545678.76887, 'test2b' => '%\'"@?=;:/,$', 'test2c' => 'And now for a string test'); $test2suburl = 'RestfulServiceTest_Controller/?usetestmanifest=1&flush=1&'; foreach ($test2params as $key => $value) { $test2suburl .= "{$key}={$value}&"; } $test2suburl = substr($test2suburl, 0, -1); $test2 = $connection->request($test2suburl)->getBody(); foreach ($test2params as $key => $value) { $this->assertContains("<request_item name=\"{$key}\">{$value}</request_item>", $test2); $this->assertContains("<get_item name=\"{$key}\">{$value}</get_item>", $test2); } $test3params = array_merge($test1params, $test2params); // We want to check using setQueryString() and hard coded $connection->setQueryString($test1params); $test3 = $connection->request($test2suburl)->getBody(); foreach ($test3params as $key => $value) { $this->assertContains("<request_item name=\"{$key}\">{$value}</request_item>", $test3); $this->assertContains("<get_item name=\"{$key}\">{$value}</get_item>", $test3); } }
/** * 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()); }
/** * 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); }
/** * 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); }
/** * 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 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); }
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']; } }
/** * 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 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; }
/** * Check we can add query strings all over the shop and it's ok */ public function testGetAbsoluteURLQueries() { $restWithoutSlash = new RestfulService('http://example.com?b=query2'); $restWithSlash = new RestfulService('http://example.com/?b=query2'); $restWithQuery = new RestfulService('http://example.com/?b=query2'); $restWithQuery->setQueryString(array('c' => 'query3')); $this->assertEquals('http://example.com/url?b=query2&a=query1', $restWithoutSlash->getAbsoluteRequestURL('url?a=query1')); $this->assertEquals('http://example.com/url?b=query2&a=query1', $restWithSlash->getAbsoluteRequestURL('url?a=query1')); $this->assertEquals('http://example.com/url?b=query2&a=query1&c=query3', $restWithQuery->getAbsoluteRequestURL('url?a=query1')); $this->assertEquals('http://example.com/url?b=query2', $restWithoutSlash->getAbsoluteRequestURL('url')); $this->assertEquals('http://example.com/url?b=query2', $restWithSlash->getAbsoluteRequestURL('url')); $this->assertEquals('http://example.com/url?b=query2&c=query3', $restWithQuery->getAbsoluteRequestURL('url')); $restWithoutSlash = new RestfulService('http://example.com'); $restWithSlash = new RestfulService('http://example.com/'); $restWithQuery = new RestfulService('http://example.com/'); $restWithQuery->setQueryString(array('c' => 'query3')); $this->assertEquals('http://example.com/url?a=query1', $restWithoutSlash->getAbsoluteRequestURL('url?a=query1')); $this->assertEquals('http://example.com/url?a=query1', $restWithSlash->getAbsoluteRequestURL('url?a=query1')); $this->assertEquals('http://example.com/url?a=query1&c=query3', $restWithQuery->getAbsoluteRequestURL('url?a=query1')); $this->assertEquals('http://example.com/url', $restWithoutSlash->getAbsoluteRequestURL('url')); $this->assertEquals('http://example.com/url', $restWithSlash->getAbsoluteRequestURL('url')); $this->assertEquals('http://example.com/url?c=query3', $restWithQuery->getAbsoluteRequestURL('url')); }
public function check() { $OdeonCinemaID = (int) $this->request->param("ID"); if ($OdeonCinemaID) { if ($this->OdeonCinema = OdeonCinema::get_by_id("OdeonCinema", $OdeonCinemaID)) { $this->OdeonCinema->getCurrentFilms(); $OdeonFilmID = (int) $this->request->param("OtherID"); if ($OdeonFilmID) { if ($this->OdeonFilm = OdeonFilm::get_by_id("OdeonFilm", $OdeonFilmID)) { $maxdays = 15; $baseURL = "https://www.odeon.co.uk/"; $date = new Date(); $RestfulService = new RestfulService($baseURL); $i = 0; do { $date->setValue("+{$i} day"); if (!OdeonScreening::get("OdeonScreening", implode(" AND ", array("DATE_FORMAT(ScreeningTime,'%d%m%y') = '{$date->Format("dmy")}'", "FilmID='{$OdeonFilmID}'", "CinemaID='{$OdeonCinemaID}'")))->Count()) { $query = array('date' => $date->Format("Y-m-d"), 'siteId' => $OdeonCinemaID, 'filmMasterId' => $OdeonFilmID, 'type' => 'DAY'); $RestfulService->setQueryString($query); $Response = $RestfulService->request("showtimes/day"); if (!$Response->isError()) { $html = HtmlDomParser::str_get_html($Response->getBody()); foreach ($html->find('ul') as $ul) { foreach ($ul->find('li') as $li) { $ScreeningTime = new SS_Datetime(); $ScreeningTime->setValue("{$date->Format("Y-m-d")} {$li->find('a', 0)->innertext}:00"); $checkAgainstAPI = true; if ($OdeonScreening = OdeonScreening::get_one("OdeonScreening", implode(" AND ", array("CinemaID='{$OdeonCinemaID}'", "FilmID='{$OdeonFilmID}'", "ScreeningTime='{$ScreeningTime->Rfc2822()}'")))) { $checkAgainstAPI = $OdeonScreening->checkAgainstAPI(); } else { $OdeonScreening = new OdeonScreening(); $OdeonScreening->CinemaID = $OdeonCinemaID; $OdeonScreening->FilmID = $OdeonFilmID; $OdeonScreening->ScreeningTime = $ScreeningTime->Rfc2822(); } if ($checkAgainstAPI) { $URLSegment = str_replace($baseURL, "", $li->find('a', 0)->href); $Response_init = $RestfulService->request($URLSegment, "GET", null, null, array(CURLOPT_COOKIESESSION => TRUE)); if (!$Response_init->isError()) { $dom = new DOMDocument(); $dom->strictErrorChecking = FALSE; libxml_use_internal_errors(true); $dom->loadHTML($Response_init->getBody()); libxml_clear_errors(); $nodes = $dom->getElementsByTagName('form'); $submit_url = false; $hidden_inputs = array(); foreach ($nodes as $node) { if (!$submit_url && $node->hasAttributes()) { foreach ($node->attributes as $attribute) { if (!$submit_url && $attribute->nodeName == 'action') { $submit_url = $attribute->nodeValue; } } } } unset($node); $SubmitURL = ltrim($submit_url, '/'); $Cookies = $Response_init->getHeader("Set-Cookie"); if (is_array($Cookies)) { $Cookies = implode(';', $Cookies); } $Response_availability = $RestfulService->request($SubmitURL, "GET", null, null, array(CURLOPT_COOKIE => $Cookies)); if (!$Response_availability->isError()) { $html_availability = HtmlDomParser::str_get_html($Response_availability->getBody()); $ticketsTable = $html_availability->find('#tickets-table', 0); if ($ticketsTable) { $ticketsForm = $html_availability->find('#tickets', 0); $data = array("submit" => null); foreach ($ticketsTable->find('select') as $select) { $data[$select->attr["name"]] = "0"; } foreach ($ticketsTable->find('tr') as $tr) { foreach ($tr->find('td') as $td) { switch ($td->getAttribute("class")) { case "ticket-col": $OdeonScreening->Title = trim($td->innertext); break; case "price-col": $OdeonScreening->Cost = ltrim(explode(" ", trim($td->plaintext))[0], '£'); break; case "quantity-col": $Availability = 1; foreach ($td->find('select') as $select) { foreach ($select->find('option') as $option) { $Availability = $option->attr["value"]; } $data[$select->attr["name"]] = $Availability; } $Response_seats = $RestfulService->request(ltrim(html_entity_decode($ticketsForm->attr['action']), "/"), "POST", $data, null, array(CURLOPT_COOKIE => $Cookies)); if (!$Response_seats->isError()) { $html_seats = HtmlDomParser::str_get_html($Response_seats->getBody()); if (trim($html_seats->find('.step-headline', 0)->innertext) == "Choose your seats") { $OdeonScreening->Availability = $Availability; $OdeonScreening->SessionURL = $URLSegment; $OdeonScreening->duplicate(); } } break; } } } } } } } } } } else { Debug::show($query); Debug::show($Response); } } $i++; } while ($i < $maxdays); } else { echo "Not a valid film ID"; } } } else { echo "Not a valid cinema ID"; } } return $this; }
/** * Calls Pardot_API and returns response. * * Checks if this object has required properties for authentication. If yes and not authenticated, authenticates. * Next, build the API user and calls the API. On error, attempt to authenticate to retrieve a new API key unless * this is an authentication request, to avoid infinite loops. If reauthenticated and $args['new_api_key'] is a valid * callback then callsback with new API key so caller can store it. * * @param string $item_type One of 'login', 'account', 'campaign' or 'form'. * @param array $args Query arguments (but might contain ignored auth arguments. * @param string $property Property to retrieve; defaults to 'result' but can be 'api_key' or 'account'. * @return bool|SimpleXMLElement Returns API response as a SimpleXMLElement if successful, false if API call fails. * * @since 1.0.0 */ function get_response($item_type, $args = array(), $property = 'result', $paged = 1) { $this->error = false; if (!$this->has_auth()) { error_log("no auth"); $this->error = 'Cannot authenticate. No email, password or user_key assigned.'; return false; } if (!$this->api_key && 'login' != $item_type) { $this->authenticate($args); } $args = array_merge($args, array('user_key' => $this->user_key, 'api_key' => $this->api_key, 'offset' => $paged > 1 ? ($paged - 1) * 200 : 0)); $http_request = new RestfulService($this->_get_url($item_type, $args)); $http_request->setQueryString(array_merge(array('timeout' => '30', 'redirection' => '5', 'method' => 'POST', 'blocking' => true, 'compress' => false, 'decompress' => true, 'sslverify' => false, 'body' => $args), $args)); $connect = $http_request->request(); if (isset($args['email'])) { $args['email'] = urlencode($args['email']); } if (isset($args['password'])) { $args['password'] = base64_encode($args['password']); } $response = false; if ($connect->getStatusCode() == 200) { $response = new SimpleXMLElement($connect->getBody()); if (!empty($response->err)) { $this->error = $response->err; if ('login' == $item_type) { $this->api_key = false; } else { $auth = $this->get_auth(); if (isset($args['new_api_key'])) { $this->api_key_maybe_invalidated = true; $auth['new_api_key'] = $args['new_api_key']; } if ($this->authenticate($auth)) { /** * Try again after a successful authentication */ $response = $this->get_response($item_type, $args, $property, true); if ($response) { $this->error = false; } } } } if ($this->error) { $response = false; } if ($response && empty($response->{$property})) { $response = false; $this->error = "HTTP Response did not contain property: {$property}."; } if ($response && $this->api_key_maybe_invalidated && 'login' == $item_type && 'api_key' == $property) { if (isset($args['new_api_key']) && is_callable($args['new_api_key'])) { call_user_func($args['new_api_key'], (string) $response->api_key); $this->api_key_maybe_invalidated = false; } } } return $response; }
protected static function getService($url, $banExpression) { // prepare API call $service = new RestfulService($url, 0); // set basic auth $username = Config::inst()->get('SectionIO', 'username'); $password = Config::inst()->get('SectionIO', 'password'); $service->basicAuth($username, $password); // set query string (ban expression) $service->setQueryString(array('banExpression' => $banExpression)); return $service; }
/** * @return array */ private function request($apiURLPostfix, $params) { $service = new RestfulService($this->endpoint, 1800); $service->setQueryString($params); $response = $service->request($apiURLPostfix); if ($response->isError()) { user_error(__CLASS__ . ' error with response. -- ' . $response->getBody(), E_USER_WARNING); return null; } $data = json_decode($response->getBody()); if (!isset($data->list)) { user_error(__CLASS__ . ' is missing list property from json feed.', E_USER_WARNING); return null; } if (!is_array($data->list)) { user_error(__CLASS__ . ' expected "list" property from json feed to be an array.', E_USER_WARNING); return null; } //$data->response = $response; // Debug return $data; }
function complete() { //TODO: check that request came from paystation.co.nz if (isset($_REQUEST['ec'])) { if (isset($_REQUEST['ms'])) { $payid = (int) substr($_REQUEST['ms'], strpos($_REQUEST['ms'], '-') + 1); //extract PaystationPayment ID off the end if ($payment = DataObject::get_by_id('PaystationHostedPaymentBurnbright', $payid)) { $payment->Status = $_REQUEST['ec'] == '0' ? 'Success' : 'Failure'; if ($_REQUEST['ti']) { $payment->TransactionID = $_REQUEST['ti']; } if ($_REQUEST['em']) { $payment->Message = $_REQUEST['em']; } $this->Status = 'Success'; //Quick Lookup if (self::$usequicklookup) { $paystation = new RestfulService(self::$quicklookupurl, 0); //REST connection that will expire immediately $paystation->httpHeader('Accept: application/xml'); $paystation->httpHeader('Content-Type: application/x-www-form-urlencoded'); $data = array('pi' => PaystationHostedPaymentBurnbright::get_paystation_id(), 'ms' => $_REQUEST['ms']); $paystation->setQueryString($data); $response = $paystation->request(null, 'GET'); $sxml = $response->simpleXML(); echo "<br/>"; if ($sxml && ($s = $sxml->LookupResponse)) { //check transaction ID matches if ($payment->TransactionID != (string) $s->PaystationTransactionID) { $payment->Status = "Failure"; $payment->Message .= "The transaction ID didn't match."; } //check amount matches if ($payment->Amount * 100 != (int) $s->PurchaseAmount) { $payment->Status = "Failure"; $payment->Message .= "The purchase amount was inconsistent."; } //check session ID matches if (session_id() != substr($_REQUEST['ms'], 0, strpos($_REQUEST['ms'], '-'))) { $payment->Status = "Failure"; $payment->Message .= "Session id didn't match."; } //TODO: extra - check IP address against $payment->IP?? } elseif ($sxml && ($s = $sxml->LookupStatus)) { $payment->Status = "Failure"; $payment->Message .= $s->LookupMessage; } else { //falied connection? $payment->Status = "Failure"; $payment->Message .= "Paystation quick lookup failed."; } } $payment->write(); $payment->redirectToReturnURL(); return; } else { user_error('There is no any Paystation payment which ID is #' . $payid, E_USER_ERROR); } } else { user_error('There is no any Paystation hosted payment ID specified', E_USER_ERROR); } } else { user_error('There is no any Paystation hosted payment error code specified', E_USER_ERROR); } //TODO: sawp errors for payment failures?? }
/** * Get updates from the remote systems */ public function getUpdates() { $config = SiteConfig::current_site_config(); $systemId = $config->getSyncroIdentifier(); $nodes = RestrictedList::create('RemoteSyncroNode')->filter('Enabled', 1)->requirePerm('View'); foreach ($nodes as $node) { $url = $node->NodeURL . self::SERVICE_URL; $lastSync = $node->LastSync ? $node->LastSync : '2012-01-01 00:00:00'; $params = array('token' => $node->APIToken, 'since' => $lastSync, 'system' => $systemId, 'rand' => date('Y-m-d-H-i')); $svc = new RestfulService($url, -1); $svc->setQueryString($params); $response = $svc->request(); if ($response->isError()) { // log and proceed return; throw new Exception("Request failed to {$url}"); } $response = $response->getBody(); if (is_string($response) && strlen($response)) { $data = json_decode($response); if ($data && is_array($data->response)) { $this->log->logInfo("Loading " . count($data->response) . " objects from " . $node->NodeURL); $this->processUpdateData($data->response, $node); } } } }
/** * Get information about the current movie to display. * Uses the OMDb API indirectly through the {@link MovieInformation->getInfo} function which * returns the XML body. * * Gets the rotten tomato information as well as the IMDb information. Also obtains both the * short and long version of the plot (at the expense of another query). In future this could * become configurable. * * @return ArrayData The information about the current pages movie */ public function getInfo() { // This will get us XML body to play with as well as testing validity $body = $this->isValid(); if ($body === false) { throw new SS_HTTPResponse_Exception(ErrorPage::response_for(404), 404); } $api = new RestfulService('http://www.omdbapi.com/'); $results = $api->getAttributes($body, 'movie'); $return = $results[0]; // Get short plot as well $api->setQueryString(array('r' => 'xml', 'type' => 'movie', 't' => $this->Title, 'plot' => 'short', 'v' => 1)); $results = $api->request(); $results = $api->getAttributes($results->getBody(), 'movie'); if ($results && !empty($results)) { $results = $results[0]; $return->setField('shortPlot', $results->getField('plot')); } return $return; }