Example #1
0
 public static function simplepie($feed_url = NULL)
 {
     if (!$feed_url) {
         return false;
     }
     $data = new SimplePie();
     //*******************************
     // Convert To GeoRSS feed
     // To Disable Uncomment these 3 lines
     //*******************************
     $geocoder = new Geocoder();
     $georss_feed = $geocoder->geocode_feed($feed_url);
     if ($georss_feed == false or empty($georss_feed)) {
         // Our RSS feed pull failed, so let's grab the original RSS feed
         $data->set_feed_url($feed_url);
     } else {
         // Converting our feed to GeoRSS was successful, use that data
         $data->set_raw_data($georss_feed);
     }
     // Uncomment Below to disable geocoding
     //$data->set_feed_url( $feed_url );
     //*******************************
     $data->enable_cache(false);
     $data->enable_order_by_date(true);
     $data->init();
     $data->handle_content_type();
     return $data;
 }
Example #2
0
 public function getWOEID($location)
 {
     $GeocoderR = new Geocoder();
     $Long_Lat = $GeocoderR->geoCoding($location);
     $latitude = $Long_Lat["Lat"];
     $longitude = $Long_Lat["Long"];
     $url_post = "http://where.yahooapis.com/v1/places.q('" . urlencode($location) . "')?appid=26vtqA3IkY33IePAzOJso2VF9Ywrisdq4XzshIm0v3jNw1MfzIFhu7M9dGzxQtXz";
     $weather_feed = file_get_contents($url_post);
     $objDOM = new DOMDocument();
     $objDOM->loadXML($weather_feed);
     $woeid = $objDOM->getElementsByTagName("place")->item(0)->getElementsByTagName("woeid")->item(0)->nodeValue;
     return $woeid;
 }
Example #3
0
 function prepareform($pay, $user)
 {
     // Documentation:
     // https://www.paypal.com/developer
     // Warning: the automatic return only works if we force the
     // users to create a paypal account. We do not use it; thus
     // the user must come back on the site.
     global $globals, $platal;
     $this->urlform = 'https://' . $globals->money->paypal_site . '/cgi-bin/webscr';
     $roboturl = str_replace("https://", "http://", $globals->baseurl) . '/' . $platal->ns . "payment/paypal_return/" . $user->id() . "?comment=" . urlencode(Env::v('comment')) . '&display=' . Post::i('display');
     $this->infos = array('commercant' => array('business' => $globals->money->paypal_compte, 'rm' => 2, 'return' => $roboturl, 'cn' => 'Commentaires', 'no_shipping' => 1, 'cbt' => empty($GLOBALS['IS_XNET_SITE']) ? 'Revenir sur polytechnique.org.' : 'Revenir sur polytechnique.net.'));
     $info_client = array('first_name' => $user->firstName(), 'last_name' => $user->lastName(), 'email' => $user->bestEmail());
     if ($user->hasProfile()) {
         $res = XDB::query("SELECT  pa.text, GROUP_CONCAT(pace2.short_name) AS city,\n                                       GROUP_CONCAT(pace3.short_name) AS zip, GROUP_CONCAT(pace1.short_name) AS country,\n                                       IF(pp1.display_tel != '', pp1.display_tel, pp2.display_tel) AS night_phone_b\n                                 FROM  profile_addresses                 AS pa\n                            LEFT JOIN  profile_phones                    AS pp1   ON (pp1.pid = pa.pid AND pp1.link_type = 'address' AND pp1.link_id = pa.id)\n                            LEFT JOIN  profile_phones                    AS pp2   ON (pp2.pid = pa.pid AND pp2.link_type = 'user' AND pp2.link_id = 0)\n                            LEFT JOIN  profile_addresses_components      AS pc    ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid\n                                                                                      AND pa.type = pc.type AND pa.id = pc.id)\n                            LEFT JOIN  profile_addresses_components_enum AS pace1 ON (FIND_IN_SET('country', pace1.types) AND pace1.id = pc.component_id)\n                            LEFT JOIN  profile_addresses_components_enum AS pace2 ON (FIND_IN_SET('locality', pace2.types) AND pace2.id = pc.component_id)\n                            LEFT JOIN  profile_addresses_components_enum AS pace3 ON (FIND_IN_SET('postal_code', pace3.types) AND pace3.id = pc.component_id)\n                                WHERE  pa.pid = {?} AND FIND_IN_SET('current', pa.flags)\n                             GROUP BY  pa.pid, pa.jobid, pa.groupid, pa.id, pa.type\n                                LIMIT  1", $user->profile()->id());
         if (is_array($res)) {
             $this->infos['client'] = array_map('replace_accent', array_merge($info_client, $res->fetchOneAssoc()));
             list($this->infos['client']['address1'], $this->infos['client']['address2']) = explode("\n", Geocoder::getFirstLines($this->infos['client']['text'], $this->infos['client']['zip'], 2));
             unset($this->infos['client']['text']);
         } else {
             $this->infos['client'] = array_map('replace_accent', $info_client);
         }
     } else {
         $this->infos['client'] = array_map('replace_accent', $info_client);
     }
     // We build the transaction's reference
     $prefix = rand_url_id();
     $fullref = substr("{$prefix}-xorg-{$pay->id}", -15);
     $this->infos['commande'] = array('item_name' => replace_accent($pay->text), 'amount' => $this->val_number, 'currency_code' => 'EUR', 'custom' => $fullref);
     $this->infos['divers'] = array('cmd' => '_xclick');
 }
