/** * Custom validation for this model - complements the default validate() * * @param array array to validate * @param Auth instance of Auth class; used for testing purposes * @return bool TRUE if validation succeeds, FALSE otherwise */ public static function custom_validate(array &$post, Auth $auth = null) { // Initalize validation $post = Validation::factory($post)->pre_filter('trim', TRUE); if ($auth === null) { $auth = new Auth(); } $post->add_rules('username', 'required', 'length[3,100]', 'alpha_numeric'); $post->add_rules('name', 'required', 'length[3,100]'); $post->add_rules('email', 'required', 'email', 'length[4,64]'); // If user id is not specified, check if the username already exists if (empty($post->user_id)) { $post->add_callbacks('username', array('User_Model', 'unique_value_exists')); $post->add_callbacks('email', array('User_Model', 'unique_value_exists')); } // Only check for the password if the user id has been specified if (empty($post->user_id)) { $post->add_rules('password', 'required', 'length[5,50]', 'alpha_numeric'); } // If Password field is not blank if (!empty($post->password) or empty($post->password) and !empty($post->password_again)) { $post->add_rules('password', 'required', 'length[5,50]', 'alpha_numeric', 'matches[password_again]'); } $post->add_rules('role', 'required', 'length[3,30]', 'alpha_numeric'); $post->add_rules('notify', 'between[0,1]'); if (!$auth->logged_in('superadmin')) { $post->add_callbacks('role', array('User_Model', 'prevent_superadmin_modification')); } // Additional validation checks Event::run('ushahidi_action.user_submit_admin', $post); // Return return $post->validate(); }
public function action_login() { if (Auth::check()) { Response::redirect('/'); // user already logged in } $val = Validation::factory('users'); $val->add_field('username', 'Your username', 'required|min_length[3]|max_length[20]'); $val->add_field('password', 'Your password', 'required|min_length[3]|max_length[20]'); if ($val->run()) { $auth = Auth::instance(); if ($auth->login($val->validated('username'), $val->validated('password'))) { Session::set_flash('notice', 'FLASH: logged in'); Response::redirect('users'); } else { $data['username'] = $val->validated('username'); $data['errors'] = 'Wrong username/password. Try again'; } } else { if ($_POST) { $data['username'] = $val->validated('username'); $data['errors'] = 'Wrong username/password combo. Try again'; } else { $data['errors'] = false; } } $this->template->title = 'Login'; $this->template->logged_in = false; $this->template->errors = @$data['errors']; $this->template->content = View::factory('users/login', $data); }
/** * Upload function for a JNCC style designations spreadsheet. */ public function upload_csv() { try { // We will be using a POST array to send data, and presumably a FILES array for the // media. // Upload size $ups = Kohana::config('indicia.maxUploadSize'); $_FILES = Validation::factory($_FILES)->add_rules('csv_upload', 'upload::valid', 'upload::required', 'upload::type[csv]', "upload::size[{$ups}]"); if (count($_FILES) === 0) { echo "No file was uploaded."; } elseif ($_FILES->validate()) { if (array_key_exists('name_is_guid', $_POST) && $_POST['name_is_guid'] == 'true') { $finalName = strtolower($_FILES['csv_upload']['name']); } else { $finalName = time() . strtolower($_FILES['csv_upload']['name']); } $fTmp = upload::save('csv_upload', $finalName); url::redirect('taxon_designation/import_progress?file=' . urlencode(basename($fTmp))); } else { kohana::log('error', 'Validation errors uploading file ' . $_FILES['csv_upload']['name']); kohana::log('error', print_r($_FILES->errors('form_error_messages'), true)); throw new ValidationError('Validation error', 2004, $_FILES->errors('form_error_messages')); } } catch (Exception $e) { $this->handle_error($e); } }
/** * Отправка письма на восстановление пароля * @return */ public function action_forgot_password() { $this->template->title = $this->site_name . 'Восстановление пароля'; $this->template->bc['#'] = 'Восстановление пароля'; if ($_POST) { $validation = Validation::factory($_POST)->rule('username_email', 'not_empty'); if ($validation->check()) { $have_user = DB::select('email', 'id', 'username')->from('users')->where('username', '=', $validation['username_email'])->or_where('email', '=', $validation['username_email'])->execute()->current(); if ($have_user) { //echo $have_user; $key = md5($validation['username_email']); DB::insert('recover_passwords', array('key', 'user_id'))->values(array($key, $have_user['id']))->execute(); $email_view = View::factory('email/recover_password')->set('username', $have_user['username'])->set('key', $key)->render(); Email::send($have_user['email'], array('*****@*****.**', 'Ассоциация автосервисов'), 'Восстановление пароля', $email_view, true); $view = View::factory('frontend/auth/forgot_send_email_complete'); $this->template->content = $view; return; } else { $this->errors['username_email'] = 'Такой пользователь не найден'; } } else { $this->errors = $validation->errors('registration'); } } $this->view = View::factory('frontend/auth/forgot')->set('values', $this->values)->set('errors', $this->errors); $this->template->content = $this->view; }
/** * Validation image file * * @return $this * @throws Exception */ private function _validation() { if (!Upload::valid(Arr::get($_FILES, $this->_config['fn']))) { throw new Exception('Error field input name'); } return Validation::factory($_FILES)->rule($this->_config['fn'], 'Upload::valid')->rule($this->_config['fn'], 'Upload::type', array(':value', array('jpg', 'jpeg', 'png', 'gif')))->rule($this->_config['fn'], 'Upload::size', array(':value', '10M'))->rule($this->_config['fn'], 'Upload::image'); }
function action_view() { $open_coupon = Arr::get($_GET, 'print_coupon', FALSE); $service = ORM::factory('service', $this->request->param('id', NULL)); if (!$service->loaded() || !$service->active) { Message::set(Message::ERROR, 'Такой сервис не найден'); $this->request->redirect('/'); } $this->validation = Validation::factory($_POST)->rule('antibot', 'not_empty'); if ($_POST) { $review = ORM::factory('review'); try { $review->values($_POST, array('text', 'email')); $review->date = Date::formatted_time(); $review->service_id = $service->id; $review->active = 0; //$review->user_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; $review->save($this->validation); Message::set(Message::SUCCESS, Kohana::message('success_msg', 'review_created')); $this->request->redirect('services/' . $service->id); } catch (ORM_Validation_Exception $e) { $this->errors = $e->errors('models'); $this->values = $_POST; } } $this->view = View::factory('frontend/services/view_service')->set('service', $service)->set('open_coupon', $open_coupon)->set('coupon_frame', HTML::iframe('services/get_coupon/' . $service->id, 'coupon_frame'))->set('values', $this->values)->set('errors', $this->errors); $this->template->bc['/'] = 'Главная'; $this->template->bc['#'] = $service->name; $this->template->title = 'Автосервис ' . $service->name . ' ' . $service->about; $this->template->meta_description = strip_tags($service->about); $this->add_js('http://api-maps.yandex.ru/1.1/index.xml?key=' . $this->settings['YMaps_key'] . '&onerror=map_alert'); $this->add_js('assets/js/maps_detail.js'); $this->add_js('assets/share42/share42.js'); $this->template->content = $this->view; }
public function action_hashpass() { $this->template->positionleft = false; //Создание обьекта авторизации $auth = Auth::instance(); $data = array(); if ($auth->logged_in()) { if ($_POST) { $post = Validation::factory($_POST); $post->rule('password_old', 'not_empty')->rule('password_old', 'Model_Myuser::not_password')->rule('password_new', 'not_empty')->rule('password_confirm', 'not_empty')->rule('password_confirm', 'matches', array(':validation', 'password_new', ':field')); if ($post->check()) { $model = ORM::factory('myuser')->where("id", "=", $auth->get_user()->id)->find(); $model->password = $auth->hash_password($post['password_new']); $model->save(); $this->redirect('main'); } else { $data = $post->errors("chanepass"); } } $view = View::factory('chanepass'); $view->data = $data; // $this->template->content = View::factory($view); $this->template->content = $view; } else { $this->redirect('auth'); } }
public function action_archivos() { $errors = array(); $id = $_GET['contra']; $proceso = ORM::factory('gestiones', $id); if ($_POST) { $id_archivo = 0; $archivo_texto = ''; $post = Validation::factory($_FILES)->rule('archivo', 'Upload::not_empty')->rule('archivo', 'Upload::type', array(':value', array('jpg', 'png', 'gif', 'pdf', 'doc', 'docx', 'ppt', 'xls', 'xlsx')))->rule('archivo', 'Upload::size', array(':value', '3M')); // ->rules ( 'archivo', array (array ('Upload::valid' ), array ('Upload::type', array (':value', array ('pdf', 'doc', 'docx', 'ppt', 'xls', 'xlsx' ) ) ), array ('Upload::size', array (':value', '5M' ) ) ) ); //si pasa la validacion guardamamos if ($post->check()) { //guardamos el archivo $filename = upload::save($_FILES['archivo1']); $archivo1 = ORM::factory('archivos1'); //intanciamos el modelo $archivo1->archivo = basename($filename); $archivo1->extension = $_FILES['archivo']['type']; $archivo1->size = $_FILES['archivo']['size']; $archivo1->fecha = date('Y-m-d'); $archivo1->proceso_id = $_POST['proceso_id']; // $archivo->id = $nuevo->id; $archivo->save(); $_POST = array(); //enviamos email // $this->template->content=View::factory('digitales'); } else { $errors['Datos'] = 'No se pudo guardar, vuelva a intentarlo'; } } else { $errors['Archivos'] = 'Ocurrio un error al subir el archivo'; } $archivos = ORM::factory('archivos')->where('proceso_id', '=', $id)->find_all(); $this->template->content = View::factory('Archivos')->bind('errors', $errors)->bind('proceso', $proceso)->bind('archivos', $archivos); }
public function action_ajax_add_feedback() { if ($_POST) { $errors = array('name' => 'false', 'text' => 'false', 'email' => 'false', 'check' => 'false', 'phone' => 'false'); if (Validation::factory($_POST)->rule('email', 'email')->rule('email', 'not_empty')->check()) { $errors['email'] = 'true'; } if (Validation::factory($_POST)->rule('phone', 'not_empty')->check()) { $errors['phone'] = 'true'; } if (Validation::factory($_POST)->rule('name', 'not_empty')->check()) { $errors['name'] = 'true'; } if (Validation::factory($_POST)->rule('text', 'not_empty')->check()) { $errors['text'] = 'true'; } $check = arr::get($_POST, 'check'); if (!$check) { $errors['check'] = 'true'; } if ($errors['name'] == 'true' && $errors['email'] == 'true' && $errors['phone'] == 'true' && $errors['text'] == 'true' && $errors['check'] == 'true') { $feedback = ORM::factory('Feedback'); $feedback->name = arr::get($_POST, 'name'); $feedback->phone = arr::get($_POST, 'phone'); $feedback->email = arr::get($_POST, 'email'); $feedback->text = arr::get($_POST, 'text'); $feedback->save(); Email::send('*****@*****.**', array('*****@*****.**', 'Trip-Shop'), 'Новый отзыв', 'Имя - ' . arr::get($_POST, 'name') . '<br/>' . 'Email - ' . arr::get($_POST, 'email') . '<br/>' . 'Телефон - ' . arr::get($_POST, 'phone') . '<br/>' . arr::get($_POST, 'text'), true); } echo json_encode($errors); } else { $this->forward_404(); } }
public function login() { // if user is logged in, redirect refering page $validation = Validation::factory($_POST)->pre_filter('trim', TRUE)->add_rules('username', 'required')->add_rules('password', 'required'); $return_path = $this->session->get('return_path') ? $this->session->get('return_path') : '/'; $login = View::factory('pages/login'); $login->login_failed = false; if ($_POST) { if (!$validation->validate()) { $login->login_failed = true; $form = $validation->as_array(); $errors = $validation->errors('custom_error'); } else { $username = $validation->username; $password = $validation->password; if ($this->auth->login($username, $password, true)) { // Login successful, redirect Session::instance()->set_flash('flash', SubfolioLanguage::get_text('login_complete')); url::redirect($return_path); exit; } else { $login->login_failed = true; Session::instance()->set_flash('error', SubfolioLanguage::get_text('login_failed')); } } } else { $login->login_failed = false; } $this->template->content = $login; }
/** * REST endpoint for sharing droplets via email */ public function action_share() { $this->template = ''; $this->auto_render = FALSE; if ($this->request->method() != "POST") { throw HTTP_Exception::factory(405)->allowed('POST'); } // Extract the input data to be used for sending the email $post = Arr::extract($_POST, array('recipient', 'drop_title', 'drop_url', 'security_code')); $csrf_token = $this->request->headers('x-csrf-token'); // Setup validation $validation = Validation::factory($post)->rule('recipient', 'not_empty')->rule('recipient', 'email')->rule('security_code', 'Captcha::valid')->rule('drop_title', 'not_empty')->rule('drop_url', 'url'); // Validate if (!CSRF::valid($csrf_token) or !$validation->check()) { Kohana::$log->add(Log::DEBUG, "CSRF token or form validation failure"); throw HTTP_Exception::factory(400); } else { list($recipient, $subject) = array($post['recipient'], $post['drop_title']); // Modify the mail body to include the email address of the // use sharing content $mail_body = __(":user has shared a drop with you via SwiftRiver\n\n:url", array(':user' => $this->user['owner']['username'], ':url' => $post['drop_url'])); // Send the email Swiftriver_Mail::send($recipient, $subject, $mail_body); } }
private function _login() { $array = $this->request->post('login'); $array = Validation::factory($array)->label('username', 'Username')->label('password', 'Password')->label('email', 'Email')->rules('username', array(array('not_empty')))->rules('password', array(array('not_empty'))); $fieldname = Valid::email(Arr::get($array, 'username')) ? Auth::EMAIL : Auth::USERNAME; // Get the remember login option $remember = isset($array['remember']); Observer::notify('admin_login_validation', $array); if ($array->check()) { Observer::notify('admin_login_before', $array); if (Auth::instance()->login($array['username'], $array['password'], $remember)) { Observer::notify('admin_login_success', $array['username']); Session::instance()->delete('install_data'); Kohana::$log->add(Log::INFO, ':user login')->write(); if ($next_url = Flash::get('redirect')) { $this->go($next_url); } // $this->go to defaut controller and action $this->go_backend(); } else { Observer::notify('admin_login_failed', $array); Messages::errors(__('Login failed. Please check your login data and try again.')); $array->error($fieldname, 'incorrect'); Kohana::$log->add(Log::ALERT, 'Try to login with :field: :value. Incorrect data', array(':field' => $fieldname, ':value' => $array['username']))->write(); } } else { Messages::errors($array->errors('validation')); } $this->go(Route::get('user')->uri(array('action' => 'login'))); }
public function extra_rules() { $received = UTF8::get_value($this->_form, "min") + UTF8::get_value($this->_form, "max"); $sent = UTF8::get_value($this->_form, "captcha"); $captcha = array("sent" => (string) $sent, "received" => (string) $received); return Validation::factory($this->_form)->rule("display_name", "not_empty")->rule("display_name", "regex", array(":value", "/^[a-z_.]++\$/iD"))->rule("user_email", "not_empty")->rule("user_email", "Valid::email")->rule("user_email", "Valid::email_domain")->rule("phone", "not_empty")->rule("phone", "Valid::phone", array(":value", array(9, 10, 11)))->rule("reason", "not_empty")->rule("message", "not_empty")->rule("message", "min_length", array(":value", 4))->rule("message", "max_length", array(":value", 150))->rule("captcha", "not_empty")->rule("captcha", "Valid::matches", array($captcha, "sent", "received"))->rule("overflow", "is_empty")->rule("csrf", "not_empty")->rule("csrf", "Security::check"); }
public function addPortfolio($no) { $tempFileName = 'file' . rand(10000000, 99999999); $validationFiles = Validation::factory($_FILES)->rules('portfolioSmall', array(array('Upload::not_empty'), array('Upload::image')))->rules('portfolioBig', array(array('Upload::not_empty'), array('Upload::image'))); $validationText = Validation::factory($_POST)->rule('name', 'not_empty'); if ($validationFiles->check() and $validationText->check()) { Upload::save($validationFiles['portfolioSmall'], $tempFileName . '.png', Upload::$default_directory); Upload::save($validationFiles['portfolioBig'], $tempFileName . '.jpg', Upload::$default_directory); $tempFileNamePath = Upload::$default_directory . $tempFileName; $filePath = Kohana::$config->load('portfolio')->get('filePath'); if (copy($tempFileNamePath . '.png', $filePath . $tempFileName . '.png') and copy($tempFileNamePath . '.jpg', $filePath . $tempFileName . '.jpg')) { unlink($tempFileNamePath . '.png'); unlink($tempFileNamePath . '.jpg'); $this->path = $tempFileName; $this->name = HTML::chars($_POST['name']); $this->type = HTML::chars($_POST['type']); if (!$no) { $this->no = (int) $this->maxNoPortfolio() + 1; } else { $this->no = $no; } $this->create(); return true; } else { return false; } } else { return false; } }
public function action_register() { if (\Auth::check()) { \Session::set_flash('error', 'FLASH: Can\'t register while logged in, log out first.'); \Output::redirect('myauth'); } // The same fields as the example above $val = \Validation::factory('myauth2'); $val->add_field('username', 'Your username', 'required|min_length[3]|max_length[20]'); // $val->add_field('username', 'Your username', 'required|min_length[3]|max_length[20]|unique[simpleauth.username]'); $val->add_field('password', 'Your password', 'required|min_length[3]|max_length[20]'); $val->add_field('email', 'Email', 'required|valid_email'); // run validation on just post if ($val->run()) { if (\Auth::instance()->create_user($val->validated('username'), $val->validated('password'), $val->validated('email'), '100')) { \Session::set_flash('notice', 'FLASH: User created.'); \Output::redirect('myauth'); } else { throw new Exception('Smth went wrong while registering'); } } else { // validation failed if ($_POST) { $data['username'] = $val->validated('username'); $data['login_error'] = 'All fields are required.'; } else { $data['login_error'] = false; } } $this->template->title = 'Myauth » Register'; $this->template->login_error = @$data['login_error']; $this->template->content = \View::factory('register'); }
/** * Edit */ public function action_edit() { $this->title = __('home.page_edit'); // Fields for save $for_extract = ['text', 'meta_t', 'meta_d', 'meta_k']; $config = Config::get('home'); $data = Arr::extract($_POST, $for_extract); if ($this->request->is_post()) { $data = Validation::factory(array_map('trim', $data))->rule('meta_t', 'not_empty')->rule('meta_d', 'not_empty')->rule('meta_k', 'not_empty'); if ($data->check()) { foreach ($for_extract as $field) { $config[$field] = $data[$field]; } $config->save(); Message::success(__('settings.changes_saved')); HTTP::redirect(Route::url('b_home')); } else { Message::error(__('settings.error_saving')); $errors = $data->errors('validation'); } } else { $data = $config; } $this->content = View::factory($this->view, ['data' => $data])->bind('errors', $errors); }
public function action_index() { $view = View::factory('home/register'); if ($this->request->method() === Request::POST) { if (!Security::check($this->request->post('token'))) { throw new Exception("Bad Token"); } $post = Validation::factory($_POST)->rule('name', 'not_empty')->rule('surname', 'not_empty')->rule('email', 'not_empty')->rule('email', 'email')->rule('email', 'Model_Client::if_email_exists')->rule('pass', 'not_empty')->rule('pass_confirm', 'not_empty')->rule('pass', 'matches', array(':validation', 'pass_confirm', 'pass'))->rule('checkbox', 'not_empty'); if ($post->check()) { $salt = 'MySalt!'; $name = $this->request->post('name'); $surname = $this->request->post('surname'); $email = $this->request->post('email'); $pass = crypt($salt, $this->request->post('pass')); $checkbox = $this->request->post('checkbox'); $clients = new Model_Client(); $data = array('name' => $name, 'surname' => $surname, 'email' => $email, 'pass' => $pass, 'is_superuser' => '0'); $create_user = $clients->create_user($data); if (!$create_user) { throw new Exception("Please check all fields!"); } $this->request->redirect('/'); } } $this->template->content = $view->render(); }
function index() { $this->template->content = new View('admin/blocks'); $this->template->content->title = Kohana::lang('ui_admin.blocks'); // Get Registered Blocks if (!is_array($this->_registered_blocks)) { $this->_registered_blocks = array(); } // Get Active Blocks $settings = ORM::factory('settings', 1); $active_blocks = $settings->blocks; $active_blocks = array_filter(explode("|", $active_blocks)); // setup and initialize form field names $form = array('action' => '', 'block' => ''); // copy the form as errors, so the errors will be stored with keys corresponding to the form field names $errors = $form; $form_error = FALSE; $form_saved = FALSE; $form_action = ""; if ($_POST) { $post = Validation::factory($_POST); // Add some filters $post->pre_filter('trim', TRUE); // Add some rules, the input field, followed by a list of checks, carried out in order $post->add_rules('action', 'required', 'alpha', 'length[1,1]'); $post->add_rules('block', 'required', 'alpha_dash'); if (!array_key_exists($post->block, $this->_registered_blocks)) { $post->add_error('block', 'exists'); } if ($post->validate()) { // Activate a block if ($post->action == 'a') { array_push($active_blocks, $post->block); $settings->blocks = implode("|", $active_blocks); $settings->save(); } elseif ($post->action == 'd') { $active_blocks = array_diff($active_blocks, array($post->block)); $settings->blocks = implode("|", $active_blocks); $settings->save(); } } else { $errors = arr::overwrite($errors, $post->errors('blocks')); $form_error = TRUE; } } // Sort the Blocks $sorted_blocks = blocks::sort($active_blocks, array_keys($this->_registered_blocks)); $this->template->content->form = $form; $this->template->content->errors = $errors; $this->template->content->form_error = $form_error; $this->template->content->form_saved = $form_saved; $this->template->content->form_action = $form_action; $this->template->content->total_items = count($this->_registered_blocks); $this->template->content->registered_blocks = $this->_registered_blocks; $this->template->content->active_blocks = $active_blocks; $this->template->content->sorted_blocks = $sorted_blocks; // Javascript Header $this->template->tablerowsort_enabled = TRUE; $this->template->js = new View('admin/blocks_js'); }
public function action_index() { $this->template->title = "Welcome at Smacky Burgers"; $tables = ORM::factory('table')->find_all(); if (!$_POST) { //display the form $this->template->content = View::factory('forms/reservation')->set('errors', array())->set('tables', $tables); } else { try { $reservation = ORM::factory('reservation'); $reservation->values($_POST); $reservation->start = $_POST['date'] . " " . $_POST['time']; $reservation->end = date("Y-m-d H:i", strtotime($reservation->start) + 3600); //add extra validation rules $extra_rules = Validation::factory($_POST)->rule('date', 'not_empty')->rule('date', array($reservation, 'validate_date'), array(':validation', ':field', ':value'))->rule('time', 'not_empty')->rule('time', array($reservation, 'validate_date'), array(':validation', ':field', ':value')); $reservation->save($extra_rules); //everything went well, so display a success-page $this->template->content = View::factory('forms/reservation_success')->set('reservation', $reservation); } catch (ORM_Validation_Exception $e) { $errors = $e->errors('models'); //flatten the error array foreach ($errors as $field => $msg) { if (is_array($msg)) { $errors = array_merge($errors, $msg); } } unset($errors['_external']); //display the form and errors $this->template->content = View::factory('forms/reservation')->set('errors', $errors)->set('tables', $tables); } } }
public function addUser($data) { $vData = $data; $validation = Validation::factory($vData); $validation->rule('username', 'not_empty'); $validation->rule('username', 'email'); if (!$validation->check()) { $this->errors = $validation->errors('userErrors'); return FALSE; } $pass = Arr::get($data, 'pass'); $username = addslashes(Arr::get($data, 'username')); $myuser = ORM::factory('Myuser'); $auth = Auth::instance(); $pass = $auth->hash($pass); //Создаем пользователя $myuser->username = $username; $myuser->email = $username; $myuser->password = $pass; $myuser->name = addslashes(Arr::get($data, 'name')); $myuser->phone = addslashes(Arr::get($data, 'phone')); try { $myuser->save(); //Узнаем id пользователя $add_user_id = ORM::factory("user", array("username" => $username))->id; $token = substr($auth->hash($add_user_id . $username), 0, 20); //добавляем роль пользователя $model_addrole = new Model_Addrole(); $model_addrole->user_id = $add_user_id; $model_addrole->role_id = Arr::get($data, "role"); $model_addrole->save(); //добавляем запись для активации $model_addtoken = new Model_Addtoken(); $model_addtoken->user_id = $add_user_id; $model_addtoken->token = $token; $model_addtoken->save(); //отправляем пользователю сообщение для авторизации $config = Kohana::$config->load('email'); $mbase = new Model_Base(); $options = $mbase->getOptions(); Email::connect($config); $to = $username; $subject = 'Добро пожаловать на сайт ' . $options['sitename']; $from = $config['options']['username']; $message = '<b>Отправитель</b>: ' . Kohana::$base_url . '<br>'; $message .= 'Для работы с заказами на сайте Вам необходимо активировать учетную запись. <br> <br> Ваш логин: ' . $username . '<br> Ваш пароль: ' . Arr::get($data, 'pass') . '<br><br> Для активации перейдите по <a href="' . Kohana::$base_url . 'registration?token=' . $token . '&user='******'">этой ссылке</a> <hr> Спасибо за то, что пользуетесь услугами нашего сайта. По всем вопросам обращайтесь в техподдержку: ' . $config['options']['username']; $res = Email::send($to, $from, $subject, $message, $html = TRUE); return $add_user_id; } catch (ORM_Validation_Exception $e) { $this->errors = $e->errors('validation'); return false; } }
/** * Validates and optionally saves a message log record from an array * * @param array $array Data to be validated and optionally saved * @param bool $save Creates the record in the DB when TRUE * @return bool */ public function validate(array &$array, $save = FALSE) { // Validation rules for a log entry $array = Validation::factory($array)->pre_filter('trim')->add_rules('message_id', 'required')->add_rules('message_sender', 'required')->add_rules('message_type', 'required', 'in_array[0,1]'); // Pass validation to parent and return return parent::validate($array, $save); }
/** * @param bool $id * @return bool * @throws Kohana_Exception * * insert or update book */ public function insBook($id = false) { $_POST = Arr::map('trim', $_POST); $post = Validation::factory($_POST); $post->rule('name', 'not_empty')->rule('name', 'alpha_numeric', array(':value', false))->rule('name', 'min_length', array(':value', 2))->rule('name', 'max_length', array(':value', 20))->rule('email', 'email')->rule('body', 'not_empty')->rule('body', 'max_length', array(':value', 1024)); if ($post->check()) { if ($id) { $book = ORM::factory('Guestbook', $id); } else { $book = ORM::factory('Guestbook'); } $book->name = Security::encode_php_tags(HTML::chars($_POST['name'])); $book->email = Security::encode_php_tags(HTML::chars($_POST['email'])); $book->body = Security::encode_php_tags(HTML::chars($_POST['body'])); try { if ($id) { $book->update(); } else { $book->create(); } return true; } catch (ORM_Validation_Exception $e) { return false; } } else { //$errors = $post -> errors('validation'); return false; } }
public function action_index() { $count = ORM::factory('User')->count_all(); if ($count === 0) { $this->template->content = View::factory('install/index'); if ($this->request->method() === Request::POST) { if (!Security::check($this->request->param('id'))) { throw new Exception("Bad token!"); } $post = Validation::factory($_POST)->rule('username', 'not_empty')->rule('email', 'not_empty')->rule('email', 'email')->rule('password', 'not_empty')->rule('password', 'min_length', array(':value', '8'))->rule('password2x', 'not_empty')->rule('password', 'matches', array(':validation', 'password', 'password2x')); if ($post->check()) { $user = new Model_User(); $post = $this->request->post(); $user->values($post)->save(); $adminRole = ORM::factory('Role')->where('name', '=', 'admin')->find(); $loginRole = ORM::factory('Role')->where('name', '=', 'login')->find(); $user->add('roles', $loginRole); $user->add('roles', $adminRole); $this->redirect('install/successful'); } else { $this->redirect('install/oops'); } } } else { $this->redirect(''); } }
public function action_login() { $this->template->menu_login = TRUE; // Если залогинен, то перекидываем на дерево if (Auth::instance()->logged_in()) { $this->redirect(Route::url('user/id', array('user_id' => Auth::instance()->get_user()->id))); } $post = Arr::extract($this->request->post(), array('email', 'password')); $data['errors'] = NULL; if ($this->request->method() == 'POST') { $valid = Validation::factory($post)->rules('email', array(array('not_empty')))->rules('password', array(array('not_empty')))->labels(array('email' => 'Адрес электронной почты', 'password' => 'Пароль')); if (!$valid->check()) { $data['errors'] = $valid->errors('valid'); } else { if (Auth::instance()->login($valid['email'], $valid['password'], TRUE)) { // Авторизация прошла успешно if (!is_null($this->request->referrer())) { $this->redirect($this->request->referrer()); } else { $this->redirect(Route::url('user/id', array('user_id' => Auth::instance()->get_user()->id))); } } else { $data['errors'] = array('usermail' => '', 'userpass' => Kohana::message('valid', 'login.incorrect')); } } } $data += $post; $this->template->content = View::factory('auth/login', $data); }
/** * Delete existing SMS message * * @param string response_type - The response to return.XML or JSON. */ public function _delete_sms_msg($response_type) { if ($_POST) { $post = Validation::factory($_POST); // Add some filters $post->pre_filter('trim', TRUE); // Add some rules, the input field, followed by a list of //checks, carried out in order $post->add_rules('action', 'required', 'alpha', 'length[1,1]'); $post->add_rules('message_id.*', 'required', 'numeric'); if ($post->validate()) { $sms_id = $post->sms_id; $sms = new Message_Model($sms_id); if ($sms->loaded == true) { $sms->delete(); } else { //Comment id doesn't exist in DB //TODO i18nize the string $this->error_messages .= "SMS ID does not exist."; $this->ret_value = 1; } } else { //TODO i18nize the string $this->error_messages .= "SMS ID is required."; $this->ret_value = 1; } } else { $this->ret_value = 3; } return $this->api_actions->_response($this->ret_value, $response_type); }
public function action_registration() { if ($this->auth->logged_in()) { // Редиректим HTTP::redirect(URL::base()); } $this->template->title = "Registration"; $content = new View('reg'); $data = array(); if ($_POST) { $user = ORM::factory('user'); $data = Arr::extract($_POST, array('username', 'password', 'password_confirm')); $user->values($data, array('username', 'password')); $extra_validation = Validation::factory(array('username' => $data['username'], 'password' => $data['password'], 'password_confirm' => $data['password_confirm'])); $extra_validation->rule('password', 'alpha_numeric', array(':value', TRUE))->rule('password', 'not_empty')->rule('password', 'min_length', array(':value', 4))->rule('password', 'max_length', array(':value', 32))->rule('username', 'not_empty')->rule('username', 'alpha_numeric', array(':value', TRUE))->rule('password_confirm', 'matches', array(':validation', 'password_confirm', 'password')); try { $user->save($extra_validation); $user->add('roles', ORM::factory('role')->where('name', '=', 'login')->find()); //$this->auth->login($data['username'], $data['password'], 1); $content = View::factory('reg_success'); $this->template->title = "Successfully registration"; } catch (ORM_Validation_Exception $e) { $content->form_data = $data; $content->errors = $extra_validation->errors(''); } } $this->template->content = $content; }
/** * Validates and optionally saves a form field record from an array * * @param array $array Values to check * @param bool $save Save the record when validation suceeds * @return bool */ public function validate(array &$array, $save = FALSE) { // Setup validation $array = Validation::factory($array)->pre_filter('trim', TRUE)->add_rules('form_id', 'required', 'numeric', array('Form_Model', 'is_valid_form'))->add_rules('field_type', 'required', 'numeric')->add_rules('field_name', 'required', 'length[1,1000]')->add_rules('field_required', 'required', 'between[0,1]')->add_rules('field_ispublic_visible', 'required', 'numeric')->add_rules('field_ispublic_submit', 'required', 'numeric'); // Get the field type $array->field_isdate = $array->field_type == 3 ? 1 : 0; // Ensure that checkboxes and radio buttons have a default value if ($array->field_type == 5 or $array->field_type == 6 or $array->field_type == 7) { $array->add_rules('field_default', 'required', 'standard_text'); } // Check if field width and height have been specified if (!empty($array->field_width)) { $array->add_rules('field_width', 'between[0,300]'); } if (!empty($array->field_height)) { $array->add_rules('field_height', 'between[0,50]'); } if (!empty($array->field_default)) { $array->add_rules('field_default', 'length[1,10000]'); } // If date field, and default value is not empty, add date validation rules if (!empty($array->field_default) and !empty($array->field_isdate)) { $array->add_rules('field_default', array('valid', 'date_mmddyyyy')); } // Return return parent::validate($array, $save); }
/** * Validates and optionally saves a new level record from an array * * @param array $array Values to check * @param save $save Saves the level record when validation succeeds * @return bool */ public function validate(array &$array, $save = FALSE) { // Setup validation $array = Validation::factory($array)->pre_filter('trim')->add_rules('level_title', 'required', 'length[3,80]')->add_rules('level_description', 'required')->add_rules('level_weight', 'required'); // Pass validation to parent and return return parent::validate($array, $save); }
/** * Basic */ public function action_edit() { $this->title = __('settings.settings_general'); // Fields for save $for_extract = ['per_page_frontend', 'per_page_backend', 'sitename', 'siteslogan', 'copyright', 'year_creation_site', 'type_backend_menu']; $config = Config::get('settings'); $data = Arr::extract($_POST, $for_extract); if ($this->request->is_post()) { $data = Validation::factory(array_map('trim', $data))->rules('per_page_frontend', [['not_empty'], ['digit']])->rules('per_page_backend', [['not_empty'], ['digit']])->rules('year_creation_site', [['not_empty'], ['digit']])->rule('sitename', 'not_empty'); if ($data->check()) { foreach ($for_extract as $field) { $config[$field] = $data[$field]; } $config->save(); Message::success(__('settings.changes_saved')); HTTP::redirect(Route::url('b_settings')); } else { Message::error(__('settings.error_saving')); $errors = $data->errors('validation'); } } else { $data = $config; } $this->content = View::factory($this->view, ['data' => $data])->bind('errors', $errors); }
public function validator($data, $validate_file = TRUE) { $validator = Validation::factory($data)->rule('title', 'not_empty')->rule('role', 'not_empty'); if ($validate_file) { $validator->rules('name', array(array('Upload::not_empty', NULL), array('Upload::valid', NULL), array('Upload::size', array(':value', '5M')), array('Upload::type', array(':value', array('jpg', 'png', 'gif', 'jpeg', 'pdf', 'doc', 'odt', 'txt', 'xls', 'rtf', 'bmp', 'ppt', 'docx', 'pptx'))))); } return $validator; }