/**
  * Создает новую модель Города.
  * Если создание прошло успешно - перенаправляет на просмотр.
  *
  * @return void
  */
 public function actionCreate()
 {
     $model = new City();
     if (Yii::app()->getRequest()->getPost('City') !== null) {
         $model->setAttributes(Yii::app()->getRequest()->getPost('City'));
         if ($model->save()) {
             Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('CityModule.city', 'Запись добавлена!'));
             $this->redirect((array) Yii::app()->getRequest()->getPost('submit-type', ['update', 'id' => $model->id]));
         }
     }
     $this->render('create', ['model' => $model]);
 }
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 50) as $index) {
         $city = new City();
         $city->link = $faker->url;
         $city->img_src = $faker->imageUrl($width = 640, $height = 480);
         $city->name_en = $faker->city;
         $city->latitude = $faker->latitude;
         $city->longitude = $faker->longitude;
         $city->save();
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $data = Input::all();
     $city = new City();
     $city->municipality_id = $data['municipality_id'];
     $city->name = $data['name'];
     try {
         $city->save();
     } catch (ValidationException $errors) {
         return Redirect::route('admin.cities.create')->withErrors($errors->getErrors())->withInput();
     }
     return Redirect::route('admin.cities.create')->withErrors(array('mainSuccess' => 'Градът/селото е успешно добавен.'));
 }
Beispiel #4
0
 public static function check($_cpt, $_cntry)
 {
     $city = City::model()->find('country_id=:cntry AND caption=:cpt', array(':cntry' => $_cntry, ':cpt' => $_cpt));
     if ($city !== null) {
         return $city->getPrimaryKey();
     }
     $city = new City();
     $city->attributes = array('caption' => $_cpt, 'country_id' => $_cntry);
     if ($city->save()) {
         return $city->getPrimaryKey();
     }
     return false;
 }
 private function ifCityUndefined($userStep, $cityName)
 {
     if (City::model()->cityNotExist($cityName)) {
         if (!WikiUtils::checkCityByWiki($cityName) && !WikiUtils::checkCityByWiki($cityName . "_(город)")) {
             $userStep->error = GameUtils::ERROR_CITY_UNDEFINED;
             return true;
         }
         $city = new City();
         $city->name = $cityName;
         $city->save();
         return false;
     }
 }
Beispiel #6
0
 /**
  * 录入
  *
  */
 public function actionCreate()
 {
     parent::_acl('city_create');
     $model = new City();
     if (isset($_POST['City'])) {
         $model->attributes = $_POST['City'];
         if ($model->save()) {
             AdminLogger::_create(array('catalog' => 'create', 'intro' => '录入城市,ID:' . $model->id));
             $this->redirect(array('index'));
         }
     }
     $this->render('create', array('model' => $model));
 }
