Example #1
0
 public function action_index()
 {
     $materials = new Model_Material('group');
     $gid = $this->request->param('id');
     $data = $materials->getTopMaterials($gid, 'time', 1);
     $this->template->data = $data;
 }
Example #2
0
 public function action_index()
 {
     $materialId = $this->request->param('id');
     $materials = new Model_Material('groups');
     //получить содержимое папки
     $data = $materials->getMaterial($materialId);
     $fields = $materials->getFields2($materialId, TRUE);
     $model = array("photos" => array());
     $model["id"] = Arr::get($data, "id");
     $model["name"] = Arr::get($data, "name");
     $model["article"] = Arr::get($data, "art");
     $model["price"] = number_format(Arr::get($fields, 'price'), 0, "", " ");
     Resources::add_scripts(array("js/modules/material/material.js"), get_class());
     // --- Фотки ----------------------------------------------------
     // есть фото
     if (isset($fields["photos"][0])) {
         $photos = $fields["photos"];
         $model["general_photo"] = $photos[0]["value"];
         // Фоток больше 1
         if (count($photos) > 1) {
             foreach ($photos as $photo) {
                 $model["photos"][] = array("original" => $photo["value"], "mini" => Route::url("miniimg2", array("filename" => $photo["value"])));
             }
         }
     } else {
         $model["general_photo"] = "/img/noimg.png";
     }
     // --- /Фотки ----------------------------------------------------
     // --- Коментарии ------------------------------------------------
     echo '<script>window.material_id = JSON.parse(\'' . $materialId . '\');</script>';
     $this->load_module("comments", "/widgets/Comments/index");
     // --- /Коментарии -----------------------------------------------
     $this->set_template("/widgets/material/material.php", "twig")->render($model)->body();
 }
Example #3
0
 public function getTags($fieldName)
 {
     $materials = new Model_Material('group');
     //получаем ид поля по названию
     $fields[] = $materials->getField($fieldName);
     $tags = array();
     foreach ($fields as $field) {
         //получить все значения
         $result = DB::select('value')->from('group_param_values')->where('pid', '=', $field['id'])->execute();
         $vids = $result->as_array();
         foreach ($vids as $vid) {
             $result = DB::select('value')->from($field['type'])->where('id', '=', $vid['value'])->execute();
             $values = $result->as_array();
             foreach ($values as $value) {
                 $value = explode(',', $value['value']);
                 foreach ($value as $tag) {
                     if ($tag != '') {
                         $tags[trim($tag)] = $materials->str2url($tag);
                     }
                 }
             }
         }
     }
     ksort($tags);
     return $tags;
 }
Example #4
0
 public function getPath($dir)
 {
     //первым делом ищем в структуре
     $category = new Model_Category('tree');
     $categoryId = $category->getCategoryIdByUrl($dir);
     if ($categoryId) {
         $dirs = [];
         $categoryData = $category->getCategory($categoryId);
         $parents = $category->getParents($categoryId);
         foreach ($parents as $parent) {
             if ($parent['level'] > 1 && $parent['url'] != 'glavnaya') {
                 $dirs[] = $parent['url'];
             }
         }
         return array('name' => $categoryData['name'], 'path' => implode('/', $dirs));
     }
     //теперь ищем в материалах
     $materials = new Model_Material('group');
     $materialUrl = str_replace('.html', '', $dir);
     $materialId = $materials->getMaterialIdByUrl($materialUrl);
     if ($materialId) {
         $materialData = $materials->getMaterial($materialId);
         $categoryId = $materials->getTreeIdByMid($materialId);
         $categoryData = $category->getCategory($categoryId);
         return array('name' => $materialData['name'], 'path' => $categoryData['url'] . '/' . $dir);
     } else {
         return FALSE;
     }
 }
Example #5
0
 public function action_tags()
 {
     $widgets = array();
     $tagName = urldecode($this->request->param('id'));
     $materials = new Model_Material('groups');
     $materialList = $materials->getMidFromTags($tagName);
     if (!$materialList) {
         throw new HTTP_Exception_404();
     }
     //Описание ингридиента
     $tagUrl = $materials->str2url($tagName);
     $ingridientId = $materials->getMaterialIdByUrl($tagUrl);
     if ($ingridientId) {
         $widgets[] = Request::factory('widgets/material/index/' . $ingridientId)->execute();
     }
     $this->styles = array('/css/search.css');
     $old_styles = $this->template->styles;
     array_unique($this->styles);
     $new_styles = array_merge($this->styles, $old_styles);
     $this->template->styles = $new_styles;
     $this->template->title = $tagName . '';
     $this->template->page_title = $tagName;
     $this->template->keywords = $tagName . '' . $tagName;
     $this->template->description = '' . $tagName;
     $materialsString = implode('/', $materialList);
     View::set_global('categoryName', '');
     $widgets[] = Request::factory('widgets/catalog/index/' . $materialsString . '/tags')->execute();
     $this->template->styles[] = 'css/catalog.css';
     $this->template->block_center = $widgets;
 }
Example #6
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 #7
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 #8
0
 public function action_index()
 {
     $model = array("items" => array());
     $this->setopt(array("name" => "catalog_id", "description" => "Ид каталога", "default" => 4));
     $materials = new Model_Material('group');
     $gid = $this->getopt("catalog_id");
     $items = $materials->getTopMaterials($gid, 'views', 4);
     foreach ($items as $id => $item) {
         $model["items"][] = array("photo" => $item['photos'][0]['value'], "href" => '/' . $item['node'] . $item['url'] . '.html', "name" => $item['name'], "price" => number_format(Arr::get($item, 'price'), 0, '', ' '));
     }
     $this->set_template("/widgets/w_top.php", "twig")->render($model)->body();
 }
