Advertisement
Guest User

Untitled

a guest
Aug 20th, 2012
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.96 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Simpla CMS
  5.  *
  6.  * @copyright   2011 Denis Pikusov
  7.  * @link        http://simplacms.ru
  8.  * @author      Denis Pikusov
  9.  *
  10.  */
  11.  
  12. require_once('Simpla.php');
  13.  
  14. class Categories extends Simpla
  15. {
  16.     // Список указателей на категории в дереве категорий (ключ = id категории)
  17.     private $all_categories;
  18.     // Дерево категорий
  19.     private $categories_tree;
  20.  
  21.     // Функция возвращает массив категорий
  22.     public function get_categories($filter = array())
  23.     {
  24.         if(!isset($this->categories_tree))
  25.             $this->init_categories();
  26.  
  27.         if(!empty($filter['product_id']))
  28.         {
  29.             $query = $this->db->placehold("SELECT category_id FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$filter['product_id']);
  30.             $this->db->query($query);
  31.             $categories_ids = $this->db->results('category_id');
  32.             $result = array();
  33.             foreach($categories_ids as $id)
  34.                 if(isset($this->all_categories[$id]))
  35.                     $result[$id] = $this->all_categories[$id];
  36.             return $result;
  37.         }
  38.        
  39.         return $this->all_categories;
  40.     }  
  41.  
  42.     // Функция возвращает id категорий для заданного товара
  43.     public function get_product_categories($product_id)
  44.     {
  45.         $query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$product_id);
  46.         $this->db->query($query);
  47.         return $this->db->results();
  48.     }  
  49.  
  50.     // Функция возвращает id категорий для всех товаров
  51.     public function get_products_categories()
  52.     {
  53.         $query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories ORDER BY position");
  54.         $this->db->query($query);
  55.         return $this->db->results();
  56.     }  
  57.  
  58.     // Функция возвращает дерево категорий
  59.     public function get_categories_tree()
  60.     {
  61.         if(!isset($this->categories_tree))
  62.             $this->init_categories();
  63.            
  64.         return $this->categories_tree;
  65.     }
  66.  
  67.     // Функция возвращает заданную категорию
  68.     public function get_category($id)
  69.     {
  70.         if(!isset($this->all_categories))
  71.             $this->init_categories();
  72.         if(is_int($id) && array_key_exists(intval($id), $this->all_categories))
  73.             return $category = $this->all_categories[intval($id)];
  74.         elseif(is_string($id))
  75.             foreach ($this->all_categories as $category)
  76.                 if ($category->url == $id)
  77.                     return $this->get_category((int)$category->id);
  78.        
  79.         return false;
  80.     }
  81.    
  82.     // Добавление категории
  83.     public function add_category($category)
  84.     {
  85.         $category = (array)$category;
  86.         if(empty($category['url']))
  87.         {
  88.             $category['url'] = preg_replace("/[\s]+/ui", '_', $category['name']);
  89.             $category['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $category['url']));
  90.         }  
  91.  
  92.         // Если есть категория с таким URL, добавляем к нему число
  93.         while($this->get_category((string)$category['url']))
  94.         {
  95.             if(preg_match('/(.+)_([0-9]+)$/', $category['url'], $parts))
  96.                 $category['url'] = $parts[1].'_'.($parts[2]+1);
  97.             else
  98.                 $category['url'] = $category['url'].'_2';
  99.         }
  100.  
  101.         $this->db->query("INSERT INTO __categories SET ?%", $category);
  102.         $id = $this->db->insert_id();
  103.         $this->db->query("UPDATE __categories SET position=id WHERE id=?", $id);       
  104.         $this->init_categories();      
  105.         return $id;
  106.     }
  107.    
  108.     // Изменение категории
  109.     public function update_category($id, $category)
  110.     {
  111.         $query = $this->db->placehold("UPDATE __categories SET ?% WHERE id=? LIMIT 1", $category, intval($id));
  112.         $this->db->query($query);
  113.         $this->init_categories();
  114.         return $id;
  115.     }
  116.    
  117.     // Удаление категории
  118.     public function delete_category($id)
  119.     {
  120.         if(!$category = $this->get_category(intval($id)))
  121.             return false;
  122.         foreach($category->children as $id)
  123.         {
  124.             if(!empty($id))
  125.             {
  126.                 $this->delete_image($id);
  127.                 $query = $this->db->placehold("DELETE FROM __categories WHERE id=? LIMIT 1", $id);
  128.                 $this->db->query($query);
  129.                 $query = $this->db->placehold("DELETE FROM __products_categories WHERE category_id=?", $id);
  130.                 $this->db->query($query);
  131.                 $this->init_categories();          
  132.             }
  133.         }
  134.         return true;
  135.     }
  136.    
  137.     // Добавить категорию к заданному товару
  138.     public function add_product_category($product_id, $category_id, $position=0)
  139.     {
  140.         $query = $this->db->placehold("INSERT IGNORE INTO __products_categories SET product_id=?, category_id=?, position=?", $product_id, $category_id, $position);
  141.         $this->db->query($query);
  142.     }
  143.  
  144.     // Удалить категорию заданного товара
  145.     public function delete_product_category($product_id, $category_id)
  146.     {
  147.         $query = $this->db->placehold("DELETE FROM __products_categories WHERE product_id=? AND category_id=? LIMIT 1", intval($product_id), intval($category_id));
  148.         $this->db->query($query);
  149.     }
  150.    
  151.     // Удалить изображение категории
  152.     public function delete_image($category_id)
  153.     {
  154.         $query = $this->db->placehold("SELECT image FROM __categories WHERE id=?", $category_id);
  155.         $this->db->query($query);
  156.         $filename = $this->db->result('image');
  157.         if(!empty($filename))
  158.         {
  159.             $query = $this->db->placehold("UPDATE __categories SET image=NULL WHERE id=?", $category_id);
  160.             $this->db->query($query);
  161.             $query = $this->db->placehold("SELECT count(*) as count FROM __categories WHERE image=? LIMIT 1", $filename);
  162.             $this->db->query($query);
  163.             $count = $this->db->result('count');
  164.             if($count == 0)
  165.             {          
  166.                 @unlink($this->config->root_dir.$this->config->categories_images_dir.$filename);       
  167.             }
  168.             $this->init_categories();
  169.         }
  170.     }
  171.  
  172.  
  173.     // Инициализация категорий, после которой категории будем выбирать из локальной переменной
  174.     private function init_categories()
  175.     {
  176.         // Дерево категорий
  177.         $tree = new stdClass();
  178.         $tree->subcategories = array();
  179.        
  180.         // Указатели на узлы дерева
  181.         $pointers = array();
  182.         $pointers[0] = &$tree;
  183.         $pointers[0]->path = array();
  184.        
  185.         // Выбираем все категории
  186.         //      $query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position
  187.         //                                  FROM __categories c ORDER BY c.parent_id, c.position");
  188.         $query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position, COUNT(p.id) as products_count
  189.                                        FROM __categories c LEFT JOIN __products_categories pc ON pc.category_id=c.id LEFT JOIN __products p ON p.id=pc.product_id AND p.visible GROUP BY c.id ORDER BY c.parent_id, c.position");
  190.         $this->db->query($query);
  191.         $categories = $this->db->results();
  192.                
  193.         $finish = false;
  194.         // Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть
  195.         while(!empty($categories)  && !$finish)
  196.         {
  197.             $flag = false;
  198.             // Проходим все выбранные категории
  199.             foreach($categories as $k=>$category)
  200.             {
  201.                 if(isset($pointers[$category->parent_id]))
  202.                 {
  203.                     // В дерево категорий (через указатель) добавляем текущую категорию
  204.                     $pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category;
  205.                    
  206.                     // Путь к текущей категории
  207.                     $curr = clone($pointers[$category->id]);
  208.                     $pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr));
  209.                    
  210.                     // Убираем использованную категорию из массива категорий
  211.                     unset($categories[$k]);
  212.                     $flag = true;
  213.                 }
  214.             }
  215.             if(!$flag) $finish = true;
  216.         }
  217.        
  218.         // Для каждой категории id всех ее деток узнаем
  219.         $ids = array_reverse(array_keys($pointers));
  220.         foreach($ids as $id)
  221.         {
  222.             if($id>0)
  223.             {
  224.                 $pointers[$id]->children[] = $id;
  225.  
  226.                 if(isset($pointers[$pointers[$id]->parent_id]->children))
  227.                     $pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children);
  228.                 else
  229.                     $pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children;
  230.                    
  231.                 // Добавляем количество товаров к родительской категории, если текущая видима
  232.                 //if(isset($pointers[$pointers[$id]->parent_id]) && $pointers[$id]->visible)
  233.                 //  $pointers[$pointers[$id]->parent_id]->products_count += $pointers[$id]->products_count;
  234.             }
  235.         }
  236.         unset($pointers[0]);
  237.  
  238.         $this->categories_tree = $tree->subcategories;
  239.         $this->all_categories = $pointers; 
  240.     }
  241. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement