public function callcheckLocale() { $result = 0; if (isset($_POST['pg_id'])) { $pg_id = $_POST['pg_id']; } else { return $result; } include_once ENGINE_PATH . 'class/classGeoip.php'; include_once ENGINE_PATH . 'class/classPage.php'; $page = new Page($pg_id); $geo = new Geo(); $currenLocale = $geo->getCode(); $pageLang = $page->language; // var_dump($currenLocale, $pageLang); if ($currenLocale != $pageLang) { $geotext = $page->getLocalizedString('geotext', $currenLocale); $relpages = $page->getRelativePageAddresses(); //var_dump($relpages); if (isset($relpages[$currenLocale])) { $result = "<a href='" . $relpages[$currenLocale] . "'>" . $geotext . "</a>"; } } echo $result; }
public function getAllChildren(Geo $geo) { if (!$geo->isLoaded()) { return array(); } return $this->findByWhereMany("parentId = '{$geo->getPKValue()}'"); }
function _display_zip($options) { $geo = new Geo($dbcon); $geo->Zip = $options['map_zip']; $geo->zip_lookup(); $options['map_lat'] = $geo->lat; $options['map_lon'] = $geo->long; return $this->_display_basic($options); }
public function execute($params = array()) { $ip = filter_input(INPUT_POST, 'ip'); $netmask = filter_input(INPUT_POST, 'netmask'); $validateIP = new Net_IPv4(); $net = $validateIP->getNetLength($netmask); $subnet = $validateIP->getSubnet($ip, $netmask); $ipValid = $subnet . '/' . $net; $geo_model = new Geo(); $geos = $geo_model->getGeoList($ipValid); require 'app/Views/Geo_View.php'; }
public function getNameForLocation(Geo $geo, $lang) { if (!$geo->isLoaded()) { return false; } $this->sql_order = 'isshort DESC, ispreferred DESC'; if ($this->findByWhere("geonameId = '{$geo->getPKValue()}' AND isoLanguage = '{$this->dao->escape($lang)}'")) { return $this->alternatename; } else { return false; } }
/** * returns total usage count for $geo * * @param object $geo * @access public * @return int */ public function getAllUsageForGeo(Geo $geo) { $result = $array(); if (!$geo->isLoaded()) { return 0; } $use = $this->getUsageForGeoByType($geo); $count = 0; foreach ($use as $item) { $count += $item; } return $count; }
function getRemote($ip = false) { $ip = $ip ? $ip : $_SERVER['REMOTE_ADDR']; $info = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR'])); self::$info = $info; return $info; }
protected function __construct(LatLng $sw, LatLng $ne) { $s = $sw->lat(); $w = $sw->lng(); $n = $ne->lat(); $e = $ne->lng(); // Wrap latitudes around the globe $s = Geo::wrapLat($s); $n = Geo::wrapLat($n); // Compute difference in longitude extremities $lngDiff = $e - $w; // Compute new longitudes if ($lngDiff >= 360) { $e = 180; $w = -180; } else { $e = Geo::wrapLng($e); $w = Geo::wrapLng($w); } // Assign bounds' attributes $this->s = $s; $this->w = $w; $this->n = $n; $this->e = $e; }
/** * @covers Marando\AstroCoord\Geo::isE */ public function testIsE() { for ($lon = 0; $lon < 180; $lon++) { $this->assertTrue(Geo::deg(0, $lon)->isE(), "1 < Lon < 180 ({$lon})"); } for ($lon = -180; $lon < 0; $lon++) { $this->assertFalse(Geo::deg(0, $lon)->isE(), "-180 < Lon < 0 ({$lon})"); } }
public function __construct($productId) { if (!empty($productId[0])) { $this->productId = intval($productId[0]); } if (1 > $this->productId) { return; } $this->purchase = new Purchase(); if ($this->purchase->init($this->productId)) { if (isset($_POST['process'])) { $this->postValid = $this->validatePost(); } else { $cur = "USD"; $geo = new Geo(); $code = $geo->getCode(); if (!empty($code)) { $cur = $this->purchase->detectCurrency($code); } if (isset($productId[1])) { $cur = $productId[1]; } // if(isset($_COOKIE['currency']) && $_COOKIE['currency']!='null' && $cur!=='RUB') // $cur = $_COOKIE['currency']; if (isset($_GET['cur'])) { $cur = $_GET['cur']; } $this->licenseData = $this->purchase->processLicenseData(); $this->licenseData['geo_currency'] = $cur; $this->licenseData['currencies'] = $this->purchase->returnCurrency(); if (isset($_COOKIE['operatorid'])) { $this->licenseData['operator_id'] = $_COOKIE['operatorid']; } if (isset($_GET['operator'])) { $this->licenseData['operator_id'] = $_GET['operator']; } if (isset($productId[2])) { $this->licenseData['operator_id'] = $productId[2]; } } } }
/** * Converts the response in JSON format to the list of value objects i.e Geo * * @param json * - response in JSON format * * @return List of Geo Points object filled with json data * */ public function buildArrayResponse($json) { $geoObjList = array(); $jsonObj = new JSONObject($json); $jsonObjApp42 = $jsonObj->__get("app42"); $jsonObjResponse = $jsonObjApp42->__get("response"); $jsonObjGeoStorage = $jsonObjResponse->__get("geo"); if ($jsonObjGeoStorage->__get("storage") instanceof JSONObject) { //Single Item $jsonObjGeoStorage = $jsonObjGeoStorage->__get("storage"); $geoObj = new Geo(); $pointList = array(); $geoObj->setPointList($pointList); $geoObj->setStrResponse($json); $geoObj->setResponseSuccess($jsonObjResponse->__get("success")); $this->buildObjectFromJSONTree($geoObj, $jsonObjGeoStorage); array_push($geoObjList, $geoObj); if ($jsonObjGeoStorage->has("points")) { $this->buildInternalObj($geoObj, $jsonObjGeoStorage); } } else { //Multiple Item $jsonStorageArray = $jsonObjGeoStorage->getJSONArray("storage"); for ($i = 0; $i < count($jsonStorageArray); $i++) { $jsonObjStorage = $jsonStorageArray[$i]; $geoObj = new Geo(); $pointList = array(); $geoObj->setPointList($pointList); $geoObj->setStrResponse($json); $geoObj->setResponseSuccess($jsonObjResponse->__get("success")); $jsonObjStorage = new JSONObject($jsonObjStorage); $this->buildObjectFromJSONTree($geoObj, $jsonObjStorage); array_push($geoObjList, $geoObj); if ($jsonObjStorage->has("points")) { $this->buildInternalObj($geoObj, $jsonObjStorage); } } } return $geoObjList; }
function get_geo($modin, $geo_field = NULL, $update = NULL, $limit = '1000', $offset = '0') { global $dbcon; $type = $_REQUEST['type']; if ($update) { $up_sql = ' and ' . $geo_field . ' != "" '; } $sql = "select * from userdata where modin =" . $modin . $up_sql . " limit {$offset}, {$limit}"; $R = $dbcon->Execute($sql) or die("Error getting udm data " . $sql . $dbcon->ErrorMsg()); $t = 0; $x = 0; while (!$R->EOF) { $t++; $geo = new Geo($dbcon); $geo->City = $R->Fields("City"); $geo->State = $R->Fields("State"); $geo->Street = $R->Fields("Street"); $geo->Zip = $R->Fields("Zip"); if ($geo->Street) { $geo->geocoder_getdata(); } ///if ( ($R->Fields("City")) && ($R->Fields("State")) && ($type == 'City') && (!$geo->lat) ) { // $geo->city_lookup(); //} if ($geo->lat && $geo->long) { $sql = "update userdata set " . $geo_field . " = '" . $geo->lat . "," . $geo->long . "' where id = " . $R->Fields("id"); $dbcon->Execute($sql) or die("Error updating udm " . $sql . $dbcon->ErrorMsg()); echo $R->Fields("id") . ": " . $geo->lat . $geo->long . "<br>"; $x++; } else { $html .= "<a href = 'modinput4_view.php?uid=" . $R->Fields("id") . "&modin=" . $modin . "'>" . $R->Fields("Street") . " " . $R->Fields("City") . " " . $R->Fields("State") . " " . $R->Fields("Zip") . " </a><br>"; } $R->MoveNext(); } $out = "Found {$x} address of {$t} <br><br>Failed Addresses<br> {$html}"; return $out; }
<?php error_reporting(E_ALL); ini_set('display_errors', true); header('Content-type: text/html; charset=UTF-8'); include 'geo.php'; $geo = new Geo(); // запускаем класс // Если хотите передать в функцию уже известный IP, то можно сделать так // $o['ip'] = '178.204.102.30'; <-- Пример IP адреса г. Казань // $geo = new Geo($o); // этот метод позволяет получить все данные по ip в виде массива. // массив имеет ключи 'inetnum', 'country', 'city', 'region', 'district', 'lat', 'lng' $data = $geo->get_value(); // если нужен какой то отдельный параметр, передаем его в функцию в виде первого значения //$data = $geo->get_value('city'); // например, вернет название города # $data = $geo->get_value('country'); // вернет название страны # $data = $geo->get_value('region'); // вернет название региона # $data = $geo->get_value('district'); // вернет название района # lat - географическая ширина и lng - долгота # inetnum - диапазон ip адресов, в который входит проверяемый ip адрес // чтобы использовать кеширование нужно в функцию передать второй параметр - true или false # пример //$data = $geo->get_value('city', true); // если true, то данные о городе пользователя сохранятся в куки браузера // в этом случае повторный запрос для проверки происходить не будет. // это рекомендуется и поэтому по-умолчанию кешеривание включено # пример //$data = $geo->get_value('city', false); // если false, то данные каждый раз будут запрашиваться с сервера ipgeobase //также кеширование используется и для других параметров
/** * Declares an association between this object and a Geo object. * * @param Geo $v * @return Institucion The current object (for fluent API support) * @throws PropelException */ public function setGeo(Geo $v = null) { if ($v === null) { $this->setGeoId(NULL); } else { $this->setGeoId($v->getId()); } $this->aGeo = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the Geo object, it will not be re-added. if ($v !== null) { $v->addInstitucion($this); } return $this; }
/** * finds a local group for a geo location * * @param object $geo * @access public * @return object|false */ public function getGroupForGeo(Geo $geo, $local = false) { if (!$geo->isLoaded()) { return false; } return $this->findByWhere("IdGeoname = '{$geo->getPKValue()}'" . ($local ? " AND IsLocal = TRUE" : '')); }
function read_request() { $this->setupRegion(); $options = $this->getOptions(); // CHECK FOR SEARCH CRITERIA //ByDate //looks for records changed after the specified date if (isset($_REQUEST['bydate']) && $_REQUEST['bydate']) { $sql_criteria[] = '`timestamp` >= ' . $this->dbcon->qstr($_REQUEST['bydate']); } //Zip Code Search Request if (isset($_REQUEST['zip']) && isset($_REQUEST['distance']) && $_REQUEST['zip'] && $_REQUEST['distance']) { $srch_options['zip'] = $_REQUEST['zip']; $srch_options['distance'] = $_REQUEST['distance']; $srch_loc = new Geo($this->dbcon, NULL, NULL, NULL, $_REQUEST['zip']); if ($ziplist = $srch_loc->zip_radius($_REQUEST['distance'])) { $zipset = "(" . $_REQUEST['zip']; foreach ($ziplist as $zindex => $zinfo) { if (strlen($zindex) == 4) { $zindex = '0' . $zindex; } $zipset .= "," . $this->dbcon->qstr($zindex); } $zipset .= ")"; $sql_criteria[] = "zip IN {$zipset}"; } else { $flash = AMP_System_Flash::instance(); $flash->add_message("Sorry, no match found for that zip code"); //$this->udm->errorMessage("Sorry, no match found for that zip code"); } } //State Request from index page if (isset($_REQUEST['state']) && $_REQUEST['state']) { $sql_criteria[] = "State=" . $this->dbcon->qstr($_REQUEST['state']); $this->lookups['city']['LookupWhere'] = " modin=" . $this->udm->instance . " AND State=" . $this->dbcon->qstr($_REQUEST['state']); $this->setupLookup('city'); $city_value = isset($_REQUEST['city']) && $_REQUEST['city'] ? $_REQUEST['city'] : null; $this->fields_def['city'] = array('type' => 'select', 'label' => 'Select City', 'values' => $this->lookups['city']['Set'], 'value' => $city_value); } //city Request from index page if (isset($_REQUEST['city']) && $_REQUEST['city']) { $sql_criteria[] = "city=" . $this->dbcon->qstr($_REQUEST['city']); } //Area Request from pulldown if (isset($_REQUEST['area']) && $_REQUEST['area']) { $this->setupLookup('area'); if ($state_name = $this->lookups['area']['Set'][$_REQUEST['area']]) { $state_code = array_search($state_name, $this->lookups['state']['Set']); if ($state_code) { $sql_criteria[] = "State=" . $this->dbcon->qstr($state_code); } } } //Country if (isset($_REQUEST['country']) && $_REQUEST['country']) { //check to see if the search is by code if (strlen($_REQUEST['country']) == 3 && ($country_name = $this->lookups['country']['Set'][$_REQUEST['country']])) { $criteria_code = "Country=" . $this->dbcon->qstr($_REQUEST['country']); } else { if ($country_code = array_search($_REQUEST['country'], $this->regionset->regions['WORLD'])) { $criteria_code = "Country=" . $this->dbcon->qstr($country_code); } } $sql_criteria[] = "( " . $criteria_code . " OR ( Country=" . $this->dbcon->qstr($_REQUEST['country']) . "))"; } //Keyword - fulltext search if (isset($_REQUEST['keyword']) && $_REQUEST['keyword']) { //Create a set of phrases to search for $kwsearch = $_REQUEST['keyword']; if (substr_count($kwsearch, '"') >= 2) { //extract quoted phrases //method kudos to insipience.com preg_match_all("/\"([\\w\\s]+)(\"|\$)/", $kwsearch, $matches, PREG_PATTERN_ORDER); $phrases = $matches[1]; $terms = explode(" ", preg_replace("/\"[\\w\\s]*(\"|\$)/", "", $kwsearch)); $phrase_set = array_merge($terms, $phrases); } else { $phrase_set = split(' ', $kwsearch); } //determine the fields to include in the search $db_fields = $this->udm->dbcon->MetaColumnNames('userdata'); foreach ($this->udm->fields as $fname => $fdef) { if ($fdef['type'] == 'text' || $fdef['type'] == 'textarea') { $textfields[] = $fname; } } if (is_array($textfields)) { $src_fields = array_intersect($db_fields, $textfields); //SQL should be case-insensitive by default //but it's acting weird, so let's force the issue. foreach ($src_fields as $key => $value) { $src_fields[$key] = "if(isnull(`" . $value . "`),'',`" . $value . "`)"; } $src_name = "Lower(Concat( " . join(',', $src_fields) . "))"; foreach ($phrase_set as $keyword) { //make sure it's not an empty phrase if ($keyword) { $sql_criteria[] = "{$src_name} LIKE " . $this->dbcon->qstr('%' . strtolower($keyword) . '%'); } } } } //Company if (isset($_REQUEST['Company']) && $_REQUEST['Company']) { $sql_criteria[] = "Company LIKE" . $this->dbcon->qstr('%' . $_REQUEST['Company'] . '%'); } //Modin if (isset($_REQUEST['modin']) && $_REQUEST['modin']) { $sql_criteria['modin'] = "modin=" . $_REQUEST['modin']; } //Uid or Creator_id if (isset($_REQUEST['uid']) && $_REQUEST['uid']) { if (is_array($_REQUEST['uid'])) { //allow for multiple ids $sql_criteria[] = "id in(" . join(",", $_REQUEST['uid']) . ")"; } else { $sql_criteria[] = "id=" . $this->dbcon->qstr($_REQUEST['uid']); } } //Publish status if (isset($_REQUEST['publish']) && is_numeric($_REQUEST['publish'])) { if ($_REQUEST['publish']) { $sql_criteria[] = "publish=1"; } else { $sql_criteria[] = "(isnull(publish) OR publish!=1)"; } } //tags if (isset($_REQUEST['tag']) && $_REQUEST['tag']) { $tagged_forms = AMPSystem_Lookup::instance('formsByTag', $_REQUEST['tag']); if (!$tagged_forms || empty($tagged_forms)) { $sql_criteria[] = 'FALSE'; } else { $sql_criteria[] = 'id in( ' . join(",", array_keys($tagged_forms)) . ')'; } } //name if (isset($_REQUEST['name']) && $_REQUEST['name']) { $sql_criteria[] = 'Concat( if( isnull( First_Name ), "", First_Name ), if ( isnull( Last_Name ), "", Last_Name ), if ( isnull( Company ), "", Company )) LIKE ' . $this->dbcon->qstr('%' . str_replace(' ', '%', $_REQUEST['name']) . '%'); } //arbitrary "extra" fields sql if (isset($options['search_extra_fields_sql']) && $options['search_extra_fields_sql'] && function_exists($options['search_extra_fields_sql'])) { $extra_sql_function = $options['search_extra_fields_sql']; $extra_criteria = $extra_sql_function($this); if ($extra_criteria) { $sql_criteria = array_merge($sql_criteria, $extra_criteria); } } $specified_fields = array('publish', 'search', 'sortby', 'qty', 'offset', 'uid', 'modin', 'country', 'area', 'city', 'state', 'zip', 'distance', 'bydate', 'tag', 'name', 'keyword'); foreach ($this->_included_fields as $fieldname) { if (!isset($this->udm->fields[$fieldname])) { continue; } if (array_search($fieldname, $specified_fields) !== FALSE) { continue; } if (!(isset($_REQUEST[$fieldname]) && $_REQUEST[$fieldname])) { continue; } if (is_int($_REQUEST[$fieldname])) { //do precise search for numeric values $sql_criteria[] = $fieldname . ' = ' . $this->dbcon->qstr($_REQUEST[$fieldname]); } elseif (is_array($_REQUEST[$fieldname]) && $this->udm->fields[$fieldname]['type'] == 'date') { $date_preferences = 'form.' . $this->udm->instance . '.date.search.inc.php'; if (!file_exists_incpath($date_preferences)) { $request_year = isset($_REQUEST[$fieldname]['Y']) && $_REQUEST[$fieldname]['Y'] ? $_REQUEST[$fieldname]['Y'] : false; $request_month = isset($_REQUEST[$fieldname]['M']) && $_REQUEST[$fieldname]['M'] ? $_REQUEST[$fieldname]['M'] : false; //if ( $request_month && $request_year ) { //$sql_criteria[] = $fieldname . ' > ' . $this->dbcon->qstr( $]['Y'] . '-' . str_pad( $_REQUEST[$fieldname]['M'], 2, '0', STR_PAD_LEFT) . '-01' ); //$sql_criteria[] = $fieldname . ' < ' . $this->dbcon->qstr( $_REQUEST[$fieldname]['Y'] . '-' . str_pad( $_REQUEST[$fieldname]['M'], 2, '0', STR_PAD_LEFT) . '-32' ); //} if ($request_year) { $sql_criteria[] = 'YEAR( ' . $fieldname . ') = ' . $this->dbcon->qstr($_REQUEST[$fieldname]['Y']); } if ($request_month) { $sql_criteria[] = 'MONTH( ' . $fieldname . ') = ' . $this->dbcon->qstr($_REQUEST[$fieldname]['M']); } } else { $date_crit_method = 'form_' . $this->udm->instance . '_date_search'; include_once $date_preferences; $sql_criteria[] = $date_crit_method($fieldname); } } else { //do string 'contains' search $sql_criteria[] = $fieldname . ' LIKE ' . $this->dbcon->qstr('%' . $_REQUEST[$fieldname] . '%'); } } //Vet valid URL data $vetted_set = array(); $criteria_set = $this->udm->getURLCriteria(); foreach ($this->fields_def as $field => $fdef) { if (!isset($criteria_set[$field])) { continue; } if (!($criteria_set[$field] || $criteria_set[$field] === '0')) { continue; } $vetted_set[$field] = $criteria_set[$field]; } $this->udm->url_criteria = $vetted_set; return $sql_criteria; }
<?php // Set the error_reporting to E_ALL error_reporting(E_ALL); // Include the config file require_once 'includes/config.php'; // Include the mail library which processes the geocoding requests require_once 'lib/geo.inc.php'; // If we have debug parameter in the URL then set the debug mode $debug = !empty($_GET['debug']) ? true : false; $geo = new Geo($debug, $config); // Get either the coordinates or address depending on the current request parameter if (!empty($_GET['q'])) { $r = $geo->get_latlon($_GET['q']); } elseif (!empty($_GET['g'])) { $r = $geo->get_address($_GET['g']); } // If there were errors then display the same $c = count($geo->last_status) - 1; if ($c < 0) { $c = 0; } if (!empty($geo->last_error[$c])) { echo $geo->last_error[$c]; } else { // If callabck method was specified then call it if (!empty($_GET['callback'])) { header('Content-Type: application/javascript'); if (!empty($_GET['q'])) { echo $_GET['callback'] . "([" . $r . "]);"; } elseif (!empty($_GET['g'])) {
require( $hd."/bitrix/modules/main/include/prolog_before.php"); ini_set('display_errors', 1 ); CModule::IncludeModule('iblock'); require( $hd."/service/contract/c_geodata.php"); if ( isset($_REQUEST["get"]) ){ $result = array(); switch( $_REQUEST["get"] ){ case 'country': $result["data"] = Geo::getCounty(intval( $_REQUEST["cid"] )); break; case 'district': break; case 'region': $result["data"] = Geo::getRegion(intval( $_REQUEST["cid"] ),intval( $_REQUEST["did"] ),intval( $_REQUEST["rid"] )); break; case 'town': $result["data"] = Geo::getCity( intval($_REQUEST["cid"]), intval($_REQUEST["did"]), intval($_REQUEST["rid"]), intval($_REQUEST["tid"]) ); break; } echo json_encode ( $result ); } require( $hd."/bitrix/modules/main/include/epilog_after.php");?>
function makeCriteriaZipDistance($value, $value_type = 'zip') { if (!$this->_zip_distance_expected) { //a distance alone returns TRUE, a zip alone will be checked vs lzip return $value_type == 'zip' ? $this->_makeCriteriaContains('lzip', $value) : 'TRUE'; } $this->_zip_distance[$value_type] = $value; //check to make sure both parameters are set if (!(isset($this->_zip_distance['distance']) && isset($this->_zip_distance['zip']))) { return 'TRUE'; } require_once 'AMP/Geo/Geo.php'; $geo_search = new Geo($this->dbcon, null, null, null, $this->_zip_distance['zip']); $included_zips = $geo_search->zip_radius($this->_zip_distance['distance']); $included_zips[$this->_zip_distance['zip']] = "base"; $included_zips = array_map(array($this, '_zip_crit'), array_keys($included_zips)); return 'lzip IN ( ' . join(',', $included_zips) . ')'; }
/** * Update the specified resource in storage. * PATCH /comments/{id} * * @param int $id * @return Response */ public function update($id) { // $validator = Comment::validate(Input::all()); $user = Auth::user(); // if ($validator->fails()) // return $this->respondInsufficientPrivileges($validator->messages()->all()); if (Input::get('text') == '' & !Input::has('attachments')) { return $this->respondInsufficientPrivileges('Send some text'); } if (strlen(Input::get('text')) > 2500) { return $this->respondInsufficientPrivileges('Слишком длинный текст'); } $comment = Comment::find($id); if (!$comment) { return $this->respondNotFound('Comment not found'); } if (!$user->can('Comment.update', $comment)) { return $this->respondInsufficientPrivileges('Unauthorized action'); } $comment->fill(Input::all()); if ($comment->save()) { if (Input::has('attachments') && !empty(Input::get('attachments'))) { $attachments = Input::get('attachments'); $comment->cars()->detach(); $comment->geos()->detach(); $comment->carsWithNumbers()->detach(); foreach ($attachments as $attachment) { $carHelper = new Helpers\carHelper(); if ($attachment['type'] == 'Geo') { $geo = Geo::create(['long' => $attachment['long'], 'lat' => $attachment['lat'], 'location' => $attachment['location']]); $comment->geos()->save($geo); } if ($attachment['type'] == 'Car') { $car = $carHelper::fetchCar($user, $attachment['id']); if ($car) { $comment->cars()->attach($car->id); } } if ($attachment['type'] == 'CarNumber') { $car = $carHelper::fetchCar($user, $attachment['id']); if ($car) { $comment->carsWithNumbers()->attach($car->id); } } if ($attachment['type'] == 'Image') { $image = Image::find($attachment['id']); if ($image && !$comment->images()->find($attachment['id'])) { $comment->images()->save($image); } if ($comment->images()->find($attachment['id'])) { $images[] = $image->id; } } } if (isset($images)) { $comment->images()->whereNotIn('id', $images)->delete(); } else { $comment->images()->delete(); } } else { $comment->images()->delete(); $comment->cars()->detach(); $comment->geos()->detach(); $comment->carsWithNumbers()->detach(); } return $this->respond($this->collectionTransformer->transformComment($comment)); } return $this->respondServerError(); }
*/ function is_valid_ip($ip = null) { if (preg_match("#^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\$#", $ip)) { return true; } // если ip-адрес попадает под регулярное выражение, возвращаем true return false; // иначе возвращаем false } } header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Cache-Control: post-check=0,pre-check=0"); header("Cache-Control: max-age=0"); header("Pragma: no-cache"); header("Content-type: text/javascript"); $o = array(); $o['charset'] = 'utf-8'; //$o['ip'] = '213.149.3.180'; // для тестирования $geo = new Geo($o); $data = $geo->get_value(false, false); // print ("var client = {lat:0,lon:0,ip:''};\n"); if (count($data) > 0 && $data['lat'] != '' && $data['lon'] != '') { print "var clientLat = " . $data['lat'] . ";\n"; print "var clientLon = " . $data['lon'] . ";\n"; } else { print "var clientLat = 0;\n"; print "var clientLon = 0;\n"; } print "var clientIp = '" . $geo->get_ip() . "';\n";
/** * Makers list */ public function indexAction() { $request = $this->request; $persistent = $this->persistent; // Reset $reset = $this->request->getQuery('reset', 'int'); if (isset($reset)) { $persistent->makersParams = null; } // Persistent parameters if (!is_array($persistent->makersParams)) { $persistent->makersParams = ['qry' => ['conditions' => "id IS NOT NULL", 'order' => 'updated DESC'], 'sort' => ['page' => 1, 'perpage' => 50]]; } $parameters = $persistent->makersParams; $parameters['sort']['perpage'] = isset($parameters['sort']['perpage']) ? $parameters['sort']['perpage'] : 50; $parameters['sort']['page'] = isset($parameters['sort']['page']) ? $parameters['sort']['page'] : 1; if ($request->getQuery('page', 'int')) { $parameters['sort']['page'] = $request->getQuery('page', 'int'); } if ($request->getQuery('perpage', 'int')) { $parameters['sort']['perpage'] = $request->getQuery('perpage', 'int'); } // Search if ($request->isPost()) { $parameters['search_region'] = null; $parameters['search_approved'] = null; // Placer if (!empty($_POST['search_region'])) { $search_region_get = $request->getPost('search_region', 'int'); $parameters['search_region'] = $search_region_get; $search_region = " AND geo_id = {$search_region_get}"; } else { $search_region = null; } // Name or ID if (!empty($_POST['search_name'])) { $search_name_get = $request->getPost('search_name', 'string'); if (preg_match('/^[0-9,\\s]+$/', $request->getPost('search_name', 'string'))) { $search_split = preg_split('/[,\\s]/', $search_name_get, 0, PREG_SPLIT_NO_EMPTY); $search_name = implode(', ', $search_split); $search_name = " AND id IN ({$search_name})"; } else { $search_name = " AND name LIKE '%{$search_name_get}%'"; } } else { $search_name_get = null; $search_name = null; } // Email if (!empty($_POST['search_email'])) { $search_email_get = $request->getPost('search_email', 'string'); $search_email = " AND email LIKE '%{$search_email_get}%'"; } else { $search_email_get = null; $search_email = null; } // Phone if (!empty($_POST['search_phone'])) { $search_phone_get = $request->getPost('search_phone', 'string'); $search_phone = " AND phone LIKE '%{$search_phone_get}%' OR phone2 LIKE '%{$search_phone_get}%'"; } else { $search_phone_get = null; $search_phone = null; } // Approved status if (!empty($_POST['search_approved'])) { $search_approved_get = $request->getPost('search_approved', 'int'); $parameters['search_approved'] = $search_approved_get; $search_approved = " AND approved = {$search_approved_get}"; } else { $search_approved = null; } // Search parameters $parameters['qry'] = ['conditions' => "id IS NOT NULL\n {$search_region}\n {$search_name}\n {$search_email}\n {$search_phone}\n {$search_approved}"]; } // Other parameters $parameters['count'] = PMaker::count($parameters['qry']); $parameters['qry']['order'] = "updated DESC"; $parameters['qry']['limit'] = 10000; $persistent->makersParams = $parameters; // var_dump($parameters); $makers = PMaker::find($parameters['qry']); // Paginator $paginator = new Paginator(["data" => $makers, "limit" => $parameters['sort']['perpage'], "page" => $parameters['sort']['page']]); $this->view->page = $paginator->getPaginate(); // Set selected search values $this->view->selected_region = isset($parameters['search_region']) && !empty($parameters['search_region']) ? $parameters['search_region'] : null; $this->view->selected_approved = isset($parameters['search_approved']) && !empty($parameters['search_approved']) ? $parameters['search_approved'] : null; $this->view->makers_count = $parameters['count']; // All regions $this->view->regions_list = array_column(Geo::find(['order' => 'title ASC'])->toArray(), 'title', 'id'); // Currencies $currencies_array = array_column(PCrosscurrency::find()->toArray(), 'title', 'title'); $this->view->currencies_list = ['UAH' => $currencies_array['UAH']] + $currencies_array; // Countries $countries_array = array_column(Countries::find("active=1")->toArray(), 'title', 'id'); $ukraine = array_search('Украина', $countries_array); $this->view->countries_list = [$ukraine => $countries_array[$ukraine]] + $countries_array; $this->view->users_list = Accounts::getUsersByRole(['researcher', 'mobilegroup'], false, 'name ASC'); $this->view->can_edit = AccRoles::findFirst("user_id={$this->auth->id} AND (role_id=991 OR role_id=5)"); }
function geo() { $this->set('title', 'Geo'); $this->expect(is_null($this->get('ERROR')), 'No errors expected at this point', 'ERROR variable is set: ' . $this->get('ERROR.text')); $this->expect(Geo::$countries, 'Geo plugin returns ' . count(Geo::$countries) . ' countries', 'Geo plugin failed to retrieve countries'); $tz = Geo::timezones(); $this->expect(count($tz), 'Geo plugin returns an array of ' . count($tz) . ' timezones', 'Geo plugin failed to retrieve timezones'); while (TRUE) { $loc = array_rand($tz); if (is_int(strpos($loc, '/')) && is_bool(strpos($loc, 'Etc'))) { break; } } $this->expect($tz[$loc], $loc . ' timezone returns UTC' . ($tz[$loc]['offset'] ? '+' : '') . $tz[$loc]['offset'] . ' offset', 'UTC offset not available'); $this->set('QUIET', TRUE); $weather = Geo::weather($tz[$loc]['latitude'], $tz[$loc]['longitude']); $this->set('QUIET', FALSE); $this->expect($weather, 'GeoNames weather report: Temperature at ' . $weather['stationName'] . ' is ' . $weather['temperature'] . ' degrees', 'Weather report for above location is not available'); $this->clear('ERROR'); $this->set('QUIET', TRUE); $location = Geo::location(); $this->set('QUIET', FALSE); $this->expect($location, 'Detected GeoLocation is ' . $location['city'] . ', ' . $location['countryName'], 'GeoLocation is not available'); $this->clear('ERROR'); echo $this->render('basic/results.htm'); }
function mergiLng($lng, $zoom) { $f = GEO_TILE_SIZE * pow(2, $zoom); return Geo::mercatorLngInv($lng / $f * GEO_2_PI - M_PI); }
/** * Get distance from current Geo object coordinates to another * * @param Geo $dest * @param int $round * @param boolean $km * @throws Exception * @return mixed */ public function distanceTo(Geo $dest, $round = 2, $km = false) { $distance = null; if (null === $this->latitude || null === $this->longitude) { throw new Exception('The origin coordinates are not set.'); } if (null === $dest->getLatitude() || null === $dest->getLongitude()) { throw new Exception('The destination coordinates are not set.'); } $origin = ['latitude' => $this->latitude, 'longitude' => $this->longitude]; $destination = ['latitude' => $dest->getLatitude(), 'longitude' => $dest->getLongitude()]; return self::calculateDistance($origin, $destination, $round, $km); }
/** * Adds an object to the instance pool. * * Propel keeps cached copies of objects in an instance pool when they are retrieved * from the database. In some cases -- especially when you override doSelect*() * methods in your stub classes -- you may need to explicitly add objects * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * * @param Geo $value A Geo object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ public static function addInstanceToPool(Geo $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { $key = (string) $obj->getId(); } // if key === null self::$instances[$key] = $obj; } }
/** * Экспорт результатов */ function showExport() { global $surveys_dictonaries; // список справочников из настроек include_once PATH_COMMON . '/classes/geo.php'; $geo = new Geo(array('dbname' => $this->geo_dbname, 'tablename' => $this->geo_tablename)); $columns = sql_getRows("SHOW COLUMNS FROM `surveys_users`", true); if (!isset($columns['region'])) { sql_query("ALTER TABLE `surveys_users` ADD region VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['city'])) { sql_query("ALTER TABLE `surveys_users` ADD city VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['district'])) { sql_query("ALTER TABLE `surveys_users` ADD district VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['country'])) { sql_query("ALTER TABLE `surveys_users` ADD country VARCHAR( 255 ) NOT NULL;"); } $id = (int) get('id', 0, 'g'); $export = array(); $export2 = array(); $quests = sql_getRows('SELECT id, text, type FROM surveys_quests WHERE id_survey=' . $id); // Cоберем верхнюю строку - заголовки $row = array(); foreach ($this->exported_fields as $fld) { $row[] = $this->str('export_' . $fld); } foreach ($quests as $k => $quest) { $row[] = $this->__csv_chars($quest['text']); $variants = sql_getRows("SELECT id, text FROM surveys_quest_variants\n WHERE id_quest={$quest['id']} ORDER BY priority"); foreach ($variants as $v) { $v['text'] = $this->__csv_chars($v['text']); if ($quest['type'] == 'single' || $quest['type'] == 'multi') { $row[] = $v['text']; } elseif ($quest['type'] == 'catalog') { $catalog = $this->getDictonaryValues($v['text']); foreach ($catalog as $item) { $row[] = $item['name']; } } } if (in_array($quest['type'], array('single', 'multi', 'catalog'))) { $row[] = ''; } $quests[$k]['variants'] = $variants; } $export[] = implode(';', $row); $export2[] = implode(';', $row); $users = sql_getRows("SELECT * FROM surveys_users WHERE id_survey = '{$id}' ORDER BY date", false); // Cоберем результаты foreach ($users as $k => $u) { $u['number'] = $k + 1; if (!$u['country'] && !$u['district'] && !$u['region'] && !$u['city'] && $geo->is_valid_ip($u['ip'])) { $geo->ip = $u['ip']; $ip_data = $geo->get_value(); $u['city'] = mysql_real_escape_string($ip_data['city']); $u['region'] = mysql_real_escape_string($ip_data['region']); $u['district'] = mysql_real_escape_string($ip_data['district']); $u['country'] = mysql_real_escape_string($ip_data['country']); sql_query('UPDATE surveys_users SET city="' . $u['city'] . '", region="' . $u['region'] . '", district="' . $u['district'] . '", country="' . $u['country'] . '" WHERE id="' . $u['id'] . '"'); } $sql = "SELECT af.text as text\n FROM surveys_log as sl LEFT JOIN surveys_free_answ as af\n ON (af.id_variant=sl.id_variant && af.id_user=sl.id_user)\n WHERE sl.id_user='******'id']}'"; $row = array(); foreach ($this->exported_fields as $fld) { $row[] = $u[$fld]; } $row2 = $row; foreach ($quests as $quest) { switch ($quest['type']) { case 'single': case 'multi': $row[] = ''; $row2[] = ''; foreach ($quest['variants'] as $v) { $data = sql_getRow($sql . ' AND sl.id_variant = ' . $v['id']); if (!empty($data)) { $row[] = $this->str('export_cb_answer'); if ($data['text']) { $row2[] = $this->__csv_chars($data['text']); } else { $row2[] = $v['text']; } } else { $row[] = $this->str('export_cb_no_answer'); $row2[] = $this->str('export_cb_no_answer'); } } $row[] = ''; $row2[] = ''; break; case 'catalog': $row[] = ''; $row2[] = ''; $catalog = $this->getDictonaryValues($quest['variants']['0']['text']); // данные для типа опроса, справочник $data = sql_getRow('SELECT t.' . $surveys_dictonaries[$quest['variants']['0']['text']]['value'] . ', t.' . $surveys_dictonaries[$quest['variants']['0']['text']]['name'] . ' as text FROM surveys_log sl LEFT JOIN ' . $surveys_dictonaries[$quest['variants']['0']['text']]['table'] . ' as t ON (t.id=sl.text) WHERE sl.id_user='******'id'] . ' AND sl.id_quest=' . (int) $quest['id']); // список вариантов ответов foreach ($catalog as $item) { if (!empty($data) && $data[$surveys_dictonaries[$quest['variants']['0']['text']]['value']] == $item['value']) { $row[] = $this->str('export_cb_answer'); $row2[] = $this->__csv_chars($item['name']); } else { $row[] = $this->str('export_cb_no_answer'); $row2[] = $this->str('export_cb_no_answer'); } } $row[] = ''; $row2[] = ''; break; break; default: foreach ($quest['variants'] as $v) { $text = $this->__csv_chars(sql_getValue($sql . ' AND sl.id_variant = ' . $v['id'])); $row[] = $text; $row2[] = $text; } } } $export[] = implode(';', $row); $export2[] = implode(';', $row2); } $this->writeArchive(array('exported_survey_v_check.csv' => implode("\n", $export), 'exported_survey_v_text.csv' => implode("\n", $export2))); }
public function adminUpdate($id) { // dd(Input::all()); $post = Post::find($id); if (!$post) { App::abort(404); } $post->fill(Input::all()); if (Input::has('geo')) { $post->geos()->detach(); $post->geos()->save(Geo::create(['long' => Input::get('geo')['long'], 'lat' => Input::get('geo')['lat'], 'location' => Input::get('geo')['location']])); } if (Input::has('car')) { $post->cars()->detach(); $user = User::find($post->user_id); $carHistory = $user->carsHistory()->create(['mark' => Input::get('car')['mark'] != 0 ?: null, 'model' => Input::get('car')['model'] != 0 ?: null, 'year' => Input::get('car')['year'] != 0 ?: null, 'color' => Input::get('car')['color'] != 0 ?: null, 'body_type' => Input::get('car')['body_type'] != 0 ?: null]); $post->cars()->attach($carHistory->id); } if (Input::has('carNumber')) { $post->carsWithNumbers()->detach(); $user = User::find($post->user_id); $carNumber = $user->carsHistory()->create(['mark' => Input::get('carNumber')['mark'] != 0 ?: null, 'model' => Input::get('carNumber')['model'] != 0 ?: null, 'year' => Input::get('carNumber')['year'] != 0 ?: null, 'color' => Input::get('carNumber')['color'] != 0 ?: null, 'body_type' => Input::get('carNumber')['body_type'] != 0 ?: null]); $post->carsWithNumbers()->attach($carNumber->id); } if (Input::has('images')) { foreach (Input::get('images') as $image) { dd($image); } } if ($post->save()) { return Redirect::to('/admin/posts'); } App::abort(500); }
function read_request() { global $_REQUEST; $this->setupRegion(); // CHECK FOR SEARCH CRITERIA //ByDate //searches for future events only if no start date is specified. if (isset($_REQUEST['bydate']) && $_REQUEST['bydate']) { $sql_criteria[] = '((`date` >= ' . $this->dbcon->qstr($_REQUEST['bydate']) . ' AND `recurring_options`=0) OR (`enddate`>=' . $this->dbcon->qstr($_REQUEST['bydate']) . ' AND `recurring_options`>0))'; } elseif ($exact_date = $this->_makeExactDate()) { $sql_criteria[] = '( `date` = ' . $this->dbcon->qstr($exact_date) . ')'; } else { if (!(isset($_REQUEST['old']) && $_REQUEST['old'] == 1)) { $sql_criteria[] = '((`date` >= CURDATE() AND `recurring_options`=0) || (`recurring_options`>0 AND `enddate`>= CURDATE() ))'; } } //Zip Code Search Request if (isset($_REQUEST['zip']) && isset($_REQUEST['distance']) && $_REQUEST['zip'] && $_REQUEST['distance']) { $srch_options['zip'] = $_REQUEST['zip']; $srch_options['distance'] = $_REQUEST['distance']; $srch_loc = new Geo($this->dbcon, NULL, NULL, NULL, $_REQUEST['zip']); if ($ziplist = $srch_loc->zip_radius($_REQUEST['distance'])) { $zipset = "(" . $_REQUEST['zip']; foreach ($ziplist as $zindex => $zinfo) { if (strlen($zindex) == 4) { $zindex = '0' . $zindex; } $zipset .= "," . $this->dbcon->qstr($zindex); } $zipset .= ")"; $sql_criteria[] = "lzip IN {$zipset}"; } else { $this->calendar->error = "Sorry, US zip codes only"; } } //State Request from event index page if (isset($_REQUEST['state']) && $_REQUEST['state']) { $sql_criteria[] = "lstate=" . $this->dbcon->qstr($_REQUEST['state']); $this->lookups['lcity']['LookupWhere'] = " lstate=" . $this->dbcon->qstr($_REQUEST['state']); $this->setupLookup('lcity'); $this->fields_def['city'] = array('type' => 'select', 'label' => 'Select City', 'values' => $this->lookups['lcity']['Set'], 'value' => $_REQUEST['city']); } //city Request from event index page if (isset($_REQUEST['city']) && $_REQUEST['city']) { $sql_criteria[] = "lcity=" . $this->dbcon->qstr($_REQUEST['city']); } //Area Request from pulldown if (isset($_REQUEST['area']) && $_REQUEST['area']) { $this->setupLookup('area'); if ($state_name = $this->lookups['area']['Set'][$_REQUEST['area']]) { $state_code = array_search($state_name, $this->lookups['lstate']['Set']); if ($state_code) { $sql_criteria[] = "lstate=" . $this->dbcon->qstr($state_code); } } } //Event Type if (isset($_REQUEST['caltype']) && $_REQUEST['caltype']) { $this->setupLookup('caltype'); $sql_criteria[] = "typeid=" . $this->dbcon->qstr($_REQUEST['caltype']); } //Country if (isset($_REQUEST['lcountry']) && $_REQUEST['lcountry']) { //check to see if the search is by code if (strlen($_REQUEST['lcountry']) == 3 && ($country_name = $this->lookups['lcountry']['Set'][$_REQUEST['lcountry']])) { $sql_criteria[] = "lcountry=" . $this->dbcon->qstr($_REQUEST['lcountry']); } else { if ($country_code = array_search($_REQUEST['lcountry'], $this->regionset->regions['WORLD'])) { $sql_criteria[] = "lcountry=" . $this->dbcon->qstr($country_code); } } } //Modin if (isset($_REQUEST['modin']) && $_REQUEST['modin']) { $this->setupLookup('modin'); $sql_criteria[] = "modin=" . $this->dbcon->qstr($_REQUEST['modin']); } //Student events if (isset($_REQUEST['student']) && $_REQUEST['student']) { $sql_criteria[] = "student=1"; } //Old events (legacy compatibility) if (isset($_REQUEST['old']) && $_REQUEST['old']) { $sql_criteria[] = '((`date` < CURDATE() AND `recurring_options`=0) || (`recurring_options`>0 AND `enddate`< CURDATE() ))'; } //Uid or Creator_id if (isset($_REQUEST['uid']) && $_REQUEST['uid']) { $sql_criteria[] = "uid=" . $this->dbcon->qstr($_REQUEST['uid']); } //Publish status if (isset($_REQUEST['publish']) && is_numeric($_REQUEST['publish'])) { if ($_REQUEST['publish']) { $sql_criteria[] = "publish=1"; } else { $sql_criteria[] = "publish!=1"; } } //Repeating Event if (isset($_REQUEST['recurring_options']) && $_REQUEST['recurring_options'] == 1) { $sql_criteria[] = "recurring_options>0"; } elseif (isset($_REQUEST['recurring_options']) && $_REQUEST['recurring_options'] === '0') { $sql_criteria[] = "(recurring_options=0 or isnull(recurring_options))"; } //Grab valid URL data $this->calendar->url_criteria = array(); foreach ($this->fields_def as $field => $fdef) { if (isset($_REQUEST[$field]) && ($_REQUEST[$field] || $_REQUEST[$field] === '0')) { $this->calendar->url_criteria[] = $field . '=' . $_REQUEST[$field]; } } return $sql_criteria; }
/** * Сохранение голоса в БД * @param $id * @param $item * @param array $free * * @return int|bool */ function saveVote($id, $item, $free) { $catalog = get('catalog', array(), 'p'); sql_query('BEGIN'); include_once PATH_COMMON . '/classes/geo.php'; $geo = new Geo(array('dbname' => $this->geo_dbname, 'tablename' => $this->geo_tablename)); $real_ip = $geo->get_ip(); $ip_data = $geo->get_value(); $columns = sql_getRows("SHOW COLUMNS FROM `" . $this->table_users . "`", true); if (!isset($columns['region'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD region VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['city'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD city VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['district'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD district VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['country'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD country VARCHAR( 255 ) NOT NULL;"); } // Добавим в список нового проголосовавшего $user_id = sql_insert($this->table_users, array('id_survey' => $id, 'ip' => $real_ip, 'city' => $ip_data['city'], 'region' => $ip_data['region'], 'district' => $ip_data['district'], 'country' => $ip_data['country'])); if (!is_int($user_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_users); // Если пришли оветы в свободной форме if ($free) { foreach ($item as $val) { foreach ($val as $k => $id_var) { if (array_key_exists($id_var, $free)) { $_id = sql_insert($this->table_free, array('id_variant' => (int) $id_var, 'id_user' => $user_id, 'text' => $free[$id_var])); if (!is_int($_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_free); } } } } // Список вопросов $rows = sql_getRows("SELECT id FROM " . $this->table_quests . " WHERE id_survey=" . $id); // Запишем результат в лог foreach ($rows as $k => $v) { foreach ($item[$v] as $variant) { $_id = sql_insert($this->table_log, array('id_survey' => $id, 'id_quest' => $v, 'id_variant' => $variant, 'id_user' => $user_id, 'text' => isset($free[$variant]) ? $free[$variant] : '')); if (!is_int($_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_log); } foreach ($catalog[$v] as $k => $variant) { $_id = sql_insert($this->table_log, array('id_survey' => $id, 'id_quest' => $v, 'id_variant' => $k, 'id_user' => $user_id, 'text' => $variant)); if (!is_int($_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_log); } } $query = 'UPDATE ' . $this->table . ' SET answ_cnt=answ_cnt+1 WHERE id =' . $id; sql_query($query); touch_cache($this->table); sql_query('COMMIT'); return $user_id; }