Example #9
0
 public function action_index()
 {
     $data = array();
     if (!is_readable(APPPATH . 'config/database.php')) {
         Request::initial()->redirect('install');
     }
     $cat = new Model_Category();
     $materials = new Model_Material();
     $cat->checkTree();
     $tree = $cat->getTree();
     $data['tree'] = $cat->getITree($tree);
     $data['teachers'] = $materials->getTeachersGropupByNode();
     $this->tpl->content = View::factory('main', $data);
 }
Example #10
0
 public function action_index()
 {
     $materialId = $this->request->param('id');
     $materials = new Model_Material('groups');
     //get widget template
     $widget = new Model_Widget();
     $template = $widget->getTempalte('files', $materialId);
     if ($template) {
         $this->template = View::factory('widgets/' . $template);
     }
     //get data
     $data = $materials->getMaterial($materialId);
     $fields = $materials->getFields2($materialId, TRUE);
     $this->template->material = $data;
     $this->template->fields = $fields;
 }
Example #11
0
 public function action_index()
 {
     $materialId = $this->request->param('id');
     $materials = new Model_Material('groups');
     //получить содержимое папки
     $data = $materials->getMaterial($materialId);
     $fields = $materials->getFields2($materialId, TRUE);
     //смотрим шаблон для виджета
     $widget = new Model_Widget();
     $template = $widget->getTempalte('material', $materialId);
     if ($template) {
         $this->template = View::factory('widgets/' . $template);
     }
     $group = $materials->getGroup($materials->getGroupFromMid($materialId));
     if ($group['name'] == 'Новости') {
         $this->template = View::factory('widgets/w_news_item');
         $this->template->breadcrumbs = Request::factory('widgets/breadcrumb/index/')->execute();
     }
     //        if($group['name']=='Диспенсеры')
     //        {
     //            if(isset($fields['type'][0]))
     //            {
     //                $uri = Request::detect_uri();
     //                $dirs = explode('/', $uri);
     //                array_pop($dirs);
     //                $categoryName = array_pop($dirs);
     //
     //                $category = new Model_Category('tree');
     //                $categoryId = $category->getCategoryIdByUrl($categoryName);
     //
     //                $GLOBALS['categoryId'] = $categoryId;
     //
     //                $dopdata = $materials->getFullMaterials2($group['id'], 5, 0, NULL, array('type' => array($fields['type'][0]['value'])));
     //                unset($dopdata[$materialId]);
     //
     //                $this->template->dopdata = array_slice($dopdata, 0, 4);
     //            }
     //        }
     //получаем комментарии
     $comments = Request::factory('widgets/comments/index/' . $materialId)->execute();
     $callback_form = Request::factory('widgets/callback/index/')->execute();
     $this->template->callback = $callback_form;
     $this->template->material = $data;
     $this->template->fields = $fields;
     $this->template->comments = $comments;
 }
Example #12
0
 public function action_index()
 {
     $materials = new Model_Material('group');
     $gid = $this->request->param('id');
     $template = $this->request->param('template');
     if ($template) {
         $this->template = View::factory('widgets/' . $template);
     }
     //смотрим шаблон для виджета
     $widget = new Model_Widget();
     $template = $widget->getTempalte('top', $gid);
     if ($template) {
         $this->template = View::factory('widgets/' . $template);
     }
     $data = $materials->getRandomMaterials($gid, 4, time());
     $this->template->data = $data;
 }
Example #13
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;
 }
Example #14
0
 public function vote($materialId, $ansver)
 {
     $ansverId = trim(str_replace('Вариант', '', $ansver));
     $materials = new Model_Material('group');
     $fields = $materials->getFields2($materialId);
     foreach ($fields as $field) {
         if ($field['title'] == 'Ответов ' . $ansverId) {
             //получаем значение
             $query = 'SELECT b.* FROM group_param_values a, ' . $field['type'] . ' b WHERE a.mid =' . $materialId . ' AND a.pid =' . $field['id'] . ' AND a.value = b.id';
             $res = DB::query(Database::SELECT, $query)->execute()->current();
             $cnt = intval($res['value']) + 1;
             $query = 'UPDATE ' . $field['type'] . ' SET value = ' . $cnt . ' WHERE id =' . $res['id'];
             $res = DB::query(Database::UPDATE, $query)->execute();
             if ($res) {
                 return TRUE;
             }
         }
     }
 }
Example #15
0
 public function action_index()
 {
     $string = urldecode($this->request->param('id'));
     $materials = new Model_Material('groups');
     $pageNum = intval(Arr::get($_GET, 'page', 0));
     if (strlen($string) > 2) {
         $cat_counter = $materials->getCountFullMaterials2(0, $string);
         $pagination = Pagination::factory(array('total_items' => $cat_counter));
         if (isset($param_array['page']) && $param_array['page'] == 'all') {
             $pagination->items_per_page = 20;
             $pagination->offset = 0;
         }
         $pagination->current_page = $pageNum;
         $data = $materials->getFullMaterials2(0, $pagination->items_per_page, $pagination->offset, $string);
         $this->template->pagination = $pagination;
         $this->template->data = $data;
     } else {
         $this->template->pagination = '';
         $this->template->data = array();
     }
 }