Beispiel #7
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new City();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['City'])) {
         $model->attributes = $_POST['City'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function actionCreateOrg()
 {
     $org = Organization::model()->count();
     if ($org == 0) {
         $this->layout = 'installation_layout';
         $model = new Organization();
         $user = new User();
         $auth_assign = new AuthAssignment();
         // Uncomment the following line if AJAX validation is needed
         $this->performAjaxValidation($model);
         if (isset($_POST['Organization']['organization_name']) && !empty($_POST['Organization']['phone']) && !empty($_POST['Organization']['email'])) {
             $country_model = new Country();
             $country_model->name = $_POST['Organization']['country'];
             $country_model->save();
             $state_model = new State();
             $state_model->state_name = $_POST['Organization']['state'];
             $state_model->country_id = $country_model->id;
             $state_model->save();
             $city_model = new City();
             $city_model->city_name = $_POST['Organization']['city'];
             $city_model->country_id = $country_model->id;
             $city_model->state_id = $state_model->state_id;
             $city_model->save();
             $model->attributes = $_POST['Organization'];
             $model->organization_created_by = 1;
             $model->organization_creation_date = new CDbExpression('NOW()');
             $model->city = $city_model->city_id;
             $model->state = $state_model->state_id;
             $model->country = $country_model->id;
             if ($model->save(false)) {
                 $user->user_organization_email_id = $model->email;
                 $user->user_password = md5($model->email . $model->email);
                 $user->user_type = 'admin';
                 $user->user_created_by = 1;
                 $user->user_creation_date = new CDbExpression('NOW()');
                 $user->user_organization_id = $model->organization_id;
                 $user->save();
                 $auth_assign->itemname = 'SuperAdmin';
                 $auth_assign->userid = $user->user_id;
                 $auth_assign->save(false);
                 $this->redirect(array('redirectLogin'));
             }
         }
         $this->render('create_org', array('model' => $model));
     } else {
         Yii::app()->user->logout();
         $this->redirect(array('login'));
     }
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new City();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['City'])) {
         $model->attributes = $_POST['City'];
         if ($model->save()) {
             $this->audit->logAudit(Yii::app()->user->id, new DateTime(), Constants::AUDITORIA_OBJETO_CIUDAD, Constants::AUDITORIA_OPERACION_ALTA, $model->id);
             $this->render('/site/successfullOperation', array('header' => 'Ciudad creada con éxito', 'message' => 'Haga click en volver para regresar a la gestión de ciudades', 'returnUrl' => Yii::app()->createUrl('city/admin'), 'viewUrl' => Yii::app()->createUrl("city/view", array("id" => $model->id))));
             return;
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function actionCreate()
 {
     $model = new City();
     if (isset($_POST['City'])) {
         $model->setAttributes($_POST['City']);
         if ($model->save()) {
             if (Yii::app()->getRequest()->getIsAjaxRequest()) {
                 Yii::app()->end();
             } else {
                 $this->redirect(array('view', 'id' => $model->city_id));
             }
         }
     }
     $this->render('create', array('model' => $model));
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new City('region');
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['City'])) {
         $model->attributes = $_POST['City'];
         //echo '<pre>'; print_r($model->attributes); die();
         //если выбрали - регион, значит надо проверить валидацией и после сохранения привязать
         if ($model->validate()) {
             if ($model->save()) {
                 $this->redirect(array('view', 'id' => $model->id));
             }
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function insertCity()
 {
     $cre = ["city" => Input::get('city')];
     $rules = ["city" => 'required'];
     $validator = Validator::make($cre, $rules);
     if ($validator->passes()) {
         $city = new City();
         $city->city_name = Input::get('city');
         $city->save();
         $count = City::count();
         $data['success'] = 'true';
         $data['message'] = html_entity_decode(View::make('admin.manage.cities.view', ["data" => $city, "count" => $count]));
     } else {
         $data["success"] = false;
         $data["message"] = "All fields are not filled";
     }
     return json_encode($data);
 }
Beispiel #13
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeCity(sfWebRequest $request)
 {
     $wiki = file_get_contents('C:\\1\\1.htm');
     preg_match_all('/<tr><td>.*?<\\/td><td>.*?<\\/td><td><a href=".*?">(.*?)<\\/a><\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>.*?<\\/td><td>(.*?)<\\/td><\\/tr>/', $wiki, $matchesarray);
     $weight = array();
     for ($i = 0; $i < sizeof($matchesarray[1]); $i++) {
         $weight[$matchesarray[1][$i]] = floatval(str_replace(array(' ', ','), array('', '.'), $matchesarray[2][$i])) * 1000;
     }
     fb($weight);
     $regions = array();
     $cities = array();
     for ($i = 1; $i <= 115; $i++) {
         fb('page ' . $i);
         $page = file_get_contents('http://www.voiceip.ru/home/kody_gorodov/?country_id=1&p_num=' . $i);
         $page = iconv('windows-1251', 'utf-8', $page);
         preg_match_all("/<tr align = center><td width = 50%>(.*?) \\((.*?)\\)<\\/td><td width = 10%>/", $page, $matchesarray2);
         for ($k = 0; $k < sizeof($matchesarray2[0]); $k++) {
             $city = $matchesarray2[1][$k];
             $region = $matchesarray2[2][$k];
             if (!isset($regions[$region])) {
                 $regions[$region] = array();
             }
             $regions[$region][] = array('name' => $city, 'weight' => isset($weight[$city]) ? $weight[$city] : 1);
             $cities[] = $city;
         }
     }
     foreach ($regions as $region => $cities) {
         $r = new Region();
         $r->country_id = 1;
         $r->name = $region;
         $r->save();
         foreach ($cities as $city) {
             try {
                 $c = new City();
                 $c->name = $city['name'];
                 $c->weight = $city['weight'];
                 $c->Region = $r;
                 $c->save();
             } catch (Exception $e) {
             }
         }
     }
 }
 public function store()
 {
     $rules = ['name' => 'required'];
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator)->withInput();
     } else {
         if (Input::has('city_id')) {
             $id = Input::get('city_id');
             $city = CityModel::find($id);
         } else {
             $city = new CityModel();
         }
         $city->name = Input::get('name');
         $city->save();
         $alert['msg'] = 'City has been saved successfully';
         $alert['type'] = 'success';
         return Redirect::route('admin.city')->with('alert', $alert);
     }
 }
Beispiel #15
0
 public static function getCityByName($name)
 {
     $name = str_replace(array('г. ', 'гор. ', 'с. ', 'сел. ', 'пгт. ', 'пгт.'), array('г.', 'г.', 'с.', 'с.', 'г.', 'г.'), $name);
     if (isset(self::$_cache[$name])) {
         return self::$_cache[$name];
     }
     $city = self::model()->find(array('condition' => 'title like :name', 'params' => array(':name' => $name)));
     if (!$city) {
         $city = new City();
         $city->title = $name;
         $pos = Yii::app()->geocoder->addressToPos($name);
         if ($pos) {
             $city->longitude = $pos[0];
             $city->latitude = $pos[1];
         }
         $city->save(false);
     }
     self::$_cache[$name] = $city;
     return $city;
 }
 /**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param      PropelPDO $con
  * @return     int The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws     PropelException
  * @see        save()
  */
 protected function doSave(PropelPDO $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their coresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->aCity !== null) {
             if ($this->aCity->isModified() || $this->aCity->isNew()) {
                 $affectedRows += $this->aCity->save($con);
             }
             $this->setCity($this->aCity);
         }
         if ($this->isNew()) {
             $this->modifiedColumns[] = CityInfoPeer::ID;
         }
         // If this object has been modified, then save it to the database.
         if ($this->isModified()) {
             if ($this->isNew()) {
                 $pk = CityInfoPeer::doInsert($this, $con);
                 $affectedRows += 1;
                 // we are assuming that there is only 1 row per doInsert() which
                 // should always be true here (even though technically
                 // BasePeer::doInsert() can insert multiple rows).
                 $this->setId($pk);
                 //[IMV] update autoincrement primary key
                 $this->setNew(false);
             } else {
                 $affectedRows += CityInfoPeer::doUpdate($this, $con);
             }
             $this->resetModified();
             // [HL] After being saved an object is no longer 'modified'
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }
<?php

require_once __DIR__ . "/../vendor/autoload.php";
require_once __DIR__ . "/../City.php";
session_start();
if (empty($_SESSION['list_of_cities'])) {
    $_SESSION['list_of_cities'] = array();
}
$app = new Silex\Application();
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app->get("/", function () use($app) {
    return $app['twig']->render('cities.html.twig', array('cities' => City::getAll()));
});
$app->post("/cities", function () use($app) {
    $city = new City($_POST['description'], $_POST['landmark']);
    ///connects to label id on cities.html.twig
    $city->save();
    return $app['twig']->render('create_city.html.twig', array('newcity' => $city));
});
$app->post("/delete_cities", function () use($app) {
    City::deleteAll();
    return $app['twig']->render('delete_cities.html.twig');
});
return $app;
Beispiel #18
0
	public static function addNewCity($city)
    {
    	$trueCity = null;
    	if(!empty($city)){ // добавляем город
						$trueCity = new City;
						$trueCity->title = $city;
						$trueCity->alternative_title = $city;

						$address_city = $city;
						$params = array(
						    'geocode' => $address_city,         // координаты
						    'format'  => 'json',                          // формат ответа
						    'results' => 1,                               // количество выводимых результатов
						    'kind'=>'locality'
						  //  'key'     => '...',                           // ваш api key
						);
						$trueRegion = $result_region = null;
						$response = json_decode(@file_get_contents('http://geocode-maps.yandex.ru/1.x/?' . http_build_query($params, '', '&')));
						if ($response && $response->response->GeoObjectCollection->metaDataProperty->GeocoderResponseMetaData->found > 0)
						{
							$result = $response->response->GeoObjectCollection->featureMember[0]->GeoObject->Point->pos;
						    if($result){
						    	$exp_str1 = explode(" ", $result);
								$trueCity->latitude = $exp_str1[1];
								$trueCity->longitude = $exp_str1[0]; 
						    } 
						    $result = $response->response->GeoObjectCollection->featureMember[0]->GeoObject->name;
						    if($result){ 
						    	$trueCity->title = $result;
						    	$trueCity->alternative_title = $result;
						     }
						    $result_region = $response->response->GeoObjectCollection->featureMember[0]->GeoObject->metaDataProperty->GeocoderMetaData->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;
						    if($result_region){
						    	$trueRegion = Region::model()->find('LOWER(title)=:title',array(':title'=>MHelper::String()->toLower($result_region)));
									if(!$trueRegion){
										$trueRegion = new Region;
										$trueRegion->title = $result_region;
									    $trueRegion->save();
									}
						    } 
						}
						if($trueCity->latitude)
						{
							// склонение 
							$params = array(
							    'format'  => 'json',                          // формат ответа
							    'name'=>$trueCity->title
							);
							$response = CJSON::decode(@file_get_contents('http://export.yandex.ru/inflect.xml?' . http_build_query($params, '', '&')));
							if ($response) 
							{
								if(isset($response[2]))
									$trueCity->rodpad = $response[2];
								if(isset($response[6]))
									$trueCity->mestpad = $response[6];
							}

							if($trueRegion){
								$trueCity->region = $trueRegion->id;
							}
							$trueCity->pos = 0;
							$trueCityCheck = City::model()->find('LOWER(title)=:title or LOWER(alternative_title)=:alternative_title',array(':title'=>MHelper::String()->toLower($trueCity->title),':alternative_title'=>MHelper::String()->toLower($trueCity->title)));
							if($trueCityCheck) // потому-что ввести могут что угодно, а город обозначится только после запроса к яндексу.
								return $trueCityCheck;

						    if($trueCity->save()){
						    	
						    } else {

						    	if($trueCity->errors && isset($trueCity->errors['title'])){
						    		if($trueCity->errors['title'][0] == 'Город с таким названием уже существует.'){
						    			$trueCity = City::model()->find('LOWER(title)=:title or LOWER(alternative_title)=:alternative_title',array(':title'=>MHelper::String()->toLower($trueCity->title),':alternative_title'=>MHelper::String()->toLower($trueCity->title)));
						    		}
						    	}
						    }
						}


					} 
					return $trueCity;
    }
Beispiel #19
0
<?php 
include 'admin-config.php';
$city_id = $state_id = $city_name = $city_status = $error = "";
if (strlen(Request::post("submit"))) {
    $city_id = Request::post("city_id");
    $state_id = Request::post("state_id");
    $city_name = Request::post("city_name");
    $city_status = Validation::getStautsTinyVal(Request::post("active"));
    $cityObj = new City();
    $cityObj->set("city_id", $city_id);
    $cityObj->set("state_id", $state_id);
    $cityObj->set("city_name", $city_name);
    $cityObj->set("city_status", $city_status);
    if ($cityObj->save()) {
        General::redirectUrl("city.php");
    } else {
        $error = "City Name alreday exist !";
    }
}
include 'header.php';
include 'sitebar.php';
?>
<div class="ch-container">
    <div class="row">
        <div id="content" class="col-lg-10 col-sm-10">
            <!-- content starts -->
            <div>
                <ul class="breadcrumb">
                    <li>
                        <a href="#">Home</a>
 public function parseCitiesAction()
 {
     $csv = array();
     $lines = file('https://raw.githubusercontent.com/attichka/code_examples/master/phone_codes_parser/ukraine_phone_codes.csv', FILE_IGNORE_NEW_LINES);
     foreach ($lines as $key => $value) {
         $csv[$key] = str_getcsv($value);
     }
     foreach ($csv as $data) {
         $city = new \City();
         $city->name = $data[0];
         if ($data[1] == "Київ") {
             $region = new \Region();
             $region->id = 9;
         } elseif ($data[1] == "Севастополь") {
             $region = new \Region();
             $region->id = 11;
         } else {
             $region = \Region::findFirst("name = '" . $data[1] . "'");
         }
         if ($region != NULL) {
             $city->region_id = $region->id;
             $city->phone_code = $data[2];
             if ($city->save()) {
                 echo "FINE!";
             } else {
                 echo "<pre>";
                 foreach ($city->getMessages() as $message) {
                     echo "Message: ", $message->getMessage();
                     echo "Field: ", $message->getField();
                     echo "Type: ", $message->getType();
                 }
                 echo "</pre>";
             }
         } else {
             debug("Error parse region on: ", $city);
         }
     }
 }
//if load states button is press process the states
if (isset($_POST['loadstates'])) {
    $city = new City();
    $filename = $_POST['filename'];
    $city->delete_by_country($countrycode);
    $file = SITE_ROOT . "/cities/" . $filename;
    $file = fopen($file, "r");
    while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
        $city = new City();
        $city->countrycode = $countrycode;
        $city->code = trim($data[0]);
        $city->var_name = $state->mod_write_check(trim($data[1]));
        $city->name = trim(SpaceBeforeCapital($data[1]));
        $city->countycode = trim($data[2]);
        $city->statecode = trim($data[3]);
        $save = $city->save();
    }
    fclose($file);
    $message = "<div class='success'>State codes loaded from " . $filename . " </div>";
    $session->message($message);
    redirect_to($_SERVER['PHP_SELF']);
}
//delete all the states from list
if (isset($_POST['deletestates'])) {
    global $db, $database;
    $city = new City();
    $city->delete_by_country($countrycode);
    /* We should remove the state definition from counties, cities and zips tables also for this country */
    //$db->query("update ".TBL_COUNTIES." set statecode='' where countrycode='$countrycode' ");
    //$db->query("update ".TBL_CITY." set statecode='' where countrycode='$countrycode' ");
    $message = "<div class='success'>State codes for #COUNTRY# are deleted </div>";
 /**
  * Execute the action.
  * @param array command line parameters specific for this command
  */
 public function actionIndex($type = 'airports', $filename = '')
 {
     if ($type == 'airports') {
         if ($filename) {
             $path = Yii::getPathOfAlias('application.runtime');
             if (file_exists($filename)) {
                 $fp = fopen($filename, 'r');
                 $outfp = fopen($path . '/' . basename($filename), 'w');
                 if (!$outfp) {
                     echo "Cant open file " . $path . '/' . basename($filename) . " for writing\n";
                     die;
                 }
                 $formatLine = fgets($fp);
                 $formatLine = str_replace(array("\r", "\n"), array(''), $formatLine);
                 $columnNames = explode('|', $formatLine);
                 //print_r($formatLine);die();
                 $column = array();
                 foreach ($columnNames as $i => $columnName) {
                     $column[$columnName] = $i;
                 }
                 //print_r($column);
                 $skipAll = false;
                 while (!feof($fp)) {
                     $lineData = fgets($fp);
                     $lineData = str_replace(array("\r", "\n"), array(''), $lineData);
                     $lineData = iconv("cp1251", "UTF-8", $lineData);
                     $data = explode('|', $lineData);
                     $needSave = true;
                     $country = Country::getCountryByCode($data[$column['country_code']]);
                     if ($country) {
                         $cities = $this->getCities($country->id, $data[$column['city_en']], $data[$column['city_ru']]);
                         if (!$cities) {
                             $cities = City::model()->findAllByAttributes(array('countryId' => $country->id, 'code' => $data[$column['iata_code']]));
                         }
                         $abort = false;
                         while (!$abort) {
                             if ($cities) {
                                 if (count($cities) > 1) {
                                     $citiesTmp = City::model()->findAllByAttributes(array('countryId' => $country->id, 'code' => $data[$column['iata_code']]));
                                     if ($citiesTmp && count($citiesTmp) == 1) {
                                         $cities = $citiesTmp;
                                     }
                                 }
                                 if (count($cities) > 1) {
                                     echo "Found " . count($cities) . " cities for line: {$lineData}\n";
                                     echo str_pad('code', 5, " ", STR_PAD_RIGHT) . str_pad('localRu', 15, " ", STR_PAD_LEFT) . str_pad('localEn', 15, " ", STR_PAD_LEFT) . "\n";
                                     foreach ($cities as $city) {
                                         echo str_pad($city->code, 5, " ", STR_PAD_RIGHT) . str_pad($city->localRu, 15, " ", STR_PAD_LEFT) . str_pad($city->localEn, 15, " ", STR_PAD_LEFT) . "\n";
                                     }
                                     echo "Type code of the selected city:\n";
                                     $name = trim(fgets(STDIN));
                                     $cities = $this->getCities($country->id, $name);
                                 } else {
                                     $this->selectAirport($data, $column, $lineData, $outfp, $cities[0]);
                                     $abort = true;
                                 }
                             } else {
                                 echo "City not found in Db. Type s - skip, c - create, f - try find in db:\n";
                                 echo "{$lineData}\n";
                                 //$char = trim(fgets(STDIN));
                                 $char = 's';
                                 if ($char == 's') {
                                     echo "Dont found any same city. Skipping line: {$lineData} \n";
                                     fwrite($outfp, $lineData . "|nocity\n");
                                     $abort = true;
                                 } elseif ($char == 'c') {
                                     $city = new City();
                                     echo "Creating new city...\n";
                                     $city->countryId = $country->id;
                                     if (!$data[$column['city_ru']]) {
                                         $data[$column['city_ru']] = $data[$column['city_en']];
                                     }
                                     echo "City name rus (default {$data[$column['city_ru']]}):\n";
                                     $newName = trim(fgets(STDIN));
                                     if ($newName) {
                                         $city->localRu = $newName;
                                     } else {
                                         $city->localRu = $data[$column['city_ru']];
                                     }
                                     echo "City name eng (default {$data[$column['city_en']]}):\n";
                                     $newName = trim(fgets(STDIN));
                                     if ($newName) {
                                         $city->localEn = $newName;
                                     } else {
                                         $city->localEn = $data[$column['city_en']];
                                     }
                                     echo "City code:\n";
                                     $newCode = trim(fgets(STDIN));
                                     if ($newCode) {
                                         $city->code = $newCode;
                                     } else {
                                         continue;
                                     }
                                     $city->position = 0;
                                     $city->save();
                                     $city->id = $city->getPrimaryKey();
                                     $this->selectAirport($data, $column, $lineData, $outfp, $city);
                                 } else {
                                     echo "Type part of city name:\n";
                                     $name = trim(fgets(STDIN));
                                     $cities = $this->getCities($country->id, $name);
                                 }
                             }
                         }
                     } else {
                         echo "Country not found, skipping line: {$lineData} \n";
                         fwrite($outfp, $lineData . "|nocountry\n");
                     }
                 }
                 fclose($fp);
                 fclose($outfp);
             } else {
                 echo 'Import file not found on path: ' . $filename;
             }
         } else {
             echo 'Option --filename cant be empty';
         }
     }
     if ($type == 'airlineWeight') {
         echo 'INN';
         if ($filename) {
             $path = Yii::getPathOfAlias('application.runtime');
             if (file_exists($filename)) {
                 $airlinessxe = simplexml_load_string(file_get_contents($filename));
                 foreach ($airlinessxe->Item as $item) {
                     $airlineCode = (string) $item['id'];
                     $modified = false;
                     try {
                         $airline = Airline::getAirlineByCode($airlineCode);
                     } catch (CException $e) {
                         $airline = false;
                     }
                     if ($airline) {
                         $airlineLocalRu = (string) $item['rusname'];
                         $airlineLocalEn = (string) $item['name'];
                         if (UtilsHelper::countRussianCharacters($airline->localRu) <= 0) {
                             $airline->localRu = $airlineLocalRu;
                             $modified = true;
                         } else {
                             echo "o_O !!! " . $airline->localRu;
                         }
                         if (!$airline->localEn && $airlineLocalEn) {
                             $airline->localEn = $airlineLocalEn;
                             $modified = true;
                         }
                         $economPrice = (string) $item->luggage->econom->price;
                         $economFreeWeight = (string) $item->luggage->econom->weight;
                         if ($airline->economFreeWeight && $economFreeWeight) {
                             if ($economPrice == 'charge') {
                                 $airline->economFreeWeight = 0;
                             } else {
                                 $airline->economFreeWeight = str_replace('kg', '', $economFreeWeight);
                             }
                             $modified = true;
                         }
                         $businessPrice = (string) $item->luggage->business->price;
                         $businessFreeWeight = (string) $item->luggage->business->weight;
                         if ($airline->businessFreeWeight && $businessFreeWeight) {
                             if ($businessPrice == 'charge') {
                                 $airline->businessFreeWeight = 0;
                             } else {
                                 $airline->businessFreeWeight = str_replace('kg', '', $businessFreeWeight);
                             }
                             $modified = true;
                         }
                         $economDescription = (string) $item->luggage->econom->description;
                         if ($airline->economDescription && $economDescription) {
                             $economDescription = substr($economDescription, strpos($economDescription, 'Багаж не должен'));
                             $airline->economDescription = trim($economDescription);
                             $modified = true;
                         }
                         $businessDescription = (string) $item->luggage->business->description;
                         if ($airline->businessDescription && $businessDescription) {
                             $businessDescription = substr($businessDescription, strpos($businessDescription, 'Багаж не должен'));
                             $airline->businessDescription = trim($businessDescription);
                             echo "try modyf ";
                             $modified = true;
                         }
                         if ($modified) {
                             $airline->save();
                         }
                     } else {
                         echo "!!!! NOT FOUND {$airlineCode}";
                         $airline = new Airline();
                         $airline->code = $airlineCode;
                         $airlineLocalRu = (string) $item['rusname'];
                         $airlineLocalEn = (string) $item['name'];
                         if (UtilsHelper::countRussianCharacters($airline->localRu) <= 0) {
                             $airline->localRu = $airlineLocalRu;
                             $airline->localEn = $airlineLocalEn;
                             $modified = true;
                         }
                         $economFreeWeight = (string) $item->luggage->econom->weight;
                         if (!$airline->economFreeWeight && $economFreeWeight) {
                             $airline->economFreeWeight = str_replace('kg', '', $economFreeWeight);
                             $modified = true;
                         }
                         $businessFreeWeight = (string) $item->luggage->business->weight;
                         if (!$airline->businessFreeWeight && $businessFreeWeight) {
                             $airline->businessFreeWeight = str_replace('kg', '', $businessFreeWeight);
                             $modified = true;
                         }
                         $economDescription = (string) $item->luggage->econom->description;
                         if (!$airline->economDescription && $economDescription) {
                             $airline->economDescription = $economDescription;
                             $modified = true;
                         }
                         $businessDescription = (string) $item->luggage->business->description;
                         if (!$airline->businessDescription && $businessDescription) {
                             $airline->businessDescription = $businessDescription;
                             $modified = true;
                         }
                         if (!$airline->save()) {
                             CVarDumper::dump($airline->getErrors());
                         }
                     }
                     echo "airline {$airlineCode} {$airlineLocalRu} {$economFreeWeight}\n";
                 }
                 echo 'ютф?';
                 //CVarDumper::dump($airlinessxe);
             }
         }
     }
     if ($type == 'iconv') {
         if ($filename) {
             $path = Yii::getPathOfAlias('application.runtime');
             if (file_exists($filename)) {
                 $data = file_get_contents($filename);
                 echo iconv('cp1251', 'UTF-8', $data);
             }
         }
     }
     if ($type == 'test') {
         $cities = City::model()->findAllByAttributes(array('code' => 'LED', 'countryId' => 174));
         if ($cities) {
             echo "Found " . count($cities) . " cities for line: \n";
             echo str_pad('code', 5, " ", STR_PAD_RIGHT) . str_pad('localRu', 19, " ", STR_PAD_LEFT) . str_pad('localEn', 19, " ", STR_PAD_LEFT) . "\n";
             foreach ($cities as $city) {
                 echo str_pad($city->code, 5, " ", STR_PAD_RIGHT) . str_pad($city->localRu, 19, " ", STR_PAD_LEFT) . str_pad($city->localEn, 19, " ", STR_PAD_LEFT) . ' ' . $city->country->id . "\n";
             }
         }
     }
     if ($type == 'hotelbookCountries') {
         Yii::import('site.common.modules.hotel.models.*');
         $HotelClient = new HotelBookClient();
         $countries = $HotelClient->getCountries();
         print_r($countries);
         foreach ($countries as $hotelCountry) {
             $nameRu = $hotelCountry['nameRu'];
             $name = $hotelCountry['nameEn'];
             $ourCountries = $this->getCountries($name, $nameRu);
             if ($ourCountries) {
                 if (count($ourCountries) > 1) {
                     echo "Found " . count($ourCountries) . " countries for nameEn:{$hotelCountry['nameEn']} nameRu:{$hotelCountry['nameRu']} \n";
                     echo str_pad('code', 5, " ", STR_PAD_RIGHT) . str_pad('localRu', 19, " ", STR_PAD_LEFT) . str_pad('localEn', 19, " ", STR_PAD_LEFT) . "\n";
                     foreach ($ourCountries as $country) {
                         echo str_pad($country->code, 5, " ", STR_PAD_RIGHT) . str_pad($country->localRu, 19, " ", STR_PAD_LEFT) . str_pad($country->localEn, 19, " ", STR_PAD_LEFT) . ' ' . $country->id . "\n";
                     }
                     echo "Enter id of country or 's' - for skip \n";
                     $oldId = trim(fgets(STDIN));
                     if ($oldId !== 's') {
                         $country = Country::getCountryByPk(intval($oldId));
                         $country->hotelbookId = $hotelCountry['id'];
                         $country->save();
                     }
                 } else {
                     $country = $ourCountries[0];
                     if (!$country->hotelbookId) {
                         $country->hotelbookId = $hotelCountry['id'];
                         $country->save();
                     }
                 }
             } else {
                 $nameRu = substr($hotelCountry['nameRu'], 0, strpos($hotelCountry['nameRu'], ' '));
                 $name = substr($hotelCountry['nameEn'], 0, strpos($hotelCountry['nameRu'], ' '));
                 $ourCountries = $this->getCountries($name, $nameRu);
                 if ($ourCountries) {
                     if (count($ourCountries) > 1) {
                         echo "Found " . count($ourCountries) . " countries for nameEn:{$hotelCountry['nameEn']} nameRu:{$hotelCountry['nameRu']} \n";
                         echo str_pad('code', 5, " ", STR_PAD_RIGHT) . str_pad('localRu', 19, " ", STR_PAD_LEFT) . str_pad('localEn', 19, " ", STR_PAD_LEFT) . "\n";
                         foreach ($ourCountries as $country) {
                             echo str_pad($country->code, 5, " ", STR_PAD_RIGHT) . str_pad($country->localRu, 19, " ", STR_PAD_LEFT) . str_pad($country->localEn, 19, " ", STR_PAD_LEFT) . ' ' . $country->id . "\n";
                         }
                         echo "Enter id of country or 's' - for skip \n";
                         $oldId = trim(fgets(STDIN));
                         if ($oldId !== 's') {
                             $country = Country::getCountryByPk(intval($oldId));
                             $country->hotelbookId = $hotelCountry['id'];
                             $country->save();
                         }
                     } else {
                         if (!$country->hotelbookId) {
                             $country = $ourCountries[0];
                             $country->hotelbookId = $hotelCountry['id'];
                             $country->save();
                         }
                     }
                 }
             }
         }
     }
     if ($type == 'geonames') {
         $criteria = new CDbCriteria();
         $criteria->condition = 'hotelbookId IS NOT NULL';
         //$criteria->params=array(':postID'=>10);
         $start = false;
         $countries = Country::model()->findAll($criteria);
         $formatLine = 'geonameid|name_mixed|name|names|latitude|longitude|feature|feature_code|country_code|country_codes|state_code|admin2_code|admin3_code|admin4_code|population|elevation|dem|timezone|modification_date';
         $formatLine = str_replace(array("\r", "\n"), array(''), $formatLine);
         $columnNames = explode('|', $formatLine);
         //print_r($formatLine);die();
         $column = array();
         foreach ($columnNames as $i => $columnName) {
             $column[$columnName] = $i;
         }
         foreach ($countries as $country) {
             $filename = '/srv/www/oleg.voyanga/public_html/console/data_files/' . $country->code . '.txt';
             if (!$start) {
                 if ($country->code == 'HR') {
                     $start = true;
                 } else {
                     continue;
                 }
             }
             if ($filename) {
                 $path = Yii::getPathOfAlias('application.runtime');
                 if (file_exists($filename)) {
                     echo "Starting parse " . $country->code . ".txt\n";
                     $fp = fopen($filename, 'r');
                     //$countryCode = basename($filename);
                     //$countryCode = substr($countryCode,0,strpos($countryCode,'.'));
                     $outfp = fopen($path . '/' . basename($filename), 'w');
                     if (!$outfp) {
                         echo "Cant open file " . $path . '/' . basename($filename) . " for writing\n";
                         die;
                     }
                     //print_r($column);
                     $skipAll = false;
                     $lineCount = 0;
                     $addedCount = 0;
                     $haveAltNames = 0;
                     $haveRuName = 0;
                     $haveIataCode = 0;
                     echo str_pad('Parsed', 10, " ", STR_PAD_RIGHT) . str_pad('Added', 10, " ", STR_PAD_RIGHT) . str_pad('AltNames', 10, " ", STR_PAD_RIGHT) . str_pad('RuName', 10, " ", STR_PAD_RIGHT) . str_pad('IataCode', 10, " ", STR_PAD_RIGHT) . "\n";
                     while (!feof($fp)) {
                         $lineData = fgets($fp);
                         $lineData = str_replace(array("\r", "\n"), array(''), $lineData);
                         $data = explode("\t", $lineData);
                         if (!$data) {
                             continue;
                         }
                         if (count($data) <= 11) {
                             continue;
                         }
                         $lineCount++;
                         $geoNames = new GeoNames();
                         if ($data[$column['feature_code']]) {
                             if ($data[$column['feature_code']] == 'PPL' || $data[$column['feature_code']] == 'PPLA' || $data[$column['feature_code']] == 'PPLC' || $data[$column['feature_code']] == 'AIRP') {
                                 $geoNames->type = $data[$column['feature_code']];
                                 $geoNames->nameEn = $data[$column['name']];
                                 $geoNames->soundexEn = UtilsHelper::soundex($geoNames->nameEn);
                                 $geoNames->countryCode = $data[$column['country_code']];
                                 $geoNames->latitude = $data[$column['latitude']];
                                 $geoNames->longitude = $data[$column['longitude']];
                                 if (in_array($data[$column['country_code']], self::$sng)) {
                                     $geoNames->nameRu = UtilsHelper::fromTranslite($geoNames->nameEn);
                                     $ruFactor = 6;
                                 } else {
                                     $geoNames->nameRu = UtilsHelper::ruTranscript($geoNames->nameEn);
                                     $ruFactor = 12;
                                 }
                                 if ($data[$column['state_code']]) {
                                     $geoNames->stateCode = $data[$column['state_code']];
                                 }
                                 if ($data[$column['names']]) {
                                     $names = explode(',', $data[$column['names']]);
                                     $rusWord = array('index' => 0, 'count' => 0, 'replacements' => 20);
                                     $manyRusWords = false;
                                     $altNames = array();
                                     $iataCode = '';
                                     foreach ($names as $ind => $altName) {
                                         $altNames[] = $altName;
                                         if ($this->isIataCode($altName)) {
                                             if ($altName != mb_strtoupper($data[$column['name']])) {
                                                 $iataCode = $altName;
                                                 $geoNames->iataCode = $iataCode;
                                                 $haveIataCode++;
                                                 unset($altNames[$ind]);
                                                 continue;
                                             }
                                         }
                                         $n = UtilsHelper::countRussianCharacters($altName);
                                         if ($n > 0) {
                                             $altCase = mb_convert_case($altName, MB_CASE_TITLE, "UTF-8");
                                             $k = levenshtein($geoNames->nameRu, $altName);
                                             $l = levenshtein($geoNames->nameRu, $altCase);
                                             if ($l < $k) {
                                                 $k = $l;
                                                 $altNames[$ind] = $altCase;
                                                 $names[$ind] = $altCase;
                                             }
                                         }
                                         if ($n > 0 && $k < $rusWord['replacements']) {
                                             if ($rusWord['count'] > 0) {
                                                 $manyRusWords = true;
                                             }
                                             $rusWord['index'] = $ind;
                                             $rusWord['replacements'] = $k;
                                             $rusWord['count'] = $n;
                                         }
                                     }
                                     if ($manyRusWords) {
                                         fwrite($outfp, "{$geoNames->latitude}|{$geoNames->longitude}|{$data[$column['name']]}|{$names[$rusWord['index']]}\n");
                                     }
                                     if ($rusWord['count'] > 0) {
                                         if ($rusWord['replacements'] < $ruFactor) {
                                             $geoNames->nameRu = $names[$rusWord['index']];
                                             $haveRuName++;
                                             //unset($altNames[$rusWord['index']]);
                                         }
                                     }
                                     $geoNames->alternateNames = implode(',', $altNames);
                                     unset($names);
                                     unset($altNames);
                                     unset($rusWord);
                                     $haveAltNames++;
                                 }
                                 $geoNames->soundexRu = UtilsHelper::soundex($geoNames->nameRu, 'RU');
                                 $geoNames->metaphoneRu = UtilsHelper::ruMetaphone($geoNames->nameRu);
                                 $geoNames->save();
                                 $addedCount++;
                             }
                         }
                         unset($geoNames);
                         unset($lineData);
                         unset($data);
                         if ($lineCount % 30000 == 0) {
                             echo str_pad($lineCount, 10, " ", STR_PAD_RIGHT) . str_pad($addedCount, 10, " ", STR_PAD_RIGHT) . str_pad($haveAltNames, 10, " ", STR_PAD_RIGHT) . str_pad($haveRuName, 10, " ", STR_PAD_RIGHT) . str_pad($haveIataCode, 10, " ", STR_PAD_RIGHT) . "\n";
                         }
                     }
                     echo str_pad($lineCount, 10, " ", STR_PAD_RIGHT) . str_pad($addedCount, 10, " ", STR_PAD_RIGHT) . str_pad($haveAltNames, 10, " ", STR_PAD_RIGHT) . str_pad($haveRuName, 10, " ", STR_PAD_RIGHT) . str_pad($haveIataCode, 10, " ", STR_PAD_RIGHT) . "\n";
                     fclose($outfp);
                 } else {
                     echo "Not found " . $country->code . ".txt\n";
                 }
             }
             //endif filename
         }
         //endforeach countries
     }
     if ($type == 'hotelbookCities') {
         Yii::import('site.common.modules.hotel.models.*');
         $HotelClient = new HotelBookClient();
         $criteria = new CDbCriteria();
         $criteria->condition = 'hotelbookId IS NOT NULL';
         $path = Yii::getPathOfAlias('application.runtime');
         //$criteria->params=array(':postID'=>10);
         $countries = Country::model()->findAll($criteria);
         $start = false;
         foreach ($countries as $country) {
             if (!$start) {
                 /*if($country->code == 'UA')
                   {
                       $start = true;
                   }else{
                       continue;
                   }/**/
                 if ($country->code == 'US') {
                     continue;
                 }
             }
             $hotelCities = $HotelClient->getCities($country->hotelbookId);
             $oneResult = 0;
             $someResult = 0;
             $manyResult = 0;
             $noResult = 0;
             $outfp = fopen($path . '/' . $country->code . '-hotel-log.txt', 'w');
             if (!$outfp) {
                 echo "Cant open file " . $path . '/' . $country->code . "-hotel-log.txt for writing\n";
                 die;
             }
             foreach ($hotelCities as $hotelCity) {
                 if (in_array($country->code, self::$sng)) {
                     $hotelCity['nameRu'] = UtilsHelper::fromTranslite($hotelCity['nameEn']);
                 } else {
                     $hotelCity['nameRu'] = UtilsHelper::ruTranscript($hotelCity['nameEn']);
                 }
                 $hotelCity['metaphoneRu'] = UtilsHelper::ruMetaphone($hotelCity['nameRu']);
                 $hotelCity['sondexEn'] = UtilsHelper::soundex($hotelCity['nameEn']);
                 $hotels = $HotelClient->getHotels($hotelCity);
                 if (count($hotels) == 0) {
                     //We are don't need empty cities
                     continue;
                 }
                 $cnt = 0;
                 $haveCoordinates = false;
                 foreach ($hotels as $hotelObj) {
                     $cnt++;
                     $query[$hotelObj['id']] = $HotelClient->hotelDetail($hotelObj['id'], true);
                     if ($cnt > 10) {
                         break;
                     }
                 }
                 $HotelClient->processAsyncRequests();
                 foreach ($query as $hotelId => $responseId) {
                     if (isset($HotelClient->requests[$responseId]['result'])) {
                         if (isset($HotelClient->requests[$responseId]['result']->latitude, $HotelClient->requests[$responseId]['result']->longitude) && $HotelClient->requests[$responseId]['result']->latitude && $HotelClient->requests[$responseId]['result']->longitude) {
                             $haveCoordinates = true;
                             $possibleLatitude = $HotelClient->requests[$responseId]['result']->latitude;
                             $possibleLongitude = $HotelClient->requests[$responseId]['result']->longitude;
                             break;
                         }
                     }
                 }
                 $cityCriteria = new CityFindCriteria();
                 $cityCriteria->paramValues = array('countryCode' => $country->code, 'nameEn' => $hotelCity['nameEn'], 'metaphoneRu' => $hotelCity['metaphoneRu'], 'soundexEn' => $hotelCity['sondexEn']);
                 //$prevCriteria = null;
                 //$prevCount = 0;
                 $currCriteria = null;
                 $count = 0;
                 $findEnd = false;
                 $needSave = false;
                 while (!$findEnd) {
                     $prevCriteria = $currCriteria;
                     $prevCount = $count;
                     $currCriteria = $cityCriteria->getCriteria();
                     $count = GeoNames::model()->count($currCriteria);
                     $findGeo = null;
                     echo "Params: " . implode(',', $cityCriteria->paramUsed) . ' count:' . $count . "\n";
                     if ($haveCoordinates && $count < 15) {
                         $geoNames = GeoNames::model()->findAll($currCriteria);
                         foreach ($geoNames as $geoName) {
                             if ($geoName->latitude && $geoName->longitude) {
                                 $distance = intval(UtilsHelper::calculateTheDistance($geoName->latitude, $geoName->longitude, $possibleLatitude, $possibleLongitude));
                                 if ($distance < 10000) {
                                     $findGeo = $geoName;
                                     $count = 1;
                                 }
                             }
                         }
                     }
                     if ($count > 1) {
                         $findEnd = !$cityCriteria->setPlus();
                     } elseif ($count < 1) {
                         $findEnd = !$cityCriteria->setMinus();
                     } else {
                         $findEnd = true;
                     }
                 }
                 if ($count < 1) {
                     if ($count < $prevCount) {
                         $currCriteria = $prevCriteria;
                         $count = $prevCount;
                         $needSave = true;
                     }
                 } else {
                     $needSave = true;
                 }
                 if ($needSave) {
                     if ($count > 6) {
                         echo "Many results for city {$hotelCity['nameEn']} - {$count}\n";
                         $manyResult++;
                         fwrite($outfp, "{$hotelCity['nameEn']}|{$hotelCity['nameRu']}|{$hotelCity['id']}|{$count}\n");
                     } elseif ($count > 1) {
                         //echo "Many results for city {$hotelCity['nameEn']} - $count\n";
                         $geoName = GeoNames::model()->find($currCriteria);
                         echo "Possible by city name city {$hotelCity['nameEn']} City: {$geoName->nameEn} Ru: {$geoName->nameRu} IATA: {$geoName->iataCode} coords: {$geoName->longitude} {$geoName->latitude}\n";
                         $someResult++;
                         fwrite($outfp, "{$hotelCity['nameEn']}|{$hotelCity['nameRu']}|{$hotelCity['id']}|{$count}\n");
                     } else {
                         if ($findGeo) {
                             $geoName = $findGeo;
                         } else {
                             $geoName = GeoNames::model()->find($currCriteria);
                         }
                         echo "Found by city name city {$hotelCity['nameEn']} City: {$geoName->nameEn} Ru: {$geoName->nameRu} IATA: {$geoName->iataCode} coords: {$geoName->longitude} {$geoName->latitude}" . ($findGeo ? " ByCoords" : "") . "\n";
                         if ($geoName->iataCode) {
                             $city = City::model()->findByAttributes(array('code' => $geoName->iataCode, 'countryId' => $country->id));
                             if (!$city) {
                                 $city = new City();
                                 $city->localEn = $geoName->nameEn;
                                 $city->localRu = $geoName->nameRu;
                                 $city->countryId = $country->id;
                                 $city->code = $geoName->iataCode;
                             }
                             $city->latitude = $geoName->latitude;
                             $city->longitude = $geoName->longitude;
                             $city->metaphoneRu = $geoName->metaphoneRu;
                             $city->hotelbookId = $hotelCity['id'];
                             if ($geoName->stateCode) {
                                 $city->stateCode = $geoName->stateCode;
                             }
                             $city->save();
                         } else {
                             $city = City::model()->findByAttributes(array('localEn' => $geoName->nameEn, 'localRu' => $geoName->nameRu, 'countryId' => $country->id));
                             if (!$city) {
                                 $city = new City();
                                 $city->localEn = $geoName->nameEn;
                                 $city->localRu = $geoName->nameRu;
                                 $city->countryId = $country->id;
                                 $city->code = $geoName->iataCode;
                             }
                             $city->latitude = $geoName->latitude;
                             $city->longitude = $geoName->longitude;
                             $city->metaphoneRu = $geoName->metaphoneRu;
                             $city->hotelbookId = $hotelCity['id'];
                             if ($geoName->stateCode) {
                                 $city->stateCode = $geoName->stateCode;
                             }
                             $city->save();
                         }
                         $oneResult++;
                     }
                 } else {
                     echo "Dont found anything for city {$hotelCity['nameEn']}\n";
                     $noResult++;
                     fwrite($outfp, "{$hotelCity['nameEn']}|{$hotelCity['nameRu']}|{$hotelCity['id']}|{$count}\n");
                 }
                 //$criteria = new EMongoCriteria(array('conditions'=>array('countryCode'=>array('equals'=>$country->code)) ));
                 //$criteria->limit(10);
                 //$geoNames = GeoNames::model()->findAll($criteria);
             }
             echo "NoResults:{$noResult} OneResult:{$oneResult} SomeResults:{$someResult} ManyResults: {$manyResult}\n";
             fclose($outfp);
             //break;
         }
     }
     if ($type == 'iataCode') {
         $criteria = new CDbCriteria();
         $criteria->condition = 'hotelbookId IS NOT NULL';
         $path = Yii::getPathOfAlias('application.runtime');
         //$criteria->params=array(':postID'=>10);
         $countries = Country::model()->findAll($criteria);
         $start = false;
         foreach ($countries as $country) {
             if (!$start) {
                 /*
                                     if($country->code == 'RU')
                                     {
                                         $start = true;
                                     }else{
                                         continue;
                                     }/**/
                 /*if($country->code == 'US')
                   {
                       continue;
                   }/**/
             }
             $criteriaCity = new CDbCriteria();
             $criteriaCity->addCondition('code IS NOT NULL');
             $criteriaCity->addCondition('countryId=' . $country->id);
             $path = Yii::getPathOfAlias('application.runtime');
             //$criteria->params=array(':postID'=>10);
             $countCities = City::model()->count($criteriaCity);
             echo "Start parsing for country {$country->code} {$countCities} results\n";
             $pageLimit = 20;
             $n = ceil($countCities / $pageLimit);
             $criteriaCity->limit = $pageLimit;
             $oneResult = 0;
             $modifyCount = 0;
             $noResult = 0;
             $lineCount = 0;
             $outfp = fopen($path . '/' . $country->code . '-iata-log.txt', 'w');
             if (!$outfp) {
                 echo "Cant open file " . $path . '/' . $country->code . "-hotel-log.txt for writing\n";
                 die;
             }
             for ($i = 0; $i < $n; $i++) {
                 $criteriaCity->offset = $i * $pageLimit;
                 //print_r($criteriaCity);
                 //echo "\n";
                 $cities = City::model()->findAll($criteriaCity);
                 foreach ($cities as $city) {
                     $lineCount++;
                     if (UtilsHelper::countRussianCharacters($city->localRu)) {
                         $nameRu = $city->localRu;
                     } else {
                         if (in_array($country->code, self::$sng)) {
                             $nameRu = UtilsHelper::fromTranslite($city->localEn);
                         } else {
                             $nameRu = UtilsHelper::ruTranscript($city->localEn);
                         }
                     }
                     $metaphoneRu = UtilsHelper::ruMetaphone($nameRu);
                     $sondexEn = UtilsHelper::soundex($city->localEn);
                     $cityCriteria = new CityFindCriteria();
                     $cityCriteria->states = array('value' => array('iata'));
                     $cityCriteria->states[0] = array('value' => array('nameEn'));
                     $cityCriteria->states[1] = array('value' => array('iata', 'nameEn'));
                     $cityCriteria->states[1][0] = array('value' => array('iata', 'metaphoneRu'));
                     $cityCriteria->states[1][1] = array('value' => array('iata', 'nameEn', 'metaphoneRu'));
                     $cityCriteria->states[0][1] = array('value' => array('nameEn', 'metaphoneRu'));
                     $cityCriteria->states[0][0] = array('value' => array('metaphoneRu'));
                     $cityCriteria->paramUsed = $cityCriteria->states['value'];
                     $cityCriteria->paramValues = array('countryCode' => $country->code, 'nameEn' => $city->localEn, 'metaphoneRu' => $metaphoneRu, 'soundexEn' => $sondexEn, 'iata' => $city->code);
                     $currCriteria = null;
                     $count = 0;
                     $findEnd = false;
                     while (!$findEnd) {
                         //$prevCriteria = $currCriteria;
                         //$prevCount = $count;
                         $currCriteria = $cityCriteria->getCriteria();
                         $count = GeoNames::model()->count($currCriteria);
                         //echo "Params: ".implode(',',$cityCriteria->paramUsed).' count:'.$count."\n";
                         if ($count > 1) {
                             $findEnd = !$cityCriteria->setPlus();
                         } elseif ($count < 1) {
                             $findEnd = !$cityCriteria->setMinus();
                         } else {
                             $findEnd = true;
                         }
                     }
                     if ($count == 1) {
                         $oneResult++;
                         $geoName = GeoNames::model()->find($currCriteria);
                         $needSave = false;
                         if (!$city->latitude) {
                             $city->latitude = $geoName->latitude;
                             $city->longitude = $geoName->longitude;
                             $needSave = true;
                         }
                         if (!UtilsHelper::countRussianCharacters($city->localRu)) {
                             $city->localRu = $geoName->nameRu;
                             $needSave = true;
                         }
                         if (!$city->metaphoneRu) {
                             $city->metaphoneRu = $geoName->metaphoneRu;
                             $needSave = true;
                         }
                         if (!$city->stateCode) {
                             $city->stateCode = $geoName->stateCode;
                             $needSave = true;
                         }
                         if ($needSave) {
                             $modifyCount++;
                             $city->save();
                         }
                     } else {
                         $noResult++;
                         fwrite($outfp, "{$city->localEn}|{$city->code}|{$city->id}|{$count}\n");
                     }
                     if ($lineCount % 30000 == 0) {
                         echo "NoResults:{$noResult} OneResult:{$oneResult}\n";
                     }
                 }
             }
             echo "Total NoResults:{$noResult} OneResult:{$oneResult} ModifyCount: {$modifyCount} line count: {$lineCount}\n";
             fclose($outfp);
             //break;
         }
     }
     if ($type == 'updateMetaphone') {
         $criteria = new CDbCriteria();
         $criteria->condition = 'hotelbookId IS NOT NULL';
         //$criteria->params=array(':postID'=>10);
         $countries = Country::model()->findAll($criteria);
         $start = false;
         foreach ($countries as $country) {
             if (!$start) {
                 if ($country->code == 'UA') {
                     $start = true;
                 } else {
                     continue;
                 }
             }
             echo 'Update ' . $country->code . " metaphone\n";
             $criteria = new EMongoCriteria(array('conditions' => array('countryCode' => array('equals' => $country->code))));
             //$criteria->limit(10);
             $geoNames = GeoNames::model()->findAll($criteria);
             $k = 0;
             foreach ($geoNames as $geoName) {
                 $geoName->metaphoneRu = UtilsHelper::ruMetaphone($geoName->nameRu);
                 $geoName->save();
                 $k++;
                 if ($k % 30000 == 0) {
                     echo "Updated {$k} lines\n";
                 }
             }
             echo "{$country->code} complete. Updated {$k} lines\n";
             //break;
         }
         //$criteria = new EMongoCriteria(array('conditions'=>array('countryCode'=>array('equals'=>$country),'metaphoneRu'=>array('equals'=>$metaphoneRu)) ));
         //VarDumper::dump(GeoNames::model()->find($criteria));
     }
 }
<?php

require_once '../Hypersistence/Hypersistence.php';
Hypersistence::registerAutoloader();
require_once './Person.php';
require_once './Book.php';
require_once './Student.php';
require_once './Course.php';
require_once './City.php';
//SAVE
$c = new City();
$c->setName('San Francisco');
$c->save();
$s = new Student();
$s->setCity($c);
$s->setEmail('*****@*****.**');
$s->setName('Mateus Fornari');
$s->setNumber('123456');
var_dump($s->save());
$course = new Course();
$course->setDescription('PHP Programming');
$course->save();
$s->addCourses($course);
$p = new Person();
$p->setCity($c);
$p->setEmail('*****@*****.**');
$p->setName('Other Person');
$p->save();
$b = new Book();
$b->setAuthor($p);
$b->setTitle('PHP Book');
 public function save_location()
 {
     $id = Input::get('id');
     $city = City::find($id);
     if (!$city) {
         $city = new City();
     }
     $city->city = Input::get('city');
     $city->zipcode = Input::get('zipcode');
     $city->save();
     $message = "Successfully updated the city";
     $type = "success";
     return Redirect::to('/admin/locations')->with('type', $type)->with('message', $message);
 }
Beispiel #25
0
 public function agregar()
 {
     $data = array();
     if ($_POST) {
         $ciudad = new City(elements(array('nombre', 'state_id'), $_POST));
         if ($ciudad->is_valid()) {
             $ciudad->save();
             $this->session->set_flashdata('msg', '<div class="success">La ciudad se guardó correctamente.</div>');
             redirect('ciudades');
         } else {
             $data['errors'] = $ciudad->errors;
         }
     }
     $data['paises'] = Country::all();
     $data['provincias'] = State::all();
     $data['titulo'] = "Agregar Ciudad";
     $data['action'] = "ciudades/agregar";
     $this->template->write_view('content', 'ciudades/agregar', $data);
     $this->template->render();
 }
        die;
    } else {
        $message = join("<br />", $city->errors);
    }
}
if (isset($_GET['action']) && $_GET['action'] == "add") {
    if (isset($_POST['bt_add'])) {
        $city_name = $_POST['txt_city_name'];
        $city_code = $_POST['txt_city_code'];
        $active = $_POST['txt_is_active'];
        if (!City::find_by_city_name($city_name)) {
            $city = new City();
            $city->city_code = $city_code;
            $city->city_name = $city_name;
            $city->is_active = $active;
            if ($city->save()) {
                $session->message("<div class='success'>City <span style='color:blue;'>" . $city_name . "</span> added </div>");
                redirect_to($_SERVER['PHP_SELF'] . "?action=" . $_GET['action']);
                die;
            } else {
                $message = join("<br />", $city->errors);
            }
        } else {
            $session->message("<div class='error'>unable to add <span style='color:blue;'>" . $city_name . "</span></div>");
            redirect_to($_SERVER['PHP_SELF'] . "?action=" . $_GET['action']);
            die;
        }
    }
}
$delete_message = "Are you sure you wont to delete this City name";
$order_by = safe_output(urlencode($_GET['order_by']));
Beispiel #27
0
    echo "<h3>adodb_backtrace:</h3>\n";
    $e = adodb_backtrace($e->gettrace());
}
$rs = $db->Execute("select distinct id, firstname,lastname from adoxyz order by id");
echo "Result=\n", $rs, "</p>";
echo "<h3>Active Record</h3>";
include_once "../adodb-active-record.inc.php";
ADOdb_Active_Record::SetDatabaseAdapter($db);
try {
    class City extends ADOdb_Active_Record
    {
    }
    $a = new City();
} catch (exception $e) {
    echo $e->getMessage();
}
try {
    $a = new City();
    echo "<p>Successfully created City()<br>";
    #var_dump($a->GetPrimaryKeys());
    $a->city = 'Kuala Lumpur';
    $a->Save();
    $a->Update();
    #$a->SetPrimaryKeys(array('city'));
    $a->country = "M'sia";
    $a->save();
    $a->Delete();
} catch (exception $e) {
    echo $e->getMessage();
}
//include_once("test-active-record.php");
Beispiel #28
0
    $courtoffice = array();
    for ($i0 = 0; isset($r['0.' . $i0]); $i0++) {
        $courtoffice[$i0] = @$r['0.' . $i0 . ''];
    }
    $jurisdiction = @$r['1'];
    $courtofappeal = @$r['2'];
    $sessions = array();
    for ($i0 = 0; isset($r['3.' . $i0]); $i0++) {
        $sessions[$i0] = array('id' => @$r['3.' . $i0 . '.0'], 'Session' => @$r['3.' . $i0 . '.0'], 'scheduled' => @$r['3.' . $i0 . '.2'], 'panel' => @$r['3.' . $i0 . '.3']);
        $sessions[$i0]['judge'] = array();
        for ($i1 = 0; isset($r['3.' . $i0 . '.1.' . $i1]); $i1++) {
            $sessions[$i0]['judge'][$i1] = @$r['3.' . $i0 . '.1.' . $i1 . ''];
        }
    }
    $City = new City($ID, $courtoffice, $jurisdiction, $courtofappeal, $sessions);
    if ($City->save() !== false) {
        die('ok:' . $_SERVER['PHP_SELF'] . '?City=' . urlencode($City->getId()));
    } else {
        die('');
    }
    exit;
    // do not show the interface
}
$buttons = "";
if (isset($_REQUEST['new'])) {
    $new = true;
} else {
    $new = false;
}
if (isset($_REQUEST['edit']) || $new) {
    $edit = true;
 public function importExcelToMysql($filePath, $fields = array(), $model = null, $startingRow = 2)
 {
     $objPHPExcel = PHPExcel_IOFactory::load($filePath);
     foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
         //field validation
         $fieldValidate = array();
         $validated = FALSE;
         for ($col = 0; $col < count($fields); ++$col) {
             $val = $worksheet->getCellByColumnAndRow($fields[$col]['col'], 1)->getValue();
             $fieldValidate[$fields[$col]['name']] = $val;
         }
         if ($fieldValidate['province_code'] == 'Kode Provinsi' and $fieldValidate['code'] == 'Kode Kab/Kota' and $fieldValidate['name'] == 'Nama Kab/Kota') {
             $validated = TRUE;
         }
         //end of validation
         if ($validated == TRUE) {
             $highestRow = $worksheet->getHighestRow();
             // e.g. 10
             $isSuccess = FALSE;
             //Read data
             for ($row = $startingRow; $row <= $highestRow; ++$row) {
                 $attributes = array();
                 for ($col = 0; $col < count($fields); ++$col) {
                     $val = $worksheet->getCellByColumnAndRow($fields[$col]['col'], $row)->getValue();
                     $attributes[$fields[$col]['name']] = $val;
                 }
                 //Define code from readed data
                 $code = $attributes['province_code'] . '.' . $attributes['code'];
                 if ($attributes['province_code'] != NULL and $attributes['code'] != NULL and $attributes['name'] != NULL) {
                     //Check data is new record or old record
                     $recorded = City::model()->find(array('condition' => "code='{$code}'"));
                     if ($recorded) {
                         //If old record, update data
                         $recorded->attributes = $attributes;
                         $recorded->code = $code;
                         $recorded->name = ucwords(strtolower($attributes['name']));
                         if ($recorded->update()) {
                             $isSuccess = TRUE;
                         }
                     } else {
                         //If new record, create new data
                         $model = new City();
                         $model->attributes = $attributes;
                         $model->code = $code;
                         $model->name = ucwords(strtolower($attributes['name']));
                         if ($model->save()) {
                             $isSuccess = TRUE;
                         }
                     }
                 }
             }
             if ($isSuccess) {
                 unlink($filePath);
                 Yii::app()->user->setFlash('success', "Data berhasil diimport.");
                 $this->redirect(array('index'));
             } else {
                 unlink($filePath);
                 Yii::app()->user->setFlash('error', "Mohon masukkan data secara lengkap.");
             }
         } else {
             //Process if operator input wrong file
             unlink($filePath);
             Yii::app()->user->setFlash('error', "Pastikan file yang Anda upload sudah benar!");
             $this->redirect(array('import'));
         }
     }
 }
 protected function newCity()
 {
     $city = new City();
     if (isset($_POST['City'])) {
         $city->attributes = $_POST['City'];
         if ($city->save()) {
             $this->refresh();
         }
     }
     return $city;
 }