Example #4
0
 /**
  * Outputs the content of the widget
  *
  * @param array $args
  * @param array $instance
  *
  */
 public function widget($args, $instance)
 {
     global $wpdb;
     if (!array_key_exists('price-min', $_GET) || !array_key_exists('price-max', $_GET) || !array_key_exists('beds', $_GET) || !array_key_exists('location', $_GET) || !array_key_exists('distance', $_GET)) {
         return;
     }
     $filters = ['price-min' => intval($_GET['price-min']), 'price-max' => intval($_GET['price-max']), 'beds' => intval($_GET['beds']), 'location' => sanitize_text_field($_GET['location']), 'distance' => intval($_GET['distance'])];
     $sort = array_key_exists('sort', $_GET) ? sanitize_text_field($_GET['sort']) : 'distance';
     $sortDir = array_key_exists('sortdir', $_GET) ? sanitize_text_field($_GET['sortdir']) : 'asc';
     $page = array_key_exists('page', $_GET) ? intval($_GET['page']) : 1;
     require_once get_stylesheet_directory() . '/includes/Geocoder.php';
     $geocoder = new Geocoder();
     $location = $geocoder->getLocation($filters['location']);
     $sql = "\n            SELECT DISTINCT\n              {$wpdb->posts}.ID as post_id,\n              CAST(price.meta_value AS UNSIGNED) AS price,\n              beds.meta_value AS beds,\n              latitude.meta_value AS latitude,\n              longitude.meta_value AS longitude,\n              p.distance_unit * DEGREES(\n                ACOS(\n                  COS(RADIANS(p.latpoint)) * COS(RADIANS(latitude.meta_value)) * COS(\n                    RADIANS(\n                      p.longpoint - longitude.meta_value\n                    )\n                  ) + SIN(RADIANS(p.latpoint)) * SIN(RADIANS(latitude.meta_value))\n                )\n              ) AS distance\n            FROM\n              {$wpdb->posts}\n              INNER JOIN {$wpdb->postmeta} beds\n                ON beds.post_id = {$wpdb->posts}.ID\n                AND beds.meta_key = 'wpcf-bedrooms'\n              INNER JOIN {$wpdb->postmeta} price\n                ON price.post_id = {$wpdb->posts}.ID\n                AND price.meta_key = 'wpcf-price'\n              INNER JOIN {$wpdb->postmeta} latitude\n                ON latitude.post_id = {$wpdb->posts}.ID\n                AND latitude.meta_key = 'wpcf-latitude'\n              INNER JOIN {$wpdb->postmeta} longitude\n                ON longitude.post_id = {$wpdb->posts}.ID\n                AND longitude.meta_key = 'wpcf-longitude'\n              JOIN\n                (SELECT\n                  {$location['lat']} AS latpoint,\n                  {$location['lng']} AS longpoint,\n                  {$filters['distance']} AS radius,\n                  69.0 AS distance_unit) AS p\n                ON 1 = 1\n            WHERE latitude.meta_value BETWEEN p.latpoint - (p.radius / p.distance_unit)\n              AND p.latpoint + (p.radius / p.distance_unit)\n              AND longitude.meta_value BETWEEN p.longpoint - (\n                p.radius / (\n                  p.distance_unit * COS(RADIANS(p.latpoint))\n                )\n              )\n              AND p.longpoint + (\n                p.radius / (\n                  p.distance_unit * COS(RADIANS(p.latpoint))\n                )\n              )\n              AND {$wpdb->posts}.post_type = 'sale-property'\n              AND beds.meta_value >= {$filters['beds']}\n              AND price.meta_value BETWEEN {$filters['price-min']}\n              AND {$filters['price-max']}\n            ORDER BY {$sort} {$sortDir}\n        ";
     $properties = $wpdb->get_results($sql);
     require get_stylesheet_directory() . '/property-results-widget-template.php';
 }
Example #5
0
 public function dataRefresh(Cafe $client)
 {
     $cafes = \App\Http\Models\Cafe::all();
     foreach ($cafes as $cafe) {
         $foursquareID = $cafe->foursquareID;
         // grab foursquare ID
         $command = $this->{$client}->getCommand('venues', array('venue_id' => $foursquareID));
         // grab foursquare data
         $foursquareData = $command->execute();
         // save to a variable
         $json4sq = json_decode(json_encode($foursquareData));
         // convert to a json object; foursquare object is part of $json4sq->response
         // set the properties of the object we just pulled
         $cafe->lat = $json4sq->response->venue->location->lat;
         $cafe->lng = $json4sq->response->venue->location->lng;
         if (isset($json4sq->response->venue->bestPhoto)) {
             $photoURL = $json4sq->response->venue->bestPhoto->prefix . 'original' . $json4sq->response->venue->bestPhoto->suffix;
         } else {
             $photoURL = null;
         }
         $cafe->photoURL = $photoURL;
         $cafe->street = $json4sq->response->venue->location->address;
         if (isset($json4sq->response->venue->location->crossStreet)) {
             $cafe->crossStreet = $json4sq->response->venue->location->crossStreet;
         }
         $cafe->state = $json4sq->response->venue->location->state;
         $cafe->country = $json4sq->response->venue->location->country;
         if (isset($json4sq->response->venue->contact->postalCode)) {
             $cafe->postcode = $json4sq->response->venue->location->postalCode;
         }
         if (isset($json4sq->response->venue->contact->phone)) {
             $cafe->phone = $json4sq->response->venue->contact->phone;
         }
         if (isset($json4sq->response->venue->contact->twitter)) {
             $cafe->twitter = $json4sq->response->venue->contact->twitter;
         }
         if (isset($json4sq->response->venue->contact->facebookUsername)) {
             $cafe->facebook = $json4sq->response->venue->contact->facebookUsername;
         }
         if (isset($json4sq->response->venue->url)) {
             $cafe->url = $json4sq->response->venue->url;
         }
         if (isset($json4sq->response->venue->location->neighborhood)) {
             $cafe->neighbourhood = $json4sq->response->venue->location->neighborhood;
         } else {
             $lat = $json4sq->response->venue->location->lat;
             $lng = $json4sq->response->venue->location->lng;
             $latlng = $lat . "," . $lng;
             $param = array("latlng" => $latlng);
             $response = \Geocoder::geocode('json', $param);
             $googleJson = json_decode($response);
             $cafe->neighbourhood = $googleJson->results[0]->address_components[2]->long_name;
         }
         $cafe->save();
     }
 }
Example #6
0
 protected function parse($st)
 {
     $st = preg_replace('/[\\w\\d]{100,}/', '', $st);
     // убираем слишком длинную строку, иначе рушится регулярка
     if (!preg_match_all('#' . '.*?<strong>(?<_name>[^<]+?\\d[^<]+?)<' . '.*?Телефон: (?<phone>.+?)<br>' . '.*?Режим работы: (?<hours>.+?)<br>' . '(?<wheel>[^<]+?маломобильн)?' . '.*?Адрес: .+?, (?<_addr>.+?)<br>' . '(.{0,1500}?viewPointOnMap..(?<lon>[\\d.]+).,.(?<lat>[\\d.]+).)?' . '#su', $st, $m, PREG_SET_ORDER)) {
         return;
     }
     foreach ($m as $obj) {
         if ($obj['wheel']) {
             $obj['wheelchair'] = 'yes';
         }
         $obj['contact:phone'] = $this->phone($obj['phone']);
         // номер отделения
         if (preg_match('#[\\d/]+#', $obj['_name'], $m_)) {
             $obj['ref'] = $m_[0];
         }
         // формируем часы работы
         $obj['opening_hours'] = $this->time($this->parseTime($obj['hours']));
         // обрабатываем адрес
         $obj['_addr'] = preg_replace('/\\d{6}/i', '', $obj['_addr']);
         // убираем индекс
         $obj['_addr'] = preg_replace('/(^[^а-я0-9]+|[^а-я0-9]+$)/ui', '', $obj['_addr']);
         // мусор на границах
         $obj['_addr'] = preg_replace('/\\(.+/ui', '', $obj['_addr']);
         // убираем все что в скобках и правее
         // отделение
         if (preg_match('/[а-я]+ отделение/iu', $obj['_name'], $m)) {
             $obj['department'] = $m[0];
         }
         if (strpos($obj[0], 'не обслуживаются')) {
             $obj['disused'] = 'yes';
             $obj['opening_hours'] = '';
         }
         // заменяем координаты с сайта сбербанка на геокодированные
         $geocoder = new Geocoder();
         $obj = array_merge($obj, $geocoder->getCoordsByAddress($obj['_addr']));
         $this->addObject($this->makeObject($obj));
     }
 }
Example #7
0
 public static function simplepie($feed_url = NULL)
 {
     if (!$feed_url) {
         return false;
     }
     $data = new SimplePie();
     //*******************************
     // Convert To GeoRSS feed
     // To Disable Uncomment these 3 lines
     //*******************************
     $geocoder = new Geocoder();
     $georss_feed = $geocoder->geocode_feed($feed_url);
     $data->set_raw_data($georss_feed);
     // Uncomment Below to disable geocoding
     //$data->set_feed_url( $feed_url );
     //*******************************
     $data->enable_cache(false);
     $data->enable_order_by_date(true);
     $data->init();
     $data->handle_content_type();
     return $data;
 }