Example #16
0
 public function action_catalog()
 {
     $materials = new Model_Material('groups');
     //получаем url материала
     $materialID = $this->request->param('id');
     $material = $materials->getMaterial($materialID);
     $fields = $materials->getFields2($materialID, TRUE);
     $this->template->title = $material['name'];
     $this->template->page_title = $material['name'];
     $this->template->keywords = $material['keywords'];
     $this->template->description = $material['description'];
     $this->template->links = array('<link rel="canonical" href="' . Kohana::$base_url . 'catalog/' . $materialID . '.html"/>');
     $this->template->styles = Resources::load_styles();
     if (!$material['id']) {
         throw new HTTP_Exception_404();
     }
     //обновляем просмотры
     $materials->updateViews($material['id']);
     $widgets[] = Request::factory('widgets/material/index/' . $materialID)->execute();
     $this->template->block_center = $widgets;
 }
 public function action_showcontent()
 {
     $data = array();
     $id = $this->request->param('id');
     $material = new Model_Material();
     $data = $material->showMaterialById($id);
     if (!$data) {
         throw new HTTP_Exception_404('Запрашиваемая статья не найдена');
         return;
     }
     $this->template->content = View::factory('contentview', $data);
     //Категории для сайдбара
     $tree = new Model_Tree();
     $data_cat = array();
     $data_cat = $tree->getCategoryUrl();
     if (!$data_cat) {
         throw new HTTP_Exception_404('Запрашиваемая категория не найдена');
         return;
     }
     $this->template->categorys = $data_cat;
 }
Example #18
0
 public function action_index()
 {
     $errors = array();
     $materialId = $this->request->param('id');
     $materials = new Model_Material('group');
     //смотрим шаблон для виджета
     $widget = new Model_Widget();
     $template = $widget->getTempalte('polls', $materialId);
     if ($template) {
         $this->template = View::factory('widgets/' . $template);
     }
     $name = 'polls_' . $materialId;
     $voted = FALSE;
     //Cookie::delete($name);
     if (Cookie::get($name)) {
         $voted = TRUE;
     } else {
         if (isset($_POST['save_polls'])) {
             $polls = new Model_Polls();
             //сохраняем результаты голосования
             $result = $polls->vote($_POST['save_polls'], $_POST['answer']);
             if ($result) {
                 //создаем куки по данному опросу
                 if (!Cookie::set($name, 'voted', Date::YEAR)) {
                     $errors[] = 'Вероятно в Вашем браузере отключены Cookie.';
                 } else {
                     $voted = TRUE;
                 }
             }
         }
     }
     $data = $materials->getMaterial($materialId);
     $fields = $materials->getFields2($materialId, TRUE);
     $fields2 = $materials->getFields2($materialId, FALSE);
     $this->template->data = $data;
     $this->template->fields = $fields;
     $this->template->fields2 = $fields2;
     $this->template->voted = $voted;
     //Получаем список меню
 }
Example #19
0
 public function action_index()
 {
     // basic
     $url = $this->request->param('id');
     $data = array();
     $tree = new Model_Tree();
     $data['categorys'] = $tree->getCategoryUrl();
     if (!$data['categorys']) {
         throw new HTTP_Exception_404('Запрашиваемая категория не найдена');
         return;
     }
     $this->template = View::factory('basic', $data);
     //home
     $data_content = array();
     $material = new Model_Material();
     $data_content = $material->getBooksID();
     if (!$data_content) {
         throw new HTTP_Exception_404('Запрашиваемая категория не найдена');
         return;
     }
     $this->template->contentpost = $data_content;
 }
Example #20
0
 public function action_index()
 {
     $materials = new Model_Material('groups');
     $gid = $this->request->param('id');
     $ready = array();
     //получаем набор фильтров
     $filters = $materials->getFieldsSet($gid);
     foreach ($filters as $filter) {
         if ($filter['for_filters'] == '1') {
             if ($filter['type'] == 'select') {
                 $value_set = array();
                 $set = $materials->getSelectValues($filter['id']);
                 foreach ($set as $set_item) {
                     $value_set[] = $set_item;
                 }
                 $filter['value_set'] = $value_set;
             }
             array_push($ready, $filter);
         }
     }
     $this->template->filters = $ready;
     $this->template->search_params = $_GET;
 }
Example #21
0
 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('files', 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['uploads']['name']); ++$i) {
             if ($files['uploads']['size'][$i] < 50000000 && $files['uploads']['size'][$i] > 100) {
                 //расширение файла
                 $ext = explode('.', $files['uploads']['name'][$i]);
                 $extension = array_pop($ext);
                 //генерируем имя изображения
                 $base = new Model_Base();
                 $extarr = explode('.', $files['uploads']['name'][$i]);
                 $ext = array_pop($extarr);
                 //$filename = $material['url'] . '_'.substr(md5(microtime() * time()),0,rand(20,10)).'.'.$ext;
                 $filename = $files['uploads']['name'][$i];
                 $names = explode('/', $filename);
                 $title = array_pop($names);
                 if (copy($files['uploads']['tmp_name'][$i], DOCROOT . $this->dir . $filename)) {
                     $insert = DB::insert('files', array('id', 'value', 'title', 'size', 'ext'))->values(array('', DIRECTORY_SEPARATOR . $this->dir . $filename, $title, $files['uploads']['size'][$i], $ext));
                     $result = $insert->execute();
                     $paramId = $result[0];
                     $insert = DB::insert('group_param_values', array('id', 'pid', 'mid', 'value'))->values(array('', $pid, $mid, $paramId))->execute();
                 }
             }
         }
     }
 }
