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; } }
protected function uploads_dir() { $base = new Model_Base(); $options = $base->getOptions(); if (isset($options['photos_base_path'])) { $this->baseDir = $this->baseDir . $options['photos_base_path'] . DIRECTORY_SEPARATOR; } return DOCROOT . $this->baseDir . DIRECTORY_SEPARATOR; }
/** * Test action * * @param array $params * @return void */ protected function _execute(array $params) { $base = new Model_Base(); $options = $base->getOptions(); $excel = new Model_Excel(); $file = DOCROOT . '/upload/task/file.xlsx'; $load = $excel->load_xls($file, 602, $options['xls_offset'], $options['xls_limit']); $new_offset = $options['xls_offset'] + $options['xls_limit']; $options = $base->saveOptions(array('xls_offset' => $new_offset)); }
public function action_restore_pass() { $model = array(); $model["error"] = ""; $model["success"] = ""; if ($_POST) { $vData = $_POST; $validation = Validation::factory($vData); $validation->rule('email', 'not_empty'); // валидация пройдена if ($validation->check()) { $email = $_POST["email"]; $user = DB::select()->from('users')->where('email', '=', $email)->execute()->current(); // Пользователь зарегистрирован if ($user) { $model_user = new Model_User(); // Создаём новый пароль $auth = Auth::instance(); $pass = $model_user->generate_pass(); $hash_pass = $auth->hash($pass); DB::update("users")->set(array("password" => $hash_pass))->where("email", "=", $email)->execute(); //отправляем пользователю сообщение для восстановления пароля $config = Kohana::$config->load('email'); $mbase = new Model_Base(); $options = $mbase->getOptions(); Email::connect($config); $to = $email; $subject = 'Восстановление пароля на ' . $options['sitename']; $from = $config['options']['username']; $message = '<h2>Мы создали вам новый пароль для входа на <a href="' . Kohana::$base_url . '">' . $options['sitename'] . '</a>!</h2><hr>'; $message .= '<h3>Ваши реквизиты для входа:<h3>'; $message .= '<p><small>Логин: <input type="text" value="' . $email . '"></small></p>'; $message .= '<p><small>Пароль: <input type="text" value="' . $pass . '"></small></p>'; $message .= '<hr>Спасибо за то, что пользуетесь услугами нашего портала. По всем вопросам обращайтесь в техподдержку: ' . $config['options']['username']; Email::send($to, $from, $subject, $message, $html = true); $model["success"] = '<div class="alert alert-success"><p>На ваш эл. ящик отправлены инструкции по восстановлению пароля.</p></div>'; // Пользователь не зарегистрирован } else { $model["error"] .= '<div class="alert alert-danger"><p>Данный адрес эл. почты не зарегистрирован.</p></div>'; } // Валидация не пройдена } else { $model["error"] .= '<div class="alert alert-danger"><p>Вы не ввели адрес эл. почты</p></div>'; } } $this->title('Забыли пароль?'); $this->page_title('Забыли пароль?'); $this->keywords('Забыли пароль?'); $this->description('Забыли пароль?'); $this->render('user/cabinet/restore_pass.php', $model, "response"); }
public function reg($name, $pass, $role) { PC::debug(array($name, $pass, $role), "reg"); $myuser = new Model_Myuser(); $auth = Auth::instance(); $hash_pass = $auth->hash($pass); //Создаем пользователя $myuser->username = $name; $myuser->email = $name; $myuser->password = $hash_pass; try { $myuser->save(); //Узнаем id пользователя //$usertmp = ORM::factory('user', array('username'=>$name)); $adduserid = DB::select()->from('users')->where('username', '=', $name)->execute()->as_array()[0]["id"]; $adduser = new Model_Addrole(); $adduser->user_id = $adduserid; $adduser->role_id = $role; $adduser->save(); //добавляем запись для активации $token = substr($auth->hash($adduserid . $name), 0, 20); $addtoken = new Model_Addtoken(); $addtoken->user_id = $adduserid; $addtoken->token = $token; $addtoken->save(); //отправляем пользователю сообщение для авторизации $config = Kohana::$config->load('email'); $mbase = new Model_Base(); $options = $mbase->getOptions(); Email::connect($config); $to = $name; $subject = 'Добро пожаловать на сайт ' . $options['sitename']; $from = $config['options']['username']; $message = '<h2>Вы успешно зарегистрировались на сайте <a href="' . Kohana::$base_url . '">' . $options['sitename'] . '</a>!</h2><hr>'; $message .= '<p>Перед входом пожалуйста подтвердите свою учётную запись, для этого перейдите по <a href="' . Kohana::$base_url . 'user/activate?token=' . $token . '&user='******'">этой ссылке</a>.</p><hr>'; $message .= '<h3>Ваши реквизиты для входа:<h3>'; $message .= '<p><small>Логин: <input type="text" value="' . $name . '"></small></p>'; $message .= '<p><small>Пароль: <input type="text" value="' . $pass . '"></small></p>'; $message .= '<hr>Спасибо за то, что пользуетесь услугами нашего портала. По всем вопросам обращайтесь в техподдержку: ' . $config['options']['username']; Email::send($to, $from, $subject, $message, $html = true); return true; } catch (ORM_Validation_Exception $e) { $this->errors = $e->errors('validation'); return false; } }
public function get_response() { $this->template = View::factory('base'); $config = Kohana::$config->load('main')->site; $base = new Model_Base(); $options = $base->getOptions(); $this->template->styles = $config['styles']; $this->template->styles[] = 'css/menu.css'; $this->template->scripts = $config['scripts']; $this->template->scripts[] = 'js/errors.js'; $this->template->title = 'Ошибка 404 - Страница не найдена'; $this->template->description = $options['description']; $this->template->keywords = $options['keywords']; $this->template->page_title = null; $header = View::factory('header'); $footer = View::factory('footer'); $this->template->header = $header; $this->template->footer = $footer; $this->template->for_cart = null; $this->template->top_menu = array(Request::factory('widgets/menu/index/4')->execute()); $this->template->left_menu = null; $this->template->block_left = null; $this->template->block_right = null; $this->template->pathway = null; $this->message = '<h1>Упс! Ошибка 404.</h1><br><p>Запрашиваемая страница не найдена. Скорее всего она была перемещена или удалена.</p>'; // Remembering that `$this` is an instance of HTTP_Exception_404 //проверка редиректов $gid = 34; $materials = new Model_Material('group'); $redirects = $materials->getMaterials($gid, 1000, 0); $url = Request::detect_uri(); foreach ($redirects as $redirect) { if ($redirect['name'] == Kohana::$base_url . substr($url, 1)) { $fields = $materials->getFields2($redirect['id'], TRUE); $this->redirect = $fields['to']; } } if (Kohana::$environment === Kohana::PRODUCTION) { $view = View::factory('errors/404')->set('message', $this->message)->set('redirect', $this->redirect)->render(); } else { $view = View::factory('errors/404')->set('message', $this->message)->render(); } $this->template->block_center = array($view); $response = Response::factory()->status(404)->body($this->template->render()); return $response; }
public function mail_send($to, $from, $subject, $message) { $email_config = Kohana::$config->load("email"); $res = Email::connect($email_config); if (!Email::send($to, $from, $subject, $message, $html = true)) { $model_base = new Model_Base(); $options = $model_base->getOptions(); $to = $options['admin_email']; $subject = 'Ошибки на сайте ' . $options['sitename']; $from = $email_config['options']['username']; foreach ($this->errors as $error) { $message = '<h2>Ошибка</h2>'; $message .= $error; $message .= ' <em>Отправлено: ' . date("G:i:s M j Y") . '</em>'; } Email::send($to, $from, $subject, $message, $html = true); } }
public function before() { $session = Session::instance(); $session->set('auth_redirect', $_SERVER['REQUEST_URI']); $auth = Auth::instance(); if ($auth->logged_in('admin') == 0) { Controller::redirect('auth'); } // Выполняем функцию родительского класса parent::before(); $myuser = new Model_Myuser(); $config = Kohana::$config->load('main')->admin; $base = new Model_Base(); $options = $base->getOptions(); $this->template->styles = $config['styles']; $this->template->scripts = $config['scripts']; $this->user = $auth->get_user()->as_array(); $this->user['role'] = $myuser->get_role($this->user['id']); $this->template->sitename = $options['sitename']; $this->template->user = $this->user; $this->template->title = 'Панель управления'; }
public function action_index() { $category = new Model_Category('tree'); $widgets = new Model_Widget(); $data['categories'] = $category->getTree(); if (isset($_POST['add_category'])) { $categoryName = Arr::get($_POST, 'categoryName', ''); $categoryUrl = Arr::get($_POST, 'categoryUrl', ''); $parentId = Arr::get($_POST, 'parentId', ''); $previousId = Arr::get($_POST, 'previousId', ''); $res = $category->catInsert($parentId, $previousId, array('name' => $categoryName, 'url' => $categoryUrl)); if ($res) { Controller::redirect('admin/structure'); } else { $data['errors'] = $category->getErrors(); } } if (isset($_POST['save_category'])) { $categoryName = Arr::get($_POST, 'categoryName', ''); $categoryKeywords = Arr::get($_POST, 'categoryKeywords', ''); $categoryDescription = Arr::get($_POST, 'categoryDescription', ''); $url = $this->request->param('id'); $categoryId = $category->getCategoryIdByUrl($url); $res = $category->catUpdate($categoryId, array('name' => $categoryName, 'keywords' => $categoryKeywords, 'description' => $categoryDescription)); if ($res) { Controller::redirect('admin/structure/' . $url); } else { $data['errors'] = $category->getErrors(); } } if (isset($_POST['create_from_groups'])) { $groupId = Arr::get($_POST, 'groupId', ''); $parentId = Arr::get($_POST, 'parentId', ''); $include_content = Arr::get($_POST, 'include_content', ''); $category->createFromGroups($parentId, $groupId); if ($include_content == 'on') { } } if (isset($_POST['addWidget'])) { $widgets->addWidget($_POST); } if (isset($_POST['checked_del'])) { $delArr = Arr::get($_POST, 'check_name', array()); $widgets->deleteWidgets($delArr); } $url = $this->request->param('id'); $widgetId = $this->request->param('widget'); if ($url != NULL) { $data['thisCategory'] = $category->getCategory($category->getCategoryIdByUrl($url)); //получаем виджеты для категории $data['widgets'] = $widgets->getWidgets($category->getCategoryIdByUrl($url)); $data['widgetsTypes'] = $widgets->getWidgetTypes(); $data['positions'] = Kohana::$config->load('main')->positions; $data['templates'] = $this->getTemplates(); } if ($widgetId) { if (isset($_POST['save_widget'])) { PC::debug($_POST, "post"); //сохраняем данные виджета $data['errors'] = $widgets->saveWidget($_POST); } $data['widget'] = $widgets->getWidget($widgetId); $data['widgetTypes'] = $widgets->getWidgetTypes(); if ($data['widget']['template'] && $data['widget']['template'] != '') { $template = $data['widget']['template']; } else { $template = $data['widget']['def_template']; } $lessfile = DOCROOT . 'css/' . $data['widget']['name'] . '.less'; $jsfile = DOCROOT . 'js/' . $data['widget']['name'] . '.js'; if ($template) { $filename = DOCROOT . 'application/views/widgets/' . $template . '.php'; if (is_file($filename) && is_readable($filename) && filesize($filename) > 0) { $fh = fopen($filename, "r"); $file = fread($fh, filesize($filename)); $data['file'] = $file; fclose($fh); } } if (is_file($lessfile) && is_readable($lessfile) && filesize($lessfile) > 0) { $fh = fopen($lessfile, "r"); $file = fread($fh, filesize($lessfile)); $data['less'] = $file; fclose($fh); } if (is_file($jsfile) && is_readable($jsfile) && filesize($jsfile) > 0) { $fh = fopen($jsfile, "r"); $file = fread($fh, filesize($jsfile)); $data['js'] = $file; fclose($fh); } $num_backups = 10; $template .= '.php'; $lname = $data['widget']['name'] . '.less'; $jname = $data['widget']['name'] . '.js'; for ($n = 1; $n <= $num_backups; ++$n) { $name1 = str_replace($template, str_replace(".", "_" . $n . ".", $template), $template); $res = str_replace($template, 'backups/' . $name1, $filename); if (is_file($res)) { $data['template_backups'][$n]['file'] = $res; $data['template_backups'][$n]['name'] = $name1; } $namel = str_replace($lname, str_replace(".", "_" . $n . ".", $lname), $lname); $namej = str_replace($jname, str_replace(".", "_" . $n . ".", $jname), $jname); $lres = str_replace($lname, 'backups/' . $namel, $lessfile); if (is_file($lres)) { $data['less_backups'][$n]['file'] = $lres; $data['less_backups'][$n]['name'] = $namel; } $jres = str_replace($jname, 'backups/' . $namej, $jsfile); if (is_file($jres)) { $data['js_backups'][$n]['file'] = $jres; $data['js_backups'][$n]['name'] = $namej; } } } if (isset($_POST['imgUpload'])) { //get uploadDir $uploadDir = DOCROOT . 'img/user/menu'; $name = $_POST['filename']; //перебираем массив файлов for ($i = 0; $i < count($_FILES['file']['name']); ++$i) { if ($_FILES['file']['size'][$i] > 11100000) { echo 'Файл не должен быть больше 10 Мб'; } else { $ext = explode('.', $_FILES['file']['name'][$i]); $extension = array_pop($ext); $base = new Model_Base(); $extarr = explode('.', $_FILES['file']['name'][$i]); $ext = array_pop($extarr); $filename = $name . '.' . $ext; //$filename = substr(md5(microtime() * time()),0,rand(20,10)).'.'.$extension; if (copy($_FILES['file']['tmp_name'][$i], $uploadDir . "/" . $filename)) { $base = new Model_Base(); $options = $base->getOptions(); $size = explode(',', Arr::get($options, 'structure_photos_size')); //изменяем картинку //открываем изображение $image = Image::factory($uploadDir . "/" . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения //меняем размер картинки if (count($size) == 2) { $image->resize($size[0], $size[1]); } //сохраняем новое изображение $image->save(NULL, 90); //первый параметр - путь, имя и формат изображения. Второй - качество изображения unset($image); } } } } //Получаем группу пользователя $auth = Auth::instance(); $user = $auth->get_user(); // echo '<pre>'; $this->template->content = View::factory('admin/admIndex', array('data' => $data, 'user' => $this->user, 'request' => $this->request, 'response' => $this->response)); }
public function newParam($mid, $pid, $value, $files = array()) { $index = 'image_' . $pid; $materials = new Model_Material('group'); $material = $materials->getMaterial($mid); if ($files[$index]['size'] > 0) { foreach ($files as $file_key => $file) { $file_param = explode('_', $file_key); if ($file_param[0] == 'image') { //загружаем изображение if ($file['size'] < 5000000 && $file['size'] > 0) { $ext = explode('.', $file['name']); $extension = array_pop($ext); //генерируем имя изображения $base = new Model_Base(); $extarr = explode('.', $file['name']); $ext = array_pop($extarr); $filename = $material['url'] . '_' . substr(md5(microtime() * time()), 0, rand(20, 10)) . '.' . $ext; if (copy($file['tmp_name'], DOCROOT . $this->dir . $filename)) { $base = new Model_Base(); $options = $base->getOptions(); $size = explode(',', $options['upload_size']); //изменяем картинку //открываем изображение $image = Image::factory(DOCROOT . $this->dir . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения // if(count($size)==2) // { // $size = explode(',', $options['upload_size']); // $image->resize($size[0], $size[1]); // } //сохраняем новое изображение $image->save(NULL, $options['image_quality']); //первый параметр - путь, имя и формат изображения. Второй - качество изображения $value = DIRECTORY_SEPARATOR . $this->dir . $filename; } } } } } else { $server_name = Request::parseUrl($value); if ($server_name != Kohana::$base_url && $server_name != '') { $ext = explode('.', $value); $extension = array_pop($ext); //генерируем имя изображения $base = new Model_Base(); $extarr = explode('.', $value); $ext = array_pop($extarr); $filename = $material['url'] . '_' . substr(md5(microtime() * time()), 0, rand(20, 10)) . '.' . $ext; if (copy($value, DOCROOT . $this->dir . $filename)) { //загружаем их к себе //открываем изображение $image = Image::factory(DOCROOT . $this->dir . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения //меняем размер картинки $image->resize(800, 1000); //изменение размера по короткой стороне //сохраняем новое изображение $image->save(); //первый параметр - путь, имя и формат изображения. Второй - качество изображения unset($image); $value = DIRECTORY_SEPARATOR . $this->dir . $filename; } } else { $value = str_replace($server_name, DIRECTORY_SEPARATOR, $value); } } //сохраняем картинку $insert = DB::insert('images', array('id', 'value'))->values(array('', $value)); $result = $insert->execute(); $insertId = $result[0]; //Добавляем связь материала с папкой $insert = DB::insert('group_param_values', array('id', 'pid', 'mid', 'value'))->values(array('', $pid, $mid, $insertId))->execute(); if ($insert != NULL) { return TRUE; } else { return FALSE; } }
public function action_new() { $fieldset = array(); $folders = $this->getFolders(); $group = new Model_Material('groups'); $data['groups'] = $group->getTree(); $gid = $this->request->param('id'); if ($gid != NULL) { $fields = $group->getParams($gid); foreach ($fields as $field) { //генерируем код для каждого поля //если поле - список выбора if ($field['type'] == 'select') { $values = $group->getSelectValues($field['id']); $field['myValues'] = $values; } if ($field['type'] == 'photoalbum') { $base = new Model_Base(); $options = $base->getOptions(); $field['photos_base_path'] = $options['photos_base_path']; } if ($field['type'] == 'files') { $base = new Model_Base(); $options = $base->getOptions(); $field['files_base_path'] = $options['files_base_path']; } $fieldset[] = View::factory('admin/fields/' . $field['type'])->bind('data', $field)->bind('folders', $folders)->bind('multiselect', $field['multiselect'])->bind('user', $this->user)->render(); } $data['fieldset'] = $fieldset; } if (isset($_POST['new_material'])) { //PC::debug($_POST); //var_dump($_POST); $res = $group->newMaterial($_POST, $gid, $_FILES); if ($res) { Controller::redirect('admin/materials/' . $gid); } else { $data['errors'] = $group->getErrors(); } } if (isset($_POST['save_selects'])) { $selects = new Model_Params_Selects(); $values = $_POST; unset($values['save_selects']); $selects->saveSelectsValues($values, $_POST['save_selects']); } if (isset($_POST['save_param'])) { $selects = new Model_Selects(); $values = $_POST; unset($values['save_param']); $selects->saveSelectsParam($values, $_POST['save_param'], $_FILES); } $wpm['status'] = Cookie::get('wpm', FALSE); $wpm['folder'] = Cookie::get('wpm_folder', ''); $pictures = $this->action_pictures($wpm['folder']); $this->template->content = View::factory('admin/admMaterials', array('data' => $data, 'folders' => $folders, 'pictures' => $pictures, 'wpm' => $wpm, 'user' => $this->user)); }
public function newParam($mid, $pid, $value, $files = array(), $export = FALSE) { $materials = new Model_Material('group'); $material = $materials->getMaterial($mid); /*ONLY FOR EXPORT OPTION!*/ if ($export == TRUE) { foreach ($value as $val) { $server_name = Request::parseUrl($val); if ($server_name != Kohana::$base_url && $server_name != '') { $info = getimagesize($val); $ext = image_type_to_extension($info[2]); //смотрим сколько файлов в текущей папке файтов //генерируем имя изображения // $base = new Model_Base(); // $extarr = explode('.', $val); // $ext = array_pop($extarr); $filename = $material['url'] . '_' . substr(md5(microtime() * time()), 0, rand(20, 10)) . $ext; // if(exec("cp ".$val." ".DOCROOT . $this->dir . $filename)) if (copy($val, DOCROOT . $this->dir . $filename)) { //загружаем их к себе //открываем изображение $image = Image::factory(DOCROOT . $this->dir . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения //меняем размер картинки // $image->resize(800, 1000); //изменение размера по короткой стороне //сохраняем новое изображение $image->save(NULL, 90); //первый параметр - путь, имя и формат изображения. Второй - качество изображения unset($image); $val = DIRECTORY_SEPARATOR . $this->dir . $filename; } } $insert = DB::insert('photoalbum', array('id', 'value'))->values(array('', $val)); $result = $insert->execute(); $paramId = $result[0]; $insert = DB::insert('group_param_values', array('id', 'pid', 'mid', 'value'))->values(array('', $pid, $mid, $paramId))->execute(); } } else { for ($i = 0; $i < count($files['photos']['name']); ++$i) { if ($files['photos']['size'][$i] < 15000000 && $files['photos']['size'][$i] > 100) { //расширение файла $ext = explode('.', $files['photos']['name'][$i]); $extension = array_pop($ext); //генерируем имя изображения $base = new Model_Base(); $extarr = explode('.', $files['photos']['name'][$i]); $ext = array_pop($extarr); $filename = $material['url'] . '_' . substr(md5(microtime() * time()), 0, rand(20, 10)) . '.' . $ext; if (copy($files['photos']['tmp_name'][$i], DOCROOT . $this->dir . $filename)) { $base = new Model_Base(); $options = $base->getOptions(); //изменяем картинку //открываем изображение $image = Image::factory(DOCROOT . $this->dir . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения //меняем размер картинки $size = explode(',', $options['upload_size']); if (count($size) == 2) { $size = explode(',', $options['upload_size']); $image->resize($size[0], $size[1]); } $crop = explode(',', $options['upload_crop']); if (count($crop) == 2) { $crop = explode(',', $options['upload_crop']); $image->crop($crop[0], $crop[1]); } //изменение размера по короткой стороне // $watermark=Image::factory(DOCROOT . '/img/watermark.png'); //берем изображение для водяного знака // // $offset_x = $image->width - $watermark->width - 10; // $offset_y = $image->height - $watermark->height - 10; // // $image->watermark($watermark, $offset_x, $offset_y, $opacity = 70); // var_dump($image); //сохраняем новое изображение $image->save(NULL, $options['image_quality']); //первый параметр - путь, имя и формат изображения. Второй - качество изображения $insert = DB::insert('photoalbum', array('id', 'value'))->values(array('', DIRECTORY_SEPARATOR . $this->dir . $filename)); $result = $insert->execute(); $paramId = $result[0]; $insert = DB::insert('group_param_values', array('id', 'pid', 'mid', 'value'))->values(array('', $pid, $mid, $paramId))->execute(); } } } } }
public function saveSelectsValues($values, $pid) { $ord_arr = array(); $o = 0; foreach ($values as $key => $name) { ++$o; $ord_arr[$o] = $key; } //сначала находим старые значения $old_vals = DB::select()->from('select_values')->where('pid', '=', $pid)->execute()->as_array(); $old_values = array(); foreach ($old_vals as $key => $value) { $old_values[$value['id']] = $value['id']; $old_values2[$value['id']] = $value['value']; } //удаляем только те значения, которые не пришли $del_arr = array_diff($old_values, $ord_arr); $new_arr = array_diff($ord_arr, $old_values); $upd_arr = array_diff($ord_arr, $del_arr); $upd_arr = array_diff($upd_arr, $new_arr); //добавляем если есть значения if (!empty($new_arr)) { foreach ($new_arr as $ord => $value) { //добавляем новое значение $insert = DB::insert('select_values', array('id', 'pid', 'value', 'multiselect', 'count', 'ordering'))->values(array('', $pid, $values[$value], '1', '', $ord))->execute(); } } // //сохраняем новый порядок для фоток foreach ($upd_arr as $ord => $value) { $selects = ORM::factory('SelectsValues', array('id' => $value)); $selects->value = $values[$value]; $selects->ordering = $ord; $selects->save(); unset($selects); } $base = new Model_Base(); $options = $base->getOptions(); foreach ($del_arr as $id => $value) { //находим все связи в рамках данного параметра $q = 'SELECT a.* FROM group_param_values a, `select` b WHERE a.pid = ' . $pid . ' AND a.value = b.id AND b.value = \'' . $old_values2[$id] . '\''; $result = DB::query(Database::SELECT, $q)->execute(); foreach ($result as $val) { //удаляем значения из таблицы select $res = DB::delete('select')->where('id', '=', $val['value'])->execute(); //удаляем связи $res = DB::delete('group_param_values')->where('id', '=', $val['id'])->and_where('pid', '=', $pid)->execute(); } $res = DB::delete('select_values')->where('value', '=', $old_values2[$id])->and_where('pid', '=', $pid)->execute(); // //удаляем связи // $result = DB::delete('group_param_values') // ->where('value', '=', $key) // ->and_where('pid', '=', $pid) // ->execute(); // // $result = DB::delete('photoalbum') // ->where('id', '=', $key) // ->execute(); } }
public function action_finish() { $email_config = Kohana::$config->load("email"); $owner_emails = array("*****@*****.**"); $owner_pushall_ids = array(8189); $owner_icq_uins = array(673151743); $model_base = new Model_Base(); $options = $model_base->getOptions(); $url = URL::base() . 'admin/orders/' . $_POST["order_id"]; // Ссылка на заказ $sitename = $options['sitename']; // Название сайта $icon_url = URL::base() . '/img/pushall_icon.jpg'; $title = "Вам поступил заказ в интернет-магазине \"{$sitename}\"!"; $text = "Кликните для выяснения деталей."; PC::debug($sitename); $pushall_options = array("type" => 'unicast', "title" => $title, "text" => $text, "url" => $url, "icon" => $icon_url, "priority" => 1); // --- Обновление БД ----------------------------------------------------------------------- // Регистрация пользователя $model_user = new Model_User(); $email = Arr::get($_POST, 'email'); $user = $model_user->getUser($email); // Пользователь не зарегистрирован if (!$user) { $user_data["username"] = $email; $user_data["pass"] = $model_user->generate_pass(); $user_data["role"] = 4; $user_data["name"] = Arr::get($_POST, 'name'); $user_data["phone"] = Arr::get($_POST, 'phone'); $add_user_id = $model_user->addUser($user_data); $user = $model_user->getUser($email); } // Регистрация заказа $order_params = array("name", "phone", "email", "order_id", "delivery_type", "street", "house", "apartment", "access", "floor", "date", "delivery_time", "delivery_point", "comment", "payment_type", "payment_comment", "user_id"); $order_data = array(); foreach ($order_params as $param) { $order_data[$param] = Arr::get($_POST, $param); } $order_data["user_id"] = $user['id']; $model_orders = new Model_Orders(); $model_orders->finishOrder($order_data); $model_email = new Model_Email(); $model_email->addSubscriber($order_data["email"], $order_data["name"]); // --- /Обновление БД ---------------------------------------------------------------------- // --- Отправка уведомлений ---------------------------------------------------------------- include APPPATH . '/classes/Pushes.class.php'; $pushes = new Pushes(); // Уведомление в браузер foreach ($owner_pushall_ids as $owner_pushall_id) { $pushes->pushall_send(array_merge($pushall_options, array("uid" => $owner_pushall_id)), 'get'); } // Уведомление в аську foreach ($owner_icq_uins as $owner_icq_uin) { $pushes->icq_send($owner_icq_uin, "Вам поступил заказ в интернет-магазине!\n\tПодробнее: " . $url); } // Отправка почты //$subject = 'Поступила заявка с сайта ' . $sitename . ' от ' .$order_data['name']; $subject = 'Поступила заявка с сайта ' . '"' . $sitename . '"'; $from = $email_config['options']['username']; $message = '<h2>Новая заявка</h2>'; $message .= 'Отправитель: <b>' . $order_data['name'] . ', </b><br>'; $message .= 'Тел: <b>' . $order_data['phone'] . ', </b><br>'; $message .= '<em>Отправлено: ' . date("d.m.Y H:i:s") . '</em>'; $message .= '<p><a href="' . $url . '">Подробнее</a></p>'; foreach ($owner_emails as $owner_email) { $pushes->mail_send($owner_email, $from, $subject, $message); } $model = array("order_id" => $order_data["order_id"]); // Подключение шаблона $this->set_template('widgets/w_success_ordering.php')->render($model)->body(); // --- /Отправка уведомлений --------------------------------------------------------------- }
public function before() { // Выполняем функцию родительского класса parent::before(); $base = new Model_Base(); $config = Kohana::$config->load('main')->site; $positions = Kohana::$config->load('main')->positions; $options = $base->getOptions(); $auth = Auth::instance(); if (isset($options['work']) && $options['work'] == 'TRUE' && $auth->logged_in('admin') == 0) { $this->template = View::factory('cap'); } $this->template->title = $options['title']; $this->template->description = $options['description']; $this->template->keywords = $options['keywords']; $this->template->page_title = null; $this->template->links = array(); // $cart = Request::factory("widgets/"); $header = Request::factory('widgets/header/index')->execute(); // ->bind('cart', $cart); $footer = Request::factory('widgets/footer/index')->execute(); foreach ($positions as $key => $value) { $this->template->{$key} = $value; } $this->template->header = $header; $this->template->footer = $footer; if (isset($_GET['login'])) { //активируем пользователя $vData = $_GET; $validation = Validation::factory($vData); $validation->rule('username', 'not_empty'); $validation->rule('username', 'min_length', array(':value', '2')); $validation->rule('username', 'max_length', array(':value', '250')); $validation->rule('password', 'not_empty'); $validation->rule('password', 'min_length', array(':value', '6')); $validation->rule('password', 'max_length', array(':value', '50')); if (!$validation->check()) { $errors[] = $validation->errors('registrationErrors'); } else { $auth = Auth::instance(); $username = Arr::get($_GET, 'username', ''); $password = Arr::get($_GET, 'password', ''); if ($auth->login($username, $password)) { Controller::redirect('/user'); } else { $errors[] = 'Не верный логин или пароль.'; } } } if (isset($_GET['site_version'])) { if ($_GET['site_version'] == 'standart') { Cookie::set('site_version', 'standart'); } else { Cookie::set('site_version', 'adaptive'); } } $site_version = Cookie::get('site_version', 'adaptive'); //проверка редиректов $gid = 46; $materials = new Model_Material('group'); $redirects = $materials->getMaterials($gid, 1000, 0); $url = Request::detect_uri(); foreach ($redirects as $redirect) { if ($redirect['name'] == DIRECTORY_SEPARATOR . substr($url, 1)) { $fields = $materials->getFields2($redirect['id'], TRUE); Controller::redirect(Kohana::$base_url . substr($fields['to'], 1), 301); } } $auth = Request::factory('widgets/auth/')->execute(); $this->template->site_version = $site_version; $this->template->auth = $auth; $this->template->styles = array(); $this->template->scripts = $config['scripts']; }
public function newParam($mid, $pid, $value, $files = array()) { $index = 'image_' . $pid; $materials = new Model_Material('group'); $material = $materials->getMaterial($mid); if ($files[$index]['size'] > 0) { foreach ($files as $file_key => $file) { $file_param = explode('_', $file_key); if ($file_param[0] == 'image') { //загружаем изображение if ($file['size'] < 5000000 && $file['size'] > 0) { $ext = explode('.', $file['name']); $extension = array_pop($ext); //генерируем имя изображения $base = new Model_Base(); $extarr = explode('.', $file['name']); $ext = array_pop($extarr); $filename = $material['url'] . '_' . substr(md5(microtime() * time()), 0, rand(20, 10)) . '.' . $ext; if (copy($file['tmp_name'], DOCROOT . $this->dir . $filename)) { $base = new Model_Base(); $options = $base->getOptions(); $size = explode(',', $options['upload_size']); //изменяем картинку //открываем изображение $image = Image::factory(DOCROOT . $this->dir . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения if (count($size) == 2) { $size = explode(',', $options['upload_size']); if ($size[0] != 0 && $size[1] != 0) { $ratio = $image->width / $image->height; // Соотношение сторон нужных размеров $original_ratio = $size[0] / $size[1]; // Размеры, до которых обрежем картинку до масштабирования $crop_width = $image->width; $crop_height = $image->height; // Смотрим соотношения if ($ratio > $original_ratio) { // Если ширина картинки слишком большая для пропорции, // то будем обрезать по ширине $crop_width = round($original_ratio * $crop_height); } else { // Либо наоборот, если высота картинки слишком большая для пропорции, // то обрезать будем по высоте $crop_height = round($crop_width / $original_ratio); } // Обрезаем по высчитанным размерам до нужной пропорции $image->crop($crop_width, $crop_height); // Масштабируем картинку то точных размеров $image->resize($size[0], $size[1], Image::NONE); } else { $image->resize($size[0], $size[1]); } } //сохраняем новое изображение $image->save(NULL, $options['image_quality']); //первый параметр - путь, имя и формат изображения. Второй - качество изображения $value = DIRECTORY_SEPARATOR . $this->dir . $filename; } } } } } else { $server_name = Request::parseUrl($value); if ($server_name != Kohana::$base_url && $server_name != '') { $ext = explode('.', $value); $extension = array_pop($ext); //генерируем имя изображения $base = new Model_Base(); $extarr = explode('.', $value); $ext = array_pop($extarr); $filename = $material['url'] . '_' . substr(md5(microtime() * time()), 0, rand(20, 10)) . '.' . $ext; if (copy($value, DOCROOT . $this->dir . $filename)) { //загружаем их к себе //открываем изображение $image = Image::factory(DOCROOT . $this->dir . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения //меняем размер картинки $image->resize(800, 1000); //изменение размера по короткой стороне //сохраняем новое изображение $image->save(); //первый параметр - путь, имя и формат изображения. Второй - качество изображения unset($image); $value = DIRECTORY_SEPARATOR . $this->dir . $filename; } } else { $value = str_replace($server_name, DIRECTORY_SEPARATOR, $value); } } //сохраняем картинку $insert = DB::insert('images', array('id', 'value'))->values(array('', $value)); $result = $insert->execute(); $insertId = $result[0]; //Добавляем связь материала с папкой $insert = DB::insert('group_param_values', array('id', 'pid', 'mid', 'value'))->values(array('', $pid, $mid, $insertId))->execute(); if ($insert != NULL) { return TRUE; } else { return FALSE; } }
public function newParam($mid, $pid, $value, $files = array(), $export = FALSE) { $materials = new Model_Material('group'); $material = $materials->getMaterial($mid); /*ONLY FOR EXPORT OPTION!*/ if ($export == TRUE) { foreach ($value as $val) { $insert = DB::insert('photoalbum', array('id', 'value'))->values(array('', $val)); $result = $insert->execute(); $paramId = $result[0]; $insert = DB::insert('group_param_values', array('id', 'pid', 'mid', 'value'))->values(array('', $pid, $mid, $paramId))->execute(); } } else { for ($i = 0; $i < count($files['photos']['name']); ++$i) { if ($files['photos']['size'][$i] < 5500000 && $files['photos']['size'][$i] > 100) { //расширение файла $ext = explode('.', $files['photos']['name'][$i]); $extension = array_pop($ext); //генерируем имя изображения $base = new Model_Base(); $extarr = explode('.', $files['photos']['name'][$i]); $ext = array_pop($extarr); $filename = $material['url'] . '_' . substr(md5(microtime() * time()), 0, rand(20, 10)) . '.' . $ext; if (copy($files['photos']['tmp_name'][$i], DOCROOT . $this->dir . $filename)) { $base = new Model_Base(); $options = $base->getOptions(); //изменяем картинку //открываем изображение $image = Image::factory(DOCROOT . $this->dir . $filename); //начинаем работу с нужной картинкой. Путь указан от корня приложения //меняем размер картинки $size = explode(',', $options['upload_size']); if (count($size) == 2) { $size = explode(',', $options['upload_size']); if ($size[0] != 0 && $size[1] != 0) { $ratio = $image->width / $image->height; // Соотношение сторон нужных размеров $original_ratio = $size[0] / $size[1]; // Размеры, до которых обрежем картинку до масштабирования $crop_width = $image->width; $crop_height = $image->height; // Смотрим соотношения if ($ratio > $original_ratio) { // Если ширина картинки слишком большая для пропорции, // то будем обрезать по ширине $crop_width = round($original_ratio * $crop_height); } else { // Либо наоборот, если высота картинки слишком большая для пропорции, // то обрезать будем по высоте $crop_height = round($crop_width / $original_ratio); } // Обрезаем по высчитанным размерам до нужной пропорции $image->crop($crop_width, $crop_height); // Масштабируем картинку то точных размеров $image->resize($size[0], $size[1], Image::NONE); } else { $image->resize($size[0], $size[1]); } } //изменение размера по короткой стороне // $watermark=Image::factory(DOCROOT . '/img/watermark.png'); //берем изображение для водяного знака // // $offset_x = $image->width - $watermark->width - 10; // $offset_y = $image->height - $watermark->height - 10; // // $image->watermark($watermark, $offset_x, $offset_y, $opacity = 70); // var_dump($image); //сохраняем новое изображение $image->save(NULL, $options['image_quality']); //первый параметр - путь, имя и формат изображения. Второй - качество изображения $insert = DB::insert('photoalbum', array('id', 'value'))->values(array('', DIRECTORY_SEPARATOR . $this->dir . $filename)); $result = $insert->execute(); $paramId = $result[0]; $insert = DB::insert('group_param_values', array('id', 'pid', 'mid', 'value'))->values(array('', $pid, $mid, $paramId))->execute(); } } } } }
public function action_index() { //смотрим шаблон для виджета $id = $this->request->param('id'); $widget = new Model_Widget(); $template = $widget->getTempalte('callback', $id); if ($template) { $this->template = View::factory('widgets/' . $template); } if (isset($_POST['callback-order'])) { if (Captcha::valid(Arr::get($_POST, 'comm-captcha'))) { $base = new Model_Base(); $options = $base->getOptions(); $vData = $_POST; $validation = Validation::factory($vData); $validation->rule('cb-name', 'not_empty'); $validation->rule('cb-name', 'min_length', array(':value', '2')); $validation->rule('cb-name', 'max_length', array(':value', '250')); $validation->rule('cb-phone', 'not_empty'); $validation->rule('cb-phone', 'phone'); $validation->rule('cb-phone', 'min_length', array(':value', '6')); $validation->rule('cb-phone', 'max_length', array(':value', '15')); if (!$validation->check()) { $this->errors = $validation->errors('callbackErrors'); } else { $name = Arr::get($_POST, 'cb-name', ''); $phone = Arr::get($_POST, 'cb-phone', ''); //отправляем письмо $config = Kohana::$config->load('email'); Email::connect($config); $to = $config['options']['callback_email']; //$to = '*****@*****.**'; $subject = 'Поступила заявка с сайта ' . $options['sitename'] . ' от ' . $name . ''; $from = $config['options']['username']; $message = '<h2>Новая заявка</h2>'; $message .= 'Отправитель: <b>' . $name . ', </b><br>'; $message .= 'Тел: <b>' . $phone . ', </b><br>'; $message .= '<em>Отправлено: ' . date("G:i:s M j Y") . '</em>'; Email::send($to, $from, $subject, $message, $html = TRUE); if (count($this->errors) > 0) { $base = new Model_Base(); $options = $base->getOptions(); $to = $options['admin_email']; $subject = 'Ошибки на сайте ' . $options['sitename']; $from = $config['options']['username']; foreach ($this->errors as $error) { $message = '<h2>Ошибка</h2>'; $message .= $error; $message .= ' <em>Отправлено: ' . date("G:i:s M j Y") . '</em>'; } Email::send($to, $from, $subject, $message, $html = TRUE); } else { $this->messages[] = 'Спасибо! Ваш вопрос успешно отправлен.'; } } } else { $this->errors['captcha'] = "Код введен неверно"; } } $captcha_image = Captcha::instance()->render(); $this->template->captcha = $captcha_image; $this->template->errors = $this->errors; $this->template->messages = $this->messages; }
public function action_room() { $base = new Model_Base(); $options = $base->getOptions(); if (!isset($options['room']) || $options['room'] != 'TRUE') { Controller::redirect('/'); } $this->template->title = 'Личный кабинет'; $this->template->page_title = 'Личный кабинет'; $this->template->keywords = 'Личный кабинет'; $this->template->description = 'Личный кабинет'; $data = array(); $errors = array(); $widgets = $this->getWidgets(0); $auth = Auth::instance(); // var_dump($auth->hash($_POST['password'])); if (is_array($widgets)) { foreach ($widgets as $position => $widget) { $this->template->{$position} = $widget; } } if (!$auth->logged_in('visitor')) { if (isset($_POST['login'])) { $username = Arr::get($_POST, 'username', ''); $password = Arr::get($_POST, 'password', ''); if ($auth->login($username, $password)) { //print('Залогинен'); $session = Session::instance(); $auth_redirect = $session->get('auth_redirect', ''); $session->delete('auth_redirect'); Controller::redirect('/user'); } else { //print('Ошибка'); $errors[] = 'Не верный логин или пароль.'; } } $this->template->block_center[] = View::factory('widgets/w_auth')->bind('errors', $errors); } else { $param = $this->request->param('act'); $materals = new Model_Material('group'); //получаем пользователя $user = $auth->get_user(); if ($param == 'show') { $user_orders = Module::create(array("controller" => "user/cabinet/orders", "action" => "index", "options" => array())); //echo $user_orders["body"]; //получаем материалы пользователя $data['materials'] = $materals->getUserMaterials($user->id); //$this->template->block_center[] = $user_orders["body"]; //return new View($file, $data); /*$page = View::factory('widgets/w_room') ->bind('errors', $errors) ->bind('messages', $messages) ->bind('data', $data); var_dump($page);*/ // --- tests ------------------------------------------------------------- $this->template->title = 'Личный кабинет'; $this->template->page_title = 'Личный кабинет'; $this->template->keywords = 'Личный кабинет'; $this->template->description = 'Личный кабинет'; $auth = Auth::instance(); if ($auth->logged_in() != 0) { $this->template->content = View::factory('admin/admIndex'); } else { $this->template->content = View::factory('admin/admLogin'); if (isset($_POST['enter'])) { $username = Arr::get($_POST, 'username', ''); $password = Arr::get($_POST, 'password', ''); if ($auth->login($username, $password)) { //print('Залогинен'); $session = Session::instance(); $auth_redirect = $session->get('auth_redirect', ''); $session->delete('auth_redirect'); Controller::redirect($auth_redirect); } else { //print('Ошибка'); $this->template->error = 'Не верный логин или пароль.'; } } } // --- tests ------------------------------------------------------------- //exit(); } elseif ($param == 'edit') { $materialId = $this->request->param('id'); //получаем материал $data['material'] = $materals->getMaterial($materialId, $user->id); if ($data['material']) { $gid = $materals->getGroupFromMid($materialId); $data['fieldset'] = $materals->getFieldsSet($gid); //получаем поля $data['fields'] = $materals->getFields($materialId, TRUE); } else { $errors[] = 'Данный материал не найден'; } } elseif ($param == 'settings') { if (isset($_POST['save_settings'])) { //сохраняем настройки $modelUser = new Model_User(); $res = $modelUser->saveUser($_POST, $user->id); if (is_array($res)) { $errors = $res; } else { $messages[] = $res; } } $data['user'] = ORM::factory('User', array('id' => $user->id)); } $this->template->block_center[] = View::factory('widgets/w_room')->bind('errors', $errors)->bind('messages', $messages)->bind('data', $data); } }