Example #1
0
    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;
        }
    }
Example #2
0
 public function getCart($userId)
 {
     $result = DB::select()->from($this->tableName)->where('user', '=', $userId)->group_by('mid')->execute()->as_array();
     $material = new Model_Material('groups');
     $category = new Model_Category('tree');
     $base = new Model_Base();
     $arr = array();
     foreach ($result as $item) {
         //var_dump($item);
         //название модели
         $materialData = $material->getMaterial($item['mid']);
         $arr[$item['mid']]['name'] = $materialData['name'];
         $arr[$item['mid']]['mid'] = $item['mid'];
         //url модели
         $categoryName = $category->getNode($material->getTreeIdByMid($item['mid']));
         $categoryName = $base->str2url($categoryName['name']);
         $arr[$item['mid']]['url'] = $categoryName . '/' . $materialData['url'] . '.html';
         //Изображение
         $fields = $material->getFields($item['mid'], true);
         $arr[$item['mid']]['img'] = $fields['Photos'][0];
         //количество
         $arr[$item['mid']]['count'] = $this->getCartCount($userId, $item['mid']);
         //сумма
         $arr[$item['mid']]['sum'] = $this->getCartPrice($userId, $item['mid']);
         //размер
         $arr[$item['mid']]['size'] = $item['size'];
         //цвет
         $arr[$item['mid']]['color'] = $item['color'];
     }
     return $arr;
 }
Example #3
0
 public function action_index()
 {
     $base = new Model_Base();
     $pageNum = 0;
     $param = $this->request->param('id');
     $filters = $base->safeArrAssoc($_GET);
     $params = explode('/', $param);
     $gid = $params[0];
     foreach ($params as $paramName) {
         if (preg_match("/page(\\d)/", $paramName)) {
             $pageNum = str_replace('page', '', $paramName);
         }
     }
     $marker = array_pop($params);
     $catalog = new Model_Material('groups');
     //смотрим шаблон для виджета
     $widget = new Model_Widget();
     $template = $widget->getTempalte('catalog2', $gid);
     if ($template) {
         $this->template = View::factory('widgets/' . $template);
     }
     // $categoryName = $catalog->getCategoryNameByCatalog();
     //получить содержимое папки
     // $count = $catalog->getCountMaterials($param);
     $count = $catalog->getCountMaterials($gid);
     $pagination = Pagination::factory(array('total_items' => $count));
     $pagination->current_page = $pageNum;
     $data = $catalog->getFullMaterials($gid);
     $this->template->data = $data;
     $this->template->pagination = $pagination;
 }
Example #4
0
 /**
  * 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));
 }
Example #5
0
 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>Логин:&nbsp;&nbsp;<input type="text" value="' . $email . '"></small></p>';
                 $message .= '<p><small>Пароль:&nbsp;<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");
 }
Example #6
0
 public function action_index()
 {
     if ($_FILES['upload']) {
         if ($_FILES['upload'] == "none" or empty($_FILES['upload']['name'])) {
             $message = "Вы не выбрали файл";
         } else {
             if ($_FILES['upload']["size"] == 0 or $_FILES['upload']["size"] > 12050000) {
                 $message = "Размер файла не соответствует нормам";
             } else {
                 if ($_FILES['upload']["type"] != "image/jpeg" and $_FILES['upload']["type"] != "image/jpeg" and $_FILES['upload']["type"] != "image/png") {
                     $message = "Допускается загрузка только картинок JPG и PNG.";
                 } else {
                     if (!is_uploaded_file($_FILES['upload']["tmp_name"])) {
                         $message = "Что-то пошло не так. Попытайтесь загрузить файл ещё раз.";
                     } else {
                         $message = '';
                         $uploadDir = $this->uploads_dir();
                         $ext = explode('.', $_FILES['upload']['name']);
                         $extension = array_pop($ext);
                         $base = new Model_Base();
                         $extarr = explode('.', $_FILES['upload']['name']);
                         $ext = array_pop($extarr);
                         $name = implode('', $extarr);
                         $name = substr(md5(microtime() * time()), 0, rand(20, 10));
                         //$name =rand(1, 1000).'-'.md5($_FILES['upload']['name']).'.'.$ext;
                         $filename = $base->str2url($name) . '.' . $ext;
                         //$filename = substr(md5(microtime() * time()),0,rand(20,10)).'.'.$extension;
                         if (copy($_FILES['upload']['tmp_name'], $uploadDir . "/" . $filename)) {
                             $message = "Файл " . $name . " загружен";
                         }
                         //                $name =rand(1, 1000).'-'.md5($_FILES['upload']['name']).'.'.$this->getex($_FILES['upload']['name']);
                         //                move_uploaded_file($_FILES['upload']['tmp_name'], "/img/user/".$name);
                         //                $full_path = 'http://sp-salon.ru/img/user/'.$name;
                         //                $message = "Файл ".$_FILES['upload']['name']." загружен";
                         //                $size=@getimagesize('/img/user/'.$name);
                         //                if($size[0]<50 OR $size[1]<50){
                         //                    unlink('/img/user/'.$name);
                         //                    $message = "Файл не является допустимым изображением";
                         //                    $full_path="";
                         //                }
                     }
                 }
             }
         }
         $callback = $_REQUEST['CKEditorFuncNum'];
         echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction("' . $callback . '", "' . DIRECTORY_SEPARATOR . $this->baseDir . $filename . '", "' . $message . '" );</script>';
     }
 }
Example #7
0
 public function __construct($table = NULL, $db_zone_name = NULL)
 {
     parent::__construct();
     $this->_table = $table;
     $this->_db_zone_name = $db_zone_name;
     $this->_sql_maker = Lib_PDOSqlMaker::getInstance();
 }
Example #8
0
 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;
 }
 function __construct($message = '', $is_success = false, $model = null, $models = null)
 {
     parent::__construct();
     $this->Message = $message;
     $this->IsSuccess = $is_success;
     $this->Model = $model;
     $this->Models = $models;
 }
Example #10
0
 public function __construct()
 {
     parent::__construct();
     $user = Model_User::create();
     $udata = (object) $user->getAuth();
     $this->userId = $udata->user_id;
     $this->userRole = $udata->role;
 }
Example #11
0
 function __construct($db, $user_id = 0)
 {
     parent::__construct($db, $user_id);
     /*$db['driver_options']  = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8"');
     		$this->db = Zend_Db::factory('PDO_MYSQL', $db);
     	 	$this->db->query("SET names 'utf8'");	 
     	 	$this->user_id = $user_id;*/
 }