Example #22
0
 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'];
 }
Example #23
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;
     }
 }
Example #24
0
 public function send($data)
 {
     $material = new Model_Material('groups');
     $fields = $material->getFields2($data['template'], TRUE);
     //отправляем письмо
     $config = Kohana::$config->load('email');
     Email::connect($config);
     $subject = Arr::get($fields, 'title');
     $from = $config['options']['username'];
     $message = Arr::get($fields, 'text');
     $message = str_replace('@#object#@', Arr::get($data, 'object_name'), $message);
     $message = str_replace('@#url#@', Arr::get($data, 'object_url'), $message);
     //генерируем уникальный разделитель
     $bound = "--" . md5(uniqid(time()));
     foreach ($data['check_name'] as $subscriberId) {
         $subscriber = $this->getSubscriber($subscriberId);
         if ($subscriber['active'] == 1) {
             $message = str_replace('@#subscriber#@', $subscriber['name'], $message);
             $subject = str_replace('@#subscriber#@', $subscriber['name'], $subject);
             $message = str_replace('@#site#@', Kohana::$base_url, $message);
             $mymessage = str_replace('@#email#@', $subscriber['email'], $message);
             //            $mail_header = "MIME-Version: 1.0;\r\n";
             //            $mail_header.= "Content-Type: multipart/mixed; boundary=\"$bound\"\r\n";
             $headers = "MIME-Version: 1.0\r\n";
             $headers .= "Content-type: text/html; charset=UTF-8\r\n";
             $headers .= "From: Morrismedia <" . $from . ">\r\n";
             //прикрепляем файл
             //путь к файлу
             $file_path = DOCROOT . '/img/user/novost-1_859f1ca6ad9b29c3475.png';
             //если файл найден, прикрепляем его к сообщению
             if (file_exists($file_path)) {
                 $file_name = basename($file_path);
                 $fa = fopen($file_path, "rb");
                 if ($fa) {
                     $multipart_message = "\r\n--{$bound}\r\n";
                     $multipart_message .= "Content-type: text/html; charset=UTF-8\r\n";
                     $multipart_message .= "Content-Transfer-Encoding: base64\r\n";
                     $multipart_message .= "\r\n";
                     $multipart_message .= chunk_split(base64_encode($message));
                     $multipart_message .= "\r\n\r\n--{$bound}\r\n";
                     $multipart_message .= "Content-Type: application/octet-stream; name=\"{$file_name}\"\r\n";
                     $multipart_message .= "Content-Transfer-Encoding: base64\r\n";
                     $multipart_message .= "Content-Disposition: attachment; filename=\"{$file_name}\"\r\n";
                     $multipart_message .= "\r\n";
                     $multipart_message .= chunk_split(base64_encode(fread($fa, filesize($file_path))));
                     fclose($fa);
                     //передаем текст сообщения и прикрепленный файл в переменную
                     $message = $multipart_message;
                 } else {
                     $message = $message;
                 }
             } else {
                 //если файл не существует передаем текстовое сообщение
                 $message = $message;
             }
             // var_dump($mail_header);
             $result = mail($subscriber['email'], $subject, $mymessage, $headers);
             if ($result) {
                 $this->messages[] = 'Успешная отправка на ' . $subscriber['email'];
                 $this->updateSend($subscriber['email']);
             } else {
                 $this->errors[] = 'Ошибка отправки на ' . $subscriber['email'];
             }
             //            try
             //            {
             //                if(mail($subscriber['email'], $subject, $message, $mail_header, '*****@*****.**'))
             ////                if(Email::send($subscriber['email'], $from, $subject, $message, $html = TRUE))
             //                {
             //                    $this->messages[] = 'Успешная отправка на '.$subscriber['email'];
             //                    $this->updateSend($subscriber['email']);
             //                }
             //                else
             //                    $this->errors[] = 'Ошибка отправки на '.$subscriber['email'];
             //            }
             //            catch (Exception $e)
             //            {
             //                $this->errors[] = 'Ошибка отправки на '.$subscriber['email'];
             //            }
         }
     }
     return array('messages' => $this->messages, 'errors' => $this->errors);
 }
