public function send()
 {
     //если нет в сессии пользователя, аккаунт которого восстанавливается, редирект на форму восстановления
     if (!$this->Session->check('recover_user_id') or !is_numeric($this->Session->read('recover_user_id'))) {
         $this->redirect(array('controller' => 'recovery', 'action' => 'index'));
         exit;
     }
     //поиск mail или phone по базе
     $find_user = $this->User->find('first', array('conditions' => array('id' => $this->Session->read('recover_user_id'))));
     if (count($find_user) == 0) {
         $this->redirect(array('controller' => 'recovery', 'action' => 'index', '?' => array('action' => 'failed', 'error' => 'user_not_found')));
     } else {
         $user_mail = $find_user['User']['mail'];
         $user_id = $find_user['User']['id'];
         $mail_key_salt = Configure::read('MAIL_KEY_SALT');
         //Создание ссылки восстановления
         $mail_key = generate_mail_key($user_id, $mail_key_salt);
         $data_to_save = array('mail_key' => $mail_key);
         $this->User->id = $user_id;
         $this->User->save($data_to_save);
         //Отправка письма с восстановлением
         //			$mail_template = 'user_register_mail_template';
         //			$mail_layout = 'user_register_mail_layout';
         //отправка регистрационного письма
         App::uses('CakeEmail', 'Network/Email');
         $sended_data = L('BO_RECOVERY_TITLE') . "<br>";
         $sended_data .= L('EMAIL') . ": " . $user_mail;
         $sended_data .= ", ";
         $sended_data .= "<a href='" . site_url() . "/recovery/setup_password/" . $mail_key . "'>" . L('RECOVERY_LINK_TEXT') . "</a>: <br>";
         $email = new CakeEmail();
         $email->emailFormat('html');
         $email->template('user_recovery_password_template', 'user_recovery_password_layout');
         $email->from(Configure::read('SITE_MAIL'));
         $email->to($user_mail);
         $email->subject(L('BO_RECOVERY_TITLE') . Configure::read('SITENAME'));
         $email->viewVars(array('sended_data' => $sended_data));
         echo 4;
         $email->send();
         echo 5;
         echo 1;
         $this->redirect(array('controller' => 'recovery', 'action' => 'sended'));
         exit;
     }
 }
 /**
  * Регистрация нового мастера
  */
 public function register()
 {
     $data = $this->params['data'];
     $upload_config = $this->request->data['upload_config'] ? $this->request->data['upload_config'] : null;
     if (isset($_FILES['file']) and $_FILES['file']['size'] > 0 and !empty($_FILES['file']['name'])) {
         $result_upload = $this->Uploader->upload($upload_config, $_FILES['file']);
     } else {
         $result_upload = null;
     }
     $user_data_step_1 = $this->Session->read('step_1_data');
     //данные пользователя
     $user_mail = $user_data_step_1["User"]["mail"];
     $user_data_step_1["User"]["specialization"] = isset($data['Register']["specialization"]) ? $data['Register']["specialization"] : null;
     $user_data_step_1["User"]["about_me"] = isset($data['Register']["about_me"]) ? $data['Register']["about_me"] : null;
     $user_data_step_1["User"]["education"] = isset($data['Register']["education"]) ? $data['Register']["education"] : null;
     $user_data_step_1["User"]["regards"] = isset($data['Register']["regards"]) ? $data['Register']["regards"] : null;
     $user_data_step_1["User"]["sex"] = isset($user_data_step_1["Register"]["sex"]) ? $data['Register']["sex"] : 1;
     $user_data_step_1["User"]["business_type"] = isset($user_data_step_1["User"]["business_type"]) ? $user_data_step_1["User"]["business_type"] : null;
     $user_data_step_1["User"]["interview_status"] = 'not_checked';
     $user_data_step_1["User"]["data_status"] = 'not_checked';
     $user_data_step_1["User"]["ref_id"] = isset($user_data_step_1["User"]["ref_id"]) ? $user_data_step_1["User"]["ref_id"] : null;
     $user_data_step_1["User"]["last_activity"] = date("Y-m-d H:i:s");
     $user_data_step_1["User"]["uptime"] = date("Y-m-d H:i:s");
     //date("Y-m-d H:i:s");;
     $user_data_step_1["User"]["mail_key"] = md5(time() . $user_data_step_1["User"]["mail"] . $user_data_step_1["User"]["phone"]);
     //генерация пароля с солью
     $real_pwd = $user_data_step_1["User"]["password"];
     $user_data_step_1["User"]["password"] = get_hash(Configure::read('USER_AUTH_SALT'), $user_data_step_1["User"]["password"]);
     $prepared_lastname = translit(mb_ucfirst(mb_strtolower($user_data_step_1['User']["lastname"])));
     $prepared_firstname = translit(mb_ucfirst(mb_strtolower(mb_substr($user_data_step_1['User']["firstname"], 0, 1))));
     $prepared_fathername = translit(mb_ucfirst(mb_strtolower(mb_substr($user_data_step_1['User']["fathername"], 0, 1))));
     $user_data_step_1["User"]["login"] = $prepared_lastname . $prepared_firstname . $prepared_fathername;
     $ref_id = $this->Session->read('REF');
     $user_data_step_1["User"]["ref_id"] = isset($ref_id) ? $ref_id : 0;
     if (!isset($user_data_step_1["User"]["city_id"]) or !is_numeric($user_data_step_1["User"]["city_id"])) {
         $user_data_step_1["User"]["city_id"] = 0;
     }
     //проверка логина
     $this->loadModel('User');
     $counter = 0;
     $login = $user_data_step_1["User"]["login"];
     $check_login = false;
     while ($check_login == false) {
         $test_login = $counter > 0 ? $login . $counter : $login;
         $check_login_count = $this->User->find('count', array('conditions' => array('login' => $test_login)));
         if ($check_login_count == 0) {
             $check_login = true;
             $user_data_step_1["User"]["login"] = $test_login;
         }
         $counter++;
     }
     $this->User->save($user_data_step_1);
     $user_id = $this->User->getLastInsertId();
     //ключ активации
     $mail_key_salt = Configure::read('MAIL_KEY_SALT');
     $mail_key = generate_mail_key($user_id, $mail_key_salt);
     //перенос изображения после создания нового пользователя
     $user_data_step_1["User"]["main_foto"] = $result_upload['full_path'];
     if ($result_upload !== null) {
         //если файл был загружен во временную директорию переносим его в директорию пользователя
         $user_dir = "u" . $user_id;
         $file_transfer = $this->Uploader->transfer_file($result_upload['file'], Configure::read('FILE_TEMP_DIR'), Configure::read('USER_FILE_UPLOAD_DIR') . DS . $user_dir, true);
         if ($file_transfer) {
             $uploaded_image = $this->Uploader->new_filename;
         }
     }
     /*запись услуг в прайс*/
     $this->loadModel('Userprices');
     $this->Userprices->useTable = 'user_prices';
     $money_types = Configure::read('VALID_MONEY_PREFIXES');
     $this->loadModel('Paytype');
     $this->Paytype->useTable = 'service_pay_types';
     for ($x = 0; $x < count($data['Register']["service"]["id"]); $x++) {
         $service_name = $data['Register']["service"]["id"][$x];
         $service_price = $data['Register']["service"]["price"][$x];
         $money_type = $data['Register']["service"]["money_type"][$x];
         $payment_type = $data['Register']["service"]["payment_type"][$x];
         $check_payment_type = $this->Paytype->find('count', array('conditions' => array('id' => $payment_type)));
         if (!empty($service) and is_numeric($service_price) and $service_price > 0 and in_array($money_type, $money_types) and $check_payment_type > 0) {
             $data_to_save = array('user_id' => $user_id, 'value' => $service_price, 'comment' => $service_name, 'money_type' => $money_type, 'pay_type_id' => $payment_type, 'status' => 'hidden');
             $result = $this->Userprices->save($data_to_save);
         } else {
             continue;
         }
     }
     //запись районов/адресов для оказания услуг
     $this->loadModel('UserToRegionPlace');
     $this->UserToRegionPlace->useTable = 'user_to_region_places';
     for ($x = 0; $x < count($data['Register']["place_live"]["region"]); $x++) {
         $address = isset($data['Register']["place_live"]["address"][$x]) ? $data['Register']["place_live"]["address"][$x] : '';
         $region_id = $data['Register']["place_live"]["region"][$x];
         if (isset($region_id) and is_numeric($region_id)) {
             $check_region_id = $this->Regions->find('first', array('conditions' => array('id' => $region_id)));
             if (count($check_region_id) > 0) {
                 $region_city_id = $check_region_id['Regions']['city_id'][0];
                 $user_city_id = $user_data_step_1['User']['city_id'];
                 //проверка соответствия региона города
                 if ($user_city_id == $region_city_id) {
                     //записываем адрес
                     $data_to_save = array('user_id' => $user_id, 'address' => $address, 'region_id' => $region_id, 'city_id' => $user_city_id);
                     $result = $this->UserToRegionPlace->save($data_to_save);
                 }
             }
         }
     }
     //запись районов для выезда
     $this->loadModel('UserToRegionGuest');
     $this->UserToRegionGuest->useTable = 'user_to_region_guests';
     if (isset($data['Register']["place_guest"])) {
         for ($x = 0; $x < count($data['Register']["place_guest"]["region"]); $x++) {
             $region_id = $data['Register']["place_guest"]["region"][$x];
             $check_region_id = $this->Regions->find('first', array('conditions' => array('id' => $region_id)));
             if (count($check_region_id) > 0) {
                 $region_city_id = $check_region_id['Regions']['city_id'];
                 $user_city_id = $user_data_step_1['User']['city_id'];
                 //проверка соответствия региона города
                 if ($user_city_id == $region_city_id) {
                     //записываем адрес
                     $data_to_save = array('user_id' => $user_id, 'region_id' => $region_id, 'city_id' => $user_city_id);
                     $this->UserToRegionGuest->save($data_to_save);
                 }
             }
         }
     }
     //получение id страны
     $this->loadModel('City');
     if ($user_data_step_1['User']['city_id'] > 0) {
         $country_data = $this->City->find('first', array('conditions' => array('id' => $user_data_step_1['User']['city_id'])));
         $country_id = $country_data['City']['country_id'];
     } else {
         $country_id = 0;
     }
     $this->User->id = $user_id;
     if (!isset($uploaded_image)) {
         $uploaded_image = '';
     }
     $data_to_save = array('mail_key' => $mail_key, 'main_foto' => $uploaded_image, 'country_id' => $country_id);
     $this->User->save($data_to_save);
     //если указаны категории - сохраняем их
     /*
     if (count($data['Register']["service"] > 0)) {
     	$this->loadModel('Service');
     	$this->loadModel('Servicetouser');
     	for ($x = 0; $x < count($data['Register']["service"]); $x++) {
     		$cur_id = $data['Register']["service"]["id"][$x];
     		if (is_numeric($cur_id)) {
     			$service = $this->Service->find('all', array('conditions' => array('Service.id = ' . $cur_id)))[0];
     			if ($service == null) {
     				$this->Error->setError('ERROR_201');
     			} else {
     				$this->Servicetouser->useTable = 'service_to_users';
     				$data_for_save = array(
     					"service_id" => $service["Service"]["id"],
     					"user_id" => $user_id
     				);
     				$this->Servicetouser->save($data_for_save);
     			}
     		}
     	}
     }
     */
     App::uses('CakeEmail', 'Network/Email');
     $sended_data = L("YOU_JUST_REGISTERED") . " " . site_url() . "<br>";
     $sended_data .= L("REGISTER_DATA") . " " . L("YOUR_LOGIN") . " :" . $login;
     $sended_data .= ", ";
     $sended_data .= L("YOUR_PASSWORD") . ": " . $real_pwd . "<br>";
     $sended_data .= "<a href='" . site_url() . "/activate_account/user/" . $mail_key . "'>" . L('ACTIVATE_LINK') . "</a> " . L('REGISTER_LINK_TEXT') . ": <br>";
     $email = new CakeEmail();
     $email->emailFormat('html');
     $email->template('user_register_mail_template', 'user_register_mail_layout');
     $email->from(Configure::read('SITE_MAIL'));
     $email->to($user_data_step_1["User"]["mail"]);
     $email->subject(L('REGISTER_ON_PROJECT') . " " . site_url());
     $email->viewVars(array('sended_data' => $sended_data));
     $email->send();
     $this->redirect(array('controller' => 'register', 'action' => 'ok'));
 }