Example #8
0
 public function store()
 {
     $user = Auth::user();
     $meal = new Meal();
     $meal->name = Input::get('name');
     $meal->description = Input::get('description');
     $meal->street = Input::get('street');
     $meal->city = Input::get('city');
     $meal->zip_code = Input::get('zip_code');
     $meal->seats = Input::get('seats');
     // get long and lat
     $param = array("address" => Input::get('street') . " " . Input::get('city') . " " . Input::get('zip_code'));
     $response = \Geocoder::geocode('json', $param);
     $json = json_decode($response, true);
     $location = $json['results'][0]['geometry']['location'];
     $lat = $location['lat'];
     $lng = $location['lng'];
     $meal->lat = $lat;
     $meal->lng = $lng;
     // get and parse date
     $date = Input::get('meal_date');
     $date_array = explode("/", $date);
     $day = (int) $date_array[0];
     $month = (int) $date_array[1];
     $year = (int) $date_array[2];
     // get and parse time
     $time = Input::get('meal_time');
     $time_array = explode(":", $time);
     $hour = (int) $time_array[0];
     $minutes = (int) $time_array[1];
     // create new dateTime
     $date_time = Carbon::create($year, $month, $day, $hour, $minutes);
     $meal->meal_date_time = $date_time;
     // create ingredients
     $ingredients = Input::get('ingredient');
     $meal_ingredients = array();
     foreach ($ingredients as $ingredient) {
         $meal_ingredients[] = new Ingredient(array('name' => $ingredient['name'], 'unit' => $ingredient['unit'], 'quantity' => $ingredient['quantity']));
     }
     //save  into the DB
     $meal->save();
     $user->meals()->attach($meal);
     $meal->ingredients()->saveMany($meal_ingredients);
     // redirect
     Flash::success('Votre repas a bien été crée !');
     return Redirect::route('meals.show', $meal);
 }
 /**
  * Parses each row of the CSV file and then extracts addresses, groups by category, and GeoCodes address data.
  * Sends GeoCoded coordinates to mapview.blade View where the Maps API v3 places markers at those locations
  * @return View
  */
 public function processHeaders()
 {
     //flash old input to session in case of errors
     Input::flashOnly('filePath');
     //setup holding array for locations ordered by category
     $groupedLocations = array();
     // Create $locations array to hold address + zip of each row
     $locations = array();
     // Check if all values in the input array only appear once
     $data = array_count_values(Input::all());
     foreach ($data as $key => $value) {
         if ($value != 1) {
             return Redirect::to('/')->withInput()->with('errorMsg', 'Multiple headers cannot reference the same column.');
         }
     }
     //our data is now the keys (integers) of each column. This is a 0-based column index
     $inputCSV = Reader::createFromPath(urldecode(Input::get('filePath')));
     $inputCSV->setDelimiter(',');
     $validRows = $inputCSV->addFilter(function ($row, $index) {
         return $index > 0;
         //ignore headers
     })->addFilter(function ($row) {
         return isset($row[Input::get('zip')], $row[Input::get('address')], $row[Input::get('category')]);
         //only get rows where zip, addr, and category are filled
     })->fetchAll();
     // Loop through fetched rows from CSV
     for ($i = 0; $i < sizeof($validRows); $i++) {
         //Add addresses to $locations array formatted as: 555+Address+St+ZIPCODE
         $locations[] = array('addrMarker' => urlencode($validRows[$i][Input::get('address')] . " " . $validRows[$i][Input::get('zip')]), 'category' => $validRows[$i][Input::get('category')]);
     }
     // Get geocoded coordinates for each entry in $location
     foreach ($locations as $location) {
         $geocodedLoc = Geocoder::geocode('json', array('address' => $location['addrMarker']));
         // Hold Geocoded coordinates
         $tempLatLang = json_decode($geocodedLoc, $assoc = true);
         // Build grouped array based on category data
         // Create new subarray for each unique category
         if (!isset($groupedLocations[$location['category']])) {
             $groupedLocations[$location['category']] = array();
         }
         $groupedLocations[$location['category']][] = array('lat' => $tempLatLang['results'][0]['geometry']['location']['lat'], 'lng' => $tempLatLang['results'][0]['geometry']['location']['lng'], 'category' => $location['category']);
     }
     return View::make('mapview')->with('mapDataPts', $groupedLocations);
 }
Example #10
0
 public function anyIndex()
 {
     $in = Input::only('lat', 'lng');
     $out = array();
     $rules = array('lat' => 'required', 'lng' => 'required');
     $vd = Validator::make($in, $rules);
     if ($vd->fails()) {
         return;
     }
     try {
         $geo = Geocoder::reverse($in['lat'], $in['lng']);
         $out['code'] = $geo->getCountryCode();
         $out['city'] = $geo->getRegionCode();
         $out['town'] = $geo->getCity();
         $out['zipcode'] = $geo->getZipCode();
         $out['streetName'] = $geo->getStreetName();
     } catch (\Exception $e) {
         return Response::json(array('error' => $e->getMessage()));
     }
     return Response::json($out);
 }
 public function run($request)
 {
     // Try to geocode a sample address
     $address = Geocoder::config()->local_address;
     // Test simple geocoding
     $geo = Geocoder::simpleGeocode($address);
     DB::alteration_message("Testing general behaviour");
     if ($geo) {
         DB::alteration_message('Simple geocoding is working ' . $geo['Latitude'] . '/' . $geo['Longitude'], 'created');
     } else {
         DB::alteration_message('Simple geocoding failed', 'error');
     }
     // Test all providers
     $geocoder = Geocoder::getGeocoder();
     $list = array_keys($geocoder->getProviders());
     DB::alteration_message("Registered providers are : " . implode(',', $list));
     foreach ($geocoder->getProviders() as $name => $provider) {
         DB::alteration_message("Testing : " . $name);
         try {
             $res = $geocoder->using($name)->geocode($address);
             if ($res->count()) {
                 DB::alteration_message("Provider {$name} is working and returned " . $res->count() . ' results', 'created');
                 foreach ($res as $result) {
                     DB::alteration_message('Geoloc is working ' . $result->getLatitude() . '/' . $result->getLongitude(), 'created');
                 }
             } else {
                 DB::alteration_message("Provider {$name} failed to geocode address", 'error');
             }
         } catch (\Geocoder\Exception\NoResult $ex) {
             DB::alteration_message("Provider {$name} failed to geocode address", 'error');
             DB::alteration_message($ex->getMessage(), 'error');
         } catch (\Exception $ex) {
             DB::alteration_message($ex->getMessage(), 'error');
         }
     }
 }