Example #25
0
 public function action_index()
 {
     $data = array();
     $id = $this->request->param('id');
     $emails = new Model_Email();
     $material = new Model_Material('group');
     if (isset($_POST['send'])) {
         $fields = $material->getFields2($_POST['template'], TRUE);
         //отправляем письмо
         $config = Kohana::$config->load('email');
         Email::connect($config);
         $subject = Arr::get($fields, 'title');
         $from = $config['options']['username'];
         $message = Arr::get($fields, 'text');
         //генерируем уникальный разделитель
         $bound = "--" . md5(uniqid(time()));
         foreach ($_POST['check_name'] as $subscriberId) {
             $subscriber = $emails->getSubscriber($subscriberId);
             $message = str_replace('@#subscriber#@', $subscriber['name'], $message);
             $subject = str_replace('@#subscriber#@', $subscriber['name'], $subject);
             $message = str_replace('@#site#@', Kohana::$base_url, $message);
             $mail_header = "MIME-Version: 1.0;\r\n";
             $mail_header .= "Content-Type: multipart/mixed; boundary=\"{$bound}\"\r\n";
             $mail_header .= "Отправитель: <" . $from . ">\r\n";
             $mail_header .= "Для ответа <" . $from . ">\r\n";
             $mail_header .= "Subject: {$subject} \n";
             //прикрепляем файл
             //путь к файлу
             $file_path = DOCROOT . '/img/user/novost-1_859f1ca6ad9b29c3475.png';
             //если файл найден, прикрепляем его к сообщению
             if (file_exists($file_path)) {
                 $file_name = basename($file_path);
                 $fa = fopen($file_path, "rb");
                 if ($fa) {
                     $multipart_message = "\r\n--{$bound}\r\n";
                     $multipart_message .= "Content-Type: text/html; charset=UTF-8\r\n";
                     $multipart_message .= "Content-Transfer-Encoding: base64\r\n";
                     $multipart_message .= "\r\n";
                     $multipart_message .= chunk_split(base64_encode($message));
                     $multipart_message .= "\r\n\r\n--{$bound}\r\n";
                     $multipart_message .= "Content-Type: application/octet-stream; name=\"{$file_name}\"\r\n";
                     $multipart_message .= "Content-Transfer-Encoding: base64\r\n";
                     $multipart_message .= "Content-Disposition: attachment; filename=\"{$file_name}\"\r\n";
                     $multipart_message .= "\r\n";
                     $multipart_message .= chunk_split(base64_encode(fread($fa, filesize($file_path))));
                     fclose($fa);
                     //передаем текст сообщения и прикрепленный файл в переменную
                     $message = $multipart_message;
                 } else {
                     $message = $message;
                 }
             } else {
                 //если файл не существует передаем текстовое сообщение
                 $message = $message;
             }
             //   var_dump($message);
             try {
                 if (mail($subscriber['email'], $subject, $message, $mail_header)) {
                     //                    if(Email::send($subscriber['email'], $from, $subject, $message, $html = TRUE))
                     $this->messages[] = 'Успешная отправка на ' . $subscriber['email'];
                 } else {
                     $this->errors[] = 'Ошибка отправки на ' . $subscriber['email'];
                 }
             } catch (Exception $e) {
                 $this->errors[] = 'Ошибка отправки на ' . $subscriber['email'];
             }
         }
     }
     if ($id == NULL) {
         $this->templates = $material->getMaterials(59, 100, 0, '', array(), array('text'));
         $data['emails'] = $emails->getEmails();
     }
     $this->template->content = View::factory('admin/admEmails', array('data' => $data, 'user' => $this->user, 'templates' => $this->templates, 'errors' => $this->errors, 'messages' => $this->messages));
 }
Example #26
0
 public function goSearch($string)
 {
     $materials = new Model_Material('groups');
     //подключаем библиотеки
     require_once DOCROOT . 'application/classes/PHPMorphy/src/common.php';
     $dir = DOCROOT . 'application/classes/PHPMorphy/dicts/';
     $lang = 'ru_RU';
     $opts = array('storage' => PHPMORPHY_STORAGE_FILE);
     try {
         $morphy = new phpMorphy($dir, $lang, $opts);
     } catch (phpMorphy_Exception $e) {
         die('Error occured while creating phpMorphy instance: ' . $e->getMessage());
     }
     $data = array();
     $request = null;
     $errors = null;
     if (!empty($string)) {
         // Очищаем от html-тегов и прочего
         $search = trim(addslashes(strip_tags($string)));
         $request = $search;
     }
     /* Создаем экземпляр phpMorphy */
     if (!empty($search)) {
         // Обрабатываем данные как и в прошлом контроллере
         if (mb_strlen($search, "UTF-8") > 2) {
             preg_match_all('/([a-zа-яё]+)/ui', mb_strtoupper($search, "UTF-8"), $search_words);
             $words = $morphy->lemmatize($search_words[1]);
             $s_words = array();
             $pre_result = array();
             $sorter = array();
             foreach ($words as $k => $w) {
                 if (!$w) {
                     $w[0] = $k;
                 }
                 if (mb_strlen($w[0], "UTF-8") > 2) {
                     $s_words[] = $w[0];
                 }
             }
             if (!count($s_words)) {
                 // Обрабатываем ошибку (нет ни одного слова длиннее 2 символов)
             } else {
                 //перебираем каждое слово
                 foreach ($s_words as $s_word) {
                     //сначала ищем в названиях материалов
                     $search_index = ORM::factory('Materials')->where('name', 'LIKE', '%' . $s_word . '%')->find_all();
                     foreach ($search_index as $si) {
                         //если в другом слове было совпадение
                         if (isset($pre_result[$si->id])) {
                             //добавляем вес
                             $sorter[$si->id] = $sorter[$si->id] + 2;
                             $pre_result[$si->id]['weight'] = $pre_result[$si->id]['weight'] + 2;
                             $pre_result[$si->id]['s_text'] = str_ireplace(mb_strtolower($s_word), '<b>' . $s_word . '</b>', strip_tags($pre_result[$si->id]['s_text']));
                         } else {
                             $sorter[$si->id] = 2;
                             $material = $materials->getMaterial($si->id);
                             $pre_result[$si->id] = array('weight' => 2, 's_text' => str_ireplace(mb_strtolower($s_word), '<b>' . $s_word . '</b>', strip_tags($si->name)));
                         }
                     }
                     //ищем в текстах
                     $search_index = ORM::factory('Texts')->where('value', 'LIKE', '%' . $s_word . '%')->find_all();
                     foreach ($search_index as $si) {
                         //получаем mid для материала
                         $mid = $materials->getMidFromFieldId($si->id, 'texts');
                         if (isset($pre_result[$mid])) {
                             $sorter[$mid] = $sorter[$mid] + 1;
                             $pre_result[$mid]['weight'] = $pre_result[$mid]['weight'] + 1;
                             $pre_result[$mid]['s_text'] = str_ireplace(mb_strtolower($s_word), '<b>' . $s_word . '</b>', strip_tags($pre_result[$mid]['s_text']));
                         } else {
                             $pre_result[$mid] = array('weight' => 2, 's_text' => str_ireplace(mb_strtolower($s_word), '<b>' . $s_word . '</b>', strip_tags($si->value)));
                             $sorter[$mid] = 1;
                         }
                     }
                     //ищем в текстах
                     $search_index = ORM::factory('Chars')->where('value', 'LIKE', '%' . $s_word . '%')->find_all();
                     foreach ($search_index as $si) {
                         //получаем mid для материала
                         $mid = $materials->getMidFromFieldId($si->id, 'chars');
                         if (isset($pre_result[$mid])) {
                             $sorter[$mid] = $sorter[$mid] + 1;
                             $pre_result[$mid]['weight'] = $pre_result[$mid]['weight'] + 1;
                             $pre_result[$mid]['s_text'] = str_ireplace(mb_strtolower($s_word), '<b>' . $s_word . '</b>', strip_tags($pre_result[$mid]['s_text']));
                         } else {
                             $pre_result[$mid] = array('weight' => 2, 's_text' => str_ireplace(mb_strtolower($s_word), '<b>' . $s_word . '</b>', strip_tags($si->value)));
                             $sorter[$mid] = 1;
                         }
                     }
                 }
                 arsort($sorter);
                 // Сортируем массив по весу результатов
                 foreach ($sorter as $id => $weight) {
                     // Тут, соответственно, получаем данные о результатах и помещаем в массив
                     $data[] = $id;
                 }
             }
         } else {
             // Обрабатываем ошибку - введен слишком короткий запрос
         }
     } else {
         // Обрабатываем ошибку - пустой поисковый запрос
     }
     return $data;
 }
