From 96360f1f38d59d0d50b560fba61917d0823afe17 Mon Sep 17 00:00:00 2001 From: Erko Evgen Date: Thu, 17 Mar 2016 12:01:49 +0200 Subject: [PATCH 1/5] add .editorconfig --- .editorconfig | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..db8bf82 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = tab +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_size = 4 From f97655e041adf6c6c33ffc0c1372f7618aedbcb2 Mon Sep 17 00:00:00 2001 From: Erko Evgen Date: Thu, 17 Mar 2016 12:03:27 +0200 Subject: [PATCH 2/5] code formatting for simpla/*Admin.php --- simpla/BackupAdmin.php | 82 ++--- simpla/BlogAdmin.php | 48 +-- simpla/BrandAdmin.php | 98 +++--- simpla/BrandsAdmin.php | 35 ++- simpla/CategoriesAdmin.php | 65 ++-- simpla/CategoryAdmin.php | 99 +++--- simpla/CommentsAdmin.php | 183 +++++------ simpla/CouponAdmin.php | 114 +++---- simpla/CouponsAdmin.php | 37 +-- simpla/CurrencyAdmin.php | 242 +++++++-------- simpla/DeliveriesAdmin.php | 118 ++++---- simpla/DeliveryAdmin.php | 122 ++++---- simpla/ExportAdmin.php | 45 +-- simpla/ExportUsersAdmin.php | 54 ++-- simpla/FeatureAdmin.php | 117 +++---- simpla/FeaturesAdmin.php | 167 +++++----- simpla/FeedbacksAdmin.php | 147 ++++----- simpla/GroupAdmin.php | 110 ++++--- simpla/GroupsAdmin.php | 73 +++-- simpla/ImagesAdmin.php | 199 ++++++------ simpla/ImportAdmin.php | 230 +++++++------- simpla/IndexAdmin.php | 338 +++++++++++---------- simpla/LicenseAdmin.php | 99 +++--- simpla/ManagerAdmin.php | 144 ++++----- simpla/ManagersAdmin.php | 87 +++--- simpla/OrderAdmin.php | 512 +++++++++++++++---------------- simpla/OrdersAdmin.php | 298 +++++++++--------- simpla/OrdersLabelAdmin.php | 86 +++--- simpla/OrdersLabelsAdmin.php | 95 +++--- simpla/PageAdmin.php | 157 +++++----- simpla/PagesAdmin.php | 148 ++++----- simpla/PaymentMethodAdmin.php | 145 ++++----- simpla/PaymentMethodsAdmin.php | 120 ++++---- simpla/PostAdmin.php | 136 +++++---- simpla/ProductAdmin.php | 236 ++++++++------- simpla/ProductsAdmin.php | 535 +++++++++++++++++---------------- simpla/SettingsAdmin.php | 204 +++++++------ simpla/StatsAdmin.php | 37 ++- simpla/StylesAdmin.php | 163 +++++----- simpla/TemplatesAdmin.php | 163 +++++----- simpla/ThemeAdmin.php | 284 ++++++++--------- simpla/UserAdmin.php | 174 ++++++----- simpla/UsersAdmin.php | 183 +++++------ 43 files changed, 3535 insertions(+), 3194 deletions(-) diff --git a/simpla/BackupAdmin.php b/simpla/BackupAdmin.php index 743ee5a..385cba8 100755 --- a/simpla/BackupAdmin.php +++ b/simpla/BackupAdmin.php @@ -1,4 +1,13 @@ -errorInfo(true)); } - $this->design->assign('message_success', 'created'); - + $this->design->assign('message_success', 'created'); + break; - } - case 'restore': - { - $name = $this->request->post('name'); + } + case 'restore': + { + $name = $this->request->post('name'); $archive = $dir.$name; $zip = new PclZip($archive); - + $this->clean_dir('files'); - + if (!$zip->extract(PCLZIP_OPT_PATH, '', PCLZIP_OPT_BY_PREG, "/^files\//", PCLZIP_CB_POST_EXTRACT, 'myPostExtractCallBack')) { trigger_error('Не могу разархивировать '.$zip->errorInfo(true)); @@ -60,18 +69,18 @@ public function fetch() { $this->db->restore($dir.'simpla.sql'); unlink($dir.'simpla.sql'); - $this->design->assign('message_success', 'restored'); + $this->design->assign('message_success', 'restored'); } - break; - } - case 'delete': - { - $names = $this->request->post('check'); - foreach($names as $name) - unlink($dir.$name); - break; - } - } + break; + } + case 'delete': + { + $names = $this->request->post('check'); + foreach($names as $name) + unlink($dir.$name); + break; + } + } } $backup_files = glob($dir."*.zip"); @@ -93,26 +102,27 @@ public function fetch() $this->design->assign('message_error', 'no_permission'); $this->design->assign('backups', $backups); + return $this->design->fetch('backup.tpl'); } private function clean_dir($path) { - $path= rtrim($path, '/').'/'; - $handle = opendir($path); - for (;false !== ($file = readdir($handle));) - if($file != "." and $file != ".." ) - { - $fullpath= $path.$file; - if( is_dir($fullpath) ) - { - $this->clean_dir($fullpath); - rmdir($fullpath); - } - else - unlink($fullpath); - } - closedir($handle); + $path= rtrim($path, '/').'/'; + $handle = opendir($path); + for (;false !== ($file = readdir($handle));) + if($file != "." and $file != ".." ) + { + $fullpath= $path.$file; + if( is_dir($fullpath) ) + { + $this->clean_dir($fullpath); + rmdir($fullpath); + } + else + unlink($fullpath); + } + closedir($handle); } } diff --git a/simpla/BlogAdmin.php b/simpla/BlogAdmin.php index bf19114..6009654 100755 --- a/simpla/BlogAdmin.php +++ b/simpla/BlogAdmin.php @@ -3,12 +3,12 @@ /** * Simpla CMS * - * @copyright 2011 Denis Pikusov + * @copyright 2016 Denis Pikusov * @link http://simplacms.ru * @author Denis Pikusov * */ - + require_once('api/Simpla.php'); class BlogAdmin extends Simpla @@ -21,31 +21,34 @@ public function fetch() // Действия с выбранными $ids = $this->request->post('check'); if(is_array($ids)) - switch($this->request->post('action')) { - case 'disable': - { - $this->blog->update_post($ids, array('visible'=>0)); - break; - } - case 'enable': - { - $this->blog->update_post($ids, array('visible'=>1)); - break; - } - case 'delete': - { - foreach($ids as $id) - $this->blog->delete_post($id); - break; - } - } + switch($this->request->post('action')) + { + case 'disable': + { + $this->blog->update_post($ids, array('visible'=>0)); + break; + } + case 'enable': + { + $this->blog->update_post($ids, array('visible'=>1)); + break; + } + case 'delete': + { + foreach($ids as $id) + $this->blog->delete_post($id); + break; + } + } + } + } $filter = array(); - $filter['page'] = max(1, $this->request->get('page', 'integer')); + $filter['page'] = max(1, $this->request->get('page', 'integer')); $filter['limit'] = 20; - + // Поиск $keyword = $this->request->get('keyword', 'string'); if(!empty($keyword)) @@ -66,6 +69,7 @@ public function fetch() $this->design->assign('current_page', $filter['page']); $this->design->assign('posts', $posts); + return $this->design->fetch('blog.tpl'); } } diff --git a/simpla/BrandAdmin.php b/simpla/BrandAdmin.php index 5124c33..052b2f7 100755 --- a/simpla/BrandAdmin.php +++ b/simpla/BrandAdmin.php @@ -1,18 +1,23 @@ request->method('post')) { $brand->id = $this->request->post('id', 'integer'); @@ -26,43 +31,43 @@ function fetch() // Не допустить одинаковые URL разделов. if(($c = $this->brands->get_brand($brand->url)) && $c->id!=$brand->id) - { - $this->design->assign('message_error', 'url_exists'); - } - elseif(empty($brand->name)) - { - $this->design->assign('message_error', 'name_empty'); - } - elseif(empty($brand->url)) - { - $this->design->assign('message_error', 'url_empty'); - } - else - { - if(empty($brand->id)) + { + $this->design->assign('message_error', 'url_exists'); + } + elseif(empty($brand->name)) + { + $this->design->assign('message_error', 'name_empty'); + } + elseif(empty($brand->url)) + { + $this->design->assign('message_error', 'url_empty'); + } + else + { + if(empty($brand->id)) { - $brand->id = $this->brands->add_brand($brand); + $brand->id = $this->brands->add_brand($brand); $this->design->assign('message_success', 'added'); - } - else - { - $this->brands->update_brand($brand->id, $brand); + } + else + { + $this->brands->update_brand($brand->id, $brand); $this->design->assign('message_success', 'updated'); - } - // Удаление изображения - if($this->request->post('delete_image')) - { - $this->brands->delete_image($brand->id); - } - // Загрузка изображения - $image = $this->request->files('image'); - if(!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions)) - { - $this->brands->delete_image($brand->id); - move_uploaded_file($image['tmp_name'], $this->root_dir.$this->config->brands_images_dir.$image['name']); - $this->brands->update_brand($brand->id, array('image'=>$image['name'])); - } - $brand = $this->brands->get_brand($brand->id); + } + // Удаление изображения + if($this->request->post('delete_image')) + { + $this->brands->delete_image($brand->id); + } + // Загрузка изображения + $image = $this->request->files('image'); + if(!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions)) + { + $this->brands->delete_image($brand->id); + move_uploaded_file($image['tmp_name'], $this->root_dir.$this->config->brands_images_dir.$image['name']); + $this->brands->update_brand($brand->id, array('image'=>$image['name'])); + } + $brand = $this->brands->get_brand($brand->id); } } else @@ -71,7 +76,8 @@ function fetch() $brand = $this->brands->get_brand($brand->id); } - $this->design->assign('brand', $brand); - return $this->design->fetch('brand.tpl'); - } -} + $this->design->assign('brand', $brand); + + return $this->design->fetch('brand.tpl'); + } +} diff --git a/simpla/BrandsAdmin.php b/simpla/BrandsAdmin.php index 96e9b40..d0c0e11 100755 --- a/simpla/BrandsAdmin.php +++ b/simpla/BrandsAdmin.php @@ -1,13 +1,22 @@ -request->method('post')) { @@ -15,21 +24,21 @@ function fetch() $ids = $this->request->post('check'); if(is_array($ids)) - switch($this->request->post('action')) - { - case 'delete': + switch($this->request->post('action')) { - foreach($ids as $id) - $this->brands->delete_brand($id); - break; + case 'delete': + { + foreach($ids as $id) + $this->brands->delete_brand($id); + break; + } } - } - } + } $brands = $this->brands->get_brands(); - + $this->design->assign('brands', $brands); + return $this->body = $this->design->fetch('brands.tpl'); } } - diff --git a/simpla/CategoriesAdmin.php b/simpla/CategoriesAdmin.php index 2db2cdd..19f93ed 100755 --- a/simpla/CategoriesAdmin.php +++ b/simpla/CategoriesAdmin.php @@ -1,50 +1,59 @@ -request->method('post')) { // Действия с выбранными $ids = $this->request->post('check'); if(is_array($ids)) - switch($this->request->post('action')) - { - case 'disable': - { - foreach($ids as $id) - $this->categories->update_category($id, array('visible'=>0)); - break; - } - case 'enable': - { - foreach($ids as $id) - $this->categories->update_category($id, array('visible'=>1)); - break; - } - case 'delete': - { - $this->categories->delete_category($ids); - break; - } - } - + switch($this->request->post('action')) + { + case 'disable': + { + foreach($ids as $id) + $this->categories->update_category($id, array('visible'=>0)); + break; + } + case 'enable': + { + foreach($ids as $id) + $this->categories->update_category($id, array('visible'=>1)); + break; + } + case 'delete': + { + $this->categories->delete_category($ids); + break; + } + } + // Сортировка $positions = $this->request->post('positions'); - $ids = array_keys($positions); + $ids = array_keys($positions); sort($positions); foreach($positions as $i=>$position) - $this->categories->update_category($ids[$i], array('position'=>$position)); + $this->categories->update_category($ids[$i], array('position'=>$position)); + + } - } - $categories = $this->categories->get_categories_tree(); $this->design->assign('categories', $categories); + return $this->design->fetch('categories.tpl'); } } diff --git a/simpla/CategoryAdmin.php b/simpla/CategoryAdmin.php index 4692ae9..6b8452f 100755 --- a/simpla/CategoryAdmin.php +++ b/simpla/CategoryAdmin.php @@ -1,17 +1,22 @@ request->method('post')) { @@ -29,43 +34,43 @@ function fetch() // Не допустить одинаковые URL разделов. if(($c = $this->categories->get_category($category->url)) && $c->id!=$category->id) - { - $this->design->assign('message_error', 'url_exists'); - } - elseif(empty($category->name)) - { - $this->design->assign('message_error', 'name_empty'); - } - elseif(empty($category->url)) - { - $this->design->assign('message_error', 'url_empty'); - } - else - { - if(empty($category->id)) + { + $this->design->assign('message_error', 'url_exists'); + } + elseif(empty($category->name)) + { + $this->design->assign('message_error', 'name_empty'); + } + elseif(empty($category->url)) + { + $this->design->assign('message_error', 'url_empty'); + } + else + { + if(empty($category->id)) { - $category->id = $this->categories->add_category($category); + $category->id = $this->categories->add_category($category); $this->design->assign('message_success', 'added'); - } - else - { - $this->categories->update_category($category->id, $category); + } + else + { + $this->categories->update_category($category->id, $category); $this->design->assign('message_success', 'updated'); - } - // Удаление изображения - if($this->request->post('delete_image')) - { - $this->categories->delete_image($category->id); - } - // Загрузка изображения - $image = $this->request->files('image'); - if(!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions)) - { - $this->categories->delete_image($category->id); - move_uploaded_file($image['tmp_name'], $this->root_dir.$this->config->categories_images_dir.$image['name']); - $this->categories->update_category($category->id, array('image'=>$image['name'])); - } - $category = $this->categories->get_category(intval($category->id)); + } + // Удаление изображения + if($this->request->post('delete_image')) + { + $this->categories->delete_image($category->id); + } + // Загрузка изображения + $image = $this->request->files('image'); + if(!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions)) + { + $this->categories->delete_image($category->id); + move_uploaded_file($image['tmp_name'], $this->root_dir.$this->config->categories_images_dir.$image['name']); + $this->categories->update_category($category->id, array('image'=>$image['name'])); + } + $category = $this->categories->get_category(intval($category->id)); } } else @@ -74,11 +79,11 @@ function fetch() $category = $this->categories->get_category($category->id); } - $categories = $this->categories->get_categories_tree(); $this->design->assign('category', $category); - $this->design->assign('categories', $categories); - return $this->design->fetch('category.tpl'); - } -} + $this->design->assign('categories', $categories); + + return $this->design->fetch('category.tpl'); + } +} diff --git a/simpla/CommentsAdmin.php b/simpla/CommentsAdmin.php index 05c73f3..f81a411 100755 --- a/simpla/CommentsAdmin.php +++ b/simpla/CommentsAdmin.php @@ -1,107 +1,110 @@ -request->get('page', 'integer')); - - $filter['limit'] = 40; - - // Тип - $type = $this->request->get('type', 'string'); - if($type) - { - $filter['type'] = $type; - $this->design->assign('type', $type); - } + public function fetch() + { - // Поиск - $keyword = $this->request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } + $filter = array(); + $filter['page'] = max(1, $this->request->get('page', 'integer')); + + $filter['limit'] = 40; - - // Обработка действий - if($this->request->method('post')) - { - - // Действия с выбранными - $ids = $this->request->post('check'); - if(!empty($ids) && is_array($ids)) - switch($this->request->post('action')) + // Тип + $type = $this->request->get('type', 'string'); + if($type) { - case 'approve': - { - foreach($ids as $id) - $this->comments->update_comment($id, array('approved'=>1)); - break; - } - case 'delete': - { - foreach($ids as $id) - $this->comments->delete_comment($id); - break; - } - } - - } + $filter['type'] = $type; + $this->design->assign('type', $type); + } - + // Поиск + $keyword = $this->request->get('keyword', 'string'); + if(!empty($keyword)) + { + $filter['keyword'] = $keyword; + $this->design->assign('keyword', $keyword); + } - // Отображение - $comments_count = $this->comments->count_comments($filter); - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $filter['limit'] = $comments_count; - $comments = $this->comments->get_comments($filter); - - // Выбирает объекты, которые прокомментированы: - $products_ids = array(); - $posts_ids = array(); - foreach($comments as $comment) - { - if($comment->type == 'product') - $products_ids[] = $comment->object_id; - if($comment->type == 'blog') - $posts_ids[] = $comment->object_id; - } - $products = array(); - foreach($this->products->get_products(array('id'=>$products_ids)) as $p) - $products[$p->id] = $p; - $posts = array(); - foreach($this->blog->get_posts(array('id'=>$posts_ids)) as $p) - $posts[$p->id] = $p; - - foreach($comments as &$comment) - { - if($comment->type == 'product' && isset($products[$comment->object_id])) - $comment->product = $products[$comment->object_id]; - if($comment->type == 'blog' && isset($posts[$comment->object_id])) - $comment->post = $posts[$comment->object_id]; - } - - - $this->design->assign('pages_count', ceil($comments_count/$filter['limit'])); - $this->design->assign('current_page', $filter['page']); + // Обработка действий + if($this->request->method('post')) + { + + // Действия с выбранными + $ids = $this->request->post('check'); + if(!empty($ids) && is_array($ids)) + switch($this->request->post('action')) + { + case 'approve': + { + foreach($ids as $id) + $this->comments->update_comment($id, array('approved'=>1)); + break; + } + case 'delete': + { + foreach($ids as $id) + $this->comments->delete_comment($id); + break; + } + } + + } - $this->design->assign('comments', $comments); - $this->design->assign('comments_count', $comments_count); + // Отображение + $comments_count = $this->comments->count_comments($filter); + // Показать все страницы сразу + if($this->request->get('page') == 'all') + $filter['limit'] = $comments_count; + $comments = $this->comments->get_comments($filter); + + // Выбирает объекты, которые прокомментированы: + $products_ids = array(); + $posts_ids = array(); + foreach($comments as $comment) + { + if($comment->type == 'product') + $products_ids[] = $comment->object_id; + if($comment->type == 'blog') + $posts_ids[] = $comment->object_id; + } + $products = array(); + foreach($this->products->get_products(array('id'=>$products_ids)) as $p) + $products[$p->id] = $p; - return $this->design->fetch('comments.tpl'); - } -} + $posts = array(); + foreach($this->blog->get_posts(array('id'=>$posts_ids)) as $p) + $posts[$p->id] = $p; + + foreach($comments as &$comment) + { + if($comment->type == 'product' && isset($products[$comment->object_id])) + $comment->product = $products[$comment->object_id]; + if($comment->type == 'blog' && isset($posts[$comment->object_id])) + $comment->post = $posts[$comment->object_id]; + } + + + $this->design->assign('pages_count', ceil($comments_count/$filter['limit'])); + $this->design->assign('current_page', $filter['page']); + $this->design->assign('comments', $comments); + $this->design->assign('comments_count', $comments_count); -?> \ No newline at end of file + return $this->design->fetch('comments.tpl'); + } +} diff --git a/simpla/CouponAdmin.php b/simpla/CouponAdmin.php index 115fa77..2c9a054 100755 --- a/simpla/CouponAdmin.php +++ b/simpla/CouponAdmin.php @@ -1,62 +1,72 @@ -request->method('post')) - { - $coupon->id = $this->request->post('id', 'integer'); - $coupon->code = $this->request->post('code', 'string'); - if($this->request->post('expires')) - $coupon->expire = date('Y-m-d', strtotime($this->request->post('expire'))); - else - $coupon->expire = null; - $coupon->value = $this->request->post('value', 'float'); - $coupon->type = $this->request->post('type', 'string'); - $coupon->min_order_price = $this->request->post('min_order_price', 'float'); - $coupon->single = $this->request->post('single', 'float'); - - // Не допустить одинаковые URL разделов. - if(($a = $this->coupons->get_coupon((string)$coupon->code)) && $a->id!=$coupon->id) +request->method('post')) + { + $coupon->id = $this->request->post('id', 'integer'); + $coupon->code = $this->request->post('code', 'string'); + if($this->request->post('expires')) + $coupon->expire = date('Y-m-d', strtotime($this->request->post('expire'))); + else + $coupon->expire = null; + $coupon->value = $this->request->post('value', 'float'); + $coupon->type = $this->request->post('type', 'string'); + $coupon->min_order_price = $this->request->post('min_order_price', 'float'); + $coupon->single = $this->request->post('single', 'float'); + + // Не допустить одинаковые URL разделов. + if(($a = $this->coupons->get_coupon((string)$coupon->code)) && $a->id!=$coupon->id) { $this->design->assign('message_error', 'code_exists'); } - elseif(empty($coupon->code)) - { - $this->design->assign('message_error', 'code_empty'); - } + elseif(empty($coupon->code)) + { + $this->design->assign('message_error', 'code_empty'); + } else { if(empty($coupon->id)) - { - $coupon->id = $this->coupons->add_coupon($coupon); - $coupon = $this->coupons->get_coupon($coupon->id); - $this->design->assign('message_success', 'added'); - } - else - { - $this->coupons->update_coupon($coupon->id, $coupon); - $coupon = $this->coupons->get_coupon($coupon->id); - $this->design->assign('message_success', 'updated'); - } - - - } - } - else - { - $coupon->id = $this->request->get('id', 'integer'); - $coupon = $this->coupons->get_coupon($coupon->id); - } - -// if(empty($coupon->id)) -// $coupon->expire = date($this->settings->date_format, time()); - + { + $coupon->id = $this->coupons->add_coupon($coupon); + $coupon = $this->coupons->get_coupon($coupon->id); + $this->design->assign('message_success', 'added'); + } + else + { + $this->coupons->update_coupon($coupon->id, $coupon); + $coupon = $this->coupons->get_coupon($coupon->id); + $this->design->assign('message_success', 'updated'); + } + + + } + } + else + { + $coupon->id = $this->request->get('id', 'integer'); + $coupon = $this->coupons->get_coupon($coupon->id); + } + +// if(empty($coupon->id)) +// $coupon->expire = date($this->settings->date_format, time()); + $this->design->assign('coupon', $coupon); + return $this->design->fetch('coupon.tpl'); } } diff --git a/simpla/CouponsAdmin.php b/simpla/CouponsAdmin.php index 2994558..512f243 100755 --- a/simpla/CouponsAdmin.php +++ b/simpla/CouponsAdmin.php @@ -3,12 +3,12 @@ /** * Simpla CMS * - * @copyright 2012 Denis Pikusov + * @copyright 2016 Denis Pikusov * @link http://simplacms.ru * @author Denis Pikusov * */ - + require_once('api/Simpla.php'); class CouponsAdmin extends Simpla @@ -23,19 +23,19 @@ public function fetch() if(is_array($ids) && count($ids)>0) switch($this->request->post('action')) { - case 'delete': - { - foreach($ids as $id) - $this->coupons->delete_coupon($id); - break; - } - } + case 'delete': + { + foreach($ids as $id) + $this->coupons->delete_coupon($id); + break; + } + } } $filter = array(); - $filter['page'] = max(1, $this->request->get('page', 'integer')); + $filter['page'] = max(1, $this->request->get('page', 'integer')); $filter['limit'] = 20; - + // Поиск $keyword = $this->request->get('keyword', 'string'); if(!empty($keyword)) @@ -44,18 +44,19 @@ public function fetch() $this->design->assign('keyword', $keyword); } - $coupons_count = $this->coupons->count_coupons($filter); - - $pages_count = ceil($coupons_count/$filter['limit']); - $filter['page'] = min($filter['page'], $pages_count); - $this->design->assign('coupons_count', $coupons_count); - $this->design->assign('pages_count', $pages_count); - $this->design->assign('current_page', $filter['page']); + $coupons_count = $this->coupons->count_coupons($filter); + + $pages_count = ceil($coupons_count/$filter['limit']); + $filter['page'] = min($filter['page'], $pages_count); + $this->design->assign('coupons_count', $coupons_count); + $this->design->assign('pages_count', $pages_count); + $this->design->assign('current_page', $filter['page']); $coupons = $this->coupons->get_coupons($filter); $this->design->assign('coupons', $coupons); + return $this->design->fetch('coupons.tpl'); } } diff --git a/simpla/CurrencyAdmin.php b/simpla/CurrencyAdmin.php index cc75f4b..8c87465 100755 --- a/simpla/CurrencyAdmin.php +++ b/simpla/CurrencyAdmin.php @@ -1,118 +1,124 @@ -request->method('post')) - { - - foreach($this->request->post('currency') as $n=>$va) - foreach($va as $i=>$v) - { - if(empty($currencies[$i])) - $currencies[$i] = new stdClass; - $currencies[$i]->$n = $v; - } - - $currencies_ids = array(); - foreach($currencies as $currency) - { - if($currency->id) - $this->money->update_currency($currency->id, $currency); - else - $currency->id = $this->money->add_currency($currency); - $currencies_ids[] = $currency->id; - } - - // Удалить непереданные валюты - $query = $this->db->placehold('DELETE FROM __currencies WHERE id NOT IN(?@)', $currencies_ids); - $this->db->query($query); - - // Пересчитать курсы - $old_currency = $this->money->get_currency(); - $new_currency = reset($currencies); - if($old_currency->id != $new_currency->id) - { - $coef = $new_currency->rate_from/$new_currency->rate_to; - - if($this->request->post('recalculate') == 1) - { - $this->db->query("UPDATE __variants SET price=price*?", $coef); - $this->db->query("UPDATE __delivery SET price=price*?, free_from=free_from*?", $coef, $coef); - $this->db->query("UPDATE __orders SET delivery_price=delivery_price*?", $coef); - $this->db->query("UPDATE __orders SET total_price=total_price*?", $coef); - $this->db->query("UPDATE __purchases SET price=price*?", $coef); - $this->db->query("UPDATE __coupons SET value=value*? WHERE type='absolute'", $coef); - $this->db->query("UPDATE __coupons SET min_order_price=min_order_price*?", $coef); - $this->db->query("UPDATE __orders SET coupon_discount=coupon_discount*?", $coef); - } - - $this->db->query("UPDATE __currencies SET rate_from=1.0*rate_from*$new_currency->rate_to/$old_currency->rate_to"); - $this->db->query("UPDATE __currencies SET rate_to=1.0*rate_to*$new_currency->rate_from/$old_currency->rate_from"); - $this->db->query("UPDATE __currencies SET rate_to = rate_from WHERE id=?", $new_currency->id); - $this->db->query("UPDATE __currencies SET rate_to = 1, rate_from = 1 WHERE (rate_to=0 OR rate_from=0) AND id=?", $new_currency->id); - } - - // Отсортировать валюты - asort($currencies_ids); - $i = 0; - foreach($currencies_ids as $currency_id) - { - $this->money->update_currency($currencies_ids[$i], array('position'=>$currency_id)); - $i++; - } - - // Действия с выбранными - $action = $this->request->post('action'); - $id = $this->request->post('action_id'); - - if(!empty($action) && !empty($id)) - switch($action) - { - case 'disable': - { - $this->money->update_currency($id, array('enabled'=>0)); - break; - } - case 'enable': - { - $this->money->update_currency($id, array('enabled'=>1)); - break; - } - case 'show_cents': - { - $this->money->update_currency($id, array('cents'=>2)); - break; - } - case 'hide_cents': - { - $this->money->update_currency($id, array('cents'=>0)); - break; - } - case 'delete': - { - $this->money->delete_currency($id); - break; - } - } - - } - - - - // Отображение - $currencies = $this->money->get_currencies(); - $currency = $this->money->get_currency(); - $this->design->assign('currency', $currency); - $this->design->assign('currencies', $currencies); - return $this->design->fetch('currency.tpl'); - } -} \ No newline at end of file +request->method('post')) + { + + foreach($this->request->post('currency') as $n=>$va) + foreach($va as $i=>$v) + { + if(empty($currencies[$i])) + $currencies[$i] = new stdClass; + $currencies[$i]->$n = $v; + } + + $currencies_ids = array(); + foreach($currencies as $currency) + { + if($currency->id) + $this->money->update_currency($currency->id, $currency); + else + $currency->id = $this->money->add_currency($currency); + $currencies_ids[] = $currency->id; + } + + // Удалить непереданные валюты + $query = $this->db->placehold('DELETE FROM __currencies WHERE id NOT IN(?@)', $currencies_ids); + $this->db->query($query); + + // Пересчитать курсы + $old_currency = $this->money->get_currency(); + $new_currency = reset($currencies); + if($old_currency->id != $new_currency->id) + { + $coef = $new_currency->rate_from/$new_currency->rate_to; + + if($this->request->post('recalculate') == 1) + { + $this->db->query("UPDATE __variants SET price=price*?", $coef); + $this->db->query("UPDATE __delivery SET price=price*?, free_from=free_from*?", $coef, $coef); + $this->db->query("UPDATE __orders SET delivery_price=delivery_price*?", $coef); + $this->db->query("UPDATE __orders SET total_price=total_price*?", $coef); + $this->db->query("UPDATE __purchases SET price=price*?", $coef); + $this->db->query("UPDATE __coupons SET value=value*? WHERE type='absolute'", $coef); + $this->db->query("UPDATE __coupons SET min_order_price=min_order_price*?", $coef); + $this->db->query("UPDATE __orders SET coupon_discount=coupon_discount*?", $coef); + } + + $this->db->query("UPDATE __currencies SET rate_from=1.0*rate_from*$new_currency->rate_to/$old_currency->rate_to"); + $this->db->query("UPDATE __currencies SET rate_to=1.0*rate_to*$new_currency->rate_from/$old_currency->rate_from"); + $this->db->query("UPDATE __currencies SET rate_to = rate_from WHERE id=?", $new_currency->id); + $this->db->query("UPDATE __currencies SET rate_to = 1, rate_from = 1 WHERE (rate_to=0 OR rate_from=0) AND id=?", $new_currency->id); + } + + // Отсортировать валюты + asort($currencies_ids); + $i = 0; + foreach($currencies_ids as $currency_id) + { + $this->money->update_currency($currencies_ids[$i], array('position'=>$currency_id)); + $i++; + } + + // Действия с выбранными + $action = $this->request->post('action'); + $id = $this->request->post('action_id'); + + if(!empty($action) && !empty($id)) + switch($action) + { + case 'disable': + { + $this->money->update_currency($id, array('enabled'=>0)); + break; + } + case 'enable': + { + $this->money->update_currency($id, array('enabled'=>1)); + break; + } + case 'show_cents': + { + $this->money->update_currency($id, array('cents'=>2)); + break; + } + case 'hide_cents': + { + $this->money->update_currency($id, array('cents'=>0)); + break; + } + case 'delete': + { + $this->money->delete_currency($id); + break; + } + } + + } + + // Отображение + $currencies = $this->money->get_currencies(); + $currency = $this->money->get_currency(); + $this->design->assign('currency', $currency); + $this->design->assign('currencies', $currencies); + + return $this->design->fetch('currency.tpl'); + } +} diff --git a/simpla/DeliveriesAdmin.php b/simpla/DeliveriesAdmin.php index 97c4bbd..a1e726c 100755 --- a/simpla/DeliveriesAdmin.php +++ b/simpla/DeliveriesAdmin.php @@ -1,56 +1,62 @@ -request->method('post')) - { - // Действия с выбранными - $ids = $this->request->post('check'); - - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'disable': - { - $this->delivery->update_delivery($ids, array('enabled'=>0)); - break; - } - case 'enable': - { - $this->delivery->update_delivery($ids, array('enabled'=>1)); - break; - } - case 'delete': - { - foreach($ids as $id) - $this->delivery->delete_delivery($id); - break; - } - } - - // Сортировка - $positions = $this->request->post('positions'); - $ids = array_keys($positions); - sort($positions); - foreach($positions as $i=>$position) - $this->delivery->update_delivery($ids[$i], array('position'=>$position)); - - } - - - - // Отображение - $deliveries = $this->delivery->get_deliveries(); - $this->design->assign('deliveries', $deliveries); - return $this->design->fetch('deliveries.tpl'); - } -} \ No newline at end of file +request->method('post')) + { + // Действия с выбранными + $ids = $this->request->post('check'); + + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'disable': + { + $this->delivery->update_delivery($ids, array('enabled'=>0)); + break; + } + case 'enable': + { + $this->delivery->update_delivery($ids, array('enabled'=>1)); + break; + } + case 'delete': + { + foreach($ids as $id) + $this->delivery->delete_delivery($id); + break; + } + } + + // Сортировка + $positions = $this->request->post('positions'); + $ids = array_keys($positions); + sort($positions); + foreach($positions as $i=>$position) + $this->delivery->update_delivery($ids[$i], array('position'=>$position)); + + } + + // Отображение + $deliveries = $this->delivery->get_deliveries(); + $this->design->assign('deliveries', $deliveries); + + return $this->design->fetch('deliveries.tpl'); + } +} diff --git a/simpla/DeliveryAdmin.php b/simpla/DeliveryAdmin.php index 8a47c0b..a2f7810 100755 --- a/simpla/DeliveryAdmin.php +++ b/simpla/DeliveryAdmin.php @@ -1,64 +1,74 @@ -request->method('post')) - { - $delivery->id = $this->request->post('id', 'intgeger'); - $delivery->enabled = $this->request->post('enabled', 'boolean'); - $delivery->name = $this->request->post('name'); - $delivery->description = $this->request->post('description'); - $delivery->price = $this->request->post('price'); - $delivery->free_from = $this->request->post('free_from'); - $delivery->separate_payment = $this->request->post('separate_payment'); - +request->method('post')) + { + $delivery->id = $this->request->post('id', 'intgeger'); + $delivery->enabled = $this->request->post('enabled', 'boolean'); + $delivery->name = $this->request->post('name'); + $delivery->description = $this->request->post('description'); + $delivery->price = $this->request->post('price'); + $delivery->free_from = $this->request->post('free_from'); + $delivery->separate_payment = $this->request->post('separate_payment'); + if(!$delivery_payments = $this->request->post('delivery_payments')) $delivery_payments = array(); if(empty($delivery->name)) - { - $this->design->assign('message_error', 'empty_name'); - } - else - { - if(empty($delivery->id)) - { - $delivery->id = $this->delivery->add_delivery($delivery); - $this->design->assign('message_success', 'added'); - } - else - { - $this->delivery->update_delivery($delivery->id, $delivery); - $this->design->assign('message_success', 'updated'); - } + { + $this->design->assign('message_error', 'empty_name'); + } + else + { + if(empty($delivery->id)) + { + $delivery->id = $this->delivery->add_delivery($delivery); + $this->design->assign('message_success', 'added'); + } + else + { + $this->delivery->update_delivery($delivery->id, $delivery); + $this->design->assign('message_success', 'updated'); + } - $this->delivery->update_delivery_payments($delivery->id, $delivery_payments); - } + $this->delivery->update_delivery_payments($delivery->id, $delivery_payments); + } } else { - $delivery->id = $this->request->get('id', 'integer'); - if(!empty($delivery->id)) - { - $delivery = $this->delivery->get_delivery($delivery->id); - } - $delivery_payments = $this->delivery->get_delivery_payments($delivery->id); - } - $this->design->assign('delivery_payments', $delivery_payments); - - // Все способы оплаты - $payment_methods = $this->payment->get_payment_methods(); - $this->design->assign('payment_methods', $payment_methods); - - $this->design->assign('delivery', $delivery); - - return $this->design->fetch('delivery.tpl'); - } - -} - + $delivery->id = $this->request->get('id', 'integer'); + if(!empty($delivery->id)) + { + $delivery = $this->delivery->get_delivery($delivery->id); + } + $delivery_payments = $this->delivery->get_delivery_payments($delivery->id); + } + $this->design->assign('delivery_payments', $delivery_payments); + + // Все способы оплаты + $payment_methods = $this->payment->get_payment_methods(); + $this->design->assign('payment_methods', $payment_methods); + + $this->design->assign('delivery', $delivery); + + return $this->design->fetch('delivery.tpl'); + } + +} + diff --git a/simpla/ExportAdmin.php b/simpla/ExportAdmin.php index 8bfc024..a7fdcdc 100755 --- a/simpla/ExportAdmin.php +++ b/simpla/ExportAdmin.php @@ -1,17 +1,28 @@ -design->assign('export_files_dir', $this->export_files_dir); - if(!is_writable($this->export_files_dir)) - $this->design->assign('message_error', 'no_permission'); - return $this->design->fetch('export.tpl'); - } - -} - +design->assign('export_files_dir', $this->export_files_dir); + if(!is_writable($this->export_files_dir)) + $this->design->assign('message_error', 'no_permission'); + + return $this->design->fetch('export.tpl'); + } + +} + diff --git a/simpla/ExportUsersAdmin.php b/simpla/ExportUsersAdmin.php index 7139dfc..3f70873 100755 --- a/simpla/ExportUsersAdmin.php +++ b/simpla/ExportUsersAdmin.php @@ -1,21 +1,33 @@ -design->assign('export_files_dir', $this->export_files_dir); - $this->design->assign('sort', $this->request->get('sort')); - $this->design->assign('keyword', $this->request->get('keyword')); - $this->design->assign('group_id', $this->request->get('group_id')); - $this->design->assign('export_files_dir', $this->export_files_dir); - if(!is_writable($this->export_files_dir)) - $this->design->assign('message_error', 'no_permission'); - return $this->design->fetch('export_users.tpl'); - } - -} - +design->assign('export_files_dir', $this->export_files_dir); + $this->design->assign('sort', $this->request->get('sort')); + $this->design->assign('keyword', $this->request->get('keyword')); + $this->design->assign('group_id', $this->request->get('group_id')); + $this->design->assign('export_files_dir', $this->export_files_dir); + + if(!is_writable($this->export_files_dir)) + $this->design->assign('message_error', 'no_permission'); + + return $this->design->fetch('export_users.tpl'); + } + +} + diff --git a/simpla/FeatureAdmin.php b/simpla/FeatureAdmin.php index 97435c6..d799163 100755 --- a/simpla/FeatureAdmin.php +++ b/simpla/FeatureAdmin.php @@ -1,53 +1,64 @@ -request->method('post')) - { - $feature->id = $this->request->post('id', 'integer'); - $feature->name = $this->request->post('name'); - $feature->in_filter = intval($this->request->post('in_filter')); - $feature_categories = $this->request->post('feature_categories'); - - if(empty($feature->id)) - { - $feature->id = $this->features->add_feature($feature); - $feature = $this->features->get_feature($feature->id); - $this->design->assign('message_success', 'added'); - } - else - { - $this->features->update_feature($feature->id, $feature); - $feature = $this->features->get_feature($feature->id); - $this->design->assign('message_success', 'updated'); - } - $this->features->update_feature_categories($feature->id, $feature_categories); - } - else - { - $feature->id = $this->request->get('id', 'integer'); - $feature = $this->features->get_feature($feature->id); - } - - $feature_categories = array(); - if($feature) - { - $feature_categories = $this->features->get_feature_categories($feature->id); - } - - $categories = $this->categories->get_categories_tree(); - $this->design->assign('categories', $categories); - $this->design->assign('feature', $feature); - $this->design->assign('feature_categories', $feature_categories); - return $this->body = $this->design->fetch('feature.tpl'); - } -} - - - - +request->method('post')) + { + $feature->id = $this->request->post('id', 'integer'); + $feature->name = $this->request->post('name'); + $feature->in_filter = intval($this->request->post('in_filter')); + $feature_categories = $this->request->post('feature_categories'); + + if(empty($feature->id)) + { + $feature->id = $this->features->add_feature($feature); + $feature = $this->features->get_feature($feature->id); + $this->design->assign('message_success', 'added'); + } + else + { + $this->features->update_feature($feature->id, $feature); + $feature = $this->features->get_feature($feature->id); + $this->design->assign('message_success', 'updated'); + } + $this->features->update_feature_categories($feature->id, $feature_categories); + } + else + { + $feature->id = $this->request->get('id', 'integer'); + $feature = $this->features->get_feature($feature->id); + } + + $feature_categories = array(); + if($feature) + { + $feature_categories = $this->features->get_feature_categories($feature->id); + } + + $categories = $this->categories->get_categories_tree(); + $this->design->assign('categories', $categories); + $this->design->assign('feature', $feature); + $this->design->assign('feature_categories', $feature_categories); + + return $this->body = $this->design->fetch('feature.tpl'); + } +} + + + + diff --git a/simpla/FeaturesAdmin.php b/simpla/FeaturesAdmin.php index 00e7418..28072dc 100755 --- a/simpla/FeaturesAdmin.php +++ b/simpla/FeaturesAdmin.php @@ -1,80 +1,87 @@ -request->method('post')) - { - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'set_in_filter': - { - $this->features->update_feature($ids, array('in_filter'=>1)); - break; - } - case 'unset_in_filter': - { - $this->features->update_feature($ids, array('in_filter'=>0)); - break; - } - case 'delete': - { - $current_cat = $this->request->get('category_id', 'integer'); - foreach($ids as $id) - { - // текущие категории - $cats = $this->features->get_feature_categories($id); - - // В каких категориях оставлять - $diff = array_diff($cats, (array)$current_cat); - if(!empty($current_cat) && !empty($diff)) - { - $this->features->update_feature_categories($id, $diff); - } - else - { - $this->features->delete_feature($id); - } - } - break; - } - } - - // Сортировка - $positions = $this->request->post('positions'); - $ids = array_keys($positions); - sort($positions); - foreach($positions as $i=>$position) - $this->features->update_feature($ids[$i], array('position'=>$position)); - - } - - $categories = $this->categories->get_categories_tree(); - $category = null; - - $filter = array(); - $category_id = $this->request->get('category_id', 'integer'); - if($category_id) - { - $category = $this->categories->get_category($category_id); - $filter['category_id'] = $category->id; - } - - $features = $this->features->get_features($filter); - - $this->design->assign('categories', $categories); - $this->design->assign('category', $category); - $this->design->assign('features', $features); - return $this->body = $this->design->fetch('features.tpl'); - } -} +request->method('post')) + { + // Действия с выбранными + $ids = $this->request->post('check'); + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'set_in_filter': + { + $this->features->update_feature($ids, array('in_filter'=>1)); + break; + } + case 'unset_in_filter': + { + $this->features->update_feature($ids, array('in_filter'=>0)); + break; + } + case 'delete': + { + $current_cat = $this->request->get('category_id', 'integer'); + foreach($ids as $id) + { + // текущие категории + $cats = $this->features->get_feature_categories($id); + + // В каких категориях оставлять + $diff = array_diff($cats, (array)$current_cat); + if(!empty($current_cat) && !empty($diff)) + { + $this->features->update_feature_categories($id, $diff); + } + else + { + $this->features->delete_feature($id); + } + } + break; + } + } + + // Сортировка + $positions = $this->request->post('positions'); + $ids = array_keys($positions); + sort($positions); + foreach($positions as $i=>$position) + $this->features->update_feature($ids[$i], array('position'=>$position)); + + } + + $categories = $this->categories->get_categories_tree(); + $category = null; + + $filter = array(); + $category_id = $this->request->get('category_id', 'integer'); + if($category_id) + { + $category = $this->categories->get_category($category_id); + $filter['category_id'] = $category->id; + } + + $features = $this->features->get_features($filter); + + $this->design->assign('categories', $categories); + $this->design->assign('category', $category); + $this->design->assign('features', $features); + + return $this->body = $this->design->fetch('features.tpl'); + } +} diff --git a/simpla/FeedbacksAdmin.php b/simpla/FeedbacksAdmin.php index 10825eb..f411e5e 100755 --- a/simpla/FeedbacksAdmin.php +++ b/simpla/FeedbacksAdmin.php @@ -1,71 +1,76 @@ -request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } - - - // Обработка действий - if($this->request->method('post')) - { - // Действия с выбранными - $ids = $this->request->post('check'); - if(!empty($ids)) - switch($this->request->post('action')) - { - case 'delete': - { - foreach($ids as $id) - $this->feedbacks->delete_feedback($id); - break; - } - } - - } - - // Отображение - $filter = array(); - $filter['page'] = max(1, $this->request->get('page', 'integer')); - $filter['limit'] = 40; - - // Поиск - $keyword = $this->request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } - - $feedbacks_count = $this->feedbacks->count_feedbacks($filter); - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $filter['limit'] = $feedbacks_count; - - $feedbacks = $this->feedbacks->get_feedbacks($filter, true); - - $this->design->assign('pages_count', ceil($feedbacks_count/$filter['limit'])); - $this->design->assign('current_page', $filter['page']); - - $this->design->assign('feedbacks', $feedbacks); - $this->design->assign('feedbacks_count', $feedbacks_count); - - return $this->design->fetch('feedbacks.tpl'); - } -} - - -?> \ No newline at end of file +request->get('keyword', 'string'); + if(!empty($keyword)) + { + $filter['keyword'] = $keyword; + $this->design->assign('keyword', $keyword); + } + + + // Обработка действий + if($this->request->method('post')) + { + // Действия с выбранными + $ids = $this->request->post('check'); + if(!empty($ids)) + switch($this->request->post('action')) + { + case 'delete': + { + foreach($ids as $id) + $this->feedbacks->delete_feedback($id); + break; + } + } + + } + + // Отображение + $filter = array(); + $filter['page'] = max(1, $this->request->get('page', 'integer')); + $filter['limit'] = 40; + + // Поиск + $keyword = $this->request->get('keyword', 'string'); + if(!empty($keyword)) + { + $filter['keyword'] = $keyword; + $this->design->assign('keyword', $keyword); + } + + $feedbacks_count = $this->feedbacks->count_feedbacks($filter); + // Показать все страницы сразу + if($this->request->get('page') == 'all') + $filter['limit'] = $feedbacks_count; + + $feedbacks = $this->feedbacks->get_feedbacks($filter, true); + + $this->design->assign('pages_count', ceil($feedbacks_count/$filter['limit'])); + $this->design->assign('current_page', $filter['page']); + + $this->design->assign('feedbacks', $feedbacks); + $this->design->assign('feedbacks_count', $feedbacks_count); + + return $this->design->fetch('feedbacks.tpl'); + } +} diff --git a/simpla/GroupAdmin.php b/simpla/GroupAdmin.php index fe3ae75..27a1730 100755 --- a/simpla/GroupAdmin.php +++ b/simpla/GroupAdmin.php @@ -1,50 +1,60 @@ -request->method('post')) - { - $group->id = $this->request->post('id', 'integer'); - $group->name = $this->request->post('name'); - $group->discount = $this->request->post('discount'); - - if(empty($group->name)) - { - $this->design->assign('message_error', 'name_empty'); - } - else - { - if(empty($group->id)) - { - $group->id = $this->users->add_group($group); - $this->design->assign('message_success', 'added'); - } - else - { - $group->id = $this->users->update_group($group->id, $group); - $this->design->assign('message_success', 'updated'); - } - $group = $this->users->get_group(intval($group->id)); - } - - } - else - { - $id = $this->request->get('id', 'integer'); - if(!empty($id)) - $group = $this->users->get_group(intval($id)); - } - - if(!empty($group)) - { - $this->design->assign('group', $group); - } - - return $this->design->fetch('group.tpl'); - } - -} +request->method('post')) + { + $group->id = $this->request->post('id', 'integer'); + $group->name = $this->request->post('name'); + $group->discount = $this->request->post('discount'); + + if(empty($group->name)) + { + $this->design->assign('message_error', 'name_empty'); + } + else + { + if(empty($group->id)) + { + $group->id = $this->users->add_group($group); + $this->design->assign('message_success', 'added'); + } + else + { + $group->id = $this->users->update_group($group->id, $group); + $this->design->assign('message_success', 'updated'); + } + $group = $this->users->get_group(intval($group->id)); + } + + } + else + { + $id = $this->request->get('id', 'integer'); + if(!empty($id)) + $group = $this->users->get_group(intval($id)); + } + + if(!empty($group)) + { + $this->design->assign('group', $group); + } + + return $this->design->fetch('group.tpl'); + } + +} diff --git a/simpla/GroupsAdmin.php b/simpla/GroupsAdmin.php index 4e97370..6f8dfed 100755 --- a/simpla/GroupsAdmin.php +++ b/simpla/GroupsAdmin.php @@ -1,33 +1,40 @@ -request->method('post')) - { - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'delete': - { - foreach($ids as $id) - $this->users->delete_group($id); - break; - } - } - } - - $groups = $this->users->get_groups(); - - $this->design->assign('groups', $groups); - return $this->body = $this->design->fetch('groups.tpl'); - } -} +request->method('post')) + { + // Действия с выбранными + $ids = $this->request->post('check'); + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'delete': + { + foreach($ids as $id) + $this->users->delete_group($id); + break; + } + } + } + + $groups = $this->users->get_groups(); + + $this->design->assign('groups', $groups); + + return $this->body = $this->design->fetch('groups.tpl'); + } +} diff --git a/simpla/ImagesAdmin.php b/simpla/ImagesAdmin.php index 6e9fc44..4018e93 100755 --- a/simpla/ImagesAdmin.php +++ b/simpla/ImagesAdmin.php @@ -1,94 +1,105 @@ -settings->theme.'/images/'; - $allowed_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico'); - $images = array(); - - // Сохраняем - if($this->request->method('post') && !is_file($images_dir.'../locked')) - { - $old_names = $this->request->post('old_name'); - $new_names = $this->request->post('new_name'); - if(is_array($old_names)) - foreach($old_names as $i=>$old_name) - { - $new_name = $new_names[$i]; - $new_name = trim(pathinfo($new_name, PATHINFO_FILENAME).'.'.pathinfo($old_name, PATHINFO_EXTENSION), '.'); - - if(is_writable($images_dir) && is_file($images_dir.$old_name) && !is_file($images_dir.$new_name)) - rename($images_dir.$old_name, $images_dir.$new_name); - elseif(is_file($images_dir.$new_name) && $new_name!=$old_name) - $message_error = 'name_exists'; - } - - $delete_image = trim($this->request->post('delete_image'), '.'); - - if(!empty($delete_image)) - { - @unlink($images_dir.$delete_image); - } - - // Загрузка изображений - if($images = $this->request->files('upload_images')) - { - for($i=0; $idesign->assign('message_error', $message_error); - - } - - - - // Чтаем все файлы - if($handle = opendir($images_dir)) { - while(false !== ($file = readdir($handle))) - { - if(is_file($images_dir.$file) && $file[0] != '.' && in_array(pathinfo($file, PATHINFO_EXTENSION), $allowed_extentions)) - { - $image = new stdClass; - $image->name = $file; - $image->size = filesize($images_dir.$file); - list($image->width, $image->height) = @getimagesize($images_dir.$file); - $images[$file] = $image; - } - } - closedir($handle); - ksort($images); - } - - // Если нет прав на запись - передаем в дизайн предупреждение - if(!is_writable($images_dir)) - { - $this->design->assign('message_error', 'permissions'); - } - elseif(is_file($images_dir.'../locked')) - { - $this->design->assign('message_error', 'theme_locked'); - } - - $this->design->assign('theme', $this->settings->theme); - $this->design->assign('images', $images); - $this->design->assign('images_dir', $images_dir); - return $this->design->fetch('images.tpl'); - } - -} - +settings->theme.'/images/'; + $allowed_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico'); + $images = array(); + + // Сохраняем + if($this->request->method('post') && !is_file($images_dir.'../locked')) + { + $old_names = $this->request->post('old_name'); + $new_names = $this->request->post('new_name'); + if(is_array($old_names)) + foreach($old_names as $i=>$old_name) + { + $new_name = $new_names[$i]; + $new_name = trim(pathinfo($new_name, PATHINFO_FILENAME).'.'.pathinfo($old_name, PATHINFO_EXTENSION), '.'); + + if(is_writable($images_dir) && is_file($images_dir.$old_name) && !is_file($images_dir.$new_name)) + rename($images_dir.$old_name, $images_dir.$new_name); + elseif(is_file($images_dir.$new_name) && $new_name!=$old_name) + $message_error = 'name_exists'; + } + + $delete_image = trim($this->request->post('delete_image'), '.'); + + if(!empty($delete_image)) + { + @unlink($images_dir.$delete_image); + } + + // Загрузка изображений + if($images = $this->request->files('upload_images')) + { + for($i=0; $idesign->assign('message_error', $message_error); + + } + + + + // Чтаем все файлы + if($handle = opendir($images_dir)) { + while(false !== ($file = readdir($handle))) + { + if(is_file($images_dir.$file) && $file[0] != '.' && in_array(pathinfo($file, PATHINFO_EXTENSION), $allowed_extentions)) + { + $image = new stdClass; + $image->name = $file; + $image->size = filesize($images_dir.$file); + list($image->width, $image->height) = @getimagesize($images_dir.$file); + $images[$file] = $image; + } + } + closedir($handle); + ksort($images); + } + + // Если нет прав на запись - передаем в дизайн предупреждение + if(!is_writable($images_dir)) + { + $this->design->assign('message_error', 'permissions'); + } + elseif(is_file($images_dir.'../locked')) + { + $this->design->assign('message_error', 'theme_locked'); + } + + $this->design->assign('theme', $this->settings->theme); + $this->design->assign('images', $images); + $this->design->assign('images_dir', $images_dir); + + return $this->design->fetch('images.tpl'); + } + +} + diff --git a/simpla/ImportAdmin.php b/simpla/ImportAdmin.php index f29acf2..e3de29d 100755 --- a/simpla/ImportAdmin.php +++ b/simpla/ImportAdmin.php @@ -1,110 +1,120 @@ -design->assign('import_files_dir', $this->import_files_dir); - if(!is_writable($this->import_files_dir)) - $this->design->assign('message_error', 'no_permission'); - - // Проверяем локаль - $old_locale = setlocale(LC_ALL, 0); - setlocale(LC_ALL, $this->locale); - if(setlocale(LC_ALL, 0) != $this->locale) - { - $this->design->assign('message_error', 'locale_error'); - $this->design->assign('locale', $this->locale); - } - setlocale(LC_ALL, $old_locale); - - - if($this->request->method('post') && ($this->request->files("file"))) - { - $uploaded_name = $this->request->files("file", "tmp_name"); - $temp = tempnam($this->import_files_dir, 'temp_'); - if(!move_uploaded_file($uploaded_name, $temp)) - $this->design->assign('message_error', 'upload_error'); - - if(!$this->convert_file($temp, $this->import_files_dir.$this->import_file)) - $this->design->assign('message_error', 'convert_error'); - else - $this->design->assign('filename', $this->request->files("file", "name")); - unlink($temp); - } - - return $this->design->fetch('import.tpl'); - } - - private function convert_file($source, $dest) - { - // Узнаем какая кодировка у файла - $teststring = file_get_contents($source, null, null, null, 1000000); - - if (preg_match('//u', $teststring)) // Кодировка - UTF8 - { - // Просто копируем файл - return copy($source, $dest); - } - else - { - // Конвертируем в UFT8 - if(!$src = fopen($source, "r")) - return false; - - if(!$dst = fopen($dest, "w")) - return false; - - while (($line = fgets($src, 4096)) !== false) - { - $line = $this->win_to_utf($line); - fwrite($dst, $line); - } - fclose($src); - fclose($dst); - return true; - } - } - - private function win_to_utf($text) - { - if(function_exists('iconv')) - { - return @iconv('windows-1251', 'UTF-8', $text); - } - else - { - $t = ''; - for($i=0, $m=strlen($text); $i<$m; $i++) - { - $c=ord($text[$i]); - if ($c<=127) {$t.=chr($c); continue; } - if ($c>=192 && $c<=207) {$t.=chr(208).chr($c-48); continue; } - if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; } - if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; } -// if ($c==184) { $t.=chr(209).chr(209); continue; }; -// if ($c==168) { $t.=chr(208).chr(129); continue; }; - if ($c==184) { $t.=chr(209).chr(145); continue; }; #ё - if ($c==168) { $t.=chr(208).chr(129); continue; }; #Ё - if ($c==179) { $t.=chr(209).chr(150); continue; }; #і - if ($c==178) { $t.=chr(208).chr(134); continue; }; #І - if ($c==191) { $t.=chr(209).chr(151); continue; }; #ї - if ($c==175) { $t.=chr(208).chr(135); continue; }; #ї - if ($c==186) { $t.=chr(209).chr(148); continue; }; #є - if ($c==170) { $t.=chr(208).chr(132); continue; }; #Є - if ($c==180) { $t.=chr(210).chr(145); continue; }; #ґ - if ($c==165) { $t.=chr(210).chr(144); continue; }; #Ґ - if ($c==184) { $t.=chr(209).chr(145); continue; }; #Ґ - } - return $t; - } - } - -} - +design->assign('import_files_dir', $this->import_files_dir); + if(!is_writable($this->import_files_dir)) + $this->design->assign('message_error', 'no_permission'); + + // Проверяем локаль + $old_locale = setlocale(LC_ALL, 0); + setlocale(LC_ALL, $this->locale); + if(setlocale(LC_ALL, 0) != $this->locale) + { + $this->design->assign('message_error', 'locale_error'); + $this->design->assign('locale', $this->locale); + } + setlocale(LC_ALL, $old_locale); + + + if($this->request->method('post') && ($this->request->files("file"))) + { + $uploaded_name = $this->request->files("file", "tmp_name"); + $temp = tempnam($this->import_files_dir, 'temp_'); + if(!move_uploaded_file($uploaded_name, $temp)) + $this->design->assign('message_error', 'upload_error'); + + if(!$this->convert_file($temp, $this->import_files_dir.$this->import_file)) + $this->design->assign('message_error', 'convert_error'); + else + $this->design->assign('filename', $this->request->files("file", "name")); + unlink($temp); + } + + return $this->design->fetch('import.tpl'); + } + + private function convert_file($source, $dest) + { + // Узнаем какая кодировка у файла + $teststring = file_get_contents($source, null, null, null, 1000000); + + if (preg_match('//u', $teststring)) // Кодировка - UTF8 + { + // Просто копируем файл + return copy($source, $dest); + } + else + { + // Конвертируем в UFT8 + if(!$src = fopen($source, "r")) + return false; + + if(!$dst = fopen($dest, "w")) + return false; + + while (($line = fgets($src, 4096)) !== false) + { + $line = $this->win_to_utf($line); + fwrite($dst, $line); + } + fclose($src); + fclose($dst); + return true; + } + } + + private function win_to_utf($text) + { + if(function_exists('iconv')) + { + return @iconv('windows-1251', 'UTF-8', $text); + } + else + { + $t = ''; + for($i=0, $m=strlen($text); $i<$m; $i++) + { + $c=ord($text[$i]); + if ($c<=127) {$t.=chr($c); continue; } + if ($c>=192 && $c<=207) {$t.=chr(208).chr($c-48); continue; } + if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; } + if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; } +// if ($c==184) { $t.=chr(209).chr(209); continue; }; +// if ($c==168) { $t.=chr(208).chr(129); continue; }; + if ($c==184) { $t.=chr(209).chr(145); continue; }; #ё + if ($c==168) { $t.=chr(208).chr(129); continue; }; #Ё + if ($c==179) { $t.=chr(209).chr(150); continue; }; #і + if ($c==178) { $t.=chr(208).chr(134); continue; }; #І + if ($c==191) { $t.=chr(209).chr(151); continue; }; #ї + if ($c==175) { $t.=chr(208).chr(135); continue; }; #ї + if ($c==186) { $t.=chr(209).chr(148); continue; }; #є + if ($c==170) { $t.=chr(208).chr(132); continue; }; #Є + if ($c==180) { $t.=chr(210).chr(145); continue; }; #ґ + if ($c==165) { $t.=chr(210).chr(144); continue; }; #Ґ + if ($c==184) { $t.=chr(209).chr(145); continue; }; #Ґ + } + return $t; + } + } + +} + diff --git a/simpla/IndexAdmin.php b/simpla/IndexAdmin.php index c4197bb..bf79d8e 100755 --- a/simpla/IndexAdmin.php +++ b/simpla/IndexAdmin.php @@ -1,165 +1,173 @@ - 'products', - 'ProductAdmin' => 'products', - 'CategoriesAdmin' => 'categories', - 'CategoryAdmin' => 'categories', - 'BrandsAdmin' => 'brands', - 'BrandAdmin' => 'brands', - 'FeaturesAdmin' => 'features', - 'FeatureAdmin' => 'features', - 'OrdersAdmin' => 'orders', - 'OrderAdmin' => 'orders', - 'OrdersLabelsAdmin' => 'labels', - 'OrdersLabelAdmin' => 'labels', - 'UsersAdmin' => 'users', - 'UserAdmin' => 'users', - 'ExportUsersAdmin' => 'users', - 'GroupsAdmin' => 'groups', - 'GroupAdmin' => 'groups', - 'CouponsAdmin' => 'coupons', - 'CouponAdmin' => 'coupons', - 'PagesAdmin' => 'pages', - 'PageAdmin' => 'pages', - 'BlogAdmin' => 'blog', - 'PostAdmin' => 'blog', - 'CommentsAdmin' => 'comments', - 'FeedbacksAdmin' => 'feedbacks', - 'ImportAdmin' => 'import', - 'ExportAdmin' => 'export', - 'BackupAdmin' => 'backup', - 'StatsAdmin' => 'stats', - 'ThemeAdmin' => 'design', - 'StylesAdmin' => 'design', - 'TemplatesAdmin' => 'design', - 'ImagesAdmin' => 'design', - 'SettingsAdmin' => 'settings', - 'CurrencyAdmin' => 'currency', - 'DeliveriesAdmin' => 'delivery', - 'DeliveryAdmin' => 'delivery', - 'PaymentMethodAdmin' => 'payment', - 'PaymentMethodsAdmin' => 'payment', - 'ManagersAdmin' => 'managers', - 'ManagerAdmin' => 'managers', - 'LicenseAdmin' => 'license' - ); - - // Конструктор - public function __construct() - { - // Вызываем конструктор базового класса - parent::__construct(); - - - $p=11; $g=2; $x=7; $r = ''; $s = $x; - $bs = explode(' ', $this->config->license); - foreach($bs as $bl){ - for($i=0, $m=''; $idomains, $l->expiration, $l->comment) = explode('#', $r, 3); - - $l->domains = explode(',', $l->domains); - $h = getenv("HTTP_HOST"); - if(substr($h, 0, 4) == 'www.') $h = substr($h, 4); - if((!in_array($h, $l->domains) || (strtotime($l->expiration)expiration!='*')) && $this->request->get('module')!='LicenseAdmin') - header('location: '.$this->config->root_url.'/simpla/index.php?module=LicenseAdmin'); - else - { - $l->valid = true; - $this->design->assign('license', $l); - } - - $this->design->assign('license', $l); - - $this->design->set_templates_dir('simpla/design/html'); - - if(!is_dir($this->config->root_dir.'/compiled')) - mkdir($this->config->root_dir.'simpla/design/compiled', 0777); - - $this->design->set_compiled_dir('simpla/design/compiled'); - - $this->design->assign('settings', $this->settings); - $this->design->assign('config', $this->config); - - // Администратор - $this->manager = $this->managers->get_manager(); - $this->design->assign('manager', $this->manager); - - // Берем название модуля из get-запроса - $module = $this->request->get('module', 'string'); - $module = preg_replace("/[^A-Za-z0-9]+/", "", $module); - - // Если не запросили модуль - используем модуль первый из разрешенных - if(empty($module) || !is_file('simpla/'.$module.'.php')) - { - foreach($this->modules_permissions as $m=>$p) - { - if($this->managers->access($p)) - { - $module = $m; - break; - } - } - } - if(empty($module)) - $module = 'ProductsAdmin'; - - // Подключаем файл с необходимым модулем - require_once('simpla/'.$module.'.php'); - - // Создаем соответствующий модуль - if(class_exists($module)) - $this->module = new $module(); - else - die("Error creating $module class"); - - } - - function fetch() - { - $currency = $this->money->get_currency(); - $this->design->assign("currency", $currency); - - // Проверка прав доступа к модулю - if(isset($this->modules_permissions[get_class($this->module)]) - && $this->managers->access($this->modules_permissions[get_class($this->module)])) - { - $content = $this->module->fetch(); - $this->design->assign("content", $content); - } - else - { - $this->design->assign("content", "Permission denied"); - } - - // Счетчики для верхнего меню - $new_orders_counter = $this->orders->count_orders(array('status'=>0)); - $this->design->assign("new_orders_counter", $new_orders_counter); - - $new_comments_counter = $this->comments->count_comments(array('approved'=>0)); - $this->design->assign("new_comments_counter", $new_comments_counter); - - // Создаем текущую обертку сайта (обычно index.tpl) - $wrapper = $this->design->smarty->getTemplateVars('wrapper'); - if(is_null($wrapper)) - $wrapper = 'index.tpl'; - - if(!empty($wrapper)) - return $this->body = $this->design->fetch($wrapper); - else - return $this->body = $content; - } -} + 'products', + 'ProductAdmin' => 'products', + 'CategoriesAdmin' => 'categories', + 'CategoryAdmin' => 'categories', + 'BrandsAdmin' => 'brands', + 'BrandAdmin' => 'brands', + 'FeaturesAdmin' => 'features', + 'FeatureAdmin' => 'features', + 'OrdersAdmin' => 'orders', + 'OrderAdmin' => 'orders', + 'OrdersLabelsAdmin' => 'labels', + 'OrdersLabelAdmin' => 'labels', + 'UsersAdmin' => 'users', + 'UserAdmin' => 'users', + 'ExportUsersAdmin' => 'users', + 'GroupsAdmin' => 'groups', + 'GroupAdmin' => 'groups', + 'CouponsAdmin' => 'coupons', + 'CouponAdmin' => 'coupons', + 'PagesAdmin' => 'pages', + 'PageAdmin' => 'pages', + 'BlogAdmin' => 'blog', + 'PostAdmin' => 'blog', + 'CommentsAdmin' => 'comments', + 'FeedbacksAdmin' => 'feedbacks', + 'ImportAdmin' => 'import', + 'ExportAdmin' => 'export', + 'BackupAdmin' => 'backup', + 'StatsAdmin' => 'stats', + 'ThemeAdmin' => 'design', + 'StylesAdmin' => 'design', + 'TemplatesAdmin' => 'design', + 'ImagesAdmin' => 'design', + 'SettingsAdmin' => 'settings', + 'CurrencyAdmin' => 'currency', + 'DeliveriesAdmin' => 'delivery', + 'DeliveryAdmin' => 'delivery', + 'PaymentMethodAdmin' => 'payment', + 'PaymentMethodsAdmin' => 'payment', + 'ManagersAdmin' => 'managers', + 'ManagerAdmin' => 'managers', + 'LicenseAdmin' => 'license' + ); + + // Конструктор + public function __construct() + { + // Вызываем конструктор базового класса + parent::__construct(); + + + $p=11; $g=2; $x=7; $r = ''; $s = $x; + $bs = explode(' ', $this->config->license); + foreach($bs as $bl){ + for($i=0, $m=''; $idomains, $l->expiration, $l->comment) = explode('#', $r, 3); + + $l->domains = explode(',', $l->domains); + $h = getenv("HTTP_HOST"); + if(substr($h, 0, 4) == 'www.') $h = substr($h, 4); + if((!in_array($h, $l->domains) || (strtotime($l->expiration)expiration!='*')) && $this->request->get('module')!='LicenseAdmin') + header('location: '.$this->config->root_url.'/simpla/index.php?module=LicenseAdmin'); + else + { + $l->valid = true; + $this->design->assign('license', $l); + } + + $this->design->assign('license', $l); + + $this->design->set_templates_dir('simpla/design/html'); + + if(!is_dir($this->config->root_dir.'/compiled')) + mkdir($this->config->root_dir.'simpla/design/compiled', 0777); + + $this->design->set_compiled_dir('simpla/design/compiled'); + + $this->design->assign('settings', $this->settings); + $this->design->assign('config', $this->config); + + // Администратор + $this->manager = $this->managers->get_manager(); + $this->design->assign('manager', $this->manager); + + // Берем название модуля из get-запроса + $module = $this->request->get('module', 'string'); + $module = preg_replace("/[^A-Za-z0-9]+/", "", $module); + + // Если не запросили модуль - используем модуль первый из разрешенных + if(empty($module) || !is_file('simpla/'.$module.'.php')) + { + foreach($this->modules_permissions as $m=>$p) + { + if($this->managers->access($p)) + { + $module = $m; + break; + } + } + } + if(empty($module)) + $module = 'ProductsAdmin'; + + // Подключаем файл с необходимым модулем + require_once('simpla/'.$module.'.php'); + + // Создаем соответствующий модуль + if(class_exists($module)) + $this->module = new $module(); + else + die("Error creating $module class"); + + } + + public function fetch() + { + $currency = $this->money->get_currency(); + $this->design->assign("currency", $currency); + + // Проверка прав доступа к модулю + if(isset($this->modules_permissions[get_class($this->module)]) + && $this->managers->access($this->modules_permissions[get_class($this->module)])) + { + $content = $this->module->fetch(); + $this->design->assign("content", $content); + } + else + { + $this->design->assign("content", "Permission denied"); + } + + // Счетчики для верхнего меню + $new_orders_counter = $this->orders->count_orders(array('status'=>0)); + $this->design->assign("new_orders_counter", $new_orders_counter); + + $new_comments_counter = $this->comments->count_comments(array('approved'=>0)); + $this->design->assign("new_comments_counter", $new_comments_counter); + + // Создаем текущую обертку сайта (обычно index.tpl) + $wrapper = $this->design->smarty->getTemplateVars('wrapper'); + if(is_null($wrapper)) + $wrapper = 'index.tpl'; + + if(!empty($wrapper)) + return $this->body = $this->design->fetch($wrapper); + else + return $this->body = $content; + } +} diff --git a/simpla/LicenseAdmin.php b/simpla/LicenseAdmin.php index ffbdd48..88b7f65 100755 --- a/simpla/LicenseAdmin.php +++ b/simpla/LicenseAdmin.php @@ -1,44 +1,55 @@ -request->method('POST')) - { - $license = $this->request->post('license'); - $this->config->license = trim($license); - } - - $p=11; $g=2; $x=7; $r = ''; $s = $x; - $bs = explode(' ', $this->config->license); - foreach($bs as $bl){ - for($i=0, $m=''; $idomains, $l->expiration, $l->comment) = explode('#', $r, 3); - - $l->domains = explode(',', $l->domains); - - $h = getenv("HTTP_HOST"); - if(substr($h, 0, 4) == 'www.') $h = substr($h, 4); - $l->valid = true; - if(!in_array($h, $l->domains)) - $l->valid = false; - if(strtotime($l->expiration)expiration!='*') - $l->valid = false; - - - $this->design->assign('license', $l); - - return $this->design->fetch('license.tpl'); - } - -} - +request->method('POST')) + { + $license = $this->request->post('license'); + $this->config->license = trim($license); + } + + $p=11; $g=2; $x=7; $r = ''; $s = $x; + $bs = explode(' ', $this->config->license); + foreach($bs as $bl){ + for($i=0, $m=''; $idomains, $l->expiration, $l->comment) = explode('#', $r, 3); + + $l->domains = explode(',', $l->domains); + + $h = getenv("HTTP_HOST"); + if(substr($h, 0, 4) == 'www.') $h = substr($h, 4); + $l->valid = true; + if(!in_array($h, $l->domains)) + $l->valid = false; + if(strtotime($l->expiration)expiration!='*') + $l->valid = false; + + + $this->design->assign('license', $l); + + return $this->design->fetch('license.tpl'); + } + +} + diff --git a/simpla/ManagerAdmin.php b/simpla/ManagerAdmin.php index 881d7ac..19adca3 100755 --- a/simpla/ManagerAdmin.php +++ b/simpla/ManagerAdmin.php @@ -1,67 +1,77 @@ -request->method('post')) - { - $manager = new stdClass(); - $manager->old_login = $this->request->post('old_login'); - $manager->login = $this->request->post('login'); - - if(!is_writable($this->managers->passwd_file)) - { - $this->design->assign('message_error', 'not_writable'); - } - elseif(empty($manager->login)) - { - $this->design->assign('message_error', 'empty_login'); - } - elseif($this->managers->get_manager($manager->login) && $manager->login!=$manager->old_login) - { - $manager->login = $manager->old_login; - $manager->permissions = (array)$this->request->post('permissions'); - $this->design->assign('message_error', 'login_exists'); - } - else - { - if($this->request->post('password') != "") - $manager->password = $this->request->post('password'); - - // Обновляем права только другим менеджерам - $current_manager = $this->managers->get_manager(); - if($manager->old_login != $current_manager->login) - $manager->permissions = (array)$this->request->post('permissions'); - - if(empty($manager->old_login)) - { - $manager->login = $this->managers->add_manager($manager); - $this->design->assign('message_success', 'added'); - } - else - { - $manager->login = $this->managers->update_manager($manager->old_login, $manager); - $this->design->assign('message_success', 'updated'); - } - $manager = $this->managers->get_manager($manager->login); - } - } - else - { - $login = $this->request->get('login'); - if(!empty($login)) - $manager = $this->managers->get_manager($login); - } - - if(!empty($manager)) - { - $this->design->assign('m', $manager); - } - - return $this->design->fetch('manager.tpl'); - } - -} - +request->method('post')) + { + $manager = new stdClass(); + $manager->old_login = $this->request->post('old_login'); + $manager->login = $this->request->post('login'); + + if(!is_writable($this->managers->passwd_file)) + { + $this->design->assign('message_error', 'not_writable'); + } + elseif(empty($manager->login)) + { + $this->design->assign('message_error', 'empty_login'); + } + elseif($this->managers->get_manager($manager->login) && $manager->login!=$manager->old_login) + { + $manager->login = $manager->old_login; + $manager->permissions = (array)$this->request->post('permissions'); + $this->design->assign('message_error', 'login_exists'); + } + else + { + if($this->request->post('password') != "") + $manager->password = $this->request->post('password'); + + // Обновляем права только другим менеджерам + $current_manager = $this->managers->get_manager(); + if($manager->old_login != $current_manager->login) + $manager->permissions = (array)$this->request->post('permissions'); + + if(empty($manager->old_login)) + { + $manager->login = $this->managers->add_manager($manager); + $this->design->assign('message_success', 'added'); + } + else + { + $manager->login = $this->managers->update_manager($manager->old_login, $manager); + $this->design->assign('message_success', 'updated'); + } + $manager = $this->managers->get_manager($manager->login); + } + } + else + { + $login = $this->request->get('login'); + if(!empty($login)) + $manager = $this->managers->get_manager($login); + } + + if(!empty($manager)) + { + $this->design->assign('m', $manager); + } + + return $this->design->fetch('manager.tpl'); + } + +} diff --git a/simpla/ManagersAdmin.php b/simpla/ManagersAdmin.php index 1ecaaa6..56064e0 100755 --- a/simpla/ManagersAdmin.php +++ b/simpla/ManagersAdmin.php @@ -1,40 +1,47 @@ -request->method('post')) - { - // Действия с выбранными - $logins = $this->request->post('check'); - if(is_array($logins)) - switch($this->request->post('action')) - { - case 'delete': - { - foreach($logins as $login) - $this->managers->delete_manager($login); - break; - } - } - } - - if(!is_writable($this->managers->passwd_file)) - { - $this->design->assign('message_error', 'not_writable'); - } - - $managers = $this->managers->get_managers(); - $managers_count = $this->managers->count_managers(); - $this->design->assign('managers', $managers); - $this->design->assign('managers_count', $managers_count); - return $this->body = $this->design->fetch('managers.tpl'); - } -} +request->method('post')) + { + // Действия с выбранными + $logins = $this->request->post('check'); + if(is_array($logins)) + switch($this->request->post('action')) + { + case 'delete': + { + foreach($logins as $login) + $this->managers->delete_manager($login); + break; + } + } + } + + if(!is_writable($this->managers->passwd_file)) + { + $this->design->assign('message_error', 'not_writable'); + } + + $managers = $this->managers->get_managers(); + $managers_count = $this->managers->count_managers(); + $this->design->assign('managers', $managers); + $this->design->assign('managers_count', $managers_count); + + return $this->body = $this->design->fetch('managers.tpl'); + } +} diff --git a/simpla/OrderAdmin.php b/simpla/OrderAdmin.php index b3f3e82..79a05b0 100755 --- a/simpla/OrderAdmin.php +++ b/simpla/OrderAdmin.php @@ -1,252 +1,260 @@ -request->method('post')) - { - $order->id = $this->request->post('id', 'integer'); - $order->name = $this->request->post('name'); - $order->email = $this->request->post('email'); - $order->phone = $this->request->post('phone'); - $order->address = $this->request->post('address'); - $order->comment = $this->request->post('comment'); - $order->note = $this->request->post('note'); - $order->discount = $this->request->post('discount', 'floatr'); - $order->coupon_discount = $this->request->post('coupon_discount', 'floatr'); - $order->delivery_id = $this->request->post('delivery_id', 'integer'); - $order->delivery_price = $this->request->post('delivery_price', 'float'); - $order->payment_method_id = $this->request->post('payment_method_id', 'integer'); - $order->paid = $this->request->post('paid', 'integer'); - $order->user_id = $this->request->post('user_id', 'integer'); - $order->separate_delivery = $this->request->post('separate_delivery', 'integer'); - - if(!$order_labels = $this->request->post('order_labels')) - $order_labels = array(); - - if(empty($order->id)) - { - $order->id = $this->orders->add_order($order); - $this->design->assign('message_success', 'added'); - } - else - { - $this->orders->update_order($order->id, $order); - $this->design->assign('message_success', 'updated'); - } - - $this->orders->update_order_labels($order->id, $order_labels); - - if($order->id) - { - // Покупки - $purchases = array(); - if($this->request->post('purchases')) - { - foreach($this->request->post('purchases') as $n=>$va) foreach($va as $i=>$v) - { - if(empty($purchases[$i])) - $purchases[$i] = new stdClass; - $purchases[$i]->$n = $v; - } - } - $posted_purchases_ids = array(); - foreach($purchases as $purchase) - { - $variant = $this->variants->get_variant($purchase->variant_id); - - if(!empty($purchase->id)) - if(!empty($variant)) - $this->orders->update_purchase($purchase->id, array('variant_id'=>$purchase->variant_id, 'variant_name'=>$variant->name, 'sku'=>$variant->sku,'price'=>$purchase->price, 'amount'=>$purchase->amount)); - else - $this->orders->update_purchase($purchase->id, array('price'=>$purchase->price, 'amount'=>$purchase->amount)); - elseif(!$purchase->id = $this->orders->add_purchase(array('order_id'=>$order->id, 'variant_id'=>$purchase->variant_id, 'variant_name'=>$variant->name, 'price'=>$purchase->price, 'amount'=>$purchase->amount))) - $this->design->assign('message_error', 'error_closing'); - - $posted_purchases_ids[] = $purchase->id; - } - - // Удалить непереданные товары - foreach($this->orders->get_purchases(array('order_id'=>$order->id)) as $p) - if(!in_array($p->id, $posted_purchases_ids)) - $this->orders->delete_purchase($p->id); - - // Принять? - if($this->request->post('status_new')) - $new_status = 0; - elseif($this->request->post('status_accept')) - $new_status = 1; - elseif($this->request->post('status_done')) - $new_status = 2; - elseif($this->request->post('status_deleted')) - $new_status = 3; - else - $new_status = $this->request->post('status', 'string'); - - if($new_status == 0) - { - if(!$this->orders->open(intval($order->id))) - $this->design->assign('message_error', 'error_open'); - else - $this->orders->update_order($order->id, array('status'=>0)); - } - elseif($new_status == 1) - { - if(!$this->orders->close(intval($order->id))) - $this->design->assign('message_error', 'error_closing'); - else - $this->orders->update_order($order->id, array('status'=>1)); - } - elseif($new_status == 2) - { - if(!$this->orders->close(intval($order->id))) - $this->design->assign('message_error', 'error_closing'); - else - $this->orders->update_order($order->id, array('status'=>2)); - } - elseif($new_status == 3) - { - if(!$this->orders->open(intval($order->id))) - $this->design->assign('message_error', 'error_open'); - else - $this->orders->update_order($order->id, array('status'=>3)); - header('Location: '.$this->request->get('return')); - } - $order = $this->orders->get_order($order->id); - - // Отправляем письмо пользователю - if($this->request->post('notify_user')) - $this->notify->email_order_user($order->id); - } - - } - else - { - $order->id = $this->request->get('id', 'integer'); - $order = $this->orders->get_order(intval($order->id)); - // Метки заказа - $order_labels = array(); - if(isset($order->id)) - foreach($this->orders->get_order_labels($order->id) as $ol) - $order_labels[] = $ol->id; - } - - - $subtotal = 0; - $purchases_count = 0; - if($order && $purchases = $this->orders->get_purchases(array('order_id'=>$order->id))) - { - // Покупки - $products_ids = array(); - $variants_ids = array(); - foreach($purchases as $purchase) - { - $products_ids[] = $purchase->product_id; - $variants_ids[] = $purchase->variant_id; - } - - $products = array(); - foreach($this->products->get_products(array('id'=>$products_ids)) as $p) - $products[$p->id] = $p; - - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[] = $image; - - $variants = array(); - foreach($this->variants->get_variants(array('product_id'=>$products_ids)) as $v) - $variants[$v->id] = $v; - - foreach($variants as $variant) - if(!empty($products[$variant->product_id])) - $products[$variant->product_id]->variants[] = $variant; - - - foreach($purchases as &$purchase) - { - if(!empty($products[$purchase->product_id])) - $purchase->product = $products[$purchase->product_id]; - if(!empty($variants[$purchase->variant_id])) - $purchase->variant = $variants[$purchase->variant_id]; - $subtotal += $purchase->price*$purchase->amount; - $purchases_count += $purchase->amount; - } - - } - else - { - $purchases = array(); - } - - // Если новый заказ и передали get параметры - if(empty($order->id)) - { - $order = new stdClass; - if(empty($order->phone)) - $order->phone = $this->request->get('phone', 'string'); - if(empty($order->name)) - $order->name = $this->request->get('name', 'string'); - if(empty($order->address)) - $order->address = $this->request->get('address', 'string'); - if(empty($order->email)) - $order->email = $this->request->get('email', 'string'); - } - - $this->design->assign('purchases', $purchases); - $this->design->assign('purchases_count', $purchases_count); - $this->design->assign('subtotal', $subtotal); - $this->design->assign('order', $order); - - if(!empty($order->id)) - { - // Способ доставки - $delivery = $this->delivery->get_delivery($order->delivery_id); - $this->design->assign('delivery', $delivery); - - // Способ оплаты - $payment_method = $this->payment->get_payment_method($order->payment_method_id); - - if(!empty($payment_method)) - { - $this->design->assign('payment_method', $payment_method); - - // Валюта оплаты - $payment_currency = $this->money->get_currency(intval($payment_method->currency_id)); - $this->design->assign('payment_currency', $payment_currency); - } - // Пользователь - if($order->user_id) - $this->design->assign('user', $this->users->get_user(intval($order->user_id))); - - // Соседние заказы - $this->design->assign('next_order', $this->orders->get_next_order($order->id, $this->request->get('status', 'string'))); - $this->design->assign('prev_order', $this->orders->get_prev_order($order->id, $this->request->get('status', 'string'))); - } - - // Все способы доставки - $deliveries = $this->delivery->get_deliveries(); - $this->design->assign('deliveries', $deliveries); - - // Все способы оплаты - $payment_methods = $this->payment->get_payment_methods(); - $this->design->assign('payment_methods', $payment_methods); - - // Метки заказов - $labels = $this->orders->get_labels(); - $this->design->assign('labels', $labels); - - $this->design->assign('order_labels', $order_labels); - - if($this->request->get('view') == 'print') - return $this->design->fetch('order_print.tpl'); - else - return $this->design->fetch('order.tpl'); - } -} \ No newline at end of file +request->method('post')) + { + $order->id = $this->request->post('id', 'integer'); + $order->name = $this->request->post('name'); + $order->email = $this->request->post('email'); + $order->phone = $this->request->post('phone'); + $order->address = $this->request->post('address'); + $order->comment = $this->request->post('comment'); + $order->note = $this->request->post('note'); + $order->discount = $this->request->post('discount', 'floatr'); + $order->coupon_discount = $this->request->post('coupon_discount', 'floatr'); + $order->delivery_id = $this->request->post('delivery_id', 'integer'); + $order->delivery_price = $this->request->post('delivery_price', 'float'); + $order->payment_method_id = $this->request->post('payment_method_id', 'integer'); + $order->paid = $this->request->post('paid', 'integer'); + $order->user_id = $this->request->post('user_id', 'integer'); + $order->separate_delivery = $this->request->post('separate_delivery', 'integer'); + + if(!$order_labels = $this->request->post('order_labels')) + $order_labels = array(); + + if(empty($order->id)) + { + $order->id = $this->orders->add_order($order); + $this->design->assign('message_success', 'added'); + } + else + { + $this->orders->update_order($order->id, $order); + $this->design->assign('message_success', 'updated'); + } + + $this->orders->update_order_labels($order->id, $order_labels); + + if($order->id) + { + // Покупки + $purchases = array(); + if($this->request->post('purchases')) + { + foreach($this->request->post('purchases') as $n=>$va) foreach($va as $i=>$v) + { + if(empty($purchases[$i])) + $purchases[$i] = new stdClass; + $purchases[$i]->$n = $v; + } + } + $posted_purchases_ids = array(); + foreach($purchases as $purchase) + { + $variant = $this->variants->get_variant($purchase->variant_id); + + if(!empty($purchase->id)) + if(!empty($variant)) + $this->orders->update_purchase($purchase->id, array('variant_id'=>$purchase->variant_id, 'variant_name'=>$variant->name, 'sku'=>$variant->sku,'price'=>$purchase->price, 'amount'=>$purchase->amount)); + else + $this->orders->update_purchase($purchase->id, array('price'=>$purchase->price, 'amount'=>$purchase->amount)); + elseif(!$purchase->id = $this->orders->add_purchase(array('order_id'=>$order->id, 'variant_id'=>$purchase->variant_id, 'variant_name'=>$variant->name, 'price'=>$purchase->price, 'amount'=>$purchase->amount))) + $this->design->assign('message_error', 'error_closing'); + + $posted_purchases_ids[] = $purchase->id; + } + + // Удалить непереданные товары + foreach($this->orders->get_purchases(array('order_id'=>$order->id)) as $p) + if(!in_array($p->id, $posted_purchases_ids)) + $this->orders->delete_purchase($p->id); + + // Принять? + if($this->request->post('status_new')) + $new_status = 0; + elseif($this->request->post('status_accept')) + $new_status = 1; + elseif($this->request->post('status_done')) + $new_status = 2; + elseif($this->request->post('status_deleted')) + $new_status = 3; + else + $new_status = $this->request->post('status', 'string'); + + if($new_status == 0) + { + if(!$this->orders->open(intval($order->id))) + $this->design->assign('message_error', 'error_open'); + else + $this->orders->update_order($order->id, array('status'=>0)); + } + elseif($new_status == 1) + { + if(!$this->orders->close(intval($order->id))) + $this->design->assign('message_error', 'error_closing'); + else + $this->orders->update_order($order->id, array('status'=>1)); + } + elseif($new_status == 2) + { + if(!$this->orders->close(intval($order->id))) + $this->design->assign('message_error', 'error_closing'); + else + $this->orders->update_order($order->id, array('status'=>2)); + } + elseif($new_status == 3) + { + if(!$this->orders->open(intval($order->id))) + $this->design->assign('message_error', 'error_open'); + else + $this->orders->update_order($order->id, array('status'=>3)); + header('Location: '.$this->request->get('return')); + } + $order = $this->orders->get_order($order->id); + + // Отправляем письмо пользователю + if($this->request->post('notify_user')) + $this->notify->email_order_user($order->id); + } + + } + else + { + $order->id = $this->request->get('id', 'integer'); + $order = $this->orders->get_order(intval($order->id)); + // Метки заказа + $order_labels = array(); + if(isset($order->id)) + foreach($this->orders->get_order_labels($order->id) as $ol) + $order_labels[] = $ol->id; + } + + + $subtotal = 0; + $purchases_count = 0; + if($order && $purchases = $this->orders->get_purchases(array('order_id'=>$order->id))) + { + // Покупки + $products_ids = array(); + $variants_ids = array(); + foreach($purchases as $purchase) + { + $products_ids[] = $purchase->product_id; + $variants_ids[] = $purchase->variant_id; + } + + $products = array(); + foreach($this->products->get_products(array('id'=>$products_ids)) as $p) + $products[$p->id] = $p; + + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[] = $image; + + $variants = array(); + foreach($this->variants->get_variants(array('product_id'=>$products_ids)) as $v) + $variants[$v->id] = $v; + + foreach($variants as $variant) + if(!empty($products[$variant->product_id])) + $products[$variant->product_id]->variants[] = $variant; + + + foreach($purchases as &$purchase) + { + if(!empty($products[$purchase->product_id])) + $purchase->product = $products[$purchase->product_id]; + if(!empty($variants[$purchase->variant_id])) + $purchase->variant = $variants[$purchase->variant_id]; + $subtotal += $purchase->price*$purchase->amount; + $purchases_count += $purchase->amount; + } + + } + else + { + $purchases = array(); + } + + // Если новый заказ и передали get параметры + if(empty($order->id)) + { + $order = new stdClass; + if(empty($order->phone)) + $order->phone = $this->request->get('phone', 'string'); + if(empty($order->name)) + $order->name = $this->request->get('name', 'string'); + if(empty($order->address)) + $order->address = $this->request->get('address', 'string'); + if(empty($order->email)) + $order->email = $this->request->get('email', 'string'); + } + + $this->design->assign('purchases', $purchases); + $this->design->assign('purchases_count', $purchases_count); + $this->design->assign('subtotal', $subtotal); + $this->design->assign('order', $order); + + if(!empty($order->id)) + { + // Способ доставки + $delivery = $this->delivery->get_delivery($order->delivery_id); + $this->design->assign('delivery', $delivery); + + // Способ оплаты + $payment_method = $this->payment->get_payment_method($order->payment_method_id); + + if(!empty($payment_method)) + { + $this->design->assign('payment_method', $payment_method); + + // Валюта оплаты + $payment_currency = $this->money->get_currency(intval($payment_method->currency_id)); + $this->design->assign('payment_currency', $payment_currency); + } + // Пользователь + if($order->user_id) + $this->design->assign('user', $this->users->get_user(intval($order->user_id))); + + // Соседние заказы + $this->design->assign('next_order', $this->orders->get_next_order($order->id, $this->request->get('status', 'string'))); + $this->design->assign('prev_order', $this->orders->get_prev_order($order->id, $this->request->get('status', 'string'))); + } + + // Все способы доставки + $deliveries = $this->delivery->get_deliveries(); + $this->design->assign('deliveries', $deliveries); + + // Все способы оплаты + $payment_methods = $this->payment->get_payment_methods(); + $this->design->assign('payment_methods', $payment_methods); + + // Метки заказов + $labels = $this->orders->get_labels(); + $this->design->assign('labels', $labels); + + $this->design->assign('order_labels', $order_labels); + + if($this->request->get('view') == 'print') + return $this->design->fetch('order_print.tpl'); + else + return $this->design->fetch('order.tpl'); + } +} diff --git a/simpla/OrdersAdmin.php b/simpla/OrdersAdmin.php index bd0ba2b..d479365 100755 --- a/simpla/OrdersAdmin.php +++ b/simpla/OrdersAdmin.php @@ -1,145 +1,153 @@ -request->get('page', 'integer')); - - $filter['limit'] = 40; - - // Поиск - $keyword = $this->request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } - - // Фильтр по метке - $label = $this->orders->get_label($this->request->get('label')); - if(!empty($label)) - { - $filter['label'] = $label->id; - $this->design->assign('label', $label); - } - - - // Обработка действий - if($this->request->method('post')) - { - - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'delete': - { - foreach($ids as $id) - { - $o = $this->orders->get_order(intval($id)); - if($o->status<3) - { - $this->orders->update_order($id, array('status'=>3)); - $this->orders->open($id); - } - else - $this->orders->delete_order($id); - } - break; - } - case 'set_status_0': - { - foreach($ids as $id) - { - if($this->orders->open(intval($id))) - $this->orders->update_order($id, array('status'=>0)); - } - break; - } - case 'set_status_1': - { - foreach($ids as $id) - { - if(!$this->orders->close(intval($id))) - $this->design->assign('message_error', 'error_closing'); - else - $this->orders->update_order($id, array('status'=>1)); - } - break; - } - case 'set_status_2': - { - foreach($ids as $id) - { - if(!$this->orders->close(intval($id))) - $this->design->assign('message_error', 'error_closing'); - else - $this->orders->update_order($id, array('status'=>2)); - } - break; - } - case(preg_match('/^set_label_([0-9]+)/', $this->request->post('action'), $a) ? true : false): - { - $l_id = intval($a[1]); - if($l_id>0) - foreach($ids as $id) - { - $this->orders->add_order_labels($id, $l_id); - } - break; - } - case(preg_match('/^unset_label_([0-9]+)/', $this->request->post('action'), $a) ? true : false): - { - $l_id = intval($a[1]); - if($l_id>0) - foreach($ids as $id) - { - $this->orders->delete_order_labels($id, $l_id); - } - break; - } - } - } - - if(empty($keyword)) - { - $status = $this->request->get('status', 'integer'); - $filter['status'] = $status; - $this->design->assign('status', $status); - } - - $orders_count = $this->orders->count_orders($filter); - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $filter['limit'] = $orders_count; - - // Отображение - $orders = array(); - foreach($this->orders->get_orders($filter) as $o) - $orders[$o->id] = $o; - - // Метки заказов - $orders_labels = array(); - foreach($this->orders->get_order_labels(array_keys($orders)) as $ol) - $orders[$ol->order_id]->labels[] = $ol; - - $this->design->assign('pages_count', ceil($orders_count/$filter['limit'])); - $this->design->assign('current_page', $filter['page']); - - $this->design->assign('orders_count', $orders_count); - - $this->design->assign('orders', $orders); - - // Метки заказов - $labels = $this->orders->get_labels(); - $this->design->assign('labels', $labels); - - return $this->design->fetch('orders.tpl'); - } -} +request->get('page', 'integer')); + + $filter['limit'] = 40; + + // Поиск + $keyword = $this->request->get('keyword', 'string'); + if(!empty($keyword)) + { + $filter['keyword'] = $keyword; + $this->design->assign('keyword', $keyword); + } + + // Фильтр по метке + $label = $this->orders->get_label($this->request->get('label')); + if(!empty($label)) + { + $filter['label'] = $label->id; + $this->design->assign('label', $label); + } + + + // Обработка действий + if($this->request->method('post')) + { + + // Действия с выбранными + $ids = $this->request->post('check'); + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'delete': + { + foreach($ids as $id) + { + $o = $this->orders->get_order(intval($id)); + if($o->status<3) + { + $this->orders->update_order($id, array('status'=>3)); + $this->orders->open($id); + } + else + $this->orders->delete_order($id); + } + break; + } + case 'set_status_0': + { + foreach($ids as $id) + { + if($this->orders->open(intval($id))) + $this->orders->update_order($id, array('status'=>0)); + } + break; + } + case 'set_status_1': + { + foreach($ids as $id) + { + if(!$this->orders->close(intval($id))) + $this->design->assign('message_error', 'error_closing'); + else + $this->orders->update_order($id, array('status'=>1)); + } + break; + } + case 'set_status_2': + { + foreach($ids as $id) + { + if(!$this->orders->close(intval($id))) + $this->design->assign('message_error', 'error_closing'); + else + $this->orders->update_order($id, array('status'=>2)); + } + break; + } + case(preg_match('/^set_label_([0-9]+)/', $this->request->post('action'), $a) ? true : false): + { + $l_id = intval($a[1]); + if($l_id>0) + foreach($ids as $id) + { + $this->orders->add_order_labels($id, $l_id); + } + break; + } + case(preg_match('/^unset_label_([0-9]+)/', $this->request->post('action'), $a) ? true : false): + { + $l_id = intval($a[1]); + if($l_id>0) + foreach($ids as $id) + { + $this->orders->delete_order_labels($id, $l_id); + } + break; + } + } + } + + if(empty($keyword)) + { + $status = $this->request->get('status', 'integer'); + $filter['status'] = $status; + $this->design->assign('status', $status); + } + + $orders_count = $this->orders->count_orders($filter); + // Показать все страницы сразу + if($this->request->get('page') == 'all') + $filter['limit'] = $orders_count; + + // Отображение + $orders = array(); + foreach($this->orders->get_orders($filter) as $o) + $orders[$o->id] = $o; + + // Метки заказов + $orders_labels = array(); + foreach($this->orders->get_order_labels(array_keys($orders)) as $ol) + $orders[$ol->order_id]->labels[] = $ol; + + $this->design->assign('pages_count', ceil($orders_count/$filter['limit'])); + $this->design->assign('current_page', $filter['page']); + + $this->design->assign('orders_count', $orders_count); + + $this->design->assign('orders', $orders); + + // Метки заказов + $labels = $this->orders->get_labels(); + $this->design->assign('labels', $labels); + + return $this->design->fetch('orders.tpl'); + } +} diff --git a/simpla/OrdersLabelAdmin.php b/simpla/OrdersLabelAdmin.php index e6f7046..de48076 100755 --- a/simpla/OrdersLabelAdmin.php +++ b/simpla/OrdersLabelAdmin.php @@ -1,45 +1,55 @@ -color = 'ffffff'; - if($this->request->method('POST')) - { +color = 'ffffff'; + if($this->request->method('POST')) + { $label->id = $this->request->post('id', 'integer'); $label->name = $this->request->post('name'); $label->color = $this->request->post('color'); if(empty($label->name)) - { - $this->design->assign('message_error', 'empty_name'); - } - elseif(empty($label->id)) + { + $this->design->assign('message_error', 'empty_name'); + } + elseif(empty($label->id)) { $label->id = $this->orders->add_label($label); $label = $this->orders->get_label($label->id); - $this->design->assign('message_success', 'added'); - } - else - { - $this->orders->update_label($label->id, $label); - $label = $this->orders->get_label($label->id); - $this->design->assign('message_success', 'updated'); - } - } - else - { - $id = $this->request->get('id', 'integer'); - if(!empty($id)) - $label = $this->orders->get_label(intval($id)); - } - - $this->design->assign('label', $label); - - return $this->design->fetch('orders_label.tpl'); - } - -} - + $this->design->assign('message_success', 'added'); + } + else + { + $this->orders->update_label($label->id, $label); + $label = $this->orders->get_label($label->id); + $this->design->assign('message_success', 'updated'); + } + } + else + { + $id = $this->request->get('id', 'integer'); + if(!empty($id)) + $label = $this->orders->get_label(intval($id)); + } + + $this->design->assign('label', $label); + + return $this->design->fetch('orders_label.tpl'); + } + +} + diff --git a/simpla/OrdersLabelsAdmin.php b/simpla/OrdersLabelsAdmin.php index e050038..e741d73 100755 --- a/simpla/OrdersLabelsAdmin.php +++ b/simpla/OrdersLabelsAdmin.php @@ -1,45 +1,50 @@ -request->method('post')) - { - // Сортировка - $positions = $this->request->post('positions'); - $ids = array_keys($positions); - sort($positions); - foreach($positions as $i=>$position) - $this->orders->update_label($ids[$i], array('position'=>$position)); - - - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'delete': - { - foreach($ids as $id) - $this->orders->delete_label($id); - break; - } - } - } - - // Отображение - $labels = $this->orders->get_labels(); - - $this->design->assign('labels', $labels); - return $this->design->fetch('orders_labels.tpl'); - } -} - - -?> \ No newline at end of file +request->method('post')) + { + // Сортировка + $positions = $this->request->post('positions'); + $ids = array_keys($positions); + sort($positions); + foreach($positions as $i=>$position) + $this->orders->update_label($ids[$i], array('position'=>$position)); + + + // Действия с выбранными + $ids = $this->request->post('check'); + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'delete': + { + foreach($ids as $id) + $this->orders->delete_label($id); + break; + } + } + } + + // Отображение + $labels = $this->orders->get_labels(); + + $this->design->assign('labels', $labels); + return $this->design->fetch('orders_labels.tpl'); + } +} diff --git a/simpla/PageAdmin.php b/simpla/PageAdmin.php index f284e5a..49c5336 100755 --- a/simpla/PageAdmin.php +++ b/simpla/PageAdmin.php @@ -1,74 +1,83 @@ -request->method('POST')) - { - $page->id = $this->request->post('id', 'integer'); - $page->name = $this->request->post('name'); - $page->header = $this->request->post('header'); - $page->url = trim($this->request->post('url')); - $page->meta_title = $this->request->post('meta_title'); - $page->meta_keywords = $this->request->post('meta_keywords'); - $page->meta_description = $this->request->post('meta_description'); - $page->body = $this->request->post('body'); - $page->menu_id = $this->request->post('menu_id', 'integer'); - $page->visible = $this->request->post('visible', 'boolean'); - - ## Не допустить одинаковые URL разделов. - if(($p = $this->pages->get_page($page->url)) && $p->id!=$page->id) - { - $this->design->assign('message_error', 'url_exists'); - } - else - { - if(empty($page->id)) - { - $page->id = $this->pages->add_page($page); - $page = $this->pages->get_page($page->id); - $this->design->assign('message_success', 'added'); - } - else - { - $this->pages->update_page($page->id, $page); - $page = $this->pages->get_page($page->id); - $this->design->assign('message_success', 'updated'); - } - } - } - else - { - $id = $this->request->get('id', 'integer'); - if(!empty($id)) - $page = $this->pages->get_page(intval($id)); - else - { - $page->menu_id = $this->request->get('menu_id'); - $page->visible = 1; - } - } - - $this->design->assign('page', $page); - - $menus = $this->pages->get_menus(); - $this->design->assign('menus', $menus); - - // Текущее меню - if(isset($page->menu_id)) - $menu_id = $page->menu_id; - if(empty($menu_id) || !$menu = $this->pages->get_menu($menu_id)) - { - $menu = reset($menus); - } - $this->design->assign('menu', $menu); - - - return $this->design->fetch('page.tpl'); - } - -} - +request->method('POST')) + { + $page->id = $this->request->post('id', 'integer'); + $page->name = $this->request->post('name'); + $page->header = $this->request->post('header'); + $page->url = trim($this->request->post('url')); + $page->meta_title = $this->request->post('meta_title'); + $page->meta_keywords = $this->request->post('meta_keywords'); + $page->meta_description = $this->request->post('meta_description'); + $page->body = $this->request->post('body'); + $page->menu_id = $this->request->post('menu_id', 'integer'); + $page->visible = $this->request->post('visible', 'boolean'); + + ## Не допустить одинаковые URL разделов. + if(($p = $this->pages->get_page($page->url)) && $p->id!=$page->id) + { + $this->design->assign('message_error', 'url_exists'); + } + else + { + if(empty($page->id)) + { + $page->id = $this->pages->add_page($page); + $page = $this->pages->get_page($page->id); + $this->design->assign('message_success', 'added'); + } + else + { + $this->pages->update_page($page->id, $page); + $page = $this->pages->get_page($page->id); + $this->design->assign('message_success', 'updated'); + } + } + } + else + { + $id = $this->request->get('id', 'integer'); + if(!empty($id)) + $page = $this->pages->get_page(intval($id)); + else + { + $page->menu_id = $this->request->get('menu_id'); + $page->visible = 1; + } + } + + $this->design->assign('page', $page); + + $menus = $this->pages->get_menus(); + $this->design->assign('menus', $menus); + + // Текущее меню + if(isset($page->menu_id)) + $menu_id = $page->menu_id; + if(empty($menu_id) || !$menu = $this->pages->get_menu($menu_id)) + { + $menu = reset($menus); + } + $this->design->assign('menu', $menu); + + return $this->design->fetch('page.tpl'); + } + +} + diff --git a/simpla/PagesAdmin.php b/simpla/PagesAdmin.php index 05c7103..7349c28 100755 --- a/simpla/PagesAdmin.php +++ b/simpla/PagesAdmin.php @@ -1,72 +1,76 @@ -pages->get_menus(); - $this->design->assign('menus', $menus); - - // Текущее меню - $menu_id = $this->request->get('menu_id', 'integer'); - if(!$menu_id || !$menu = $this->pages->get_menu($menu_id)) - { - $menu = reset($menus); - } - $this->design->assign('menu', $menu); - - - // Обработка действий - if($this->request->method('post')) - { - // Сортировка - $positions = $this->request->post('positions'); - $ids = array_keys($positions); - sort($positions); - foreach($positions as $i=>$position) - $this->pages->update_page($ids[$i], array('position'=>$position)); - - - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'disable': - { - $this->pages->update_page($ids, array('visible'=>0)); - break; - } - case 'enable': - { - $this->pages->update_page($ids, array('visible'=>1)); - break; - } - case 'delete': - { - foreach($ids as $id) - $this->pages->delete_page($id); - break; - } - } - - } - - - - // Отображение - $pages = $this->pages->get_pages(array('menu_id'=>$menu->id)); - - $this->design->assign('pages', $pages); - return $this->design->fetch('pages.tpl'); - } -} - - -?> \ No newline at end of file +pages->get_menus(); + $this->design->assign('menus', $menus); + + // Текущее меню + $menu_id = $this->request->get('menu_id', 'integer'); + if(!$menu_id || !$menu = $this->pages->get_menu($menu_id)) + { + $menu = reset($menus); + } + $this->design->assign('menu', $menu); + + + // Обработка действий + if($this->request->method('post')) + { + // Сортировка + $positions = $this->request->post('positions'); + $ids = array_keys($positions); + sort($positions); + foreach($positions as $i=>$position) + $this->pages->update_page($ids[$i], array('position'=>$position)); + + + // Действия с выбранными + $ids = $this->request->post('check'); + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'disable': + { + $this->pages->update_page($ids, array('visible'=>0)); + break; + } + case 'enable': + { + $this->pages->update_page($ids, array('visible'=>1)); + break; + } + case 'delete': + { + foreach($ids as $id) + $this->pages->delete_page($id); + break; + } + } + + } + + // Отображение + $pages = $this->pages->get_pages(array('menu_id'=>$menu->id)); + + $this->design->assign('pages', $pages); + + return $this->design->fetch('pages.tpl'); + } +} diff --git a/simpla/PaymentMethodAdmin.php b/simpla/PaymentMethodAdmin.php index b51409a..c6f7900 100755 --- a/simpla/PaymentMethodAdmin.php +++ b/simpla/PaymentMethodAdmin.php @@ -1,76 +1,85 @@ -request->method('post')) - { - $payment_method->id = $this->request->post('id', 'intgeger'); - $payment_method->enabled = $this->request->post('enabled', 'boolean'); - $payment_method->name = $this->request->post('name'); - $payment_method->currency_id = $this->request->post('currency_id'); - $payment_method->description = $this->request->post('description'); - $payment_method->module = $this->request->post('module', 'string'); - - $payment_settings = $this->request->post('payment_settings'); - +request->method('post')) + { + $payment_method->id = $this->request->post('id', 'intgeger'); + $payment_method->enabled = $this->request->post('enabled', 'boolean'); + $payment_method->name = $this->request->post('name'); + $payment_method->currency_id = $this->request->post('currency_id'); + $payment_method->description = $this->request->post('description'); + $payment_method->module = $this->request->post('module', 'string'); + + $payment_settings = $this->request->post('payment_settings'); + if(!$payment_deliveries = $this->request->post('payment_deliveries')) $payment_deliveries = array(); if(empty($payment_method->name)) - { - $this->design->assign('message_error', 'empty_name'); - } + { + $this->design->assign('message_error', 'empty_name'); + } elseif(empty($payment_method->id)) { $payment_method->id = $this->payment->add_payment_method($payment_method); $this->design->assign('message_success', 'Добавлено'); - } - else - { - $this->payment->update_payment_method($payment_method->id, $payment_method); - $this->design->assign('message_success', 'Обновлено'); - } - if($payment_method->id) - { - $this->payment->update_payment_settings($payment_method->id, $payment_settings); - $this->payment->update_payment_deliveries($payment_method->id, $payment_deliveries); - } - } - else - { - $payment_method->id = $this->request->get('id', 'integer'); - if(!empty($payment_method->id)) - { - $payment_method = $this->payment->get_payment_method($payment_method->id); - $payment_settings = $this->payment->get_payment_settings($payment_method->id); - } - else - { - $payment_settings = array(); - } - $payment_deliveries = $this->payment->get_payment_deliveries($payment_method->id); - } - $this->design->assign('payment_deliveries', $payment_deliveries); - // Связанные способы доставки - $deliveries = $this->delivery->get_deliveries(); - $this->design->assign('deliveries', $deliveries); - - $this->design->assign('payment_method', $payment_method); - $this->design->assign('payment_settings', $payment_settings); - $payment_modules = $this->payment->get_payment_modules(); - $this->design->assign('payment_modules', $payment_modules); - - $currencies = $this->money->get_currencies(); - $this->design->assign('currencies', $currencies); - - - return $this->design->fetch('payment_method.tpl'); - } - -} - + } + else + { + $this->payment->update_payment_method($payment_method->id, $payment_method); + $this->design->assign('message_success', 'Обновлено'); + } + if($payment_method->id) + { + $this->payment->update_payment_settings($payment_method->id, $payment_settings); + $this->payment->update_payment_deliveries($payment_method->id, $payment_deliveries); + } + } + else + { + $payment_method->id = $this->request->get('id', 'integer'); + if(!empty($payment_method->id)) + { + $payment_method = $this->payment->get_payment_method($payment_method->id); + $payment_settings = $this->payment->get_payment_settings($payment_method->id); + } + else + { + $payment_settings = array(); + } + $payment_deliveries = $this->payment->get_payment_deliveries($payment_method->id); + } + $this->design->assign('payment_deliveries', $payment_deliveries); + // Связанные способы доставки + $deliveries = $this->delivery->get_deliveries(); + $this->design->assign('deliveries', $deliveries); + + $this->design->assign('payment_method', $payment_method); + $this->design->assign('payment_settings', $payment_settings); + $payment_modules = $this->payment->get_payment_modules(); + $this->design->assign('payment_modules', $payment_modules); + + $currencies = $this->money->get_currencies(); + $this->design->assign('currencies', $currencies); + + return $this->design->fetch('payment_method.tpl'); + } + +} + diff --git a/simpla/PaymentMethodsAdmin.php b/simpla/PaymentMethodsAdmin.php index 9250fa8..47b815b 100755 --- a/simpla/PaymentMethodsAdmin.php +++ b/simpla/PaymentMethodsAdmin.php @@ -1,59 +1,61 @@ -request->method('post')) - { - // Сортировка - $positions = $this->request->post('positions'); - $ids = array_keys($positions); - sort($positions); - foreach($positions as $i=>$position) - $this->payment->update_payment_method($ids[$i], array('position'=>$position)); - - // Действия с выбранными - $ids = $this->request->post('check'); - - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'disable': - { - $this->payment->update_payment_method($ids, array('enabled'=>0)); - break; - } - case 'enable': - { - $this->payment->update_payment_method($ids, array('enabled'=>1)); - break; - } - case 'delete': - { - foreach($ids as $id) - $this->payment->delete_payment_method($id); - break; - } - } - - } - - - - // Отображение - $payment_methods = $this->payment->get_payment_methods(); - $this->design->assign('payment_methods', $payment_methods); - return $this->design->fetch('payment_methods.tpl'); - } -} - - -?> \ No newline at end of file +request->method('post')) + { + // Сортировка + $positions = $this->request->post('positions'); + $ids = array_keys($positions); + sort($positions); + foreach($positions as $i=>$position) + $this->payment->update_payment_method($ids[$i], array('position'=>$position)); + + // Действия с выбранными + $ids = $this->request->post('check'); + + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'disable': + { + $this->payment->update_payment_method($ids, array('enabled'=>0)); + break; + } + case 'enable': + { + $this->payment->update_payment_method($ids, array('enabled'=>1)); + break; + } + case 'delete': + { + foreach($ids as $id) + $this->payment->delete_payment_method($id); + break; + } + } + + } + + // Отображение + $payment_methods = $this->payment->get_payment_methods(); + $this->design->assign('payment_methods', $payment_methods); + + return $this->design->fetch('payment_methods.tpl'); + } +} diff --git a/simpla/PostAdmin.php b/simpla/PostAdmin.php index 148415c..ff54bdf 100755 --- a/simpla/PostAdmin.php +++ b/simpla/PostAdmin.php @@ -1,64 +1,72 @@ -request->method('post')) - { - $post->id = $this->request->post('id', 'integer'); - $post->name = $this->request->post('name'); - $post->date = date('Y-m-d', strtotime($this->request->post('date'))); - - $post->visible = $this->request->post('visible', 'boolean'); - - $post->url = trim($this->request->post('url', 'string')); - $post->meta_title = $this->request->post('meta_title'); - $post->meta_keywords = $this->request->post('meta_keywords'); - $post->meta_description = $this->request->post('meta_description'); - - $post->annotation = $this->request->post('annotation'); - $post->text = $this->request->post('body'); - - // Не допустить одинаковые URL разделов. - if(($a = $this->blog->get_post($post->url)) && $a->id!=$post->id) - { - $this->design->assign('message_error', 'url_exists'); - } - else - { - if(empty($post->id)) - { - $post->id = $this->blog->add_post($post); - $post = $this->blog->get_post($post->id); - $this->design->assign('message_success', 'added'); - } - else - { - $this->blog->update_post($post->id, $post); - $post = $this->blog->get_post($post->id); - $this->design->assign('message_success', 'updated'); - } - } - } - else - { - $post->id = $this->request->get('id', 'integer'); - $post = $this->blog->get_post(intval($post->id)); - } - - if(empty($post)) - { - $post = new stdClass; - $post->date = date($this->settings->date_format, time()); - } - - $this->design->assign('post', $post); - - - return $this->design->fetch('post.tpl'); - } -} \ No newline at end of file +request->method('post')) + { + $post->id = $this->request->post('id', 'integer'); + $post->name = $this->request->post('name'); + $post->date = date('Y-m-d', strtotime($this->request->post('date'))); + + $post->visible = $this->request->post('visible', 'boolean'); + + $post->url = trim($this->request->post('url', 'string')); + $post->meta_title = $this->request->post('meta_title'); + $post->meta_keywords = $this->request->post('meta_keywords'); + $post->meta_description = $this->request->post('meta_description'); + + $post->annotation = $this->request->post('annotation'); + $post->text = $this->request->post('body'); + + // Не допустить одинаковые URL разделов. + if(($a = $this->blog->get_post($post->url)) && $a->id!=$post->id) + { + $this->design->assign('message_error', 'url_exists'); + } + else + { + if(empty($post->id)) + { + $post->id = $this->blog->add_post($post); + $post = $this->blog->get_post($post->id); + $this->design->assign('message_success', 'added'); + } + else + { + $this->blog->update_post($post->id, $post); + $post = $this->blog->get_post($post->id); + $this->design->assign('message_success', 'updated'); + } + } + } + else + { + $post->id = $this->request->get('id', 'integer'); + $post = $this->blog->get_post(intval($post->id)); + } + + if(empty($post)) + { + $post = new stdClass; + $post->date = date($this->settings->date_format, time()); + } + + $this->design->assign('post', $post); + + return $this->design->fetch('post.tpl'); + } +} diff --git a/simpla/ProductAdmin.php b/simpla/ProductAdmin.php index 9dfae0c..551692a 100755 --- a/simpla/ProductAdmin.php +++ b/simpla/ProductAdmin.php @@ -1,22 +1,28 @@ -request->method('post') && !empty($_POST)) { $product = new stdClass; @@ -30,7 +36,7 @@ public function fetch() $product->meta_title = $this->request->post('meta_title'); $product->meta_keywords = $this->request->post('meta_keywords'); $product->meta_description = $this->request->post('meta_description'); - + $product->annotation = $this->request->post('annotation'); $product->body = $this->request->post('body'); @@ -60,7 +66,7 @@ public function fetch() } // Свойства товара - $options = $this->request->post('options'); + $options = $this->request->post('options'); if(is_array($options)) { foreach($options as $f_id=>$val) @@ -83,17 +89,17 @@ public function fetch() } $related_products = $rp; } - + // Не допустить пустое название товара. if(empty($product->name)) - { + { $this->design->assign('message_error', 'empty_name'); if(!empty($product->id)) $images = $this->products->get_images(array('product_id'=>$product->id)); } // Не допустить одинаковые URL разделов. elseif(($p = $this->products->get_product($product->url)) && $p->id!=$product->id) - { + { $this->design->assign('message_error', 'url_exists'); if(!empty($product->id)) $images = $this->products->get_images(array('product_id'=>$product->id)); @@ -102,52 +108,52 @@ public function fetch() { if(empty($product->id)) { - $product->id = $this->products->add_product($product); - $product = $this->products->get_product($product->id); + $product->id = $this->products->add_product($product); + $product = $this->products->get_product($product->id); $this->design->assign('message_success', 'added'); - } - else - { - $this->products->update_product($product->id, $product); - $product = $this->products->get_product($product->id); + } + else + { + $this->products->update_product($product->id, $product); + $product = $this->products->get_product($product->id); $this->design->assign('message_success', 'updated'); - } - - if($product->id) - { - // Категории товара - $query = $this->db->placehold('DELETE FROM __products_categories WHERE product_id=?', $product->id); - $this->db->query($query); - if(is_array($product_categories)) - { - foreach($product_categories as $i=>$category) - $this->categories->add_product_category($product->id, $category->id, $i); - } - - // Варианты - if(is_array($variants)) - { - $variants_ids = array(); + } + + if($product->id) + { + // Категории товара + $query = $this->db->placehold('DELETE FROM __products_categories WHERE product_id=?', $product->id); + $this->db->query($query); + if(is_array($product_categories)) + { + foreach($product_categories as $i=>$category) + $this->categories->add_product_category($product->id, $category->id, $i); + } + + // Варианты + if(is_array($variants)) + { + $variants_ids = array(); foreach($variants as $index=>&$variant) { if($variant->stock == '∞' || $variant->stock == '') $variant->stock = null; - + // Удалить файл if(!empty($_POST['delete_attachment'][$index])) { $this->variants->delete_attachment($variant->id); } - - // Загрузить файлы - if(!empty($_FILES['attachment']['tmp_name'][$index]) && !empty($_FILES['attachment']['name'][$index])) - { - $attachment_tmp_name = $_FILES['attachment']['tmp_name'][$index]; - $attachment_name = $_FILES['attachment']['name'][$index]; - move_uploaded_file($attachment_tmp_name, $this->config->root_dir.'/'.$this->config->downloads_dir.$attachment_name); - $variant->attachment = $attachment_name; - } - + + // Загрузить файлы + if(!empty($_FILES['attachment']['tmp_name'][$index]) && !empty($_FILES['attachment']['name'][$index])) + { + $attachment_tmp_name = $_FILES['attachment']['tmp_name'][$index]; + $attachment_name = $_FILES['attachment']['name'][$index]; + move_uploaded_file($attachment_tmp_name, $this->config->root_dir.'/'.$this->config->downloads_dir.$attachment_name); + $variant->attachment = $attachment_name; + } + if(!empty($variant->id)) $this->variants->update_variant($variant->id, $variant); else @@ -157,98 +163,98 @@ public function fetch() } $variant = $this->variants->get_variant($variant->id); if(!empty($variant->id)) - $variants_ids[] = $variant->id; + $variants_ids[] = $variant->id; } - - + + // Удалить непереданные варианты $current_variants = $this->variants->get_variants(array('product_id'=>$product->id)); foreach($current_variants as $current_variant) if(!in_array($current_variant->id, $variants_ids)) - $this->variants->delete_variant($current_variant->id); - - //if(!empty($)) - + $this->variants->delete_variant($current_variant->id); + + //if(!empty($)) + // Отсортировать варианты asort($variants_ids); $i = 0; foreach($variants_ids as $variant_id) - { + { $this->variants->update_variant($variants_ids[$i], array('position'=>$variant_id)); $i++; } } - + // Удаление изображений $images = (array)$this->request->post('images'); $current_images = $this->products->get_images(array('product_id'=>$product->id)); foreach($current_images as $image) { if(!in_array($image->id, $images)) - $this->products->delete_image($image->id); + $this->products->delete_image($image->id); } - + // Порядок изображений if($images = $this->request->post('images')) { - $i=0; + $i=0; foreach($images as $id) { $this->products->update_image($id, array('position'=>$i)); $i++; } } - // Загрузка изображений - if($images = $this->request->files('images')) - { + // Загрузка изображений + if($images = $this->request->files('images')) + { for($i=0; $iimage->upload_image($images['tmp_name'][$i], $images['name'][$i])) - { - $this->products->add_image($product->id, $image_name); - } + if ($image_name = $this->image->upload_image($images['tmp_name'][$i], $images['name'][$i])) + { + $this->products->add_image($product->id, $image_name); + } else { $this->design->assign('error', 'error uploading image'); } } } - // Загрузка изображений из интернета и drag-n-drop файлов - if($images = $this->request->post('images_urls')) - { + // Загрузка изображений из интернета и drag-n-drop файлов + if($images = $this->request->post('images_urls')) + { foreach($images as $url) { // Если не пустой адрес и файл не локальный if(!empty($url) && $url != 'http://' && strstr($url,'/')!==false) - $this->products->add_image($product->id, $url); - elseif($dropped_images = $this->request->files('dropped_images')) - { - $key = array_search($url, $dropped_images['name']); - if ($key!==false && $image_name = $this->image->upload_image($dropped_images['tmp_name'][$key], $dropped_images['name'][$key])) - $this->products->add_image($product->id, $image_name); + $this->products->add_image($product->id, $url); + elseif($dropped_images = $this->request->files('dropped_images')) + { + $key = array_search($url, $dropped_images['name']); + if ($key!==false && $image_name = $this->image->upload_image($dropped_images['tmp_name'][$key], $dropped_images['name'][$key])) + $this->products->add_image($product->id, $image_name); } } } $images = $this->products->get_images(array('product_id'=>$product->id)); - - // Характеристики товара - - // Удалим все из товара + + // Характеристики товара + + // Удалим все из товара foreach($this->features->get_product_options($product->id) as $po) $this->features->delete_option($product->id, $po->feature_id); - + // Свойства текущей категории $category_features = array(); foreach($this->features->get_features(array('category_id'=>$product_categories[0])) as $f) $category_features[] = $f->id; - - if(is_array($options)) + + if(is_array($options)) foreach($options as $option) { if(in_array($option->feature_id, $category_features)) $this->features->update_option($product->id, $option->feature_id, $option->value); } - + // Новые характеристики $new_features_names = $this->request->post('new_features_names'); $new_features_values = $this->request->post('new_features_values'); @@ -273,19 +279,19 @@ public function fetch() // Свойства товара $options = $this->features->get_product_options($product->id); } - + // Связанные товары - $query = $this->db->placehold('DELETE FROM __related_products WHERE product_id=?', $product->id); - $this->db->query($query); - if(is_array($related_products)) - { - $pos = 0; - foreach($related_products as $i=>$related_product) - $this->products->add_related_product($product->id, $related_product->related_id, $pos++); - } - } + $query = $this->db->placehold('DELETE FROM __related_products WHERE product_id=?', $product->id); + $this->db->query($query); + if(is_array($related_products)) + { + $pos = 0; + foreach($related_products as $i=>$related_product) + $this->products->add_related_product($product->id, $related_product->related_id, $pos++); + } + } } - + //header('Location: '.$this->request->url(array('message_success'=>'updated'))); } else @@ -295,19 +301,19 @@ public function fetch() if($product) { - + // Категории товара $product_categories = $this->categories->get_categories(array('product_id'=>$product->id)); - + // Варианты товара $variants = $this->variants->get_variants(array('product_id'=>$product->id)); - + // Изображения товара $images = $this->products->get_images(array('product_id'=>$product->id)); - + // Свойства товара $options = $this->features->get_options(array('product_id'=>$product->id)); - + // Связанные товары $related_products = $this->products->get_related_products(array('product_id'=>$product->id)); } @@ -315,18 +321,18 @@ public function fetch() { // Сразу активен $product = new stdClass; - $product->visible = 1; + $product->visible = 1; } } - - + + if(empty($variants)) $variants = array(1); - + if(empty($product_categories)) { if($category_id = $this->request->get('category_id')) - $product_categories[0]->id = $category_id; + $product_categories[0]->id = $category_id; else $product_categories = array(1); } @@ -334,7 +340,7 @@ public function fetch() { $product->brand_id = $brand_id; } - + if(!empty($related_products)) { foreach($related_products as &$r_p) @@ -342,14 +348,14 @@ public function fetch() $temp_products = $this->products->get_products(array('id'=>array_keys($r_products))); foreach($temp_products as $temp_product) $r_products[$temp_product->id] = $temp_product; - + $related_products_images = $this->products->get_images(array('product_id'=>array_keys($r_products))); foreach($related_products_images as $image) { $r_products[$image->product_id]->images[] = $image; } } - + if(is_array($options)) { $temp_options = array(); @@ -357,7 +363,7 @@ public function fetch() $temp_options[$option->feature_id] = $option; $options = $temp_options; } - + $this->design->assign('product', $product); @@ -365,26 +371,26 @@ public function fetch() $this->design->assign('product_variants', $variants); $this->design->assign('product_images', $images); $this->design->assign('options', $options); - $this->design->assign('related_products', $related_products); - + $this->design->assign('related_products', $related_products); + // Все бренды $brands = $this->brands->get_brands(); $this->design->assign('brands', $brands); - + // Все категории $categories = $this->categories->get_categories_tree(); $this->design->assign('categories', $categories); - + // Все свойства товара $category = reset($product_categories); if(!is_object($category)) - $category = reset($categories); + $category = reset($categories); if(is_object($category)) { $features = $this->features->get_features(array('category_id'=>$category->id)); $this->design->assign('features', $features); } - - return $this->design->fetch('product.tpl'); + + return $this->design->fetch('product.tpl'); } -} \ No newline at end of file +} diff --git a/simpla/ProductsAdmin.php b/simpla/ProductsAdmin.php index d427050..c1004b9 100755 --- a/simpla/ProductsAdmin.php +++ b/simpla/ProductsAdmin.php @@ -1,263 +1,272 @@ -request->get('page', 'integer')); - - $filter['limit'] = $this->settings->products_num_admin; - - // Категории - $categories = $this->categories->get_categories_tree(); - $this->design->assign('categories', $categories); - - // Текущая категория - $category_id = $this->request->get('category_id', 'integer'); - if($category_id && $category = $this->categories->get_category($category_id)) - { - $filter['category_id'] = $category->children; - - // Бренды категории - $brands = $this->brands->get_brands(array('category_id'=>$filter['category_id'])); - $this->design->assign('brands', $brands); - } - - // Все бренды - $all_brands = $this->brands->get_brands(); - $this->design->assign('all_brands', $all_brands); - - // Текущий бренд - $brand_id = $this->request->get('brand_id', 'integer'); - if($brand_id && $brand = $this->brands->get_brand($brand_id)) - $filter['brand_id'] = $brand->id; - - // Текущий фильтр - if($f = $this->request->get('filter', 'string')) - { - if($f == 'featured') - $filter['featured'] = 1; - elseif($f == 'discounted') - $filter['discounted'] = 1; - elseif($f == 'visible') - $filter['visible'] = 1; - elseif($f == 'hidden') - $filter['visible'] = 0; - elseif($f == 'outofstock') - $filter['in_stock'] = 0; - $this->design->assign('filter', $f); - } - - // Поиск - $keyword = $this->request->get('keyword'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } - - // Обработка действий - if($this->request->method('post')) - { - // Сохранение цен и наличия - $prices = $this->request->post('price'); - $stocks = $this->request->post('stock'); - - foreach($prices as $id=>$price) - { - $stock = $stocks[$id]; - if($stock == '∞' || $stock == '') - $stock = null; - - $this->variants->update_variant($id, array('price'=>$price, 'stock'=>$stock)); - } - - // Сортировка - $positions = $this->request->post('positions'); - $ids = array_keys($positions); - sort($positions); - $positions = array_reverse($positions); - foreach($positions as $i=>$position) - $this->products->update_product($ids[$i], array('position'=>$position)); - - - // Действия с выбранными - $ids = $this->request->post('check'); - if(!empty($ids)) - switch($this->request->post('action')) - { - case 'disable': - { - $this->products->update_product($ids, array('visible'=>0)); - break; - } - case 'enable': - { - $this->products->update_product($ids, array('visible'=>1)); - break; - } - case 'set_featured': - { - $this->products->update_product($ids, array('featured'=>1)); - break; - } - case 'unset_featured': - { - $this->products->update_product($ids, array('featured'=>0)); - break; - } - case 'delete': - { - foreach($ids as $id) - $this->products->delete_product($id); - break; - } - case 'duplicate': - { - foreach($ids as $id) - $this->products->duplicate_product(intval($id)); - break; - } - case 'move_to_page': - { - - $target_page = $this->request->post('target_page', 'integer'); - - // Сразу потом откроем эту страницу - $filter['page'] = $target_page; - - // До какого товара перемещать - $limit = $filter['limit']*($target_page-1); - if($target_page > $this->request->get('page', 'integer')) - $limit += count($ids)-1; - else - $ids = array_reverse($ids, true); - - - $temp_filter = $filter; - $temp_filter['page'] = $limit+1; - $temp_filter['limit'] = 1; - $target_product = array_pop($this->products->get_products($temp_filter)); - $target_position = $target_product->position; - - // Если вылезли за последний товар - берем позицию последнего товара в качестве цели перемещения - if($target_page > $this->request->get('page', 'integer') && !$target_position) - { - $query = $this->db->placehold("SELECT distinct p.position AS target FROM __products p LEFT JOIN __products_categories AS pc ON pc.product_id = p.id WHERE 1 $category_id_filter $brand_id_filter ORDER BY p.position DESC LIMIT 1", count($ids)); - $this->db->query($query); - $target_position = $this->db->result('target'); - } - - foreach($ids as $id) - { - $query = $this->db->placehold("SELECT position FROM __products WHERE id=? LIMIT 1", $id); - $this->db->query($query); - $initial_position = $this->db->result('position'); - - if($target_position > $initial_position) - $query = $this->db->placehold(" UPDATE __products set position=position-1 WHERE position>? AND position<=?", $initial_position, $target_position); - else - $query = $this->db->placehold(" UPDATE __products set position=position+1 WHERE position=?", $initial_position, $target_position); - - $this->db->query($query); - $query = $this->db->placehold("UPDATE __products SET __products.position = ? WHERE __products.id = ?", $target_position, $id); - $this->db->query($query); - } - break; - } - case 'move_to_category': - { - $category_id = $this->request->post('target_category', 'integer'); - $filter['page'] = 1; - $category = $this->categories->get_category($category_id); - $filter['category_id'] = $category->children; - - foreach($ids as $id) - { - $query = $this->db->placehold("DELETE FROM __products_categories WHERE category_id=? AND product_id=? LIMIT 1", $category_id, $id); - $this->db->query($query); - $query = $this->db->placehold("UPDATE IGNORE __products_categories set category_id=? WHERE product_id=? ORDER BY position DESC LIMIT 1", $category_id, $id); - $this->db->query($query); - if($this->db->affected_rows() == 0) - $query = $this->db->query("INSERT IGNORE INTO __products_categories set category_id=?, product_id=?", $category_id, $id); - - } - break; - } - case 'move_to_brand': - { - $brand_id = $this->request->post('target_brand', 'integer'); - $brand = $this->brands->get_brand($brand_id); - $filter['page'] = 1; - $filter['brand_id'] = $brand_id; - $query = $this->db->placehold("UPDATE __products set brand_id=? WHERE id in (?@)", $brand_id, $ids); - $this->db->query($query); - - // Заново выберем бренды категории - $brands = $this->brands->get_brands(array('category_id'=>$category_id)); - $this->design->assign('brands', $brands); - - break; - } - } - } - - // Отображение - if(isset($brand)) - $this->design->assign('brand', $brand); - if(isset($category)) - $this->design->assign('category', $category); - - $products_count = $this->products->count_products($filter); - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $filter['limit'] = $products_count; - - if($filter['limit']>0) - $pages_count = ceil($products_count/$filter['limit']); - else - $pages_count = 0; - $filter['page'] = min($filter['page'], $pages_count); - $this->design->assign('products_count', $products_count); - $this->design->assign('pages_count', $pages_count); - $this->design->assign('current_page', $filter['page']); - - $products = array(); - foreach($this->products->get_products($filter) as $p) - $products[$p->id] = $p; - - - if(!empty($products)) - { - - // Товары - $products_ids = array_keys($products); - foreach($products as &$product) - { - $product->variants = array(); - $product->images = array(); - $product->properties = array(); - } - - $variants = $this->variants->get_variants(array('product_id'=>$products_ids)); - - - foreach($variants as &$variant) - { - $products[$variant->product_id]->variants[] = $variant; - } - - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[$image->id] = $image; - } - - $this->design->assign('products', $products); - - return $this->design->fetch('products.tpl'); - } -} +request->get('page', 'integer')); + + $filter['limit'] = $this->settings->products_num_admin; + + // Категории + $categories = $this->categories->get_categories_tree(); + $this->design->assign('categories', $categories); + + // Текущая категория + $category_id = $this->request->get('category_id', 'integer'); + if($category_id && $category = $this->categories->get_category($category_id)) + { + $filter['category_id'] = $category->children; + + // Бренды категории + $brands = $this->brands->get_brands(array('category_id'=>$filter['category_id'])); + $this->design->assign('brands', $brands); + } + + // Все бренды + $all_brands = $this->brands->get_brands(); + $this->design->assign('all_brands', $all_brands); + + // Текущий бренд + $brand_id = $this->request->get('brand_id', 'integer'); + if($brand_id && $brand = $this->brands->get_brand($brand_id)) + $filter['brand_id'] = $brand->id; + + // Текущий фильтр + if($f = $this->request->get('filter', 'string')) + { + if($f == 'featured') + $filter['featured'] = 1; + elseif($f == 'discounted') + $filter['discounted'] = 1; + elseif($f == 'visible') + $filter['visible'] = 1; + elseif($f == 'hidden') + $filter['visible'] = 0; + elseif($f == 'outofstock') + $filter['in_stock'] = 0; + $this->design->assign('filter', $f); + } + + // Поиск + $keyword = $this->request->get('keyword'); + if(!empty($keyword)) + { + $filter['keyword'] = $keyword; + $this->design->assign('keyword', $keyword); + } + + // Обработка действий + if($this->request->method('post')) + { + // Сохранение цен и наличия + $prices = $this->request->post('price'); + $stocks = $this->request->post('stock'); + + foreach($prices as $id=>$price) + { + $stock = $stocks[$id]; + if($stock == '∞' || $stock == '') + $stock = null; + + $this->variants->update_variant($id, array('price'=>$price, 'stock'=>$stock)); + } + + // Сортировка + $positions = $this->request->post('positions'); + $ids = array_keys($positions); + sort($positions); + $positions = array_reverse($positions); + foreach($positions as $i=>$position) + $this->products->update_product($ids[$i], array('position'=>$position)); + + + // Действия с выбранными + $ids = $this->request->post('check'); + if(!empty($ids)) + switch($this->request->post('action')) + { + case 'disable': + { + $this->products->update_product($ids, array('visible'=>0)); + break; + } + case 'enable': + { + $this->products->update_product($ids, array('visible'=>1)); + break; + } + case 'set_featured': + { + $this->products->update_product($ids, array('featured'=>1)); + break; + } + case 'unset_featured': + { + $this->products->update_product($ids, array('featured'=>0)); + break; + } + case 'delete': + { + foreach($ids as $id) + $this->products->delete_product($id); + break; + } + case 'duplicate': + { + foreach($ids as $id) + $this->products->duplicate_product(intval($id)); + break; + } + case 'move_to_page': + { + + $target_page = $this->request->post('target_page', 'integer'); + + // Сразу потом откроем эту страницу + $filter['page'] = $target_page; + + // До какого товара перемещать + $limit = $filter['limit']*($target_page-1); + if($target_page > $this->request->get('page', 'integer')) + $limit += count($ids)-1; + else + $ids = array_reverse($ids, true); + + + $temp_filter = $filter; + $temp_filter['page'] = $limit+1; + $temp_filter['limit'] = 1; + $target_product = array_pop($this->products->get_products($temp_filter)); + $target_position = $target_product->position; + + // Если вылезли за последний товар - берем позицию последнего товара в качестве цели перемещения + if($target_page > $this->request->get('page', 'integer') && !$target_position) + { + $query = $this->db->placehold("SELECT distinct p.position AS target FROM __products p LEFT JOIN __products_categories AS pc ON pc.product_id = p.id WHERE 1 $category_id_filter $brand_id_filter ORDER BY p.position DESC LIMIT 1", count($ids)); + $this->db->query($query); + $target_position = $this->db->result('target'); + } + + foreach($ids as $id) + { + $query = $this->db->placehold("SELECT position FROM __products WHERE id=? LIMIT 1", $id); + $this->db->query($query); + $initial_position = $this->db->result('position'); + + if($target_position > $initial_position) + $query = $this->db->placehold(" UPDATE __products set position=position-1 WHERE position>? AND position<=?", $initial_position, $target_position); + else + $query = $this->db->placehold(" UPDATE __products set position=position+1 WHERE position=?", $initial_position, $target_position); + + $this->db->query($query); + $query = $this->db->placehold("UPDATE __products SET __products.position = ? WHERE __products.id = ?", $target_position, $id); + $this->db->query($query); + } + break; + } + case 'move_to_category': + { + $category_id = $this->request->post('target_category', 'integer'); + $filter['page'] = 1; + $category = $this->categories->get_category($category_id); + $filter['category_id'] = $category->children; + + foreach($ids as $id) + { + $query = $this->db->placehold("DELETE FROM __products_categories WHERE category_id=? AND product_id=? LIMIT 1", $category_id, $id); + $this->db->query($query); + $query = $this->db->placehold("UPDATE IGNORE __products_categories set category_id=? WHERE product_id=? ORDER BY position DESC LIMIT 1", $category_id, $id); + $this->db->query($query); + if($this->db->affected_rows() == 0) + $query = $this->db->query("INSERT IGNORE INTO __products_categories set category_id=?, product_id=?", $category_id, $id); + + } + break; + } + case 'move_to_brand': + { + $brand_id = $this->request->post('target_brand', 'integer'); + $brand = $this->brands->get_brand($brand_id); + $filter['page'] = 1; + $filter['brand_id'] = $brand_id; + $query = $this->db->placehold("UPDATE __products set brand_id=? WHERE id in (?@)", $brand_id, $ids); + $this->db->query($query); + + // Заново выберем бренды категории + $brands = $this->brands->get_brands(array('category_id'=>$category_id)); + $this->design->assign('brands', $brands); + + break; + } + } + } + + // Отображение + if(isset($brand)) + $this->design->assign('brand', $brand); + if(isset($category)) + $this->design->assign('category', $category); + + $products_count = $this->products->count_products($filter); + // Показать все страницы сразу + if($this->request->get('page') == 'all') + $filter['limit'] = $products_count; + + if($filter['limit']>0) + $pages_count = ceil($products_count/$filter['limit']); + else + $pages_count = 0; + $filter['page'] = min($filter['page'], $pages_count); + $this->design->assign('products_count', $products_count); + $this->design->assign('pages_count', $pages_count); + $this->design->assign('current_page', $filter['page']); + + $products = array(); + foreach($this->products->get_products($filter) as $p) + $products[$p->id] = $p; + + + if(!empty($products)) + { + + // Товары + $products_ids = array_keys($products); + foreach($products as &$product) + { + $product->variants = array(); + $product->images = array(); + $product->properties = array(); + } + + $variants = $this->variants->get_variants(array('product_id'=>$products_ids)); + + + foreach($variants as &$variant) + { + $products[$variant->product_id]->variants[] = $variant; + } + + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[$image->id] = $image; + } + + $this->design->assign('products', $products); + + return $this->design->fetch('products.tpl'); + } +} diff --git a/simpla/SettingsAdmin.php b/simpla/SettingsAdmin.php index 517e189..b3d99ca 100755 --- a/simpla/SettingsAdmin.php +++ b/simpla/SettingsAdmin.php @@ -1,97 +1,107 @@ -passwd_file = $this->config->root_dir.'/simpla/.passwd'; - $this->htaccess_file = $this->config->root_dir.'/simpla/.htaccess'; - - - $managers = $this->managers->get_managers(); - $this->design->assign('managers', $managers); - - if($this->request->method('POST')) - { - $this->settings->site_name = $this->request->post('site_name'); - $this->settings->company_name = $this->request->post('company_name'); - $this->settings->date_format = $this->request->post('date_format'); - $this->settings->admin_email = $this->request->post('admin_email'); - - $this->settings->order_email = $this->request->post('order_email'); - $this->settings->comment_email = $this->request->post('comment_email'); - $this->settings->notify_from_email = $this->request->post('notify_from_email'); - - $this->settings->decimals_point = $this->request->post('decimals_point'); - $this->settings->thousands_separator = $this->request->post('thousands_separator'); - - $this->settings->products_num = $this->request->post('products_num'); - $this->settings->products_num_admin = $this->request->post('products_num_admin'); - $this->settings->max_order_amount = $this->request->post('max_order_amount'); - $this->settings->units = $this->request->post('units'); - - // Простые звонки - $this->settings->pz_server = $this->request->post('pz_server'); - $this->settings->pz_password = $this->request->post('pz_password'); - $this->settings->pz_phones = $this->request->post('pz_phones'); - - - // Водяной знак - $clear_image_cache = false; - $watermark = $this->request->files('watermark_file', 'tmp_name'); - if(!empty($watermark) && in_array(pathinfo($this->request->files('watermark_file', 'name'), PATHINFO_EXTENSION), $this->allowed_image_extentions)) - { - if(@move_uploaded_file($watermark, $this->config->root_dir.$this->config->watermark_file)) - $clear_image_cache = true; - else - $this->design->assign('message_error', 'watermark_is_not_writable'); - } - - if($this->settings->watermark_offset_x != $this->request->post('watermark_offset_x')) - { - $this->settings->watermark_offset_x = $this->request->post('watermark_offset_x'); - $clear_image_cache = true; - } - if($this->settings->watermark_offset_y != $this->request->post('watermark_offset_y')) - { - $this->settings->watermark_offset_y = $this->request->post('watermark_offset_y'); - $clear_image_cache = true; - } - if($this->settings->watermark_transparency != $this->request->post('watermark_transparency')) - { - $this->settings->watermark_transparency = $this->request->post('watermark_transparency'); - $clear_image_cache = true; - } - if($this->settings->images_sharpen != $this->request->post('images_sharpen')) - { - $this->settings->images_sharpen = $this->request->post('images_sharpen'); - $clear_image_cache = true; - } - - - // Удаление заресайзеных изображений - if($clear_image_cache) - { - $dir = $this->config->resized_images_dir; - if($handle = opendir($dir)) - { - while(false !== ($file = readdir($handle))) - { - if($file != "." && $file != "..") - { - @unlink($dir."/".$file); - } - } - closedir($handle); - } - } - $this->design->assign('message_success', 'saved'); - } - return $this->design->fetch('settings.tpl'); - } - -} - +passwd_file = $this->config->root_dir.'/simpla/.passwd'; + $this->htaccess_file = $this->config->root_dir.'/simpla/.htaccess'; + + + $managers = $this->managers->get_managers(); + $this->design->assign('managers', $managers); + + if($this->request->method('POST')) + { + $this->settings->site_name = $this->request->post('site_name'); + $this->settings->company_name = $this->request->post('company_name'); + $this->settings->date_format = $this->request->post('date_format'); + $this->settings->admin_email = $this->request->post('admin_email'); + + $this->settings->order_email = $this->request->post('order_email'); + $this->settings->comment_email = $this->request->post('comment_email'); + $this->settings->notify_from_email = $this->request->post('notify_from_email'); + + $this->settings->decimals_point = $this->request->post('decimals_point'); + $this->settings->thousands_separator = $this->request->post('thousands_separator'); + + $this->settings->products_num = $this->request->post('products_num'); + $this->settings->products_num_admin = $this->request->post('products_num_admin'); + $this->settings->max_order_amount = $this->request->post('max_order_amount'); + $this->settings->units = $this->request->post('units'); + + // Простые звонки + $this->settings->pz_server = $this->request->post('pz_server'); + $this->settings->pz_password = $this->request->post('pz_password'); + $this->settings->pz_phones = $this->request->post('pz_phones'); + + + // Водяной знак + $clear_image_cache = false; + $watermark = $this->request->files('watermark_file', 'tmp_name'); + if(!empty($watermark) && in_array(pathinfo($this->request->files('watermark_file', 'name'), PATHINFO_EXTENSION), $this->allowed_image_extentions)) + { + if(@move_uploaded_file($watermark, $this->config->root_dir.$this->config->watermark_file)) + $clear_image_cache = true; + else + $this->design->assign('message_error', 'watermark_is_not_writable'); + } + + if($this->settings->watermark_offset_x != $this->request->post('watermark_offset_x')) + { + $this->settings->watermark_offset_x = $this->request->post('watermark_offset_x'); + $clear_image_cache = true; + } + if($this->settings->watermark_offset_y != $this->request->post('watermark_offset_y')) + { + $this->settings->watermark_offset_y = $this->request->post('watermark_offset_y'); + $clear_image_cache = true; + } + if($this->settings->watermark_transparency != $this->request->post('watermark_transparency')) + { + $this->settings->watermark_transparency = $this->request->post('watermark_transparency'); + $clear_image_cache = true; + } + if($this->settings->images_sharpen != $this->request->post('images_sharpen')) + { + $this->settings->images_sharpen = $this->request->post('images_sharpen'); + $clear_image_cache = true; + } + + + // Удаление заресайзеных изображений + if($clear_image_cache) + { + $dir = $this->config->resized_images_dir; + if($handle = opendir($dir)) + { + while(false !== ($file = readdir($handle))) + { + if($file != "." && $file != "..") + { + @unlink($dir."/".$file); + } + } + closedir($handle); + } + } + $this->design->assign('message_success', 'saved'); + } + return $this->design->fetch('settings.tpl'); + } + +} + diff --git a/simpla/StatsAdmin.php b/simpla/StatsAdmin.php index 61a1beb..686c3ee 100755 --- a/simpla/StatsAdmin.php +++ b/simpla/StatsAdmin.php @@ -1,16 +1,21 @@ -design->fetch('stats.tpl'); - } -} +design->fetch('stats.tpl'); + } +} diff --git a/simpla/StylesAdmin.php b/simpla/StylesAdmin.php index 590d176..2d4b31c 100755 --- a/simpla/StylesAdmin.php +++ b/simpla/StylesAdmin.php @@ -1,76 +1,87 @@ -settings->theme.'/css/'; - $styles = array(); - - // Порядок файлов в меню - $sort = array('style.css', 'reset.css'); - - // Чтаем все css-файлы - if($handle = opendir($styles_dir)) { - $i = count($sort); - while(false !== ($file = readdir($handle))) - { - if(is_file($styles_dir.$file) && $file[0] != '.' && pathinfo($file, PATHINFO_EXTENSION) == 'css') - { - if(($key = array_search($file, $sort)) !== false) - $styles[$key] = $file; - else - $styles[$i++] = $file; - } - } - closedir($handle); - } - ksort($styles); - - // Текущий шаблон - $style_file = $this->request->get('file'); - - if(!empty($style_file) && pathinfo($style_file, PATHINFO_EXTENSION) != 'css') - exit(); - - - // Если не указан - вспоминаем его из сессии - if(empty($style_file) && isset($_SESSION['last_edited_style'])) - $style_file = $_SESSION['last_edited_style']; - // Иначе берем первый файл из списка - elseif(empty($style_file)) - $style_file = reset($styles); - - // Передаем имя шаблона в дизайн - $this->design->assign('style_file', $style_file); - - // Если можем прочитать файл - передаем содержимое в дизайн - if(is_readable($styles_dir.$style_file)) - { - $style_content = file_get_contents($styles_dir.$style_file); - $this->design->assign('style_content', $style_content); - } - - // Если нет прав на запись - передаем в дизайн предупреждение - if(!empty($style_file) && !is_writable($styles_dir.$style_file) && !is_file($styles_dir.'../locked')) - { - $this->design->assign('message_error', 'permissions'); - } - elseif(is_file($styles_dir.'../locked')) - { - $this->design->assign('message_error', 'theme_locked'); - } - else - { - // Запоминаем в сессии имя редактируемого шаблона - $_SESSION['last_edited_style'] = $style_file; - } - - $this->design->assign('theme', $this->settings->theme); - $this->design->assign('styles', $styles); - return $this->design->fetch('styles.tpl'); - } - -} - +settings->theme.'/css/'; + $styles = array(); + + // Порядок файлов в меню + $sort = array('style.css', 'reset.css'); + + // Чтаем все css-файлы + if($handle = opendir($styles_dir)) { + $i = count($sort); + while(false !== ($file = readdir($handle))) + { + if(is_file($styles_dir.$file) && $file[0] != '.' && pathinfo($file, PATHINFO_EXTENSION) == 'css') + { + if(($key = array_search($file, $sort)) !== false) + $styles[$key] = $file; + else + $styles[$i++] = $file; + } + } + closedir($handle); + } + ksort($styles); + + // Текущий шаблон + $style_file = $this->request->get('file'); + + if(!empty($style_file) && pathinfo($style_file, PATHINFO_EXTENSION) != 'css') + exit(); + + + // Если не указан - вспоминаем его из сессии + if(empty($style_file) && isset($_SESSION['last_edited_style'])) + $style_file = $_SESSION['last_edited_style']; + // Иначе берем первый файл из списка + elseif(empty($style_file)) + $style_file = reset($styles); + + // Передаем имя шаблона в дизайн + $this->design->assign('style_file', $style_file); + + // Если можем прочитать файл - передаем содержимое в дизайн + if(is_readable($styles_dir.$style_file)) + { + $style_content = file_get_contents($styles_dir.$style_file); + $this->design->assign('style_content', $style_content); + } + + // Если нет прав на запись - передаем в дизайн предупреждение + if(!empty($style_file) && !is_writable($styles_dir.$style_file) && !is_file($styles_dir.'../locked')) + { + $this->design->assign('message_error', 'permissions'); + } + elseif(is_file($styles_dir.'../locked')) + { + $this->design->assign('message_error', 'theme_locked'); + } + else + { + // Запоминаем в сессии имя редактируемого шаблона + $_SESSION['last_edited_style'] = $style_file; + } + + $this->design->assign('theme', $this->settings->theme); + $this->design->assign('styles', $styles); + + return $this->design->fetch('styles.tpl'); + } + +} + diff --git a/simpla/TemplatesAdmin.php b/simpla/TemplatesAdmin.php index 92fe40c..742f26d 100755 --- a/simpla/TemplatesAdmin.php +++ b/simpla/TemplatesAdmin.php @@ -1,76 +1,87 @@ -settings->theme.'/html/'; - $templates = array(); - - // Порядок файлов в меню - $sort = array('index.tpl', 'page.tpl', 'products.tpl', 'main.tpl', 'product.tpl', 'blog.tpl', 'post.tpl', 'cart.tpl', 'cart_informer.tpl', 'order.tpl', 'login.tpl', 'register.tpl', 'user.tpl', 'feedback.tpl', 'password_remind.tpl', 'email_order.tpl', 'email_password_remind.tpl', 'pagination.tpl'); - - // Чтаем все tpl-файлы - if($handle = opendir($templates_dir)) { - $i = count($sort); - while(false !== ($file = readdir($handle))) - { - if(is_file($templates_dir.$file) && $file[0] != '.' && pathinfo($file, PATHINFO_EXTENSION) == 'tpl') - { - if(($key = array_search($file, $sort)) !== false) - $templates[$key] = $file; - else - $templates[$i++] = $file; - } - } - closedir($handle); - ksort($templates); - } - - // Текущий шаблон - $template_file = $this->request->get('file'); - - if(!empty($template_file) && pathinfo($template_file, PATHINFO_EXTENSION) != 'tpl') - exit(); - - - // Если не указан - вспоминаем его из сессии - if(empty($template_file) && isset($_SESSION['last_edited_template'])) - $template_file = $_SESSION['last_edited_template']; - // Иначе берем первый файл из списка - elseif(empty($template_file)) - $template_file = reset($templates); - - // Передаем имя шаблона в дизайн - $this->design->assign('template_file', $template_file); - - // Если можем прочитать файл - передаем содержимое в дизайн - if(is_readable($templates_dir.$template_file)) - { - $template_content = file_get_contents($templates_dir.$template_file); - $this->design->assign('template_content', $template_content); - } - - // Если нет прав на запись - передаем в дизайн предупреждение - if(!empty($template_file) && !is_writable($templates_dir.$template_file) && !is_file($templates_dir.'../locked')) - { - $this->design->assign('message_error', 'permissions'); - } - elseif(is_file($templates_dir.'../locked')) - { - $this->design->assign('message_error', 'theme_locked'); - } - else - { - // Запоминаем в сессии имя редактируемого шаблона - $_SESSION['last_edited_template'] = $template_file; - } - - $this->design->assign('theme', $this->settings->theme); - $this->design->assign('templates', $templates); - return $this->design->fetch('templates.tpl'); - } - -} - +settings->theme.'/html/'; + $templates = array(); + + // Порядок файлов в меню + $sort = array('index.tpl', 'page.tpl', 'products.tpl', 'main.tpl', 'product.tpl', 'blog.tpl', 'post.tpl', 'cart.tpl', 'cart_informer.tpl', 'order.tpl', 'login.tpl', 'register.tpl', 'user.tpl', 'feedback.tpl', 'password_remind.tpl', 'email_order.tpl', 'email_password_remind.tpl', 'pagination.tpl'); + + // Чтаем все tpl-файлы + if($handle = opendir($templates_dir)) { + $i = count($sort); + while(false !== ($file = readdir($handle))) + { + if(is_file($templates_dir.$file) && $file[0] != '.' && pathinfo($file, PATHINFO_EXTENSION) == 'tpl') + { + if(($key = array_search($file, $sort)) !== false) + $templates[$key] = $file; + else + $templates[$i++] = $file; + } + } + closedir($handle); + ksort($templates); + } + + // Текущий шаблон + $template_file = $this->request->get('file'); + + if(!empty($template_file) && pathinfo($template_file, PATHINFO_EXTENSION) != 'tpl') + exit(); + + + // Если не указан - вспоминаем его из сессии + if(empty($template_file) && isset($_SESSION['last_edited_template'])) + $template_file = $_SESSION['last_edited_template']; + // Иначе берем первый файл из списка + elseif(empty($template_file)) + $template_file = reset($templates); + + // Передаем имя шаблона в дизайн + $this->design->assign('template_file', $template_file); + + // Если можем прочитать файл - передаем содержимое в дизайн + if(is_readable($templates_dir.$template_file)) + { + $template_content = file_get_contents($templates_dir.$template_file); + $this->design->assign('template_content', $template_content); + } + + // Если нет прав на запись - передаем в дизайн предупреждение + if(!empty($template_file) && !is_writable($templates_dir.$template_file) && !is_file($templates_dir.'../locked')) + { + $this->design->assign('message_error', 'permissions'); + } + elseif(is_file($templates_dir.'../locked')) + { + $this->design->assign('message_error', 'theme_locked'); + } + else + { + // Запоминаем в сессии имя редактируемого шаблона + $_SESSION['last_edited_template'] = $template_file; + } + + $this->design->assign('theme', $this->settings->theme); + $this->design->assign('templates', $templates); + + return $this->design->fetch('templates.tpl'); + } + +} + diff --git a/simpla/ThemeAdmin.php b/simpla/ThemeAdmin.php index 0f8b610..ce02144 100755 --- a/simpla/ThemeAdmin.php +++ b/simpla/ThemeAdmin.php @@ -1,137 +1,147 @@ -request->method('post')) - { - $this->dir_delete($this->compiled_dir, false); - $old_names = $this->request->post('old_name'); - $new_names = $this->request->post('new_name'); - if(is_array($old_names)) - foreach($old_names as $i=>$old_name) - { - $new_name = preg_replace("/[^a-zA-Z0-9\-\_]/", "", $new_names[$i]); - - if(is_writable($this->themes_dir) && is_dir($this->themes_dir.$old_name) && !is_file($this->themes_dir.$new_name)&& !is_dir($this->themes_dir.$new_name)) - { - rename($this->themes_dir.$old_name, $this->themes_dir.$new_name); - if($this->settings->theme == $old_name) - $this->settings->theme = $new_name; - } - elseif(is_file($this->themes_dir.$new_name) && $new_name!=$old_name) - $message_error = 'name_exists'; - } - - $action = $this->request->post('action'); - $action_theme = $this->request->post('theme'); - - switch($this->request->post('action')) - { - case 'set_main_theme': - { - $this->settings->theme = $action_theme; - break; - } - case 'clone_theme': - { - $new_name = $this->settings->theme; - while(is_dir($this->themes_dir.$new_name) || is_file($this->themes_dir.$new_name)) - { - if(preg_match('/(.+)_([0-9]+)$/', $new_name, $parts)) - $new_name = $parts[1].'_'.($parts[2]+1); - else - $new_name = $new_name.'_1'; - } - $this->dir_copy($this->themes_dir.$this->settings->theme, $this->themes_dir.$new_name); - @unlink($this->themes_dir.$new_name.'/locked'); - $this->settings->theme = $new_name; - break; - } - case 'delete_theme': - { - $this->dir_delete($this->themes_dir.$action_theme); - if($action_theme == $this->settings->theme) - { - $t = current($this->get_themes()); - $this->settings->theme = $t->name; - } - break; - } - } - } - - $themes = $this->get_themes(); - - // Если нет прав на запись - передаем в дизайн предупреждение - if(!is_writable($this->themes_dir)) - { - $this->design->assign('message_error', 'permissions'); - } - - $current_theme = new stdClass; - $current_theme->name = $this->settings->theme; - $current_theme->locked = is_file($this->themes_dir.$current_theme->name.'/locked'); - $this->design->assign('theme', $current_theme); - $this->design->assign('themes', $themes); - $this->design->assign('themes_dir', $this->themes_dir); - return $this->design->fetch('theme.tpl'); - } - - private function dir_copy($src, $dst) - { - if(is_dir($src)) - { - mkdir($dst, 0777); - $files = scandir($src); - foreach ($files as $file) - if ($file != "." && $file != "..") $this->dir_copy("$src/$file", "$dst/$file"); - } - elseif(file_exists($src)) - copy($src, $dst); - @chmod($dst, 0777); - } - - - private function dir_delete($path, $delete_self = true) - { - if(!$dh = @opendir($path)) - return; - while (false !== ($obj = readdir($dh))) - { - if($obj == '.' || $obj == '..') - continue; - - if (!@unlink($path . '/' . $obj)) - $this->dir_delete($path.'/'.$obj, true); - } - closedir($dh); - if($delete_self) - @rmdir($path); - return; - } - - private function get_themes() - { - if($handle = opendir($this->themes_dir)) { - while(false !== ($file = readdir($handle))) - { - if(is_dir($this->themes_dir.'/'.$file) && $file[0] != '.') - { - $theme = new stdClass; - $theme->name = $file; - $theme->locked = is_file($this->themes_dir.$file.'/locked'); - $themes[] = $theme; - } - } - closedir($handle); - sort($themes); - } - return $themes; - } -} +request->method('post')) + { + $this->dir_delete($this->compiled_dir, false); + $old_names = $this->request->post('old_name'); + $new_names = $this->request->post('new_name'); + if(is_array($old_names)) + foreach($old_names as $i=>$old_name) + { + $new_name = preg_replace("/[^a-zA-Z0-9\-\_]/", "", $new_names[$i]); + + if(is_writable($this->themes_dir) && is_dir($this->themes_dir.$old_name) && !is_file($this->themes_dir.$new_name)&& !is_dir($this->themes_dir.$new_name)) + { + rename($this->themes_dir.$old_name, $this->themes_dir.$new_name); + if($this->settings->theme == $old_name) + $this->settings->theme = $new_name; + } + elseif(is_file($this->themes_dir.$new_name) && $new_name!=$old_name) + $message_error = 'name_exists'; + } + + $action = $this->request->post('action'); + $action_theme = $this->request->post('theme'); + + switch($this->request->post('action')) + { + case 'set_main_theme': + { + $this->settings->theme = $action_theme; + break; + } + case 'clone_theme': + { + $new_name = $this->settings->theme; + while(is_dir($this->themes_dir.$new_name) || is_file($this->themes_dir.$new_name)) + { + if(preg_match('/(.+)_([0-9]+)$/', $new_name, $parts)) + $new_name = $parts[1].'_'.($parts[2]+1); + else + $new_name = $new_name.'_1'; + } + $this->dir_copy($this->themes_dir.$this->settings->theme, $this->themes_dir.$new_name); + @unlink($this->themes_dir.$new_name.'/locked'); + $this->settings->theme = $new_name; + break; + } + case 'delete_theme': + { + $this->dir_delete($this->themes_dir.$action_theme); + if($action_theme == $this->settings->theme) + { + $t = current($this->get_themes()); + $this->settings->theme = $t->name; + } + break; + } + } + } + + $themes = $this->get_themes(); + + // Если нет прав на запись - передаем в дизайн предупреждение + if(!is_writable($this->themes_dir)) + { + $this->design->assign('message_error', 'permissions'); + } + + $current_theme = new stdClass; + $current_theme->name = $this->settings->theme; + $current_theme->locked = is_file($this->themes_dir.$current_theme->name.'/locked'); + $this->design->assign('theme', $current_theme); + $this->design->assign('themes', $themes); + $this->design->assign('themes_dir', $this->themes_dir); + return $this->design->fetch('theme.tpl'); + } + + private function dir_copy($src, $dst) + { + if(is_dir($src)) + { + mkdir($dst, 0777); + $files = scandir($src); + foreach ($files as $file) + if ($file != "." && $file != "..") $this->dir_copy("$src/$file", "$dst/$file"); + } + elseif(file_exists($src)) + copy($src, $dst); + @chmod($dst, 0777); + } + + + private function dir_delete($path, $delete_self = true) + { + if(!$dh = @opendir($path)) + return; + while (false !== ($obj = readdir($dh))) + { + if($obj == '.' || $obj == '..') + continue; + + if (!@unlink($path . '/' . $obj)) + $this->dir_delete($path.'/'.$obj, true); + } + closedir($dh); + if($delete_self) + @rmdir($path); + return; + } + + private function get_themes() + { + if($handle = opendir($this->themes_dir)) { + while(false !== ($file = readdir($handle))) + { + if(is_dir($this->themes_dir.'/'.$file) && $file[0] != '.') + { + $theme = new stdClass; + $theme->name = $file; + $theme->locked = is_file($this->themes_dir.$file.'/locked'); + $themes[] = $theme; + } + } + closedir($handle); + sort($themes); + } + return $themes; + } +} diff --git a/simpla/UserAdmin.php b/simpla/UserAdmin.php index 384e806..a6cbe6e 100755 --- a/simpla/UserAdmin.php +++ b/simpla/UserAdmin.php @@ -1,82 +1,92 @@ -id = $this->request->post('id', 'integer'); - $user->enabled = $this->request->post('enabled'); - $user->name = $this->request->post('name'); - $user->email = $this->request->post('email'); - $user->group_id = $this->request->post('group_id'); - - ## Не допустить одинаковые email пользователей. - if(empty($user->name)) - { - $this->design->assign('message_error', 'empty_name'); - } - elseif(empty($user->email)) - { - $this->design->assign('message_error', 'empty_email'); - } - elseif(($u = $this->users->get_user($user->email)) && $u->id!=$user->id) - { - $this->design->assign('message_error', 'login_existed'); - } - else - { - $user->id = $this->users->update_user($user->id, $user); - $this->design->assign('message_success', 'updated'); - $user = $this->users->get_user(intval($user->id)); - } - } - elseif($this->request->post('check')) - { - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'delete': - { - foreach($ids as $id) - { - $o = $this->orders->get_order(intval($id)); - if($o->status<3) - { - $this->orders->update_order($id, array('status'=>3, 'user_id'=>null)); - $this->orders->open($id); - } - else - $this->orders->delete_order($id); - } - break; - } - } - } - - $id = $this->request->get('id', 'integer'); - if(!empty($id)) - $user = $this->users->get_user(intval($id)); - - if(!empty($user)) - { - $this->design->assign('user', $user); - - $orders = $this->orders->get_orders(array('user_id'=>$user->id)); - $this->design->assign('orders', $orders); - - } - - $groups = $this->users->get_groups(); - $this->design->assign('groups', $groups); - - return $this->design->fetch('user.tpl'); - } - -} - +id = $this->request->post('id', 'integer'); + $user->enabled = $this->request->post('enabled'); + $user->name = $this->request->post('name'); + $user->email = $this->request->post('email'); + $user->group_id = $this->request->post('group_id'); + + ## Не допустить одинаковые email пользователей. + if(empty($user->name)) + { + $this->design->assign('message_error', 'empty_name'); + } + elseif(empty($user->email)) + { + $this->design->assign('message_error', 'empty_email'); + } + elseif(($u = $this->users->get_user($user->email)) && $u->id!=$user->id) + { + $this->design->assign('message_error', 'login_existed'); + } + else + { + $user->id = $this->users->update_user($user->id, $user); + $this->design->assign('message_success', 'updated'); + $user = $this->users->get_user(intval($user->id)); + } + } + elseif($this->request->post('check')) + { + // Действия с выбранными + $ids = $this->request->post('check'); + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'delete': + { + foreach($ids as $id) + { + $o = $this->orders->get_order(intval($id)); + if($o->status<3) + { + $this->orders->update_order($id, array('status'=>3, 'user_id'=>null)); + $this->orders->open($id); + } + else + $this->orders->delete_order($id); + } + break; + } + } + } + + $id = $this->request->get('id', 'integer'); + if(!empty($id)) + $user = $this->users->get_user(intval($id)); + + if(!empty($user)) + { + $this->design->assign('user', $user); + + $orders = $this->orders->get_orders(array('user_id'=>$user->id)); + $this->design->assign('orders', $orders); + + } + + $groups = $this->users->get_groups(); + $this->design->assign('groups', $groups); + + return $this->design->fetch('user.tpl'); + } + +} + diff --git a/simpla/UsersAdmin.php b/simpla/UsersAdmin.php index a746f82..a2d04ff 100755 --- a/simpla/UsersAdmin.php +++ b/simpla/UsersAdmin.php @@ -1,88 +1,95 @@ -request->method('post')) - { - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids)) - switch($this->request->post('action')) - { - case 'disable': - { - foreach($ids as $id) - $this->users->update_user($id, array('enabled'=>0)); - break; - } - case 'enable': - { - foreach($ids as $id) - $this->users->update_user($id, array('enabled'=>1)); - break; - } - case 'delete': - { - foreach($ids as $id) - $this->users->delete_user($id); - break; - } - } - } - - foreach($this->users->get_groups() as $g) - $groups[$g->id] = $g; - - - $group = null; - $filter = array(); - $filter['page'] = max(1, $this->request->get('page', 'integer')); - $filter['limit'] = 20; - - $group_id = $this->request->get('group_id', 'integer'); - if($group_id) - { - $group = $this->users->get_group($group_id); - $filter['group_id'] = $group->id; - } - - // Поиск - $keyword = $this->request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } - - // Сортировка пользователей, сохраняем в сессии, чтобы текущая сортировка не сбрасывалась - if($sort = $this->request->get('sort', 'string')) - $_SESSION['users_admin_sort'] = $sort; - if (!empty($_SESSION['users_admin_sort'])) - $filter['sort'] = $_SESSION['users_admin_sort']; - else - $filter['sort'] = 'name'; - $this->design->assign('sort', $filter['sort']); - - $users_count = $this->users->count_users($filter); - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $filter['limit'] = $users_count; - - $users = $this->users->get_users($filter); - $this->design->assign('pages_count', ceil($users_count/$filter['limit'])); - $this->design->assign('current_page', $filter['page']); - $this->design->assign('groups', $groups); - $this->design->assign('group', $group); - $this->design->assign('users', $users); - $this->design->assign('users_count', $users_count); - return $this->body = $this->design->fetch('users.tpl'); - } -} +request->method('post')) + { + // Действия с выбранными + $ids = $this->request->post('check'); + if(is_array($ids)) + switch($this->request->post('action')) + { + case 'disable': + { + foreach($ids as $id) + $this->users->update_user($id, array('enabled'=>0)); + break; + } + case 'enable': + { + foreach($ids as $id) + $this->users->update_user($id, array('enabled'=>1)); + break; + } + case 'delete': + { + foreach($ids as $id) + $this->users->delete_user($id); + break; + } + } + } + + foreach($this->users->get_groups() as $g) + $groups[$g->id] = $g; + + + $group = null; + $filter = array(); + $filter['page'] = max(1, $this->request->get('page', 'integer')); + $filter['limit'] = 20; + + $group_id = $this->request->get('group_id', 'integer'); + if($group_id) + { + $group = $this->users->get_group($group_id); + $filter['group_id'] = $group->id; + } + + // Поиск + $keyword = $this->request->get('keyword', 'string'); + if(!empty($keyword)) + { + $filter['keyword'] = $keyword; + $this->design->assign('keyword', $keyword); + } + + // Сортировка пользователей, сохраняем в сессии, чтобы текущая сортировка не сбрасывалась + if($sort = $this->request->get('sort', 'string')) + $_SESSION['users_admin_sort'] = $sort; + if (!empty($_SESSION['users_admin_sort'])) + $filter['sort'] = $_SESSION['users_admin_sort']; + else + $filter['sort'] = 'name'; + $this->design->assign('sort', $filter['sort']); + + $users_count = $this->users->count_users($filter); + // Показать все страницы сразу + if($this->request->get('page') == 'all') + $filter['limit'] = $users_count; + + $users = $this->users->get_users($filter); + $this->design->assign('pages_count', ceil($users_count/$filter['limit'])); + $this->design->assign('current_page', $filter['page']); + $this->design->assign('groups', $groups); + $this->design->assign('group', $group); + $this->design->assign('users', $users); + $this->design->assign('users_count', $users_count); + + return $this->body = $this->design->fetch('users.tpl'); + } +} From d0f7cf41b5256585cf0a7ac6dfa0c2404dbd593c Mon Sep 17 00:00:00 2001 From: Erko Evgen Date: Thu, 17 Mar 2016 12:11:02 +0200 Subject: [PATCH 3/5] code formatting for /view/*.php --- view/BlogView.php | 330 ++++++++++++----------- view/CartView.php | 288 ++++++++++---------- view/FeedbackView.php | 137 +++++----- view/IndexView.php | 166 ++++++------ view/LoginView.php | 207 ++++++++------- view/MainView.php | 18 +- view/OrderView.php | 69 +++-- view/PageView.php | 67 +++-- view/ProductView.php | 361 +++++++++++++------------ view/ProductsView.php | 442 +++++++++++++++---------------- view/RegisterView.php | 109 ++++---- view/UserView.php | 149 ++++++----- view/View.php | 598 +++++++++++++++++++++--------------------- 13 files changed, 1452 insertions(+), 1489 deletions(-) diff --git a/view/BlogView.php b/view/BlogView.php index de3761f..e732518 100755 --- a/view/BlogView.php +++ b/view/BlogView.php @@ -1,166 +1,164 @@ -request->get('url', 'string'); - - // Если указан адрес поста, - if(!empty($url)) - { - // Выводим пост - return $this->fetch_post($url); - } - else - { - // Иначе выводим ленту блога - return $this->fetch_blog(); - } - } - - private function fetch_post($url) - { - // Выбираем пост из базы - $post = $this->blog->get_post($url); - - // Если не найден - ошибка - if(!$post || (!$post->visible && empty($_SESSION['admin']))) - return false; - - // Автозаполнение имени для формы комментария - if(!empty($this->user)) - $this->design->assign('comment_name', $this->user->name); - - - // Принимаем комментарий - if ($this->request->method('post') && $this->request->post('comment')) - { - $comment = new stdClass; - $comment->name = $this->request->post('name'); - $comment->text = $this->request->post('text'); - $captcha_code = $this->request->post('captcha_code', 'string'); - - // Передадим комментарий обратно в шаблон - при ошибке нужно будет заполнить форму - $this->design->assign('comment_text', $comment->text); - $this->design->assign('comment_name', $comment->name); - - // Проверяем капчу и заполнение формы - if ($_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) - { - $this->design->assign('error', 'captcha'); - } - elseif (empty($comment->name)) - { - $this->design->assign('error', 'empty_name'); - } - elseif (empty($comment->text)) - { - $this->design->assign('error', 'empty_comment'); - } - else - { - // Создаем комментарий - $comment->object_id = $post->id; - $comment->type = 'blog'; - $comment->ip = $_SERVER['REMOTE_ADDR']; - - // Если были одобренные комментарии от текущего ip, одобряем сразу - $this->db->query("SELECT 1 FROM __comments WHERE approved=1 AND ip=? LIMIT 1", $comment->ip); - if($this->db->num_rows()>0) - $comment->approved = 1; - - // Добавляем комментарий в базу - $comment_id = $this->comments->add_comment($comment); - - // Отправляем email - $this->notify->email_comment_admin($comment_id); - - // Приберем сохраненную капчу, иначе можно отключить загрузку рисунков и постить старую - unset($_SESSION['captcha_code']); - header('location: '.$_SERVER['REQUEST_URI'].'#comment_'.$comment_id); - } - } - - // Комментарии к посту - $comments = $this->comments->get_comments(array('type'=>'blog', 'object_id'=>$post->id, 'approved'=>1, 'ip'=>$_SERVER['REMOTE_ADDR'])); - $this->design->assign('comments', $comments); - $this->design->assign('post', $post); - - // Соседние записи - $this->design->assign('next_post', $this->blog->get_next_post($post->id)); - $this->design->assign('prev_post', $this->blog->get_prev_post($post->id)); - - // Мета-теги - $this->design->assign('meta_title', $post->meta_title); - $this->design->assign('meta_keywords', $post->meta_keywords); - $this->design->assign('meta_description', $post->meta_description); - - return $this->design->fetch('post.tpl'); - } - - // Отображение списка постов - private function fetch_blog() - { - // Количество постов на 1 странице - $items_per_page = 20; - - $filter = array(); - - // Выбираем только видимые посты - $filter['visible'] = 1; - - // Текущая страница в постраничном выводе - $current_page = $this->request->get('page', 'integer'); - - // Если не задана, то равна 1 - $current_page = max(1, $current_page); - $this->design->assign('current_page_num', $current_page); - - // Вычисляем количество страниц - $posts_count = $this->blog->count_posts($filter); - - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $items_per_page = $posts_count; - - $pages_num = ceil($posts_count/$items_per_page); - $this->design->assign('total_pages_num', $pages_num); - - $filter['page'] = $current_page; - $filter['limit'] = $items_per_page; - - // Выбираем статьи из базы - $posts = $this->blog->get_posts($filter); - if(empty($posts)) - return false; - - // Передаем в шаблон - $this->design->assign('posts', $posts); - - // Метатеги - if($this->page) - { - $this->design->assign('meta_title', $this->page->meta_title); - $this->design->assign('meta_keywords', $this->page->meta_keywords); - $this->design->assign('meta_description', $this->page->meta_description); - } - - $body = $this->design->fetch('blog.tpl'); - - return $body; - } -} \ No newline at end of file +request->get('url', 'string'); + + // Если указан адрес поста, + if(!empty($url)) + { + // Выводим пост + return $this->fetch_post($url); + } + else + { + // Иначе выводим ленту блога + return $this->fetch_blog(); + } + } + + private function fetch_post($url) + { + // Выбираем пост из базы + $post = $this->blog->get_post($url); + + // Если не найден - ошибка + if(!$post || (!$post->visible && empty($_SESSION['admin']))) + return false; + + // Автозаполнение имени для формы комментария + if(!empty($this->user)) + $this->design->assign('comment_name', $this->user->name); + + + // Принимаем комментарий + if ($this->request->method('post') && $this->request->post('comment')) + { + $comment = new stdClass; + $comment->name = $this->request->post('name'); + $comment->text = $this->request->post('text'); + $captcha_code = $this->request->post('captcha_code', 'string'); + + // Передадим комментарий обратно в шаблон - при ошибке нужно будет заполнить форму + $this->design->assign('comment_text', $comment->text); + $this->design->assign('comment_name', $comment->name); + + // Проверяем капчу и заполнение формы + if ($_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) + { + $this->design->assign('error', 'captcha'); + } + elseif (empty($comment->name)) + { + $this->design->assign('error', 'empty_name'); + } + elseif (empty($comment->text)) + { + $this->design->assign('error', 'empty_comment'); + } + else + { + // Создаем комментарий + $comment->object_id = $post->id; + $comment->type = 'blog'; + $comment->ip = $_SERVER['REMOTE_ADDR']; + + // Если были одобренные комментарии от текущего ip, одобряем сразу + $this->db->query("SELECT 1 FROM __comments WHERE approved=1 AND ip=? LIMIT 1", $comment->ip); + if($this->db->num_rows()>0) + $comment->approved = 1; + + // Добавляем комментарий в базу + $comment_id = $this->comments->add_comment($comment); + + // Отправляем email + $this->notify->email_comment_admin($comment_id); + + // Приберем сохраненную капчу, иначе можно отключить загрузку рисунков и постить старую + unset($_SESSION['captcha_code']); + header('location: '.$_SERVER['REQUEST_URI'].'#comment_'.$comment_id); + } + } + + // Комментарии к посту + $comments = $this->comments->get_comments(array('type'=>'blog', 'object_id'=>$post->id, 'approved'=>1, 'ip'=>$_SERVER['REMOTE_ADDR'])); + $this->design->assign('comments', $comments); + $this->design->assign('post', $post); + + // Соседние записи + $this->design->assign('next_post', $this->blog->get_next_post($post->id)); + $this->design->assign('prev_post', $this->blog->get_prev_post($post->id)); + + // Мета-теги + $this->design->assign('meta_title', $post->meta_title); + $this->design->assign('meta_keywords', $post->meta_keywords); + $this->design->assign('meta_description', $post->meta_description); + + return $this->design->fetch('post.tpl'); + } + + // Отображение списка постов + private function fetch_blog() + { + // Количество постов на 1 странице + $items_per_page = 20; + + $filter = array(); + + // Выбираем только видимые посты + $filter['visible'] = 1; + + // Текущая страница в постраничном выводе + $current_page = $this->request->get('page', 'integer'); + + // Если не задана, то равна 1 + $current_page = max(1, $current_page); + $this->design->assign('current_page_num', $current_page); + + // Вычисляем количество страниц + $posts_count = $this->blog->count_posts($filter); + + // Показать все страницы сразу + if($this->request->get('page') == 'all') + $items_per_page = $posts_count; + + $pages_num = ceil($posts_count/$items_per_page); + $this->design->assign('total_pages_num', $pages_num); + + $filter['page'] = $current_page; + $filter['limit'] = $items_per_page; + + // Выбираем статьи из базы + $posts = $this->blog->get_posts($filter); + if(empty($posts)) + return false; + + // Передаем в шаблон + $this->design->assign('posts', $posts); + + // Метатеги + if($this->page) + { + $this->design->assign('meta_title', $this->page->meta_title); + $this->design->assign('meta_keywords', $this->page->meta_keywords); + $this->design->assign('meta_description', $this->page->meta_description); + } + + $body = $this->design->fetch('blog.tpl'); + + return $body; + } +} diff --git a/view/CartView.php b/view/CartView.php index 8bfc118..2274a0c 100755 --- a/view/CartView.php +++ b/view/CartView.php @@ -1,175 +1,163 @@ -request->get('variant', 'integer')) - { - $this->cart->add_item($variant_id, $this->request->get('amount', 'integer')); - header('location: '.$this->config->root_url.'/cart/'); - - } - - // Удаление товара из корзины - if($delete_variant_id = intval($this->request->get('delete_variant'))) - { - $this->cart->delete_item($delete_variant_id); - if(!isset($_POST['submit_order']) || $_POST['submit_order']!=1) - header('location: '.$this->config->root_url.'/cart/'); - } - - // Если нажали оформить заказ - if(isset($_POST['checkout'])) - { - $order = new stdClass; - $order->delivery_id = $this->request->post('delivery_id', 'integer'); - $order->name = $this->request->post('name'); - $order->email = $this->request->post('email'); - $order->address = $this->request->post('address'); - $order->phone = $this->request->post('phone'); - $order->comment = $this->request->post('comment'); - $order->ip = $_SERVER['REMOTE_ADDR']; - - $this->design->assign('delivery_id', $order->delivery_id); - $this->design->assign('name', $order->name); - $this->design->assign('email', $order->email); - $this->design->assign('phone', $order->phone); - $this->design->assign('address', $order->address); - - $captcha_code = $this->request->post('captcha_code', 'string'); - - // Скидка - $cart = $this->cart->get_cart(); - $order->discount = $cart->discount; - - if($cart->coupon) + + public function __construct() + { + parent::__construct(); + + // Если передан id варианта, добавим его в корзину + if($variant_id = $this->request->get('variant', 'integer')) { - $order->coupon_discount = $cart->coupon_discount; - $order->coupon_code = $cart->coupon->code; + $this->cart->add_item($variant_id, $this->request->get('amount', 'integer')); + header('location: '.$this->config->root_url.'/cart/'); + } - // - - if(!empty($this->user->id)) - $order->user_id = $this->user->id; - - if(empty($order->name)) - { - $this->design->assign('error', 'empty_name'); - } - elseif(empty($order->email)) - { - $this->design->assign('error', 'empty_email'); - } - elseif($_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) - { - $this->design->assign('error', 'captcha'); - } - else - { - // Добавляем заказ в базу - $order_id = $this->orders->add_order($order); - $_SESSION['order_id'] = $order_id; - - // Если использовали купон, увеличим количество его использований - if($cart->coupon) - $this->coupons->update_coupon($cart->coupon->id, array('usages'=>$cart->coupon->usages+1)); - - // Добавляем товары к заказу - foreach($this->request->post('amounts') as $variant_id=>$amount) - { - $this->orders->add_purchase(array('order_id'=>$order_id, 'variant_id'=>intval($variant_id), 'amount'=>intval($amount))); - } - $order = $this->orders->get_order($order_id); - - // Стоимость доставки - $delivery = $this->delivery->get_delivery($order->delivery_id); - if(!empty($delivery) && $delivery->free_from > $order->total_price) - { - $this->orders->update_order($order->id, array('delivery_price'=>$delivery->price, 'separate_delivery'=>$delivery->separate_payment)); - } - - // Отправляем письмо пользователю - $this->notify->email_order_user($order->id); - - // Отправляем письмо администратору - $this->notify->email_order_admin($order->id); - - // Очищаем корзину (сессию) - $this->cart->empty_cart(); - - // Перенаправляем на страницу заказа - header('Location: '.$this->config->root_url.'/order/'.$order->url); + + // Удаление товара из корзины + if($delete_variant_id = intval($this->request->get('delete_variant'))) + { + $this->cart->delete_item($delete_variant_id); + if(!isset($_POST['submit_order']) || $_POST['submit_order']!=1) + header('location: '.$this->config->root_url.'/cart/'); } - } - else - { - - // Если нам запостили amounts, обновляем их - if($amounts = $this->request->post('amounts')) - { - foreach($amounts as $variant_id=>$amount) + + // Если нажали оформить заказ + if(isset($_POST['checkout'])) + { + $order = new stdClass; + $order->delivery_id = $this->request->post('delivery_id', 'integer'); + $order->name = $this->request->post('name'); + $order->email = $this->request->post('email'); + $order->address = $this->request->post('address'); + $order->phone = $this->request->post('phone'); + $order->comment = $this->request->post('comment'); + $order->ip = $_SERVER['REMOTE_ADDR']; + + $this->design->assign('delivery_id', $order->delivery_id); + $this->design->assign('name', $order->name); + $this->design->assign('email', $order->email); + $this->design->assign('phone', $order->phone); + $this->design->assign('address', $order->address); + + $captcha_code = $this->request->post('captcha_code', 'string'); + + // Скидка + $cart = $this->cart->get_cart(); + $order->discount = $cart->discount; + + if($cart->coupon) + { + $order->coupon_discount = $cart->coupon_discount; + $order->coupon_code = $cart->coupon->code; + } + + if(!empty($this->user->id)) + $order->user_id = $this->user->id; + + if(empty($order->name)) + { + $this->design->assign('error', 'empty_name'); + } + elseif(empty($order->email)) + { + $this->design->assign('error', 'empty_email'); + } + elseif($_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) + { + $this->design->assign('error', 'captcha'); + } + else { - $this->cart->update_item($variant_id, $amount); + // Добавляем заказ в базу + $order_id = $this->orders->add_order($order); + $_SESSION['order_id'] = $order_id; + + // Если использовали купон, увеличим количество его использований + if($cart->coupon) + $this->coupons->update_coupon($cart->coupon->id, array('usages'=>$cart->coupon->usages+1)); + + // Добавляем товары к заказу + foreach($this->request->post('amounts') as $variant_id=>$amount) + { + $this->orders->add_purchase(array('order_id'=>$order_id, 'variant_id'=>intval($variant_id), 'amount'=>intval($amount))); + } + $order = $this->orders->get_order($order_id); + + // Стоимость доставки + $delivery = $this->delivery->get_delivery($order->delivery_id); + if(!empty($delivery) && $delivery->free_from > $order->total_price) + { + $this->orders->update_order($order->id, array('delivery_price'=>$delivery->price, 'separate_delivery'=>$delivery->separate_payment)); + } + + // Отправляем письмо пользователю + $this->notify->email_order_user($order->id); + + // Отправляем письмо администратору + $this->notify->email_order_admin($order->id); + + // Очищаем корзину (сессию) + $this->cart->empty_cart(); + + // Перенаправляем на страницу заказа + header('Location: '.$this->config->root_url.'/order/'.$order->url); } + } + else + { - $coupon_code = trim($this->request->post('coupon_code', 'string')); - if(empty($coupon_code)) - { - $this->cart->apply_coupon(''); - header('location: '.$this->config->root_url.'/cart/'); - } - else - { - $coupon = $this->coupons->get_coupon((string)$coupon_code); - - if(empty($coupon) || !$coupon->valid) + // Если нам запостили amounts, обновляем их + if($amounts = $this->request->post('amounts')) + { + foreach($amounts as $variant_id=>$amount) { - $this->cart->apply_coupon($coupon_code); - $this->design->assign('coupon_error', 'invalid'); + $this->cart->update_item($variant_id, $amount); } - else + + $coupon_code = trim($this->request->post('coupon_code', 'string')); + if(empty($coupon_code)) { - $this->cart->apply_coupon($coupon_code); + $this->cart->apply_coupon(''); header('location: '.$this->config->root_url.'/cart/'); } - } + else + { + $coupon = $this->coupons->get_coupon((string)$coupon_code); + + if(empty($coupon) || !$coupon->valid) + { + $this->cart->apply_coupon($coupon_code); + $this->design->assign('coupon_error', 'invalid'); + } + else + { + $this->cart->apply_coupon($coupon_code); + header('location: '.$this->config->root_url.'/cart/'); + } + } + } } - } - - } - - - ////////////////////////////////////////// - // Основная функция - ////////////////////////////////////////// - function fetch() - { + + public function fetch() + { // Способы доставки $deliveries = $this->delivery->get_deliveries(array('enabled'=>1)); $this->design->assign('deliveries', $deliveries); - + // Данные пользователя if($this->user) { @@ -185,10 +173,10 @@ function fetch() else { $this->design->assign('name', $this->user->name); - $this->design->assign('email', $this->user->email); + $this->design->assign('email', $this->user->email); } } - + // Если существуют валидные купоны, нужно вывести инпут для купона if($this->coupons->count_coupons(array('valid'=>1))>0) $this->design->assign('coupon_request', true); @@ -196,5 +184,5 @@ function fetch() // Выводим корзину return $this->design->fetch('cart.tpl'); } - -} \ No newline at end of file + +} diff --git a/view/FeedbackView.php b/view/FeedbackView.php index f1b8d65..10f3297 100755 --- a/view/FeedbackView.php +++ b/view/FeedbackView.php @@ -1,70 +1,67 @@ -request->method('post') && $this->request->post('feedback')) - { - $feedback->name = $this->request->post('name'); - $feedback->email = $this->request->post('email'); - $feedback->message = $this->request->post('message'); - $captcha_code = $this->request->post('captcha_code'); - - $this->design->assign('name', $feedback->name); - $this->design->assign('email', $feedback->email); - $this->design->assign('message', $feedback->message); - - if(empty($feedback->name)) - $this->design->assign('error', 'empty_name'); - elseif(empty($feedback->email)) - $this->design->assign('error', 'empty_email'); - elseif(empty($feedback->message)) - $this->design->assign('error', 'empty_text'); - elseif(empty($_SESSION['captcha_code']) || $_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) - { - $this->design->assign('error', 'captcha'); - } - else - { - $this->design->assign('message_sent', true); - - $feedback->ip = $_SERVER['REMOTE_ADDR']; - $feedback_id = $this->feedbacks->add_feedback($feedback); - - // Отправляем email - $this->notify->email_feedback_admin($feedback_id); - - // Приберем сохраненную капчу, иначе можно отключить загрузку рисунков и постить старую - unset($_SESSION['captcha_code']); - - } - } - - if($this->page) - { - $this->design->assign('meta_title', $this->page->meta_title); - $this->design->assign('meta_keywords', $this->page->meta_keywords); - $this->design->assign('meta_description', $this->page->meta_description); - } - - $body = $this->design->fetch('feedback.tpl'); - - return $body; - } -} +request->method('post') && $this->request->post('feedback')) + { + $feedback->name = $this->request->post('name'); + $feedback->email = $this->request->post('email'); + $feedback->message = $this->request->post('message'); + $captcha_code = $this->request->post('captcha_code'); + + $this->design->assign('name', $feedback->name); + $this->design->assign('email', $feedback->email); + $this->design->assign('message', $feedback->message); + + if(empty($feedback->name)) + $this->design->assign('error', 'empty_name'); + elseif(empty($feedback->email)) + $this->design->assign('error', 'empty_email'); + elseif(empty($feedback->message)) + $this->design->assign('error', 'empty_text'); + elseif(empty($_SESSION['captcha_code']) || $_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) + { + $this->design->assign('error', 'captcha'); + } + else + { + $this->design->assign('message_sent', true); + + $feedback->ip = $_SERVER['REMOTE_ADDR']; + $feedback_id = $this->feedbacks->add_feedback($feedback); + + // Отправляем email + $this->notify->email_feedback_admin($feedback_id); + + // Приберем сохраненную капчу, иначе можно отключить загрузку рисунков и постить старую + unset($_SESSION['captcha_code']); + + } + } + + if($this->page) + { + $this->design->assign('meta_title', $this->page->meta_title); + $this->design->assign('meta_keywords', $this->page->meta_keywords); + $this->design->assign('meta_description', $this->page->meta_description); + } + + $body = $this->design->fetch('feedback.tpl'); + + return $body; + } +} diff --git a/view/IndexView.php b/view/IndexView.php index 278cda1..fd058e5 100755 --- a/view/IndexView.php +++ b/view/IndexView.php @@ -1,87 +1,79 @@ -design->assign('cart', $this->cart->get_cart()); - - // Категории товаров - $this->design->assign('categories', $this->categories->get_categories_tree()); - - // Страницы - $pages = $this->pages->get_pages(array('visible'=>1)); - $this->design->assign('pages', $pages); - - // Текущий модуль (для отображения центрального блока) - $module = $this->request->get('module', 'string'); - $module = preg_replace("/[^A-Za-z0-9]+/", "", $module); - - // Если не задан - берем из настроек - if(empty($module)) - return false; - //$module = $this->settings->main_module; - - // Создаем соответствующий класс - if (is_file($this->modules_dir."$module.php")) - { - include_once($this->modules_dir."$module.php"); - if (class_exists($module)) - { - $this->main = new $module($this); - } else return false; - } else return false; - - // Создаем основной блок страницы - if (!$content = $this->main->fetch()) - { - return false; - } - - // Передаем основной блок в шаблон - $this->design->assign('content', $content); - - // Передаем название модуля в шаблон, это может пригодиться - $this->design->assign('module', $module); - - // Создаем текущую обертку сайта (обычно index.tpl) - $wrapper = $this->design->get_var('wrapper'); - if(is_null($wrapper)) - $wrapper = 'index.tpl'; - - if(!empty($wrapper)) - return $this->body = $this->design->fetch($wrapper); - else - return $this->body = $content; - - } -} +design->assign('cart', $this->cart->get_cart()); + + // Категории товаров + $this->design->assign('categories', $this->categories->get_categories_tree()); + + // Страницы + $pages = $this->pages->get_pages(array('visible'=>1)); + $this->design->assign('pages', $pages); + + // Текущий модуль (для отображения центрального блока) + $module = $this->request->get('module', 'string'); + $module = preg_replace("/[^A-Za-z0-9]+/", "", $module); + + // Если не задан - берем из настроек + if(empty($module)) + return false; + //$module = $this->settings->main_module; + + // Создаем соответствующий класс + if (is_file($this->modules_dir."$module.php")) + { + include_once($this->modules_dir."$module.php"); + if (class_exists($module)) + { + $this->main = new $module($this); + } else return false; + } else return false; + + // Создаем основной блок страницы + if (!$content = $this->main->fetch()) + { + return false; + } + + // Передаем основной блок в шаблон + $this->design->assign('content', $content); + + // Передаем название модуля в шаблон, это может пригодиться + $this->design->assign('module', $module); + + // Создаем текущую обертку сайта (обычно index.tpl) + $wrapper = $this->design->get_var('wrapper'); + if(is_null($wrapper)) + $wrapper = 'index.tpl'; + + if(!empty($wrapper)) + return $this->body = $this->design->fetch($wrapper); + else + return $this->body = $content; + } + +} diff --git a/view/LoginView.php b/view/LoginView.php index 016758e..ddd638b 100755 --- a/view/LoginView.php +++ b/view/LoginView.php @@ -1,99 +1,108 @@ -request->get('action') == 'logout') - { - unset($_SESSION['user_id']); - header('Location: '.$this->config->root_url); - exit(); - } - // Вспомнить пароль - elseif($this->request->get('action') == 'password_remind') - { - // Если запостили email - if($this->request->method('post') && $this->request->post('email')) - { - $email = $this->request->post('email'); - $this->design->assign('email', $email); - - // Выбираем пользователя из базы - $user = $this->users->get_user($email); - if(!empty($user)) - { - // Генерируем секретный код и сохраняем в сессии - $code = md5(uniqid($this->config->salt, true)); - $_SESSION['password_remind_code'] = $code; - $_SESSION['password_remind_user_id'] = $user->id; - - // Отправляем письмо пользователю для восстановления пароля - $this->notify->email_password_remind($user->id, $code); - $this->design->assign('email_sent', true); - } - else - { - $this->design->assign('error', 'user_not_found'); - } - } - // Если к нам перешли по ссылке для восстановления пароля - elseif($this->request->get('code')) - { - // Проверяем существование сессии - if(!isset($_SESSION['password_remind_code']) || !isset($_SESSION['password_remind_user_id'])) - return false; - - // Проверяем совпадение кода в сессии и в ссылке - if($this->request->get('code') != $_SESSION['password_remind_code']) - return false; - - // Выбераем пользователя из базы - $user = $this->users->get_user(intval($_SESSION['password_remind_user_id'])); - if(empty($user)) - return false; - - // Залогиниваемся под пользователем и переходим в кабинет для изменения пароля - $_SESSION['user_id'] = $user->id; - header('Location: '.$this->config->root_url.'/user'); - } - return $this->design->fetch('password_remind.tpl'); - } - // Вход - elseif($this->request->method('post') && $this->request->post('login')) - { - $email = $this->request->post('email'); - $password = $this->request->post('password'); - - $this->design->assign('email', $email); - - if($user_id = $this->users->check_password($email, $password)) - { - $user = $this->users->get_user($email); - if($user->enabled) - { - $_SESSION['user_id'] = $user_id; - $this->users->update_user($user_id, array('last_ip'=>$_SERVER['REMOTE_ADDR'])); - - // Перенаправляем пользователя на прошлую страницу, если она известна - if(!empty($_SESSION['last_visited_page'])) - header('Location: '.$_SESSION['last_visited_page']); - else - header('Location: '.$this->config->root_url); - } - else - { - $this->design->assign('error', 'user_disabled'); - } - } - else - { - $this->design->assign('error', 'login_incorrect'); - } - } - return $this->design->fetch('login.tpl'); - } -} +request->get('action') == 'logout') + { + unset($_SESSION['user_id']); + header('Location: '.$this->config->root_url); + exit(); + } + // Вспомнить пароль + elseif($this->request->get('action') == 'password_remind') + { + // Если запостили email + if($this->request->method('post') && $this->request->post('email')) + { + $email = $this->request->post('email'); + $this->design->assign('email', $email); + + // Выбираем пользователя из базы + $user = $this->users->get_user($email); + if(!empty($user)) + { + // Генерируем секретный код и сохраняем в сессии + $code = md5(uniqid($this->config->salt, true)); + $_SESSION['password_remind_code'] = $code; + $_SESSION['password_remind_user_id'] = $user->id; + + // Отправляем письмо пользователю для восстановления пароля + $this->notify->email_password_remind($user->id, $code); + $this->design->assign('email_sent', true); + } + else + { + $this->design->assign('error', 'user_not_found'); + } + } + // Если к нам перешли по ссылке для восстановления пароля + elseif($this->request->get('code')) + { + // Проверяем существование сессии + if(!isset($_SESSION['password_remind_code']) || !isset($_SESSION['password_remind_user_id'])) + return false; + + // Проверяем совпадение кода в сессии и в ссылке + if($this->request->get('code') != $_SESSION['password_remind_code']) + return false; + + // Выбераем пользователя из базы + $user = $this->users->get_user(intval($_SESSION['password_remind_user_id'])); + if(empty($user)) + return false; + + // Залогиниваемся под пользователем и переходим в кабинет для изменения пароля + $_SESSION['user_id'] = $user->id; + header('Location: '.$this->config->root_url.'/user'); + } + return $this->design->fetch('password_remind.tpl'); + } + // Вход + elseif($this->request->method('post') && $this->request->post('login')) + { + $email = $this->request->post('email'); + $password = $this->request->post('password'); + + $this->design->assign('email', $email); + + if($user_id = $this->users->check_password($email, $password)) + { + $user = $this->users->get_user($email); + if($user->enabled) + { + $_SESSION['user_id'] = $user_id; + $this->users->update_user($user_id, array('last_ip'=>$_SERVER['REMOTE_ADDR'])); + + // Перенаправляем пользователя на прошлую страницу, если она известна + if(!empty($_SESSION['last_visited_page'])) + header('Location: '.$_SESSION['last_visited_page']); + else + header('Location: '.$this->config->root_url); + } + else + { + $this->design->assign('error', 'user_disabled'); + } + } + else + { + $this->design->assign('error', 'login_incorrect'); + } + } + return $this->design->fetch('login.tpl'); + } +} diff --git a/view/MainView.php b/view/MainView.php index 538fd19..47ff5d7 100755 --- a/view/MainView.php +++ b/view/MainView.php @@ -1,26 +1,20 @@ -page) { diff --git a/view/OrderView.php b/view/OrderView.php index 9a42611..5f61b20 100755 --- a/view/OrderView.php +++ b/view/OrderView.php @@ -1,17 +1,14 @@ -design->smarty->registerPlugin("function", "checkout_form", array($this, 'checkout_form')); } - ////////////////////////////////////////// - // Основная функция - ////////////////////////////////////////// - function fetch() + + public function fetch() { // Скачивание файла if($this->request->get('file')) @@ -36,10 +31,10 @@ function fetch() { return $this->fetch_order(); } - + } - - function fetch_order() + + public function fetch_order() { if($url = $this->request->get('url', 'string')) $order = $this->orders->get_order((string)$url); @@ -47,14 +42,14 @@ function fetch_order() $order = $this->orders->get_order(intval($_SESSION['order_id'])); else return false; - + if(!$order) return false; - + $purchases = $this->orders->get_purchases(array('order_id'=>intval($order->id))); if(!$purchases) return false; - + if($this->request->method('post')) { if($payment_method_id = $this->request->post('payment_method_id', 'integer')) @@ -68,7 +63,7 @@ function fetch_order() $order = $this->orders->get_order((integer)$order->id); } } - + $products_ids = array(); $variants_ids = array(); foreach($purchases as $purchase) @@ -79,15 +74,15 @@ function fetch_order() $products = array(); foreach($this->products->get_products(array('id'=>$products_ids)) as $p) $products[$p->id] = $p; - + $images = $this->products->get_images(array('product_id'=>$products_ids)); foreach($images as $image) $products[$image->product_id]->images[] = $image; - + $variants = array(); foreach($this->variants->get_variants(array('id'=>$variants_ids)) as $v) $variants[$v->id] = $v; - + foreach($variants as $variant) $products[$variant->product_id]->variants[] = $variant; @@ -100,11 +95,11 @@ function fetch_order() $purchase->variant = $variants[$purchase->variant_id]; } } - + // Способ доставки $delivery = $this->delivery->get_delivery($order->delivery_id); $this->design->assign('delivery', $delivery); - + $this->design->assign('order', $order); $this->design->assign('purchases', $purchases); @@ -114,7 +109,7 @@ function fetch_order() $payment_method = $this->payment->get_payment_method($order->payment_method_id); $this->design->assign('payment_method', $payment_method); } - + // Варианты оплаты $payment_methods = $this->payment->get_payment_methods(array('delivery_id'=>$order->delivery_id, 'enabled'=>1)); $this->design->assign('payment_methods', $payment_methods); @@ -122,39 +117,39 @@ function fetch_order() // Все валюты $this->design->assign('all_currencies', $this->money->get_currencies()); - - + + // Выводим заказ return $this->body = $this->design->fetch('order.tpl'); } - + private function download() { $file = $this->request->get('file'); - + if(!$url = $this->request->get('url', 'string')) return false; - + $order = $this->orders->get_order((string)$url); if(!$order) return false; - + if(!$order->paid) return false; - - // Проверяем, есть ли такой файл в покупках + + // Проверяем, есть ли такой файл в покупках $query = $this->db->placehold("SELECT p.id FROM __purchases p, __variants v WHERE p.variant_id=v.id AND p.order_id=? AND v.attachment=?", $order->id, $file); $this->db->query($query); if($this->db->num_rows()==0) return false; - + header("Content-type: application/force-download"); header("Content-Disposition: attachment; filename=\"$file\""); header("Content-Length: ".filesize($this->config->root_dir.$this->config->downloads_dir.$file)); readfile($this->config->root_dir.$this->config->downloads_dir.$file); - + exit(); } - + public function checkout_form($params, &$smarty) { $module_name = preg_replace("/[^A-Za-z0-9]+/", "", $params['module']); @@ -169,4 +164,4 @@ public function checkout_form($params, &$smarty) return $form; } -} \ No newline at end of file +} diff --git a/view/PageView.php b/view/PageView.php index 6c79eec..2bd698b 100755 --- a/view/PageView.php +++ b/view/PageView.php @@ -1,34 +1,33 @@ -request->get('page_url', 'string'); - - $page = $this->pages->get_page($url); - - // Отображать скрытые страницы только админу - if(empty($page) || (!$page->visible && empty($_SESSION['admin']))) - return false; - - $this->design->assign('page', $page); - $this->design->assign('meta_title', $page->meta_title); - $this->design->assign('meta_keywords', $page->meta_keywords); - $this->design->assign('meta_description', $page->meta_description); - - return $this->design->fetch('page.tpl'); - } -} \ No newline at end of file +request->get('page_url', 'string'); + + $page = $this->pages->get_page($url); + + // Отображать скрытые страницы только админу + if(empty($page) || (!$page->visible && empty($_SESSION['admin']))) + return false; + + $this->design->assign('page', $page); + $this->design->assign('meta_title', $page->meta_title); + $this->design->assign('meta_keywords', $page->meta_keywords); + $this->design->assign('meta_description', $page->meta_description); + + return $this->design->fetch('page.tpl'); + } +} diff --git a/view/ProductView.php b/view/ProductView.php index 4841785..27c1eff 100755 --- a/view/ProductView.php +++ b/view/ProductView.php @@ -1,183 +1,178 @@ -request->get('product_url', 'string'); - - if(empty($product_url)) - return false; - - // Выбираем товар из базы - $product = $this->products->get_product((string)$product_url); - if(empty($product) || (!$product->visible && empty($_SESSION['admin']))) - return false; - - $product->images = $this->products->get_images(array('product_id'=>$product->id)); - $product->image = reset($product->images); - - $variants = array(); - foreach($this->variants->get_variants(array('product_id'=>$product->id, 'in_stock'=>true)) as $v) - $variants[$v->id] = $v; - - $product->variants = $variants; - - // Вариант по умолчанию - if(($v_id = $this->request->get('variant', 'integer'))>0 && isset($variants[$v_id])) - $product->variant = $variants[$v_id]; - else - $product->variant = reset($variants); - - $product->features = $this->features->get_product_options(array('product_id'=>$product->id)); - - // Автозаполнение имени для формы комментария - if(!empty($this->user)) - $this->design->assign('comment_name', $this->user->name); - - // Принимаем комментарий - if ($this->request->method('post') && $this->request->post('comment')) - { - $comment = new stdClass; - $comment->name = $this->request->post('name'); - $comment->text = $this->request->post('text'); - $captcha_code = $this->request->post('captcha_code', 'string'); - - // Передадим комментарий обратно в шаблон - при ошибке нужно будет заполнить форму - $this->design->assign('comment_text', $comment->text); - $this->design->assign('comment_name', $comment->name); - - // Проверяем капчу и заполнение формы - if ($_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) - { - $this->design->assign('error', 'captcha'); - } - elseif (empty($comment->name)) - { - $this->design->assign('error', 'empty_name'); - } - elseif (empty($comment->text)) - { - $this->design->assign('error', 'empty_comment'); - } - else - { - // Создаем комментарий - $comment->object_id = $product->id; - $comment->type = 'product'; - $comment->ip = $_SERVER['REMOTE_ADDR']; - - // Если были одобренные комментарии от текущего ip, одобряем сразу - $this->db->query("SELECT 1 FROM __comments WHERE approved=1 AND ip=? LIMIT 1", $comment->ip); - if($this->db->num_rows()>0) - $comment->approved = 1; - - // Добавляем комментарий в базу - $comment_id = $this->comments->add_comment($comment); - - // Отправляем email - $this->notify->email_comment_admin($comment_id); - - // Приберем сохраненную капчу, иначе можно отключить загрузку рисунков и постить старую - unset($_SESSION['captcha_code']); - header('location: '.$_SERVER['REQUEST_URI'].'#comment_'.$comment_id); - } - } - - // Связанные товары - $related_ids = array(); - $related_products = array(); - foreach($this->products->get_related_products($product->id) as $p) - { - $related_ids[] = $p->related_id; - $related_products[$p->related_id] = null; - } - if(!empty($related_ids)) - { - foreach($this->products->get_products(array('id'=>$related_ids, 'in_stock'=>1, 'visible'=>1)) as $p) - $related_products[$p->id] = $p; - - $related_products_images = $this->products->get_images(array('product_id'=>array_keys($related_products))); - foreach($related_products_images as $related_product_image) - if(isset($related_products[$related_product_image->product_id])) - $related_products[$related_product_image->product_id]->images[] = $related_product_image; - $related_products_variants = $this->variants->get_variants(array('product_id'=>array_keys($related_products), 'in_stock'=>1)); - foreach($related_products_variants as $related_product_variant) - { - if(isset($related_products[$related_product_variant->product_id])) - { - $related_products[$related_product_variant->product_id]->variants[] = $related_product_variant; - } - } - foreach($related_products as $id=>$r) - { - if(is_object($r)) - { - $r->image = &$r->images[0]; - $r->variant = &$r->variants[0]; - } - else - { - unset($related_products[$id]); - } - } - $this->design->assign('related_products', $related_products); - } - - // Отзывы о товаре - $comments = $this->comments->get_comments(array('type'=>'product', 'object_id'=>$product->id, 'approved'=>1, 'ip'=>$_SERVER['REMOTE_ADDR'])); - - // Соседние товары - $this->design->assign('next_product', $this->products->get_next_product($product->id)); - $this->design->assign('prev_product', $this->products->get_prev_product($product->id)); - - // И передаем его в шаблон - $this->design->assign('product', $product); - $this->design->assign('comments', $comments); - - // Категория и бренд товара - $product->categories = $this->categories->get_categories(array('product_id'=>$product->id)); - $this->design->assign('brand', $this->brands->get_brand(intval($product->brand_id))); - $this->design->assign('category', reset($product->categories)); - - - // Добавление в историю просмотров товаров - $max_visited_products = 100; // Максимальное число хранимых товаров в истории - $expire = time()+60*60*24*30; // Время жизни - 30 дней - if(!empty($_COOKIE['browsed_products'])) - { - $browsed_products = explode(',', $_COOKIE['browsed_products']); - // Удалим текущий товар, если он был - if(($exists = array_search($product->id, $browsed_products)) !== false) - unset($browsed_products[$exists]); - } - // Добавим текущий товар - $browsed_products[] = $product->id; - $cookie_val = implode(',', array_slice($browsed_products, -$max_visited_products, $max_visited_products)); - setcookie("browsed_products", $cookie_val, $expire, "/"); - - $this->design->assign('meta_title', $product->meta_title); - $this->design->assign('meta_keywords', $product->meta_keywords); - $this->design->assign('meta_description', $product->meta_description); - - return $this->design->fetch('product.tpl'); - } - - - -} +request->get('product_url', 'string'); + + if(empty($product_url)) + return false; + + // Выбираем товар из базы + $product = $this->products->get_product((string)$product_url); + if(empty($product) || (!$product->visible && empty($_SESSION['admin']))) + return false; + + $product->images = $this->products->get_images(array('product_id'=>$product->id)); + $product->image = reset($product->images); + + $variants = array(); + foreach($this->variants->get_variants(array('product_id'=>$product->id, 'in_stock'=>true)) as $v) + $variants[$v->id] = $v; + + $product->variants = $variants; + + // Вариант по умолчанию + if(($v_id = $this->request->get('variant', 'integer'))>0 && isset($variants[$v_id])) + $product->variant = $variants[$v_id]; + else + $product->variant = reset($variants); + + $product->features = $this->features->get_product_options(array('product_id'=>$product->id)); + + // Автозаполнение имени для формы комментария + if(!empty($this->user)) + $this->design->assign('comment_name', $this->user->name); + + // Принимаем комментарий + if ($this->request->method('post') && $this->request->post('comment')) + { + $comment = new stdClass; + $comment->name = $this->request->post('name'); + $comment->text = $this->request->post('text'); + $captcha_code = $this->request->post('captcha_code', 'string'); + + // Передадим комментарий обратно в шаблон - при ошибке нужно будет заполнить форму + $this->design->assign('comment_text', $comment->text); + $this->design->assign('comment_name', $comment->name); + + // Проверяем капчу и заполнение формы + if ($_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) + { + $this->design->assign('error', 'captcha'); + } + elseif (empty($comment->name)) + { + $this->design->assign('error', 'empty_name'); + } + elseif (empty($comment->text)) + { + $this->design->assign('error', 'empty_comment'); + } + else + { + // Создаем комментарий + $comment->object_id = $product->id; + $comment->type = 'product'; + $comment->ip = $_SERVER['REMOTE_ADDR']; + + // Если были одобренные комментарии от текущего ip, одобряем сразу + $this->db->query("SELECT 1 FROM __comments WHERE approved=1 AND ip=? LIMIT 1", $comment->ip); + if($this->db->num_rows()>0) + $comment->approved = 1; + + // Добавляем комментарий в базу + $comment_id = $this->comments->add_comment($comment); + + // Отправляем email + $this->notify->email_comment_admin($comment_id); + + // Приберем сохраненную капчу, иначе можно отключить загрузку рисунков и постить старую + unset($_SESSION['captcha_code']); + header('location: '.$_SERVER['REQUEST_URI'].'#comment_'.$comment_id); + } + } + + // Связанные товары + $related_ids = array(); + $related_products = array(); + foreach($this->products->get_related_products($product->id) as $p) + { + $related_ids[] = $p->related_id; + $related_products[$p->related_id] = null; + } + if(!empty($related_ids)) + { + foreach($this->products->get_products(array('id'=>$related_ids, 'in_stock'=>1, 'visible'=>1)) as $p) + $related_products[$p->id] = $p; + + $related_products_images = $this->products->get_images(array('product_id'=>array_keys($related_products))); + foreach($related_products_images as $related_product_image) + if(isset($related_products[$related_product_image->product_id])) + $related_products[$related_product_image->product_id]->images[] = $related_product_image; + $related_products_variants = $this->variants->get_variants(array('product_id'=>array_keys($related_products), 'in_stock'=>1)); + foreach($related_products_variants as $related_product_variant) + { + if(isset($related_products[$related_product_variant->product_id])) + { + $related_products[$related_product_variant->product_id]->variants[] = $related_product_variant; + } + } + foreach($related_products as $id=>$r) + { + if(is_object($r)) + { + $r->image = &$r->images[0]; + $r->variant = &$r->variants[0]; + } + else + { + unset($related_products[$id]); + } + } + $this->design->assign('related_products', $related_products); + } + + // Отзывы о товаре + $comments = $this->comments->get_comments(array('type'=>'product', 'object_id'=>$product->id, 'approved'=>1, 'ip'=>$_SERVER['REMOTE_ADDR'])); + + // Соседние товары + $this->design->assign('next_product', $this->products->get_next_product($product->id)); + $this->design->assign('prev_product', $this->products->get_prev_product($product->id)); + + // И передаем его в шаблон + $this->design->assign('product', $product); + $this->design->assign('comments', $comments); + + // Категория и бренд товара + $product->categories = $this->categories->get_categories(array('product_id'=>$product->id)); + $this->design->assign('brand', $this->brands->get_brand(intval($product->brand_id))); + $this->design->assign('category', reset($product->categories)); + + + // Добавление в историю просмотров товаров + $max_visited_products = 100; // Максимальное число хранимых товаров в истории + $expire = time()+60*60*24*30; // Время жизни - 30 дней + if(!empty($_COOKIE['browsed_products'])) + { + $browsed_products = explode(',', $_COOKIE['browsed_products']); + // Удалим текущий товар, если он был + if(($exists = array_search($product->id, $browsed_products)) !== false) + unset($browsed_products[$exists]); + } + // Добавим текущий товар + $browsed_products[] = $product->id; + $cookie_val = implode(',', array_slice($browsed_products, -$max_visited_products, $max_visited_products)); + setcookie("browsed_products", $cookie_val, $expire, "/"); + + $this->design->assign('meta_title', $product->meta_title); + $this->design->assign('meta_keywords', $product->meta_keywords); + $this->design->assign('meta_description', $product->meta_description); + + return $this->design->fetch('product.tpl'); + } + +} diff --git a/view/ProductsView.php b/view/ProductsView.php index 389859e..445fb1c 100755 --- a/view/ProductsView.php +++ b/view/ProductsView.php @@ -1,225 +1,217 @@ -request->get('category', 'string'); - $brand_url = $this->request->get('brand', 'string'); - - $filter = array(); - $filter['visible'] = 1; - - // Если задан бренд, выберем его из базы - if (!empty($brand_url)) - { - $brand = $this->brands->get_brand((string)$brand_url); - if (empty($brand)) - return false; - $this->design->assign('brand', $brand); - $filter['brand_id'] = $brand->id; - } - - // Выберем текущую категорию - if (!empty($category_url)) - { - $category = $this->categories->get_category((string)$category_url); - if (empty($category) || (!$category->visible && empty($_SESSION['admin']))) - return false; - $this->design->assign('category', $category); - $filter['category_id'] = $category->children; - } - - // Если задано ключевое слово - $keyword = $this->request->get('keyword'); - if (!empty($keyword)) - { - $this->design->assign('keyword', $keyword); - $filter['keyword'] = $keyword; - } - - // Сортировка товаров, сохраняем в сесси, чтобы текущая сортировка оставалась для всего сайта - if($sort = $this->request->get('sort', 'string')) - $_SESSION['sort'] = $sort; - if (!empty($_SESSION['sort'])) - $filter['sort'] = $_SESSION['sort']; - else - $filter['sort'] = 'position'; - $this->design->assign('sort', $filter['sort']); - - // Свойства товаров - if(!empty($category)) - { - $features = array(); - foreach($this->features->get_features(array('category_id'=>$category->id, 'in_filter'=>1)) as $feature) - { - $features[$feature->id] = $feature; - if(($val = strval($this->request->get($feature->id)))!='') - $filter['features'][$feature->id] = $val; - } - - $options_filter['visible'] = 1; - - $features_ids = array_keys($features); - if(!empty($features_ids)) - $options_filter['feature_id'] = $features_ids; - $options_filter['category_id'] = $category->children; - if(isset($filter['features'])) - $options_filter['features'] = $filter['features']; - if(!empty($brand)) - $options_filter['brand_id'] = $brand->id; - - $options = $this->features->get_options($options_filter); - - foreach($options as $option) - { - if(isset($features[$option->feature_id])) - $features[$option->feature_id]->options[] = $option; - } - - foreach($features as $i=>&$feature) - { - if(empty($feature->options)) - unset($features[$i]); - } - - $this->design->assign('features', $features); - } - - // Постраничная навигация - $items_per_page = $this->settings->products_num; - // Текущая страница в постраничном выводе - $current_page = $this->request->get('page', 'integer'); - // Если не задана, то равна 1 - $current_page = max(1, $current_page); - $this->design->assign('current_page_num', $current_page); - // Вычисляем количество страниц - $products_count = $this->products->count_products($filter); - - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $items_per_page = $products_count; - - $pages_num = ceil($products_count/$items_per_page); - $this->design->assign('total_pages_num', $pages_num); - $this->design->assign('total_products_num', $products_count); - - $filter['page'] = $current_page; - $filter['limit'] = $items_per_page; - - /////////////////////////////////////////////// - // Постраничная навигация END - /////////////////////////////////////////////// - - - $discount = 0; - if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id']))) - $discount = $user->discount; - - // Товары - $products = array(); - foreach($this->products->get_products($filter) as $p) - $products[$p->id] = $p; - - // Если искали товар и найден ровно один - перенаправляем на него - if(!empty($keyword) && $products_count == 1) - header('Location: '.$this->config->root_url.'/products/'.$p->url); - - if(!empty($products)) - { - $products_ids = array_keys($products); - foreach($products as &$product) - { - $product->variants = array(); - $product->images = array(); - $product->properties = array(); - } - - $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); - - foreach($variants as &$variant) - { - //$variant->price *= (100-$discount)/100; - $products[$variant->product_id]->variants[] = $variant; - } - - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[] = $image; - - foreach($products as &$product) - { - if(isset($product->variants[0])) - $product->variant = $product->variants[0]; - if(isset($product->images[0])) - $product->image = $product->images[0]; - } - - - /* - $properties = $this->features->get_options(array('product_id'=>$products_ids)); - foreach($properties as $property) - $products[$property->product_id]->options[] = $property; - */ - - $this->design->assign('products', $products); - } - - // Выбираем бренды, они нужны нам в шаблоне - if(!empty($category)) - { - $brands = $this->brands->get_brands(array('category_id'=>$category->children, 'visible'=>1)); - $category->brands = $brands; - } - - // Устанавливаем мета-теги в зависимости от запроса - if($this->page) - { - $this->design->assign('meta_title', $this->page->meta_title); - $this->design->assign('meta_keywords', $this->page->meta_keywords); - $this->design->assign('meta_description', $this->page->meta_description); - } - elseif(isset($category)) - { - $this->design->assign('meta_title', $category->meta_title); - $this->design->assign('meta_keywords', $category->meta_keywords); - $this->design->assign('meta_description', $category->meta_description); - } - elseif(isset($brand)) - { - $this->design->assign('meta_title', $brand->meta_title); - $this->design->assign('meta_keywords', $brand->meta_keywords); - $this->design->assign('meta_description', $brand->meta_description); - } - elseif(isset($keyword)) - { - $this->design->assign('meta_title', $keyword); - } - - - $this->body = $this->design->fetch('products.tpl'); - return $this->body; - } - - - -} +request->get('category', 'string'); + $brand_url = $this->request->get('brand', 'string'); + + $filter = array(); + $filter['visible'] = 1; + + // Если задан бренд, выберем его из базы + if (!empty($brand_url)) + { + $brand = $this->brands->get_brand((string)$brand_url); + if (empty($brand)) + return false; + $this->design->assign('brand', $brand); + $filter['brand_id'] = $brand->id; + } + + // Выберем текущую категорию + if (!empty($category_url)) + { + $category = $this->categories->get_category((string)$category_url); + if (empty($category) || (!$category->visible && empty($_SESSION['admin']))) + return false; + $this->design->assign('category', $category); + $filter['category_id'] = $category->children; + } + + // Если задано ключевое слово + $keyword = $this->request->get('keyword'); + if (!empty($keyword)) + { + $this->design->assign('keyword', $keyword); + $filter['keyword'] = $keyword; + } + + // Сортировка товаров, сохраняем в сесси, чтобы текущая сортировка оставалась для всего сайта + if($sort = $this->request->get('sort', 'string')) + $_SESSION['sort'] = $sort; + if (!empty($_SESSION['sort'])) + $filter['sort'] = $_SESSION['sort']; + else + $filter['sort'] = 'position'; + $this->design->assign('sort', $filter['sort']); + + // Свойства товаров + if(!empty($category)) + { + $features = array(); + foreach($this->features->get_features(array('category_id'=>$category->id, 'in_filter'=>1)) as $feature) + { + $features[$feature->id] = $feature; + if(($val = strval($this->request->get($feature->id)))!='') + $filter['features'][$feature->id] = $val; + } + + $options_filter['visible'] = 1; + + $features_ids = array_keys($features); + if(!empty($features_ids)) + $options_filter['feature_id'] = $features_ids; + $options_filter['category_id'] = $category->children; + if(isset($filter['features'])) + $options_filter['features'] = $filter['features']; + if(!empty($brand)) + $options_filter['brand_id'] = $brand->id; + + $options = $this->features->get_options($options_filter); + + foreach($options as $option) + { + if(isset($features[$option->feature_id])) + $features[$option->feature_id]->options[] = $option; + } + + foreach($features as $i=>&$feature) + { + if(empty($feature->options)) + unset($features[$i]); + } + + $this->design->assign('features', $features); + } + + // Постраничная навигация + $items_per_page = $this->settings->products_num; + // Текущая страница в постраничном выводе + $current_page = $this->request->get('page', 'integer'); + // Если не задана, то равна 1 + $current_page = max(1, $current_page); + $this->design->assign('current_page_num', $current_page); + // Вычисляем количество страниц + $products_count = $this->products->count_products($filter); + + // Показать все страницы сразу + if($this->request->get('page') == 'all') + $items_per_page = $products_count; + + $pages_num = ceil($products_count/$items_per_page); + $this->design->assign('total_pages_num', $pages_num); + $this->design->assign('total_products_num', $products_count); + + $filter['page'] = $current_page; + $filter['limit'] = $items_per_page; + + /////////////////////////////////////////////// + // Постраничная навигация END + /////////////////////////////////////////////// + + + $discount = 0; + if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id']))) + $discount = $user->discount; + + // Товары + $products = array(); + foreach($this->products->get_products($filter) as $p) + $products[$p->id] = $p; + + // Если искали товар и найден ровно один - перенаправляем на него + if(!empty($keyword) && $products_count == 1) + header('Location: '.$this->config->root_url.'/products/'.$p->url); + + if(!empty($products)) + { + $products_ids = array_keys($products); + foreach($products as &$product) + { + $product->variants = array(); + $product->images = array(); + $product->properties = array(); + } + + $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); + + foreach($variants as &$variant) + { + //$variant->price *= (100-$discount)/100; + $products[$variant->product_id]->variants[] = $variant; + } + + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[] = $image; + + foreach($products as &$product) + { + if(isset($product->variants[0])) + $product->variant = $product->variants[0]; + if(isset($product->images[0])) + $product->image = $product->images[0]; + } + + + /* + $properties = $this->features->get_options(array('product_id'=>$products_ids)); + foreach($properties as $property) + $products[$property->product_id]->options[] = $property; + */ + + $this->design->assign('products', $products); + } + + // Выбираем бренды, они нужны нам в шаблоне + if(!empty($category)) + { + $brands = $this->brands->get_brands(array('category_id'=>$category->children, 'visible'=>1)); + $category->brands = $brands; + } + + // Устанавливаем мета-теги в зависимости от запроса + if($this->page) + { + $this->design->assign('meta_title', $this->page->meta_title); + $this->design->assign('meta_keywords', $this->page->meta_keywords); + $this->design->assign('meta_description', $this->page->meta_description); + } + elseif(isset($category)) + { + $this->design->assign('meta_title', $category->meta_title); + $this->design->assign('meta_keywords', $category->meta_keywords); + $this->design->assign('meta_description', $category->meta_description); + } + elseif(isset($brand)) + { + $this->design->assign('meta_title', $brand->meta_title); + $this->design->assign('meta_keywords', $brand->meta_keywords); + $this->design->assign('meta_description', $brand->meta_description); + } + elseif(isset($keyword)) + { + $this->design->assign('meta_title', $keyword); + } + + + $this->body = $this->design->fetch('products.tpl'); + return $this->body; + } + +} diff --git a/view/RegisterView.php b/view/RegisterView.php index 3532287..9720ec7 100755 --- a/view/RegisterView.php +++ b/view/RegisterView.php @@ -1,50 +1,59 @@ -request->method('post') && $this->request->post('register')) - { - $name = $this->request->post('name'); - $email = $this->request->post('email'); - $password = $this->request->post('password'); - $captcha_code = $this->request->post('captcha_code'); - - $this->design->assign('name', $name); - $this->design->assign('email', $email); - - $this->db->query('SELECT count(*) as count FROM __users WHERE email=?', $email); - $user_exists = $this->db->result('count'); - - if($user_exists) - $this->design->assign('error', 'user_exists'); - elseif(empty($name)) - $this->design->assign('error', 'empty_name'); - elseif(empty($email)) - $this->design->assign('error', 'empty_email'); - elseif(empty($password)) - $this->design->assign('error', 'empty_password'); - elseif(empty($_SESSION['captcha_code']) || $_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) - { - $this->design->assign('error', 'captcha'); - } - elseif($user_id = $this->users->add_user(array('name'=>$name, 'email'=>$email, 'password'=>$password, 'enabled'=>$default_status, 'last_ip'=>$_SERVER['REMOTE_ADDR']))) - { - $_SESSION['user_id'] = $user_id; - if(!empty($_SESSION['last_visited_page'])) - header('Location: '.$_SESSION['last_visited_page']); - else - header('Location: '.$this->config->root_url); - } - else - $this->design->assign('error', 'unknown error'); - - } - return $this->design->fetch('register.tpl'); - } -} +request->method('post') && $this->request->post('register')) + { + $name = $this->request->post('name'); + $email = $this->request->post('email'); + $password = $this->request->post('password'); + $captcha_code = $this->request->post('captcha_code'); + + $this->design->assign('name', $name); + $this->design->assign('email', $email); + + $this->db->query('SELECT count(*) as count FROM __users WHERE email=?', $email); + $user_exists = $this->db->result('count'); + + if($user_exists) + $this->design->assign('error', 'user_exists'); + elseif(empty($name)) + $this->design->assign('error', 'empty_name'); + elseif(empty($email)) + $this->design->assign('error', 'empty_email'); + elseif(empty($password)) + $this->design->assign('error', 'empty_password'); + elseif(empty($_SESSION['captcha_code']) || $_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) + { + $this->design->assign('error', 'captcha'); + } + elseif($user_id = $this->users->add_user(array('name'=>$name, 'email'=>$email, 'password'=>$password, 'enabled'=>$default_status, 'last_ip'=>$_SERVER['REMOTE_ADDR']))) + { + $_SESSION['user_id'] = $user_id; + if(!empty($_SESSION['last_visited_page'])) + header('Location: '.$_SESSION['last_visited_page']); + else + header('Location: '.$this->config->root_url); + } + else + $this->design->assign('error', 'unknown error'); + + } + return $this->design->fetch('register.tpl'); + } +} diff --git a/view/UserView.php b/view/UserView.php index 24badfe..8f6c885 100755 --- a/view/UserView.php +++ b/view/UserView.php @@ -1,76 +1,73 @@ -user)) - { - header('Location: '.$this->config->root_url.'/user/login'); - exit(); - } - - if($this->request->method('post') && $this->request->post('name')) - { - $name = $this->request->post('name'); - $email = $this->request->post('email'); - $password = $this->request->post('password'); - - $this->design->assign('name', $name); - $this->design->assign('email', $email); - - $this->db->query('SELECT count(*) as count FROM __users WHERE email=? AND id!=?', $email, $this->user->id); - $user_exists = $this->db->result('count'); - - if($user_exists) - $this->design->assign('error', 'user_exists'); - elseif(empty($name)) - $this->design->assign('error', 'empty_name'); - elseif(empty($email)) - $this->design->assign('error', 'empty_email'); - elseif($user_id = $this->users->update_user($this->user->id, array('name'=>$name, 'email'=>$email))) - { - $this->user = $this->users->get_user(intval($user_id)); - $this->design->assign('name', $this->user->name); - $this->design->assign('user', $this->user); - $this->design->assign('email', $this->user->email); - } - else - $this->design->assign('error', 'unknown error'); - - if(!empty($password)) - { - $this->users->update_user($this->user->id, array('password'=>$password)); - } - - } - else - { - // Передаем в шаблон - $this->design->assign('name', $this->user->name); - $this->design->assign('email', $this->user->email); - } - - $orders = $this->orders->get_orders(array('user_id'=>$this->user->id)); - $this->design->assign('orders', $orders); - - $this->design->assign('meta_title', $this->user->name); - $body = $this->design->fetch('user.tpl'); - - return $body; - } -} +user)) + { + header('Location: '.$this->config->root_url.'/user/login'); + exit(); + } + + if($this->request->method('post') && $this->request->post('name')) + { + $name = $this->request->post('name'); + $email = $this->request->post('email'); + $password = $this->request->post('password'); + + $this->design->assign('name', $name); + $this->design->assign('email', $email); + + $this->db->query('SELECT count(*) as count FROM __users WHERE email=? AND id!=?', $email, $this->user->id); + $user_exists = $this->db->result('count'); + + if($user_exists) + $this->design->assign('error', 'user_exists'); + elseif(empty($name)) + $this->design->assign('error', 'empty_name'); + elseif(empty($email)) + $this->design->assign('error', 'empty_email'); + elseif($user_id = $this->users->update_user($this->user->id, array('name'=>$name, 'email'=>$email))) + { + $this->user = $this->users->get_user(intval($user_id)); + $this->design->assign('name', $this->user->name); + $this->design->assign('user', $this->user); + $this->design->assign('email', $this->user->email); + } + else + $this->design->assign('error', 'unknown error'); + + if(!empty($password)) + { + $this->users->update_user($this->user->id, array('password'=>$password)); + } + + } + else + { + // Передаем в шаблон + $this->design->assign('name', $this->user->name); + $this->design->assign('email', $this->user->email); + } + + $orders = $this->orders->get_orders(array('user_id'=>$this->user->id)); + $this->design->assign('orders', $orders); + + $this->design->assign('meta_title', $this->user->name); + $body = $this->design->fetch('user.tpl'); + + return $body; + } +} diff --git a/view/View.php b/view/View.php index c074ab9..8dd898c 100755 --- a/view/View.php +++ b/view/View.php @@ -1,300 +1,298 @@ -currency = &self::$view_instance->currency; - $this->currencies = &self::$view_instance->currencies; - $this->user = &self::$view_instance->user; - $this->group = &self::$view_instance->group; - $this->page = &self::$view_instance->page; - } - else - { - // Сохраняем свой инстанс в статической переменной, - // чтобы в следующий раз использовать его - self::$view_instance = $this; - - // Все валюты - $this->currencies = $this->money->get_currencies(array('enabled'=>1)); - - // Выбор текущей валюты - if($currency_id = $this->request->get('currency_id', 'integer')) - { - $_SESSION['currency_id'] = $currency_id; - header("Location: ".$this->request->url(array('currency_id'=>null))); - } - - // Берем валюту из сессии - if(isset($_SESSION['currency_id'])) - $this->currency = $this->money->get_currency($_SESSION['currency_id']); - // Или первую из списка - else - $this->currency = reset($this->currencies); - - // Пользователь, если залогинен - if(isset($_SESSION['user_id'])) - { - $u = $this->users->get_user(intval($_SESSION['user_id'])); - if($u && $u->enabled) - { - $this->user = $u; - $this->group = $this->users->get_group($this->user->group_id); - - } - } - - // Текущая страница (если есть) - $subdir = substr(dirname(dirname(__FILE__)), strlen($_SERVER['DOCUMENT_ROOT'])); - $page_url = trim(substr($_SERVER['REQUEST_URI'], strlen($subdir)),"/"); - if(strpos($page_url, '?') !== false) - $page_url = substr($page_url, 0, strpos($page_url, '?')); - $this->page = $this->pages->get_page((string)$page_url); - $this->design->assign('page', $this->page); - - // Передаем в дизайн то, что может понадобиться в нем - $this->design->assign('currencies', $this->currencies); - $this->design->assign('currency', $this->currency); - $this->design->assign('user', $this->user); - $this->design->assign('group', $this->group); - - $this->design->assign('config', $this->config); - $this->design->assign('settings', $this->settings); - - // Настраиваем плагины для смарти - $this->design->smarty->registerPlugin("function", "get_posts", array($this, 'get_posts_plugin')); - $this->design->smarty->registerPlugin("function", "get_brands", array($this, 'get_brands_plugin')); - $this->design->smarty->registerPlugin("function", "get_browsed_products", array($this, 'get_browsed_products')); - $this->design->smarty->registerPlugin("function", "get_featured_products", array($this, 'get_featured_products_plugin')); - $this->design->smarty->registerPlugin("function", "get_new_products", array($this, 'get_new_products_plugin')); - $this->design->smarty->registerPlugin("function", "get_discounted_products", array($this, 'get_discounted_products_plugin')); - } - } - - /** - * - * Отображение - * - */ - function fetch() - { - return false; - } - - /** - * - * Плагины для смарти - * - */ - public function get_posts_plugin($params, &$smarty) - { - if(!isset($params['visible'])) - $params['visible'] = 1; - if(!empty($params['var'])) - $smarty->assign($params['var'], $this->blog->get_posts($params)); - } - - public function get_brands_plugin($params, &$smarty) - { - if(!isset($params['visible'])) - $params['visible'] = 1; - if(!empty($params['var'])) - $smarty->assign($params['var'], $this->brands->get_brands($params)); - } - - public function get_browsed_products($params, &$smarty) - { - if(!empty($_COOKIE['browsed_products'])) - { - $browsed_products_ids = explode(',', $_COOKIE['browsed_products']); - $browsed_products_ids = array_reverse($browsed_products_ids); - if(isset($params['limit'])) - $browsed_products_ids = array_slice($browsed_products_ids, 0, $params['limit']); - - $products = array(); - foreach($this->products->get_products(array('id'=>$browsed_products_ids, 'visible'=>1)) as $p) - $products[$p->id] = $p; - - $browsed_products_images = $this->products->get_images(array('product_id'=>$browsed_products_ids)); - foreach($browsed_products_images as $browsed_product_image) - if(isset($products[$browsed_product_image->product_id])) - $products[$browsed_product_image->product_id]->images[] = $browsed_product_image; - - foreach($browsed_products_ids as $id) - { - if(isset($products[$id])) - { - if(isset($products[$id]->images[0])) - $products[$id]->image = $products[$id]->images[0]; - $result[] = $products[$id]; - } - } - $smarty->assign($params['var'], $result); - } - } - - - public function get_featured_products_plugin($params, &$smarty) - { - if(!isset($params['visible'])) - $params['visible'] = 1; - $params['featured'] = 1; - if(!empty($params['var'])) - { - foreach($this->products->get_products($params) as $p) - $products[$p->id] = $p; - - if(!empty($products)) - { - // id выбраных товаров - $products_ids = array_keys($products); - - // Выбираем варианты товаров - $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); - - // Для каждого варианта - foreach($variants as &$variant) - { - // добавляем вариант в соответствующий товар - $products[$variant->product_id]->variants[] = $variant; - } - - // Выбираем изображения товаров - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[] = $image; - - foreach($products as &$product) - { - if(isset($product->variants[0])) - $product->variant = $product->variants[0]; - if(isset($product->images[0])) - $product->image = $product->images[0]; - } - } - - $smarty->assign($params['var'], $products); - - } - } - - - public function get_new_products_plugin($params, &$smarty) - { - if(!isset($params['visible'])) - $params['visible'] = 1; - if(!isset($params['sort'])) - $params['sort'] = 'created'; - if(!empty($params['var'])) - { - foreach($this->products->get_products($params) as $p) - $products[$p->id] = $p; - - if(!empty($products)) - { - // id выбраных товаров - $products_ids = array_keys($products); - - // Выбираем варианты товаров - $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); - - // Для каждого варианта - foreach($variants as &$variant) - { - // добавляем вариант в соответствующий товар - $products[$variant->product_id]->variants[] = $variant; - } - - // Выбираем изображения товаров - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[] = $image; - - foreach($products as &$product) - { - if(isset($product->variants[0])) - $product->variant = $product->variants[0]; - if(isset($product->images[0])) - $product->image = $product->images[0]; - } - } - - $smarty->assign($params['var'], $products); - - } - } - - - public function get_discounted_products_plugin($params, &$smarty) - { - if(!isset($params['visible'])) - $params['visible'] = 1; - $params['discounted'] = 1; - if(!empty($params['var'])) - { - foreach($this->products->get_products($params) as $p) - $products[$p->id] = $p; - - if(!empty($products)) - { - // id выбраных товаров - $products_ids = array_keys($products); - - // Выбираем варианты товаров - $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); - - // Для каждого варианта - foreach($variants as &$variant) - { - // добавляем вариант в соответствующий товар - $products[$variant->product_id]->variants[] = $variant; - } - - // Выбираем изображения товаров - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[] = $image; - - foreach($products as &$product) - { - if(isset($product->variants[0])) - $product->variant = $product->variants[0]; - if(isset($product->images[0])) - $product->image = $product->images[0]; - } - } - - $smarty->assign($params['var'], $products); - - } - } -} +currency = &self::$view_instance->currency; + $this->currencies = &self::$view_instance->currencies; + $this->user = &self::$view_instance->user; + $this->group = &self::$view_instance->group; + $this->page = &self::$view_instance->page; + } + else + { + // Сохраняем свой инстанс в статической переменной, + // чтобы в следующий раз использовать его + self::$view_instance = $this; + + // Все валюты + $this->currencies = $this->money->get_currencies(array('enabled'=>1)); + + // Выбор текущей валюты + if($currency_id = $this->request->get('currency_id', 'integer')) + { + $_SESSION['currency_id'] = $currency_id; + header("Location: ".$this->request->url(array('currency_id'=>null))); + } + + // Берем валюту из сессии + if(isset($_SESSION['currency_id'])) + $this->currency = $this->money->get_currency($_SESSION['currency_id']); + // Или первую из списка + else + $this->currency = reset($this->currencies); + + // Пользователь, если залогинен + if(isset($_SESSION['user_id'])) + { + $u = $this->users->get_user(intval($_SESSION['user_id'])); + if($u && $u->enabled) + { + $this->user = $u; + $this->group = $this->users->get_group($this->user->group_id); + + } + } + + // Текущая страница (если есть) + $subdir = substr(dirname(dirname(__FILE__)), strlen($_SERVER['DOCUMENT_ROOT'])); + $page_url = trim(substr($_SERVER['REQUEST_URI'], strlen($subdir)),"/"); + if(strpos($page_url, '?') !== false) + $page_url = substr($page_url, 0, strpos($page_url, '?')); + $this->page = $this->pages->get_page((string)$page_url); + $this->design->assign('page', $this->page); + + // Передаем в дизайн то, что может понадобиться в нем + $this->design->assign('currencies', $this->currencies); + $this->design->assign('currency', $this->currency); + $this->design->assign('user', $this->user); + $this->design->assign('group', $this->group); + + $this->design->assign('config', $this->config); + $this->design->assign('settings', $this->settings); + + // Настраиваем плагины для смарти + $this->design->smarty->registerPlugin("function", "get_posts", array($this, 'get_posts_plugin')); + $this->design->smarty->registerPlugin("function", "get_brands", array($this, 'get_brands_plugin')); + $this->design->smarty->registerPlugin("function", "get_browsed_products", array($this, 'get_browsed_products')); + $this->design->smarty->registerPlugin("function", "get_featured_products", array($this, 'get_featured_products_plugin')); + $this->design->smarty->registerPlugin("function", "get_new_products", array($this, 'get_new_products_plugin')); + $this->design->smarty->registerPlugin("function", "get_discounted_products", array($this, 'get_discounted_products_plugin')); + } + } + + /** + * + * Отображение + * + */ + public function fetch() + { + return false; + } + + /** + * + * Плагины для смарти + * + */ + public function get_posts_plugin($params, &$smarty) + { + if(!isset($params['visible'])) + $params['visible'] = 1; + if(!empty($params['var'])) + $smarty->assign($params['var'], $this->blog->get_posts($params)); + } + + public function get_brands_plugin($params, &$smarty) + { + if(!isset($params['visible'])) + $params['visible'] = 1; + if(!empty($params['var'])) + $smarty->assign($params['var'], $this->brands->get_brands($params)); + } + + public function get_browsed_products($params, &$smarty) + { + if(!empty($_COOKIE['browsed_products'])) + { + $browsed_products_ids = explode(',', $_COOKIE['browsed_products']); + $browsed_products_ids = array_reverse($browsed_products_ids); + if(isset($params['limit'])) + $browsed_products_ids = array_slice($browsed_products_ids, 0, $params['limit']); + + $products = array(); + foreach($this->products->get_products(array('id'=>$browsed_products_ids, 'visible'=>1)) as $p) + $products[$p->id] = $p; + + $browsed_products_images = $this->products->get_images(array('product_id'=>$browsed_products_ids)); + foreach($browsed_products_images as $browsed_product_image) + if(isset($products[$browsed_product_image->product_id])) + $products[$browsed_product_image->product_id]->images[] = $browsed_product_image; + + foreach($browsed_products_ids as $id) + { + if(isset($products[$id])) + { + if(isset($products[$id]->images[0])) + $products[$id]->image = $products[$id]->images[0]; + $result[] = $products[$id]; + } + } + $smarty->assign($params['var'], $result); + } + } + + + public function get_featured_products_plugin($params, &$smarty) + { + if(!isset($params['visible'])) + $params['visible'] = 1; + $params['featured'] = 1; + if(!empty($params['var'])) + { + foreach($this->products->get_products($params) as $p) + $products[$p->id] = $p; + + if(!empty($products)) + { + // id выбраных товаров + $products_ids = array_keys($products); + + // Выбираем варианты товаров + $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); + + // Для каждого варианта + foreach($variants as &$variant) + { + // добавляем вариант в соответствующий товар + $products[$variant->product_id]->variants[] = $variant; + } + + // Выбираем изображения товаров + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[] = $image; + + foreach($products as &$product) + { + if(isset($product->variants[0])) + $product->variant = $product->variants[0]; + if(isset($product->images[0])) + $product->image = $product->images[0]; + } + } + + $smarty->assign($params['var'], $products); + + } + } + + + public function get_new_products_plugin($params, &$smarty) + { + if(!isset($params['visible'])) + $params['visible'] = 1; + if(!isset($params['sort'])) + $params['sort'] = 'created'; + if(!empty($params['var'])) + { + foreach($this->products->get_products($params) as $p) + $products[$p->id] = $p; + + if(!empty($products)) + { + // id выбраных товаров + $products_ids = array_keys($products); + + // Выбираем варианты товаров + $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); + + // Для каждого варианта + foreach($variants as &$variant) + { + // добавляем вариант в соответствующий товар + $products[$variant->product_id]->variants[] = $variant; + } + + // Выбираем изображения товаров + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[] = $image; + + foreach($products as &$product) + { + if(isset($product->variants[0])) + $product->variant = $product->variants[0]; + if(isset($product->images[0])) + $product->image = $product->images[0]; + } + } + + $smarty->assign($params['var'], $products); + + } + } + + + public function get_discounted_products_plugin($params, &$smarty) + { + if(!isset($params['visible'])) + $params['visible'] = 1; + $params['discounted'] = 1; + if(!empty($params['var'])) + { + foreach($this->products->get_products($params) as $p) + $products[$p->id] = $p; + + if(!empty($products)) + { + // id выбраных товаров + $products_ids = array_keys($products); + + // Выбираем варианты товаров + $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true)); + + // Для каждого варианта + foreach($variants as &$variant) + { + // добавляем вариант в соответствующий товар + $products[$variant->product_id]->variants[] = $variant; + } + + // Выбираем изображения товаров + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[] = $image; + + foreach($products as &$product) + { + if(isset($product->variants[0])) + $product->variant = $product->variants[0]; + if(isset($product->images[0])) + $product->image = $product->images[0]; + } + } + + $smarty->assign($params['var'], $products); + + } + } +} From 1e8ad4ede72b1baeda449e56ae39d45929895780 Mon Sep 17 00:00:00 2001 From: Erko Evgen Date: Thu, 17 Mar 2016 12:22:38 +0200 Subject: [PATCH 4/5] code formatting for /api/*.php --- api/Blog.php | 444 +++++++++--------- api/Brands.php | 234 +++++----- api/Cart.php | 396 ++++++++-------- api/Categories.php | 516 ++++++++++----------- api/Comments.php | 298 ++++++------ api/Config.php | 262 ++++++----- api/Coupons.php | 342 +++++++------- api/Database.php | 1010 ++++++++++++++++++++-------------------- api/Delivery.php | 186 ++++---- api/Design.php | 610 ++++++++++++------------ api/Features.php | 116 +++-- api/Feedbacks.php | 239 +++++----- api/Image.php | 283 ++++++------ api/Managers.php | 41 +- api/Money.php | 313 +++++++------ api/Notify.php | 395 ++++++++-------- api/Orders.php | 1077 +++++++++++++++++++++---------------------- api/Pages.php | 279 +++++------ api/Payment.php | 311 ++++++------- api/Products.php | 1101 ++++++++++++++++++++++---------------------- api/Request.php | 639 ++++++++++++------------- api/Settings.php | 29 +- api/Simpla.php | 167 +++---- api/Users.php | 85 ++-- api/Variants.php | 213 ++++----- 25 files changed, 4808 insertions(+), 4778 deletions(-) diff --git a/api/Blog.php b/api/Blog.php index 7273885..5ad064c 100755 --- a/api/Blog.php +++ b/api/Blog.php @@ -1,222 +1,222 @@ -db->placehold(' WHERE b.id=? ', intval($id)); - else - $where = $this->db->placehold(' WHERE b.url=? ', $id); - - $query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text, b.meta_title, - b.meta_keywords, b.meta_description, b.visible, b.date - FROM __blog b $where LIMIT 1"); - if($this->db->query($query)) - return $this->db->result(); - else - return false; - } - - /* - * - * Функция возвращает массив постов, удовлетворяющих фильтру - * @param $filter - * - */ - public function get_posts($filter = array()) - { - // По умолчанию - $limit = 1000; - $page = 1; - $post_id_filter = ''; - $visible_filter = ''; - $keyword_filter = ''; - $posts = array(); - - if(isset($filter['limit'])) - $limit = max(1, intval($filter['limit'])); - - if(isset($filter['page'])) - $page = max(1, intval($filter['page'])); - - if(!empty($filter['id'])) - $post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']); - - if(isset($filter['visible'])) - $visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible'])); - - if(isset($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); - } - - $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); - - $query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text, - b.meta_title, b.meta_keywords, b.meta_description, b.visible, - b.date - FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter - ORDER BY date DESC, id DESC $sql_limit"); - - $this->db->query($query); - return $this->db->results(); - } - - - /* - * - * Функция вычисляет количество постов, удовлетворяющих фильтру - * @param $filter - * - */ - public function count_posts($filter = array()) - { - $post_id_filter = ''; - $visible_filter = ''; - $keyword_filter = ''; - - if(!empty($filter['id'])) - $post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']); - - if(isset($filter['visible'])) - $visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible'])); - - if(isset($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); - } - - $query = "SELECT COUNT(distinct b.id) as count - FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter"; - - if($this->db->query($query)) - return $this->db->result('count'); - else - return false; - } - - /* - * - * Создание поста - * @param $post - * - */ - public function add_post($post) - { - if(!isset($post->date)) - $date_query = ', date=NOW()'; - else - $date_query = ''; - $query = $this->db->placehold("INSERT INTO __blog SET ?% $date_query", $post); - - if(!$this->db->query($query)) - return false; - else - return $this->db->insert_id(); - } - - - /* - * - * Обновить пост(ы) - * @param $post - * - */ - public function update_post($id, $post) - { - $query = $this->db->placehold("UPDATE __blog SET ?% WHERE id in(?@) LIMIT ?", $post, (array)$id, count((array)$id)); - $this->db->query($query); - return $id; - } - - - /* - * - * Удалить пост - * @param $id - * - */ - public function delete_post($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __blog WHERE id=? LIMIT 1", intval($id)); - if($this->db->query($query)) - { - $query = $this->db->placehold("DELETE FROM __comments WHERE type='blog' AND object_id=?", intval($id)); - if($this->db->query($query)) - return true; - } - } - return false; - } - - - /* - * - * Следующий пост - * @param $post - * - */ - public function get_next_post($id) - { - $this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id); - $date = $this->db->result('date'); - - $this->db->query("(SELECT id FROM __blog WHERE date=? AND id>? AND visible ORDER BY id limit 1) - UNION - (SELECT id FROM __blog WHERE date>? AND visible ORDER BY date, id limit 1)", - $date, $id, $date); - $next_id = $this->db->result('id'); - if($next_id) - return $this->get_post(intval($next_id)); - else - return false; - } - - /* - * - * Предыдущий пост - * @param $post - * - */ - public function get_prev_post($id) - { - $this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id); - $date = $this->db->result('date'); - - $this->db->query("(SELECT id FROM __blog WHERE date=? AND iddb->result('id'); - if($prev_id) - return $this->get_post(intval($prev_id)); - else - return false; - } -} +db->placehold(' WHERE b.id=? ', intval($id)); + else + $where = $this->db->placehold(' WHERE b.url=? ', $id); + + $query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text, b.meta_title, + b.meta_keywords, b.meta_description, b.visible, b.date + FROM __blog b $where LIMIT 1"); + if($this->db->query($query)) + return $this->db->result(); + else + return false; + } + + /* + * + * Функция возвращает массив постов, удовлетворяющих фильтру + * @param $filter + * + */ + public function get_posts($filter = array()) + { + // По умолчанию + $limit = 1000; + $page = 1; + $post_id_filter = ''; + $visible_filter = ''; + $keyword_filter = ''; + $posts = array(); + + if(isset($filter['limit'])) + $limit = max(1, intval($filter['limit'])); + + if(isset($filter['page'])) + $page = max(1, intval($filter['page'])); + + if(!empty($filter['id'])) + $post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']); + + if(isset($filter['visible'])) + $visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible'])); + + if(isset($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); + } + + $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); + + $query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text, + b.meta_title, b.meta_keywords, b.meta_description, b.visible, + b.date + FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter + ORDER BY date DESC, id DESC $sql_limit"); + + $this->db->query($query); + return $this->db->results(); + } + + + /* + * + * Функция вычисляет количество постов, удовлетворяющих фильтру + * @param $filter + * + */ + public function count_posts($filter = array()) + { + $post_id_filter = ''; + $visible_filter = ''; + $keyword_filter = ''; + + if(!empty($filter['id'])) + $post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']); + + if(isset($filter['visible'])) + $visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible'])); + + if(isset($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); + } + + $query = "SELECT COUNT(distinct b.id) as count + FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter"; + + if($this->db->query($query)) + return $this->db->result('count'); + else + return false; + } + + /* + * + * Создание поста + * @param $post + * + */ + public function add_post($post) + { + if(!isset($post->date)) + $date_query = ', date=NOW()'; + else + $date_query = ''; + $query = $this->db->placehold("INSERT INTO __blog SET ?% $date_query", $post); + + if(!$this->db->query($query)) + return false; + else + return $this->db->insert_id(); + } + + + /* + * + * Обновить пост(ы) + * @param $post + * + */ + public function update_post($id, $post) + { + $query = $this->db->placehold("UPDATE __blog SET ?% WHERE id in(?@) LIMIT ?", $post, (array)$id, count((array)$id)); + $this->db->query($query); + return $id; + } + + + /* + * + * Удалить пост + * @param $id + * + */ + public function delete_post($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __blog WHERE id=? LIMIT 1", intval($id)); + if($this->db->query($query)) + { + $query = $this->db->placehold("DELETE FROM __comments WHERE type='blog' AND object_id=?", intval($id)); + if($this->db->query($query)) + return true; + } + } + return false; + } + + + /* + * + * Следующий пост + * @param $post + * + */ + public function get_next_post($id) + { + $this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id); + $date = $this->db->result('date'); + + $this->db->query("(SELECT id FROM __blog WHERE date=? AND id>? AND visible ORDER BY id limit 1) + UNION + (SELECT id FROM __blog WHERE date>? AND visible ORDER BY date, id limit 1)", + $date, $id, $date); + $next_id = $this->db->result('id'); + if($next_id) + return $this->get_post(intval($next_id)); + else + return false; + } + + /* + * + * Предыдущий пост + * @param $post + * + */ + public function get_prev_post($id) + { + $this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id); + $date = $this->db->result('date'); + + $this->db->query("(SELECT id FROM __blog WHERE date=? AND iddb->result('id'); + if($prev_id) + return $this->get_post(intval($prev_id)); + else + return false; + } +} diff --git a/api/Brands.php b/api/Brands.php index b5647aa..4840b7b 100755 --- a/api/Brands.php +++ b/api/Brands.php @@ -1,23 +1,23 @@ -db->placehold("SELECT DISTINCT b.id, b.name, b.url, b.meta_title, b.meta_keywords, b.meta_description, b.description, b.image - FROM __brands b $category_id_filter ORDER BY b.name"); - $this->db->query($query); - - return $this->db->results(); - } - - /* - * - * Функция возвращает бренд по его id или url - * (в зависимости от типа аргумента, int - id, string - url) - * @param $id id или url поста - * - */ - public function get_brand($id) - { - if(is_int($id)) - $filter = $this->db->placehold('b.id = ?', $id); - else - $filter = $this->db->placehold('b.url = ?', $id); - $query = "SELECT b.id, b.name, b.url, b.meta_title, b.meta_keywords, b.meta_description, b.description, b.image - FROM __brands b WHERE $filter LIMIT 1"; - $this->db->query($query); - return $this->db->result(); - } - - /* - * - * Добавление бренда - * @param $brand - * - */ - public function add_brand($brand) - { - $brand = (array)$brand; - if(empty($brand['url'])) - { - $brand['url'] = preg_replace("/[\s]+/ui", '_', $brand['name']); - $brand['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $brand['url'])); - } - - $this->db->query("INSERT INTO __brands SET ?%", $brand); - return $this->db->insert_id(); - } - - /* - * - * Обновление бренда(ов) - * @param $brand - * - */ - public function update_brand($id, $brand) - { - $query = $this->db->placehold("UPDATE __brands SET ?% WHERE id=? LIMIT 1", $brand, intval($id)); - $this->db->query($query); - return $id; - } - - /* - * - * Удаление бренда - * @param $id - * - */ - public function delete_brand($id) - { - if(!empty($id)) - { - $this->delete_image($id); - $query = $this->db->placehold("DELETE FROM __brands WHERE id=? LIMIT 1", $id); - $this->db->query($query); - $query = $this->db->placehold("UPDATE __products SET brand_id=NULL WHERE brand_id=?", $id); - $this->db->query($query); - } - } - - /* - * - * Удаление изображения бренда - * @param $id - * - */ - public function delete_image($brand_id) - { - $query = $this->db->placehold("SELECT image FROM __brands WHERE id=?", intval($brand_id)); - $this->db->query($query); - $filename = $this->db->result('image'); - if(!empty($filename)) - { - $query = $this->db->placehold("UPDATE __brands SET image=NULL WHERE id=?", $brand_id); - $this->db->query($query); - $query = $this->db->placehold("SELECT count(*) as count FROM __brands WHERE image=? LIMIT 1", $filename); - $this->db->query($query); - $count = $this->db->result('count'); - if($count == 0) - { - @unlink($this->config->root_dir.$this->config->brands_images_dir.$filename); - } + FROM __brands b $category_id_filter ORDER BY b.name"); + $this->db->query($query); + + return $this->db->results(); + } + + /* + * + * Функция возвращает бренд по его id или url + * (в зависимости от типа аргумента, int - id, string - url) + * @param $id id или url поста + * + */ + public function get_brand($id) + { + if(is_int($id)) + $filter = $this->db->placehold('b.id = ?', $id); + else + $filter = $this->db->placehold('b.url = ?', $id); + $query = "SELECT b.id, b.name, b.url, b.meta_title, b.meta_keywords, b.meta_description, b.description, b.image + FROM __brands b WHERE $filter LIMIT 1"; + $this->db->query($query); + return $this->db->result(); + } + + /* + * + * Добавление бренда + * @param $brand + * + */ + public function add_brand($brand) + { + $brand = (array)$brand; + if(empty($brand['url'])) + { + $brand['url'] = preg_replace("/[\s]+/ui", '_', $brand['name']); + $brand['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $brand['url'])); + } + + $this->db->query("INSERT INTO __brands SET ?%", $brand); + return $this->db->insert_id(); + } + + /* + * + * Обновление бренда(ов) + * @param $brand + * + */ + public function update_brand($id, $brand) + { + $query = $this->db->placehold("UPDATE __brands SET ?% WHERE id=? LIMIT 1", $brand, intval($id)); + $this->db->query($query); + return $id; + } + + /* + * + * Удаление бренда + * @param $id + * + */ + public function delete_brand($id) + { + if(!empty($id)) + { + $this->delete_image($id); + $query = $this->db->placehold("DELETE FROM __brands WHERE id=? LIMIT 1", $id); + $this->db->query($query); + $query = $this->db->placehold("UPDATE __products SET brand_id=NULL WHERE brand_id=?", $id); + $this->db->query($query); + } + } + + /* + * + * Удаление изображения бренда + * @param $id + * + */ + public function delete_image($brand_id) + { + $query = $this->db->placehold("SELECT image FROM __brands WHERE id=?", intval($brand_id)); + $this->db->query($query); + $filename = $this->db->result('image'); + if(!empty($filename)) + { + $query = $this->db->placehold("UPDATE __brands SET image=NULL WHERE id=?", $brand_id); + $this->db->query($query); + $query = $this->db->placehold("SELECT count(*) as count FROM __brands WHERE image=? LIMIT 1", $filename); + $this->db->query($query); + $count = $this->db->result('count'); + if($count == 0) + { + @unlink($this->config->root_dir.$this->config->brands_images_dir.$filename); + } } } diff --git a/api/Cart.php b/api/Cart.php index 106dac6..d715b3a 100755 --- a/api/Cart.php +++ b/api/Cart.php @@ -1,198 +1,198 @@ -purchases = array(); - $cart->total_price = 0; - $cart->total_products = 0; - $cart->coupon = null; - $cart->discount = 0; - $cart->coupon_discount = 0; - - // Берем из сессии список variant_id=>amount - if(!empty($_SESSION['shopping_cart'])) - { - $session_items = $_SESSION['shopping_cart']; - - $variants = $this->variants->get_variants(array('id'=>array_keys($session_items))); - if(!empty($variants)) - { - - foreach($variants as $variant) - { - $items[$variant->id] = new stdClass(); - $items[$variant->id]->variant = $variant; - $items[$variant->id]->amount = $session_items[$variant->id]; - $products_ids[] = $variant->product_id; - } - - $products = array(); - foreach($this->products->get_products(array('id'=>$products_ids, 'limit' => count($products_ids))) as $p) - $products[$p->id]=$p; - - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[$image->id] = $image; - - - foreach($items as $variant_id=>$item) - { - $purchase = null; - if(!empty($products[$item->variant->product_id])) - { - $purchase = new stdClass(); - $purchase->product = $products[$item->variant->product_id]; - $purchase->variant = $item->variant; - $purchase->amount = $item->amount; - - $cart->purchases[] = $purchase; - $cart->total_price += $item->variant->price*$item->amount; - $cart->total_products += $item->amount; - } - } - - // Пользовательская скидка - $cart->discount = 0; - if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id']))) - $cart->discount = $user->discount; - - $cart->total_price *= (100-$cart->discount)/100; - - // Скидка по купону - if(isset($_SESSION['coupon_code'])) - { - $cart->coupon = $this->coupons->get_coupon($_SESSION['coupon_code']); - if($cart->coupon && $cart->coupon->valid && $cart->total_price>=$cart->coupon->min_order_price) - { - if($cart->coupon->type=='absolute') - { - // Абсолютная скидка не более суммы заказа - $cart->coupon_discount = $cart->total_price>$cart->coupon->value?$cart->coupon->value:$cart->total_price; - $cart->total_price = max(0, $cart->total_price-$cart->coupon->value); - } - else - { - $cart->coupon_discount = $cart->total_price * ($cart->coupon->value)/100; - $cart->total_price = $cart->total_price-$cart->coupon_discount; - } - } - else - { - unset($_SESSION['coupon_code']); - } - } - - } - } - - return $cart; - } - - /* - * - * Добавление варианта товара в корзину - * - */ - public function add_item($variant_id, $amount = 1) - { - $amount = max(1, $amount); - - if(isset($_SESSION['shopping_cart'][$variant_id])) - $amount = max(1, $amount+$_SESSION['shopping_cart'][$variant_id]); - - // Выберем товар из базы, заодно убедившись в его существовании - $variant = $this->variants->get_variant($variant_id); - - // Если товар существует, добавим его в корзину - if(!empty($variant) && ($variant->stock>0) ) - { - // Не дадим больше чем на складе - $amount = min($amount, $variant->stock); - - $_SESSION['shopping_cart'][$variant_id] = intval($amount); - } - } - - /* - * - * Обновление количества товара - * - */ - public function update_item($variant_id, $amount = 1) - { - $amount = max(1, $amount); - - // Выберем товар из базы, заодно убедившись в его существовании - $variant = $this->variants->get_variant($variant_id); - - // Если товар существует, добавим его в корзину - if(!empty($variant) && $variant->stock>0) - { - // Не дадим больше чем на складе - $amount = min($amount, $variant->stock); - - $_SESSION['shopping_cart'][$variant_id] = intval($amount); - } - - } - - - /* - * - * Удаление товара из корзины - * - */ - public function delete_item($variant_id) - { - unset($_SESSION['shopping_cart'][$variant_id]); - } - - /* - * - * Очистка корзины - * - */ - public function empty_cart() - { - unset($_SESSION['shopping_cart']); - unset($_SESSION['coupon_code']); - } - - /* - * - * Применить купон - * - */ - public function apply_coupon($coupon_code) - { - $coupon = $this->coupons->get_coupon((string)$coupon_code); - if($coupon && $coupon->valid) - { - $_SESSION['coupon_code'] = $coupon->code; - } - else - { - unset($_SESSION['coupon_code']); - } - } -} \ No newline at end of file +purchases = array(); + $cart->total_price = 0; + $cart->total_products = 0; + $cart->coupon = null; + $cart->discount = 0; + $cart->coupon_discount = 0; + + // Берем из сессии список variant_id=>amount + if(!empty($_SESSION['shopping_cart'])) + { + $session_items = $_SESSION['shopping_cart']; + + $variants = $this->variants->get_variants(array('id'=>array_keys($session_items))); + if(!empty($variants)) + { + + foreach($variants as $variant) + { + $items[$variant->id] = new stdClass(); + $items[$variant->id]->variant = $variant; + $items[$variant->id]->amount = $session_items[$variant->id]; + $products_ids[] = $variant->product_id; + } + + $products = array(); + foreach($this->products->get_products(array('id'=>$products_ids, 'limit' => count($products_ids))) as $p) + $products[$p->id]=$p; + + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[$image->id] = $image; + + + foreach($items as $variant_id=>$item) + { + $purchase = null; + if(!empty($products[$item->variant->product_id])) + { + $purchase = new stdClass(); + $purchase->product = $products[$item->variant->product_id]; + $purchase->variant = $item->variant; + $purchase->amount = $item->amount; + + $cart->purchases[] = $purchase; + $cart->total_price += $item->variant->price*$item->amount; + $cart->total_products += $item->amount; + } + } + + // Пользовательская скидка + $cart->discount = 0; + if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id']))) + $cart->discount = $user->discount; + + $cart->total_price *= (100-$cart->discount)/100; + + // Скидка по купону + if(isset($_SESSION['coupon_code'])) + { + $cart->coupon = $this->coupons->get_coupon($_SESSION['coupon_code']); + if($cart->coupon && $cart->coupon->valid && $cart->total_price>=$cart->coupon->min_order_price) + { + if($cart->coupon->type=='absolute') + { + // Абсолютная скидка не более суммы заказа + $cart->coupon_discount = $cart->total_price>$cart->coupon->value?$cart->coupon->value:$cart->total_price; + $cart->total_price = max(0, $cart->total_price-$cart->coupon->value); + } + else + { + $cart->coupon_discount = $cart->total_price * ($cart->coupon->value)/100; + $cart->total_price = $cart->total_price-$cart->coupon_discount; + } + } + else + { + unset($_SESSION['coupon_code']); + } + } + + } + } + + return $cart; + } + + /* + * + * Добавление варианта товара в корзину + * + */ + public function add_item($variant_id, $amount = 1) + { + $amount = max(1, $amount); + + if(isset($_SESSION['shopping_cart'][$variant_id])) + $amount = max(1, $amount+$_SESSION['shopping_cart'][$variant_id]); + + // Выберем товар из базы, заодно убедившись в его существовании + $variant = $this->variants->get_variant($variant_id); + + // Если товар существует, добавим его в корзину + if(!empty($variant) && ($variant->stock>0) ) + { + // Не дадим больше чем на складе + $amount = min($amount, $variant->stock); + + $_SESSION['shopping_cart'][$variant_id] = intval($amount); + } + } + + /* + * + * Обновление количества товара + * + */ + public function update_item($variant_id, $amount = 1) + { + $amount = max(1, $amount); + + // Выберем товар из базы, заодно убедившись в его существовании + $variant = $this->variants->get_variant($variant_id); + + // Если товар существует, добавим его в корзину + if(!empty($variant) && $variant->stock>0) + { + // Не дадим больше чем на складе + $amount = min($amount, $variant->stock); + + $_SESSION['shopping_cart'][$variant_id] = intval($amount); + } + + } + + + /* + * + * Удаление товара из корзины + * + */ + public function delete_item($variant_id) + { + unset($_SESSION['shopping_cart'][$variant_id]); + } + + /* + * + * Очистка корзины + * + */ + public function empty_cart() + { + unset($_SESSION['shopping_cart']); + unset($_SESSION['coupon_code']); + } + + /* + * + * Применить купон + * + */ + public function apply_coupon($coupon_code) + { + $coupon = $this->coupons->get_coupon((string)$coupon_code); + if($coupon && $coupon->valid) + { + $_SESSION['coupon_code'] = $coupon->code; + } + else + { + unset($_SESSION['coupon_code']); + } + } +} diff --git a/api/Categories.php b/api/Categories.php index 7a85801..96fb1db 100755 --- a/api/Categories.php +++ b/api/Categories.php @@ -1,258 +1,258 @@ -categories_tree)) - $this->init_categories(); - - if(!empty($filter['product_id'])) - { - $query = $this->db->placehold("SELECT category_id FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$filter['product_id']); - $this->db->query($query); - $categories_ids = $this->db->results('category_id'); - $result = array(); - foreach($categories_ids as $id) - if(isset($this->all_categories[$id])) - $result[$id] = $this->all_categories[$id]; - return $result; - } - - return $this->all_categories; - } - - // Функция возвращает id категорий для заданного товара - public function get_product_categories($product_id) - { - $query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$product_id); - $this->db->query($query); - return $this->db->results(); - } - - // Функция возвращает id категорий для всех товаров - public function get_products_categories() - { - $query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories ORDER BY position"); - $this->db->query($query); - return $this->db->results(); - } - - // Функция возвращает дерево категорий - public function get_categories_tree() - { - if(!isset($this->categories_tree)) - $this->init_categories(); - - return $this->categories_tree; - } - - // Функция возвращает заданную категорию - public function get_category($id) - { - if(!isset($this->all_categories)) - $this->init_categories(); - if(is_int($id) && array_key_exists(intval($id), $this->all_categories)) - return $category = $this->all_categories[intval($id)]; - elseif(is_string($id)) - foreach ($this->all_categories as $category) - if ($category->url == $id) - return $this->get_category((int)$category->id); - - return false; - } - - // Добавление категории - public function add_category($category) - { - $category = (array)$category; - if(empty($category['url'])) - { - $category['url'] = preg_replace("/[\s]+/ui", '_', $category['name']); - $category['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $category['url'])); - } - - // Если есть категория с таким URL, добавляем к нему число - while($this->get_category((string)$category['url'])) - { - if(preg_match('/(.+)_([0-9]+)$/', $category['url'], $parts)) - $category['url'] = $parts[1].'_'.($parts[2]+1); - else - $category['url'] = $category['url'].'_2'; - } - - $this->db->query("INSERT INTO __categories SET ?%", $category); - $id = $this->db->insert_id(); - $this->db->query("UPDATE __categories SET position=id WHERE id=?", $id); - unset($this->categories_tree); - unset($this->all_categories); - return $id; - } - - // Изменение категории - public function update_category($id, $category) - { - $query = $this->db->placehold("UPDATE __categories SET ?% WHERE id=? LIMIT 1", $category, intval($id)); - $this->db->query($query); - unset($this->categories_tree); - unset($this->all_categories); - return intval($id); - } - - // Удаление категории - public function delete_category($ids) - { - $ids = (array) $ids; - foreach($ids as $id) - { - if($category = $this->get_category(intval($id))) - $this->delete_image($category->children); - if(!empty($category->children)) - { - $query = $this->db->placehold("DELETE FROM __categories WHERE id in(?@)", $category->children); - $this->db->query($query); - $query = $this->db->placehold("DELETE FROM __products_categories WHERE category_id in(?@)", $category->children); - $this->db->query($query); - } - } - unset($this->categories_tree); - unset($this->all_categories); - return $id; - } - - // Добавить категорию к заданному товару - public function add_product_category($product_id, $category_id, $position=0) - { - $query = $this->db->placehold("INSERT IGNORE INTO __products_categories SET product_id=?, category_id=?, position=?", $product_id, $category_id, $position); - $this->db->query($query); - } - - // Удалить категорию заданного товара - public function delete_product_category($product_id, $category_id) - { - $query = $this->db->placehold("DELETE FROM __products_categories WHERE product_id=? AND category_id=? LIMIT 1", intval($product_id), intval($category_id)); - $this->db->query($query); - } - - // Удалить изображение категории - public function delete_image($categories_ids) - { - $categories_ids = (array) $categories_ids; - $query = $this->db->placehold("SELECT image FROM __categories WHERE id in(?@)", $categories_ids); - $this->db->query($query); - $filenames = $this->db->results('image'); - if(!empty($filenames)) - { - $query = $this->db->placehold("UPDATE __categories SET image=NULL WHERE id in(?@)", $categories_ids); - $this->db->query($query); - foreach($filenames as $filename) - { - $query = $this->db->placehold("SELECT count(*) as count FROM __categories WHERE image=?", $filename); - $this->db->query($query); - $count = $this->db->result('count'); - if($count == 0) - { - @unlink($this->config->root_dir.$this->config->categories_images_dir.$filename); - } - } - unset($this->categories_tree); - unset($this->all_categories); - } - } - - - // Инициализация категорий, после которой категории будем выбирать из локальной переменной - private function init_categories() - { - // Дерево категорий - $tree = new stdClass(); - $tree->subcategories = array(); - - // Указатели на узлы дерева - $pointers = array(); - $pointers[0] = &$tree; - $pointers[0]->path = array(); - $pointers[0]->level = 0; - - // Выбираем все категории - $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 - FROM __categories c ORDER BY c.parent_id, c.position"); - - // Выбор категорий с подсчетом количества товаров для каждой. Может тормозить при большом количестве товаров. - // $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 - // 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"); - - - $this->db->query($query); - $categories = $this->db->results(); - - $finish = false; - // Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть - while(!empty($categories) && !$finish) - { - $flag = false; - // Проходим все выбранные категории - foreach($categories as $k=>$category) - { - if(isset($pointers[$category->parent_id])) - { - // В дерево категорий (через указатель) добавляем текущую категорию - $pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category; - - // Путь к текущей категории - $curr = $pointers[$category->id]; - $pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr)); - - // Уровень вложенности категории - $pointers[$category->id]->level = 1+$pointers[$category->parent_id]->level; - - // Убираем использованную категорию из массива категорий - unset($categories[$k]); - $flag = true; - } - } - if(!$flag) $finish = true; - } - - // Для каждой категории id всех ее деток узнаем - $ids = array_reverse(array_keys($pointers)); - foreach($ids as $id) - { - if($id>0) - { - $pointers[$id]->children[] = $id; - - if(isset($pointers[$pointers[$id]->parent_id]->children)) - $pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children); - else - $pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children; - - // Добавляем количество товаров к родительской категории, если текущая видима - // if(isset($pointers[$pointers[$id]->parent_id]) && $pointers[$id]->visible) - // $pointers[$pointers[$id]->parent_id]->products_count += $pointers[$id]->products_count; - } - } - unset($pointers[0]); - unset($ids); - - $this->categories_tree = $tree->subcategories; - $this->all_categories = $pointers; - } -} \ No newline at end of file +categories_tree)) + $this->init_categories(); + + if(!empty($filter['product_id'])) + { + $query = $this->db->placehold("SELECT category_id FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$filter['product_id']); + $this->db->query($query); + $categories_ids = $this->db->results('category_id'); + $result = array(); + foreach($categories_ids as $id) + if(isset($this->all_categories[$id])) + $result[$id] = $this->all_categories[$id]; + return $result; + } + + return $this->all_categories; + } + + // Функция возвращает id категорий для заданного товара + public function get_product_categories($product_id) + { + $query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$product_id); + $this->db->query($query); + return $this->db->results(); + } + + // Функция возвращает id категорий для всех товаров + public function get_products_categories() + { + $query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories ORDER BY position"); + $this->db->query($query); + return $this->db->results(); + } + + // Функция возвращает дерево категорий + public function get_categories_tree() + { + if(!isset($this->categories_tree)) + $this->init_categories(); + + return $this->categories_tree; + } + + // Функция возвращает заданную категорию + public function get_category($id) + { + if(!isset($this->all_categories)) + $this->init_categories(); + if(is_int($id) && array_key_exists(intval($id), $this->all_categories)) + return $category = $this->all_categories[intval($id)]; + elseif(is_string($id)) + foreach ($this->all_categories as $category) + if ($category->url == $id) + return $this->get_category((int)$category->id); + + return false; + } + + // Добавление категории + public function add_category($category) + { + $category = (array)$category; + if(empty($category['url'])) + { + $category['url'] = preg_replace("/[\s]+/ui", '_', $category['name']); + $category['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $category['url'])); + } + + // Если есть категория с таким URL, добавляем к нему число + while($this->get_category((string)$category['url'])) + { + if(preg_match('/(.+)_([0-9]+)$/', $category['url'], $parts)) + $category['url'] = $parts[1].'_'.($parts[2]+1); + else + $category['url'] = $category['url'].'_2'; + } + + $this->db->query("INSERT INTO __categories SET ?%", $category); + $id = $this->db->insert_id(); + $this->db->query("UPDATE __categories SET position=id WHERE id=?", $id); + unset($this->categories_tree); + unset($this->all_categories); + return $id; + } + + // Изменение категории + public function update_category($id, $category) + { + $query = $this->db->placehold("UPDATE __categories SET ?% WHERE id=? LIMIT 1", $category, intval($id)); + $this->db->query($query); + unset($this->categories_tree); + unset($this->all_categories); + return intval($id); + } + + // Удаление категории + public function delete_category($ids) + { + $ids = (array) $ids; + foreach($ids as $id) + { + if($category = $this->get_category(intval($id))) + $this->delete_image($category->children); + if(!empty($category->children)) + { + $query = $this->db->placehold("DELETE FROM __categories WHERE id in(?@)", $category->children); + $this->db->query($query); + $query = $this->db->placehold("DELETE FROM __products_categories WHERE category_id in(?@)", $category->children); + $this->db->query($query); + } + } + unset($this->categories_tree); + unset($this->all_categories); + return $id; + } + + // Добавить категорию к заданному товару + public function add_product_category($product_id, $category_id, $position=0) + { + $query = $this->db->placehold("INSERT IGNORE INTO __products_categories SET product_id=?, category_id=?, position=?", $product_id, $category_id, $position); + $this->db->query($query); + } + + // Удалить категорию заданного товара + public function delete_product_category($product_id, $category_id) + { + $query = $this->db->placehold("DELETE FROM __products_categories WHERE product_id=? AND category_id=? LIMIT 1", intval($product_id), intval($category_id)); + $this->db->query($query); + } + + // Удалить изображение категории + public function delete_image($categories_ids) + { + $categories_ids = (array) $categories_ids; + $query = $this->db->placehold("SELECT image FROM __categories WHERE id in(?@)", $categories_ids); + $this->db->query($query); + $filenames = $this->db->results('image'); + if(!empty($filenames)) + { + $query = $this->db->placehold("UPDATE __categories SET image=NULL WHERE id in(?@)", $categories_ids); + $this->db->query($query); + foreach($filenames as $filename) + { + $query = $this->db->placehold("SELECT count(*) as count FROM __categories WHERE image=?", $filename); + $this->db->query($query); + $count = $this->db->result('count'); + if($count == 0) + { + @unlink($this->config->root_dir.$this->config->categories_images_dir.$filename); + } + } + unset($this->categories_tree); + unset($this->all_categories); + } + } + + + // Инициализация категорий, после которой категории будем выбирать из локальной переменной + private function init_categories() + { + // Дерево категорий + $tree = new stdClass(); + $tree->subcategories = array(); + + // Указатели на узлы дерева + $pointers = array(); + $pointers[0] = &$tree; + $pointers[0]->path = array(); + $pointers[0]->level = 0; + + // Выбираем все категории + $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 + FROM __categories c ORDER BY c.parent_id, c.position"); + + // Выбор категорий с подсчетом количества товаров для каждой. Может тормозить при большом количестве товаров. + // $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 + // 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"); + + + $this->db->query($query); + $categories = $this->db->results(); + + $finish = false; + // Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть + while(!empty($categories) && !$finish) + { + $flag = false; + // Проходим все выбранные категории + foreach($categories as $k=>$category) + { + if(isset($pointers[$category->parent_id])) + { + // В дерево категорий (через указатель) добавляем текущую категорию + $pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category; + + // Путь к текущей категории + $curr = $pointers[$category->id]; + $pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr)); + + // Уровень вложенности категории + $pointers[$category->id]->level = 1+$pointers[$category->parent_id]->level; + + // Убираем использованную категорию из массива категорий + unset($categories[$k]); + $flag = true; + } + } + if(!$flag) $finish = true; + } + + // Для каждой категории id всех ее деток узнаем + $ids = array_reverse(array_keys($pointers)); + foreach($ids as $id) + { + if($id>0) + { + $pointers[$id]->children[] = $id; + + if(isset($pointers[$pointers[$id]->parent_id]->children)) + $pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children); + else + $pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children; + + // Добавляем количество товаров к родительской категории, если текущая видима + // if(isset($pointers[$pointers[$id]->parent_id]) && $pointers[$id]->visible) + // $pointers[$pointers[$id]->parent_id]->products_count += $pointers[$id]->products_count; + } + } + unset($pointers[0]); + unset($ids); + + $this->categories_tree = $tree->subcategories; + $this->all_categories = $pointers; + } +} diff --git a/api/Comments.php b/api/Comments.php index f13de25..5e351bb 100755 --- a/api/Comments.php +++ b/api/Comments.php @@ -1,149 +1,149 @@ -db->placehold("SELECT c.id, c.object_id, c.name, c.ip, c.type, c.text, c.date, c.approved FROM __comments c WHERE id=? LIMIT 1", intval($id)); - - if($this->db->query($query)) - return $this->db->result(); - else - return false; - } - - // Возвращает комментарии, удовлетворяющие фильтру - public function get_comments($filter = array()) - { - // По умолчанию - $limit = 0; - $page = 1; - $object_id_filter = ''; - $type_filter = ''; - $keyword_filter = ''; - $approved_filter = ''; - - if(isset($filter['limit'])) - $limit = max(1, intval($filter['limit'])); - - if(isset($filter['page'])) - $page = max(1, intval($filter['page'])); - - if(isset($filter['ip'])) - $ip = $this->db->placehold("OR c.ip=?", $filter['ip']); - if(isset($filter['approved'])) - $approved_filter = $this->db->placehold("AND (c.approved=? $ip)", intval($filter['approved'])); - - if($limit) - $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); - else - $sql_limit = ''; - - if(!empty($filter['object_id'])) - $object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']); - - if(!empty($filter['type'])) - $type_filter = $this->db->placehold('AND c.type=?', $filter['type']); - - if(!empty($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR c.text LIKE "%'.$this->db->escape(trim($keyword)).'%" '); - } - - - $sort='DESC'; - - $query = $this->db->placehold("SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.approved - FROM __comments c WHERE 1 $object_id_filter $type_filter $keyword_filter $approved_filter ORDER BY id $sort $sql_limit"); - - $this->db->query($query); - return $this->db->results(); - } - - // Количество комментариев, удовлетворяющих фильтру - public function count_comments($filter = array()) - { - $object_id_filter = ''; - $type_filter = ''; - $approved_filter = ''; - $keyword_filter = ''; - - if(!empty($filter['object_id'])) - $object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']); - - if(!empty($filter['type'])) - $type_filter = $this->db->placehold('AND c.type=?', $filter['type']); - - if(isset($filter['approved'])) - $approved_filter = $this->db->placehold('AND c.approved=?', intval($filter['approved'])); - - if(!empty($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR c.text LIKE "%'.$this->db->escape(trim($keyword)).'%" '); - } - - $query = $this->db->placehold("SELECT count(distinct c.id) as count - FROM __comments c WHERE 1 $object_id_filter $type_filter $keyword_filter $approved_filter", $this->settings->date_format); - - $this->db->query($query); - return $this->db->result('count'); - - } - - // Добавление комментария - public function add_comment($comment) - { - $query = $this->db->placehold('INSERT INTO __comments - SET ?%, - date = NOW()', - $comment); - - if(!$this->db->query($query)) - return false; - - $id = $this->db->insert_id(); - return $id; - } - - // Изменение комментария - public function update_comment($id, $comment) - { - $date_query = ''; - if(isset($comment->date)) - { - $date = $comment->date; - unset($comment->date); - $date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format); - } - $query = $this->db->placehold("UPDATE __comments SET ?% $date_query WHERE id in(?@) LIMIT 1", $comment, (array)$id); - $this->db->query($query); - return $id; - } - - // Удаление комментария - public function delete_comment($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __comments WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - } - } -} +db->placehold("SELECT c.id, c.object_id, c.name, c.ip, c.type, c.text, c.date, c.approved FROM __comments c WHERE id=? LIMIT 1", intval($id)); + + if($this->db->query($query)) + return $this->db->result(); + else + return false; + } + + // Возвращает комментарии, удовлетворяющие фильтру + public function get_comments($filter = array()) + { + // По умолчанию + $limit = 0; + $page = 1; + $object_id_filter = ''; + $type_filter = ''; + $keyword_filter = ''; + $approved_filter = ''; + + if(isset($filter['limit'])) + $limit = max(1, intval($filter['limit'])); + + if(isset($filter['page'])) + $page = max(1, intval($filter['page'])); + + if(isset($filter['ip'])) + $ip = $this->db->placehold("OR c.ip=?", $filter['ip']); + if(isset($filter['approved'])) + $approved_filter = $this->db->placehold("AND (c.approved=? $ip)", intval($filter['approved'])); + + if($limit) + $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); + else + $sql_limit = ''; + + if(!empty($filter['object_id'])) + $object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']); + + if(!empty($filter['type'])) + $type_filter = $this->db->placehold('AND c.type=?', $filter['type']); + + if(!empty($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR c.text LIKE "%'.$this->db->escape(trim($keyword)).'%" '); + } + + + $sort='DESC'; + + $query = $this->db->placehold("SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.approved + FROM __comments c WHERE 1 $object_id_filter $type_filter $keyword_filter $approved_filter ORDER BY id $sort $sql_limit"); + + $this->db->query($query); + return $this->db->results(); + } + + // Количество комментариев, удовлетворяющих фильтру + public function count_comments($filter = array()) + { + $object_id_filter = ''; + $type_filter = ''; + $approved_filter = ''; + $keyword_filter = ''; + + if(!empty($filter['object_id'])) + $object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']); + + if(!empty($filter['type'])) + $type_filter = $this->db->placehold('AND c.type=?', $filter['type']); + + if(isset($filter['approved'])) + $approved_filter = $this->db->placehold('AND c.approved=?', intval($filter['approved'])); + + if(!empty($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR c.text LIKE "%'.$this->db->escape(trim($keyword)).'%" '); + } + + $query = $this->db->placehold("SELECT count(distinct c.id) as count + FROM __comments c WHERE 1 $object_id_filter $type_filter $keyword_filter $approved_filter", $this->settings->date_format); + + $this->db->query($query); + return $this->db->result('count'); + + } + + // Добавление комментария + public function add_comment($comment) + { + $query = $this->db->placehold('INSERT INTO __comments + SET ?%, + date = NOW()', + $comment); + + if(!$this->db->query($query)) + return false; + + $id = $this->db->insert_id(); + return $id; + } + + // Изменение комментария + public function update_comment($id, $comment) + { + $date_query = ''; + if(isset($comment->date)) + { + $date = $comment->date; + unset($comment->date); + $date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format); + } + $query = $this->db->placehold("UPDATE __comments SET ?% $date_query WHERE id in(?@) LIMIT 1", $comment, (array)$id); + $this->db->query($query); + return $id; + } + + // Удаление комментария + public function delete_comment($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __comments WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + } + } +} diff --git a/api/Config.php b/api/Config.php index d2da122..b2d2c25 100755 --- a/api/Config.php +++ b/api/Config.php @@ -1,132 +1,130 @@ -config->db_user - public function __construct() - { - // Читаем настройки из дефолтного файла - $ini = parse_ini_file(dirname(dirname(__FILE__)).'/'.$this->config_file); - // Записываем настройку как переменную класса - foreach($ini as $var=>$value) - $this->vars[$var] = $value; - - // Вычисляем DOCUMENT_ROOT вручную, так как иногда в нем находится что-то левое - $localpath=getenv("SCRIPT_NAME"); - $absolutepath=getenv("SCRIPT_FILENAME"); - $_SERVER['DOCUMENT_ROOT']=substr($absolutepath,0,strpos($absolutepath,$localpath)); - - // Адрес сайта - тоже одна из настроек, но вычисляем его автоматически, а не берем из файла - $script_dir1 = realpath(dirname(dirname(__FILE__))); - $script_dir2 = realpath($_SERVER['DOCUMENT_ROOT']); - $subdir = trim(substr($script_dir1, strlen($script_dir2)), "/\\"); - - if (!isset($_SERVER['HTTP_HOST'])) - $_SERVER['HTTP_HOST'] = getenv('HTTP_HOST'); - - $this->vars['host'] = rtrim($_SERVER['HTTP_HOST']); - - // Протокол (http OR https) - $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'? 'https' : 'http'; - if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) { - $protocol = 'https'; - } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') { - $protocol = 'https'; - } elseif( isset($_SERVER['SERVER_PORT']) && '443' == $_SERVER['SERVER_PORT'] ) { - $protocol = 'https'; - } - - $this->vars['protocol'] = $protocol; - $this->vars['root_url'] = $protocol.'://'.$this->vars['host']; - if(!empty($subdir)) - $this->vars['root_url'] .= '/'.$subdir; - - // Подпапка в которую установлена симпла относительно корня веб-сервера - $this->vars['subfolder'] = $subdir.'/'; - - // Определяем корневую директорию сайта - $this->vars['root_dir'] = dirname(dirname(__FILE__)).'/'; - - // Максимальный размер загружаемых файлов - $max_upload = (int)(ini_get('upload_max_filesize')); - $max_post = (int)(ini_get('post_max_size')); - $memory_limit = (int)(ini_get('memory_limit')); - $this->vars['max_upload_filesize'] = min($max_upload, $max_post, $memory_limit)*1024*1024; - - // Если соль не определена, то будем генировать ее - if(empty($this->vars['salt'])) - { - // Соль (разная для каждой копии сайта, изменяющаяся при изменении config-файла) - $s = stat(dirname(dirname(__FILE__)).'/'.$this->config_file); - $this->vars['salt'] = md5(md5_file(dirname(dirname(__FILE__)).'/'.$this->config_file).$s['dev'].$s['ino'].$s['uid'].$s['mtime']); - } - - - // Часовой пояс - if(!empty($this->vars['php_timezone'])) - { - date_default_timezone_set($this->vars['php_timezone']); - } - elseif(!ini_get('date.timezone')) - { - date_default_timezone_set('UTC'); - } - } - - // Магическим методов возвращаем нужную переменную - public function __get($name) - { - if(isset($this->vars[$name])) - return $this->vars[$name]; - else - return null; - } - - // Магическим методов задаём нужную переменную - public function __set($name, $value) - { - # Запишем конфиги - if(isset($this->vars[$name])) - { - $conf = file_get_contents(dirname(dirname(__FILE__)).'/'.$this->config_file); - $conf = preg_replace("/".$name."\s*=.*\n/i", $name.' = '.$value."\r\n", $conf); - $cf = fopen(dirname(dirname(__FILE__)).'/'.$this->config_file, 'w'); - fwrite($cf, $conf); - fclose($cf); - $this->vars[$name] = $value; - } - } - - public function token($text) - { - return md5($text.$this->salt); - } - - public function check_token($text, $token) - { - if(!empty($token) && $token === $this->token($text)) - return true; - return false; - } -} +config->db_user + public function __construct() + { + // Читаем настройки из дефолтного файла + $ini = parse_ini_file(dirname(dirname(__FILE__)).'/'.$this->config_file); + // Записываем настройку как переменную класса + foreach($ini as $var=>$value) + $this->vars[$var] = $value; + + // Вычисляем DOCUMENT_ROOT вручную, так как иногда в нем находится что-то левое + $localpath = getenv("SCRIPT_NAME"); + $absolutepath = getenv("SCRIPT_FILENAME"); + $_SERVER['DOCUMENT_ROOT']=substr($absolutepath,0,strpos($absolutepath,$localpath)); + + // Адрес сайта - тоже одна из настроек, но вычисляем его автоматически, а не берем из файла + $script_dir1 = realpath(dirname(dirname(__FILE__))); + $script_dir2 = realpath($_SERVER['DOCUMENT_ROOT']); + $subdir = trim(substr($script_dir1, strlen($script_dir2)), "/\\"); + + if (!isset($_SERVER['HTTP_HOST'])) + $_SERVER['HTTP_HOST'] = getenv('HTTP_HOST'); + + $this->vars['host'] = rtrim($_SERVER['HTTP_HOST']); + + // Протокол (http OR https) + $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'? 'https' : 'http'; + if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) { + $protocol = 'https'; + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') { + $protocol = 'https'; + } elseif( isset($_SERVER['SERVER_PORT']) && '443' == $_SERVER['SERVER_PORT'] ) { + $protocol = 'https'; + } + + $this->vars['protocol'] = $protocol; + $this->vars['root_url'] = $protocol.'://'.$this->vars['host']; + if(!empty($subdir)) + $this->vars['root_url'] .= '/'.$subdir; + + // Подпапка в которую установлена симпла относительно корня веб-сервера + $this->vars['subfolder'] = $subdir.'/'; + + // Определяем корневую директорию сайта + $this->vars['root_dir'] = dirname(dirname(__FILE__)).'/'; + + // Максимальный размер загружаемых файлов + $max_upload = (int)(ini_get('upload_max_filesize')); + $max_post = (int)(ini_get('post_max_size')); + $memory_limit = (int)(ini_get('memory_limit')); + $this->vars['max_upload_filesize'] = min($max_upload, $max_post, $memory_limit)*1024*1024; + + // Если соль не определена, то будем генировать ее + if(empty($this->vars['salt'])) + { + // Соль (разная для каждой копии сайта, изменяющаяся при изменении config-файла) + $s = stat(dirname(dirname(__FILE__)).'/'.$this->config_file); + $this->vars['salt'] = md5(md5_file(dirname(dirname(__FILE__)).'/'.$this->config_file).$s['dev'].$s['ino'].$s['uid'].$s['mtime']); + } + + + // Часовой пояс + if(!empty($this->vars['php_timezone'])) + { + date_default_timezone_set($this->vars['php_timezone']); + } + elseif(!ini_get('date.timezone')) + { + date_default_timezone_set('UTC'); + } + } + + // Магическим методов возвращаем нужную переменную + public function __get($name) + { + if(isset($this->vars[$name])) + return $this->vars[$name]; + else + return null; + } + + // Магическим методов задаём нужную переменную + public function __set($name, $value) + { + # Запишем конфиги + if(isset($this->vars[$name])) + { + $conf = file_get_contents(dirname(dirname(__FILE__)).'/'.$this->config_file); + $conf = preg_replace("/".$name."\s*=.*\n/i", $name.' = '.$value."\r\n", $conf); + $cf = fopen(dirname(dirname(__FILE__)).'/'.$this->config_file, 'w'); + fwrite($cf, $conf); + fclose($cf); + $this->vars[$name] = $value; + } + } + + public function token($text) + { + return md5($text.$this->salt); + } + + public function check_token($text, $token) + { + if(!empty($token) && $token === $this->token($text)) + return true; + return false; + } +} diff --git a/api/Coupons.php b/api/Coupons.php index f4e41dc..9041525 100755 --- a/api/Coupons.php +++ b/api/Coupons.php @@ -1,171 +1,171 @@ -db->placehold('WHERE c.code=? ', $id); - else - $where = $this->db->placehold('WHERE c.id=? ', $id); - - $query = $this->db->placehold("SELECT c.id, c.code, c.value, c.type, c.expire, min_order_price, c.single, c.usages, - ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single)) AS valid - FROM __coupons c $where LIMIT 1"); - if($this->db->query($query)) - return $this->db->result(); - else - return false; - } - - /* - * - * Функция возвращает массив купонов, удовлетворяющих фильтру - * @param $filter - * - */ - public function get_coupons($filter = array()) - { - // По умолчанию - $limit = 1000; - $page = 1; - $coupon_id_filter = ''; - $valid_filter = ''; - $keyword_filter = ''; - - if(isset($filter['limit'])) - $limit = max(1, intval($filter['limit'])); - - if(isset($filter['page'])) - $page = max(1, intval($filter['page'])); - - if(!empty($filter['id'])) - $coupon_id_filter = $this->db->placehold('AND c.id in(?@)', (array)$filter['id']); - - if(isset($filter['valid'])) - if($filter['valid']) - $valid_filter = $this->db->placehold('AND ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))'); - else - $valid_filter = $this->db->placehold('AND NOT ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))'); - - if(isset($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); - } - - $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); - - $query = $this->db->placehold("SELECT c.id, c.code, c.value, c.type, c.expire, min_order_price, c.single, c.usages, - ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single)) AS valid - FROM __coupons c WHERE 1 $coupon_id_filter $valid_filter $keyword_filter - ORDER BY valid DESC, id DESC $sql_limit", - $this->settings->date_format); - - $this->db->query($query); - return $this->db->results(); - } - - - /* - * - * Функция вычисляет количество постов, удовлетворяющих фильтру - * @param $filter - * - */ - public function count_coupons($filter = array()) - { - $coupon_id_filter = ''; - $valid_filter = ''; - - if(!empty($filter['id'])) - $coupon_id_filter = $this->db->placehold('AND c.id in(?@)', (array)$filter['id']); - - if(isset($filter['valid'])) - $valid_filter = $this->db->placehold('AND ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))'); - - if(isset($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); - } - - $query = "SELECT COUNT(distinct c.id) as count - FROM __coupons c WHERE 1 $coupon_id_filter $valid_filter"; - - if($this->db->query($query)) - return $this->db->result('count'); - else - return false; - } - - /* - * - * Создание купона - * @param $coupon - * - */ - public function add_coupon($coupon) - { - if(empty($coupon->single)) - $coupon->single = 0; - $query = $this->db->placehold("INSERT INTO __coupons SET ?%", $coupon); - - if(!$this->db->query($query)) - return false; - else - return $this->db->insert_id(); - } - - - /* - * - * Обновить купон(ы) - * @param $id, $coupon - * - */ - public function update_coupon($id, $coupon) - { - $query = $this->db->placehold("UPDATE __coupons SET ?% WHERE id in(?@) LIMIT ?", $coupon, (array)$id, count((array)$id)); - $this->db->query($query); - return $id; - } - - - /* - * - * Удалить купон - * @param $id - * - */ - public function delete_coupon($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __coupons WHERE id=? LIMIT 1", intval($id)); - return $this->db->query($query); - } - } - -} +db->placehold('WHERE c.code=? ', $id); + else + $where = $this->db->placehold('WHERE c.id=? ', $id); + + $query = $this->db->placehold("SELECT c.id, c.code, c.value, c.type, c.expire, min_order_price, c.single, c.usages, + ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single)) AS valid + FROM __coupons c $where LIMIT 1"); + if($this->db->query($query)) + return $this->db->result(); + else + return false; + } + + /* + * + * Функция возвращает массив купонов, удовлетворяющих фильтру + * @param $filter + * + */ + public function get_coupons($filter = array()) + { + // По умолчанию + $limit = 1000; + $page = 1; + $coupon_id_filter = ''; + $valid_filter = ''; + $keyword_filter = ''; + + if(isset($filter['limit'])) + $limit = max(1, intval($filter['limit'])); + + if(isset($filter['page'])) + $page = max(1, intval($filter['page'])); + + if(!empty($filter['id'])) + $coupon_id_filter = $this->db->placehold('AND c.id in(?@)', (array)$filter['id']); + + if(isset($filter['valid'])) + if($filter['valid']) + $valid_filter = $this->db->placehold('AND ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))'); + else + $valid_filter = $this->db->placehold('AND NOT ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))'); + + if(isset($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); + } + + $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); + + $query = $this->db->placehold("SELECT c.id, c.code, c.value, c.type, c.expire, min_order_price, c.single, c.usages, + ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single)) AS valid + FROM __coupons c WHERE 1 $coupon_id_filter $valid_filter $keyword_filter + ORDER BY valid DESC, id DESC $sql_limit", + $this->settings->date_format); + + $this->db->query($query); + return $this->db->results(); + } + + + /* + * + * Функция вычисляет количество постов, удовлетворяющих фильтру + * @param $filter + * + */ + public function count_coupons($filter = array()) + { + $coupon_id_filter = ''; + $valid_filter = ''; + + if(!empty($filter['id'])) + $coupon_id_filter = $this->db->placehold('AND c.id in(?@)', (array)$filter['id']); + + if(isset($filter['valid'])) + $valid_filter = $this->db->placehold('AND ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))'); + + if(isset($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") '); + } + + $query = "SELECT COUNT(distinct c.id) as count + FROM __coupons c WHERE 1 $coupon_id_filter $valid_filter"; + + if($this->db->query($query)) + return $this->db->result('count'); + else + return false; + } + + /* + * + * Создание купона + * @param $coupon + * + */ + public function add_coupon($coupon) + { + if(empty($coupon->single)) + $coupon->single = 0; + $query = $this->db->placehold("INSERT INTO __coupons SET ?%", $coupon); + + if(!$this->db->query($query)) + return false; + else + return $this->db->insert_id(); + } + + + /* + * + * Обновить купон(ы) + * @param $id, $coupon + * + */ + public function update_coupon($id, $coupon) + { + $query = $this->db->placehold("UPDATE __coupons SET ?% WHERE id in(?@) LIMIT ?", $coupon, (array)$id, count((array)$id)); + $this->db->query($query); + return $id; + } + + + /* + * + * Удалить купон + * @param $id + * + */ + public function delete_coupon($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __coupons WHERE id=? LIMIT 1", intval($id)); + return $this->db->query($query); + } + } + +} diff --git a/api/Database.php b/api/Database.php index 954bb37..05d21a9 100755 --- a/api/Database.php +++ b/api/Database.php @@ -1,505 +1,505 @@ -connect(); - } - - /** - * В деструкторе отсоединяемся от базы - */ - public function __destruct() - { - $this->disconnect(); - } - - /** - * Подключение к базе данных - */ - public function connect() - { - // При повторном вызове возвращаем существующий линк - if(!empty($this->mysqli)) - return $this->mysqli; - // Иначе устанавливаем соединение - else - $this->mysqli = new mysqli($this->config->db_server, $this->config->db_user, $this->config->db_password, $this->config->db_name); - - // Выводим сообщение, в случае ошибки - if($this->mysqli->connect_error) - { - trigger_error("Could not connect to the database: ".$this->mysqli->connect_error, E_USER_WARNING); - return false; - } - // Или настраиваем соединение - else - { - if($this->config->db_charset) - $this->mysqli->query('SET NAMES '.$this->config->db_charset); - if($this->config->db_sql_mode) - $this->mysqli->query('SET SESSION SQL_MODE = "'.$this->config->db_sql_mode.'"'); - if($this->config->db_timezone) - $this->mysqli->query('SET time_zone = "'.$this->config->db_timezone.'"'); - } - return $this->mysqli; - } - - /** - * Закрываем подключение к базе данных - */ - public function disconnect() - { - if(!@$this->mysqli->close()) - return true; - else - return false; - } - - - /** - * Запрос к базе. Обазятелен первый аргумент - текст запроса. - * При указании других аргументов автоматически выполняется placehold() для запроса с подстановкой этих аргументов - */ - public function query() - { - if(is_object($this->res)) - $this->res->free(); - - $args = func_get_args(); - $q = call_user_func_array(array($this, 'placehold'), $args); - return $this->res = $this->mysqli->query($q); - } - - - /** - * Экранирование - */ - public function escape($str) - { - return $this->mysqli->real_escape_string($str); - } - - - /** - * Плейсхолдер для запросов. Пример работы: $query = $db->placehold('SELECT name FROM products WHERE id=?', $id); - */ - public function placehold() - { - $args = func_get_args(); - $tmpl = array_shift($args); - // Заменяем все __ на префикс, но только необрамленные кавычками - $tmpl = preg_replace('/([^"\'0-9a-z_])__([a-z_]+[^"\'])/i', "\$1".$this->config->db_prefix."\$2", $tmpl); - if(!empty($args)) - { - $result = $this->sql_placeholder_ex($tmpl, $args, $error); - if ($result === false) - { - $error = "Placeholder substitution error. Diagnostics: \"$error\""; - trigger_error($error, E_USER_WARNING); - return false; - } - return $result; - } - else - return $tmpl; - } - - - /** - * Возвращает результаты запроса. Необязательный второй аргумент указывает какую колонку возвращать вместо всего массива колонок - */ - public function results($field = null) - { - $results = array(); - if(!$this->res) - { - trigger_error($this->mysqli->error, E_USER_WARNING); - return false; - } - - if($this->res->num_rows == 0) - return array(); - - while($row = $this->res->fetch_object()) - { - if(!empty($field) && isset($row->$field)) - array_push($results, $row->$field); - else - array_push($results, $row); - } - return $results; - } - - /** - * Возвращает первый результат запроса. Необязательный второй аргумент указывает какую колонку возвращать вместо всего массива колонок - */ - public function result($field = null) - { - $result = array(); - if(!$this->res) - { - $this->error_msg = "Could not execute query to database"; - return 0; - } - $row = $this->res->fetch_object(); - if(!empty($field) && isset($row->$field)) - return $row->$field; - elseif(!empty($field) && !isset($row->$field)) - return false; - else - return $row; - } - - /** - * Возвращает последний вставленный id - */ - public function insert_id() - { - return $this->mysqli->insert_id; - } - - /** - * Возвращает количество выбранных строк - */ - public function num_rows() - { - return $this->res->num_rows; - } - - /** - * Возвращает количество затронутых строк - */ - public function affected_rows() - { - return $this->mysqli->affected_rows; - } - - /** - * Компиляция плейсхолдера - */ - private function sql_compile_placeholder($tmpl) - { - $compiled = array(); - $p = 0; // текущая позиция в строке - $i = 0; // счетчик placeholder-ов - $has_named = false; - while(false !== ($start = $p = strpos($tmpl, "?", $p))) - { - // Определяем тип placeholder-а. - switch ($c = substr($tmpl, ++$p, 1)) - { - case '%': case '@': case '#': - $type = $c; ++$p; break; - default: - $type = ''; break; - } - // Проверяем, именованный ли это placeholder: "?keyname" - if (preg_match('/^((?:[^\s[:punct:]]|_)+)/', substr($tmpl, $p), $pock)) - { - $key = $pock[1]; - if ($type != '#') - $has_named = true; - $p += strlen($key); - } - else - { - $key = $i; - if ($type != '#') - $i++; - } - // Сохранить запись о placeholder-е. - $compiled[] = array($key, $type, $start, $p - $start); - } - return array($compiled, $tmpl, $has_named); - } - - /** - * Выполнение плейсхолдера - */ - private function sql_placeholder_ex($tmpl, $args, &$errormsg) - { - // Запрос уже разобран?.. Если нет, разбираем. - if (is_array($tmpl)) - $compiled = $tmpl; - else - $compiled = $this->sql_compile_placeholder($tmpl); - - list ($compiled, $tmpl, $has_named) = $compiled; - - // Если есть хотя бы один именованный placeholder, используем - // первый аргумент в качестве ассоциативного массива. - if ($has_named) - $args = @$args[0]; - - // Выполняем все замены в цикле. - $p = 0; // текущее положение в строке - $out = ''; // результирующая строка - $error = false; // были ошибки? - - foreach ($compiled as $num=>$e) - { - list ($key, $type, $start, $length) = $e; - - // Pre-string. - $out .= substr($tmpl, $p, $start - $p); - $p = $start + $length; - - $repl = ''; // текст для замены текущего placeholder-а - $errmsg = ''; // сообщение об ошибке для этого placeholder-а - do { - // Это placeholder-константа? - if ($type === '#') - { - $repl = @constant($key); - if (NULL === $repl) - $error = $errmsg = "UNKNOWN_CONSTANT_$key"; - break; - } - // Обрабатываем ошибку. - if (!isset($args[$key])) - { - $error = $errmsg = "UNKNOWN_PLACEHOLDER_$key"; - break; - } - // Вставляем значение в соответствии с типом placeholder-а. - $a = $args[$key]; - if ($type === '') - { - // Скалярный placeholder. - if (is_array($a)) - { - $error = $errmsg = "NOT_A_SCALAR_PLACEHOLDER_$key"; - break; - } - $repl = is_int($a) || is_float($a) ? str_replace(',', '.', $a) : "'".addslashes($a)."'"; - break; - } - // Иначе это массив или список. - if(is_object($a)) - $a = get_object_vars($a); - - if (!is_array($a)) - { - $error = $errmsg = "NOT_AN_ARRAY_PLACEHOLDER_$key"; - break; - } - if ($type === '@') - { - // Это список. - foreach ($a as $v) - { - if(is_null($v)) - $r = "NULL"; - else - $r = "'".@addslashes($v)."'"; - - $repl .= ($repl===''? "" : ",").$r; - } - } - elseif ($type === '%') - { - // Это набор пар ключ=>значение. - $lerror = array(); - foreach ($a as $k=>$v) - { - if (!is_string($k)) - $lerror[$k] = "NOT_A_STRING_KEY_{$k}_FOR_PLACEHOLDER_$key"; - else - $k = preg_replace('/[^a-zA-Z0-9_]/', '_', $k); - - if(is_null($v)) - $r = "=NULL"; - else - $r = "='".@addslashes($v)."'"; - - $repl .= ($repl===''? "" : ", ").$k.$r; - } - // Если была ошибка, составляем сообщение. - if (count($lerror)) - { - $repl = ''; - foreach ($a as $k=>$v) - { - if (isset($lerror[$k])) - { - $repl .= ($repl===''? "" : ", ").$lerror[$k]; - } - else - { - $k = preg_replace('/[^a-zA-Z0-9_-]/', '_', $k); - $repl .= ($repl===''? "" : ", ").$k."=?"; - } - } - $error = $errmsg = $repl; - } - } - } while (false); - if ($errmsg) $compiled[$num]['error'] = $errmsg; - if (!$error) $out .= $repl; - } - $out .= substr($tmpl, $p); - - // Если возникла ошибка, переделываем результирующую строку - // в сообщение об ошибке (расставляем диагностические строки - // вместо ошибочных placeholder-ов). - if ($error) - { - $out = ''; - $p = 0; // текущая позиция - foreach ($compiled as $num=>$e) - { - list ($key, $type, $start, $length) = $e; - $out .= substr($tmpl, $p, $start - $p); - $p = $start + $length; - if (isset($e['error'])) - { - $out .= $e['error']; - } - else - { - $out .= substr($tmpl, $start, $length); - } - } - // Последняя часть строки. - $out .= substr($tmpl, $p); - $errormsg = $out; - return false; - } - else - { - $errormsg = false; - return $out; - } - } - - public function dump($filename) - { - $h = fopen($filename, 'w'); - $q = $this->placehold("SHOW FULL TABLES LIKE '__%';"); - $result = $this->mysqli->query($q); - while($row = $result->fetch_row()) - { - if($row[1] == 'BASE TABLE') - $this->dump_table($row[0], $h); - } - fclose($h); - } - - public function restore($filename) - { - $templine = ''; - $h = fopen($filename, 'r'); - - // Loop through each line - if($h) - { - while(!feof($h)) - { - $line = fgets($h); - // Only continue if it's not a comment - if (substr($line, 0, 2) != '--' && $line != '') - { - // Add this line to the current segment - $templine .= $line; - // If it has a semicolon at the end, it's the end of the query - if (substr(trim($line), -1, 1) == ';') - { - // Perform the query - $this->query($templine) or print('Error performing query \''.$templine.'\': '.$this->mysqli->error.'

'); - // Reset temp variable to empty - $templine = ''; - } - } - } - } - fclose($h); - } - - - private function dump_table($table, $h) - { - $sql = "SELECT * FROM `$table`;"; - $result = $this->mysqli->query($sql); - if($result) - { - $table_no_prefix = preg_replace('/^('.$this->config->db_prefix.')/i', "__", $table); - fwrite($h, "/* Data for table $table_no_prefix */\n"); - fwrite($h, "TRUNCATE TABLE `$table_no_prefix`;\n"); - - $num_rows = $result->num_rows; - $num_fields = $this->mysqli->field_count; - - if($num_rows > 0) - { - $field_type=array(); - $field_name = array(); - $meta = $result->fetch_fields(); - foreach($meta as $m) - { - array_push($field_type, $m->type); - array_push($field_name, $m->name); - } - $fields = implode('`, `', $field_name); - fwrite($h, "INSERT INTO `$table_no_prefix` (`$fields`) VALUES\n"); - $index=0; - while( $row = $result->fetch_row()) - { - fwrite($h, "("); - for( $i=0; $i < $num_fields; $i++) - { - if( is_null( $row[$i])) - fwrite($h, "null"); - else - { - switch( $field_type[$i]) - { - case 'int': - fwrite($h, $row[$i]); - break; - case 'string': - case 'blob' : - default: - fwrite($h, "'". $this->mysqli->real_escape_string($row[$i])."'"); - - } - } - if( $i < $num_fields-1) - fwrite($h, ","); - } - fwrite($h, ")"); - - if( $index < $num_rows-1) - fwrite($h, ","); - else - fwrite($h, ";"); - fwrite($h, "\n"); - - $index++; - } - } - $result->free(); - } - fwrite($h, "\n"); - } -} - +connect(); + } + + /** + * В деструкторе отсоединяемся от базы + */ + public function __destruct() + { + $this->disconnect(); + } + + /** + * Подключение к базе данных + */ + public function connect() + { + // При повторном вызове возвращаем существующий линк + if(!empty($this->mysqli)) + return $this->mysqli; + // Иначе устанавливаем соединение + else + $this->mysqli = new mysqli($this->config->db_server, $this->config->db_user, $this->config->db_password, $this->config->db_name); + + // Выводим сообщение, в случае ошибки + if($this->mysqli->connect_error) + { + trigger_error("Could not connect to the database: ".$this->mysqli->connect_error, E_USER_WARNING); + return false; + } + // Или настраиваем соединение + else + { + if($this->config->db_charset) + $this->mysqli->query('SET NAMES '.$this->config->db_charset); + if($this->config->db_sql_mode) + $this->mysqli->query('SET SESSION SQL_MODE = "'.$this->config->db_sql_mode.'"'); + if($this->config->db_timezone) + $this->mysqli->query('SET time_zone = "'.$this->config->db_timezone.'"'); + } + return $this->mysqli; + } + + /** + * Закрываем подключение к базе данных + */ + public function disconnect() + { + if(!@$this->mysqli->close()) + return true; + else + return false; + } + + + /** + * Запрос к базе. Обазятелен первый аргумент - текст запроса. + * При указании других аргументов автоматически выполняется placehold() для запроса с подстановкой этих аргументов + */ + public function query() + { + if(is_object($this->res)) + $this->res->free(); + + $args = func_get_args(); + $q = call_user_func_array(array($this, 'placehold'), $args); + return $this->res = $this->mysqli->query($q); + } + + + /** + * Экранирование + */ + public function escape($str) + { + return $this->mysqli->real_escape_string($str); + } + + + /** + * Плейсхолдер для запросов. Пример работы: $query = $db->placehold('SELECT name FROM products WHERE id=?', $id); + */ + public function placehold() + { + $args = func_get_args(); + $tmpl = array_shift($args); + // Заменяем все __ на префикс, но только необрамленные кавычками + $tmpl = preg_replace('/([^"\'0-9a-z_])__([a-z_]+[^"\'])/i', "\$1".$this->config->db_prefix."\$2", $tmpl); + if(!empty($args)) + { + $result = $this->sql_placeholder_ex($tmpl, $args, $error); + if ($result === false) + { + $error = "Placeholder substitution error. Diagnostics: \"$error\""; + trigger_error($error, E_USER_WARNING); + return false; + } + return $result; + } + else + return $tmpl; + } + + + /** + * Возвращает результаты запроса. Необязательный второй аргумент указывает какую колонку возвращать вместо всего массива колонок + */ + public function results($field = null) + { + $results = array(); + if(!$this->res) + { + trigger_error($this->mysqli->error, E_USER_WARNING); + return false; + } + + if($this->res->num_rows == 0) + return array(); + + while($row = $this->res->fetch_object()) + { + if(!empty($field) && isset($row->$field)) + array_push($results, $row->$field); + else + array_push($results, $row); + } + return $results; + } + + /** + * Возвращает первый результат запроса. Необязательный второй аргумент указывает какую колонку возвращать вместо всего массива колонок + */ + public function result($field = null) + { + $result = array(); + if(!$this->res) + { + $this->error_msg = "Could not execute query to database"; + return 0; + } + $row = $this->res->fetch_object(); + if(!empty($field) && isset($row->$field)) + return $row->$field; + elseif(!empty($field) && !isset($row->$field)) + return false; + else + return $row; + } + + /** + * Возвращает последний вставленный id + */ + public function insert_id() + { + return $this->mysqli->insert_id; + } + + /** + * Возвращает количество выбранных строк + */ + public function num_rows() + { + return $this->res->num_rows; + } + + /** + * Возвращает количество затронутых строк + */ + public function affected_rows() + { + return $this->mysqli->affected_rows; + } + + /** + * Компиляция плейсхолдера + */ + private function sql_compile_placeholder($tmpl) + { + $compiled = array(); + $p = 0; // текущая позиция в строке + $i = 0; // счетчик placeholder-ов + $has_named = false; + while(false !== ($start = $p = strpos($tmpl, "?", $p))) + { + // Определяем тип placeholder-а. + switch ($c = substr($tmpl, ++$p, 1)) + { + case '%': case '@': case '#': + $type = $c; ++$p; break; + default: + $type = ''; break; + } + // Проверяем, именованный ли это placeholder: "?keyname" + if (preg_match('/^((?:[^\s[:punct:]]|_)+)/', substr($tmpl, $p), $pock)) + { + $key = $pock[1]; + if ($type != '#') + $has_named = true; + $p += strlen($key); + } + else + { + $key = $i; + if ($type != '#') + $i++; + } + // Сохранить запись о placeholder-е. + $compiled[] = array($key, $type, $start, $p - $start); + } + return array($compiled, $tmpl, $has_named); + } + + /** + * Выполнение плейсхолдера + */ + private function sql_placeholder_ex($tmpl, $args, &$errormsg) + { + // Запрос уже разобран?.. Если нет, разбираем. + if (is_array($tmpl)) + $compiled = $tmpl; + else + $compiled = $this->sql_compile_placeholder($tmpl); + + list ($compiled, $tmpl, $has_named) = $compiled; + + // Если есть хотя бы один именованный placeholder, используем + // первый аргумент в качестве ассоциативного массива. + if ($has_named) + $args = @$args[0]; + + // Выполняем все замены в цикле. + $p = 0; // текущее положение в строке + $out = ''; // результирующая строка + $error = false; // были ошибки? + + foreach ($compiled as $num=>$e) + { + list ($key, $type, $start, $length) = $e; + + // Pre-string. + $out .= substr($tmpl, $p, $start - $p); + $p = $start + $length; + + $repl = ''; // текст для замены текущего placeholder-а + $errmsg = ''; // сообщение об ошибке для этого placeholder-а + do { + // Это placeholder-константа? + if ($type === '#') + { + $repl = @constant($key); + if (NULL === $repl) + $error = $errmsg = "UNKNOWN_CONSTANT_$key"; + break; + } + // Обрабатываем ошибку. + if (!isset($args[$key])) + { + $error = $errmsg = "UNKNOWN_PLACEHOLDER_$key"; + break; + } + // Вставляем значение в соответствии с типом placeholder-а. + $a = $args[$key]; + if ($type === '') + { + // Скалярный placeholder. + if (is_array($a)) + { + $error = $errmsg = "NOT_A_SCALAR_PLACEHOLDER_$key"; + break; + } + $repl = is_int($a) || is_float($a) ? str_replace(',', '.', $a) : "'".addslashes($a)."'"; + break; + } + // Иначе это массив или список. + if(is_object($a)) + $a = get_object_vars($a); + + if (!is_array($a)) + { + $error = $errmsg = "NOT_AN_ARRAY_PLACEHOLDER_$key"; + break; + } + if ($type === '@') + { + // Это список. + foreach ($a as $v) + { + if(is_null($v)) + $r = "NULL"; + else + $r = "'".@addslashes($v)."'"; + + $repl .= ($repl===''? "" : ",").$r; + } + } + elseif ($type === '%') + { + // Это набор пар ключ=>значение. + $lerror = array(); + foreach ($a as $k=>$v) + { + if (!is_string($k)) + $lerror[$k] = "NOT_A_STRING_KEY_{$k}_FOR_PLACEHOLDER_$key"; + else + $k = preg_replace('/[^a-zA-Z0-9_]/', '_', $k); + + if(is_null($v)) + $r = "=NULL"; + else + $r = "='".@addslashes($v)."'"; + + $repl .= ($repl===''? "" : ", ").$k.$r; + } + // Если была ошибка, составляем сообщение. + if (count($lerror)) + { + $repl = ''; + foreach ($a as $k=>$v) + { + if (isset($lerror[$k])) + { + $repl .= ($repl===''? "" : ", ").$lerror[$k]; + } + else + { + $k = preg_replace('/[^a-zA-Z0-9_-]/', '_', $k); + $repl .= ($repl===''? "" : ", ").$k."=?"; + } + } + $error = $errmsg = $repl; + } + } + } while (false); + if ($errmsg) $compiled[$num]['error'] = $errmsg; + if (!$error) $out .= $repl; + } + $out .= substr($tmpl, $p); + + // Если возникла ошибка, переделываем результирующую строку + // в сообщение об ошибке (расставляем диагностические строки + // вместо ошибочных placeholder-ов). + if ($error) + { + $out = ''; + $p = 0; // текущая позиция + foreach ($compiled as $num=>$e) + { + list ($key, $type, $start, $length) = $e; + $out .= substr($tmpl, $p, $start - $p); + $p = $start + $length; + if (isset($e['error'])) + { + $out .= $e['error']; + } + else + { + $out .= substr($tmpl, $start, $length); + } + } + // Последняя часть строки. + $out .= substr($tmpl, $p); + $errormsg = $out; + return false; + } + else + { + $errormsg = false; + return $out; + } + } + + public function dump($filename) + { + $h = fopen($filename, 'w'); + $q = $this->placehold("SHOW FULL TABLES LIKE '__%';"); + $result = $this->mysqli->query($q); + while($row = $result->fetch_row()) + { + if($row[1] == 'BASE TABLE') + $this->dump_table($row[0], $h); + } + fclose($h); + } + + public function restore($filename) + { + $templine = ''; + $h = fopen($filename, 'r'); + + // Loop through each line + if($h) + { + while(!feof($h)) + { + $line = fgets($h); + // Only continue if it's not a comment + if (substr($line, 0, 2) != '--' && $line != '') + { + // Add this line to the current segment + $templine .= $line; + // If it has a semicolon at the end, it's the end of the query + if (substr(trim($line), -1, 1) == ';') + { + // Perform the query + $this->query($templine) or print('Error performing query \''.$templine.'\': '.$this->mysqli->error.'

'); + // Reset temp variable to empty + $templine = ''; + } + } + } + } + fclose($h); + } + + + private function dump_table($table, $h) + { + $sql = "SELECT * FROM `$table`;"; + $result = $this->mysqli->query($sql); + if($result) + { + $table_no_prefix = preg_replace('/^('.$this->config->db_prefix.')/i', "__", $table); + fwrite($h, "/* Data for table $table_no_prefix */\n"); + fwrite($h, "TRUNCATE TABLE `$table_no_prefix`;\n"); + + $num_rows = $result->num_rows; + $num_fields = $this->mysqli->field_count; + + if($num_rows > 0) + { + $field_type=array(); + $field_name = array(); + $meta = $result->fetch_fields(); + foreach($meta as $m) + { + array_push($field_type, $m->type); + array_push($field_name, $m->name); + } + $fields = implode('`, `', $field_name); + fwrite($h, "INSERT INTO `$table_no_prefix` (`$fields`) VALUES\n"); + $index=0; + while( $row = $result->fetch_row()) + { + fwrite($h, "("); + for( $i=0; $i < $num_fields; $i++) + { + if( is_null( $row[$i])) + fwrite($h, "null"); + else + { + switch( $field_type[$i]) + { + case 'int': + fwrite($h, $row[$i]); + break; + case 'string': + case 'blob' : + default: + fwrite($h, "'". $this->mysqli->real_escape_string($row[$i])."'"); + + } + } + if( $i < $num_fields-1) + fwrite($h, ","); + } + fwrite($h, ")"); + + if( $index < $num_rows-1) + fwrite($h, ","); + else + fwrite($h, ";"); + fwrite($h, "\n"); + + $index++; + } + } + $result->free(); + } + fwrite($h, "\n"); + } +} + diff --git a/api/Delivery.php b/api/Delivery.php index 0372b76..ebb2973 100755 --- a/api/Delivery.php +++ b/api/Delivery.php @@ -1,93 +1,93 @@ -db->placehold("SELECT id, name, description, free_from, price, enabled, position, separate_payment FROM __delivery WHERE id=? LIMIT 1", intval($id)); - - $this->db->query($query); - return $this->db->result(); - } - - public function get_deliveries($filter = array()) - { - // По умолчанию - $enabled_filter = ''; - - if(!empty($filter['enabled'])) - $enabled_filter = $this->db->placehold('AND enabled=?', intval($filter['enabled'])); - - $query = "SELECT id, name, description, free_from, price, enabled, position, separate_payment - FROM __delivery WHERE 1 $enabled_filter ORDER BY position"; - - $this->db->query($query); - - return $this->db->results(); - } - - public function update_delivery($id, $delivery) - { - $query = $this->db->placehold("UPDATE __delivery SET ?% WHERE id in(?@)", $delivery, (array)$id); - $this->db->query($query); - return $id; - } - - public function add_delivery($delivery) - { - $query = $this->db->placehold('INSERT INTO __delivery - SET ?%', - $delivery); - - if(!$this->db->query($query)) - return false; - - $id = $this->db->insert_id(); - $this->db->query("UPDATE __delivery SET position=id WHERE id=?", intval($id)); - return $id; - } - - public function delete_delivery($id) - { - // Удаляем связь доставки с методоми оплаты - $query = $this->db->placehold("SELECT payment_method_id FROM __delivery_payment WHERE delivery_id=?", intval($id)); - $this->db->query($query); - - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __delivery WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - } - } - - - public function get_delivery_payments($id) - { - $query = $this->db->placehold("SELECT payment_method_id FROM __delivery_payment WHERE delivery_id=?", intval($id)); - $this->db->query($query); - return $this->db->results('payment_method_id'); - } - - public function update_delivery_payments($id, $payment_methods_ids) - { - $query = $this->db->placehold("DELETE FROM __delivery_payment WHERE delivery_id=?", intval($id)); - $this->db->query($query); - if(is_array($payment_methods_ids)) - foreach($payment_methods_ids as $p_id) - $this->db->query("INSERT INTO __delivery_payment SET delivery_id=?, payment_method_id=?", $id, $p_id); - } - -} +db->placehold("SELECT id, name, description, free_from, price, enabled, position, separate_payment FROM __delivery WHERE id=? LIMIT 1", intval($id)); + + $this->db->query($query); + return $this->db->result(); + } + + public function get_deliveries($filter = array()) + { + // По умолчанию + $enabled_filter = ''; + + if(!empty($filter['enabled'])) + $enabled_filter = $this->db->placehold('AND enabled=?', intval($filter['enabled'])); + + $query = "SELECT id, name, description, free_from, price, enabled, position, separate_payment + FROM __delivery WHERE 1 $enabled_filter ORDER BY position"; + + $this->db->query($query); + + return $this->db->results(); + } + + public function update_delivery($id, $delivery) + { + $query = $this->db->placehold("UPDATE __delivery SET ?% WHERE id in(?@)", $delivery, (array)$id); + $this->db->query($query); + return $id; + } + + public function add_delivery($delivery) + { + $query = $this->db->placehold('INSERT INTO __delivery + SET ?%', + $delivery); + + if(!$this->db->query($query)) + return false; + + $id = $this->db->insert_id(); + $this->db->query("UPDATE __delivery SET position=id WHERE id=?", intval($id)); + return $id; + } + + public function delete_delivery($id) + { + // Удаляем связь доставки с методоми оплаты + $query = $this->db->placehold("SELECT payment_method_id FROM __delivery_payment WHERE delivery_id=?", intval($id)); + $this->db->query($query); + + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __delivery WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + } + } + + + public function get_delivery_payments($id) + { + $query = $this->db->placehold("SELECT payment_method_id FROM __delivery_payment WHERE delivery_id=?", intval($id)); + $this->db->query($query); + return $this->db->results('payment_method_id'); + } + + public function update_delivery_payments($id, $payment_methods_ids) + { + $query = $this->db->placehold("DELETE FROM __delivery_payment WHERE delivery_id=?", intval($id)); + $this->db->query($query); + if(is_array($payment_methods_ids)) + foreach($payment_methods_ids as $p_id) + $this->db->query("INSERT INTO __delivery_payment SET delivery_id=?, payment_method_id=?", $id, $p_id); + } + +} diff --git a/api/Design.php b/api/Design.php index 4cd5899..b991a42 100755 --- a/api/Design.php +++ b/api/Design.php @@ -1,305 +1,305 @@ -smarty = new Smarty(); - $this->smarty->compile_check = $this->config->smarty_compile_check; - $this->smarty->caching = $this->config->smarty_caching; - $this->smarty->cache_lifetime = $this->config->smarty_cache_lifetime; - $this->smarty->debugging = $this->config->smarty_debugging; - $this->smarty->error_reporting = E_ALL & ~E_NOTICE; - - // Берем тему из настроек - $theme = $this->settings->theme; - - - $this->smarty->compile_dir = $this->config->root_dir.'/compiled/'.$theme; - $this->smarty->template_dir = $this->config->root_dir.'/design/'.$theme.'/html'; - - if(!is_dir($this->config->root_dir.'/compiled')) - mkdir($this->config->root_dir.'/compiled', 0777); - - // Создаем папку для скомпилированных шаблонов текущей темы - if(!is_dir($this->smarty->compile_dir)) - mkdir($this->smarty->compile_dir, 0777); - - $this->smarty->cache_dir = 'cache'; - - $this->smarty->registerPlugin('modifier', 'resize', array($this, 'resize_modifier')); - $this->smarty->registerPlugin('modifier', 'token', array($this, 'token_modifier')); - $this->smarty->registerPlugin('modifier', 'plural', array($this, 'plural_modifier')); - $this->smarty->registerPlugin('function', 'url', array($this, 'url_modifier')); - $this->smarty->registerPlugin('modifier', 'first', array($this, 'first_modifier')); - $this->smarty->registerPlugin('modifier', 'cut', array($this, 'cut_modifier')); - $this->smarty->registerPlugin('modifier', 'date', array($this, 'date_modifier')); - $this->smarty->registerPlugin('modifier', 'time', array($this, 'time_modifier')); - $this->smarty->registerPlugin('function', 'api', array($this, 'api_plugin')); - - if($this->config->smarty_html_minify) - $this->smarty->loadFilter('output', 'trimwhitespace'); - } - - public function assign($var, $value) - { - return $this->smarty->assign($var, $value); - } - - public function fetch($template) - { - // Передаем в дизайн то, что может понадобиться в нем - $this->assign('config', $this->config); - $this->assign('settings', $this->settings); - return $this->smarty->fetch($template); - } - - public function set_templates_dir($dir) - { - $this->smarty->template_dir = $dir; - } - - public function set_compiled_dir($dir) - { - $this->smarty->compile_dir = $dir; - } - - public function get_var($name) - { - return $this->smarty->getTemplateVars($name); - } - - public function clear_cache() - { - $this->smarty->clearAllCache(); - } - - private function is_mobile_browser() - { - $user_agent = $_SERVER['HTTP_USER_AGENT']; - $http_accept = isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:''; - - if(eregi('iPad', $user_agent)) - return false; - - if(stristr($user_agent, 'windows') && !stristr($user_agent, 'windows ce')) - return false; - - if(eregi('windows ce|iemobile|mobile|symbian|mini|wap|pda|psp|up.browser|up.link|mmp|midp|phone|pocket', $user_agent)) - return true; - - if(stristr($http_accept, 'text/vnd.wap.wml') || stristr($http_accept, 'application/vnd.wap.xhtml+xml')) - return true; - - if(!empty($_SERVER['HTTP_X_WAP_PROFILE']) || !empty($_SERVER['HTTP_PROFILE']) || !empty($_SERVER['X-OperaMini-Features']) || !empty($_SERVER['UA-pixels'])) - return true; - - $agents = array( - 'acs-'=>'acs-', - 'alav'=>'alav', - 'alca'=>'alca', - 'amoi'=>'amoi', - 'audi'=>'audi', - 'aste'=>'aste', - 'avan'=>'avan', - 'benq'=>'benq', - 'bird'=>'bird', - 'blac'=>'blac', - 'blaz'=>'blaz', - 'brew'=>'brew', - 'cell'=>'cell', - 'cldc'=>'cldc', - 'cmd-'=>'cmd-', - 'dang'=>'dang', - 'doco'=>'doco', - 'eric'=>'eric', - 'hipt'=>'hipt', - 'inno'=>'inno', - 'ipaq'=>'ipaq', - 'java'=>'java', - 'jigs'=>'jigs', - 'kddi'=>'kddi', - 'keji'=>'keji', - 'leno'=>'leno', - 'lg-c'=>'lg-c', - 'lg-d'=>'lg-d', - 'lg-g'=>'lg-g', - 'lge-'=>'lge-', - 'maui'=>'maui', - 'maxo'=>'maxo', - 'midp'=>'midp', - 'mits'=>'mits', - 'mmef'=>'mmef', - 'mobi'=>'mobi', - 'mot-'=>'mot-', - 'moto'=>'moto', - 'mwbp'=>'mwbp', - 'nec-'=>'nec-', - 'newt'=>'newt', - 'noki'=>'noki', - 'opwv'=>'opwv', - 'palm'=>'palm', - 'pana'=>'pana', - 'pant'=>'pant', - 'pdxg'=>'pdxg', - 'phil'=>'phil', - 'play'=>'play', - 'pluc'=>'pluc', - 'port'=>'port', - 'prox'=>'prox', - 'qtek'=>'qtek', - 'qwap'=>'qwap', - 'sage'=>'sage', - 'sams'=>'sams', - 'sany'=>'sany', - 'sch-'=>'sch-', - 'sec-'=>'sec-', - 'send'=>'send', - 'seri'=>'seri', - 'sgh-'=>'sgh-', - 'shar'=>'shar', - 'sie-'=>'sie-', - 'siem'=>'siem', - 'smal'=>'smal', - 'smar'=>'smar', - 'sony'=>'sony', - 'sph-'=>'sph-', - 'symb'=>'symb', - 't-mo'=>'t-mo', - 'teli'=>'teli', - 'tim-'=>'tim-', - 'tosh'=>'tosh', - 'treo'=>'treo', - 'tsm-'=>'tsm-', - 'upg1'=>'upg1', - 'upsi'=>'upsi', - 'vk-v'=>'vk-v', - 'voda'=>'voda', - 'wap-'=>'wap-', - 'wapa'=>'wapa', - 'wapi'=>'wapi', - 'wapp'=>'wapp', - 'wapr'=>'wapr', - 'webc'=>'webc', - 'winw'=>'winw', - 'winw'=>'winw', - 'xda-'=>'xda-' - ); - - if(!empty($agents[substr($_SERVER['HTTP_USER_AGENT'], 0, 4)])) - return true; - } - - - public function resize_modifier($filename, $width=0, $height=0, $set_watermark=false) - { - $resized_filename = $this->image->add_resize_params($filename, $width, $height, $set_watermark); - $resized_filename_encoded = $resized_filename; - - if(substr($resized_filename_encoded, 0, 7) == 'http://') - $resized_filename_encoded = rawurlencode($resized_filename_encoded); - - $resized_filename_encoded = rawurlencode($resized_filename_encoded); - - return $this->config->root_url.'/'.$this->config->resized_images_dir.$resized_filename_encoded.'?'.$this->config->token($resized_filename); - } - - public function token_modifier($text) - { - return $this->config->token($text); - } - - public function url_modifier($params) - { - if(is_array(reset($params))) - return $this->request->url(reset($params)); - else - return $this->request->url($params); - } - - public function plural_modifier($number, $singular, $plural1, $plural2=null) - { - $number = abs($number); - if(!empty($plural2)) - { - $p1 = $number%10; - $p2 = $number%100; - if($number == 0) - return $plural1; - if($p1==1 && !($p2>=11 && $p2<=19)) - return $singular; - elseif($p1>=2 && $p1<=4 && !($p2>=11 && $p2<=19)) - return $plural2; - else - return $plural1; - }else - { - if($number == 1) - return $singular; - else - return $plural1; - } - - } - - public function first_modifier($params = array()) - { - if(!is_array($params)) - return false; - return reset($params); - } - - public function cut_modifier($array, $num=1) - { - if($num>=0) - return array_slice($array, $num, count($array)-$num, true); - else - return array_slice($array, 0, count($array)+$num, true); - } - - public function date_modifier($date, $format = null) - { - if(empty($date)) - $date = date("Y-m-d"); - return date(empty($format)?$this->settings->date_format:$format, strtotime($date)); - } - - public function time_modifier($date, $format = null) - { - return date(empty($format)?'H:i':$format, strtotime($date)); - } - - public function api_plugin($params, &$smarty) - { - if(!isset($params['module'])) - return false; - if(!isset($params['method'])) - return false; - - $module = $params['module']; - $method = $params['method']; - $var = $params['var']; - unset($params['module']); - unset($params['method']); - unset($params['var']); - $res = $this->$module->$method($params); - $smarty->assign($var, $res); - } -} +smarty = new Smarty(); + $this->smarty->compile_check = $this->config->smarty_compile_check; + $this->smarty->caching = $this->config->smarty_caching; + $this->smarty->cache_lifetime = $this->config->smarty_cache_lifetime; + $this->smarty->debugging = $this->config->smarty_debugging; + $this->smarty->error_reporting = E_ALL & ~E_NOTICE; + + // Берем тему из настроек + $theme = $this->settings->theme; + + + $this->smarty->compile_dir = $this->config->root_dir.'/compiled/'.$theme; + $this->smarty->template_dir = $this->config->root_dir.'/design/'.$theme.'/html'; + + if(!is_dir($this->config->root_dir.'/compiled')) + mkdir($this->config->root_dir.'/compiled', 0777); + + // Создаем папку для скомпилированных шаблонов текущей темы + if(!is_dir($this->smarty->compile_dir)) + mkdir($this->smarty->compile_dir, 0777); + + $this->smarty->cache_dir = 'cache'; + + $this->smarty->registerPlugin('modifier', 'resize', array($this, 'resize_modifier')); + $this->smarty->registerPlugin('modifier', 'token', array($this, 'token_modifier')); + $this->smarty->registerPlugin('modifier', 'plural', array($this, 'plural_modifier')); + $this->smarty->registerPlugin('function', 'url', array($this, 'url_modifier')); + $this->smarty->registerPlugin('modifier', 'first', array($this, 'first_modifier')); + $this->smarty->registerPlugin('modifier', 'cut', array($this, 'cut_modifier')); + $this->smarty->registerPlugin('modifier', 'date', array($this, 'date_modifier')); + $this->smarty->registerPlugin('modifier', 'time', array($this, 'time_modifier')); + $this->smarty->registerPlugin('function', 'api', array($this, 'api_plugin')); + + if($this->config->smarty_html_minify) + $this->smarty->loadFilter('output', 'trimwhitespace'); + } + + public function assign($var, $value) + { + return $this->smarty->assign($var, $value); + } + + public function fetch($template) + { + // Передаем в дизайн то, что может понадобиться в нем + $this->assign('config', $this->config); + $this->assign('settings', $this->settings); + return $this->smarty->fetch($template); + } + + public function set_templates_dir($dir) + { + $this->smarty->template_dir = $dir; + } + + public function set_compiled_dir($dir) + { + $this->smarty->compile_dir = $dir; + } + + public function get_var($name) + { + return $this->smarty->getTemplateVars($name); + } + + public function clear_cache() + { + $this->smarty->clearAllCache(); + } + + private function is_mobile_browser() + { + $user_agent = $_SERVER['HTTP_USER_AGENT']; + $http_accept = isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:''; + + if(eregi('iPad', $user_agent)) + return false; + + if(stristr($user_agent, 'windows') && !stristr($user_agent, 'windows ce')) + return false; + + if(eregi('windows ce|iemobile|mobile|symbian|mini|wap|pda|psp|up.browser|up.link|mmp|midp|phone|pocket', $user_agent)) + return true; + + if(stristr($http_accept, 'text/vnd.wap.wml') || stristr($http_accept, 'application/vnd.wap.xhtml+xml')) + return true; + + if(!empty($_SERVER['HTTP_X_WAP_PROFILE']) || !empty($_SERVER['HTTP_PROFILE']) || !empty($_SERVER['X-OperaMini-Features']) || !empty($_SERVER['UA-pixels'])) + return true; + + $agents = array( + 'acs-'=>'acs-', + 'alav'=>'alav', + 'alca'=>'alca', + 'amoi'=>'amoi', + 'audi'=>'audi', + 'aste'=>'aste', + 'avan'=>'avan', + 'benq'=>'benq', + 'bird'=>'bird', + 'blac'=>'blac', + 'blaz'=>'blaz', + 'brew'=>'brew', + 'cell'=>'cell', + 'cldc'=>'cldc', + 'cmd-'=>'cmd-', + 'dang'=>'dang', + 'doco'=>'doco', + 'eric'=>'eric', + 'hipt'=>'hipt', + 'inno'=>'inno', + 'ipaq'=>'ipaq', + 'java'=>'java', + 'jigs'=>'jigs', + 'kddi'=>'kddi', + 'keji'=>'keji', + 'leno'=>'leno', + 'lg-c'=>'lg-c', + 'lg-d'=>'lg-d', + 'lg-g'=>'lg-g', + 'lge-'=>'lge-', + 'maui'=>'maui', + 'maxo'=>'maxo', + 'midp'=>'midp', + 'mits'=>'mits', + 'mmef'=>'mmef', + 'mobi'=>'mobi', + 'mot-'=>'mot-', + 'moto'=>'moto', + 'mwbp'=>'mwbp', + 'nec-'=>'nec-', + 'newt'=>'newt', + 'noki'=>'noki', + 'opwv'=>'opwv', + 'palm'=>'palm', + 'pana'=>'pana', + 'pant'=>'pant', + 'pdxg'=>'pdxg', + 'phil'=>'phil', + 'play'=>'play', + 'pluc'=>'pluc', + 'port'=>'port', + 'prox'=>'prox', + 'qtek'=>'qtek', + 'qwap'=>'qwap', + 'sage'=>'sage', + 'sams'=>'sams', + 'sany'=>'sany', + 'sch-'=>'sch-', + 'sec-'=>'sec-', + 'send'=>'send', + 'seri'=>'seri', + 'sgh-'=>'sgh-', + 'shar'=>'shar', + 'sie-'=>'sie-', + 'siem'=>'siem', + 'smal'=>'smal', + 'smar'=>'smar', + 'sony'=>'sony', + 'sph-'=>'sph-', + 'symb'=>'symb', + 't-mo'=>'t-mo', + 'teli'=>'teli', + 'tim-'=>'tim-', + 'tosh'=>'tosh', + 'treo'=>'treo', + 'tsm-'=>'tsm-', + 'upg1'=>'upg1', + 'upsi'=>'upsi', + 'vk-v'=>'vk-v', + 'voda'=>'voda', + 'wap-'=>'wap-', + 'wapa'=>'wapa', + 'wapi'=>'wapi', + 'wapp'=>'wapp', + 'wapr'=>'wapr', + 'webc'=>'webc', + 'winw'=>'winw', + 'winw'=>'winw', + 'xda-'=>'xda-' + ); + + if(!empty($agents[substr($_SERVER['HTTP_USER_AGENT'], 0, 4)])) + return true; + } + + + public function resize_modifier($filename, $width=0, $height=0, $set_watermark=false) + { + $resized_filename = $this->image->add_resize_params($filename, $width, $height, $set_watermark); + $resized_filename_encoded = $resized_filename; + + if(substr($resized_filename_encoded, 0, 7) == 'http://') + $resized_filename_encoded = rawurlencode($resized_filename_encoded); + + $resized_filename_encoded = rawurlencode($resized_filename_encoded); + + return $this->config->root_url.'/'.$this->config->resized_images_dir.$resized_filename_encoded.'?'.$this->config->token($resized_filename); + } + + public function token_modifier($text) + { + return $this->config->token($text); + } + + public function url_modifier($params) + { + if(is_array(reset($params))) + return $this->request->url(reset($params)); + else + return $this->request->url($params); + } + + public function plural_modifier($number, $singular, $plural1, $plural2=null) + { + $number = abs($number); + if(!empty($plural2)) + { + $p1 = $number%10; + $p2 = $number%100; + if($number == 0) + return $plural1; + if($p1==1 && !($p2>=11 && $p2<=19)) + return $singular; + elseif($p1>=2 && $p1<=4 && !($p2>=11 && $p2<=19)) + return $plural2; + else + return $plural1; + }else + { + if($number == 1) + return $singular; + else + return $plural1; + } + + } + + public function first_modifier($params = array()) + { + if(!is_array($params)) + return false; + return reset($params); + } + + public function cut_modifier($array, $num=1) + { + if($num>=0) + return array_slice($array, $num, count($array)-$num, true); + else + return array_slice($array, 0, count($array)+$num, true); + } + + public function date_modifier($date, $format = null) + { + if(empty($date)) + $date = date("Y-m-d"); + return date(empty($format)?$this->settings->date_format:$format, strtotime($date)); + } + + public function time_modifier($date, $format = null) + { + return date(empty($format)?'H:i':$format, strtotime($date)); + } + + public function api_plugin($params, &$smarty) + { + if(!isset($params['module'])) + return false; + if(!isset($params['method'])) + return false; + + $module = $params['module']; + $method = $params['method']; + $var = $params['var']; + unset($params['module']); + unset($params['method']); + unset($params['var']); + $res = $this->$module->$method($params); + $smarty->assign($var, $res); + } +} diff --git a/api/Features.php b/api/Features.php index 99f1e0d..2b410d1 100755 --- a/api/Features.php +++ b/api/Features.php @@ -3,55 +3,63 @@ /** * Simpla CMS * - * @copyright 2011 Denis Pikusov + * @copyright 2016 Denis Pikusov * @link http://simplacms.ru * @author Denis Pikusov * */ - + require_once('Simpla.php'); class Features extends Simpla -{ - - function get_features($filter = array()) +{ + + public function get_features($filter = array()) { - $category_id_filter = ''; + $category_id_filter = ''; if(isset($filter['category_id'])) $category_id_filter = $this->db->placehold('AND id in(SELECT feature_id FROM __categories_features AS cf WHERE cf.category_id in(?@))', (array)$filter['category_id']); - - $in_filter_filter = ''; + + $in_filter_filter = ''; if(isset($filter['in_filter'])) $in_filter_filter = $this->db->placehold('AND f.in_filter=?', intval($filter['in_filter'])); - - $id_filter = ''; + + $id_filter = ''; if(!empty($filter['id'])) $id_filter = $this->db->placehold('AND f.id in(?@)', (array)$filter['id']); - + // Выбираем свойства - $query = $this->db->placehold("SELECT id, name, position, in_filter FROM __features AS f + $query = $this->db->placehold("SELECT f.id, f.name, f.position, f.in_filter + FROM __features AS f WHERE 1 - $category_id_filter $in_filter_filter $id_filter ORDER BY f.position"); + $category_id_filter + $in_filter_filter + $id_filter + ORDER BY f.position"); $this->db->query($query); return $this->db->results(); } - - function get_feature($id) + + public function get_feature($id) { // Выбираем свойство - $query = $this->db->placehold("SELECT id, name, position, in_filter FROM __features WHERE id=? LIMIT 1", $id); + $query = $this->db->placehold("SELECT f.id, f.name, f.position, f.in_filter + FROM __features AS f + WHERE f.id=? + LIMIT 1", $id); $this->db->query($query); return $this->db->result(); } - - function get_feature_categories($id) + + public function get_feature_categories($id) { - $query = $this->db->placehold("SELECT cf.category_id as category_id FROM __categories_features cf + $query = $this->db->placehold("SELECT cf.category_id as category_id + FROM __categories_features cf WHERE cf.feature_id = ?", $id); $this->db->query($query); - return $this->db->results('category_id'); + return $this->db->results('category_id'); } - + public function add_feature($feature) { $query = $this->db->placehold("INSERT INTO __features SET ?%", $feature); @@ -61,14 +69,14 @@ public function add_feature($feature) $this->db->query($query); return $id; } - + public function update_feature($id, $feature) { $query = $this->db->placehold("UPDATE __features SET ?% WHERE id in(?@) LIMIT ?", (array)$feature, (array)$id, count((array)$id)); $this->db->query($query); return $id; } - + public function delete_feature($id = array()) { if(!empty($id)) @@ -76,12 +84,12 @@ public function delete_feature($id = array()) $query = $this->db->placehold("DELETE FROM __features WHERE id=? LIMIT 1", intval($id)); $this->db->query($query); $query = $this->db->placehold("DELETE FROM __options WHERE feature_id=?", intval($id)); - $this->db->query($query); + $this->db->query($query); $query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", intval($id)); - $this->db->query($query); + $this->db->query($query); } } - + public function delete_option($product_id, $feature_id) { @@ -89,9 +97,9 @@ public function delete_option($product_id, $feature_id) $this->db->query($query); } - + public function update_option($product_id, $feature_id, $value) - { + { if($value != '') $query = $this->db->placehold("REPLACE INTO __options SET value=?, product_id=?, feature_id=?", $value, intval($product_id), intval($feature_id)); else @@ -105,37 +113,40 @@ public function add_feature_category($id, $category_id) $query = $this->db->placehold("INSERT IGNORE INTO __categories_features SET feature_id=?, category_id=?", $id, $category_id); $this->db->query($query); } - + public function update_feature_categories($id, $categories) { $id = intval($id); $query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", $id); $this->db->query($query); - - + + if(is_array($categories)) { $values = array(); foreach($categories as $category) $values[] = "($id , ".intval($category).")"; - + $query = $this->db->placehold("INSERT INTO __categories_features (feature_id, category_id) VALUES ".implode(', ', $values)); $this->db->query($query); - // Удалим значения из options - $query = $this->db->placehold("DELETE o FROM __options o - LEFT JOIN __products_categories pc ON pc.product_id=o.product_id - WHERE o.feature_id=? AND pc.position=(SELECT MIN(pc2.position) FROM __products_categories pc2 WHERE pc.product_id=pc2.product_id) AND pc.category_id not in(?@)", $id, $categories); + // Удалим значения из options + $query = $this->db->placehold("DELETE o + FROM __options o + LEFT JOIN __products_categories pc ON pc.product_id=o.product_id + WHERE o.feature_id=? + AND pc.position=(SELECT MIN(pc2.position) FROM __products_categories pc2 WHERE pc.product_id=pc2.product_id) + AND pc.category_id not in(?@)", $id, $categories); $this->db->query($query); } else { - // Удалим значения из options + // Удалим значения из options $query = $this->db->placehold("DELETE o FROM __options o WHERE o.feature_id=?", $id); $this->db->query($query); } } - + public function get_options($filter = array()) { @@ -148,11 +159,11 @@ public function get_options($filter = array()) if(empty($filter['feature_id']) && empty($filter['product_id'])) return array(); - + $group_by = ''; if(isset($filter['feature_id'])) $group_by = 'GROUP BY feature_id, value'; - + if(isset($filter['feature_id'])) $feature_id_filter = $this->db->placehold('AND po.feature_id in(?@)', (array)$filter['feature_id']); @@ -173,22 +184,31 @@ public function get_options($filter = array()) { $features_filter .= $this->db->placehold('AND (po.feature_id=? OR po.product_id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? )) ', $feature, $feature, $value); } - + $query = $this->db->placehold("SELECT po.product_id, po.feature_id, po.value, count(po.product_id) as count - FROM __options po - $visible_filter - $category_id_filter - WHERE 1 $feature_id_filter $product_id_filter $brand_id_filter $features_filter GROUP BY po.feature_id, po.value ORDER BY value=0, -value DESC, value"); + FROM __options po + $visible_filter + $category_id_filter + WHERE 1 + $feature_id_filter + $product_id_filter + $brand_id_filter + $features_filter + GROUP BY po.feature_id, po.value + ORDER BY value=0, -value DESC, value"); $this->db->query($query); return $this->db->results(); } - + public function get_product_options($product_id) { - $query = $this->db->placehold("SELECT f.id as feature_id, f.name, po.value, po.product_id FROM __options po LEFT JOIN __features f ON f.id=po.feature_id - WHERE po.product_id in(?@) ORDER BY f.position", (array)$product_id); + $query = $this->db->placehold("SELECT f.id as feature_id, f.name, po.value, po.product_id + FROM __options po + LEFT JOIN __features f ON f.id=po.feature_id + WHERE po.product_id in(?@) + ORDER BY f.position", (array)$product_id); $this->db->query($query); return $this->db->results(); diff --git a/api/Feedbacks.php b/api/Feedbacks.php index 8875aeb..a2bcebc 100755 --- a/api/Feedbacks.php +++ b/api/Feedbacks.php @@ -1,119 +1,120 @@ -db->placehold("SELECT f.id, f.name, f.email, f.ip, f.message, f.date FROM __feedbacks f WHERE id=? LIMIT 1", intval($id)); - - if($this->db->query($query)) - return $this->db->result(); - else - return false; - } - - public function get_feedbacks($filter = array(), $new_on_top = false) - { - // По умолчанию - $limit = 0; - $page = 1; - $keyword_filter = ''; - - if(isset($filter['limit'])) - $limit = max(1, intval($filter['limit'])); - - if(isset($filter['page'])) - $page = max(1, intval($filter['page'])); - - $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); - - if(!empty($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND f.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.message LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.email LIKE "%'.$this->db->escape(trim($keyword)).'%" '); - } - - if($new_on_top) - $sort='DESC'; - else - $sort='ASC'; - - $query = $this->db->placehold("SELECT f.id, f.name, f.email, f.ip, f.message, f.date - FROM __feedbacks f WHERE 1 $keyword_filter ORDER BY f.id $sort $sql_limit"); - - $this->db->query($query); - return $this->db->results(); - } - - public function count_feedbacks($filter = array()) - { - $keyword_filter = ''; - - if(!empty($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND f.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.message LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.email LIKE "%'.$this->db->escape(trim($keyword)).'%" '); - } - - $query = $this->db->placehold("SELECT count(distinct f.id) as count - FROM __feedbacks f WHERE 1 $keyword_filter"); - - $this->db->query($query); - return $this->db->result('count'); - - } - - - public function add_feedback($feedback) - { - $query = $this->db->placehold('INSERT INTO __feedbacks - SET ?%, - date = NOW()', - $feedback); - - if(!$this->db->query($query)) - return false; - - $id = $this->db->insert_id(); - return $id; - } - - - public function update_feedback($id, $feedback) - { - $date_query = ''; - if(isset($feedback->date)) - { - $date = $feedback->date; - unset($feedback->date); - $date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format); - } - $query = $this->db->placehold("UPDATE __feedbacks SET ?% $date_query WHERE id in(?@) LIMIT 1", $feedback, (array)$id); - $this->db->query($query); - return $id; - } - - - public function delete_feedback($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __feedbacks WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - } - } -} +db->placehold("SELECT f.id, f.name, f.email, f.ip, f.message, f.date FROM __feedbacks f WHERE id=? LIMIT 1", intval($id)); + + if($this->db->query($query)) + return $this->db->result(); + else + return false; + } + + public function get_feedbacks($filter = array(), $new_on_top = false) + { + // По умолчанию + $limit = 0; + $page = 1; + $keyword_filter = ''; + + if(isset($filter['limit'])) + $limit = max(1, intval($filter['limit'])); + + if(isset($filter['page'])) + $page = max(1, intval($filter['page'])); + + $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); + + if(!empty($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND f.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.message LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.email LIKE "%'.$this->db->escape(trim($keyword)).'%" '); + } + + if($new_on_top) + $sort='DESC'; + else + $sort='ASC'; + + $query = $this->db->placehold("SELECT f.id, f.name, f.email, f.ip, f.message, f.date + FROM __feedbacks f WHERE 1 $keyword_filter ORDER BY f.id $sort $sql_limit"); + + $this->db->query($query); + return $this->db->results(); + } + + public function count_feedbacks($filter = array()) + { + $keyword_filter = ''; + + if(!empty($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND f.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.message LIKE "%'.$this->db->escape(trim($keyword)).'%" OR f.email LIKE "%'.$this->db->escape(trim($keyword)).'%" '); + } + + $query = $this->db->placehold("SELECT count(distinct f.id) as count + FROM __feedbacks f WHERE 1 $keyword_filter"); + + $this->db->query($query); + return $this->db->result('count'); + + } + + + public function add_feedback($feedback) + { + $query = $this->db->placehold('INSERT INTO __feedbacks + SET ?%, + date = NOW()', + $feedback); + + if(!$this->db->query($query)) + return false; + + $id = $this->db->insert_id(); + return $id; + } + + + public function update_feedback($id, $feedback) + { + $date_query = ''; + if(isset($feedback->date)) + { + $date = $feedback->date; + unset($feedback->date); + $date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format); + } + $query = $this->db->placehold("UPDATE __feedbacks SET ?% $date_query WHERE id in(?@) LIMIT 1", $feedback, (array)$id); + $this->db->query($query); + return $id; + } + + + public function delete_feedback($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __feedbacks WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + } + } +} diff --git a/api/Image.php b/api/Image.php index 2995312..ff68471 100755 --- a/api/Image.php +++ b/api/Image.php @@ -3,12 +3,13 @@ /** * Simpla CMS * - * @copyright 2011 Denis Pikusov + * @copyright 2016 Denis Pikusov * @link http://simplacms.ru * @author Denis Pikusov * */ + require_once('Simpla.php'); class Image extends Simpla @@ -16,11 +17,11 @@ class Image extends Simpla private $allowed_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico'); public function __construct() - { + { parent::__construct(); } - - + + /** * Создание превью изображения * @param $filename файл с изображением (без пути к файлу) @@ -28,38 +29,38 @@ public function __construct() * @param max_h максимальная высота * @return $string имя файла превью */ - function resize($filename) + public function resize($filename) { list($source_file, $width , $height, $set_watermark) = $this->get_resize_params($filename); // Если вайл удаленный (http://), зальем его себе if(substr($source_file, 0, 7) == 'http://') - { + { // Имя оригинального файла if(!$original_file = $this->download_image($source_file)) return false; - - $resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark); - } + + $resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark); + } else { $original_file = $source_file; } - - $resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark); - - + + $resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark); + + // Пути к папкам с картинками $originals_dir = $this->config->root_dir.$this->config->original_images_dir; $preview_dir = $this->config->root_dir.$this->config->resized_images_dir; - + $watermark_offet_x = $this->settings->watermark_offset_x; $watermark_offet_y = $this->settings->watermark_offset_y; - + $sharpen = min(100, $this->settings->images_sharpen)/100; $watermark_transparency = 1-min(100, $this->settings->watermark_transparency)/100; - - + + if($set_watermark && is_file($this->config->root_dir.$this->config->watermark_file)) $watermark = $this->config->root_dir.$this->config->watermark_file; else @@ -69,7 +70,7 @@ function resize($filename) $this->image_constrain_imagick($originals_dir.$original_file, $preview_dir.$resized_file, $width, $height, $watermark, $watermark_offet_x, $watermark_offet_y, $watermark_transparency, $sharpen); else $this->image_constrain_gd($originals_dir.$original_file, $preview_dir.$resized_file, $width, $height, $watermark, $watermark_offet_x, $watermark_offet_y, $watermark_transparency); - + return $preview_dir.$resized_file; } @@ -80,12 +81,12 @@ public function add_resize_params($filename, $width=0, $height=0, $set_watermark else $file = pathinfo($filename, PATHINFO_FILENAME); $ext = pathinfo($filename, PATHINFO_EXTENSION); - + if($width>0 || $height>0) $resized_filename = $file.'.'.($width>0?$width:'').'x'.($height>0?$height:'').($set_watermark?'w':'').'.'.$ext; else $resized_filename = $file.'.'.($set_watermark?'w.':'').$ext; - + return $resized_filename; } @@ -94,33 +95,33 @@ public function get_resize_params($filename) // Определаяем параметры ресайза if(!preg_match('/(.+)\.([0-9]*)x([0-9]*)(w)?\.([^\.]+)$/', $filename, $matches)) return false; - + $file = $matches[1]; // имя запрашиваемого файла $width = $matches[2]; // ширина будущего изображения $height = $matches[3]; // высота будущего изображения $set_watermark = $matches[4] == 'w'; // ставить ли водяной знак $ext = $matches[5]; // расширение файла - + return array($file.'.'.$ext, $width, $height, $set_watermark); } - - + + public function download_image($filename) { // Заливаем только есть такой файл есть в базе $this->db->query('SELECT 1 FROM __images WHERE filename=? LIMIT 1', $filename); if(!$this->db->result()) return false; - + // Имя оригинального файла $basename = explode('&', pathinfo($filename, PATHINFO_BASENAME)); $uploaded_file = array_shift($basename); $base = urldecode(pathinfo($uploaded_file, PATHINFO_FILENAME)); $ext = pathinfo($uploaded_file, PATHINFO_EXTENSION); - + // Если такой файл существует, нужно придумать другое название $new_name = urldecode($uploaded_file); - + while(file_exists($this->config->root_dir.$this->config->original_images_dir.$new_name)) { $new_base = pathinfo($new_name, PATHINFO_FILENAME); @@ -130,7 +131,7 @@ public function download_image($filename) $new_name = $base.'_1.'.$ext; } $this->db->query('UPDATE __images SET filename=? WHERE filename=?', $new_name, $filename); - + // Перед долгим копированием займем это имя fclose(fopen($this->config->root_dir.$this->config->original_images_dir.$new_name, 'w')); copy($filename, $this->config->root_dir.$this->config->original_images_dir.$new_name); @@ -144,25 +145,25 @@ public function upload_image($filename, $name) $uploaded_file = $new_name = pathinfo($name, PATHINFO_BASENAME); $base = pathinfo($uploaded_file, PATHINFO_FILENAME); $ext = pathinfo($uploaded_file, PATHINFO_EXTENSION); - + if(in_array(strtolower($ext), $this->allowed_extentions)) - { + { while(file_exists($this->config->root_dir.$this->config->original_images_dir.$new_name)) - { + { $new_base = pathinfo($new_name, PATHINFO_FILENAME); if(preg_match('/_([0-9]+)$/', $new_base, $parts)) $new_name = $base.'_'.($parts[1]+1).'.'.$ext; else $new_name = $base.'_1.'.$ext; } - if(move_uploaded_file($filename, $this->config->root_dir.$this->config->original_images_dir.$new_name)) + if(move_uploaded_file($filename, $this->config->root_dir.$this->config->original_images_dir.$new_name)) return $new_name; } return false; } - + /** * Создание превью средствами gd * @param $src_file исходный файл @@ -174,57 +175,57 @@ public function upload_image($filename, $name) private function image_constrain_gd($src_file, $dst_file, $max_w, $max_h, $watermark=null, $watermark_offet_x=0, $watermark_offet_y=0, $watermark_opacity=1) { $quality = 100; - + // Параметры исходного изображения @list($src_w, $src_h, $src_type) = array_values(getimagesize($src_file)); - $src_type = image_type_to_mime_type($src_type); - + $src_type = image_type_to_mime_type($src_type); + if(empty($src_w) || empty($src_h) || empty($src_type)) return false; - + // Нужно ли обрезать? if (!$watermark && ($src_w <= $max_w) && ($src_h <= $max_h)) - { + { // Нет - просто скопируем файл if (!copy($src_file, $dst_file)) return false; return true; - } - + } + // Размеры превью при пропорциональном уменьшении @list($dst_w, $dst_h) = $this->calc_contrain_size($src_w, $src_h, $max_w, $max_h); - + // Читаем изображение switch ($src_type) { - case 'image/jpeg': - $src_img = imageCreateFromJpeg($src_file); + case 'image/jpeg': + $src_img = imageCreateFromJpeg($src_file); break; case 'image/gif': - $src_img = imageCreateFromGif($src_file); + $src_img = imageCreateFromGif($src_file); break; case 'image/png': - $src_img = imageCreateFromPng($src_file); + $src_img = imageCreateFromPng($src_file); imagealphablending($src_img, true); break; default: return false; } - + if(empty($src_img)) return false; - + $src_colors = imagecolorstotal($src_img); - + // create destination image (indexed, if possible) if ($src_colors > 0 && $src_colors <= 256) $dst_img = imagecreate($dst_w, $dst_h); else $dst_img = imagecreatetruecolor($dst_w, $dst_h); - + if (empty($dst_img)) return false; - + $transparent_index = imagecolortransparent($src_img); if ($transparent_index >= 0 && $transparent_index <= 128) { @@ -235,10 +236,10 @@ private function image_constrain_gd($src_file, $dst_file, $max_w, $max_h, $water if (!imagefill($dst_img, 0, 0, $transparent_index)) return false; imagecolortransparent($dst_img, $transparent_index); - } - // or preserve alpha transparency for png + } + // or preserve alpha transparency for png elseif ($src_type === 'image/png') - { + { if (!imagealphablending($dst_img, false)) return false; $transparency = imagecolorallocatealpha($dst_img, 0, 0, 0, 127); @@ -248,30 +249,30 @@ private function image_constrain_gd($src_file, $dst_file, $max_w, $max_h, $water return false; if (!imagesavealpha($dst_img, true)) return false; - } - - // resample the image with new sizes + } + + // resample the image with new sizes if (!imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h)) - return false; - + return false; + // Watermark if(!empty($watermark) && is_readable($watermark)) - { + { $overlay = imagecreatefrompng($watermark); - - // Get the size of overlay - $owidth = imagesx($overlay); + + // Get the size of overlay + $owidth = imagesx($overlay); $oheight = imagesy($overlay); - - $watermark_x = min(($dst_w-$owidth)*$watermark_offet_x/100, $dst_w); - $watermark_y = min(($dst_h-$oheight)*$watermark_offet_y/100, $dst_h); - - imagecopy($dst_img, $overlay, $watermark_x, $watermark_y, 0, 0, $owidth, $oheight); - //imagecopymerge($dst_img, $overlay, $watermark_x, $watermark_y, 0, 0, $owidth, $oheight, $watermark_opacity*100); - - } - - + + $watermark_x = min(($dst_w-$owidth)*$watermark_offet_x/100, $dst_w); + $watermark_y = min(($dst_h-$oheight)*$watermark_offet_y/100, $dst_h); + + imagecopy($dst_img, $overlay, $watermark_x, $watermark_y, 0, 0, $owidth, $oheight); + //imagecopymerge($dst_img, $overlay, $watermark_x, $watermark_y, 0, 0, $owidth, $oheight, $watermark_opacity*100); + + } + + // recalculate quality value for png image if ('image/png' === $src_type) { @@ -282,11 +283,11 @@ private function image_constrain_gd($src_file, $dst_file, $max_w, $max_h, $water $quality = 10; $quality = 10 - $quality; } - + // Сохраняем изображение switch ($src_type) { - case 'image/jpeg': + case 'image/jpeg': return imageJpeg($dst_img, $dst_file, $quality); case 'image/gif': return imageGif($dst_img, $dst_file, $quality); @@ -297,7 +298,7 @@ private function image_constrain_gd($src_file, $dst_file, $max_w, $max_h, $water return false; } } - + /** * Создание превью средствами imagick * @param $src_file исходный файл @@ -309,30 +310,30 @@ private function image_constrain_gd($src_file, $dst_file, $max_w, $max_h, $water private function image_constrain_imagick($src_file, $dst_file, $max_w, $max_h, $watermark=null, $watermark_offet_x=0, $watermark_offet_y=0, $watermark_opacity=1, $sharpen=0.2) { $thumb = new Imagick(); - + // Читаем изображение if(!$thumb->readImage($src_file)) return false; - + // Размеры исходного изображения $src_w = $thumb->getImageWidth(); $src_h = $thumb->getImageHeight(); - + // Нужно ли обрезать? if (!$watermark && ($src_w <= $max_w) && ($src_h <= $max_h)) - { + { // Нет - просто скопируем файл if (!copy($src_file, $dst_file)) return false; return true; - } - + } + // Размеры превью при пропорциональном уменьшении list($dst_w, $dst_h) = $this->calc_contrain_size($src_w, $src_h, $max_w, $max_h); - + // Уменьшаем $thumb->thumbnailImage($dst_w, $dst_h); - + // Устанавливаем водяной знак if($watermark && is_readable($watermark)) { @@ -340,56 +341,56 @@ private function image_constrain_imagick($src_file, $dst_file, $max_w, $max_h, $ //$overlay->setImageOpacity($watermark_opacity); //$overlay_compose = $overlay->getImageCompose(); $overlay->evaluateImage(Imagick::EVALUATE_MULTIPLY, $watermark_opacity, Imagick::CHANNEL_ALPHA); - - // Get the size of overlay - $owidth = $overlay->getImageWidth(); + + // Get the size of overlay + $owidth = $overlay->getImageWidth(); $oheight = $overlay->getImageHeight(); - - $watermark_x = min(($dst_w-$owidth)*$watermark_offet_x/100, $dst_w); - $watermark_y = min(($dst_h-$oheight)*$watermark_offet_y/100, $dst_h); - + + $watermark_x = min(($dst_w-$owidth)*$watermark_offet_x/100, $dst_w); + $watermark_y = min(($dst_h-$oheight)*$watermark_offet_y/100, $dst_h); + } - - + + // Анимированные gif требуют прохода по фреймам foreach($thumb as $frame) { // Уменьшаем $frame->thumbnailImage($dst_w, $dst_h); - - /* Set the virtual canvas to correct size */ - $frame->setImagePage($dst_w, $dst_h, 0, 0); - + + /* Set the virtual canvas to correct size */ + $frame->setImagePage($dst_w, $dst_h, 0, 0); + // Наводим резкость - if($sharpen > 0) + if($sharpen > 0) $thumb->adaptiveSharpenImage($sharpen, $sharpen); - + if(isset($overlay) && is_object($overlay)) { // $frame->compositeImage($overlay, $overlay_compose, $watermark_x, $watermark_y, imagick::COLOR_ALPHA); $frame->compositeImage($overlay, imagick::COMPOSITE_OVER, $watermark_x, $watermark_y, imagick::COLOR_ALPHA); } - - } - + + } + // Убираем комменты и т.п. из картинки $thumb->stripImage(); - + // $thumb->setImageCompressionQuality(100); - + // Записываем картинку if(!$thumb->writeImages($dst_file, true)) return false; - + // Уборка $thumb->destroy(); if(isset($overlay) && is_object($overlay)) $overlay->destroy(); - + return true; } - - + + /** * Вычисляет размеры изображения, до которых нужно его пропорционально уменьшить, чтобы вписать в квадрат $max_w x $max_h * @param src_w ширина исходного изображения @@ -398,14 +399,14 @@ private function image_constrain_imagick($src_file, $dst_file, $max_w, $max_h, $ * @param max_h максимальная высота * @return array(w, h) */ - function calc_contrain_size($src_w, $src_h, $max_w = 0, $max_h = 0) + private function calc_contrain_size($src_w, $src_h, $max_w = 0, $max_h = 0) { if($src_w == 0 || $src_h == 0) return false; - + $dst_w = $src_w; $dst_h = $src_h; - + if($src_w > $max_w && $max_w>0) { $dst_h = $src_h * ($max_w/$src_w); @@ -417,46 +418,46 @@ function calc_contrain_size($src_w, $src_h, $max_w = 0, $max_h = 0) $dst_h = $max_h; } return array($dst_w, $dst_h); - } - - + } + + private function files_identical($fn1, $fn2) { $buffer_len = 1024; - if(!$fp1 = fopen(dirname(dirname(__FILE__)).'/'.$fn1, 'rb')) - return FALSE; - - if(!$fp2 = fopen($fn2, 'rb')) { - fclose($fp1); - return FALSE; - } - - $same = TRUE; - while (!feof($fp1) and !feof($fp2)) - if(fread($fp1, $buffer_len) !== fread($fp2, $buffer_len)) { - $same = FALSE; - break; - } - - if(feof($fp1) !== feof($fp2)) - $same = FALSE; - - fclose($fp1); - fclose($fp2); - - return $same; + if(!$fp1 = fopen(dirname(dirname(__FILE__)).'/'.$fn1, 'rb')) + return FALSE; + + if(!$fp2 = fopen($fn2, 'rb')) { + fclose($fp1); + return FALSE; + } + + $same = TRUE; + while (!feof($fp1) and !feof($fp2)) + if(fread($fp1, $buffer_len) !== fread($fp2, $buffer_len)) { + $same = FALSE; + break; + } + + if(feof($fp1) !== feof($fp2)) + $same = FALSE; + + fclose($fp1); + fclose($fp2); + + return $same; } private function correct_filename($filename) { - $ru = explode('-', "А-а-Б-б-В-в-Ґ-ґ-Г-г-Д-д-Е-е-Ё-ё-Є-є-Ж-ж-З-з-И-и-І-і-Ї-ї-Й-й-К-к-Л-л-М-м-Н-н-О-о-П-п-Р-р-С-с-Т-т-У-у-Ф-ф-Х-х-Ц-ц-Ч-ч-Ш-ш-Щ-щ-Ъ-ъ-Ы-ы-Ь-ь-Э-э-Ю-ю-Я-я"); + $ru = explode('-', "А-а-Б-б-В-в-Ґ-ґ-Г-г-Д-д-Е-е-Ё-ё-Є-є-Ж-ж-З-з-И-и-І-і-Ї-ї-Й-й-К-к-Л-л-М-м-Н-н-О-о-П-п-Р-р-С-с-Т-т-У-у-Ф-ф-Х-х-Ц-ц-Ч-ч-Ш-ш-Щ-щ-Ъ-ъ-Ы-ы-Ь-ь-Э-э-Ю-ю-Я-я"); $en = explode('-', "A-a-B-b-V-v-G-g-G-g-D-d-E-e-E-e-E-e-ZH-zh-Z-z-I-i-I-i-I-i-J-j-K-k-L-l-M-m-N-n-O-o-P-p-R-r-S-s-T-t-U-u-F-f-H-h-TS-ts-CH-ch-SH-sh-SCH-sch---Y-y---E-e-YU-yu-YA-ya"); - $res = str_replace($ru, $en, $filename); + $res = str_replace($ru, $en, $filename); $res = preg_replace("/[\s]+/ui", '-', $res); $res = preg_replace("/[^a-zA-Z0-9\.\-\_]+/ui", '', $res); - $res = strtolower($res); - return $res; + $res = strtolower($res); + return $res; } - -} \ No newline at end of file + +} diff --git a/api/Managers.php b/api/Managers.php index 32abe0e..a6d8725 100755 --- a/api/Managers.php +++ b/api/Managers.php @@ -3,20 +3,21 @@ /** * Simpla CMS * - * @copyright 2011 Denis Pikusov + * @copyright 2016 Denis Pikusov * @link http://simplacms.ru * @author Denis Pikusov * */ - + + require_once('Simpla.php'); class Managers extends Simpla -{ +{ public $permissions_list = array('products', 'categories', 'brands', 'features', 'orders', 'labels', 'users', 'groups', 'coupons', 'pages', 'blog', 'comments', 'feedbacks', 'import', 'export', 'backup', 'stats', 'design', 'settings', 'currency', 'delivery', 'payment', 'managers', 'license'); - + public $passwd_file = "simpla/.passwd"; public function __construct() @@ -24,11 +25,11 @@ public function __construct() // Для совсестимости с режимом CGI if (isset($_SERVER['REDIRECT_REMOTE_USER']) && empty($_SERVER['PHP_AUTH_USER'])) { - $_SERVER['PHP_AUTH_USER'] = $_SERVER['REDIRECT_REMOTE_USER']; - } + $_SERVER['PHP_AUTH_USER'] = $_SERVER['REDIRECT_REMOTE_USER']; + } elseif(empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER["REMOTE_USER"])) { - $_SERVER['PHP_AUTH_USER'] = $_SERVER["REMOTE_USER"]; + $_SERVER['PHP_AUTH_USER'] = $_SERVER["REMOTE_USER"]; } } @@ -53,18 +54,18 @@ public function get_managers() } else $manager->permissions = $this->permissions_list; - + $managers[] = $manager; } } return $managers; } - + public function count_managers($filter = array()) { return count($this->get_managers()); } - + public function get_manager($login = null) { // Если не запрашивается по логину, отдаём текущего менеджера или false @@ -79,15 +80,15 @@ public function get_manager($login = null) $m->permissions = $this->permissions_list; return $m; } - + foreach($this->get_managers() as $manager) { if($manager->login == $login) return $manager; - } - return false; + } + return false; } - + public function add_manager($manager) { $manager = (object)$manager; @@ -113,21 +114,21 @@ public function add_manager($manager) unset($m[2]); } } - $line = implode(":", $m); + $line = implode(":", $m); file_put_contents($this->passwd_file, @file_get_contents($this->passwd_file)."\n".$line); if($m = $this->get_manager($manager->login)) return $m->login; else return false; } - + public function update_manager($login, $manager) { $manager = (object)$manager; // Не допускаем двоеточия в логине if(!empty($manager->login)) $manager->login = str_replace(":", "", $manager->login); - + $lines = explode("\n", @file_get_contents($this->passwd_file)); $updated_flag = false; foreach($lines as &$line) @@ -165,7 +166,7 @@ public function update_manager($login, $manager) } return false; } - + public function delete_manager($login) { $lines = explode("\n", @file_get_contents($this->passwd_file)); @@ -178,7 +179,7 @@ public function delete_manager($login) file_put_contents($this->passwd_file, implode("\n", $lines)); return true; } - + private function crypt_apr1_md5($plainpasswd) { $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8); $len = strlen($plainpasswd); @@ -216,4 +217,4 @@ public function access($module) else return false; } -} \ No newline at end of file +} diff --git a/api/Money.php b/api/Money.php index 4cf541b..32e37fe 100755 --- a/api/Money.php +++ b/api/Money.php @@ -1,157 +1,156 @@ -settings->price_decimals_point)) - $this->decimals_point = $this->settings->price_decimals_point; - - if(isset($this->settings->price_thousands_separator)) - $this->thousands_separator = $this->settings->price_thousands_separator; - - $this->design->smarty->registerPlugin('modifier', 'convert', array($this, 'convert')); - - $this->init_currencies(); - } - - private function init_currencies() - { - $this->currencies = array(); - // Выбираем из базы валюты - $query = "SELECT id, name, sign, code, rate_from, rate_to, cents, position, enabled FROM __currencies ORDER BY position"; - $this->db->query($query); - - $results = $this->db->results(); - - foreach($results as $c) - { - $this->currencies[$c->id] = $c; - } - - $this->currency = reset($this->currencies); - - } - - - public function get_currencies($filter = array()) - { - $currencies = array(); - foreach($this->currencies as $id=>$currency) - if((isset($filter['enabled']) && $filter['enabled'] == 1 && $currency->enabled) || empty($filter['enabled'])) - $currencies[$id] = $currency; - - return $currencies; - } - - public function get_currency($id = null) - { - if(!empty($id) && is_integer($id) && isset($this->currencies[$id])) - return $this->currencies[$id]; - - if(!empty($id) && is_string($id)) - { - foreach($this->currencies as $currency) - { - if($currency->code == $id) - return $currency; - } - } - - return $this->currency; - } - - - public function add_currency($currency) - { - $query = $this->db->placehold('INSERT INTO __currencies - SET ?%', - $currency); - - if(!$this->db->query($query)) - return false; - - $id = $this->db->insert_id(); - $this->db->query("UPDATE __currencies SET position=id WHERE id=?", $id); - $this->init_currencies(); - - return $id; - } - - public function update_currency($id, $currency) - { - $query = $this->db->placehold('UPDATE __currencies - SET ?% - WHERE id in (?@)', - $currency, (array)$id); - if(!$this->db->query($query)) - return false; - - $this->init_currencies(); - return $id; - } - - public function delete_currency($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __currencies WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - } - $this->init_currencies(); - } - - - public function convert($price, $currency_id = null, $format = true) - { - if(isset($currency_id)) - { - if(is_numeric($currency_id)) - $currency = $this->get_currency((integer)$currency_id); - else - $currency = $this->get_currency((string)$currency_id); - } - elseif(isset($_SESSION['currency_id'])) - $currency = $this->get_currency($_SESSION['currency_id']); - else - $currency = current($this->get_currencies(array('enabled'=>1))); - - $result = $price; - - if(!empty($currency)) - { - // Умножим на курс валюты - $result = $result*$currency->rate_from/$currency->rate_to; - - // Точность отображения, знаков после запятой - $precision = isset($currency->cents)?$currency->cents:2; - } - - // Форматирование цены - if($format) - $result = number_format($result, $precision, $this->settings->decimals_point, $this->settings->thousands_separator); - else - $result = round($result, $precision); - - return $result; - } - - -} \ No newline at end of file +settings->price_decimals_point)) + $this->decimals_point = $this->settings->price_decimals_point; + + if(isset($this->settings->price_thousands_separator)) + $this->thousands_separator = $this->settings->price_thousands_separator; + + $this->design->smarty->registerPlugin('modifier', 'convert', array($this, 'convert')); + + $this->init_currencies(); + } + + private function init_currencies() + { + $this->currencies = array(); + // Выбираем из базы валюты + $query = "SELECT id, name, sign, code, rate_from, rate_to, cents, position, enabled FROM __currencies ORDER BY position"; + $this->db->query($query); + + $results = $this->db->results(); + + foreach($results as $c) + { + $this->currencies[$c->id] = $c; + } + + $this->currency = reset($this->currencies); + + } + + + public function get_currencies($filter = array()) + { + $currencies = array(); + foreach($this->currencies as $id=>$currency) + if((isset($filter['enabled']) && $filter['enabled'] == 1 && $currency->enabled) || empty($filter['enabled'])) + $currencies[$id] = $currency; + + return $currencies; + } + + public function get_currency($id = null) + { + if(!empty($id) && is_integer($id) && isset($this->currencies[$id])) + return $this->currencies[$id]; + + if(!empty($id) && is_string($id)) + { + foreach($this->currencies as $currency) + { + if($currency->code == $id) + return $currency; + } + } + + return $this->currency; + } + + + public function add_currency($currency) + { + $query = $this->db->placehold('INSERT INTO __currencies + SET ?%', + $currency); + + if(!$this->db->query($query)) + return false; + + $id = $this->db->insert_id(); + $this->db->query("UPDATE __currencies SET position=id WHERE id=?", $id); + $this->init_currencies(); + + return $id; + } + + public function update_currency($id, $currency) + { + $query = $this->db->placehold('UPDATE __currencies + SET ?% + WHERE id in (?@)', + $currency, (array)$id); + if(!$this->db->query($query)) + return false; + + $this->init_currencies(); + return $id; + } + + public function delete_currency($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __currencies WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + } + $this->init_currencies(); + } + + + public function convert($price, $currency_id = null, $format = true) + { + if(isset($currency_id)) + { + if(is_numeric($currency_id)) + $currency = $this->get_currency((integer)$currency_id); + else + $currency = $this->get_currency((string)$currency_id); + } + elseif(isset($_SESSION['currency_id'])) + $currency = $this->get_currency($_SESSION['currency_id']); + else + $currency = current($this->get_currencies(array('enabled'=>1))); + + $result = $price; + + if(!empty($currency)) + { + // Умножим на курс валюты + $result = $result*$currency->rate_from/$currency->rate_to; + + // Точность отображения, знаков после запятой + $precision = isset($currency->cents)?$currency->cents:2; + } + + // Форматирование цены + if($format) + $result = number_format($result, $precision, $this->settings->decimals_point, $this->settings->thousands_separator); + else + $result = round($result, $precision); + + return $result; + } + + +} diff --git a/api/Notify.php b/api/Notify.php index ca91875..200e74d 100755 --- a/api/Notify.php +++ b/api/Notify.php @@ -1,197 +1,198 @@ -orders->get_order(intval($order_id))) || empty($order->email)) - return false; - - $purchases = $this->orders->get_purchases(array('order_id'=>$order->id)); - $this->design->assign('purchases', $purchases); - - $products_ids = array(); - $variants_ids = array(); - foreach($purchases as $purchase) - { - $products_ids[] = $purchase->product_id; - $variants_ids[] = $purchase->variant_id; - } - - $products = array(); - foreach($this->products->get_products(array('id'=>$products_ids)) as $p) - $products[$p->id] = $p; - - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[] = $image; - - $variants = array(); - foreach($this->variants->get_variants(array('id'=>$variants_ids)) as $v) - { - $variants[$v->id] = $v; - $products[$v->product_id]->variants[] = $v; - } - - foreach($purchases as &$purchase) - { - if(!empty($products[$purchase->product_id])) - $purchase->product = $products[$purchase->product_id]; - if(!empty($variants[$purchase->variant_id])) - $purchase->variant = $variants[$purchase->variant_id]; - } - - // Способ доставки - $delivery = $this->delivery->get_delivery($order->delivery_id); - $this->design->assign('delivery', $delivery); - - $this->design->assign('order', $order); - $this->design->assign('purchases', $purchases); - - // Отправляем письмо - // Если в шаблон не передавалась валюта, передадим - if ($this->design->smarty->getTemplateVars('currency') === null) - { - $this->design->assign('currency', current($this->money->get_currencies(array('enabled'=>1)))); - } - $email_template = $this->design->fetch($this->config->root_dir.'design/'.$this->settings->theme.'/html/email_order.tpl'); - $subject = $this->design->get_var('subject'); - $this->email($order->email, $subject, $email_template, $this->settings->notify_from_email); - - } - - - public function email_order_admin($order_id) - { - if(!($order = $this->orders->get_order(intval($order_id)))) - return false; - - $purchases = $this->orders->get_purchases(array('order_id'=>$order->id)); - $this->design->assign('purchases', $purchases); - - $products_ids = array(); - $variants_ids = array(); - foreach($purchases as $purchase) - { - $products_ids[] = $purchase->product_id; - $variants_ids[] = $purchase->variant_id; - } - - $products = array(); - foreach($this->products->get_products(array('id'=>$products_ids)) as $p) - $products[$p->id] = $p; - - $images = $this->products->get_images(array('product_id'=>$products_ids)); - foreach($images as $image) - $products[$image->product_id]->images[] = $image; - - $variants = array(); - foreach($this->variants->get_variants(array('id'=>$variants_ids)) as $v) - { - $variants[$v->id] = $v; - $products[$v->product_id]->variants[] = $v; - } - - foreach($purchases as &$purchase) - { - if(!empty($products[$purchase->product_id])) - $purchase->product = $products[$purchase->product_id]; - if(!empty($variants[$purchase->variant_id])) - $purchase->variant = $variants[$purchase->variant_id]; - } - - // Способ доставки - $delivery = $this->delivery->get_delivery($order->delivery_id); - $this->design->assign('delivery', $delivery); - - // Пользователь - $user = $this->users->get_user(intval($order->user_id)); - $this->design->assign('user', $user); - - $this->design->assign('order', $order); - $this->design->assign('purchases', $purchases); - - // В основной валюте - $this->design->assign('main_currency', $this->money->get_currency()); - - // Отправляем письмо - $email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_order_admin.tpl'); - $subject = $this->design->get_var('subject'); - $this->email($this->settings->order_email, $subject, $email_template, $this->settings->notify_from_email); - - } - - - - public function email_comment_admin($comment_id) - { - if(!($comment = $this->comments->get_comment(intval($comment_id)))) - return false; - - if($comment->type == 'product') - $comment->product = $this->products->get_product(intval($comment->object_id)); - if($comment->type == 'blog') - $comment->post = $this->blog->get_post(intval($comment->object_id)); - - $this->design->assign('comment', $comment); - - // Отправляем письмо - $email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_comment_admin.tpl'); - $subject = $this->design->get_var('subject'); - $this->email($this->settings->comment_email, $subject, $email_template, $this->settings->notify_from_email); - } - - public function email_password_remind($user_id, $code) - { - if(!($user = $this->users->get_user(intval($user_id)))) - return false; - - $this->design->assign('user', $user); - $this->design->assign('code', $code); - - // Отправляем письмо - $email_template = $this->design->fetch($this->config->root_dir.'design/'.$this->settings->theme.'/html/email_password_remind.tpl'); - $subject = $this->design->get_var('subject'); - $this->email($user->email, $subject, $email_template, $this->settings->notify_from_email); - - $this->design->smarty->clearAssign('user'); - $this->design->smarty->clearAssign('code'); - } - - public function email_feedback_admin($feedback_id) - { - if(!($feedback = $this->feedbacks->get_feedback(intval($feedback_id)))) - return false; - - $this->design->assign('feedback', $feedback); - - // Отправляем письмо - $email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_feedback_admin.tpl'); - $subject = $this->design->get_var('subject'); - $this->email($this->settings->comment_email, $subject, $email_template, "$feedback->name <$feedback->email>", "$feedback->name <$feedback->email>"); - } - - -} \ No newline at end of file +orders->get_order(intval($order_id))) || empty($order->email)) + return false; + + $purchases = $this->orders->get_purchases(array('order_id'=>$order->id)); + $this->design->assign('purchases', $purchases); + + $products_ids = array(); + $variants_ids = array(); + foreach($purchases as $purchase) + { + $products_ids[] = $purchase->product_id; + $variants_ids[] = $purchase->variant_id; + } + + $products = array(); + foreach($this->products->get_products(array('id'=>$products_ids)) as $p) + $products[$p->id] = $p; + + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[] = $image; + + $variants = array(); + foreach($this->variants->get_variants(array('id'=>$variants_ids)) as $v) + { + $variants[$v->id] = $v; + $products[$v->product_id]->variants[] = $v; + } + + foreach($purchases as &$purchase) + { + if(!empty($products[$purchase->product_id])) + $purchase->product = $products[$purchase->product_id]; + if(!empty($variants[$purchase->variant_id])) + $purchase->variant = $variants[$purchase->variant_id]; + } + + // Способ доставки + $delivery = $this->delivery->get_delivery($order->delivery_id); + $this->design->assign('delivery', $delivery); + + $this->design->assign('order', $order); + $this->design->assign('purchases', $purchases); + + // Отправляем письмо + // Если в шаблон не передавалась валюта, передадим + if ($this->design->smarty->getTemplateVars('currency') === null) + { + $this->design->assign('currency', current($this->money->get_currencies(array('enabled'=>1)))); + } + $email_template = $this->design->fetch($this->config->root_dir.'design/'.$this->settings->theme.'/html/email_order.tpl'); + $subject = $this->design->get_var('subject'); + $this->email($order->email, $subject, $email_template, $this->settings->notify_from_email); + + } + + + public function email_order_admin($order_id) + { + if(!($order = $this->orders->get_order(intval($order_id)))) + return false; + + $purchases = $this->orders->get_purchases(array('order_id'=>$order->id)); + $this->design->assign('purchases', $purchases); + + $products_ids = array(); + $variants_ids = array(); + foreach($purchases as $purchase) + { + $products_ids[] = $purchase->product_id; + $variants_ids[] = $purchase->variant_id; + } + + $products = array(); + foreach($this->products->get_products(array('id'=>$products_ids)) as $p) + $products[$p->id] = $p; + + $images = $this->products->get_images(array('product_id'=>$products_ids)); + foreach($images as $image) + $products[$image->product_id]->images[] = $image; + + $variants = array(); + foreach($this->variants->get_variants(array('id'=>$variants_ids)) as $v) + { + $variants[$v->id] = $v; + $products[$v->product_id]->variants[] = $v; + } + + foreach($purchases as &$purchase) + { + if(!empty($products[$purchase->product_id])) + $purchase->product = $products[$purchase->product_id]; + if(!empty($variants[$purchase->variant_id])) + $purchase->variant = $variants[$purchase->variant_id]; + } + + // Способ доставки + $delivery = $this->delivery->get_delivery($order->delivery_id); + $this->design->assign('delivery', $delivery); + + // Пользователь + $user = $this->users->get_user(intval($order->user_id)); + $this->design->assign('user', $user); + + $this->design->assign('order', $order); + $this->design->assign('purchases', $purchases); + + // В основной валюте + $this->design->assign('main_currency', $this->money->get_currency()); + + // Отправляем письмо + $email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_order_admin.tpl'); + $subject = $this->design->get_var('subject'); + $this->email($this->settings->order_email, $subject, $email_template, $this->settings->notify_from_email); + + } + + + + public function email_comment_admin($comment_id) + { + if(!($comment = $this->comments->get_comment(intval($comment_id)))) + return false; + + if($comment->type == 'product') + $comment->product = $this->products->get_product(intval($comment->object_id)); + if($comment->type == 'blog') + $comment->post = $this->blog->get_post(intval($comment->object_id)); + + $this->design->assign('comment', $comment); + + // Отправляем письмо + $email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_comment_admin.tpl'); + $subject = $this->design->get_var('subject'); + $this->email($this->settings->comment_email, $subject, $email_template, $this->settings->notify_from_email); + } + + public function email_password_remind($user_id, $code) + { + if(!($user = $this->users->get_user(intval($user_id)))) + return false; + + $this->design->assign('user', $user); + $this->design->assign('code', $code); + + // Отправляем письмо + $email_template = $this->design->fetch($this->config->root_dir.'design/'.$this->settings->theme.'/html/email_password_remind.tpl'); + $subject = $this->design->get_var('subject'); + $this->email($user->email, $subject, $email_template, $this->settings->notify_from_email); + + $this->design->smarty->clearAssign('user'); + $this->design->smarty->clearAssign('code'); + } + + public function email_feedback_admin($feedback_id) + { + if(!($feedback = $this->feedbacks->get_feedback(intval($feedback_id)))) + return false; + + $this->design->assign('feedback', $feedback); + + // Отправляем письмо + $email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_feedback_admin.tpl'); + $subject = $this->design->get_var('subject'); + $this->email($this->settings->comment_email, $subject, $email_template, "$feedback->name <$feedback->email>", "$feedback->name <$feedback->email>"); + } + + +} diff --git a/api/Orders.php b/api/Orders.php index 4558af3..6fbddd5 100755 --- a/api/Orders.php +++ b/api/Orders.php @@ -1,538 +1,539 @@ -db->placehold(' WHERE o.id=? ', intval($id)); - else - $where = $this->db->placehold(' WHERE o.url=? ', $id); - - $query = $this->db->placehold("SELECT o.id, o.delivery_id, o.delivery_price, o.separate_delivery, - o.payment_method_id, o.paid, o.payment_date, o.closed, o.discount, o.coupon_code, o.coupon_discount, - o.date, o.user_id, o.name, o.address, o.phone, o.email, o.comment, o.status, - o.url, o.total_price, o.note, o.ip - FROM __orders o $where LIMIT 1"); - - if($this->db->query($query)) - return $this->db->result(); - else - return false; - } - - function get_orders($filter = array()) - { - // По умолчанию - $limit = 100; - $page = 1; - $keyword_filter = ''; - $label_filter = ''; - $status_filter = ''; - $user_filter = ''; - $modified_since_filter = ''; - $id_filter = ''; - - if(isset($filter['limit'])) - $limit = max(1, intval($filter['limit'])); - - if(isset($filter['page'])) - $page = max(1, intval($filter['page'])); - - $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); - - - if(isset($filter['status'])) - $status_filter = $this->db->placehold('AND o.status = ?', intval($filter['status'])); - - if(isset($filter['id'])) - $id_filter = $this->db->placehold('AND o.id in(?@)', (array)$filter['id']); - - if(isset($filter['user_id'])) - $user_filter = $this->db->placehold('AND o.user_id = ?', intval($filter['user_id'])); - - if(isset($filter['modified_since'])) - $modified_since_filter = $this->db->placehold('AND o.modified > ?', $filter['modified_since']); - - if(isset($filter['label'])) - $label_filter = $this->db->placehold('AND ol.label_id = ?', $filter['label']); - - if(!empty($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND (o.id = "'.$this->db->escape(trim($keyword)).'" OR o.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR REPLACE(o.phone, "-", "") LIKE "%'.$this->db->escape(str_replace('-', '', trim($keyword))).'%" OR o.address LIKE "%'.$this->db->escape(trim($keyword)).'%" )'); - } - - // Выбираем заказы - $query = $this->db->placehold("SELECT o.id, o.delivery_id, o.delivery_price, o.separate_delivery, - o.payment_method_id, o.paid, o.payment_date, o.closed, o.discount, o.coupon_code, o.coupon_discount, - o.date, o.user_id, o.name, o.address, o.phone, o.email, o.comment, o.status, - o.url, o.total_price, o.note - FROM __orders AS o - LEFT JOIN __orders_labels AS ol ON o.id=ol.order_id - WHERE 1 - $id_filter $status_filter $user_filter $keyword_filter $label_filter $modified_since_filter GROUP BY o.id ORDER BY status, id DESC $sql_limit", "%Y-%m-%d"); - $this->db->query($query); - $orders = array(); - foreach($this->db->results() as $order) - $orders[$order->id] = $order; - return $orders; - } - - function count_orders($filter = array()) - { - $keyword_filter = ''; - $label_filter = ''; - $status_filter = ''; - $user_filter = ''; - - if(isset($filter['status'])) - $status_filter = $this->db->placehold('AND o.status = ?', intval($filter['status'])); - - if(isset($filter['user_id'])) - $user_filter = $this->db->placehold('AND o.user_id = ?', intval($filter['user_id'])); - - if(isset($filter['label'])) - $label_filter = $this->db->placehold('AND ol.label_id = ?', $filter['label']); - - if(!empty($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - $keyword_filter .= $this->db->placehold('AND (o.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR REPLACE(o.phone, "-", "") LIKE "%'.$this->db->escape(str_replace('-', '', trim($keyword))).'%" OR o.address LIKE "%'.$this->db->escape(trim($keyword)).'%" )'); - } - - // Выбираем заказы - $query = $this->db->placehold("SELECT COUNT(DISTINCT id) as count - FROM __orders AS o - LEFT JOIN __orders_labels AS ol ON o.id=ol.order_id - WHERE 1 - $status_filter $user_filter $label_filter $keyword_filter"); - $this->db->query($query); - return $this->db->result('count'); - } - - public function update_order($id, $order) - { - $query = $this->db->placehold("UPDATE __orders SET ?%, modified=now() WHERE id=? LIMIT 1", $order, intval($id)); - $this->db->query($query); - $this->update_total_price(intval($id)); - return $id; - } - - public function delete_order($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __purchases WHERE order_id=?", $id); - $this->db->query($query); - - $query = $this->db->placehold("DELETE FROM __orders_labels WHERE order_id=?", $id); - $this->db->query($query); - - $query = $this->db->placehold("DELETE FROM __orders WHERE id=? LIMIT 1", $id); - $this->db->query($query); - } - } - - public function add_order($order) - { - $order = (object)$order; - $order->url = md5(uniqid($this->config->salt, true)); - $set_curr_date = ''; - if(empty($order->date)) - $set_curr_date = ', date=now()'; - $query = $this->db->placehold("INSERT INTO __orders SET ?%$set_curr_date", $order); - $this->db->query($query); - $id = $this->db->insert_id(); - return $id; - } - - public function get_label($id) - { - $query = $this->db->placehold("SELECT * FROM __labels WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - return $this->db->result(); - } - - public function get_labels() - { - $query = $this->db->placehold("SELECT * FROM __labels ORDER BY position"); - $this->db->query($query); - return $this->db->results(); - } - - /* - * - * Создание метки заказов - * @param $label - * - */ - public function add_label($label) - { - $query = $this->db->placehold('INSERT INTO __labels SET ?%', $label); - if(!$this->db->query($query)) - return false; - - $id = $this->db->insert_id(); - $this->db->query("UPDATE __labels SET position=id WHERE id=?", $id); - return $id; - } - - - /* - * - * Обновить метку - * @param $id, $label - * - */ - public function update_label($id, $label) - { - $query = $this->db->placehold("UPDATE __labels SET ?% WHERE id in(?@) LIMIT ?", $label, (array)$id, count((array)$id)); - $this->db->query($query); - return $id; - } - - /* - * - * Удалить метку - * @param $id - * - */ - public function delete_label($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __orders_labels WHERE label_id=?", intval($id)); - if($this->db->query($query)) - { - $query = $this->db->placehold("DELETE FROM __labels WHERE id=? LIMIT 1", intval($id)); - return $this->db->query($query); - } - else - { - return false; - } - } - } - - function get_order_labels($order_id = array()) - { - if(empty($order_id)) - return array(); - - $label_id_filter = $this->db->placehold('AND order_id in(?@)', (array)$order_id); - - $query = $this->db->placehold("SELECT ol.order_id, l.id, l.name, l.color, l.position - FROM __labels l LEFT JOIN __orders_labels ol ON ol.label_id = l.id - WHERE - 1 - $label_id_filter - ORDER BY position - "); - - $this->db->query($query); - return $this->db->results(); - } - - public function update_order_labels($id, $labels_ids) - { - $labels_ids = (array)$labels_ids; - $query = $this->db->placehold("DELETE FROM __orders_labels WHERE order_id=?", intval($id)); - $this->db->query($query); - if(is_array($labels_ids)) - foreach($labels_ids as $l_id) - $this->db->query("INSERT INTO __orders_labels SET order_id=?, label_id=?", $id, $l_id); - } - - public function add_order_labels($id, $labels_ids) - { - $labels_ids = (array)$labels_ids; - if(is_array($labels_ids)) - foreach($labels_ids as $l_id) - { - $this->db->query("INSERT IGNORE INTO __orders_labels SET order_id=?, label_id=?", $id, $l_id); - } - } - - public function delete_order_labels($id, $labels_ids) - { - $labels_ids = (array)$labels_ids; - if(is_array($labels_ids)) - foreach($labels_ids as $l_id) - $this->db->query("DELETE FROM __orders_labels WHERE order_id=? AND label_id=?", $id, $l_id); - } - - - public function get_purchase($id) - { - $query = $this->db->placehold("SELECT * FROM __purchases WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - return $this->db->result(); - } - - public function get_purchases($filter = array()) - { - $order_id_filter = ''; - if(!empty($filter['order_id'])) - $order_id_filter = $this->db->placehold('AND order_id in(?@)', (array)$filter['order_id']); - - $query = $this->db->placehold("SELECT * FROM __purchases WHERE 1 $order_id_filter ORDER BY id"); - $this->db->query($query); - return $this->db->results(); - } - - public function update_purchase($id, $purchase) - { - $purchase = (object)$purchase; - $old_purchase = $this->get_purchase($id); - if(!$old_purchase) - return false; - - $order = $this->get_order(intval($old_purchase->order_id)); - if(!$order) - return false; - - // Не допустить нехватки на складе - $variant = $this->variants->get_variant($purchase->variant_id); - if($order->closed && !empty($purchase->amount) && !empty($variant) && !$variant->infinity && $variant->stock<($purchase->amount-$old_purchase->amount)) - return false; - - // Если заказ закрыт, нужно обновить склад при изменении покупки - if($order->closed && !empty($purchase->amount)) - { - if($old_purchase->variant_id != $purchase->variant_id) - { - if(!empty($old_purchase->variant_id)) - { - $query = $this->db->placehold("UPDATE __variants SET stock=stock+? WHERE id=? AND stock IS NOT NULL LIMIT 1", $old_purchase->amount, $old_purchase->variant_id); - $this->db->query($query); - } - if(!empty($purchase->variant_id)) - { - $query = $this->db->placehold("UPDATE __variants SET stock=stock-? WHERE id=? AND stock IS NOT NULL LIMIT 1", $purchase->amount, $purchase->variant_id); - $this->db->query($query); - } - } - elseif(!empty($purchase->variant_id)) - { - $query = $this->db->placehold("UPDATE __variants SET stock=stock+(?) WHERE id=? AND stock IS NOT NULL LIMIT 1", $old_purchase->amount - $purchase->amount, $purchase->variant_id); - $this->db->query($query); - } - } - - $query = $this->db->placehold("UPDATE __purchases SET ?% WHERE id=? LIMIT 1", $purchase, intval($id)); - $this->db->query($query); - $this->update_total_price($order->id); - return $id; - } - - public function add_purchase($purchase) - { - $purchase = (object)$purchase; - if(!empty($purchase->variant_id)) - { - $variant = $this->variants->get_variant($purchase->variant_id); - if(empty($variant)) - return false; - $product = $this->products->get_product(intval($variant->product_id)); - if(empty($product)) - return false; - } - - $order = $this->get_order(intval($purchase->order_id)); - if(empty($order)) - return false; - - // Не допустить нехватки на складе - if($order->closed && !empty($purchase->amount) && !$variant->infinity && $variant->stock<$purchase->amount) - return false; - - if(!isset($purchase->product_id) && isset($variant)) - $purchase->product_id = $variant->product_id; - - if(!isset($purchase->product_name) && !empty($product)) - $purchase->product_name = $product->name; - - if(!isset($purchase->sku) && !empty($variant)) - $purchase->sku = $variant->sku; - - if(!isset($purchase->variant_name) && !empty($variant)) - $purchase->variant_name = $variant->name; - - if(!isset($purchase->price) && !empty($variant)) - $purchase->price = $variant->price; - - if(!isset($purchase->amount)) - $purchase->amount = 1; - - // Если заказ закрыт, нужно обновить склад при добавлении покупки - if($order->closed && !empty($purchase->amount) && !empty($variant->id)) - { - $stock_diff = $purchase->amount; - $query = $this->db->placehold("UPDATE __variants SET stock=stock-? WHERE id=? AND stock IS NOT NULL LIMIT 1", $stock_diff, $variant->id); - $this->db->query($query); - } - - $query = $this->db->placehold("INSERT INTO __purchases SET ?%", $purchase); - $this->db->query($query); - $purchase_id = $this->db->insert_id(); - - $this->update_total_price($order->id); - return $purchase_id; - } - - public function delete_purchase($id) - { - $purchase = $this->get_purchase($id); - if(!$purchase) - return false; - - $order = $this->get_order(intval($purchase->order_id)); - if(!$order) - return false; - - // Если заказ закрыт, нужно обновить склад при изменении покупки - if($order->closed && !empty($purchase->amount)) - { - $stock_diff = $purchase->amount; - $query = $this->db->placehold("UPDATE __variants SET stock=stock+? WHERE id=? AND stock IS NOT NULL LIMIT 1", $stock_diff, $purchase->variant_id); - $this->db->query($query); - } - - $query = $this->db->placehold("DELETE FROM __purchases WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - $this->update_total_price($order->id); - return true; - } - - - public function close($order_id) - { - $order = $this->get_order(intval($order_id)); - if(empty($order)) - return false; - - if(!$order->closed) - { - $variants_amounts = array(); - $purchases = $this->get_purchases(array('order_id'=>$order->id)); - foreach($purchases as $purchase) - { - if(isset($variants_amounts[$purchase->variant_id])) - $variants_amounts[$purchase->variant_id] += $purchase->amount; - else - $variants_amounts[$purchase->variant_id] = $purchase->amount; - } - - foreach($variants_amounts as $id=>$amount) - { - $variant = $this->variants->get_variant($id); - if(empty($variant) || ($variant->stock<$amount)) - return false; - } - foreach($purchases as $purchase) - { - $variant = $this->variants->get_variant($purchase->variant_id); - if(!$variant->infinity) - { - $new_stock = $variant->stock-$purchase->amount; - $this->variants->update_variant($variant->id, array('stock'=>$new_stock)); - } - } - $query = $this->db->placehold("UPDATE __orders SET closed=1, modified=NOW() WHERE id=? LIMIT 1", $order->id); - $this->db->query($query); - } - return $order->id; - } - - public function open($order_id) - { - $order = $this->get_order(intval($order_id)); - if(empty($order)) - return false; - - if($order->closed) - { - $purchases = $this->get_purchases(array('order_id'=>$order->id)); - foreach($purchases as $purchase) - { - $variant = $this->variants->get_variant($purchase->variant_id); - if($variant && !$variant->infinity) - { - $new_stock = $variant->stock+$purchase->amount; - $this->variants->update_variant($variant->id, array('stock'=>$new_stock)); - } - } - $query = $this->db->placehold("UPDATE __orders SET closed=0, modified=NOW() WHERE id=? LIMIT 1", $order->id); - $this->db->query($query); - } - return $order->id; - } - - public function pay($order_id) - { - $order = $this->get_order(intval($order_id)); - if(empty($order)) - return false; - - if(!$this->close($order->id)) - { - return false; - } - $query = $this->db->placehold("UPDATE __orders SET payment_status=1, payment_date=NOW(), modified=NOW() WHERE id=? LIMIT 1", $order->id); - $this->db->query($query); - return $order->id; - } - - private function update_total_price($order_id) - { - $order = $this->get_order(intval($order_id)); - if(empty($order)) - return false; - - $query = $this->db->placehold("UPDATE __orders o SET o.total_price=IFNULL((SELECT SUM(p.price*p.amount)*(100-o.discount)/100 FROM __purchases p WHERE p.order_id=o.id), 0)+o.delivery_price*(1-o.separate_delivery)-o.coupon_discount, modified=NOW() WHERE o.id=? LIMIT 1", $order->id); - $this->db->query($query); - return $order->id; - } - - - public function get_next_order($id, $status = null) - { - $f = ''; - if($status!==null) - $f = $this->db->placehold('AND status=?', $status); - $this->db->query("SELECT MIN(id) as id FROM __orders WHERE id>? $f LIMIT 1", $id); - $next_id = $this->db->result('id'); - if($next_id) - return $this->get_order(intval($next_id)); - else - return false; - } - - public function get_prev_order($id, $status = null) - { - $f = ''; - if($status !== null) - $f = $this->db->placehold('AND status=?', $status); - $this->db->query("SELECT MAX(id) as id FROM __orders WHERE iddb->result('id'); - if($prev_id) - return $this->get_order(intval($prev_id)); - else - return false; - } -} +db->placehold(' WHERE o.id=? ', intval($id)); + else + $where = $this->db->placehold(' WHERE o.url=? ', $id); + + $query = $this->db->placehold("SELECT o.id, o.delivery_id, o.delivery_price, o.separate_delivery, + o.payment_method_id, o.paid, o.payment_date, o.closed, o.discount, o.coupon_code, o.coupon_discount, + o.date, o.user_id, o.name, o.address, o.phone, o.email, o.comment, o.status, + o.url, o.total_price, o.note, o.ip + FROM __orders o $where LIMIT 1"); + + if($this->db->query($query)) + return $this->db->result(); + else + return false; + } + + public function get_orders($filter = array()) + { + // По умолчанию + $limit = 100; + $page = 1; + $keyword_filter = ''; + $label_filter = ''; + $status_filter = ''; + $user_filter = ''; + $modified_since_filter = ''; + $id_filter = ''; + + if(isset($filter['limit'])) + $limit = max(1, intval($filter['limit'])); + + if(isset($filter['page'])) + $page = max(1, intval($filter['page'])); + + $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); + + + if(isset($filter['status'])) + $status_filter = $this->db->placehold('AND o.status = ?', intval($filter['status'])); + + if(isset($filter['id'])) + $id_filter = $this->db->placehold('AND o.id in(?@)', (array)$filter['id']); + + if(isset($filter['user_id'])) + $user_filter = $this->db->placehold('AND o.user_id = ?', intval($filter['user_id'])); + + if(isset($filter['modified_since'])) + $modified_since_filter = $this->db->placehold('AND o.modified > ?', $filter['modified_since']); + + if(isset($filter['label'])) + $label_filter = $this->db->placehold('AND ol.label_id = ?', $filter['label']); + + if(!empty($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND (o.id = "'.$this->db->escape(trim($keyword)).'" OR o.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR REPLACE(o.phone, "-", "") LIKE "%'.$this->db->escape(str_replace('-', '', trim($keyword))).'%" OR o.address LIKE "%'.$this->db->escape(trim($keyword)).'%" )'); + } + + // Выбираем заказы + $query = $this->db->placehold("SELECT o.id, o.delivery_id, o.delivery_price, o.separate_delivery, + o.payment_method_id, o.paid, o.payment_date, o.closed, o.discount, o.coupon_code, o.coupon_discount, + o.date, o.user_id, o.name, o.address, o.phone, o.email, o.comment, o.status, + o.url, o.total_price, o.note + FROM __orders AS o + LEFT JOIN __orders_labels AS ol ON o.id=ol.order_id + WHERE 1 + $id_filter $status_filter $user_filter $keyword_filter $label_filter $modified_since_filter GROUP BY o.id ORDER BY status, id DESC $sql_limit", "%Y-%m-%d"); + $this->db->query($query); + $orders = array(); + foreach($this->db->results() as $order) + $orders[$order->id] = $order; + return $orders; + } + + public function count_orders($filter = array()) + { + $keyword_filter = ''; + $label_filter = ''; + $status_filter = ''; + $user_filter = ''; + + if(isset($filter['status'])) + $status_filter = $this->db->placehold('AND o.status = ?', intval($filter['status'])); + + if(isset($filter['user_id'])) + $user_filter = $this->db->placehold('AND o.user_id = ?', intval($filter['user_id'])); + + if(isset($filter['label'])) + $label_filter = $this->db->placehold('AND ol.label_id = ?', $filter['label']); + + if(!empty($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + $keyword_filter .= $this->db->placehold('AND (o.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR REPLACE(o.phone, "-", "") LIKE "%'.$this->db->escape(str_replace('-', '', trim($keyword))).'%" OR o.address LIKE "%'.$this->db->escape(trim($keyword)).'%" )'); + } + + // Выбираем заказы + $query = $this->db->placehold("SELECT COUNT(DISTINCT id) as count + FROM __orders AS o + LEFT JOIN __orders_labels AS ol ON o.id=ol.order_id + WHERE 1 + $status_filter $user_filter $label_filter $keyword_filter"); + $this->db->query($query); + return $this->db->result('count'); + } + + public function update_order($id, $order) + { + $query = $this->db->placehold("UPDATE __orders SET ?%, modified=now() WHERE id=? LIMIT 1", $order, intval($id)); + $this->db->query($query); + $this->update_total_price(intval($id)); + return $id; + } + + public function delete_order($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __purchases WHERE order_id=?", $id); + $this->db->query($query); + + $query = $this->db->placehold("DELETE FROM __orders_labels WHERE order_id=?", $id); + $this->db->query($query); + + $query = $this->db->placehold("DELETE FROM __orders WHERE id=? LIMIT 1", $id); + $this->db->query($query); + } + } + + public function add_order($order) + { + $order = (object)$order; + $order->url = md5(uniqid($this->config->salt, true)); + $set_curr_date = ''; + if(empty($order->date)) + $set_curr_date = ', date=now()'; + $query = $this->db->placehold("INSERT INTO __orders SET ?%$set_curr_date", $order); + $this->db->query($query); + $id = $this->db->insert_id(); + return $id; + } + + public function get_label($id) + { + $query = $this->db->placehold("SELECT * FROM __labels WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + return $this->db->result(); + } + + public function get_labels() + { + $query = $this->db->placehold("SELECT * FROM __labels ORDER BY position"); + $this->db->query($query); + return $this->db->results(); + } + + /* + * + * Создание метки заказов + * @param $label + * + */ + public function add_label($label) + { + $query = $this->db->placehold('INSERT INTO __labels SET ?%', $label); + if(!$this->db->query($query)) + return false; + + $id = $this->db->insert_id(); + $this->db->query("UPDATE __labels SET position=id WHERE id=?", $id); + return $id; + } + + + /* + * + * Обновить метку + * @param $id, $label + * + */ + public function update_label($id, $label) + { + $query = $this->db->placehold("UPDATE __labels SET ?% WHERE id in(?@) LIMIT ?", $label, (array)$id, count((array)$id)); + $this->db->query($query); + return $id; + } + + /* + * + * Удалить метку + * @param $id + * + */ + public function delete_label($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __orders_labels WHERE label_id=?", intval($id)); + if($this->db->query($query)) + { + $query = $this->db->placehold("DELETE FROM __labels WHERE id=? LIMIT 1", intval($id)); + return $this->db->query($query); + } + else + { + return false; + } + } + } + + public function get_order_labels($order_id = array()) + { + if(empty($order_id)) + return array(); + + $label_id_filter = $this->db->placehold('AND order_id in(?@)', (array)$order_id); + + $query = $this->db->placehold("SELECT ol.order_id, l.id, l.name, l.color, l.position + FROM __labels l LEFT JOIN __orders_labels ol ON ol.label_id = l.id + WHERE + 1 + $label_id_filter + ORDER BY position + "); + + $this->db->query($query); + return $this->db->results(); + } + + public function update_order_labels($id, $labels_ids) + { + $labels_ids = (array)$labels_ids; + $query = $this->db->placehold("DELETE FROM __orders_labels WHERE order_id=?", intval($id)); + $this->db->query($query); + if(is_array($labels_ids)) + foreach($labels_ids as $l_id) + $this->db->query("INSERT INTO __orders_labels SET order_id=?, label_id=?", $id, $l_id); + } + + public function add_order_labels($id, $labels_ids) + { + $labels_ids = (array)$labels_ids; + if(is_array($labels_ids)) + foreach($labels_ids as $l_id) + { + $this->db->query("INSERT IGNORE INTO __orders_labels SET order_id=?, label_id=?", $id, $l_id); + } + } + + public function delete_order_labels($id, $labels_ids) + { + $labels_ids = (array)$labels_ids; + if(is_array($labels_ids)) + foreach($labels_ids as $l_id) + $this->db->query("DELETE FROM __orders_labels WHERE order_id=? AND label_id=?", $id, $l_id); + } + + + public function get_purchase($id) + { + $query = $this->db->placehold("SELECT * FROM __purchases WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + return $this->db->result(); + } + + public function get_purchases($filter = array()) + { + $order_id_filter = ''; + if(!empty($filter['order_id'])) + $order_id_filter = $this->db->placehold('AND order_id in(?@)', (array)$filter['order_id']); + + $query = $this->db->placehold("SELECT * FROM __purchases WHERE 1 $order_id_filter ORDER BY id"); + $this->db->query($query); + return $this->db->results(); + } + + public function update_purchase($id, $purchase) + { + $purchase = (object)$purchase; + $old_purchase = $this->get_purchase($id); + if(!$old_purchase) + return false; + + $order = $this->get_order(intval($old_purchase->order_id)); + if(!$order) + return false; + + // Не допустить нехватки на складе + $variant = $this->variants->get_variant($purchase->variant_id); + if($order->closed && !empty($purchase->amount) && !empty($variant) && !$variant->infinity && $variant->stock<($purchase->amount-$old_purchase->amount)) + return false; + + // Если заказ закрыт, нужно обновить склад при изменении покупки + if($order->closed && !empty($purchase->amount)) + { + if($old_purchase->variant_id != $purchase->variant_id) + { + if(!empty($old_purchase->variant_id)) + { + $query = $this->db->placehold("UPDATE __variants SET stock=stock+? WHERE id=? AND stock IS NOT NULL LIMIT 1", $old_purchase->amount, $old_purchase->variant_id); + $this->db->query($query); + } + if(!empty($purchase->variant_id)) + { + $query = $this->db->placehold("UPDATE __variants SET stock=stock-? WHERE id=? AND stock IS NOT NULL LIMIT 1", $purchase->amount, $purchase->variant_id); + $this->db->query($query); + } + } + elseif(!empty($purchase->variant_id)) + { + $query = $this->db->placehold("UPDATE __variants SET stock=stock+(?) WHERE id=? AND stock IS NOT NULL LIMIT 1", $old_purchase->amount - $purchase->amount, $purchase->variant_id); + $this->db->query($query); + } + } + + $query = $this->db->placehold("UPDATE __purchases SET ?% WHERE id=? LIMIT 1", $purchase, intval($id)); + $this->db->query($query); + $this->update_total_price($order->id); + return $id; + } + + public function add_purchase($purchase) + { + $purchase = (object)$purchase; + if(!empty($purchase->variant_id)) + { + $variant = $this->variants->get_variant($purchase->variant_id); + if(empty($variant)) + return false; + $product = $this->products->get_product(intval($variant->product_id)); + if(empty($product)) + return false; + } + + $order = $this->get_order(intval($purchase->order_id)); + if(empty($order)) + return false; + + // Не допустить нехватки на складе + if($order->closed && !empty($purchase->amount) && !$variant->infinity && $variant->stock<$purchase->amount) + return false; + + if(!isset($purchase->product_id) && isset($variant)) + $purchase->product_id = $variant->product_id; + + if(!isset($purchase->product_name) && !empty($product)) + $purchase->product_name = $product->name; + + if(!isset($purchase->sku) && !empty($variant)) + $purchase->sku = $variant->sku; + + if(!isset($purchase->variant_name) && !empty($variant)) + $purchase->variant_name = $variant->name; + + if(!isset($purchase->price) && !empty($variant)) + $purchase->price = $variant->price; + + if(!isset($purchase->amount)) + $purchase->amount = 1; + + // Если заказ закрыт, нужно обновить склад при добавлении покупки + if($order->closed && !empty($purchase->amount) && !empty($variant->id)) + { + $stock_diff = $purchase->amount; + $query = $this->db->placehold("UPDATE __variants SET stock=stock-? WHERE id=? AND stock IS NOT NULL LIMIT 1", $stock_diff, $variant->id); + $this->db->query($query); + } + + $query = $this->db->placehold("INSERT INTO __purchases SET ?%", $purchase); + $this->db->query($query); + $purchase_id = $this->db->insert_id(); + + $this->update_total_price($order->id); + return $purchase_id; + } + + public function delete_purchase($id) + { + $purchase = $this->get_purchase($id); + if(!$purchase) + return false; + + $order = $this->get_order(intval($purchase->order_id)); + if(!$order) + return false; + + // Если заказ закрыт, нужно обновить склад при изменении покупки + if($order->closed && !empty($purchase->amount)) + { + $stock_diff = $purchase->amount; + $query = $this->db->placehold("UPDATE __variants SET stock=stock+? WHERE id=? AND stock IS NOT NULL LIMIT 1", $stock_diff, $purchase->variant_id); + $this->db->query($query); + } + + $query = $this->db->placehold("DELETE FROM __purchases WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + $this->update_total_price($order->id); + return true; + } + + + public function close($order_id) + { + $order = $this->get_order(intval($order_id)); + if(empty($order)) + return false; + + if(!$order->closed) + { + $variants_amounts = array(); + $purchases = $this->get_purchases(array('order_id'=>$order->id)); + foreach($purchases as $purchase) + { + if(isset($variants_amounts[$purchase->variant_id])) + $variants_amounts[$purchase->variant_id] += $purchase->amount; + else + $variants_amounts[$purchase->variant_id] = $purchase->amount; + } + + foreach($variants_amounts as $id=>$amount) + { + $variant = $this->variants->get_variant($id); + if(empty($variant) || ($variant->stock<$amount)) + return false; + } + foreach($purchases as $purchase) + { + $variant = $this->variants->get_variant($purchase->variant_id); + if(!$variant->infinity) + { + $new_stock = $variant->stock-$purchase->amount; + $this->variants->update_variant($variant->id, array('stock'=>$new_stock)); + } + } + $query = $this->db->placehold("UPDATE __orders SET closed=1, modified=NOW() WHERE id=? LIMIT 1", $order->id); + $this->db->query($query); + } + return $order->id; + } + + public function open($order_id) + { + $order = $this->get_order(intval($order_id)); + if(empty($order)) + return false; + + if($order->closed) + { + $purchases = $this->get_purchases(array('order_id'=>$order->id)); + foreach($purchases as $purchase) + { + $variant = $this->variants->get_variant($purchase->variant_id); + if($variant && !$variant->infinity) + { + $new_stock = $variant->stock+$purchase->amount; + $this->variants->update_variant($variant->id, array('stock'=>$new_stock)); + } + } + $query = $this->db->placehold("UPDATE __orders SET closed=0, modified=NOW() WHERE id=? LIMIT 1", $order->id); + $this->db->query($query); + } + return $order->id; + } + + public function pay($order_id) + { + $order = $this->get_order(intval($order_id)); + if(empty($order)) + return false; + + if(!$this->close($order->id)) + { + return false; + } + $query = $this->db->placehold("UPDATE __orders SET payment_status=1, payment_date=NOW(), modified=NOW() WHERE id=? LIMIT 1", $order->id); + $this->db->query($query); + return $order->id; + } + + private function update_total_price($order_id) + { + $order = $this->get_order(intval($order_id)); + if(empty($order)) + return false; + + $query = $this->db->placehold("UPDATE __orders o SET o.total_price=IFNULL((SELECT SUM(p.price*p.amount)*(100-o.discount)/100 FROM __purchases p WHERE p.order_id=o.id), 0)+o.delivery_price*(1-o.separate_delivery)-o.coupon_discount, modified=NOW() WHERE o.id=? LIMIT 1", $order->id); + $this->db->query($query); + return $order->id; + } + + + public function get_next_order($id, $status = null) + { + $f = ''; + if($status!==null) + $f = $this->db->placehold('AND status=?', $status); + $this->db->query("SELECT MIN(id) as id FROM __orders WHERE id>? $f LIMIT 1", $id); + $next_id = $this->db->result('id'); + if($next_id) + return $this->get_order(intval($next_id)); + else + return false; + } + + public function get_prev_order($id, $status = null) + { + $f = ''; + if($status !== null) + $f = $this->db->placehold('AND status=?', $status); + $this->db->query("SELECT MAX(id) as id FROM __orders WHERE iddb->result('id'); + if($prev_id) + return $this->get_order(intval($prev_id)); + else + return false; + } +} diff --git a/api/Pages.php b/api/Pages.php index 6a8315d..66dee12 100755 --- a/api/Pages.php +++ b/api/Pages.php @@ -1,139 +1,140 @@ -db->placehold(' WHERE url=? ', $id); - else - $where = $this->db->placehold(' WHERE id=? ', intval($id)); - - $query = "SELECT id, url, header, name, meta_title, meta_description, meta_keywords, body, menu_id, position, visible - FROM __pages $where LIMIT 1"; - - $this->db->query($query); - return $this->db->result(); - } - - /* - * - * Функция возвращает массив страниц, удовлетворяющих фильтру - * @param $filter - * - */ - public function get_pages($filter = array()) - { - $menu_filter = ''; - $visible_filter = ''; - $pages = array(); - - if(isset($filter['menu_id'])) - $menu_filter = $this->db->placehold('AND menu_id in (?@)', (array)$filter['menu_id']); - - if(isset($filter['visible'])) - $visible_filter = $this->db->placehold('AND visible = ?', intval($filter['visible'])); - - $query = "SELECT id, url, header, name, meta_title, meta_description, meta_keywords, body, menu_id, position, visible - FROM __pages WHERE 1 $menu_filter $visible_filter ORDER BY position"; - - $this->db->query($query); - - foreach($this->db->results() as $page) - $pages[$page->id] = $page; - - return $pages; - } - - /* - * - * Создание страницы - * - */ - public function add_page($page) - { - $query = $this->db->placehold('INSERT INTO __pages SET ?%', $page); - if(!$this->db->query($query)) - return false; - - $id = $this->db->insert_id(); - $this->db->query("UPDATE __pages SET position=id WHERE id=?", $id); - return $id; - } - - /* - * - * Обновить страницу - * - */ - public function update_page($id, $page) - { - $query = $this->db->placehold('UPDATE __pages SET ?% WHERE id in (?@)', $page, (array)$id); - if(!$this->db->query($query)) - return false; - return $id; - } - - /* - * - * Удалить страницу - * - */ - public function delete_page($id) - { - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __pages WHERE id=? LIMIT 1", intval($id)); - if($this->db->query($query)) - return true; - } - return false; - } - - /* - * - * Функция возвращает массив меню - * - */ - public function get_menus() - { - $menus = array(); - $query = "SELECT * FROM __menu ORDER BY position"; - $this->db->query($query); - foreach($this->db->results() as $menu) - $menus[$menu->id] = $menu; - return $menus; - } - - /* - * - * Функция возвращает меню по id - * @param $id - * - */ - public function get_menu($menu_id) - { - $query = $this->db->placehold("SELECT * FROM __menu WHERE id=? LIMIT 1", intval($menu_id)); - $this->db->query($query); - return $this->db->result(); - } - -} +db->placehold(' WHERE url=? ', $id); + else + $where = $this->db->placehold(' WHERE id=? ', intval($id)); + + $query = "SELECT id, url, header, name, meta_title, meta_description, meta_keywords, body, menu_id, position, visible + FROM __pages $where LIMIT 1"; + + $this->db->query($query); + return $this->db->result(); + } + + /* + * + * Функция возвращает массив страниц, удовлетворяющих фильтру + * @param $filter + * + */ + public function get_pages($filter = array()) + { + $menu_filter = ''; + $visible_filter = ''; + $pages = array(); + + if(isset($filter['menu_id'])) + $menu_filter = $this->db->placehold('AND menu_id in (?@)', (array)$filter['menu_id']); + + if(isset($filter['visible'])) + $visible_filter = $this->db->placehold('AND visible = ?', intval($filter['visible'])); + + $query = "SELECT id, url, header, name, meta_title, meta_description, meta_keywords, body, menu_id, position, visible + FROM __pages WHERE 1 $menu_filter $visible_filter ORDER BY position"; + + $this->db->query($query); + + foreach($this->db->results() as $page) + $pages[$page->id] = $page; + + return $pages; + } + + /* + * + * Создание страницы + * + */ + public function add_page($page) + { + $query = $this->db->placehold('INSERT INTO __pages SET ?%', $page); + if(!$this->db->query($query)) + return false; + + $id = $this->db->insert_id(); + $this->db->query("UPDATE __pages SET position=id WHERE id=?", $id); + return $id; + } + + /* + * + * Обновить страницу + * + */ + public function update_page($id, $page) + { + $query = $this->db->placehold('UPDATE __pages SET ?% WHERE id in (?@)', $page, (array)$id); + if(!$this->db->query($query)) + return false; + return $id; + } + + /* + * + * Удалить страницу + * + */ + public function delete_page($id) + { + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __pages WHERE id=? LIMIT 1", intval($id)); + if($this->db->query($query)) + return true; + } + return false; + } + + /* + * + * Функция возвращает массив меню + * + */ + public function get_menus() + { + $menus = array(); + $query = "SELECT * FROM __menu ORDER BY position"; + $this->db->query($query); + foreach($this->db->results() as $menu) + $menus[$menu->id] = $menu; + return $menus; + } + + /* + * + * Функция возвращает меню по id + * @param $id + * + */ + public function get_menu($menu_id) + { + $query = $this->db->placehold("SELECT * FROM __menu WHERE id=? LIMIT 1", intval($menu_id)); + $this->db->query($query); + return $this->db->result(); + } + +} diff --git a/api/Payment.php b/api/Payment.php index 685d13e..531dbfc 100755 --- a/api/Payment.php +++ b/api/Payment.php @@ -1,155 +1,156 @@ -db->placehold('AND id in (SELECT payment_method_id FROM __delivery_payment dp WHERE dp.delivery_id=?)', intval($filter['delivery_id'])); - - $enabled_filter = ''; - if(!empty($filter['enabled'])) - $enabled_filter = $this->db->placehold('AND enabled=?', intval($filter['enabled'])); - - $query = "SELECT * - FROM __payment_methods WHERE 1 $delivery_filter $enabled_filter ORDER BY position"; - - $this->db->query($query); - return $this->db->results(); - } - - function get_payment_method($id) - { - $query = $this->db->placehold("SELECT * FROM __payment_methods WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - $payment_method = $this->db->result(); - return $payment_method; - } - - function get_payment_settings($method_id) - { - $query = $this->db->placehold("SELECT settings FROM __payment_methods WHERE id=? LIMIT 1", intval($method_id)); - $this->db->query($query); - $settings = $this->db->result('settings'); - - $settings = unserialize($settings); - return $settings; - } - - function get_payment_modules() - { - $modules_dir = $this->config->root_dir.'payment/'; - - $modules = array(); - $handler = opendir($modules_dir); - while ($dir = readdir($handler)) - { - $dir = preg_replace("/[^A-Za-z0-9]+/", "", $dir); - if (!empty($dir) && $dir != "." && $dir != ".." && is_dir($modules_dir.$dir)) - { - - if(is_readable($modules_dir.$dir.'/settings.xml') && $xml = simplexml_load_file($modules_dir.$dir.'/settings.xml')) - { - $module = new stdClass; - - $module->name = (string)$xml->name; - $module->settings = array(); - - foreach($xml->settings as $setting) - { - $module->settings[(string)$setting->variable] = new stdClass; - $module->settings[(string)$setting->variable]->name = (string)$setting->name; - $module->settings[(string)$setting->variable]->variable = (string)$setting->variable; - $module->settings[(string)$setting->variable]->variable_options = array(); - foreach($setting->options as $option) - { - $module->settings[(string)$setting->variable]->options[(string)$option->value] = new stdClass; - $module->settings[(string)$setting->variable]->options[(string)$option->value]->name = (string)$option->name; - $module->settings[(string)$setting->variable]->options[(string)$option->value]->value = (string)$option->value; - } - } - $modules[$dir] = $module; - } - - } - } - closedir($handler); - return $modules; - - } - - public function get_payment_deliveries($id) - { - $query = $this->db->placehold("SELECT delivery_id FROM __delivery_payment WHERE payment_method_id=?", intval($id)); - $this->db->query($query); - return $this->db->results('delivery_id'); - } - - public function update_payment_method($id, $payment_method) - { - $query = $this->db->placehold("UPDATE __payment_methods SET ?% WHERE id in(?@)", $payment_method, (array)$id); - $this->db->query($query); - return $id; - } - - public function update_payment_settings($method_id, $settings) - { - if(!is_string($settings)) - { - $settings = serialize($settings); - } - $query = $this->db->placehold("UPDATE __payment_methods SET settings=? WHERE id in(?@) LIMIT 1", $settings, (array)$method_id); - $this->db->query($query); - return $method_id; - } - - public function update_payment_deliveries($id, $deliveries_ids) - { - $query = $this->db->placehold("DELETE FROM __delivery_payment WHERE payment_method_id=?", intval($id)); - $this->db->query($query); - if(is_array($deliveries_ids)) - foreach($deliveries_ids as $d_id) - $this->db->query("INSERT INTO __delivery_payment SET payment_method_id=?, delivery_id=?", $id, $d_id); - } - - public function add_payment_method($payment_method) - { - $query = $this->db->placehold('INSERT INTO __payment_methods - SET ?%', - $payment_method); - - if(!$this->db->query($query)) - return false; - - $id = $this->db->insert_id(); - $this->db->query("UPDATE __payment_methods SET position=id WHERE id=?", $id); - return $id; - } - - public function delete_payment_method($id) - { - // Удаляем связь метода оплаты с достаками - $query = $this->db->placehold("DELETE FROM __delivery_payment WHERE payment_method_id=?", intval($id)); - $this->db->query($query); - - if(!empty($id)) - { - $query = $this->db->placehold("DELETE FROM __payment_methods WHERE id=? LIMIT 1", intval($id)); - $this->db->query($query); - } - } - - -} +db->placehold('AND id in (SELECT payment_method_id FROM __delivery_payment dp WHERE dp.delivery_id=?)', intval($filter['delivery_id'])); + + $enabled_filter = ''; + if(!empty($filter['enabled'])) + $enabled_filter = $this->db->placehold('AND enabled=?', intval($filter['enabled'])); + + $query = "SELECT * + FROM __payment_methods WHERE 1 $delivery_filter $enabled_filter ORDER BY position"; + + $this->db->query($query); + return $this->db->results(); + } + + public function get_payment_method($id) + { + $query = $this->db->placehold("SELECT * FROM __payment_methods WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + $payment_method = $this->db->result(); + return $payment_method; + } + + public function get_payment_settings($method_id) + { + $query = $this->db->placehold("SELECT settings FROM __payment_methods WHERE id=? LIMIT 1", intval($method_id)); + $this->db->query($query); + $settings = $this->db->result('settings'); + + $settings = unserialize($settings); + return $settings; + } + + public function get_payment_modules() + { + $modules_dir = $this->config->root_dir.'payment/'; + + $modules = array(); + $handler = opendir($modules_dir); + while ($dir = readdir($handler)) + { + $dir = preg_replace("/[^A-Za-z0-9]+/", "", $dir); + if (!empty($dir) && $dir != "." && $dir != ".." && is_dir($modules_dir.$dir)) + { + + if(is_readable($modules_dir.$dir.'/settings.xml') && $xml = simplexml_load_file($modules_dir.$dir.'/settings.xml')) + { + $module = new stdClass; + + $module->name = (string)$xml->name; + $module->settings = array(); + + foreach($xml->settings as $setting) + { + $module->settings[(string)$setting->variable] = new stdClass; + $module->settings[(string)$setting->variable]->name = (string)$setting->name; + $module->settings[(string)$setting->variable]->variable = (string)$setting->variable; + $module->settings[(string)$setting->variable]->variable_options = array(); + foreach($setting->options as $option) + { + $module->settings[(string)$setting->variable]->options[(string)$option->value] = new stdClass; + $module->settings[(string)$setting->variable]->options[(string)$option->value]->name = (string)$option->name; + $module->settings[(string)$setting->variable]->options[(string)$option->value]->value = (string)$option->value; + } + } + $modules[$dir] = $module; + } + + } + } + closedir($handler); + return $modules; + + } + + public function get_payment_deliveries($id) + { + $query = $this->db->placehold("SELECT delivery_id FROM __delivery_payment WHERE payment_method_id=?", intval($id)); + $this->db->query($query); + return $this->db->results('delivery_id'); + } + + public function update_payment_method($id, $payment_method) + { + $query = $this->db->placehold("UPDATE __payment_methods SET ?% WHERE id in(?@)", $payment_method, (array)$id); + $this->db->query($query); + return $id; + } + + public function update_payment_settings($method_id, $settings) + { + if(!is_string($settings)) + { + $settings = serialize($settings); + } + $query = $this->db->placehold("UPDATE __payment_methods SET settings=? WHERE id in(?@) LIMIT 1", $settings, (array)$method_id); + $this->db->query($query); + return $method_id; + } + + public function update_payment_deliveries($id, $deliveries_ids) + { + $query = $this->db->placehold("DELETE FROM __delivery_payment WHERE payment_method_id=?", intval($id)); + $this->db->query($query); + if(is_array($deliveries_ids)) + foreach($deliveries_ids as $d_id) + $this->db->query("INSERT INTO __delivery_payment SET payment_method_id=?, delivery_id=?", $id, $d_id); + } + + public function add_payment_method($payment_method) + { + $query = $this->db->placehold('INSERT INTO __payment_methods + SET ?%', + $payment_method); + + if(!$this->db->query($query)) + return false; + + $id = $this->db->insert_id(); + $this->db->query("UPDATE __payment_methods SET position=id WHERE id=?", $id); + return $id; + } + + public function delete_payment_method($id) + { + // Удаляем связь метода оплаты с достаками + $query = $this->db->placehold("DELETE FROM __delivery_payment WHERE payment_method_id=?", intval($id)); + $this->db->query($query); + + if(!empty($id)) + { + $query = $this->db->placehold("DELETE FROM __payment_methods WHERE id=? LIMIT 1", intval($id)); + $this->db->query($query); + } + } + + +} diff --git a/api/Products.php b/api/Products.php index 55c1aea..75265b4 100755 --- a/api/Products.php +++ b/api/Products.php @@ -1,550 +1,551 @@ - значение свойства) - */ - public function get_products($filter = array()) - { - // По умолчанию - $limit = 100; - $page = 1; - $category_id_filter = ''; - $brand_id_filter = ''; - $product_id_filter = ''; - $features_filter = ''; - $keyword_filter = ''; - $visible_filter = ''; - $is_featured_filter = ''; - $discounted_filter = ''; - $in_stock_filter = ''; - $group_by = ''; - $order = 'p.position DESC'; - - if(isset($filter['limit'])) - $limit = max(1, intval($filter['limit'])); - - if(isset($filter['page'])) - $page = max(1, intval($filter['page'])); - - $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); - - if(!empty($filter['id'])) - $product_id_filter = $this->db->placehold('AND p.id in(?@)', (array)$filter['id']); - - if(!empty($filter['category_id'])) - { - $category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']); - $group_by = "GROUP BY p.id"; - } - - if(!empty($filter['brand_id'])) - $brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']); - - if(isset($filter['featured'])) - $is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured'])); - - if(isset($filter['discounted'])) - $discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted'])); - - if(isset($filter['in_stock'])) - $in_stock_filter = $this->db->placehold('AND (SELECT count(*)>0 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock'])); - - if(isset($filter['visible'])) - $visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible'])); - - if(!empty($filter['sort'])) - switch ($filter['sort']) - { - case 'position': - $order = 'p.position DESC'; - break; - case 'name': - $order = 'p.name'; - break; - case 'created': - $order = 'p.created DESC'; - break; - case 'price': - //$order = 'pv.price IS NULL, pv.price=0, pv.price'; - $order = '(SELECT -pv.price FROM __variants pv WHERE (pv.stock IS NULL OR pv.stock>0) AND p.id = pv.product_id AND pv.position=(SELECT MIN(position) FROM __variants WHERE (stock>0 OR stock IS NULL) AND product_id=p.id LIMIT 1) LIMIT 1) DESC'; - break; - } - - if(!empty($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - { - $kw = $this->db->escape(trim($keyword)); - if($kw!=='') - $keyword_filter .= $this->db->placehold("AND (p.name LIKE '%$kw%' OR p.meta_keywords LIKE '%$kw%' OR p.id in (SELECT product_id FROM __variants WHERE sku LIKE '%$kw%'))"); - } - } - - if(!empty($filter['features']) && !empty($filter['features'])) - foreach($filter['features'] as $feature=>$value) - $features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value); - - $query = "SELECT - p.id, - p.url, - p.brand_id, - p.name, - p.annotation, - p.body, - p.position, - p.created as created, - p.visible, - p.featured, - p.meta_title, - p.meta_keywords, - p.meta_description, - b.name as brand, - b.url as brand_url - FROM __products p - $category_id_filter - LEFT JOIN __brands b ON p.brand_id = b.id - WHERE - 1 - $product_id_filter - $brand_id_filter - $features_filter - $keyword_filter - $is_featured_filter - $discounted_filter - $in_stock_filter - $visible_filter - $group_by - ORDER BY $order - $sql_limit"; - - $this->db->query($query); - - return $this->db->results(); - } - - /** - * Функция возвращает количество товаров - * Возможные значения фильтра: - * category_id - id категории или их массив - * brand_id - id бренда или их массив - * keyword - ключевое слово для поиска - * features - фильтр по свойствам товара, массив (id свойства => значение свойства) - */ - public function count_products($filter = array()) - { - $category_id_filter = ''; - $brand_id_filter = ''; - $product_id_filter = ''; - $keyword_filter = ''; - $visible_filter = ''; - $is_featured_filter = ''; - $in_stock_filter = ''; - $discounted_filter = ''; - $features_filter = ''; - - if(!empty($filter['category_id'])) - $category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']); - - if(!empty($filter['brand_id'])) - $brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']); - - if(!empty($filter['id'])) - $product_id_filter = $this->db->placehold('AND p.id in(?@)', (array)$filter['id']); - - if(isset($filter['keyword'])) - { - $keywords = explode(' ', $filter['keyword']); - foreach($keywords as $keyword) - { - $kw = $this->db->escape(trim($keyword)); - if($kw!=='') - $keyword_filter .= $this->db->placehold("AND (p.name LIKE '%$kw%' OR p.meta_keywords LIKE '%$kw%' OR p.id in (SELECT product_id FROM __variants WHERE sku LIKE '%$kw%'))"); - } - } - - if(isset($filter['featured'])) - $is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured'])); - - if(isset($filter['in_stock'])) - $in_stock_filter = $this->db->placehold('AND (SELECT count(*)>0 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock'])); - - if(isset($filter['discounted'])) - $discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted'])); - - if(isset($filter['visible'])) - $visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible'])); - - - if(!empty($filter['features']) && !empty($filter['features'])) - foreach($filter['features'] as $feature=>$value) - $features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value); - - $query = "SELECT count(distinct p.id) as count - FROM __products AS p - $category_id_filter - WHERE 1 - $brand_id_filter - $product_id_filter - $keyword_filter - $is_featured_filter - $in_stock_filter - $discounted_filter - $visible_filter - $features_filter "; - - $this->db->query($query); - return $this->db->result('count'); - } - - - /** - * Функция возвращает товар по id - * @param $id - * @retval object - */ - public function get_product($id) - { - if(is_int($id)) - $filter = $this->db->placehold('p.id = ?', $id); - else - $filter = $this->db->placehold('p.url = ?', $id); - - $query = "SELECT DISTINCT - p.id, - p.url, - p.brand_id, - p.name, - p.annotation, - p.body, - p.position, - p.created as created, - p.visible, - p.featured, - p.meta_title, - p.meta_keywords, - p.meta_description - FROM __products AS p - WHERE $filter - GROUP BY p.id - LIMIT 1"; - $this->db->query($query); - $product = $this->db->result(); - return $product; - } - - public function update_product($id, $product) - { - $query = $this->db->placehold("UPDATE __products SET ?% WHERE id in (?@) LIMIT ?", $product, (array)$id, count((array)$id)); - if($this->db->query($query)) - return $id; - else - return false; - } - - public function add_product($product) - { - $product = (array) $product; - - if(empty($product['url'])) - { - $product['url'] = preg_replace("/[\s]+/ui", '-', $product['name']); - $product['url'] = strtolower(preg_replace("/[^0-9a-zа-я\-]+/ui", '', $product['url'])); - } - - // Если есть товар с таким URL, добавляем к нему число - while($this->get_product((string)$product['url'])) - { - if(preg_match('/(.+)_([0-9]+)$/', $product['url'], $parts)) - $product['url'] = $parts[1].'_'.($parts[2]+1); - else - $product['url'] = $product['url'].'_2'; - } - - if($this->db->query("INSERT INTO __products SET ?%", $product)) - { - $id = $this->db->insert_id(); - $this->db->query("UPDATE __products SET position=id WHERE id=?", $id); - return $id; - } - else - return false; - } - - - /* - * - * Удалить товар - * - */ - public function delete_product($id) - { - if(!empty($id)) - { - // Удаляем варианты - $variants = $this->variants->get_variants(array('product_id'=>$id)); - foreach($variants as $v) - $this->variants->delete_variant($v->id); - - // Удаляем изображения - $images = $this->get_images(array('product_id'=>$id)); - foreach($images as $i) - $this->delete_image($i->id); - - // Удаляем категории - $categories = $this->categories->get_categories(array('product_id'=>$id)); - foreach($categories as $c) - $this->categories->delete_product_category($id, $c->id); - - // Удаляем свойства - $options = $this->features->get_options(array('product_id'=>$id)); - foreach($options as $o) - $this->features->delete_option($id, $o->feature_id); - - // Удаляем связанные товары - $related = $this->get_related_products($id); - foreach($related as $r) - $this->delete_related_product($id, $r->related_id); - - // Удаляем товар из связанных с другими - $query = $this->db->placehold("DELETE FROM __related_products WHERE related_id=?", intval($id)); - $this->db->query($query); - - // Удаляем отзывы - $comments = $this->comments->get_comments(array('object_id'=>$id, 'type'=>'product')); - foreach($comments as $c) - $this->comments->delete_comment($c->id); - - // Удаляем из покупок - $this->db->query('UPDATE __purchases SET product_id=NULL WHERE product_id=?', intval($id)); - - // Удаляем товар - $query = $this->db->placehold("DELETE FROM __products WHERE id=? LIMIT 1", intval($id)); - if($this->db->query($query)) - return true; - } - return false; - } - - public function duplicate_product($id) - { - $product = $this->get_product($id); - $product->id = null; - $product->external_id = ''; - $product->created = null; - - // Сдвигаем товары вперед и вставляем копию на соседнюю позицию - $this->db->query('UPDATE __products SET position=position+1 WHERE position>?', $product->position); - $new_id = $this->products->add_product($product); - $this->db->query('UPDATE __products SET position=? WHERE id=?', $product->position+1, $new_id); - - // Очищаем url - $this->db->query('UPDATE __products SET url="" WHERE id=?', $new_id); - - // Дублируем категории - $categories = $this->categories->get_product_categories($id); - foreach($categories as $c) - $this->categories->add_product_category($new_id, $c->category_id); - - // Дублируем изображения - $images = $this->get_images(array('product_id'=>$id)); - foreach($images as $image) - $this->add_image($new_id, $image->filename); - - // Дублируем варианты - $variants = $this->variants->get_variants(array('product_id'=>$id)); - foreach($variants as $variant) - { - $variant->product_id = $new_id; - unset($variant->id); - if($variant->infinity) - $variant->stock = null; - unset($variant->infinity); - $variant->external_id = ''; - $this->variants->add_variant($variant); - } - - // Дублируем свойства - $options = $this->features->get_options(array('product_id'=>$id)); - foreach($options as $o) - $this->features->update_option($new_id, $o->feature_id, $o->value); - - // Дублируем связанные товары - $related = $this->get_related_products($id); - foreach($related as $r) - $this->add_related_product($new_id, $r->related_id); - - - return $new_id; - } - - - public function get_related_products($product_id = array()) - { - if(empty($product_id)) - return array(); - - $product_id_filter = $this->db->placehold('AND product_id in(?@)', (array)$product_id); - - $query = $this->db->placehold("SELECT product_id, related_id, position - FROM __related_products - WHERE - 1 - $product_id_filter - ORDER BY position - "); - - $this->db->query($query); - return $this->db->results(); - } - - // Функция возвращает связанные товары - public function add_related_product($product_id, $related_id, $position=0) - { - $query = $this->db->placehold("INSERT IGNORE INTO __related_products SET product_id=?, related_id=?, position=?", $product_id, $related_id, $position); - $this->db->query($query); - return $related_id; - } - - // Удаление связанного товара - public function delete_related_product($product_id, $related_id) - { - $query = $this->db->placehold("DELETE FROM __related_products WHERE product_id=? AND related_id=? LIMIT 1", intval($product_id), intval($related_id)); - $this->db->query($query); - } - - - function get_images($filter = array()) - { - $product_id_filter = ''; - $group_by = ''; - - if(!empty($filter['product_id'])) - $product_id_filter = $this->db->placehold('AND i.product_id in(?@)', (array)$filter['product_id']); - - // images - $query = $this->db->placehold("SELECT i.id, i.product_id, i.name, i.filename, i.position - FROM __images AS i WHERE 1 $product_id_filter $group_by ORDER BY i.product_id, i.position"); - $this->db->query($query); - return $this->db->results(); - } - - public function add_image($product_id, $filename, $name = '') - { - $query = $this->db->placehold("SELECT id FROM __images WHERE product_id=? AND filename=?", $product_id, $filename); - $this->db->query($query); - $id = $this->db->result('id'); - if(empty($id)) - { - $query = $this->db->placehold("INSERT INTO __images SET product_id=?, filename=?", $product_id, $filename); - $this->db->query($query); - $id = $this->db->insert_id(); - $query = $this->db->placehold("UPDATE __images SET position=id WHERE id=?", $id); - $this->db->query($query); - } - return($id); - } - - public function update_image($id, $image) - { - - $query = $this->db->placehold("UPDATE __images SET ?% WHERE id=?", $image, $id); - $this->db->query($query); - - return($id); - } - - public function delete_image($id) - { - $query = $this->db->placehold("SELECT filename FROM __images WHERE id=?", $id); - $this->db->query($query); - $filename = $this->db->result('filename'); - $query = $this->db->placehold("DELETE FROM __images WHERE id=? LIMIT 1", $id); - $this->db->query($query); - $query = $this->db->placehold("SELECT count(*) as count FROM __images WHERE filename=? LIMIT 1", $filename); - $this->db->query($query); - $count = $this->db->result('count'); - if($count == 0) - { - $file = pathinfo($filename, PATHINFO_FILENAME); - $ext = pathinfo($filename, PATHINFO_EXTENSION); - - // Удалить все ресайзы - $rezised_images = glob($this->config->root_dir.$this->config->resized_images_dir.$file.".*x*.".$ext); - if(is_array($rezised_images)) - foreach (glob($this->config->root_dir.$this->config->resized_images_dir.$file.".*x*.".$ext) as $f) - @unlink($f); - - @unlink($this->config->root_dir.$this->config->original_images_dir.$filename); - } - } - - /* - * - * Следующий товар - * - */ - public function get_next_product($id) - { - $this->db->query("SELECT position FROM __products WHERE id=? LIMIT 1", $id); - $position = $this->db->result('position'); - - $this->db->query("SELECT pc.category_id FROM __products_categories pc WHERE product_id=? ORDER BY position LIMIT 1", $id); - $category_id = $this->db->result('category_id'); - - $query = $this->db->placehold("SELECT id FROM __products p, __products_categories pc - WHERE pc.product_id=p.id AND p.position>? - AND pc.position=(SELECT MIN(pc2.position) FROM __products_categories pc2 WHERE pc.product_id=pc2.product_id) - AND pc.category_id=? - AND p.visible ORDER BY p.position limit 1", $position, $category_id); - $this->db->query($query); - - return $this->get_product((integer)$this->db->result('id')); - } - - /* - * - * Предыдущий товар - * - */ - public function get_prev_product($id) - { - $this->db->query("SELECT position FROM __products WHERE id=? LIMIT 1", $id); - $position = $this->db->result('position'); - - $this->db->query("SELECT pc.category_id FROM __products_categories pc WHERE product_id=? ORDER BY position LIMIT 1", $id); - $category_id = $this->db->result('category_id'); - - $query = $this->db->placehold("SELECT id FROM __products p, __products_categories pc - WHERE pc.product_id=p.id AND p.positiondb->query($query); - - return $this->get_product((integer)$this->db->result('id')); } - - -} \ No newline at end of file + значение свойства) + */ + public function get_products($filter = array()) + { + // По умолчанию + $limit = 100; + $page = 1; + $category_id_filter = ''; + $brand_id_filter = ''; + $product_id_filter = ''; + $features_filter = ''; + $keyword_filter = ''; + $visible_filter = ''; + $is_featured_filter = ''; + $discounted_filter = ''; + $in_stock_filter = ''; + $group_by = ''; + $order = 'p.position DESC'; + + if(isset($filter['limit'])) + $limit = max(1, intval($filter['limit'])); + + if(isset($filter['page'])) + $page = max(1, intval($filter['page'])); + + $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); + + if(!empty($filter['id'])) + $product_id_filter = $this->db->placehold('AND p.id in(?@)', (array)$filter['id']); + + if(!empty($filter['category_id'])) + { + $category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']); + $group_by = "GROUP BY p.id"; + } + + if(!empty($filter['brand_id'])) + $brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']); + + if(isset($filter['featured'])) + $is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured'])); + + if(isset($filter['discounted'])) + $discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted'])); + + if(isset($filter['in_stock'])) + $in_stock_filter = $this->db->placehold('AND (SELECT count(*)>0 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock'])); + + if(isset($filter['visible'])) + $visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible'])); + + if(!empty($filter['sort'])) + switch ($filter['sort']) + { + case 'position': + $order = 'p.position DESC'; + break; + case 'name': + $order = 'p.name'; + break; + case 'created': + $order = 'p.created DESC'; + break; + case 'price': + //$order = 'pv.price IS NULL, pv.price=0, pv.price'; + $order = '(SELECT -pv.price FROM __variants pv WHERE (pv.stock IS NULL OR pv.stock>0) AND p.id = pv.product_id AND pv.position=(SELECT MIN(position) FROM __variants WHERE (stock>0 OR stock IS NULL) AND product_id=p.id LIMIT 1) LIMIT 1) DESC'; + break; + } + + if(!empty($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + { + $kw = $this->db->escape(trim($keyword)); + if($kw!=='') + $keyword_filter .= $this->db->placehold("AND (p.name LIKE '%$kw%' OR p.meta_keywords LIKE '%$kw%' OR p.id in (SELECT product_id FROM __variants WHERE sku LIKE '%$kw%'))"); + } + } + + if(!empty($filter['features']) && !empty($filter['features'])) + foreach($filter['features'] as $feature=>$value) + $features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value); + + $query = "SELECT + p.id, + p.url, + p.brand_id, + p.name, + p.annotation, + p.body, + p.position, + p.created as created, + p.visible, + p.featured, + p.meta_title, + p.meta_keywords, + p.meta_description, + b.name as brand, + b.url as brand_url + FROM __products p + $category_id_filter + LEFT JOIN __brands b ON p.brand_id = b.id + WHERE + 1 + $product_id_filter + $brand_id_filter + $features_filter + $keyword_filter + $is_featured_filter + $discounted_filter + $in_stock_filter + $visible_filter + $group_by + ORDER BY $order + $sql_limit"; + + $this->db->query($query); + + return $this->db->results(); + } + + /** + * Функция возвращает количество товаров + * Возможные значения фильтра: + * category_id - id категории или их массив + * brand_id - id бренда или их массив + * keyword - ключевое слово для поиска + * features - фильтр по свойствам товара, массив (id свойства => значение свойства) + */ + public function count_products($filter = array()) + { + $category_id_filter = ''; + $brand_id_filter = ''; + $product_id_filter = ''; + $keyword_filter = ''; + $visible_filter = ''; + $is_featured_filter = ''; + $in_stock_filter = ''; + $discounted_filter = ''; + $features_filter = ''; + + if(!empty($filter['category_id'])) + $category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']); + + if(!empty($filter['brand_id'])) + $brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']); + + if(!empty($filter['id'])) + $product_id_filter = $this->db->placehold('AND p.id in(?@)', (array)$filter['id']); + + if(isset($filter['keyword'])) + { + $keywords = explode(' ', $filter['keyword']); + foreach($keywords as $keyword) + { + $kw = $this->db->escape(trim($keyword)); + if($kw!=='') + $keyword_filter .= $this->db->placehold("AND (p.name LIKE '%$kw%' OR p.meta_keywords LIKE '%$kw%' OR p.id in (SELECT product_id FROM __variants WHERE sku LIKE '%$kw%'))"); + } + } + + if(isset($filter['featured'])) + $is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured'])); + + if(isset($filter['in_stock'])) + $in_stock_filter = $this->db->placehold('AND (SELECT count(*)>0 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock'])); + + if(isset($filter['discounted'])) + $discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted'])); + + if(isset($filter['visible'])) + $visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible'])); + + + if(!empty($filter['features']) && !empty($filter['features'])) + foreach($filter['features'] as $feature=>$value) + $features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value); + + $query = "SELECT count(distinct p.id) as count + FROM __products AS p + $category_id_filter + WHERE 1 + $brand_id_filter + $product_id_filter + $keyword_filter + $is_featured_filter + $in_stock_filter + $discounted_filter + $visible_filter + $features_filter "; + + $this->db->query($query); + return $this->db->result('count'); + } + + + /** + * Функция возвращает товар по id + * @param $id + * @retval object + */ + public function get_product($id) + { + if(is_int($id)) + $filter = $this->db->placehold('p.id = ?', $id); + else + $filter = $this->db->placehold('p.url = ?', $id); + + $query = "SELECT DISTINCT + p.id, + p.url, + p.brand_id, + p.name, + p.annotation, + p.body, + p.position, + p.created as created, + p.visible, + p.featured, + p.meta_title, + p.meta_keywords, + p.meta_description + FROM __products AS p + WHERE $filter + GROUP BY p.id + LIMIT 1"; + $this->db->query($query); + $product = $this->db->result(); + return $product; + } + + public function update_product($id, $product) + { + $query = $this->db->placehold("UPDATE __products SET ?% WHERE id in (?@) LIMIT ?", $product, (array)$id, count((array)$id)); + if($this->db->query($query)) + return $id; + else + return false; + } + + public function add_product($product) + { + $product = (array) $product; + + if(empty($product['url'])) + { + $product['url'] = preg_replace("/[\s]+/ui", '-', $product['name']); + $product['url'] = strtolower(preg_replace("/[^0-9a-zа-я\-]+/ui", '', $product['url'])); + } + + // Если есть товар с таким URL, добавляем к нему число + while($this->get_product((string)$product['url'])) + { + if(preg_match('/(.+)_([0-9]+)$/', $product['url'], $parts)) + $product['url'] = $parts[1].'_'.($parts[2]+1); + else + $product['url'] = $product['url'].'_2'; + } + + if($this->db->query("INSERT INTO __products SET ?%", $product)) + { + $id = $this->db->insert_id(); + $this->db->query("UPDATE __products SET position=id WHERE id=?", $id); + return $id; + } + else + return false; + } + + + /* + * + * Удалить товар + * + */ + public function delete_product($id) + { + if(!empty($id)) + { + // Удаляем варианты + $variants = $this->variants->get_variants(array('product_id'=>$id)); + foreach($variants as $v) + $this->variants->delete_variant($v->id); + + // Удаляем изображения + $images = $this->get_images(array('product_id'=>$id)); + foreach($images as $i) + $this->delete_image($i->id); + + // Удаляем категории + $categories = $this->categories->get_categories(array('product_id'=>$id)); + foreach($categories as $c) + $this->categories->delete_product_category($id, $c->id); + + // Удаляем свойства + $options = $this->features->get_options(array('product_id'=>$id)); + foreach($options as $o) + $this->features->delete_option($id, $o->feature_id); + + // Удаляем связанные товары + $related = $this->get_related_products($id); + foreach($related as $r) + $this->delete_related_product($id, $r->related_id); + + // Удаляем товар из связанных с другими + $query = $this->db->placehold("DELETE FROM __related_products WHERE related_id=?", intval($id)); + $this->db->query($query); + + // Удаляем отзывы + $comments = $this->comments->get_comments(array('object_id'=>$id, 'type'=>'product')); + foreach($comments as $c) + $this->comments->delete_comment($c->id); + + // Удаляем из покупок + $this->db->query('UPDATE __purchases SET product_id=NULL WHERE product_id=?', intval($id)); + + // Удаляем товар + $query = $this->db->placehold("DELETE FROM __products WHERE id=? LIMIT 1", intval($id)); + if($this->db->query($query)) + return true; + } + return false; + } + + public function duplicate_product($id) + { + $product = $this->get_product($id); + $product->id = null; + $product->external_id = ''; + $product->created = null; + + // Сдвигаем товары вперед и вставляем копию на соседнюю позицию + $this->db->query('UPDATE __products SET position=position+1 WHERE position>?', $product->position); + $new_id = $this->products->add_product($product); + $this->db->query('UPDATE __products SET position=? WHERE id=?', $product->position+1, $new_id); + + // Очищаем url + $this->db->query('UPDATE __products SET url="" WHERE id=?', $new_id); + + // Дублируем категории + $categories = $this->categories->get_product_categories($id); + foreach($categories as $c) + $this->categories->add_product_category($new_id, $c->category_id); + + // Дублируем изображения + $images = $this->get_images(array('product_id'=>$id)); + foreach($images as $image) + $this->add_image($new_id, $image->filename); + + // Дублируем варианты + $variants = $this->variants->get_variants(array('product_id'=>$id)); + foreach($variants as $variant) + { + $variant->product_id = $new_id; + unset($variant->id); + if($variant->infinity) + $variant->stock = null; + unset($variant->infinity); + $variant->external_id = ''; + $this->variants->add_variant($variant); + } + + // Дублируем свойства + $options = $this->features->get_options(array('product_id'=>$id)); + foreach($options as $o) + $this->features->update_option($new_id, $o->feature_id, $o->value); + + // Дублируем связанные товары + $related = $this->get_related_products($id); + foreach($related as $r) + $this->add_related_product($new_id, $r->related_id); + + + return $new_id; + } + + + public function get_related_products($product_id = array()) + { + if(empty($product_id)) + return array(); + + $product_id_filter = $this->db->placehold('AND product_id in(?@)', (array)$product_id); + + $query = $this->db->placehold("SELECT product_id, related_id, position + FROM __related_products + WHERE + 1 + $product_id_filter + ORDER BY position + "); + + $this->db->query($query); + return $this->db->results(); + } + + // Функция возвращает связанные товары + public function add_related_product($product_id, $related_id, $position=0) + { + $query = $this->db->placehold("INSERT IGNORE INTO __related_products SET product_id=?, related_id=?, position=?", $product_id, $related_id, $position); + $this->db->query($query); + return $related_id; + } + + // Удаление связанного товара + public function delete_related_product($product_id, $related_id) + { + $query = $this->db->placehold("DELETE FROM __related_products WHERE product_id=? AND related_id=? LIMIT 1", intval($product_id), intval($related_id)); + $this->db->query($query); + } + + + public function get_images($filter = array()) + { + $product_id_filter = ''; + $group_by = ''; + + if(!empty($filter['product_id'])) + $product_id_filter = $this->db->placehold('AND i.product_id in(?@)', (array)$filter['product_id']); + + // images + $query = $this->db->placehold("SELECT i.id, i.product_id, i.name, i.filename, i.position + FROM __images AS i WHERE 1 $product_id_filter $group_by ORDER BY i.product_id, i.position"); + $this->db->query($query); + return $this->db->results(); + } + + public function add_image($product_id, $filename, $name = '') + { + $query = $this->db->placehold("SELECT id FROM __images WHERE product_id=? AND filename=?", $product_id, $filename); + $this->db->query($query); + $id = $this->db->result('id'); + if(empty($id)) + { + $query = $this->db->placehold("INSERT INTO __images SET product_id=?, filename=?", $product_id, $filename); + $this->db->query($query); + $id = $this->db->insert_id(); + $query = $this->db->placehold("UPDATE __images SET position=id WHERE id=?", $id); + $this->db->query($query); + } + return($id); + } + + public function update_image($id, $image) + { + + $query = $this->db->placehold("UPDATE __images SET ?% WHERE id=?", $image, $id); + $this->db->query($query); + + return($id); + } + + public function delete_image($id) + { + $query = $this->db->placehold("SELECT filename FROM __images WHERE id=?", $id); + $this->db->query($query); + $filename = $this->db->result('filename'); + $query = $this->db->placehold("DELETE FROM __images WHERE id=? LIMIT 1", $id); + $this->db->query($query); + $query = $this->db->placehold("SELECT count(*) as count FROM __images WHERE filename=? LIMIT 1", $filename); + $this->db->query($query); + $count = $this->db->result('count'); + if($count == 0) + { + $file = pathinfo($filename, PATHINFO_FILENAME); + $ext = pathinfo($filename, PATHINFO_EXTENSION); + + // Удалить все ресайзы + $rezised_images = glob($this->config->root_dir.$this->config->resized_images_dir.$file.".*x*.".$ext); + if(is_array($rezised_images)) + foreach (glob($this->config->root_dir.$this->config->resized_images_dir.$file.".*x*.".$ext) as $f) + @unlink($f); + + @unlink($this->config->root_dir.$this->config->original_images_dir.$filename); + } + } + + /* + * + * Следующий товар + * + */ + public function get_next_product($id) + { + $this->db->query("SELECT position FROM __products WHERE id=? LIMIT 1", $id); + $position = $this->db->result('position'); + + $this->db->query("SELECT pc.category_id FROM __products_categories pc WHERE product_id=? ORDER BY position LIMIT 1", $id); + $category_id = $this->db->result('category_id'); + + $query = $this->db->placehold("SELECT id FROM __products p, __products_categories pc + WHERE pc.product_id=p.id AND p.position>? + AND pc.position=(SELECT MIN(pc2.position) FROM __products_categories pc2 WHERE pc.product_id=pc2.product_id) + AND pc.category_id=? + AND p.visible ORDER BY p.position limit 1", $position, $category_id); + $this->db->query($query); + + return $this->get_product((integer)$this->db->result('id')); + } + + /* + * + * Предыдущий товар + * + */ + public function get_prev_product($id) + { + $this->db->query("SELECT position FROM __products WHERE id=? LIMIT 1", $id); + $position = $this->db->result('position'); + + $this->db->query("SELECT pc.category_id FROM __products_categories pc WHERE product_id=? ORDER BY position LIMIT 1", $id); + $category_id = $this->db->result('category_id'); + + $query = $this->db->placehold("SELECT id FROM __products p, __products_categories pc + WHERE pc.product_id=p.id AND p.positiondb->query($query); + + return $this->get_product((integer)$this->db->result('id')); + } + + +} diff --git a/api/Request.php b/api/Request.php index ecd1f05..ef98bcd 100755 --- a/api/Request.php +++ b/api/Request.php @@ -1,319 +1,320 @@ -stripslashes_recursive($_POST); - $_GET = $this->stripslashes_recursive($_GET); - $_COOKIE = $this->stripslashes_recursive($_COOKIE); - $_REQUEST = $this->stripslashes_recursive($_REQUEST); - } - - } - - /** - * Определение request-метода обращения к странице (GET, POST) - * Если задан аргумент функции (название метода, в любом регистре), возвращает true или false - * Если аргумент не задан, возвращает имя метода - * Пример: - * - * if($simpla->request->method('post')) - * print 'Request method is POST'; - * - */ - public function method($method = null) - { - if(!empty($method)) - return strtolower($_SERVER['REQUEST_METHOD']) == strtolower($method); - return $_SERVER['REQUEST_METHOD']; - } - - /** - * Возвращает переменную _GET, отфильтрованную по заданному типу, если во втором параметре указан тип фильтра - * Второй параметр $type может иметь такие значения: integer, string, boolean - * Если $type не задан, возвращает переменную в чистом виде - */ - public function get($name, $type = null) - { - $val = null; - if(isset($_GET[$name])) - $val = $_GET[$name]; - - if(!empty($type) && is_array($val)) - $val = reset($val); - - if($type == 'string') - return strval(preg_replace('/[^\p{L}\p{Nd}\d\s_\-\.\%\s]/ui', '', $val)); - - if($type == 'integer') - return intval($val); - - if($type == 'boolean') - return !empty($val); - - return $val; - } - - /** - * Возвращает переменную _POST, отфильтрованную по заданному типу, если во втором параметре указан тип фильтра - * Второй параметр $type может иметь такие значения: integer, string, boolean - * Если $type не задан, возвращает переменную в чистом виде - */ - public function post($name = null, $type = null) - { - $val = null; - if(!empty($name) && isset($_POST[$name])) - $val = $_POST[$name]; - elseif(empty($name)) - $val = file_get_contents('php://input'); - - if($type == 'string') - return strval(preg_replace('/[^\p{L}\p{Nd}\d\s_\-\.\%\s]/ui', '', $val)); - - if($type == 'integer') - return intval($val); - - if($type == 'boolean') - return !empty($val); - - return $val; - } - - /** - * Возвращает переменную _FILES - * Обычно переменные _FILES являются двухмерными массивами, поэтому можно указать второй параметр, - * например, чтобы получить имя загруженного файла: $filename = $simpla->request->files('myfile', 'name'); - */ - public function files($name, $name2 = null) - { - if(!empty($name2) && !empty($_FILES[$name][$name2])) - return $_FILES[$name][$name2]; - elseif(empty($name2) && !empty($_FILES[$name])) - return $_FILES[$name]; - else - return null; - } - - /** - * Рекурсивная чистка магических слешей - */ - - private function stripslashes_recursive($var) - { - if (is_array($var)) - { - $res = array(); - foreach($var as $k => $v) - $res[$this->stripslashes_recursive($k)] = $this->stripslashes_recursive($v); - - return $res; - } - else - { - return stripslashes($var); - } - } - - - /** - * Проверка сессии - */ - public function check_session() - { - if(!empty($_POST)) - { - if(empty($_POST['session_id']) || $_POST['session_id'] != session_id()) - { - unset($_POST); - return false; - } - } - return true; - } - - - /** - * URL - */ - public function url($params = array()) - { - $url = @parse_url($_SERVER["REQUEST_URI"]); - parse_str($url['query'], $query); - - if(get_magic_quotes_gpc()) - foreach($query as &$v) - { - if(!is_array($v)) - $v = stripslashes(urldecode($v)); - } - - foreach($params as $name=>$value) - $query[$name] = $value; - - $query_is_empty = true; - foreach($query as $name=>$value) - if($value!=='' && $value!==null) - $query_is_empty = false; - - if(!$query_is_empty) - $url['query'] = http_build_query($query); - else - $url['query'] = null; - - $result = http_build_url(null, $url); - return $result; - } -} - - -if (!function_exists('http_build_url')) -{ - define('HTTP_URL_REPLACE', 1); // Replace every part of the first URL when there's one of the second URL - define('HTTP_URL_JOIN_PATH', 2); // Join relative paths - define('HTTP_URL_JOIN_QUERY', 4); // Join query strings - define('HTTP_URL_STRIP_USER', 8); // Strip any user authentication information - define('HTTP_URL_STRIP_PASS', 16); // Strip any password authentication information - define('HTTP_URL_STRIP_AUTH', 32); // Strip any authentication information - define('HTTP_URL_STRIP_PORT', 64); // Strip explicit port numbers - define('HTTP_URL_STRIP_PATH', 128); // Strip complete path - define('HTTP_URL_STRIP_QUERY', 256); // Strip query string - define('HTTP_URL_STRIP_FRAGMENT', 512); // Strip any fragments (#identifier) - define('HTTP_URL_STRIP_ALL', 1024); // Strip anything but scheme and host - - // Build an URL - // The parts of the second URL will be merged into the first according to the flags argument. - // - // @param mixed (Part(s) of) an URL in form of a string or associative array like parse_url() returns - // @param mixed Same as the first argument - // @param int A bitmask of binary or'ed HTTP_URL constants (Optional)HTTP_URL_REPLACE is the default - // @param array If set, it will be filled with the parts of the composed url like parse_url() would return - function http_build_url($url, $parts=array(), $flags=HTTP_URL_REPLACE, &$new_url=false) - { - $keys = array('user','pass','port','path','query','fragment'); - - // HTTP_URL_STRIP_ALL becomes all the HTTP_URL_STRIP_Xs - if ($flags & HTTP_URL_STRIP_ALL) - { - $flags |= HTTP_URL_STRIP_USER; - $flags |= HTTP_URL_STRIP_PASS; - $flags |= HTTP_URL_STRIP_PORT; - $flags |= HTTP_URL_STRIP_PATH; - $flags |= HTTP_URL_STRIP_QUERY; - $flags |= HTTP_URL_STRIP_FRAGMENT; - } - // HTTP_URL_STRIP_AUTH becomes HTTP_URL_STRIP_USER and HTTP_URL_STRIP_PASS - else if ($flags & HTTP_URL_STRIP_AUTH) - { - $flags |= HTTP_URL_STRIP_USER; - $flags |= HTTP_URL_STRIP_PASS; - } - - // Parse the original URL - $parse_url = parse_url($url); - - // Scheme and Host are always replaced - if (isset($parts['scheme'])) - $parse_url['scheme'] = $parts['scheme']; - if (isset($parts['host'])) - $parse_url['host'] = $parts['host']; - - // (If applicable) Replace the original URL with it's new parts - if ($flags & HTTP_URL_REPLACE) - { - foreach ($keys as $key) - { - if (isset($parts[$key])) - $parse_url[$key] = $parts[$key]; - } - } - else - { - // Join the original URL path with the new path - if (isset($parts['path']) && ($flags & HTTP_URL_JOIN_PATH)) - { - if (isset($parse_url['path'])) - $parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '', $parse_url['path']), '/') . '/' . ltrim($parts['path'], '/'); - else - $parse_url['path'] = $parts['path']; - } - - // Join the original query string with the new query string - if (isset($parts['query']) && ($flags & HTTP_URL_JOIN_QUERY)) - { - if (isset($parse_url['query'])) - $parse_url['query'] .= '&' . $parts['query']; - else - $parse_url['query'] = $parts['query']; - } - } - - // Strips all the applicable sections of the URL - // Note: Scheme and Host are never stripped - foreach ($keys as $key) - { - if ($flags & (int)constant('HTTP_URL_STRIP_' . strtoupper($key))) - unset($parse_url[$key]); - } - - - $new_url = $parse_url; - - return - ((isset($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '') - .((isset($parse_url['user'])) ? $parse_url['user'] . ((isset($parse_url['pass'])) ? ':' . $parse_url['pass'] : '') .'@' : '') - .((isset($parse_url['host'])) ? $parse_url['host'] : '') - .((isset($parse_url['port'])) ? ':' . $parse_url['port'] : '') - .((isset($parse_url['path'])) ? $parse_url['path'] : '') - .((isset($parse_url['query'])) ? '?' . $parse_url['query'] : '') - .((isset($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '') - ; - } -} - -if(!function_exists('http_build_query')) { - function http_build_query($data,$prefix=null,$sep='',$key='') { - $ret = array(); - foreach((array)$data as $k => $v) { - $k = urlencode($k); - if(is_int($k) && $prefix != null) { - $k = $prefix.$k; - }; - if(!empty($key)) { - $k = $key."[".$k."]"; - }; - - if(is_array($v) || is_object($v)) { - array_push($ret,http_build_query($v,"",$sep,$k)); - } - else { - array_push($ret,$k."=".urlencode($v)); - }; - }; - - if(empty($sep)) { - $sep = ini_get("arg_separator.output"); - }; - - return implode($sep, $ret); - }; -}; +stripslashes_recursive($_POST); + $_GET = $this->stripslashes_recursive($_GET); + $_COOKIE = $this->stripslashes_recursive($_COOKIE); + $_REQUEST = $this->stripslashes_recursive($_REQUEST); + } + + } + + /** + * Определение request-метода обращения к странице (GET, POST) + * Если задан аргумент функции (название метода, в любом регистре), возвращает true или false + * Если аргумент не задан, возвращает имя метода + * Пример: + * + * if($simpla->request->method('post')) + * print 'Request method is POST'; + * + */ + public function method($method = null) + { + if(!empty($method)) + return strtolower($_SERVER['REQUEST_METHOD']) == strtolower($method); + return $_SERVER['REQUEST_METHOD']; + } + + /** + * Возвращает переменную _GET, отфильтрованную по заданному типу, если во втором параметре указан тип фильтра + * Второй параметр $type может иметь такие значения: integer, string, boolean + * Если $type не задан, возвращает переменную в чистом виде + */ + public function get($name, $type = null) + { + $val = null; + if(isset($_GET[$name])) + $val = $_GET[$name]; + + if(!empty($type) && is_array($val)) + $val = reset($val); + + if($type == 'string') + return strval(preg_replace('/[^\p{L}\p{Nd}\d\s_\-\.\%\s]/ui', '', $val)); + + if($type == 'integer') + return intval($val); + + if($type == 'boolean') + return !empty($val); + + return $val; + } + + /** + * Возвращает переменную _POST, отфильтрованную по заданному типу, если во втором параметре указан тип фильтра + * Второй параметр $type может иметь такие значения: integer, string, boolean + * Если $type не задан, возвращает переменную в чистом виде + */ + public function post($name = null, $type = null) + { + $val = null; + if(!empty($name) && isset($_POST[$name])) + $val = $_POST[$name]; + elseif(empty($name)) + $val = file_get_contents('php://input'); + + if($type == 'string') + return strval(preg_replace('/[^\p{L}\p{Nd}\d\s_\-\.\%\s]/ui', '', $val)); + + if($type == 'integer') + return intval($val); + + if($type == 'boolean') + return !empty($val); + + return $val; + } + + /** + * Возвращает переменную _FILES + * Обычно переменные _FILES являются двухмерными массивами, поэтому можно указать второй параметр, + * например, чтобы получить имя загруженного файла: $filename = $simpla->request->files('myfile', 'name'); + */ + public function files($name, $name2 = null) + { + if(!empty($name2) && !empty($_FILES[$name][$name2])) + return $_FILES[$name][$name2]; + elseif(empty($name2) && !empty($_FILES[$name])) + return $_FILES[$name]; + else + return null; + } + + /** + * Рекурсивная чистка магических слешей + */ + + private function stripslashes_recursive($var) + { + if (is_array($var)) + { + $res = array(); + foreach($var as $k => $v) + $res[$this->stripslashes_recursive($k)] = $this->stripslashes_recursive($v); + + return $res; + } + else + { + return stripslashes($var); + } + } + + + /** + * Проверка сессии + */ + public function check_session() + { + if(!empty($_POST)) + { + if(empty($_POST['session_id']) || $_POST['session_id'] != session_id()) + { + unset($_POST); + return false; + } + } + return true; + } + + + /** + * URL + */ + public function url($params = array()) + { + $url = @parse_url($_SERVER["REQUEST_URI"]); + parse_str($url['query'], $query); + + if(get_magic_quotes_gpc()) + foreach($query as &$v) + { + if(!is_array($v)) + $v = stripslashes(urldecode($v)); + } + + foreach($params as $name=>$value) + $query[$name] = $value; + + $query_is_empty = true; + foreach($query as $name=>$value) + if($value!=='' && $value!==null) + $query_is_empty = false; + + if(!$query_is_empty) + $url['query'] = http_build_query($query); + else + $url['query'] = null; + + $result = http_build_url(null, $url); + return $result; + } +} + + +if (!function_exists('http_build_url')) +{ + define('HTTP_URL_REPLACE', 1); // Replace every part of the first URL when there's one of the second URL + define('HTTP_URL_JOIN_PATH', 2); // Join relative paths + define('HTTP_URL_JOIN_QUERY', 4); // Join query strings + define('HTTP_URL_STRIP_USER', 8); // Strip any user authentication information + define('HTTP_URL_STRIP_PASS', 16); // Strip any password authentication information + define('HTTP_URL_STRIP_AUTH', 32); // Strip any authentication information + define('HTTP_URL_STRIP_PORT', 64); // Strip explicit port numbers + define('HTTP_URL_STRIP_PATH', 128); // Strip complete path + define('HTTP_URL_STRIP_QUERY', 256); // Strip query string + define('HTTP_URL_STRIP_FRAGMENT', 512); // Strip any fragments (#identifier) + define('HTTP_URL_STRIP_ALL', 1024); // Strip anything but scheme and host + + // Build an URL + // The parts of the second URL will be merged into the first according to the flags argument. + // + // @param mixed (Part(s) of) an URL in form of a string or associative array like parse_url() returns + // @param mixed Same as the first argument + // @param int A bitmask of binary or'ed HTTP_URL constants (Optional)HTTP_URL_REPLACE is the default + // @param array If set, it will be filled with the parts of the composed url like parse_url() would return + function http_build_url($url, $parts=array(), $flags=HTTP_URL_REPLACE, &$new_url=false) + { + $keys = array('user','pass','port','path','query','fragment'); + + // HTTP_URL_STRIP_ALL becomes all the HTTP_URL_STRIP_Xs + if ($flags & HTTP_URL_STRIP_ALL) + { + $flags |= HTTP_URL_STRIP_USER; + $flags |= HTTP_URL_STRIP_PASS; + $flags |= HTTP_URL_STRIP_PORT; + $flags |= HTTP_URL_STRIP_PATH; + $flags |= HTTP_URL_STRIP_QUERY; + $flags |= HTTP_URL_STRIP_FRAGMENT; + } + // HTTP_URL_STRIP_AUTH becomes HTTP_URL_STRIP_USER and HTTP_URL_STRIP_PASS + else if ($flags & HTTP_URL_STRIP_AUTH) + { + $flags |= HTTP_URL_STRIP_USER; + $flags |= HTTP_URL_STRIP_PASS; + } + + // Parse the original URL + $parse_url = parse_url($url); + + // Scheme and Host are always replaced + if (isset($parts['scheme'])) + $parse_url['scheme'] = $parts['scheme']; + if (isset($parts['host'])) + $parse_url['host'] = $parts['host']; + + // (If applicable) Replace the original URL with it's new parts + if ($flags & HTTP_URL_REPLACE) + { + foreach ($keys as $key) + { + if (isset($parts[$key])) + $parse_url[$key] = $parts[$key]; + } + } + else + { + // Join the original URL path with the new path + if (isset($parts['path']) && ($flags & HTTP_URL_JOIN_PATH)) + { + if (isset($parse_url['path'])) + $parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '', $parse_url['path']), '/') . '/' . ltrim($parts['path'], '/'); + else + $parse_url['path'] = $parts['path']; + } + + // Join the original query string with the new query string + if (isset($parts['query']) && ($flags & HTTP_URL_JOIN_QUERY)) + { + if (isset($parse_url['query'])) + $parse_url['query'] .= '&' . $parts['query']; + else + $parse_url['query'] = $parts['query']; + } + } + + // Strips all the applicable sections of the URL + // Note: Scheme and Host are never stripped + foreach ($keys as $key) + { + if ($flags & (int)constant('HTTP_URL_STRIP_' . strtoupper($key))) + unset($parse_url[$key]); + } + + + $new_url = $parse_url; + + return + ((isset($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '') + .((isset($parse_url['user'])) ? $parse_url['user'] . ((isset($parse_url['pass'])) ? ':' . $parse_url['pass'] : '') .'@' : '') + .((isset($parse_url['host'])) ? $parse_url['host'] : '') + .((isset($parse_url['port'])) ? ':' . $parse_url['port'] : '') + .((isset($parse_url['path'])) ? $parse_url['path'] : '') + .((isset($parse_url['query'])) ? '?' . $parse_url['query'] : '') + .((isset($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '') + ; + } +} + +if(!function_exists('http_build_query')) { + function http_build_query($data,$prefix=null,$sep='',$key='') { + $ret = array(); + foreach((array)$data as $k => $v) { + $k = urlencode($k); + if(is_int($k) && $prefix != null) { + $k = $prefix.$k; + }; + if(!empty($key)) { + $k = $key."[".$k."]"; + }; + + if(is_array($v) || is_object($v)) { + array_push($ret,http_build_query($v,"",$sep,$k)); + } + else { + array_push($ret,$k."=".urlencode($v)); + }; + }; + + if(empty($sep)) { + $sep = ini_get("arg_separator.output"); + }; + + return implode($sep, $ret); + }; +}; diff --git a/api/Settings.php b/api/Settings.php index b621e40..cb7bb52 100755 --- a/api/Settings.php +++ b/api/Settings.php @@ -1,46 +1,45 @@ db->query('SELECT name, value FROM __settings'); - // и записываем их в переменную + // и записываем их в переменную foreach($this->db->results() as $result) if(!($this->vars[$result->name] = @unserialize($result->value))) $this->vars[$result->name] = $result->value; } - + public function __get($name) { if($res = parent::__get($name)) return $res; - + if(isset($this->vars[$name])) return $this->vars[$name]; else return null; } - + public function __set($name, $value) { $this->vars[$name] = $value; @@ -49,11 +48,11 @@ public function __set($name, $value) $value = serialize($value); else $value = (string) $value; - + $this->db->query('SELECT count(*) as count FROM __settings WHERE name=?', $name); if($this->db->result('count')>0) $this->db->query('UPDATE __settings SET value=? WHERE name=?', $value, $name); else $this->db->query('INSERT INTO __settings SET value=?, name=?', $value, $name); } -} \ No newline at end of file +} diff --git a/api/Simpla.php b/api/Simpla.php index 4658450..3c20bd1 100755 --- a/api/Simpla.php +++ b/api/Simpla.php @@ -1,82 +1,85 @@ - 'Config', - 'request' => 'Request', - 'db' => 'Database', - 'settings' => 'Settings', - 'design' => 'Design', - 'products' => 'Products', - 'variants' => 'Variants', - 'categories' => 'Categories', - 'brands' => 'Brands', - 'features' => 'Features', - 'money' => 'Money', - 'pages' => 'Pages', - 'blog' => 'Blog', - 'cart' => 'Cart', - 'image' => 'Image', - 'delivery' => 'Delivery', - 'payment' => 'Payment', - 'orders' => 'Orders', - 'users' => 'Users', - 'coupons' => 'Coupons', - 'comments' => 'Comments', - 'feedbacks' => 'Feedbacks', - 'notify' => 'Notify', - 'managers' => 'Managers' - ); - - // Созданные объекты - private static $objects = array(); - - /** - * Конструктор оставим пустым, но определим его на случай обращения parent::__construct() в классах API - */ - public function __construct() - { - //error_reporting(E_ALL & !E_STRICT); - } - - /** - * Магический метод, создает нужный объект API - */ - public function __get($name) - { - // Если такой объект уже существует, возвращаем его - if(isset(self::$objects[$name])) - { - return(self::$objects[$name]); - } - - // Если запрошенного API не существует - ошибка - if(!array_key_exists($name, $this->classes)) - { - return null; - } - - // Определяем имя нужного класса - $class = $this->classes[$name]; - - // Подключаем его - include_once(dirname(__FILE__).'/'.$class.'.php'); - - // Сохраняем для будущих обращений к нему - self::$objects[$name] = new $class(); - - // Возвращаем созданный объект - return self::$objects[$name]; - } -} \ No newline at end of file + 'Config', + 'request' => 'Request', + 'db' => 'Database', + 'settings' => 'Settings', + 'design' => 'Design', + 'products' => 'Products', + 'variants' => 'Variants', + 'categories' => 'Categories', + 'brands' => 'Brands', + 'features' => 'Features', + 'money' => 'Money', + 'pages' => 'Pages', + 'blog' => 'Blog', + 'cart' => 'Cart', + 'image' => 'Image', + 'delivery' => 'Delivery', + 'payment' => 'Payment', + 'orders' => 'Orders', + 'users' => 'Users', + 'coupons' => 'Coupons', + 'comments' => 'Comments', + 'feedbacks' => 'Feedbacks', + 'notify' => 'Notify', + 'managers' => 'Managers' + ); + + // Созданные объекты + private static $objects = array(); + + /** + * Конструктор оставим пустым, но определим его на случай обращения parent::__construct() в классах API + */ + public function __construct() + { + //error_reporting(E_ALL & !E_STRICT); + } + + /** + * Магический метод, создает нужный объект API + */ + public function __get($name) + { + // Если такой объект уже существует, возвращаем его + if(isset(self::$objects[$name])) + { + return(self::$objects[$name]); + } + + // Если запрошенного API не существует - ошибка + if(!array_key_exists($name, $this->classes)) + { + return null; + } + + // Определяем имя нужного класса + $class = $this->classes[$name]; + + // Подключаем его + include_once(dirname(__FILE__).'/'.$class.'.php'); + + // Сохраняем для будущих обращений к нему + self::$objects[$name] = new $class(); + + // Возвращаем созданный объект + return self::$objects[$name]; + } +} diff --git a/api/Users.php b/api/Users.php index 120b0f3..18251a2 100755 --- a/api/Users.php +++ b/api/Users.php @@ -3,24 +3,24 @@ /** * Simpla CMS * - * @copyright 2011 Denis Pikusov + * @copyright 2016 Denis Pikusov * @link http://simplacms.ru * @author Denis Pikusov * */ - + require_once('Simpla.php'); class Users extends Simpla -{ +{ // осторожно, при изменении соли испортятся текущие пароли пользователей - private $salt = '8e86a279d6e182b3c811c559e6b15484'; - - function get_users($filter = array()) + private $salt = '8e86a279d6e182b3c811c559e6b15484'; + + public function get_users($filter = array()) { $limit = 1000; $page = 1; - $group_id_filter = ''; + $group_id_filter = ''; $keyword_filter = ''; if(isset($filter['limit'])) @@ -31,14 +31,14 @@ function get_users($filter = array()) if(isset($filter['group_id'])) $group_id_filter = $this->db->placehold('AND u.group_id in(?@)', (array)$filter['group_id']); - + if(isset($filter['keyword'])) { $keywords = explode(' ', $filter['keyword']); foreach($keywords as $keyword) $keyword_filter .= $this->db->placehold('AND (u.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR u.email LIKE "%'.$this->db->escape(trim($keyword)).'%" OR u.last_ip LIKE "%'.$this->db->escape(trim($keyword)).'%")'); } - + $order = 'u.name'; if(!empty($filter['sort'])) switch ($filter['sort']) @@ -50,25 +50,25 @@ function get_users($filter = array()) $order = 'u.name'; break; } - + $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); // Выбираем пользователей $query = $this->db->placehold("SELECT u.id, u.email, u.password, u.name, u.group_id, u.enabled, u.last_ip, u.created, g.discount, g.name as group_name FROM __users u - LEFT JOIN __groups g ON u.group_id=g.id + LEFT JOIN __groups g ON u.group_id=g.id WHERE 1 $group_id_filter $keyword_filter ORDER BY $order $sql_limit"); $this->db->query($query); return $this->db->results(); } - - function count_users($filter = array()) + + public function count_users($filter = array()) { - $group_id_filter = ''; + $group_id_filter = ''; $keyword_filter = ''; if(isset($filter['group_id'])) $group_id_filter = $this->db->placehold('AND u.group_id in(?@)', (array)$filter['group_id']); - + if(isset($filter['keyword'])) { $keywords = explode(' ', $filter['keyword']); @@ -78,19 +78,19 @@ function count_users($filter = array()) // Выбираем пользователей $query = $this->db->placehold("SELECT count(*) as count FROM __users u - LEFT JOIN __groups g ON u.group_id=g.id + LEFT JOIN __groups g ON u.group_id=g.id WHERE 1 $group_id_filter $keyword_filter"); $this->db->query($query); return $this->db->result('count'); } - - function get_user($id) + + public function get_user($id) { if(gettype($id) == 'string') $where = $this->db->placehold(' WHERE u.email=? ', $id); else $where = $this->db->placehold(' WHERE u.id=? ', intval($id)); - + // Выбираем пользователя $query = $this->db->placehold("SELECT u.id, u.email, u.password, u.name, u.group_id, u.enabled, u.last_ip, u.created, g.discount, g.name as group_name FROM __users u LEFT JOIN __groups g ON u.group_id=g.id $where LIMIT 1", $id); $this->db->query($query); @@ -100,24 +100,24 @@ function get_user($id) $user->discount *= 1; // Убираем лишние нули, чтобы было 5 вместо 5.00 return $user; } - + public function add_user($user) { $user = (array)$user; if(isset($user['password'])) $user['password'] = md5($this->salt.$user['password'].md5($user['password'])); - + $query = $this->db->placehold("SELECT count(*) as count FROM __users WHERE email=?", $user['email']); $this->db->query($query); - + if($this->db->result('count') > 0) return false; - + $query = $this->db->placehold("INSERT INTO __users SET ?%", $user); $this->db->query($query); return $this->db->insert_id(); } - + public function update_user($id, $user) { $user = (array)$user; @@ -127,36 +127,36 @@ public function update_user($id, $user) $this->db->query($query); return $id; } - + /* * * Удалить пользователя * @param $post * - */ + */ public function delete_user($id) { if(!empty($id)) { $query = $this->db->placehold("UPDATE __orders SET user_id=NULL WHERE id=? LIMIT 1", intval($id)); $this->db->query($query); - + $query = $this->db->placehold("DELETE FROM __users WHERE id=? LIMIT 1", intval($id)); if($this->db->query($query)) return true; } return false; - } - - function get_groups() + } + + public function get_groups() { // Выбираем группы $query = $this->db->placehold("SELECT g.id, g.name, g.discount FROM __groups AS g ORDER BY g.discount"); $this->db->query($query); return $this->db->results(); - } - - function get_group($id) + } + + public function get_group($id) { // Выбираем группу $query = $this->db->placehold("SELECT * FROM __groups WHERE id=? LIMIT 1", $id); @@ -164,37 +164,37 @@ function get_group($id) $group = $this->db->result(); return $group; - } - - + } + + public function add_group($group) { $query = $this->db->placehold("INSERT INTO __groups SET ?%", $group); $this->db->query($query); return $this->db->insert_id(); } - + public function update_group($id, $group) { $query = $this->db->placehold("UPDATE __groups SET ?% WHERE id=? LIMIT 1", $group, intval($id)); $this->db->query($query); return $id; } - + public function delete_group($id) { if(!empty($id)) { $query = $this->db->placehold("UPDATE __users SET group_id=NULL WHERE group_id=? LIMIT 1", intval($id)); $this->db->query($query); - + $query = $this->db->placehold("DELETE FROM __groups WHERE id=? LIMIT 1", intval($id)); if($this->db->query($query)) return true; } return false; - } - + } + public function check_password($email, $password) { $encpassword = md5($this->salt.$password.md5($password)); @@ -202,7 +202,8 @@ public function check_password($email, $password) $this->db->query($query); if($id = $this->db->result('id')) return $id; + return false; } - + } diff --git a/api/Variants.php b/api/Variants.php index badcaf2..2a19130 100755 --- a/api/Variants.php +++ b/api/Variants.php @@ -1,106 +1,107 @@ -db->placehold('AND v.product_id in(?@)', (array)$filter['product_id']); - - if(!empty($filter['id'])) - $variant_id_filter = $this->db->placehold('AND v.id in(?@)', (array)$filter['id']); - - if(!empty($filter['in_stock']) && $filter['in_stock']) - $instock_filter = $this->db->placehold('AND (v.stock>0 OR v.stock IS NULL)'); - - if(!$product_id_filter && !$variant_id_filter) - return array(); - - $query = $this->db->placehold("SELECT v.id, v.product_id , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment, v.position - FROM __variants AS v - WHERE - 1 - $product_id_filter - $variant_id_filter - $instock_filter - ORDER BY v.position - ", $this->settings->max_order_amount); - - $this->db->query($query); - return $this->db->results(); - } - - - public function get_variant($id) - { - if(empty($id)) - return false; - - $query = $this->db->placehold("SELECT v.id, v.product_id , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment - FROM __variants v WHERE v.id=? - LIMIT 1", $this->settings->max_order_amount, $id); - - $this->db->query($query); - $variant = $this->db->result(); - return $variant; - } - - public function update_variant($id, $variant) - { - $query = $this->db->placehold("UPDATE __variants SET ?% WHERE id=? LIMIT 1", $variant, intval($id)); - $this->db->query($query); - return $id; - } - - public function add_variant($variant) - { - $query = $this->db->placehold("INSERT INTO __variants SET ?%", $variant); - $this->db->query($query); - return $this->db->insert_id(); - } - - public function delete_variant($id) - { - if(!empty($id)) - { - $this->delete_attachment($id); - $query = $this->db->placehold("DELETE FROM __variants WHERE id = ? LIMIT 1", intval($id)); - $this->db->query($query); - $this->db->query('UPDATE __purchases SET variant_id=NULL WHERE variant_id=?', intval($id)); - } - } - - public function delete_attachment($id) - { - $query = $this->db->placehold("SELECT attachment FROM __variants WHERE id=?", $id); - $this->db->query($query); - $filename = $this->db->result('attachment'); - $query = $this->db->placehold("SELECT 1 FROM __variants WHERE attachment=? AND id!=?", $filename, $id); - $this->db->query($query); - $exists = $this->db->num_rows(); - if(!empty($filename) && $exists == 0) - @unlink($this->config->root_dir.'/'.$this->config->downloads_dir.$filename); - $this->update_variant($id, array('attachment'=>null)); - } - -} \ No newline at end of file +db->placehold('AND v.product_id in(?@)', (array)$filter['product_id']); + + if(!empty($filter['id'])) + $variant_id_filter = $this->db->placehold('AND v.id in(?@)', (array)$filter['id']); + + if(!empty($filter['in_stock']) && $filter['in_stock']) + $instock_filter = $this->db->placehold('AND (v.stock>0 OR v.stock IS NULL)'); + + if(!$product_id_filter && !$variant_id_filter) + return array(); + + $query = $this->db->placehold("SELECT v.id, v.product_id , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment, v.position + FROM __variants AS v + WHERE + 1 + $product_id_filter + $variant_id_filter + $instock_filter + ORDER BY v.position + ", $this->settings->max_order_amount); + + $this->db->query($query); + return $this->db->results(); + } + + + public function get_variant($id) + { + if(empty($id)) + return false; + + $query = $this->db->placehold("SELECT v.id, v.product_id , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment + FROM __variants v WHERE v.id=? + LIMIT 1", $this->settings->max_order_amount, $id); + + $this->db->query($query); + $variant = $this->db->result(); + return $variant; + } + + public function update_variant($id, $variant) + { + $query = $this->db->placehold("UPDATE __variants SET ?% WHERE id=? LIMIT 1", $variant, intval($id)); + $this->db->query($query); + return $id; + } + + public function add_variant($variant) + { + $query = $this->db->placehold("INSERT INTO __variants SET ?%", $variant); + $this->db->query($query); + return $this->db->insert_id(); + } + + public function delete_variant($id) + { + if(!empty($id)) + { + $this->delete_attachment($id); + $query = $this->db->placehold("DELETE FROM __variants WHERE id = ? LIMIT 1", intval($id)); + $this->db->query($query); + $this->db->query('UPDATE __purchases SET variant_id=NULL WHERE variant_id=?', intval($id)); + } + } + + public function delete_attachment($id) + { + $query = $this->db->placehold("SELECT attachment FROM __variants WHERE id=?", $id); + $this->db->query($query); + $filename = $this->db->result('attachment'); + $query = $this->db->placehold("SELECT 1 FROM __variants WHERE attachment=? AND id!=?", $filename, $id); + $this->db->query($query); + $exists = $this->db->num_rows(); + if(!empty($filename) && $exists == 0) + @unlink($this->config->root_dir.'/'.$this->config->downloads_dir.$filename); + $this->update_variant($id, array('attachment'=>null)); + } + +} From c8c7547cf9f8d26f437c81bcdf00edf77bf41ef6 Mon Sep 17 00:00:00 2001 From: Erko Evgen Date: Thu, 17 Mar 2016 12:24:31 +0200 Subject: [PATCH 5/5] code formatting other --- index.php | 176 +++++++++++++++++++++++------------------------ password.php | 28 +++++--- simpla/index.php | 125 +++++++++++++++++---------------- sitemap.php | 13 +++- yandex.php | 18 +++-- 5 files changed, 198 insertions(+), 162 deletions(-) diff --git a/index.php b/index.php index 73b0a5f..4addb47 100755 --- a/index.php +++ b/index.php @@ -1,88 +1,88 @@ -fetch()) !== false) -{ - // Выводим результат - header("Content-type: text/html; charset=UTF-8"); - print $res; - - // Сохраняем последнюю просмотренную страницу в переменной $_SESSION['last_visited_page'] - if(empty($_SESSION['last_visited_page']) || empty($_SESSION['current_page']) || $_SERVER['REQUEST_URI'] !== $_SESSION['current_page']) - { - if(!empty($_SESSION['current_page']) && !empty($_SESSION['last_visited_page']) && $_SESSION['last_visited_page'] !== $_SESSION['current_page']) - $_SESSION['last_visited_page'] = $_SESSION['current_page']; - $_SESSION['current_page'] = $_SERVER['REQUEST_URI']; - } -} -else -{ - // Иначе страница об ошибке - header("http/1.0 404 not found"); - - // Подменим переменную GET, чтобы вывести страницу 404 - $_GET['page_url'] = '404'; - $_GET['module'] = 'PageView'; - print $view->fetch(); -} - - -$p=11; $g=2; $x=7; $r = ''; $s = $x; -$bs = explode(' ', $view->config->license); -foreach($bs as $bl){ - for($i=0, $m=''; $idomains, $l->expiration, $l->comment) = explode('#', $r, 3); - -$l->domains = explode(',', $l->domains); - -$h = getenv("HTTP_HOST"); -if(substr($h, 0, 4) == 'www.') $h = substr($h, 4); -if((!in_array($h, $l->domains) || (strtotime($l->expiration)expiration!='*'))) -{ - print "
Лицензия недействительна
Скрипт интернет-магазина Simpla
"; -} - -// Отладочная информация -if(1) -{ - print ""; -} +fetch()) !== false) +{ + // Выводим результат + header("Content-type: text/html; charset=UTF-8"); + print $res; + + // Сохраняем последнюю просмотренную страницу в переменной $_SESSION['last_visited_page'] + if(empty($_SESSION['last_visited_page']) || empty($_SESSION['current_page']) || $_SERVER['REQUEST_URI'] !== $_SESSION['current_page']) + { + if(!empty($_SESSION['current_page']) && !empty($_SESSION['last_visited_page']) && $_SESSION['last_visited_page'] !== $_SESSION['current_page']) + $_SESSION['last_visited_page'] = $_SESSION['current_page']; + $_SESSION['current_page'] = $_SERVER['REQUEST_URI']; + } +} +else +{ + // Иначе страница об ошибке + header("http/1.0 404 not found"); + + // Подменим переменную GET, чтобы вывести страницу 404 + $_GET['page_url'] = '404'; + $_GET['module'] = 'PageView'; + print $view->fetch(); +} + + +$p=11; $g=2; $x=7; $r = ''; $s = $x; +$bs = explode(' ', $view->config->license); +foreach($bs as $bl){ + for($i=0, $m=''; $idomains, $l->expiration, $l->comment) = explode('#', $r, 3); + +$l->domains = explode(',', $l->domains); + +$h = getenv("HTTP_HOST"); +if(substr($h, 0, 4) == 'www.') $h = substr($h, 4); +if((!in_array($h, $l->domains) || (strtotime($l->expiration)expiration!='*'))) +{ + print "
Лицензия недействительна
Скрипт интернет-магазина Simpla
"; +} + +// Отладочная информация +if(1) +{ + print ""; +} diff --git a/password.php b/password.php index 250f007..768125e 100755 --- a/password.php +++ b/password.php @@ -1,4 +1,14 @@ @@ -16,7 +26,7 @@ div.maindiv{width: 600px; height: 300px; position: relative; left: 50%; top: 100px; margin-left: -300px; } -
+
request->post('new_password')) { // Файл с паролями $passwd_file = $simpla->config->root_dir.'simpla/.passwd'; - + // Удаляем из сесси код, чтобы больше никто не воспользовался ссылкой unset($_SESSION['admin_password_recovery_code']); unset($_SESSION['admin_password_recovery_ip']); @@ -68,7 +78,7 @@ $new_password = $simpla->request->post('new_password'); if(!$simpla->managers->update_manager($new_login, array('password'=>$new_password))) $simpla->managers->add_manager(array('login'=>$new_login, 'password'=>$new_password)); - + print "

Восстановление пароля администратора

@@ -109,7 +119,7 @@ "; $admin_email = $simpla->settings->admin_email; - + if(isset($_POST['email'])) { if($_POST['email'] === $admin_email) @@ -117,11 +127,11 @@ $code = $simpla->config->token(mt_rand(1, mt_getrandmax()).mt_rand(1, mt_getrandmax()).mt_rand(1, mt_getrandmax())); $_SESSION['admin_password_recovery_code'] = $code; $_SESSION['admin_password_recovery_ip'] = $_SERVER['REMOTE_ADDR']; - + $message = 'Вы или кто-то другой запросил ссылку на восстановление пароля администратора.
'; $message .= 'Для смены пароля перейдите по ссылке '.$simpla->config->root_url.'/password.php?code='.$code.'
'; $message .= 'Если письмо пришло вам по ошибке, проигнорируйте его.'; - + $simpla->notify->email($admin_email, 'Восстановление пароля администратора '.$simpla->settings->site_name, $message, $simpla->settings->notify_from_email); } print "Вам отправлена ссылка для восстановления пароля. Если письмо вам не пришло, значит вы неверно указали email или что-то не так с хостингом"; @@ -130,7 +140,7 @@ } ?> -

+
diff --git a/simpla/index.php b/simpla/index.php index 73e42b8..95eacd2 100755 --- a/simpla/index.php +++ b/simpla/index.php @@ -1,58 +1,67 @@ -request->check_session()) -{ - unset($_POST); - trigger_error('Session expired', E_USER_WARNING); -} - - -print $backend->fetch(); - -// Отладочная информация -if($backend->config->debug) -{ - print ""; -} +request->check_session()) +{ + unset($_POST); + trigger_error('Session expired', E_USER_WARNING); +} + + +print $backend->fetch(); + +// Отладочная информация +if($backend->config->debug) +{ + print ""; +} diff --git a/sitemap.php b/sitemap.php index 3833824..4b5036c 100755 --- a/sitemap.php +++ b/sitemap.php @@ -1,5 +1,14 @@ db->query("SELECT v.price, v.id as variant_id, p.name as product_name, v.name as variant_name, v.position as variant_position, p.id as product_id, p.url, p.annotation, pc.category_id, i.filename as image FROM __variants v LEFT JOIN __products p ON v.product_id=p.id - - LEFT JOIN __products_categories pc ON p.id = pc.product_id AND pc.position=(SELECT MIN(position) FROM __products_categories WHERE product_id=p.id LIMIT 1) - LEFT JOIN __images i ON p.id = i.product_id AND i.position=(SELECT MIN(position) FROM __images WHERE product_id=p.id LIMIT 1) + + LEFT JOIN __products_categories pc ON p.id = pc.product_id AND pc.position=(SELECT MIN(position) FROM __products_categories WHERE product_id=p.id LIMIT 1) + LEFT JOIN __images i ON p.id = i.product_id AND i.position=(SELECT MIN(position) FROM __images WHERE product_id=p.id LIMIT 1) WHERE p.visible AND (v.stock >0 OR v.stock is NULL) GROUP BY v.id ORDER BY p.id, v.position "); print " "; - + $currency_code = reset($currencies)->code; @@ -95,4 +103,4 @@ "; print " -"; \ No newline at end of file +";