Пример #1
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;
 }
Пример #2
0
 public function action_load_price()
 {
     // Получение значения ячейки
     function get_cell_value($worksheet, $cell)
     {
         return $worksheet->getCell($cell)->getValue();
     }
     // Преобразование числового значения столбца в символьное
     function col_n2str($col_n)
     {
         return PHPExcel_Cell::stringFromColumnIndex($col_n - 1);
     }
     // Преобразование символьного значения столбца в числовое
     function col_str2n($col)
     {
         return PHPExcel_Cell::columnIndexFromString($col);
     }
     // Узнать уровень вложенности строки
     function get_level($worksheet, $row)
     {
         return $worksheet->getRowDimension($row)->getOutlineLevel();
     }
     $objPHPExcel = PHPExcel_IOFactory::load(DOCROOT . "/price.xls");
     $structure = array("name" => array("index" => "A", "type" => "chars", "title" => "Наименование", "ordering" => 1), "ed_izm" => array("index" => "N", "type" => "select", "title" => "Единица измерения", "ordering" => 2), "price" => array("index" => "O", "type" => "price", "title" => "Цена", "ordering" => 3));
     $num_structure = array_values($structure);
     $categories = array(array("id" => 0, "level" => -1, "name" => "root"));
     $materials = array();
     $category_id_counter = 1;
     // Счётчик для id категории
     $parent_category_id = 0;
     // id родительской категории
     //echo '<table border>';
     //echo "<tr><td>Id категории<td>Уровень<td>id родительской категории<td>Название категории</tr>";
     // Проход по листам
     foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
         $worksheet_title = $worksheet->getTitle();
         $max_row = $worksheet->getHighestRow();
         // максимальная строка
         $max_col = $worksheet->getHighestColumn();
         // максимальный столбец (буква)
         $max_col = col_str2n($max_col);
         // максимальный столбец (цифра)
         //echo "<p>Максимальная строка: " . $max_row . "</p>";
         //echo "<p>Максимальный столбец: " . $max_col . " (" . col_n2str($max_col) . ")</p>";
         $start_row = 12;
         // С какой строки начинаем?
         // Перебор строк
         for ($row = $start_row; $row <= $max_row; $row++) {
             $level = get_level($worksheet, $row);
             // Уровень вложенности
             // Строка является заголовком?
             if (!get_cell_value($worksheet, $num_structure[1]["index"] . $row)) {
                 $current_cell = "A" . $row;
                 // Адрес ячейки
                 $value = get_cell_value($worksheet, $current_cell);
                 // Название категории
                 $categories[$category_id_counter] = array("id" => $category_id_counter, "level" => $level, "name" => $value);
                 // Поиск родителя
                 for ($i = $category_id_counter; $i >= 0; $i--) {
                     if ($categories[$i]["level"] == $level - 1) {
                         $parent_category_id = $categories[$i]["id"];
                         break;
                     }
                 }
                 //echo "<tr><td>" . $category_id_counter . "<td>" . $level . "<td>" . $parent_category_id . "<td>" . $value;
                 $categories[$category_id_counter]["parent"] = $parent_category_id;
                 $category_id_counter++;
             } else {
                 //echo '<tr><td colspan="4"><table style="width:100%;" border><tr>';
                 foreach ($structure as $name => $el) {
                     $current_cell = $el["index"] . $row;
                     // Адрес ячейки
                     $value = get_cell_value($worksheet, $current_cell);
                     $material_data[$name] = $value;
                     //echo '<td>' . $value;
                 }
                 //echo "</table>";
                 $category_id = $category_id_counter - 1;
                 $material_data["category_id"] = $category_id;
                 if (!isset($categories[$category_id]["materials"])) {
                     $categories[$category_id]["materials"] = array();
                 }
                 $categories[$category_id]["materials"][] = $material_data;
                 $materials[] = $material_data;
             }
         }
         //echo "</table>";
         //var_dump($categories);
         //var_dump($materials);
         //echo "<hr>";
     }
     $gid = 1218;
     // id группы
     $model_material = new Model_Material('groups');
     $model_base = new Model_Base();
     $group = $model_material->getGroup($gid);
     $categories[0]["db_id"] = $gid;
     $categories[0]["name"] = $group["name"];
     $parent_id = 0;
     $insertdata = array();
     $fieldset = $model_material->getFieldsSet($gid);
     //$insert_categories = array();
     $current_level = 0;
     while (true) {
         $search_level_status = false;
         foreach ($categories as $category_id => $category_data) {
             if ($category_data["level"] == $current_level) {
                 $search_level_status = true;
                 // Поиск родителя
                 for ($i = $category_id; $i >= 0; $i--) {
                     if ($categories[$i]["level"] == $current_level - 1) {
                         $parent_id = $categories[$i]["db_id"];
                         break;
                     }
                 }
                 $insert_group_id = $model_material->groupInsert($parent_id, $parent_id, array('name' => $category_data["name"]));
                 $group_params = array();
                 foreach ($structure as $name => $param) {
                     $param_data = array_merge($param, array("name" => $name, "gid" => $insert_group_id));
                     $model_material->addParam($param_data);
                 }
                 $category_data["db_id"] = $insert_group_id;
                 if (isset($category_data["materials"])) {
                     $fieldset = $model_material->getFieldsSet($insert_group_id);
                     //var_dump($fieldset);
                     // Проход по материалам
                     foreach ($category_data["materials"] as $material) {
                         //var_dump($material);
                         $insertdata = array();
                         $insertdata['title'] = Request::clearText($material["name"]);
                         $insertdata['url'] = Request::str2url($material["name"]);
                         $insertdata['description'] = Request::clearText($material["name"]);
                         // Проход по параметрам
                         foreach ($fieldset as $field) {
                             if (isset($structure[$field["name"]])) {
                                 $insertdata[$field["type"] . '_' . $field["id"]] = $material[$field["name"]];
                                 switch ($field["type"]) {
                                     case "files":
                                         $insertdata[$field["type"] . '_' . $field["id"]] = array($material[$field["name"]]);
                                         break;
                                     case "photoalbum":
                                         $insertdata[$field["type"] . '_' . $field["id"]] = array($material[$field["name"]]);
                                         break;
                                     case "select":
                                         $insertdata[$field["type"] . '_' . $field["id"]] = array($material[$field["name"]]);
                                         break;
                                 }
                                 // Наценка 30%
                                 /*if ($field["type"] == "price") {
                                 			$insertdata[$field["type"].'_'.$field["id"]] = $material[$field["name"]] * 1.3;
                                 		}*/
                             }
                         }
                         echo "<pre>";
                         var_dump($insertdata);
                         echo "</pre>";
                         $result = $model_material->newMaterial($insertdata, $insert_group_id, TRUE);
                     }
                 }
                 //var_dump($category_data);
                 echo "<hr>";
                 $categories[$category_id] = $category_data;
             }
         }
         if (!$search_level_status) {
             break;
         }
         $current_level++;
     }
 }