Example #27
0
 public function createFromGroups($parentId, $groupId)
 {
     $material = new Model_Material('groups');
     $base = new Model_Base();
     //получаем дерево групп
     $groups = $material->getTree($groupId);
     // 1. Получаем количество групп
     $groupCount = count($groups);
     // 2. Получаем крайний правый ключ
     $parentGroup = $material->getNode($groupId);
     $rightKey = (int) $parentGroup['right_key'] + 1;
     // 3. Получаем левый ключ
     $parentNode = $this->nstree->getNode($parentId);
     // получаем левел
     $level = (int) $parentNode['level'];
     $leftKey = (int) $parentNode['left_key'] + 1;
     //echo $leftKey.'-'.$rightKey;
     $this->nstree->modifyNodes($leftKey, $rightKey);
     $parent_node_lk = $parentNode["left_key"];
     $parent_node_rk = $parentNode["right_key"];
     $parent_node_level = $parentNode["level"];
     $parent_group_lk = $parentGroup["left_key"];
     $parent_group_rk = $parentGroup["left_key"];
     $parent_group_level = $parentGroup["level"];
     foreach ($groups as $group) {
         // Преобразование level'a группы для ноды
         $level_offset = $parent_node_level - $parent_group_level;
         $url = $base->str2url($group["name"]);
         while (!$this->unique_url($url)) {
             $url = $url . "-";
         }
         $node = array("name" => $group["name"], "url" => $url, "id" => NULL, "left_key" => $group["left_key"] + $leftKey, "right_key" => $group["right_key"] + $leftKey, "level" => $group["level"] + $level_offset);
         list($insert_id, $tmp) = DB::insert("tree", array_keys($node))->values(array_values($node))->execute();
         DB::query(NULL, "COMMIT")->execute();
         //Подключаем материалы
         $action = "sidebar";
         $left_menu = array("id" => NULL, "node_id" => $insert_id, "widget_id" => 2, "param" => "twig", "action" => $action, "options" => '{"' . $action . '_parent_id":"' . $parentId . '"}', "position" => "left_block", "title" => "Меню", "ordering" => 10);
         //list($insert_id, $tmp) = DB::insert("tree_widgets_rel", array_keys($left_menu))->values(array_values($left_menu))->execute();
         DB::insert("tree_widgets_rel", array_keys($left_menu))->values(array_values($left_menu))->execute();
         $action = "index";
         $catalog = array("id" => NULL, "node_id" => $insert_id, "widget_id" => 1, "param" => "twig", "action" => $action, "options" => '{"' . $action . '_catalog_id":"' . $group['id'] . '"}', "position" => "right_block", "title" => "Каталог", "ordering" => 10);
         //list($insert_id, $tmp) = DB::insert("tree_widgets_rel", array_keys($catalog))->values(array_values($catalog))->execute();
         DB::insert("tree_widgets_rel", array_keys($catalog))->values(array_values($catalog))->execute();
     }
     /*foreach ($groups as $group)
     		{
     			//берем узел
     			//var_dump($group);
     			//обновляем данные
     			
     			$url = $base->str2url($group["name"]);
     
     			while(!$this->unique_url($url))
     			{
     				$url = $url."-";
     			}
     
     			$extrafields = array("name" => $group["name"], "url" =>$url);
     			$node = array(
     				"id" => NULL,
     				"left_key" => $group["left_key"] + $leftKey,
     				"right_key" => $group["right_key"] + $leftKey,
     				"level" => $group["level"] + $level
     			);
     			$node = $node + $extrafields;
     			list($insert_id, $tmp) = DB::insert("tree", array_keys($node))->values(array_values($node))->execute();
     
     			DB::query(NULL, "COMMIT")->execute();
     			
     			//Подключаем материалы
     
     			$action = "sidebar";
     
     			$left_menu = array(
     				"id" => NULL,
     				"node_id" => $insert_id,
     				"widget_id" => 1,
     				"param"     => "twig",
     				"action" => $action,
     				"options" => '{"' . $action . '_parent_id":"' . $parentId . '"}',
     				"position"  => "left_block",
     				"title"     => "Меню",
     				"ordering"  => 10,
     			);
     
     			list($insert_id, $tmp) = DB::insert("tree_widgets_rel", array_keys($left_menu))->values(array_values($left_menu))->execute();
     
     			$action = "index";
     			
     			$catalog = array(
     				"id" => NULL,
     				"node_id" => $insert_id,
     				"widget_id" => 1,
     				"param"     => "twig",
     				"action" => $action,
     				"options" => '{"' . $action . '_catalog_id":"' . $group['id'] . '"}',
     				"position"  => "right_block",
     				"title"     => "Каталог",
     				"ordering"  => 10,
     			);
     
     			list($insert_id, $tmp) = DB::insert("tree_widgets_rel", array_keys($catalog))->values(array_values($catalog))->execute();
     			
     		}*/
 }