Example #12
0
 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>Логин:&nbsp;&nbsp;<input type="text" value="' . $name . '"></small></p>';
         $message .= '<p><small>Пароль:&nbsp;<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;
     }
 }
Example #13
0
 public function __construct()
 {
     parent::__construct();
     //$this->storage = new Storage ('../private/materials');
     $this->storage = Resources::getInstance()->materials_storage;
     $this->attachObserver(Model_ControlWork::create());
     $this->_checkRightsObject = Model_CheckRigths::create();
 }
Example #14
0
 public function __construct($table = NULL, $db_zone_name = NULL, $data_type = NULL, $debug = FALSE)
 {
     parent::__construct();
     $this->_table = $table;
     $this->_debug = $debug;
     $this->_db_zone_name = $db_zone_name;
     $this->_sql_maker = Lib_PDOPgsqlMaker::getInstance();
     $this->_data_type = $data_type;
 }
Example #15
0
 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);
     }
 }
 /**
  * delete collection
  *
  */
 public function delete()
 {
     if ($this->loaded()) {
         // delete all the item links
         $this->clean();
         // delete collection
         parent::delete();
     }
 }
Example #17
0
 public function action_list()
 {
     $page = $this->get_query('page', 1);
     $filter = array('pid' => $this->get_query('pid'), 'author_id' => $this->get_query('uid'));
     $filter = Model_Base::clean_data($filter);
     $topic_list = Model_Topic::page($filter, $page, OJ::per_page);
     $total = Model_Topic::count($filter);
     $this->template_data['topic_list'] = $topic_list;
     $this->template_data['total'] = ceil($total / OJ::per_page);
     $this->template_data['title'] = __('discuss.list.discuss');
 }
Example #18
0
 public function __construct($db, $user_id = 0, $nocheck = 0)
 {
     parent::__construct($db);
     $this->user_id = $user_id;
     $this->shortshow = 0;
     $this->nocheck = $nocheck;
     $this->materialtype = 1;
     $this->mycoins = 0;
     $this->categoty_type = self::BASE;
     $this->arraynewcoins = array(1 => date('Y') - 2, 2 => date('Y') - 1, 3 => date('Y'));
 }
Example #19
0
 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 = 'Панель управления';
 }
Example #20
0
 public function action_talk()
 {
     $cid = $this->get_query('cid');
     $contest = Model_Contest::find_by_id($cid);
     $this->check_permission($contest);
     $page = $this->get_query('page', 1);
     $filter = array('cid' => $cid);
     $filter = Model_Base::clean_data($filter);
     $topic_list = Model_Topic::page($filter, $page, OJ::per_page);
     $total = Model_Topic::count($filter);
     $this->view = 'discuss/list';
     $this->template_data['contest'] = $contest;
     $this->template_data['cid'] = $cid;
     $this->template_data['topic_list'] = $topic_list;
     $this->template_data['total'] = ceil($total / OJ::per_page);
     $this->template_data['title'] = sprintf('%s - Discuss', $contest->title);
 }
 public function __construct()
 {
     parent::__construct();
     $this->_table = $this->_em->getRepository('CampaignReadiness');
 }
Example #22
0
 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;
 }
Example #23
0
 public function __construct()
 {
     parent::__construct();
     // $this->_table = $this->_em->getRepository('Reports');
 }
 public function __construct()
 {
     parent::__construct();
     $this->_table = $this->_em->getRepository('GatepassMaster');
 }
 public function __construct()
 {
     parent::__construct();
     $this->_table = $this->_em->getRepository('CcmTransferHistory');
 }
 public function __construct()
 {
     parent::__construct();
     $this->_table = $this->_em->getRepository('PlacementLocations');
 }
Example #27
0
 public function __construct()
 {
     parent::__construct();
     $this->_table = $this->_em->getRepository('CcmVehicles');
 }
Example #28
0
 public function __construct()
 {
     parent::__construct();
     $this->_table = $this->_em->getRepository('ListDetail');
 }
Example #29
0
 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 __construct()
 {
     parent::__construct();
     $this->_table = $this->_em->getRepository('PhysicalStockTakingDetail');
 }