Пример #3
0
 public function modify_fields($gid, $item, $config)
 {
     $materials = new Model_Material("groups");
     $fields = $materials->getFieldsSet($gid);
     // Атрибуты каталога
     $finish_fields = array();
     // Перебор атрибутов
     foreach ($fields as $field) {
         $field_name = $field["name"];
         $field_model = array("name" => $field_name, "title" => $field["title"]);
         if ($field["type"] == "select") {
             if (isset($item[$field_name])) {
                 $field_model["value"] = $item[$field_name][0]["value"];
                 if (isset($config[$field_name]["modify"])) {
                     $field_model = $config[$field_name]["modify"]($field_model);
                 }
             }
         }
         /*if ($field["type"] == "photoalbum") {
         
         				if (isset($item[$field_name])) {
         					
         					$field_model["value"] = $item[$field_name][0]["value"];
         
         					if (isset($config[$field_name]["modify"])) {
         						$field_model = $config[$field_name]["modify"]($field_model);
         					}
         
         				}
         
         			}*/
         if ($field["type"] == "price") {
             if (isset($item[$field_name])) {
                 $field_model["value"] = number_format($item[$field_name], 0, "", " ");
                 if (isset($config[$field_name]["modify"])) {
                     $field_model = $config[$field_name]["modify"]($field_model);
                 }
             }
         }
         if ($field["type"] == "chars") {
             if (isset($item[$field_name])) {
                 $field_model["value"] = Text::limit_words($item[$field_name], 40);
                 if (isset($config[$field_name]["modify"])) {
                     $field_model = $config[$field_name]["modify"]($field_model);
                 }
             }
         }
         $field_visible = true;
         if (isset($config[$field_name])) {
             if (isset($config[$field_name]["visible"])) {
                 if (!$config[$field_name]["visible"]) {
                     $field_visible = false;
                 }
             }
         }
         // Отображать поле?
         if ($field_visible) {
             $finish_fields[$field_name] = $field_model;
         }
     }
     return $finish_fields;
 }