Example #28
0
 public function action_index()
 {
     $id = $this->request->param('id');
     if ($id == 'export') {
         $query = 'SELECT * FROM vz_catalog ORDER BY act DESC LIMIT 700, 100';
         $result = DB::query(Database::SELECT, $query)->execute()->as_array();
         $types = array('', 'База отдыха', 'Загородный отель', 'Санаторий', 'Кемпинг', 'Гостиница', 'Конно - спортивный клуб', 'Коттедж');
         $region = array('0' => '', '66' => 'Свердловская область', '74' => 'Челябинская область', '72' => 'Тюменская область', '59' => 'Пермский край', '2' => 'Башкортостан');
         $facialities = array('0' => '', '1' => 'Баня', '3' => 'Баня, Бассейн', '4' => 'Бильярд', '5' => 'Баня, Бильярд', '7' => 'Баня, Бассейн, Бильярд', '9' => 'Баня, Лес', '11' => 'Баня, Бассейн, Лес', '13' => 'Баня, Бильярд, Лес', '15' => 'Баня, Бассейн, Бильярд, Лес', '17' => 'Баня, Водоем', '20' => 'Бильярд, Водоем', '21' => 'Баня, Бильярд, Водоем', '23' => 'Баня, Бассейн, Бильярд, Водоем', '24' => 'Лес, Водоем', '25' => 'Баня, Лес, Водоем', '27' => 'Баня, Бассейн, Лес, Водоем', '29' => 'Баня, Бильярд, Лес, Водоем', '31' => 'Баня, Бассейн, Бильярд, Лес, Водоем', '33' => 'Баня, Питание', '35' => 'Баня, Бассейн, Питание', '37' => 'Баня, Бильярд, Питание', '39' => 'Баня, Бассейн, Бильярд, Питание', '40' => 'Лес, Питание', '41' => 'Баня, Лес, Питание', '43' => 'Баня, Бассейн, Лес, Питание', '44' => 'Бильярд, Лес, Питание', '45' => 'Баня, Биллиард, Лес, Питание', '47' => 'Баня, Бассейн, Бильярд, Лес, Питание', '49' => 'Баня, Лес, Питание', '51' => 'Баня, Бассейн, Лес, Питание', '53' => 'Баня, Бильярд, Лес, Питание', '56' => 'Лес, Водоем, Питание', '57' => 'Баня, Лес, Водоем, Питание', '58' => 'Бассейн, Лес, Водоем, Питание', '59' => 'Баня, Бассейн, Лес, Водоем, Питание', '60' => 'Бильярд, Лес, Водоем, Питание', '61' => 'Баня, Бильярд, Лес, Водоем, Питание', '63' => 'Баня, Бассейн, Бильярд, Лес, Водоем, Питание', '65' => 'Баня, Бассейн, Бильярд, Лес, Водоем, Питание');
         $base = new Model_Base();
         $material = new Model_Material('group');
         $counter = 0;
         foreach ($result as $item) {
             $photos = array();
             $dates = array();
             $faciality = array();
             $dquery = 'SELECT busy_date FROM vz_calendar WHERE cottage_id =' . $item['id'];
             $dresult = DB::query(Database::SELECT, $dquery)->execute()->as_array();
             if (isset($facialities[$item['opt']])) {
                 $ifaciality = explode(',', $facialities[$item['opt']]);
             } else {
                 $ifaciality = array();
             }
             foreach ($ifaciality as $fitem) {
                 $faciality[] = trim($fitem);
             }
             foreach ($dresult as $date) {
                 $dates[] = $date['busy_date'];
             }
             $pquery = 'SELECT id, title FROM vz_images WHERE top = ' . $item['id'] . ' ORDER by ord';
             $presult = DB::query(Database::SELECT, $pquery)->execute()->as_array();
             foreach ($presult as $pitem) {
                 $id = intval($pitem['id']);
                 if ($id < 1000) {
                     $folder = 0;
                 }
                 if ($id > 999 && $id < 10000) {
                     $folder = substr($id, 0, 1);
                 }
                 if ($id > 9999) {
                     $folder = substr($id, 0, 2);
                 }
                 $photos[] = '/img/user/catalog/' . $folder . '/' . $pitem['id'] . 'b.jpg';
             }
             if ($item['act'] == 1) {
                 $sleep = 0;
             } else {
                 $sleep = 1;
             }
             $insert = array('title' => $item['name'], 'url' => $base->str2url($item['name']), 'description' => $item['description'], 'sleep' => $sleep, 'date_241' => $dates, 'select_223' => array($types[$item['object_type']]), 'chars_224' => $item['pagetitle'], 'chars_225' => $item['spec_offer'], 'chars_226' => $item['spec_price'], 'chars_227' => $item['city'], 'select_228' => array($region[$item['region']]), 'chars_229' => $item['len'], 'chars_230' => $item['path'], 'select_231' => $faciality, 'chars_232' => $item['bad1'], 'chars_233' => $item['bad2'], 'chars_234' => $item['rooms'], 'price_235' => $item['cost'], 'chars_236' => $item['dayprice'], 'chars_237' => $item['people'], 'chars_238' => $item['mincapacity'], 'chars_239' => $item['capacity'], 'photoalbum_243' => $photos, 'texts_242' => $item['content']);
             $res = $material->newMaterial($insert, '33', array(), TRUE);
             if ($res) {
                 ++$counter;
             } else {
                 $this->data['errors'][] = 'Материал ' . $item['name'] . ' не был добавлен';
             }
             //
             //                echo '<pre>';
             //                var_dump($insert);
             //                echo '<pre>';
         }
         $this->data['messages'][] = 'Добавлено ' . $counter . ' материалов';
     } elseif ($id == 'comments') {
         //перебираем все отзывы
         $query = 'SELECT a.*, b.name AS obj_name FROM vz_reviews a, vz_catalog b WHERE a.object_id = b.id ORDER BY object_id DESC LIMIT 0, 1000';
         $result = DB::query(Database::SELECT, $query)->execute()->as_array();
         $cnt = 0;
         foreach ($result as $comment) {
             $q = 'SELECT id FROM materials WHERE name =\'' . $comment['obj_name'] . '\'';
             $res = DB::query(Database::SELECT, $q)->execute()->current();
             if ($res) {
                 $q1 = "UPDATE vz_reviews SET object_id = " . $res['id'] . ' WHERE id =' . $comment['id'];
                 $res1 = DB::query(Database::UPDATE, $q1)->execute();
                 if (!$res1) {
                     $this->data['errors'][] = $q1;
                 } else {
                     ++$cnt;
                 }
             }
         }
         $this->data['messages'][] = 'Обновлено ' . $cnt . ' комментариев';
     } elseif ($id == 'update_id') {
         $cnt = 0;
         //ПЕРЕБИРАЕМ ВСЕ КОТТЕДЖИ
         $query = 'SELECT * FROM vz_catalog WHERE act!=0 ORDER BY act DESC LIMIT 0, 500';
         $result = DB::query(Database::SELECT, $query)->execute()->as_array();
         foreach ($result as $item) {
             //делаем запрос по названию
             $q = 'UPDATE materials SET old_id = ' . $item['id'] . ' WHERE name = \'' . $item['name'] . '\'';
             $res = DB::query(Database::UPDATE, $q)->execute();
             if (!$res) {
                 $this->data['errors'][] = $q;
             } else {
                 ++$cnt;
             }
         }
     }
     $this->template->content = View::factory('admin/admScripts', array('data' => $this->data, 'user' => $this->user));
 }
