示例#1
0
 public function __construct()
 {
     $this->local_dir = 'geoip';
     $this->local_file = Mage::getBaseDir('var') . '/' . $this->local_dir . '/GeoIP.dat';
     $this->local_archive = Mage::getBaseDir('var') . '/' . $this->local_dir . '/GeoIP.dat.gz';
     $this->remote_archive = 'http://www.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz';
     $o = array();
     $o['charset'] = 'utf-8';
     $geo = new Geo($o);
     $data = $geo->get_value();
     $ip = $geo->get_ip();
     $model_geoip = Mage::getModel('geoip/geoip')->getCollection();
     $city = $geo->get_value('city', true);
     $cities = Mage::getModel('directory/region_api')->items('RU');
     $only_cities = array();
     foreach ($cities as $city) {
         $name = explode(" (", $city['name']);
         $only_cities[$city['region_id']] = $name[0];
     }
     if (!isset($data['city'])) {
         $data['city'] = '';
     }
     if (in_array($data['city'], $only_cities)) {
         $data['code'] = array_search($data['city'], $only_cities);
     }
     $ip = $this->getClientIP();
     $geoip_model = Mage::getModel('geoip/geoip')->getCollection()->addFieldToFilter('ip', $ip)->getFirstItem();
     $find_ip = $geoip_model->getData();
     $found = 'no';
     if (!empty($find_ip)) {
         $model = Mage::getModel('geoip/geoip');
         $founded_id = $find_ip['geoip_id'];
         $model->load($founded_id);
         $data['code'] = $model->getCityCode();
         $data['city'] = $only_cities[$data['code']];
         $found = 'yes';
     }
     $this->data = $data;
     $session = Mage::getSingleton('core/session');
     $geo_info = $session->getGeoIp();
     if (isset($geo_info['is_changed'])) {
         if ($found == 'yes') {
             $session->setGeoIp($this->data);
         }
     } else {
         $session->setGeoIp($this->data);
     }
 }
示例#2
0
<?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
//также кеширование используется и для других параметров
示例#3
0
 /**
  * Сохранение голоса в БД
  * @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;
 }
示例#4
0
文件: surveys.php 项目: romlg/cms36
 /**
  * Экспорт результатов
  */
 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)));
 }
示例#5
0
     */
    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";
示例#6
0
<?php

/**
 * Automatic detect location and set detected location to order;
 * geo.php to automatic detect location;
 * setCity.php to manual change detected location;
 * setCityModal.php is modal window to manual change detected location;
 */
global $geo;
$geo = new Geo();
$GLOBALS['user_city'] = $geo->get_value("city", true);
$GLOBALS['user_city_id'] = $geo->get_value("ID");
AddEventHandler("sale", "OnSaleComponentOrderOneStepPersonType", "setCustomDefaultCity");
function setCustomDefaultCity(&$arResult, &$arUserResult)
{
    if (!$arUserResult['DELIVERY_LOCATION'] && $GLOBALS['user_city_id'] > 0) {
        $arUserResult['DELIVERY_LOCATION'] = $GLOBALS['user_city_id'];
    }
    if (!$arUserResult['ORDER_PROP'][4] && $GLOBALS['user_city_id'] > 0) {
        $arUserResult['ORDER_PROP'][4] = $GLOBALS['user_city_id'];
    }
}