Example #12
0
 protected function buildEntry($pf)
 {
     global $globals;
     $pf = $pf['value'];
     $entry = new PlVCardEntry($pf->firstNames(), $pf->lastNames(), null, null, $pf->nickname);
     $user = $pf->owner();
     // Free text
     $freetext = '(' . $pf->promo . ')';
     if ($this->freetext) {
         $freetext .= "\n" . $this->freetext;
     }
     $entry->set('NOTE', $freetext);
     if ($pf->mobile) {
         $entry->addTel(null, $pf->mobile, false, true, true, false, true, true);
     }
     // Emails
     if (!is_null($user)) {
         $entry->addMail(null, $user->bestalias, true);
         if ($user->forlife != $user->bestalias) {
             $entry->addMail(null, $user->forlife);
         }
         if ($user->forlife_alternate != $user->bestalias) {
             $entry->addMail(null, $user->forlife_alternate);
         }
     }
     // Homes
     $adrs = $pf->iterAddresses(Profile::ADDRESS_PERSO);
     while ($adr = $adrs->next()) {
         if (!$adr->postalCode || !$adr->locality || !$adr->country) {
             $group = $entry->addHome($adr->text, null, null, null, null, $adr->administrativeArea, null, $adr->hasFlag('current'), $adr->hasFlag('mail'), $adr->hasFlag('mail'));
         } else {
             $group = $entry->addHome(trim(Geocoder::getFirstLines($adr->text, $adr->postalCode, 4)), null, null, $adr->postalCode, $adr->locality, $adr->administrativeArea, $adr->country, $adr->hasFlag('current'), $adr->hasFlag('mail'), $adr->hasFlag('mail'));
         }
         foreach ($adr->phones() as $phone) {
             if ($phone->link_type == Phone::TYPE_FIXED) {
                 $entry->addTel($group, $phone->display, false, true, true, false, false, $adr->hasFlag('current') && empty($pf->mobile));
             } else {
                 if ($phone->link_type == Phone::TYPE_FAX) {
                     $entry->addTel($group, $phone->display, true, false, false, false, false, false);
                 }
             }
         }
     }
     // Pro
     $jobs = $pf->getJobs();
     foreach ($jobs as $job) {
         $terms_array = array();
         foreach ($job->terms as $term) {
             $terms_array[] = $term->full_name;
         }
         $terms = implode(', ', $terms_array);
         if ($job->address) {
             if (!$job->address->postalCode || !$job->address->locality || !$job->address->country) {
                 $group = $entry->addWork($job->company->name, null, $job->description, $terms, $job->address->text, null, null, null, null, $job->address->administrativeArea, null);
             } else {
                 $group = $entry->addWork($job->company->name, null, $job->description, $terms, trim(Geocoder::getFirstLines($job->address->text, $job->address->postalCode, 4)), null, null, $job->address->postalCode, $job->address->locality, $job->address->administrativeArea, $job->address->country);
             }
         } else {
             $group = $entry->addWork($job->company->name, null, $job->description, $terms, null, null, null, null, null, null, null);
         }
         if ($job->user_email) {
             $entry->addMail($group, $job->user_email);
         }
         foreach ($job->phones as $phone) {
             if ($phone->type == Phone::TYPE_MOBILE) {
                 $entry->addTel($group, $phone->display, false, true, true, false, true);
             } else {
                 if ($phone->type == Phone::TYPE_FAX) {
                     $entry->addTel($group, $phone->display, true);
                 } else {
                     $entry->addTel($group, $phone->display, false, true, true);
                 }
             }
         }
     }
     // Melix
     if (!is_null($user)) {
         $alias = $user->emailAlias();
         if (!is_null($alias) && $pf->alias_pub == 'public') {
             $entry->addMail(null, $alias);
         }
     }
     // Custom fields
     if (!is_null($user)) {
         $groups = $user->groups(true, true);
         if (count($groups)) {
             $gn = DirEnum::getOptions(DirEnum::GROUPESX);
             $gns = array();
             foreach (array_keys($groups) as $gid) {
                 $gns[$gid] = $gn[$gid];
             }
             $entry->set('X-GROUPS', join(', ', $gns));
         }
     }
     $binets = $pf->getBinets();
     if (count($binets)) {
         $bn = DirEnum::getOptions(DirEnum::BINETS);
         $bns = array();
         foreach ($binets as $bid) {
             $bns[$bid] = $bn[$bid];
         }
         $entry->set('X-BINETS', join(', ', $bns));
     }
     if (!empty($pf->section)) {
         $entry->set('X-SECTION', $pf->section);
     }
     // Photo
     if ($this->photos) {
         $res = XDB::query("SELECT  attach, attachmime\n                       FROM  profile_photos\n                      WHERE  pid = {?} AND pub IN ('public', {?})", $pf->id(), $this->visibility->level());
         if ($res->numRows()) {
             list($data, $type) = $res->fetchOneRow();
             $entry->setPhoto($data, strtoupper($type));
         }
     }
     return $entry;
 }
 /**
  * Geocode the current full address
  * @return \Geocoder\Model\Address
  */
 public function Geocode()
 {
     if (!$this->canBeGeolocalized()) {
         return false;
     }
     if ($this->owner->GeolocateOnLocation) {
         $result = Geocoder::geocodeAddress($this->getLocation());
     } else {
         $result = Geocoder::geocodeAddress($this->getFormattedAddress());
     }
     if ($result) {
         $this->owner->Latitude = $result->getLatitude();
         $this->owner->Longitude = $result->getLongitude();
         return $result;
     }
     return false;
 }
Example #14
0
 protected function do_geocode($address)
 {
     foreach ($this->geocoders->provider_order as $provider) {
         $msg = "MultiGeocoder using " . $provider;
         Geocoder::logger('debug', $msg);
         switch ($provider) {
             case 'google':
                 $geocoder = new GoogleGeocoder();
                 break;
             case 'yahoo':
                 $geocoder = new YahooGeocoder();
                 break;
             case 'us':
                 $geocoder = new UsGeocoder();
                 break;
             case 'ca':
                 $geocoder = new CaGeocoder();
                 break;
             default:
                 $msg = '"' . $provider . '" is an invalid Geocode provider.';
                 Geocoder::logger('error', $msg);
                 $geoloc = new GeoLoc();
                 $geoloc->success = false;
                 $geoloc->street_address = $msg;
                 return $geoloc;
         }
         $result = $geocoder->geocode($address);
         # This statement is for use by multi_geocoder_test only
         if (isset($this->geocoders->force_failure)) {
             foreach ($this->geocoders->force_failure as $prov) {
                 if ($provider == $prov) {
                     $result->success = false;
                 }
             }
         }
         if ($result->success) {
             return $result;
         }
     }
     $address_str = $address instanceof GeoLoc ? $address->to_geocodeable_s() : $address;
     $msg = "Something has gone very wrong during the geocoding of this address: " . $address_str;
     Geocoder::logger('error', $msg);
     $geoloc = new GeoLoc();
     $geoloc->success = false;
     $geoloc->street_address = $msg;
     return $geoloc;
 }
Example #15
0
 public function testGeocoderFacade()
 {
     $this->assertTrue(is_array($providers = \Geocoder::getProviders()));
     $this->assertArrayHasKey('chain', $providers);
     $this->assertInstanceOf('Geocoder\\Provider\\ChainProvider', $providers['chain']);
 }