Example #29
0
 public function getOrder($orderId)
 {
     $order = ORM::factory("Orders")->where("id", "=", $orderId)->find()->as_array();
     $items = DB::select()->from("order_materials")->where("order_id", "=", $orderId)->execute()->as_array();
     $materials = new Model_Material("groups");
     $catalog = new Model_Category("tree");
     foreach ($items as $item) {
         $material = $materials->getMaterial($item["mid"]);
         $fields = $materials->getFields2($item["mid"], TRUE);
         $categoryId = $materials->getTreeIdByMid($item["mid"]);
         $parents = $catalog->getParents($categoryId);
         $node = "";
         foreach ($parents as $key => $parent) {
             if ($parent["url"] == "glavnaya") {
                 $node .= $parents[$key + 1]["url"] . "/";
                 break;
             }
         }
         $order["items"][$item["mid"]] = array_merge($material, $fields);
         $order["items"][$item["mid"]]["cnt"] = $item["cnt"];
         $order["items"][$item["mid"]]["node"] = $node;
     }
     return $order;
 }
Example #30
0
 public function action_getTree()
 {
     $id = Arr::get($_POST, 'id');
     $table = Arr::get($_POST, 'table', 'tree');
     $materials = new Model_Material($table);
     $tree = $materials->getTree($id);
     $view = View::factory('/admin/widgets/select')->bind('tree', $tree);
     echo $view;
 }