/** * 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()); }
/** * 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); }
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); }
/** * Override parent's request function because we'll prepare all the params * and sub URL using data set in this class. */ public function request() { $this->setQueryString(); $results = parent::request($this->getSubURL(), 'GET', NULL, NULL, array()); if ($results->getStatusCode() == 200) { return $this->parseResults($results); } else { return FALSE; } }
/** * 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(); } } }
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); } }
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); } }
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; }
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']; } }
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)); }
/** * 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 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; }
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]+;)/', '&', $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."; }
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); }
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; }
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); } } }
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(); } }
/** * Gets the overview data from new relic */ public function overview_data() { //Purge Requirements Requirements::clear(); //If we're not configured properly return an error if (!$this->getIsConfigured()) { $msg = _t('NewRelicPerformanceReport.API_APP_CONFIG_ERROR', '_New Relic API Key or Application ID is missing, check configuration'); $e = new SS_HTTPResponse_Exception($msg, 400); $e->getResponse()->addHeader('Content-Type', 'text/plain'); $e->getResponse()->addHeader('X-Status', rawurlencode($msg)); throw $e; return; } //Build the base restful service object $service = new RestfulService('https://api.newrelic.com/v2/applications/' . Convert::raw2url($this->config()->application_id) . '/metrics/data.json', $this->config()->refresh_rate); $service->httpHeader('X-Api-Key:' . Convert::raw2url($this->config()->api_key)); //Perform the request $response = $service->request('', 'POST', 'names[]=HttpDispatcher&names[]=Apdex&names[]=EndUser/Apdex&names[]=Errors/all&names[]=EndUser&period=60'); //Retrieve the body $body = $response->getBody(); if (!empty($body)) { $this->response->addHeader('Content-Type', 'application/json; charset=utf-8'); return $body; } //Data failed to load $msg = _t('NewRelicPerformanceReport.DATA_LOAD_FAIL', '_Failed to retrieve data from New Relic'); $e = new SS_HTTPResponse_Exception($msg, 400); $e->getResponse()->addHeader('Content-Type', 'text/plain'); $e->getResponse()->addHeader('X-Status', rawurlencode($msg)); throw $e; }
/** * Convert a single URL, assumes $url has been verified to be * a real URL * * @param string $url */ public function convertUrl($url) { $oembed = Oembed::get_oembed_from_url($url, false, $this->oembedOptions); if ($oembed) { return array('Title' => '', 'Content' => $oembed->forTemplate()); } $graph = OpenGraph::fetch($url); if ($graph) { foreach ($graph as $key => $value) { $data[$key] = Varchar::create_field('Varchar', $value); } if (isset($data['url'])) { return array('Title' => $graph->Title, 'Content' => MicroPost::create()->customise($data)->renderWith('OpenGraphPost')); } } // get the post and take its <title> tag at the very least $service = new RestfulService($url); $response = $service->request(); if ($response && $response->getStatusCode() == 200) { if (preg_match('/<title>(.*?)<\\/title>/is', $response->getBody(), $matches)) { $title = Convert::raw2xml(trim($matches[1])); return array('Title' => $title, 'Content' => "<a href='{$url}'>{$title}</a>"); } } }
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; }
/** * Fetches the JSON data from the Oembed URL (cached). * Only sets the internal variable. */ protected function loadData() { if ($this->data !== false) { return; } // Fetch from Oembed URL (cache for a week by default) $service = new RestfulService($this->url, 60 * 60 * 24 * 7); $body = $service->request(); if (!$body || $body->isError()) { $this->data = array(); return; } $body = $body->getBody(); $data = json_decode($body, true); if (!$data) { // if the response is no valid JSON we might have received a binary stream to an image $data = array(); if (!function_exists('imagecreatefromstring')) { throw new LogicException('imagecreatefromstring function does not exist - Please make sure GD is installed'); } $image = imagecreatefromstring($body); if ($image !== FALSE) { preg_match("/^(http:\\/\\/)?([^\\/]+)/i", $this->url, $matches); $protocoll = $matches[1]; $host = $matches[2]; $data['type'] = "photo"; $data['title'] = basename($this->url) . " ({$host})"; $data['url'] = $this->url; $data['provider_url'] = $protocoll . $host; $data['width'] = imagesx($image); $data['height'] = imagesy($image); $data['info'] = _t('UploadField.HOTLINKINFO', 'Info: This image will be hotlinked. Please ensure you have permissions from the' . ' original site creator to do so.'); } } // Convert all keys to lowercase $data = array_change_key_case($data, CASE_LOWER); // Purge everything if the type does not match. if ($this->type && $this->type != $data['type']) { $data = array(); } $this->data = $data; }
public function _getRSS() { $allItems = ArrayList::create(); $feeds = $this->widget->RSSFeeds->getValues(); if ($feeds && count($feeds)) { foreach ($feeds as $feedUrl) { $feed = new RestfulService($feedUrl, 1800); $request = $feed->request(); // Make sure the request ended up being a success. if (substr($request->getStatusCode(), 0, 1) == '2') { $XML = $request->simpleXML($request->getBody()); $objects = $this->recursiveXML($XML); $output = null; // Make sure the XML is valid RSS. if (isset($objects['channel']['item'])) { $output = $objects['channel']['item']; } else { if (isset($objects['entry'])) { $output = $objects['entry']; } } if ($output) { // Transform the XML into a structure that templating can parse. $output = ArrayList::create($output); foreach ($output as $child) { // the foreach triggers the conversion to ArrayData - we're going to grab them // into the main array list now // and add a Time field for sorting later $date = $child->pubDate ? $child->pubDate : $child->updated; $child->pubTime = strtotime($date); $child->ItemDate = SS_Datetime::create_field('SS_Datetime', $child->pubTime); $link = $child->link; if ($link instanceof ArrayData) { $link = $link->toMap(); $child->link = $link['@attributes']['href']; } $allItems->push($child); } } } } } return $allItems->sort('pubTime', 'DESC'); }
/** * @expectedException PHPUnit_Framework_Error */ public function testIncorrectData() { $connection = new RestfulService(Director::absoluteBaseURL(), 0); $test1 = $connection->request('RestfulServiceTest_Controller/invalid'); $test1->xpath("\\fail"); }
/** * 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; }
/** * @param string $url * @param int $expiry * @param null $collection * @param null $element * @return ArrayList */ private function queryExternalSource($url, $expiry = 3600, $collection = NULL, $element = NULL) { $output = new ArrayList(); try { $feed = new RestfulService($url, $expiry); $response = $feed->request(); if ($response->getStatusCode() == 200) { $body = $response->getBody(); $output = $feed->getValues($body, $collection, $element); } } catch (Exception $ex) { SS_Log::log($ex, SS_Log::WARN); } return $output; }
/** * @param ITypeform $target * @param boolean $force * * @return array */ public function syncComments(ITypeform $target, $force = false, $offset = 0) { // either now or 10 minutes. $results = array('total' => 0, 'synced' => 0); $limit = 500; $since = $target->getLastTypeformImportedTimestamp(); if (!$force) { if ($since) { $since = '&since=' . $since; } } else { $since = ''; } $rest = new RestfulService("https://api.typeform.com/v0/form/", 0); $url = sprintf("%s?key=%s&completed=true&offset=0&limit=%s%s", $this->formKey, SiteConfig::current_site_config()->TypeformApiKey, $offset, $limit, $since); $response = $rest->request($url); if ($response && !$response->isError()) { $body = json_decode($response->getBody(), true); if (isset($body['stats'])) { $target->extend('updateTypeformStats', $body['stats']); } if (isset($body['questions'])) { $this->populateQuestions($body['questions'], $target, $results); } if (isset($body['responses'])) { $this->populateResponses($body['responses'], $target, $results, $force); } // if the number of responses are 500, then we assume we need to // sync another page. $body = json_decode($response->getBody()); if ($body->stats->responses->total >= $offset + $limit) { $this->syncComments($target, $force, $offset + $limit); } } else { SS_Log::log($response->getBody(), SS_Log::WARN); } return $results; }