Example #16
0
 /**
  * setup simplepie
  */
 private function _setup_simplepie($feed_url)
 {
     $data = new SimplePie();
     // Convert To GeoRSS feed
     $geocoder = new Geocoder();
     $georss_feed = $geocoder->geocode_feed($feed_url);
     $data->set_raw_data($georss_feed);
     $data->enable_cache(false);
     $data->enable_order_by_date(true);
     $data->init();
     $data->handle_content_type();
     return $data;
 }
 /**
  */
 public function handleFakeLocations($gridField, $request = null)
 {
     $class = $gridField->getModelClass();
     $all = $class::get();
     foreach ($all as $record) {
         if (!strlen(trim($record->StreetName))) {
             $tries = 0;
             do {
                 $coords = FakeRecordGenerator::latLon(null, null, 200);
                 $infos = Geocoder::reverseGeocode($coords['lat'], $coords['lng']);
                 $tries++;
             } while (!$infos && $tries < 5);
             if ($infos) {
                 $record->Latitude = $infos->getLatitude();
                 $record->Longitude = $infos->getLongitude();
                 $record->StreetName = $infos->getStreetName();
                 $record->StreetNumber = $infos->getStreetNumber();
                 $record->PostalCode = $infos->getPostalCode();
                 $record->CountryCode = $infos->getCountryCode();
                 $record->Locality = $infos->getLocality();
                 $record->write();
             }
         }
     }
     $message = sprintf(_t('DevToolkitFakeLocationsButton.ADD_FAKE_LOCATIONS', 'Added fake locations to %s'), $class);
     DevToolkitAdminExtension::SetSessionMessage($message, 'good');
     return Controller::curr()->redirectBack();
 }
 /**
  * Handle hub form (add/edit)
  *
  * @return Response
  */
 public function post_hub()
 {
     $hub = null;
     if (Input::has('id')) {
         $hub = Hub::find(Input::get('id'));
     }
     if (is_null($hub)) {
         $hub = new Hub();
     }
     $geo = Geocoder::getCoordinatesForQuery(Input::get('location'));
     $hub->name = Input::get('name');
     $hub->description = Input::get('description');
     $hub->location = Input::get('location');
     $hub->facebook = Input::get('facebook');
     $hub->google = Input::get('google');
     $hub->twitter = Input::get('twitter');
     $hub->slug = Str::slug($hub->name);
     if ($geo != 'NOT_FOUND') {
         $hub->lat = $geo['lat'];
         $hub->lng = $geo['lng'];
     }
     if (Input::has('art')) {
         $image = Input::get('art');
         $exp = explode(",", $image);
         $name = str_random(15);
         $data = base64_decode($exp[1]);
         $tempfile = storage_path() . "/temp/" . $name . "";
         file_put_contents($tempfile, $data);
         Image::make($tempfile)->resize(210, 210)->save(storage_path() . "/pictures/" . $name . ".png");
         unlink($tempfile);
         $p = new Picture();
         $p->name = $name;
         $p->user = 0;
         $p->extension = '.png';
         $p->save();
         $hub->picture = $p->id;
     }
     $hub->save();
     return Redirect::to('admin/hubs');
 }
Example #19
0
 public function format()
 {
     $this->text = trim($this->text);
     $this->phones = Phone::formatFormArray($this->phones, $this->error, $this->pub);
     if ($this->removed == 1) {
         if (!S::user()->checkPerms('directory_private') && Phone::hasPrivate($this->phones)) {
             Platal::page()->trigWarning("L'adresse ne peut être supprimée car elle contient des informations pour lesquelles vous n'avez le droit d'édition.");
         } else {
             $this->text = '';
             return true;
         }
     }
     $this->formatPostalAddress();
     if ($this->changed == 1) {
         $gmapsGeocoder = new GMapsGeocoder();
         $gmapsGeocoder->getGeocodedAddress($this);
         $componants = array();
         foreach ($this->components as $component) {
             $componants[] = Geocoder::getComponentId($component);
         }
         $this->componentsIds = implode(',', $componants);
     }
     if ($this->componentsIds == '') {
         $this->latitude = null;
         $this->longitude = null;
     }
     return true;
 }