Пример #4
0
 public function uploadFile($gid)
 {
     $material = new Model_Material('groups');
     $data = $material->getFullMaterials2($gid, 10000, 0);
     $phpexcel = new PHPExcel();
     // Создаём объект PHPExcel
     $page = $phpexcel->setActiveSheetIndex(0);
     // Делаем активной первую страницу и получаем её
     $letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
     $header = array('name' => 'Название');
     $fields = $material->getFieldsSet($gid);
     foreach ($fields as $field) {
         $header[$field['name']] = $field['title'];
     }
     $fields = $header;
     $header = array_values($fields);
     for ($i = 0; $i < count($header); ++$i) {
         $page->setCellValue($letters[$i] . "1", $header[$i]);
     }
     //echo '<pre>';
     $row = 2;
     foreach ($data as $item) {
         $col = 0;
         foreach ($fields as $key => $field) {
             if (isset($item[$key])) {
                 if (!is_array($item[$key])) {
                     $page->setCellValue($letters[$col] . $row, $item[$key]);
                 } else {
                     $str = '';
                     $s = 1;
                     foreach ($item[$key] as $val) {
                         $str .= Arr::get($val, 'value');
                         if ($s < count($item[$key])) {
                             $str .= ', ';
                         }
                         ++$s;
                     }
                     $page->setCellValue($letters[$col] . $row, $str);
                 }
             }
             ++$col;
         }
         ++$row;
     }
     //        echo '</pre>';
     $page->setTitle("Страница 1");
     // Заголовок делаем "Example"
     /* Начинаем готовиться к записи информации в xlsx-файл */
     $objWriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel2007');
     /* Записываем в файл */
     $group = $material->getGroup($gid);
     $base = new Model_Base();
     $filename = $group['id'] . '_' . $base->str2url(Text::limit_chars($group['name'], 20)) . '_' . date("Y.m.d H-i-s");
     $objWriter->save(DOCROOT . "/img/user/export/" . $filename . ".xlsx");
     return array('Файл ' . $filename . ' успешно создан в директории <a href="/admin/files/export">/export/</a>');
 }
