public function uploadContents($content) { if ($this->data['appkey'] === null) { throw new \InvalidArgumentException('appkey should not be null!'); } if ($this->data['timestamp'] === null) { throw new \InvalidArgumentException('timestamp should not be null!'); } if (!is_string($content)) { throw new \InvalidArgumentException('content should be a string!'); } $post = array('appkey' => $this->data['appkey'], 'timestamp' => $this->data['timestamp'], 'content' => $content); $url = $this->host . $this->uploadPath; $postBody = json_encode($post); $sign = md5('POST' . $url . $postBody . $this->appMasterSecret); $url = $url . '?sign=' . $sign; $http = new HttpClient(); $http->execute($url, $postBody); if ($http->httpCode === '0') { //time out throw new \UnexpectedValueException('Curl error number:' . $http->curlErrNo . ' , Curl error details:' . $http->curlErr . '\\r\\n'); } elseif ($http->httpCode !== '200') { //we did send the notifition out and got a non-200 response throw new \UnexpectedValueException('http code:' . $http->httpCode . PHP_EOL . ' details:' . $http->result . '\\r\\n'); } $returnData = json_decode($http->result, true); if ($returnData['ret'] === 'FAIL') { throw new \UnexpectedValueException('Failed to upload file, details:' . $http->result . '\\r\\n'); } else { $this->data['file_id'] = $returnData['data']['file_id']; } }
public function execute() { parent::execute(); $this->validateSeleniumResponseCode(); $this->validateHttpCode(); return $this->_responseBody; }
/** * Use remote Ushahidi deployments API to get Incident Data * Limit to 20 not to kill remote server */ private function _parse_json($sharing_id = NULL, $sharing_url = NULL) { if (!$sharing_id or !$sharing_url) { return false; } $timeout = 5; $limit = 20; $since_id = 0; $modified_ids = array(); // this is an array of our primary keys $more_reports_to_pull = TRUE; while ($more_reports_to_pull == TRUE) { $api_url = "/api?task=incidents&limit=" . $limit . "&resp=json&orderfield=incidentid&sort=0&by=sinceid&id=" . $since_id; $request = new HttpClient(sharing_helper::clean_url($sharing_url) . $api_url); $json = $request->execute(); $all_data = json_decode($json, false); if (!$all_data) { return false; } if (!isset($all_data->payload->incidents)) { return false; } // Parse Incidents Into Database $count = 0; foreach ($all_data->payload->incidents as $incident) { // See if this incident already exists so we can edit it $item_check = ORM::factory('sharing_incident')->where('sharing_id', $sharing_id)->where('incident_id', $incident->incident->incidentid)->find(); if ($item_check->loaded == TRUE) { $item = ORM::factory('sharing_incident', $item_check->id); } else { $item = ORM::factory('sharing_incident'); } $item->sharing_id = $sharing_id; $item->incident_id = $incident->incident->incidentid; $item->incident_title = $incident->incident->incidenttitle; $item->latitude = $incident->incident->locationlatitude; $item->longitude = $incident->incident->locationlongitude; $item->incident_date = $incident->incident->incidentdate; $item->save(); // Save the primary key of the row we touched. We will be deleting ones that weren't touched. $modified_ids[] = $item->id; // Save the highest pulled incident id so we can grab the next set from that id on $since_id = $incident->incident->incidentid; // Save count so we know if we need to pull any more reports or not $count++; } if ($count < $limit) { $more_reports_to_pull = FALSE; } } // Delete the reports that are no longer being displayed on the shared site ORM::factory('sharing_incident')->notin('id', $modified_ids)->where('sharing_id', $sharing_id)->delete_all(); }
/** * Fetches ushahidi from download.ushahidi.com * * @param String url-- download URL */ public function download_ushahidi($url) { $http_client = new HttpClient($url, 30); $results = $http_client->execute(); $this->log[] = "Starting to download the latest ushahidi build..."; if ($results) { $this->log[] = "Download of latest ushahidi went successful."; $this->success = true; return $results; } else { $this->errors[] = sprintf(Kohana::lang('libraries.upgrade_failed') . ": %d", $http_client->get_error_msg()); $this->success = false; return $results; } }
public function send() { //check the fields to make sure that they are not null $this->isComplete(); $url = $this->host . $this->postPath; $this->postBody = $postBody = json_encode($this->data); $sign = md5('POST' . $url . $postBody . $this->appMasterSecret); $url = $url . '?sign=' . $sign; $http = new HttpClient(); $http->execute($url, $postBody); if ($http->httpCode === '0') { // Time out throw new \UnexpectedValueException('Curl error number:' . $http->curlErrNo . ' , Curl error details:' . $http->curlErr . PHP_EOL); } elseif ($http->httpCode !== '200') { // We did send the notifition out and got a non-200 response throw new \UnexpectedValueException('Http code:' . $http->httpCode . PHP_EOL . ' details:' . $http->result . PHP_EOL); } else { return $http->result; } }
/** * Geonames Feeds GeoCoding (RSS to GEORSS) * Due to limitations, this returns only 20 items * * @param string location / address * @return string raw georss data */ function geocode_feed($feed_url = NULL) { $base_url = "http://" . GEOCODER_GEONAMES . "/rssToGeoRSS?"; // Only requests service if we have an user $geocode_username = Settings_Model::get_setting('feed_geolocation_user'); if ($feed_url && !empty($geocode_username)) { // First check to make sure geonames webservice is running $geonames_status = @remote::status($base_url); if ($geonames_status == "200") { // Successful $request_url = $base_url . "&feedUrl=" . urlencode($feed_url) . "&username=" . $geocode_username; } else { // Down perhaps?? Use direct feed $request_url = $feed_url; } $request = new HttpClient($request_url); if (!($georss = $request->execute($request_url))) { // If the request failed, something may be wrong with the GEOCODER_GEONAMES service return false; } //$georss = utf8_encode($georss); // Lez verify this we got a good reply from the geocoder before proceeding $data = new SimplePie(); $data->set_raw_data($georss); $data->init(); $data->handle_content_type(); // Feed no good - get outta here! if ($data->error()) { Kohana::log('error', $data->error() . $request_url); return false; } return trim($georss); } else { return false; } }
/** * Helper function to send a cURL request * @param url - URL for cURL to hit */ public function _curl_req($url) { $request = new HttpClient($url); $buffer = $request->execute(); if ($buffer === FALSE) { throw new Kohana_Exception($request->get_error_msg()); } return $buffer; }
/** * call an api endpoint. automatically adds needed authorization headers with access token or parameters * * @param string $endpoint * @param string $method default 'GET' * @param array $uriParameters optional * @param mixed $postBody optional, can be string or array * @param array $additionalHeaders * @return string */ public function callApiEndpoint($endpoint, $method = 'GET', array $uriParameters = array(), $postBody = null, array $additionalHeaders = array()) { $token = $this->_dataStore->retrieveAccessToken(); //check if token is invalid if ($token->getLifeTime() && $token->getLifeTime() < time()) { $token = $this->refreshAccessToken($token); } $parameters = null; $authorizationMethod = $this->_configuration->getAuthorizationMethod(); switch ($authorizationMethod) { case Service\Configuration::AUTHORIZATION_METHOD_HEADER: $additionalHeaders = array_merge(array('Authorization: OAuth ' . $token->getAccessToken()), $additionalHeaders); break; case Service\Configuration::AUTHORIZATION_METHOD_ALTERNATIVE: if ($method !== 'GET') { if (is_array($postBody)) { $postBody['oauth_token'] = $token->getAccessToken(); } else { $postBody .= '&oauth_token=' . urlencode($token->getAccessToken()); } } else { $uriParameters['oauth_token'] = $token->getAccessToken(); } break; default: throw new Exception("Invalid authorization method specified"); break; } if ($method !== 'GET') { if (is_array($postBody)) { $parameters = http_build_query($postBody); } else { $parameters = $postBody; } } if (!empty($uriParameters)) { $endpoint .= (strpos($endpoint, '?') !== false ? '&' : '?') . http_build_query($uriParameters); } $http = new HttpClient($endpoint, $method, $parameters, $additionalHeaders); $http->execute(); return $http->getResponse(); }
/** * Read in new layer KML via HttpClient * @param int $layer_id - ID of the new KML Layer */ public function layer($layer_id = 0) { $this->template = ""; $this->auto_render = FALSE; $layer = ORM::factory('layer')->where('layer_visible', 1)->find($layer_id); if ($layer->loaded) { $layer_url = $layer->layer_url; $layer_file = $layer->layer_file; if ($layer_url != '') { // Pull from a URL $layer_link = $layer_url; } else { // Pull from an uploaded file $layer_link = Kohana::config('upload.directory') . '/' . $layer_file; } $layer_request = new HttpClient($layer_link); $content = $layer_request->execute(); if ($content === FALSE) { throw new Kohana_Exception($layer_request->get_error_msg()); } else { echo $content; } } else { throw new Kohana_404_Exception(); } }
/** * Fetch latest ushahidi version from a remote instance then * compare it with local instance version number. */ public function _fetch_core_release() { // Current Version $current = urlencode(Kohana::config('settings.ushahidi_version')); // Extra Stats $url = urlencode(preg_replace("/^https?:\\/\\/(.+)\$/i", "\\1", url::base())); $ip_address = isset($_SERVER['REMOTE_ADDR']) ? urlencode($_SERVER['REMOTE_ADDR']) : ""; $version_url = "http://version.ushahidi.com/2/?v=" . $current . "&u=" . $url . "&ip=" . $ip_address; $request = new HttpClient($version_url); $version = $request->execute(); preg_match('/({.*})/', $version, $matches); $version_json_string = false; if (isset($matches[0])) { $version_json_string = $matches[0]; } // If we didn't get anything back... if (!$version_json_string) { return ""; } $version_details = json_decode($version_json_string); return $version_details; }
/** * Retrieves cities listing using GeoNames Service * * @param int $country_id The id of the country to retrieve cities for * Returns a JSON response */ public function update_cities($country_id = 0) { $this->template = ""; $this->auto_render = FALSE; // Get country ISO code from DB $country = ORM::factory('country', (int) $country_id); // No. of cities fetched $entries = 0; // Default payload to be returned to client as a JSON object $status_response = array("status" => "error", "response" => sprintf("%d %s %s", $entries, Kohana::lang('ui_admin.cities_loaded'), Kohana::lang('ui_admin.country_not_found'))); if ($country->loaded) { $base_url = "http://overpass-api.de/api/"; // Get the cities within the country info // Limited to 1000 items to avoid query time out /* This URL runs an Overpass API request using OverpassQL similar to: [out:json][timeout:300]; area["admin_level"="2"]["name:en"~"^Germany"]; ( node["place"="city"](area); ); out body 1000; */ $cities_url = $base_url . "interpreter?data=" . urlencode('[out:json][timeout:300];area["admin_level"="2"]["name:en"~"^' . $country->country . '"];(node["place"="city"](area););out body 1000;'); // Fetch the cities $cities_client = new HttpClient($cities_url, 300); if (($response = $cities_client->execute()) !== FALSE) { // Decode the JSON responce $response = json_decode($response); $cities = isset($response->elements) ? $response->elements : array(); // Only proceed if cities are returned if (count($cities) > 0) { // Set the city count for the country $country->cities = count($cities); $country->save(); // Delete all the cities for the current country ORM::factory('city')->where('country_id', $country->id)->delete_all(); // Manually construct the query (DB library can't do bulk inserts) $query = sprintf("INSERT INTO %scity (`country_id`, `city`, `city_lat`, `city_lon`) VALUES ", $this->table_prefix); $values = array(); // Create a database expression and use that to sanitize values $values_expr = new Database_Expression("(:countryid, :city, :lat, :lon)"); // Add the freshly fetched cities foreach ($cities as $city) { // Skip nameless nodes or nodes with lat/lon if (!isset($city->tags->name) or !$city->lat or !$city->lon) { continue; } $values_expr->param(':countryid', $country->id); $values_expr->param(':city', $city->tags->name); $values_expr->param(':lat', $city->lat); $values_expr->param(':lon', $city->lon); $values[] = $values_expr->compile(); } $query .= implode(",", $values); // Batch insert Database::instance()->query($query); $entries = count($cities); } // Set the response payload $status_response['status'] = "success"; $status_response['response'] = sprintf("%d %s", $entries, Kohana::lang('ui_admin.cities_loaded')); } else { // Geonames timeout $status_response['response'] = Kohana::lang('ui_admin.timeout'); } } echo json_encode($status_response); }
/** * Retrieves cities listing using GeoNames Service * * @param int $country_id The id of the country to retrieve cities for * Returns a JSON response */ public function update_cities($country_id = 0) { $this->template = ""; $this->auto_render = FALSE; // Get country ISO code from DB $country = ORM::factory('country', (int) $country_id); // No. of cities fetched $entries = 0; // Default payload to be returned to client as a JSON object $status_response = array("status" => "error", "response" => sprintf("%d %s %s", $entries, Kohana::lang('ui_admin.cities_loaded'), Kohana::lang('ui_admin.country_not_found'))); if ($country->loaded) { $iso = strtoupper($country->iso); // Base URL for the Geonames API endpoint $base_url = "http://api.geonames.org/"; // Get the country info $country_url = $base_url . "countryInfoJSON?country=%s&username=ushahididev"; $client = new HttpClient(sprintf($country_url, $iso)); if (($response = $client->execute()) !== FALSE) { // Decode the JSON $response = json_decode($response, TRUE); // Geonames returned an error if (!array_key_exists('geonames', $response)) { echo json_encode($status_response); exit; } // Get the south,east, north and west bounds $country_info = $response['geonames'][0]; // Fetch the city names // // TODO: EK <emmanuel(at)ushahidi.com // The maximum no. of cities + the geonames username // should be configurable parameters. Right now, I've set the upper // limit for the cities to 1000 // $cities_url = $base_url . "citiesJSON?north=%s&south=%s&east=%s&west=%s&username=ushahididev&maxRows=1000"; // Add the bounding box values $cities_url = sprintf($cities_url, $country_info['north'], $country_info['south'], $country_info['east'], $country_info['west']); // Fetch the cities $cities_client = new HttpClient($cities_url); if (($response = $cities_client->execute()) !== FALSE) { // Decode the JSON response $response = json_decode($response, TRUE); $cities = array_key_exists('geonames', $response) ? $response['geonames'] : array(); // Only proceed if cities are returned if (count($cities) > 0) { // Set the city count for the country $country->cities = count($cities); $country->save(); // Delete all the cities for the current country ORM::factory('city')->where('country_id', $country->id)->delete_all(); $query = sprintf("INSERT INTO %scity (`country_id`, `city`, `city_lat`, `city_lon`) VALUES ", $this->table_prefix); $values = array(); $values_template = "(%d, '%s', %s, %s)"; // Add the freshly fetched cities foreach ($cities as $city) { $values[] = sprintf($values_template, $country->id, $city['name'], $city['lat'], $city['lng']); } $query .= implode(",", $values); // Batch insert Database::instance()->query($query); $entries = count($cities); } // Set the response payload $status_response['status'] = "success"; $status_response['response'] = sprintf("%d %s", $entries, Kohana::lang('ui_admin.cities_loaded')); } else { // Geonames timed out $status_response['response'] = Kohana::lang('ui_admin.geonames_timeout'); } } else { // Geonames timeout $status_response['response'] = Kohana::lang('ui_admin.geonames_timeout'); } } echo json_encode($status_response); }
/** * Generates the thumbnail a video * * @param string $raw URL of the video * @return string url of video thumbnail */ public function thumbnail($raw) { $this->set_url($raw); $output = FALSE; if (isset($this->service['oembed'])) { $url = $this->service['oembed'] . "?url=" . urlencode($this->url); $request = new HttpClient($url); $result = $request->execute(); if ($result !== FALSE) { $oembed = json_decode($result); if (!empty($oembed) and !empty($oembed->thumbnail_url)) { $output = $oembed->thumbnail_url; } } } $data = array($this->service_name, $output); Event::run('ushahidi_filter.video_embed_thumbnail', $data); list($this->service_name, $output) = $data; return $output; }
/** * Reverse Geocode a point using Google Geocode * * @author * @param double $latitude * @param double $longitude * @return string closest approximation of the point as a display name */ static function reverseGoogle($lat, $lng) { if ($lat && $lng) { $url = Kohana::config('config.external_site_protocol') . '://maps.googleapis.com/maps/api/geocode/json?sensor=false&latlng=' . $lat . "," . $lng; $request = new HttpClient($url); if (!($json = $request->execute())) { Kohana::log('error', "Geocode - reverseGoogle\n" . $url . "\n" . $request->get_error_msg()); return FALSE; } $location = json_decode($json); if ($location->status != 'OK') { // logs anything different from OK Kohana::log('error', "Geocode - reverseGoogle: " . $location->status . " - " . $location->error_message); return FALSE; } if (count($location->results) == 0) { return FALSE; } return $location->results[0]->formatted_address; } else { return FALSE; } }