Example #20
0
// Tries to geocode all the addresses.
for ($pid = $minPid; $pid < $maxPid + 1; ++$pid) {
    $res = XDB::iterator('SELECT  *
                            FROM  profile_addresses
                           WHERE  pid = {?}', $pid);
    while ($address = $res->next()) {
        $updateTime = $address['updateTime'];
        $gmapsGeocoder = new GMapsGeocoder();
        $address = $gmapsGeocoder->getGeocodedAddress($address);
        if (!isset($address['geoloc'])) {
            // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
            XDB::execute('DELETE FROM  profile_addresses
                                WHERE  pid = {?} AND id = {?} AND type = {?}', $address['pid'], $address['id'], $address['type']);
            Geocoder::getAreaId($address, 'administrativeArea');
            Geocoder::getAreaId($address, 'subAdministrativeArea');
            Geocoder::getAreaId($address, 'locality');
            XDB::execute('INSERT INTO  profile_addresses (pid, type, id, flags, accuracy,
                                                          text, postalText, postalCode, localityId,
                                                          subAdministrativeAreaId, administrativeAreaId,
                                                          countryId, latitude, longitude, updateTime, pub, comment,
                                                          north, south, east, west)
                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
                                        {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?}, {?}, {?})', $address['pid'], $address['type'], $address['id'], $flags, $address['accuracy'], $address['text'], $address['postalText'], $address['postalCode'], $address['localityId'], $address['subAdministrativeAreaId'], $address['administrativeAreaId'], $address['countryId'], $address['latitude'], $address['longitude'], $updateTime, $address['pub'], $address['comment'], $address['north'], $address['south'], $address['east'], $address['west']);
        } else {
            XDB::execute('UPDATE  profile_addresses
                             SET  postalText = {?}
                           WHERE  pid = {?} AND id = {?} AND type = {?}', $address['postalText'], $address['pid'], $address['id'], $address['type']);
        }
        sleep(60);
        // So we don't get blacklisted by Google.
    }
Example #21
0
function get_annuaire_infos($method, $params)
{
    global $error_mat, $error_key, $globals;
    // Password verification.
    if (!isset($params[0]) || $params[0] != $globals->manageurs->manageurs_pass) {
        return false;
    }
    // If address == -1, we do not retrieve any address.
    if (isset($params[2]) && $params[2] == -1) {
        unset($params[2]);
    }
    // We check we actually have an identification number.
    if (!empty($params[1])) {
        // We only retrieve addresses when required.
        if (!isset($params[2])) {
            $res = XDB::iterRow("SELECT  pp.display_tel AS cell, p.birthdate AS age\n                                   FROM  profiles       AS p\n                              LEFT JOIN  profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = 'user'\n                                                                  AND pp.tel_type = 'mobile')\n                                  WHERE  p.xorg_id = {?} LIMIT 1", $params[1]);
            $array = $res->next();
        } else {
            $res = XDB::iterRow("SELECT  p.birthdate, pa.text, GROUP_CONCAT(pace3.short_name), GROUP_CONCAT(pace2.short_name),\n                                         GROUP_CONCAT(pace1.short_name), p.pid, pa.id\n                                   FROM  profiles                          AS p\n                              LEFT JOIN  profile_addresses                 AS pa    ON (pa.pid = p.pid)\n                              LEFT JOIN  profile_addresses_components      AS pc    ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid\n                                                                                        AND pa.type = pc.type AND pa.id = pc.id)\n                              LEFT JOIN  profile_addresses_components_enum AS pace1 ON (FIND_IN_SET(\\'country\\', pace1.types) AND pace1.id = pc.component_id)\n                              LEFT JOIN  profile_addresses_components_enum AS pace2 ON (FIND_IN_SET(\\'locality\\', pace2.types) AND pace2.id = pc.component_id)\n                              LEFT JOIN  profile_addresses_components_enum AS pace3 ON (FIND_IN_SET(\\'postal_code\\', pace3.types) AND pace3.id = pc.component_id)\n                                  WHERE  p.xorg_id = {?} AND NOT FIND_IN_SET('job', pa.flags)\n                               ORDER BY  NOT FIND_IN_SET('current', pa.flags),\n                                         FIND_IN_SET('secondary', pa.flags),\n                                         NOT FIND_IN_SET('mail', pa.flags)\n                               GROUP BY  pa.pid, pa.jobid, pa.groupid, pa.id, pa.type", $params[1]);
            // Process the addresses we got.
            if (list($age, $text, $adr['cp'], $adr['ville'], $adr['pays'], $pid, $adr['adrid']) = $res->next()) {
                list($adr['adr1'], $adr['adr2'], $adr['adr3']) = explode("\n", Geocoder::getFirstLines($text, $adr['cp'], 3));
                $sql = XDB::query("SELECT  display_tel\n                                     FROM  profile_phones\n                                    WHERE  pid = {?} AND link_type = 'user' AND tel_type = 'mobile'\n                                    LIMIT  1", $pid);
                if ($sql->numRows() > 0) {
                    $array['cell'] = $sql->fetchOneCell();
                } else {
                    $array['cell'] = '';
                }
                $array['age'] = $age;
                $array['adresse'][] = $adr;
                // We limit the address number by the number of available addresses.
                $adresse = min((int) $params[2], $res->total());
                if ($adresse != 1) {
                    // We don't want the first address.
                    $i = 2;
                    while (list($age, $text, $adr['cp'], $adr['ville'], $adr['pays'], , $adr['adrid']) = $res->next()) {
                        list($adr['adr1'], $adr['adr2'], $adr['adr3']) = explode("\n", Geocoder::getFirstLines($text, $adr['cp'], 3));
                        if ($adresse == $i) {
                            // If we want this particular address.
                            $array['adresse'][0] = $adr;
                            //$res->free();
                            break;
                        } elseif ($adresse == 0) {
                            // If we want every address.
                            $array['adresse'][] = $adr;
                        }
                        $i++;
                    }
                }
                // We add the phone numbers.
                $adrid_index = array();
                foreach ($array['adresse'] as $i => $a) {
                    $adrid_index[$a['adrid']] = $i;
                }
                $restel = XDB::iterator("SELECT  pp.display_tel AS tel, pp..tel_type, pp.link_id as adrid\n                                           FROM  profile_phones    AS pp\n                                     INNER JOIN  profile_addresses AS pa ON (pp.link_id = pa.id AND pp.pid = pa.pid)\n                                          WHERE  pp.pid = {?} AND pp.link_type = 'address'\n                                                 AND NOT FIND_IN_SET('pro', pa.statut)", $pid);
                while ($tel = $restel->next()) {
                    $array['adresse'][$adrid_index[$tel['adrid']]]['tels'][] = $tel;
                }
                foreach ($array['adresse'] as $i => $adr) {
                    unset($lasttel);
                    foreach ($adr['tels'] as $j => $t) {
                        if (!isset($array['adresse'][$i]['tel']) && strpos($t['tel_type'], 'Tél') === 0) {
                            $array['adresse'][$i]['tel'] = $t['tel'];
                        } elseif (!isset($array['adresse'][$i]['fax']) && strpos($t['tel_type'], 'Fax') === 0) {
                            $array['adresse'][$i]['fax'] = $t['tel'];
                        } else {
                            $lasttel = $t['tel'];
                        }
                        if (isset($array['adresse'][$i]['tel']) && isset($array['adresse'][$i]['fax'])) {
                            break;
                        }
                    }
                    if (!isset($array['adresse'][$i]['tel']) && isset($lasttel)) {
                        $array['adresse'][$i]['tel'] = $lasttel;
                    } elseif (!isset($array['adresse'][$i]['fax']) && isset($lasttel)) {
                        $array['adresse'][$i]['fax'] = $lasttel;
                    }
                    unset($array['adresse'][$i]['adrid']);
                    unset($array['adresse'][$i]['tels']);
                }
            } else {
                $array = false;
            }
        }
        if ($array) {
            // We did get a result: the identification number was rigth.
            // We only send the age to manageurs.com; the format is YYYY-MM-DD 0123-56-89.
            $year = (int) substr($array['age'], 0, 4);
            $month = (int) substr($array['age'], 5, 2);
            $day = (int) substr($array['age'], 8, 2);
            $age = (int) date('Y') - $year - 1;
            if ($month < (int) date('m') || $month == (int) date('m') && $day >= (int) date('d')) {
                $age += 1;
            }
            $array['age'] = $age;
            // We start the encryption of the data.
            if (manageurs_encrypt_init($params[1]) == 1) {
                // We did not find the key to encryptthe data.
                $args = array("erreur" => 3, "erreurstring" => $error_key);
                $reply = xmlrpc_encode_request(NULL, $args);
            } else {
                $reply = manageurs_encrypt_array($array);
                manageurs_encrypt_close();
            }
        } else {
            // The identification number was not valid.
            $args = array("erreur" => 2, "erreurstring" => $erreur_mat);
            $reply = xmlrpc_encode_request(NULL, $args);
        }
    } else {
        // The identification number was not in argument.
        $args = array("erreur" => 1, "erreurstring" => $error_mat);
        $reply = xmlrpc_encode_request(NULL, $args);
    }
    return $reply;
}
Example #22
0
 /**
  * Get all lots near address with available spots
  *
  * @param null $address search address
  * @return array all lots with available spots
  */
 public function getAvailableNearAddress($address = null)
 {
     // Get address information from Google Maps API
     $geocode = Geocoder::geocode($address);
     // Get address latitude
     $latitude = $geocode->getLatitude();
     // Get address longitude
     $longitude = $geocode->getLongitude();
     // Check database for nearest locations based on address's latitude and longitude
     $locations = $this->getNearestLocationsFromDB($latitude, $longitude);
     // Check if there are any locations within 5 miles
     if (empty($locations)) {
         return 'There are no parking lots within 5 miles';
     }
     // New lots array
     $lots = array();
     // Index
     $i = 0;
     // Go through each location
     foreach ($locations as $location) {
         // Find lot by id
         $lot = $this->lotRepository->find($location->id, array('regions'));
         // Store the lot's regions
         $regions = $lot->regions;
         // New lot regions array
         $lotRegions = array();
         // Index
         $j = 0;
         // Lot available spots variable
         $lotAvailableSpots = 0;
         if (count($regions)) {
             // Go through each region
             foreach ($regions as $region) {
                 // Check if region capacity is greater than spots occupied
                 if (json_decode($region['capacity']) > json_decode($region['spots_occupied'])) {
                     // Calculate available spots
                     $availableSpots = json_decode($region['capacity']) - json_decode($region['spots_occupied']);
                     // Set filtered region array
                     $filteredRegion = array('id' => $region->id, 'name' => $region->name, 'capacity' => $region->capacity, 'spots_occupied' => $region->spots_occupied, 'spots_available' => json_encode($availableSpots), 'lot_id' => $region->lot_id);
                     // Calculate lot's available spots
                     $lotAvailableSpots += $availableSpots;
                     // Save each filtered region array to the lot regions array
                     $lotRegions[$j] = $filteredRegion;
                     // Increment the index
                     $j++;
                 }
             }
             // Set the lot array
             $lot = array('id' => $lot->id, 'name' => $lot->name, 'address' => $lot->address, 'spots_available' => json_encode($lotAvailableSpots), 'distance' => $location->distance, 'longitude' => $lot->longitude, 'latitude' => $lot->latitude, 'regions' => $lotRegions);
             // Save each lot in the lots array
             $lots[$i] = $lot;
             // Increment the index
             $i++;
         }
     }
     // Return the lots array
     return $lots;
 }
Example #23
0
 public static function IsCandidate(User $user, $candidate)
 {
     $profile = $user->profile();
     if (!$profile) {
         return false;
     }
     return !$profile->has_photo || $profile->is_old || !is_null(self::ListMergeIssues($profile)) || Geocoder::countNonGeocoded($profile->id()) > 0;
 }
 /**
  * Geocode an address using defined providers
  *
  * @param string $address
  * @param bool $refresh_cache
  * @return Geocoder\Model\Address
  */
 public static function geocodeAddress($address, $refresh_cache = false)
 {
     // Cache support
     if (self::config()->cache_enabled) {
         $cache = self::getCache();
         $cache_key = md5($address . i18n::get_locale());
         if ($refresh_cache) {
             $cache_result = $cache->load($cache_key);
             if ($cache_result) {
                 return unserialize($cache_result);
             }
         }
     }
     try {
         $result = self::getGeocoder()->geocode($address);
         if ($result instanceof \Geocoder\Model\AddressCollection) {
             $result = $result->first();
         }
         if ($result && self::config()->cache_enabled) {
             $cache->save(serialize($result), $cache_key, array('address'), null);
         }
         return $result;
     } catch (Exception $e) {
         $level = SS_Log::WARN;
         if ($e instanceof \Geocoder\Exception\CollectionIsEmpty) {
             $level = false;
         }
         if ($e instanceof \Geocoder\Exception\NoResult) {
             $level = false;
         }
         if ($level) {
             SS_Log::log($e->getMessage(), $level);
         }
         self::$lastException = $e;
         return false;
     }
 }
 /**
  * Handling save profile form
  *
  * @return Response
  */
 public function saveprofile()
 {
     $input = Input::all();
     $id = Auth::user()->id;
     $geo = Geocoder::getCoordinatesForQuery($input['city'] . ', ' . $input['country'] . ', ' . $input['zip']);
     $profile = User::find($id);
     $profile->artist_name = $input['artist_name'];
     $profile->name = $input['name'];
     $profile->country = $input['country'];
     $profile->city = $input['city'];
     $profile->zip = $input['zip'];
     $profile->bio = $input['bio'];
     $profile->phone = $input['phone'];
     $profile->hub = $input['hub'];
     $profile->promo = $input['promo'];
     $profile->profile_url = Str::slug($input['artist_name']);
     $profile->picture = $input['picture_id'];
     $profile->paypal = $input['paypal'];
     if (Input::has('active')) {
         $profile->active = $input['active'];
     }
     $profile->links = $input['links'];
     if ($geo != 'NOT_FOUND') {
         $profile->lat = $geo['lat'];
         $profile->lng = $geo['lng'];
     }
     if (Input::has('web')) {
         foreach ($input['web'] as $w) {
             $link = new WebLink();
             $link->url = $w;
             $link->user = $id;
             $parse = parse_url($w);
             $link->title = $parse['host'];
             $link->save();
         }
     }
     //Disabling validation rules
     $profile::$rules['email'] = '';
     $profile::$rules['agree'] = '';
     $profile->autoHashPasswordAttributes = false;
     if ($profile->save(['artist_name' => 'required|unique:users,artist_name,' . $profile->id, 'profile_url' => 'unique:users,profile_url,' . $profile->id, 'paypal' => 'required|email'])) {
         return Redirect::to('/artist/' . $profile->profile_url);
     } else {
         Input::flash();
         return Redirect::to('profile/settings')->withInput()->with('errors', $profile->errors()->all());
     }
 }
Example #26
0
 function __construct($sw, $ne)
 {
     if (!($sw instanceof LatLng && $ne instanceof LatLng)) {
         $msg = 'The parameters to a Bounds class object must be LatLng. ';
         $msg .= 'The first parameter is a ' . get_class($sw) . '.  The second ';
         $msg .= 'is a ' . get_class($ne) . '.';
         Geocoder::logger('error', $msg);
         return null;
     }
     $this->sw = $sw;
     $this->ne = $ne;
 }
Example #27
0
include_once('geocoder.php');

if (count($_FILES) > 0) {
	if ($_FILES["file"]["error"] > 0) {
		$error = "Error: " . $_FILES["file"]["error"] . "";
	}
	else {
		if ($_FILES["file"]["type"] !== "text/plain") {
			$error = "Error: Your file is not a text file. Your file type: ".$_FILES["file"]["type"]."";
		}
		else {
			$locations = explode("\n", file_get_contents($_FILES["file"]["tmp_name"]));
			$locations_c = array();
			foreach ($locations as $location) {
				$locations_c[] = array("location" => $location, "coordinates" => Geocoder::getLatLng($location));
			}
		}
	}	
}
else {
	$error = "Error: File missing";
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
Example #28
0
 public function main($Location, $unitNum, $timeUnit, $numResults, $session)
 {
     $Loader = new LoadIntoData();
     $Geocoder = new Geocoder();
     $Twitter = new Twitter();
     $Output = new CreateOutput();
     //$Location = 'Toronto';
     $con = mysql_connect(localhost, "slidat_carlos", "cortes299940");
     mysql_select_db("slidat_cps630") or die("Unable to select database");
     $Long_Lat = $Geocoder->geoCoding($Location);
     $latitude = $Long_Lat["Lat"];
     $longitude = $Long_Lat["Long"];
     //echo "main:".$longitude;
     $Loc = $Geocoder->geoCodingReverse($latitude, $longitude);
     $new_location = $Loc["location"];
     $radius = 10;
     $qry = "SELECT Location, Latitude, Longitude FROM Locations";
     //$qry = "SELECT * from Locations";
     $resource = mysql_query($qry);
     $location_table_size = 0;
     if (mysql_num_rows($resource) > 0) {
         $location_table_size = 1;
     }
     while ($row = mysql_fetch_array($resource, MYSQL_ASSOC)) {
         $row_location = $row["Location"];
         $row_lat = $row["Latitude"];
         $row_long = $row["Longitude"];
         $distance = $Geocoder->getDistanceBetweenPointsNew($latitude, $longitude, $row_lat, $row_long);
         //echo "distance= ". $distance ."  ";
         if ($distance < $radius) {
             $matched = 1;
             break;
         } elseif ($distance >= $radius) {
             $matched = 0;
         }
     }
     if ($matched == 1 && $latitude != '' && $longitude != '') {
         $results = $Twitter->searchResultsLatLong($latitude, $longitude);
         $Loader->loadIntoData($results, $new_location, $latitude, $longitude);
         $querys2 = "SELECT Text FROM data WHERE Location = '{$new_location}'";
         $response2 = mysql_query($querys2);
         $myDate = date('y-m-d H:i:s');
         mysql_query("UPDATE Locations SET Date = '{$myDate}' WHERE Location = '{$new_location}'");
         /*
         echo "<h3><u>DATA</u></h3>";
         $counter = 1;
         while (($row2 = mysql_fetch_array($response2, MYSQL_ASSOC)))
          {
         	 if($counter > 20)
         	 {
         	   break;
         	 }
          echo"<h3>Text-hashtag:   ". $row2["Text"] ."</h3>";
          $counter = $counter + 1;
          }
         */
     } elseif (($matched == 0 || $location_table_size == 0) && $latitude != '' && $longitude != '') {
         //new location
         $myDate = date('y-m-d H:i:s');
         $query = "INSERT INTO Locations Values ('{$new_location}', '{$latitude}', '{$longitude}','{$myDate}')";
         $response = mysql_query($query);
         //echo "balls";
         $results = $Twitter->searchResultsLatLong($latitude, $longitude);
         //$command = "/usr/local/bin/php -f /home/slidat/public_html/cgi-bin/loadIntoDataCL.php -a $results -b $new_location -c $latitude -d $longitude";
         //	exec( "$command > /dev/null &");
         $Loader->loadIntoData($results, $new_location, $latitude, $longitude);
     }
     mysql_close();
     //echo "Create output";
     //Create output table for client. Based on client fiends
     return $Output->createOutput($new_location, $unitNum, $timeUnit, $numResults, $session);
 }
Example #29
0
 /**
  * Function to import a report form a row in the CSV file
  * @param array $row
  * @return bool
  */
 function importreport($row)
 {
     // If the date is not in proper date format
     if (!strtotime($row['INCIDENT DATE'])) {
         $this->errors[] = 'Could not parse incident date "' . htmlspecialchars($row['INCIDENT DATE']) . '" on line ' . ($this->rownumber + 1);
     }
     // If a value of Yes or No is NOT set for approval status for the imported row
     if (isset($row["APPROVED"]) and !in_array($row["APPROVED"], array('NO', 'YES'))) {
         $this->errors[] = 'APPROVED must be either YES or NO on line ' . ($this->rownumber + 1);
     }
     // If a value of Yes or No is NOT set for verified status for the imported row
     if (isset($row["VERIFIED"]) and !in_array($row["VERIFIED"], array('NO', 'YES'))) {
         $this->errors[] = 'VERIFIED must be either YES or NO on line ' . ($this->rownumber + 1);
     }
     if (count($this->errors)) {
         return false;
     }
     // STEP 1: SAVE LOCATION
     if (isset($row['LOCATION'])) {
         $location = new Location_Model();
         $location->location_name = isset($row['LOCATION']) ? $row['LOCATION'] : '';
         // If we have LATITUDE and LONGITUDE use those
         if (isset($row['LATITUDE']) and isset($row['LONGITUDE'])) {
             $location->latitude = isset($row['LATITUDE']) ? $row['LATITUDE'] : '';
             $location->longitude = isset($row['LONGITUDE']) ? $row['LONGITUDE'] : '';
             // Geocode reports which don't have LATITUDE and LONGITUDE
         } else {
             $location_geocoded = Geocoder::geocode_location($location->location_name);
             if ($location_geocoded) {
                 $location->latitude = $location_geocoded[1];
                 $location->longitude = $location_geocoded[0];
             }
         }
         $location->location_date = $this->time;
         $location->save();
         $this->locations_added[] = $location->id;
     }
     // STEP 2: SAVE INCIDENT
     $incident = new Incident_Model();
     $incident->location_id = isset($row['LOCATION']) ? $location->id : 0;
     $incident->user_id = 0;
     $incident->incident_title = $row['INCIDENT TITLE'];
     $incident->incident_description = isset($row['DESCRIPTION']) ? $row['DESCRIPTION'] : '';
     $incident->incident_date = date("Y-m-d H:i:s", strtotime($row['INCIDENT DATE']));
     $incident->incident_dateadd = $this->time;
     $incident->incident_active = (isset($row['APPROVED']) and $row['APPROVED'] == 'YES') ? 1 : 0;
     $incident->incident_verified = (isset($row['VERIFIED']) and $row['VERIFIED'] == 'YES') ? 1 : 0;
     $incident->save();
     $this->incidents_added[] = $incident->id;
     // STEP 3: SAVE CATEGORIES
     // If CATEGORY column exists
     if (isset($row['CATEGORY'])) {
         $categorynames = explode(',', trim($row['CATEGORY']));
         // Add categories to incident
         foreach ($categorynames as $categoryname) {
             // There seems to be an uppercase convention for categories... Don't know why
             $categoryname = strtoupper(trim($categoryname));
             // For purposes of adding an entry into the incident_category table
             $incident_category = new Incident_Category_Model();
             $incident_category->incident_id = $incident->id;
             // If category name exists, add entry in incident_category table
             if ($row['CATEGORY'] != '') {
                 if ($categoryname != '') {
                     if (!isset($this->category_ids[$categoryname])) {
                         $this->notices[] = 'There exists no category "' . htmlspecialchars($categoryname) . '" in database yet.' . ' Added to database.';
                         $category = new Category_Model();
                         $category->category_title = $categoryname;
                         // We'll just use black for now. Maybe something random?
                         $category->category_color = '000000';
                         // because all current categories are of type '5'
                         $category->category_visible = 1;
                         $category->category_description = $categoryname;
                         $category->save();
                         $this->categories_added[] = $category->id;
                         // Now category_id is known: This time, and for the rest of the import.
                         $this->category_ids[$categoryname] = $category->id;
                     }
                     $incident_category->category_id = $this->category_ids[$categoryname];
                     $incident_category->save();
                     $this->incident_categories_added[] = $incident_category->id;
                 }
             } else {
                 // Unapprove the report
                 $incident_update = ORM::factory('incident', $incident->id);
                 $incident_update->incident_active = 0;
                 $incident_update->save();
                 // Assign reports to special category for uncategorized reports: NONE
                 $incident_category->category_id = '5';
                 $incident_category->save();
             }
         }
     } else {
         // Unapprove the report
         $incident_update = ORM::factory('incident', $incident->id);
         $incident_update->incident_active = 0;
         $incident_update->save();
         // Assign reports to special category for uncategorized reports: NONE
         $incident_category = new Incident_Category_Model();
         $incident_category->incident_id = $incident->id;
         $incident_category->category_id = '5';
         $incident_category->save();
     }
     return true;
 }
Example #30
0
<?php

include_once('geocoder.php');

if (isset($_GET['location']) && !empty($_GET['location'])) {
	$location = $_GET['location'];
	$gc = Geocoder::getGoogleLatLng($location);
	$yc = Geocoder::getYahooLatLng($location);
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>Geocoders Fight</title>
	<link rel="stylesheet" href="_css/geocoder.css" type="text/css" />
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA0MB-bwjeOkgNnvIVmieN-RRGFE70GU6HoKR8y6scev5RsM1ueBTOQJOiOylC3_4webQgysLYrT4o5A" type="text/javascript"></script>
	<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&amp;appid=ERxj2g3V34HWbC4EUVmhXqsxzruo_eeQ2n6vhj3_1_geb932v.1.crOP3htc2qpA9raYBDEKqy4-"></script>
	<script type="text/javascript" src="_js/geocoder.js"></script>
</head>

<body>

<div id="container">
	<h1>Geocoders Fight</h1>
	<blockquote><p>Compare results from Google and Yahoo! geocoders...</p></blockquote>
	<div id="search">