Пример #5
0
 public function action_index($options = array("catalog_id" => 4, "items_position_type" => "half"))
 {
     $this->setopt(array("name" => "catalog_id", "description" => "Ид каталога", "default" => $options["catalog_id"]));
     $this->setopt(array("name" => "items_position_type", "description" => "Способ отображения item'ов", "default" => $options["items_position_type"]));
     // --- tests ---------------------------------------------------------------
     $model_module = new Model_Module();
     $module = $model_module->get_module(176);
     $module->get_options();
     //$module->test(1382);
     $module->set(array("action" => "index"));
     // --- /tests --------------------------------------------------------------
     $model = array();
     $qdata = array();
     $param_array = array();
     $materials = new Model_Material('groups');
     $config = Kohana::$config->load('main')->site;
     $pageNum = intval(Arr::get($_GET, 'page', 0));
     $param = $this->getopt("catalog_id");
     //$param = $this->request->param('id');
     //PC::debug($pageNum);
     $params = explode('/', $param);
     $gid = $params[0];
     foreach ($params as $paramName) {
         if (preg_match("/page(\\d)/", $paramName)) {
             $pageNum = str_replace('page', '', $paramName);
         }
     }
     $template = $this->request->param('template');
     if ($template) {
         $this->template = View::factory('widgets/' . $template);
     }
     //search for template
     $widget = new Model_Widget();
     $widgetData = $this->widget_data;
     if ($widgetData['template']) {
         $this->template = View::factory('widgets/' . $widgetData['template']);
     }
     $query = Arr::get($widgetData, 'query');
     if ($query != '') {
         $queries = explode('&', $query);
         foreach ($queries as $q) {
             $rr = explode('=', $q);
             if (!isset($param_array[$rr[0]])) {
                 $qdata[$rr[0]][] = $rr[1];
             }
         }
     }
     //counters
     $group = $materials->getGroup($gid);
     $material_count = $group['materials'];
     $search_string = Arr::get($param_array, 'art', NULL);
     //проверяем кодировку
     $res = mb_detect_encoding($search_string, array('UTF-8', 'Windows-1251'));
     if ($res != 'UTF-8') {
         $search_string = iconv($res, 'UTF-8', $search_string);
     }
     if (isset($param_array['go'])) {
         unset($param_array['go']);
     }
     if (isset($param_array['price'])) {
         $pricer = explode(';', $param_array['price']);
         $qdata['price_from'] = intval(Arr::get($pricer, 0) * 1000);
         $qdata['price_to'] = intval(Arr::get($pricer, 1) * 1000);
         unset($param_array['price']);
     }
     if (isset($param_array['sort'])) {
         $qdata['sort'] = addslashes($param_array['sort']);
     }
     $qparams = array_keys($param_array);
     //получаем доступные параметры
     $params = $materials->getFieldsSet($gid);
     foreach ($params as $param) {
         if ($param['for_filters'] == 1) {
             if (in_array($param['name'], $qparams)) {
                 switch ($param['type']) {
                     case 'select':
                         if (is_array($param_array[$param['name']])) {
                             $selvalues = $materials->getSelectValues($param['id']);
                             $vals = array_values($param_array[$param['name']]);
                             foreach ($selvalues as $value) {
                                 if (in_array($value->value, $vals)) {
                                     $qdata[$param['name']][] = $value->value;
                                 }
                             }
                         }
                         break;
                     case 'price':
                         $arr = explode(';', $param_array[$param['name']]);
                         $qdata[$param['name'] . '_from'] = intval(Arr::get($arr, 0));
                         $qdata[$param['name'] . '_to'] = intval(Arr::get($arr, 1));
                         break;
                     case 'chars':
                         $qdata[$param['name']] = addslashes($param_array[$param['name']]);
                         break;
                 }
             }
         }
     }
     //получаем данные для сортировки
     //$this->template->searchtext = $search_string;
     //$this->template->search_params = $param_array;
     // Сколько найдено материалов?
     $material_count = $materials->getCountFullMaterials2($gid, $search_string, $qdata);
     // Номер текущей страницы
     $current_page = 1;
     if (isset($_GET["page"])) {
         //if ($_GET["page"] !== 0)
         $current_page = $_GET["page"];
     }
     // Вывод всех материалов на одной странице
     $model["limit"]["text"] = "Показать все на странице";
     $model["limit"]["href"] = URL::query(array("limit" => false, "page" => 1));
     $material_limit = 24;
     if (isset($_GET["limit"])) {
         if (!$_GET["limit"]) {
             $model["limit"]["text"] = "Постраничное разделение";
             $model["limit"]["href"] = URL::query(array("limit" => true));
             $material_limit = $material_count;
             //$current_page = 1;
         }
     } else {
         $material_limit = 24;
         // Материалов на странице
     }
     $max_page = ceil($material_count / $material_limit);
     // Максимальная страница
     $material_offset = $material_limit * ($current_page - 1);
     // Смещение материалов
     // страница существует
     if ($current_page <= $max_page) {
         $items = $materials->getFullMaterials2($gid, $material_limit, $material_offset, $search_string, $qdata);
     } else {
         $items = [];
     }
     // Хлебные крошки
     $this->load_module("breadcrumb", "/widgets/Breadcrumb/index");
     // --- Выбор способа отображения item'ов ---------------------------------------------------
     $model["items_position_type"] = Arr::get($_COOKIE, "items_position_type", $this->getopt("items_position_type"));
     $this->load_module("item_position", "/widgets/ItemPosition/index");
     // --- /Выбор способа отображения item'ов ---------------------------------------------------
     // --- Пагинация --------------------------------------------------------------------------
     $this->load_module("pagination", "/widgets/Pagination/index", array("current" => $current_page, "max" => $max_page, "count" => 5));
     // --- /Пагинация -------------------------------------------------------------------------
     // Для корзины
     echo '<script>var items = JSON.parse(\'' . json_encode($items) . '\');</script>';
     $model["items"] = $items;
     // Кол-во найденых материалов
     $model["material_count"] = $material_count;
     // Изменение модели
     foreach ($model["items"] as $item_id => $item) {
         $new_model = array();
         // id материала
         $new_model["id"] = $item_id;
         // Формат цены
         $new_model["price"] = number_format($item["price"], 0, '', ' ');
         // Формат старой цены
         if (isset($item['old_price'])) {
             $new_model["old_price"] = number_format($item["old_price"], 0, '', ' ');
         }
         // Изображение
         if (isset($item['photos'][0])) {
             $new_model["photo"] = Route::url('miniimg3', array('filename' => $item['photos'][0]['value']));
         } else {
             $new_model["photo"] = Route::url('miniimg3', array('filename' => '/img/noimg.png'));
         }
         // Акция
         if (isset($item["stock"])) {
             $new_model["stock"] = " " . $item["stock"][0]["value"];
         }
         //$new_model["stock"] = "new"; //test
         // Ссылка на материал
         $new_model["href"] = "/" . $item["node"] . $item["url"] . ".html";
         // --- Обрезаем длинные поля --------------------------------------------------------
         // Название
         $new_model["name"] = $item["name"];
         if (strlen($item["name"]) > 80) {
             $new_model["name"] = Text::limit_chars($item["name"], 77);
         }
         // Описание
         $new_model["description"] = $item["description"];
         if (strlen($item["description"]) > 80) {
             $new_model["description"] = Text::limit_chars($item["description"], 77);
         }
         // --- /Обрезаем длинные поля -------------------------------------------------------
         $model["items"][$item_id] = array_merge($model["items"][$item_id], $new_model);
     }
     if ($material_count == 0) {
         $Menu = new Controller_Widgets_Menu($this->request, $this->response);
         $Menu->action_graph(array("parent_id" => Arr::get($GLOBALS, 'categoryId')));
         $this->body($Menu->get_body());
         /*$this->load_module("graph_menu", "/widgets/Graph_Menu/index", array(
         			"parent_id" => Arr::get($GLOBALS, 'categoryId'),
         		));*/
     } else {
         $this->set_template("/widgets/w_catalog.php", "twig")->render($model)->body();
     }
 }
Пример #6
0
 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);
     }
 }