diff --git a/ajax/cart.php b/ajax/cart.php index 2883de5..d005c41 100755 --- a/ajax/cart.php +++ b/ajax/cart.php @@ -1,34 +1,35 @@ -cart->add_item($this->request->get('variant', 'integer'), $this->request->get('amount', 'integer')); - $cart = $this->cart->get_cart(); - $this->design->assign('cart', $cart); - - $currencies = $this->money->get_currencies(array('enabled'=>1)); - if(isset($_SESSION['currency_id'])) - $currency = $this->money->get_currency($_SESSION['currency_id']); - else - $currency = reset($currencies); - - $this->design->assign('currency', $currency); - - return $this->design->fetch('cart_informer.tpl'); - } - } - - $cart_ajax = new CartAjax(); - $result = $cart_ajax->fetch(); - - header("Content-type: application/json; charset=UTF-8"); - header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); - header("X-Robots-Tag: noindex"); - header("Pragma: no-cache"); - header("Expires: -1"); - print json_encode($result); - exit; +cart->add_item($this->request->get('variant', 'integer'), $this->request->get('amount', 'integer')); + $cart = $this->cart->get_cart(); + $this->design->assign('cart', $cart); + + $currencies = $this->money->get_currencies(array('enabled'=>1)); + if (isset($_SESSION['currency_id'])) { + $currency = $this->money->get_currency($_SESSION['currency_id']); + } else { + $currency = reset($currencies); + } + + $this->design->assign('currency', $currency); + + return $this->design->fetch('cart_informer.tpl'); + } + } + + $cart_ajax = new CartAjax(); + $result = $cart_ajax->fetch(); + + header("Content-type: application/json; charset=UTF-8"); + header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); + header("X-Robots-Tag: noindex"); + header("Pragma: no-cache"); + header("Expires: -1"); + print json_encode($result); + exit; diff --git a/ajax/search_products.php b/ajax/search_products.php index c6f03cc..f0ae94a 100755 --- a/ajax/search_products.php +++ b/ajax/search_products.php @@ -1,55 +1,54 @@ -suggestions = array(); - $result->query = $this->request->get('query', 'string'); - - if(!empty($result->query)) - { - $kw = $this->db->escape($result->query); - - $this->db->query("SELECT p.id, p.name, i.filename as image FROM __products p - LEFT JOIN __images i ON i.product_id=p.id AND i.position=(SELECT MIN(position) FROM __images WHERE product_id=p.id LIMIT 1) - WHERE (p.name LIKE '%$kw%' OR p.meta_keywords LIKE '%$kw%' OR p.id in (SELECT product_id FROM __variants WHERE sku LIKE '%$kw%')) - AND visible=1 - GROUP BY p.id - ORDER BY p.name - LIMIT ?", $this->limit); - $products = $this->db->results(); - - $suggestions = array(); - - foreach($products as $product) - { - $suggestion = new stdClass(); - - if(!empty($product->image)) - $product->image = $this->design->resize_modifier($product->image, 35, 35); - - $suggestion->value = $product->name; - $suggestion->data = $product; - $result->suggestions[] = $suggestion; - } - } - - - return $result; - } - } - - $cart_ajax = new SearchProductsAjax(); - $result = $cart_ajax->fetch(); - - header("Content-type: application/json; charset=UTF-8"); - header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); - header("X-Robots-Tag: noindex, noarchive, nosnippet"); - header("Pragma: no-cache"); - header("Expires: -1"); - print json_encode($result); - exit; +suggestions = array(); + $result->query = $this->request->get('query', 'string'); + + if (!empty($result->query)) { + $kw = $this->db->escape($result->query); + + $this->db->query("SELECT p.id, p.name, i.filename as image FROM __products p + LEFT JOIN __images i ON i.product_id=p.id AND i.position=(SELECT MIN(position) FROM __images WHERE product_id=p.id LIMIT 1) + WHERE (p.name LIKE '%$kw%' OR p.meta_keywords LIKE '%$kw%' OR p.id in (SELECT product_id FROM __variants WHERE sku LIKE '%$kw%')) + AND visible=1 + GROUP BY p.id + ORDER BY p.name + LIMIT ?", $this->limit); + $products = $this->db->results(); + + $suggestions = array(); + + foreach ($products as $product) { + $suggestion = new stdClass(); + + if (!empty($product->image)) { + $product->image = $this->design->resize_modifier($product->image, 35, 35); + } + + $suggestion->value = $product->name; + $suggestion->data = $product; + $result->suggestions[] = $suggestion; + } + } + + + return $result; + } + } + + $cart_ajax = new SearchProductsAjax(); + $result = $cart_ajax->fetch(); + + header("Content-type: application/json; charset=UTF-8"); + header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); + header("X-Robots-Tag: noindex, noarchive, nosnippet"); + header("Pragma: no-cache"); + header("Expires: -1"); + print json_encode($result); + exit; diff --git a/index.php b/index.php index 4addb47..6dd2034 100755 --- a/index.php +++ b/index.php @@ -19,70 +19,71 @@ $view = new IndexView(); -if(isset($_GET['logout'])) -{ - header('WWW-Authenticate: Basic realm="Simpla CMS"'); - header('HTTP/1.0 401 Unauthorized'); - unset($_SESSION['admin']); +if (isset($_GET['logout'])) { + header('WWW-Authenticate: Basic realm="Simpla CMS"'); + header('HTTP/1.0 401 Unauthorized'); + unset($_SESSION['admin']); } // Если все хорошо -if(($res = $view->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(); +if (($res = $view->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 (substr($h, 0, 4) == 'www.') { + $h = substr($h, 4); +} +if ((!in_array($h, $l->domains) || (strtotime($l->expiration)expiration!='*'))) { + print "
Лицензия недействительна
Скрипт интернет-магазина Simpla
"; } // Отладочная информация -if(1) -{ - print ""; +if (1) { + print ""; } diff --git a/password.php b/password.php index 768125e..a24e925 100755 --- a/password.php +++ b/password.php @@ -34,52 +34,46 @@ $simpla = new Simpla(); // Если пришли по ссылке из письма -if($c = $simpla->request->get('code')) -{ - // Код не совпадает - прекращяем работу - if(empty($_SESSION['admin_password_recovery_code']) || empty($c) || $_SESSION['admin_password_recovery_code'] !== $c) - { - header('Location:password.php'); - exit(); - } - - // IP не совпадает - прекращяем работу - if(empty($_SESSION['admin_password_recovery_ip'])|| empty($_SERVER['REMOTE_ADDR']) || $_SESSION['admin_password_recovery_ip'] !== $_SERVER['REMOTE_ADDR']) - { - header('Location:password.php'); - exit(); - } - - // Если запостили пароль - if($new_password = $simpla->request->post('new_password')) - { - // Файл с паролями - $passwd_file = $simpla->config->root_dir.'simpla/.passwd'; - - // Удаляем из сесси код, чтобы больше никто не воспользовался ссылкой - unset($_SESSION['admin_password_recovery_code']); - unset($_SESSION['admin_password_recovery_ip']); - - // Если в файлы запрещена запись - предупреждаем об этом - if(!is_writable($passwd_file)) - { - print " +if ($c = $simpla->request->get('code')) { + // Код не совпадает - прекращяем работу + if (empty($_SESSION['admin_password_recovery_code']) || empty($c) || $_SESSION['admin_password_recovery_code'] !== $c) { + header('Location:password.php'); + exit(); + } + + // IP не совпадает - прекращяем работу + if (empty($_SESSION['admin_password_recovery_ip'])|| empty($_SERVER['REMOTE_ADDR']) || $_SESSION['admin_password_recovery_ip'] !== $_SERVER['REMOTE_ADDR']) { + header('Location:password.php'); + exit(); + } + + // Если запостили пароль + if ($new_password = $simpla->request->post('new_password')) { + // Файл с паролями + $passwd_file = $simpla->config->root_dir.'simpla/.passwd'; + + // Удаляем из сесси код, чтобы больше никто не воспользовался ссылкой + unset($_SESSION['admin_password_recovery_code']); + unset($_SESSION['admin_password_recovery_ip']); + + // Если в файлы запрещена запись - предупреждаем об этом + if (!is_writable($passwd_file)) { + print "

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

Файл /simpla/.passwd недоступен для записи.

Вам нужно зайти по FTP и изменить права доступа к этому файлу, после чего повторить процедуру восстановления пароля.

"; - } - else - { - // Новый логин и пароль - $new_login = $simpla->request->post('new_login'); - $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 " + } else { + // Новый логин и пароль + $new_login = $simpla->request->post('new_login'); + $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 "

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

Новый пароль установлен @@ -88,12 +82,10 @@ Перейти в панель управления

"; - } - } - else - { - // Форма указалия нового логина и пароля - print " + } + } else { + // Форма указалия нового логина и пароля + print "

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

@@ -103,11 +95,9 @@

"; - } -} -else -{ - print " + } +} else { + print "

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

Введите email администратора @@ -118,25 +108,22 @@

"; - $admin_email = $simpla->settings->admin_email; - - if(isset($_POST['email'])) - { - if($_POST['email'] === $admin_email) - { - $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']; + $admin_email = $simpla->settings->admin_email; - $message = 'Вы или кто-то другой запросил ссылку на восстановление пароля администратора.
'; - $message .= 'Для смены пароля перейдите по ссылке '.$simpla->config->root_url.'/password.php?code='.$code.'
'; - $message .= 'Если письмо пришло вам по ошибке, проигнорируйте его.'; + if (isset($_POST['email'])) { + if ($_POST['email'] === $admin_email) { + $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']; - $simpla->notify->email($admin_email, 'Восстановление пароля администратора '.$simpla->settings->site_name, $message, $simpla->settings->notify_from_email); - } - print "Вам отправлена ссылка для восстановления пароля. Если письмо вам не пришло, значит вы неверно указали email или что-то не так с хостингом"; - } + $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 или что-то не так с хостингом"; + } } ?> diff --git a/resize/resize.php b/resize/resize.php index 1c21973..a4cf3cb 100755 --- a/resize/resize.php +++ b/resize/resize.php @@ -8,30 +8,28 @@ $simpla = new Simpla(); -if(!$simpla->config->check_token($filename, $token)) -{ - header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); - exit('bad token'); +if (!$simpla->config->check_token($filename, $token)) { + header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); + exit('bad token'); } $resized_filename = $simpla->image->resize($filename); -if(is_readable($resized_filename)) -{ - if (function_exists('exif_imagetype')) { - $image_type = exif_imagetype( $resized_filename ); - } else { - $image_type = getimagesize( $resized_filename ); - $image_type = ( isset($image_type[2]) ) ? $image_type[2] : NULL; - } - - if( is_null($image_type) ) - $image_mime = 'image'; - else - $image_mime = image_type_to_mime_type($image_type); - - header("Content-type: ".$image_mime); - print file_get_contents($resized_filename); - exit; +if (is_readable($resized_filename)) { + if (function_exists('exif_imagetype')) { + $image_type = exif_imagetype($resized_filename); + } else { + $image_type = getimagesize($resized_filename); + $image_type = (isset($image_type[2])) ? $image_type[2] : null; + } + + if (is_null($image_type)) { + $image_mime = 'image'; + } else { + $image_mime = image_type_to_mime_type($image_type); + } + + header("Content-type: ".$image_mime); + print file_get_contents($resized_filename); + exit; } - diff --git a/simpla/BackupAdmin.php b/simpla/BackupAdmin.php index 385cba8..698759e 100755 --- a/simpla/BackupAdmin.php +++ b/simpla/BackupAdmin.php @@ -1,150 +1,135 @@ -request->method('post')) - { - switch($this->request->post('action')) - { - case 'create': - { - $filename = $dir.'simpla_'.date("Y_m_d_G_i_s").'.zip'; - ##Дамп базы - $this->db->dump($dir.'simpla.sql'); - chmod($dir.'simpla.sql', 0777); - - ### Архивируем - $zip = new PclZip($filename); - $v_list = $zip->create(array('files', $dir.'simpla.sql'), PCLZIP_OPT_REMOVE_PATH, $dir, PCLZIP_CB_PRE_ADD, "myCallBack"); - if ($v_list == 0) - { - trigger_error('Не могу заархивировать '.$zip->errorInfo(true)); - } - $this->design->assign('message_success', 'created'); - - break; - } - 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)); - } - elseif (!$zip->extract(PCLZIP_OPT_PATH, $dir, PCLZIP_OPT_BY_NAME, 'simpla.sql')) - { - trigger_error('Не могу разархивировать '.$zip->errorInfo(true)); - } - elseif (!is_readable($dir.'simpla.sql')) - { - trigger_error('Не могу прочитать файл /temp/simpla.sql'); - } - else - { - $this->db->restore($dir.'simpla.sql'); - unlink($dir.'simpla.sql'); - $this->design->assign('message_success', 'restored'); - } - break; - } - case 'delete': - { - $names = $this->request->post('check'); - foreach($names as $name) - unlink($dir.$name); - break; - } - } - } - - $backup_files = glob($dir."*.zip"); - $backups = array(); - if(is_array($backup_files)) - { - foreach($backup_files as $backup_file) - { - $backup = new stdClass; - $backup->name = basename($backup_file); - $backup->size = filesize($backup_file); - $backups[] = $backup; - } - } - $backups = array_reverse($backups); - - $this->design->assign('backup_files_dir', $dir); - if(!is_writable($dir)) - $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); - } - -} - - -function myPostExtractCallBack($p_event, &$p_header) -{ - // проверяем успешность распаковки - if ($p_header['status'] == 'ok') - { - // Меняем права доступа - @chmod($p_header['filename'], 0777); - } - return 1; -} - -function myCallBack($p_event, &$p_header) -{ - $fname = $p_header['stored_filename']; - if(preg_match('/^files\/products\/.+/i', $fname)) - return 0; - return 1; -} - - +request->method('post')) { + switch ($this->request->post('action')) { + case 'create': + { + $filename = $dir.'simpla_'.date("Y_m_d_G_i_s").'.zip'; + ##Дамп базы + $this->db->dump($dir.'simpla.sql'); + chmod($dir.'simpla.sql', 0777); + + ### Архивируем + $zip = new PclZip($filename); + $v_list = $zip->create(array('files', $dir.'simpla.sql'), PCLZIP_OPT_REMOVE_PATH, $dir, PCLZIP_CB_PRE_ADD, "myCallBack"); + if ($v_list == 0) { + trigger_error('Не могу заархивировать '.$zip->errorInfo(true)); + } + $this->design->assign('message_success', 'created'); + + break; + } + 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)); + } elseif (!$zip->extract(PCLZIP_OPT_PATH, $dir, PCLZIP_OPT_BY_NAME, 'simpla.sql')) { + trigger_error('Не могу разархивировать '.$zip->errorInfo(true)); + } elseif (!is_readable($dir.'simpla.sql')) { + trigger_error('Не могу прочитать файл /temp/simpla.sql'); + } else { + $this->db->restore($dir.'simpla.sql'); + unlink($dir.'simpla.sql'); + $this->design->assign('message_success', 'restored'); + } + break; + } + case 'delete': + { + $names = $this->request->post('check'); + foreach ($names as $name) { + unlink($dir.$name); + } + break; + } + } + } + + $backup_files = glob($dir."*.zip"); + $backups = array(); + if (is_array($backup_files)) { + foreach ($backup_files as $backup_file) { + $backup = new stdClass; + $backup->name = basename($backup_file); + $backup->size = filesize($backup_file); + $backups[] = $backup; + } + } + $backups = array_reverse($backups); + + $this->design->assign('backup_files_dir', $dir); + if (!is_writable($dir)) { + $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); + } +} + + +function myPostExtractCallBack($p_event, &$p_header) +{ + // проверяем успешность распаковки + if ($p_header['status'] == 'ok') { + // Меняем права доступа + @chmod($p_header['filename'], 0777); + } + return 1; +} + +function myCallBack($p_event, &$p_header) +{ + $fname = $p_header['stored_filename']; + if (preg_match('/^files\/products\/.+/i', $fname)) { + return 0; + } + return 1; +} diff --git a/simpla/BlogAdmin.php b/simpla/BlogAdmin.php index 6009654..a616cd2 100755 --- a/simpla/BlogAdmin.php +++ b/simpla/BlogAdmin.php @@ -1,75 +1,72 @@ -request->method('post')) - { - // Действия с выбранными - $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; - } - } - } - - } - - $filter = array(); - $filter['page'] = max(1, $this->request->get('page', 'integer')); - $filter['limit'] = 20; - - // Поиск - $keyword = $this->request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } - - $posts_count = $this->blog->count_posts($filter); - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $filter['limit'] = $posts_count; - - $posts = $this->blog->get_posts($filter); - $this->design->assign('posts_count', $posts_count); - - $this->design->assign('pages_count', ceil($posts_count/$filter['limit'])); - $this->design->assign('current_page', $filter['page']); - - $this->design->assign('posts', $posts); - - return $this->design->fetch('blog.tpl'); - } -} +request->method('post')) { + // Действия с выбранными + $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; + } + } + } + } + + $filter = array(); + $filter['page'] = max(1, $this->request->get('page', 'integer')); + $filter['limit'] = 20; + + // Поиск + $keyword = $this->request->get('keyword', 'string'); + if (!empty($keyword)) { + $filter['keyword'] = $keyword; + $this->design->assign('keyword', $keyword); + } + + $posts_count = $this->blog->count_posts($filter); + // Показать все страницы сразу + if ($this->request->get('page') == 'all') { + $filter['limit'] = $posts_count; + } + + $posts = $this->blog->get_posts($filter); + $this->design->assign('posts_count', $posts_count); + + $this->design->assign('pages_count', ceil($posts_count/$filter['limit'])); + $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 052b2f7..0bfee2d 100755 --- a/simpla/BrandAdmin.php +++ b/simpla/BrandAdmin.php @@ -1,83 +1,68 @@ -request->method('post')) - { - $brand->id = $this->request->post('id', 'integer'); - $brand->name = $this->request->post('name'); - $brand->description = $this->request->post('description'); - - $brand->url = trim($this->request->post('url', 'string')); - $brand->meta_title = $this->request->post('meta_title'); - $brand->meta_keywords = $this->request->post('meta_keywords'); - $brand->meta_description = $this->request->post('meta_description'); - - // Не допустить одинаковые 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)) - { - $brand->id = $this->brands->add_brand($brand); - $this->design->assign('message_success', 'added'); - } - 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); - } - } - else - { - $brand->id = $this->request->get('id', 'integer'); - $brand = $this->brands->get_brand($brand->id); - } - - $this->design->assign('brand', $brand); - - return $this->design->fetch('brand.tpl'); - } -} +request->method('post')) { + $brand->id = $this->request->post('id', 'integer'); + $brand->name = $this->request->post('name'); + $brand->description = $this->request->post('description'); + + $brand->url = trim($this->request->post('url', 'string')); + $brand->meta_title = $this->request->post('meta_title'); + $brand->meta_keywords = $this->request->post('meta_keywords'); + $brand->meta_description = $this->request->post('meta_description'); + + // Не допустить одинаковые 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)) { + $brand->id = $this->brands->add_brand($brand); + $this->design->assign('message_success', 'added'); + } 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); + } + } else { + $brand->id = $this->request->get('id', 'integer'); + $brand = $this->brands->get_brand($brand->id); + } + + $this->design->assign('brand', $brand); + + return $this->design->fetch('brand.tpl'); + } +} diff --git a/simpla/BrandsAdmin.php b/simpla/BrandsAdmin.php index d0c0e11..9b39cb1 100755 --- a/simpla/BrandsAdmin.php +++ b/simpla/BrandsAdmin.php @@ -1,44 +1,44 @@ -request->method('post')) - { - - // Действия с выбранными - $ids = $this->request->post('check'); - - if(is_array($ids)) - switch($this->request->post('action')) - { - 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'); - } -} +request->method('post')) { + + // Действия с выбранными + $ids = $this->request->post('check'); + + if (is_array($ids)) { + switch ($this->request->post('action')) { + 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 19f93ed..96b68db 100755 --- a/simpla/CategoriesAdmin.php +++ b/simpla/CategoriesAdmin.php @@ -1,59 +1,60 @@ -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; - } - } - - // Сортировка - $positions = $this->request->post('positions'); - $ids = array_keys($positions); - sort($positions); - foreach($positions as $i=>$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'); - } -} +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; + } + } + } + + // Сортировка + $positions = $this->request->post('positions'); + $ids = array_keys($positions); + sort($positions); + foreach ($positions as $i=>$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 6b8452f..b9384ba 100755 --- a/simpla/CategoryAdmin.php +++ b/simpla/CategoryAdmin.php @@ -1,89 +1,74 @@ -request->method('post')) - { - $category->id = $this->request->post('id', 'integer'); - $category->parent_id = $this->request->post('parent_id', 'integer'); - $category->name = $this->request->post('name'); - $category->visible = $this->request->post('visible', 'boolean'); - - $category->url = trim($this->request->post('url', 'string')); - $category->meta_title = $this->request->post('meta_title'); - $category->meta_keywords = $this->request->post('meta_keywords'); - $category->meta_description = $this->request->post('meta_description'); - - $category->description = $this->request->post('description'); - - // Не допустить одинаковые 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)) - { - $category->id = $this->categories->add_category($category); - $this->design->assign('message_success', 'added'); - } - 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)); - } - } - else - { - $category->id = $this->request->get('id', 'integer'); - $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'); - } -} +request->method('post')) { + $category->id = $this->request->post('id', 'integer'); + $category->parent_id = $this->request->post('parent_id', 'integer'); + $category->name = $this->request->post('name'); + $category->visible = $this->request->post('visible', 'boolean'); + + $category->url = trim($this->request->post('url', 'string')); + $category->meta_title = $this->request->post('meta_title'); + $category->meta_keywords = $this->request->post('meta_keywords'); + $category->meta_description = $this->request->post('meta_description'); + + $category->description = $this->request->post('description'); + + // Не допустить одинаковые 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)) { + $category->id = $this->categories->add_category($category); + $this->design->assign('message_success', 'added'); + } 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)); + } + } else { + $category->id = $this->request->get('id', 'integer'); + $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'); + } +} diff --git a/simpla/CommentsAdmin.php b/simpla/CommentsAdmin.php index 61e2c34..360dd7c 100755 --- a/simpla/CommentsAdmin.php +++ b/simpla/CommentsAdmin.php @@ -1,110 +1,112 @@ -request->get('page', 'integer')); - - $filter['limit'] = 40; - - // Тип - $type = $this->request->get('type', 'string'); - if($type) - { - $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); - } - - - // Обработка действий - 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; - } - } - - } - - // Отображение - $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, 'limit' => count($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']); - - $this->design->assign('comments', $comments); - $this->design->assign('comments_count', $comments_count); - - return $this->design->fetch('comments.tpl'); - } -} +request->get('page', 'integer')); + + $filter['limit'] = 40; + + // Тип + $type = $this->request->get('type', 'string'); + if ($type) { + $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); + } + + + // Обработка действий + 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; + } + } + } + } + + // Отображение + $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, 'limit' => count($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']); + + $this->design->assign('comments', $comments); + $this->design->assign('comments_count', $comments_count); + + return $this->design->fetch('comments.tpl'); + } +} diff --git a/simpla/CouponAdmin.php b/simpla/CouponAdmin.php index 2c9a054..000c990 100755 --- a/simpla/CouponAdmin.php +++ b/simpla/CouponAdmin.php @@ -13,60 +13,48 @@ class CouponAdmin extends Simpla { - public function fetch() - { - $coupon = new stdClass; - if($this->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'); - } - 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); - } + public function fetch() + { + $coupon = new stdClass; + if ($this->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'); + } 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()); - $this->design->assign('coupon', $coupon); + $this->design->assign('coupon', $coupon); - return $this->design->fetch('coupon.tpl'); - } + return $this->design->fetch('coupon.tpl'); + } } diff --git a/simpla/CouponsAdmin.php b/simpla/CouponsAdmin.php index 512f243..4db2d92 100755 --- a/simpla/CouponsAdmin.php +++ b/simpla/CouponsAdmin.php @@ -1,62 +1,61 @@ -request->method('post')) - { - // Действия с выбранными - $ids = $this->request->post('check'); - if(is_array($ids) && count($ids)>0) - switch($this->request->post('action')) - { - case 'delete': - { - foreach($ids as $id) - $this->coupons->delete_coupon($id); - break; - } - } - } - - $filter = array(); - $filter['page'] = max(1, $this->request->get('page', 'integer')); - $filter['limit'] = 20; - - // Поиск - $keyword = $this->request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $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 = $this->coupons->get_coupons($filter); - - $this->design->assign('coupons', $coupons); - - return $this->design->fetch('coupons.tpl'); - } -} +request->method('post')) { + // Действия с выбранными + $ids = $this->request->post('check'); + if (is_array($ids) && count($ids)>0) { + switch ($this->request->post('action')) { + case 'delete': + { + foreach ($ids as $id) { + $this->coupons->delete_coupon($id); + } + break; + } + } + } + } + + $filter = array(); + $filter['page'] = max(1, $this->request->get('page', 'integer')); + $filter['limit'] = 20; + + // Поиск + $keyword = $this->request->get('keyword', 'string'); + if (!empty($keyword)) { + $filter['keyword'] = $keyword; + $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 = $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 8c87465..c84c02b 100755 --- a/simpla/CurrencyAdmin.php +++ b/simpla/CurrencyAdmin.php @@ -14,111 +14,106 @@ class CurrencyAdmin extends Simpla { - public function fetch() - { - - // Обработка действий - if($this->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'); - } + public function fetch() + { + + // Обработка действий + if ($this->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 a1e726c..d24cb78 100755 --- a/simpla/DeliveriesAdmin.php +++ b/simpla/DeliveriesAdmin.php @@ -14,49 +14,49 @@ class DeliveriesAdmin extends Simpla { - public function fetch() - { - - // Обработка действий - if($this->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'); - } + public function fetch() + { + + // Обработка действий + if ($this->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 a2f7810..5f15f25 100755 --- a/simpla/DeliveryAdmin.php +++ b/simpla/DeliveryAdmin.php @@ -14,61 +14,50 @@ class DeliveryAdmin extends Simpla { - public function fetch() - { - $delivery = new stdClass; - if($this->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->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'); - } - + public function fetch() + { + $delivery = new stdClass; + if ($this->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->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'); + } } - diff --git a/simpla/ExportAdmin.php b/simpla/ExportAdmin.php index 562ed3e..d366e28 100755 --- a/simpla/ExportAdmin.php +++ b/simpla/ExportAdmin.php @@ -13,18 +13,19 @@ class ExportAdmin extends Simpla { - private $export_files_dir = 'simpla/files/export/'; + private $export_files_dir = 'simpla/files/export/'; - public function fetch() - { - $this->design->assign('export_files_dir', $this->export_files_dir); - if(!is_writable($this->export_files_dir)) - $this->design->assign('message_error', 'no_permission'); + public function fetch() + { + $this->design->assign('export_files_dir', $this->export_files_dir); + if (!is_writable($this->export_files_dir)) { + $this->design->assign('message_error', 'no_permission'); + } - if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) - $this->design->assign('message_error', 'iconv_or_mb_convert_encoding'); + if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) { + $this->design->assign('message_error', 'iconv_or_mb_convert_encoding'); + } - return $this->design->fetch('export.tpl'); - } - + return $this->design->fetch('export.tpl'); + } } diff --git a/simpla/ExportUsersAdmin.php b/simpla/ExportUsersAdmin.php index 0c6c05a..474b437 100755 --- a/simpla/ExportUsersAdmin.php +++ b/simpla/ExportUsersAdmin.php @@ -13,23 +13,24 @@ class ExportUsersAdmin extends Simpla { - private $export_files_dir = 'simpla/files/export_users/'; - - public function fetch() - { - $this->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'); - - if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) - $this->design->assign('message_error', 'iconv_or_mb_convert_encoding'); - - return $this->design->fetch('export_users.tpl'); - } - + private $export_files_dir = 'simpla/files/export_users/'; + + public function fetch() + { + $this->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'); + } + + if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) { + $this->design->assign('message_error', 'iconv_or_mb_convert_encoding'); + } + + return $this->design->fetch('export_users.tpl'); + } } diff --git a/simpla/FeatureAdmin.php b/simpla/FeatureAdmin.php index d799163..18b808a 100755 --- a/simpla/FeatureAdmin.php +++ b/simpla/FeatureAdmin.php @@ -14,51 +14,40 @@ class FeatureAdmin extends Simpla { - public function fetch() - { - $feature = new stdClass; - if($this->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'); - } + public function fetch() + { + $feature = new stdClass; + if ($this->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 28072dc..73a0b40 100755 --- a/simpla/FeaturesAdmin.php +++ b/simpla/FeaturesAdmin.php @@ -13,75 +13,68 @@ class FeaturesAdmin extends Simpla { - public function fetch() - { + public function fetch() + { + if ($this->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); - if($this->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; + } + } + } - // В каких категориях оставлять - $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)); + } + } - // Сортировка - $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; + } - $categories = $this->categories->get_categories_tree(); - $category = null; + $features = $this->features->get_features($filter); - $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; - } + $this->design->assign('categories', $categories); + $this->design->assign('category', $category); + $this->design->assign('features', $features); - $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'); - } + return $this->body = $this->design->fetch('features.tpl'); + } } diff --git a/simpla/FeedbacksAdmin.php b/simpla/FeedbacksAdmin.php index 20bd8b1..9f22080 100755 --- a/simpla/FeedbacksAdmin.php +++ b/simpla/FeedbacksAdmin.php @@ -15,52 +15,50 @@ class FeedbacksAdmin extends Simpla { - public function fetch() - { + public function fetch() + { + $filter = array(); + $filter['page'] = max(1, $this->request->get('page', 'integer')); + $filter['limit'] = 40; - $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)) { + switch ($this->request->post('action')) { + case 'delete': + { + foreach ($ids as $id) { + $this->feedbacks->delete_feedback($id); + } + break; + } + } + } + } - // Обработка действий - 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; - } - } + // Поиск + $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; + } - // Поиск - $keyword = $this->request->get('keyword', 'string'); - if(!empty($keyword)) - { - $filter['keyword'] = $keyword; - $this->design->assign('keyword', $keyword); - } + $feedbacks = $this->feedbacks->get_feedbacks($filter, true); - $feedbacks_count = $this->feedbacks->count_feedbacks($filter); - // Показать все страницы сразу - if($this->request->get('page') == 'all') - $filter['limit'] = $feedbacks_count; + $this->design->assign('pages_count', ceil($feedbacks_count/$filter['limit'])); + $this->design->assign('current_page', $filter['page']); - $feedbacks = $this->feedbacks->get_feedbacks($filter, true); + $this->design->assign('feedbacks', $feedbacks); + $this->design->assign('feedbacks_count', $feedbacks_count); - $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'); - } + return $this->design->fetch('feedbacks.tpl'); + } } diff --git a/simpla/GroupAdmin.php b/simpla/GroupAdmin.php index 27a1730..3f4d68f 100755 --- a/simpla/GroupAdmin.php +++ b/simpla/GroupAdmin.php @@ -13,48 +13,37 @@ class GroupAdmin extends Simpla { - public function fetch() - { - $group = new stdClass; - if($this->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'); - } - + public function fetch() + { + $group = new stdClass; + if ($this->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 6f8dfed..f8099da 100755 --- a/simpla/GroupsAdmin.php +++ b/simpla/GroupsAdmin.php @@ -13,28 +13,28 @@ class GroupsAdmin extends Simpla { - public function fetch() - { - 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) - $this->users->delete_group($id); - break; - } - } - } + public function fetch() + { + 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) { + $this->users->delete_group($id); + } + break; + } + } + } + } - $groups = $this->users->get_groups(); + $groups = $this->users->get_groups(); - $this->design->assign('groups', $groups); + $this->design->assign('groups', $groups); - return $this->body = $this->design->fetch('groups.tpl'); - } + return $this->body = $this->design->fetch('groups.tpl'); + } } diff --git a/simpla/ImagesAdmin.php b/simpla/ImagesAdmin.php index 4018e93..8ac3cda 100755 --- a/simpla/ImagesAdmin.php +++ b/simpla/ImagesAdmin.php @@ -13,93 +13,82 @@ class ImagesAdmin extends Simpla { - public function fetch() - { - $images_dir = 'design/'.$this->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'); - } - + public function fetch() + { + $images_dir = 'design/'.$this->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 e3de29d..029a22c 100755 --- a/simpla/ImportAdmin.php +++ b/simpla/ImportAdmin.php @@ -13,108 +13,148 @@ class ImportAdmin extends Simpla { - public $import_files_dir = 'simpla/files/import/'; - public $import_file = 'import.csv'; - public $allowed_extensions = array('csv', 'txt'); - private $locale = 'ru_RU.UTF-8'; - - public function fetch() - { - $this->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; } + public $import_files_dir = 'simpla/files/import/'; + public $import_file = 'import.csv'; + public $allowed_extensions = array('csv', 'txt'); + private $locale = 'ru_RU.UTF-8'; + + public function fetch() + { + $this->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; - } - } - + 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 bf79d8e..9954c47 100755 --- a/simpla/IndexAdmin.php +++ b/simpla/IndexAdmin.php @@ -14,160 +14,167 @@ // Этот класс выбирает модуль в зависимости от параметра Section и выводит его на экран class IndexAdmin extends Simpla { - // Соответсвие модулей и названий соответствующих прав - private $modules_permissions = array( - 'ProductsAdmin' => '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; - } + // Соответсвие модулей и названий соответствующих прав + private $modules_permissions = array( + 'ProductsAdmin' => '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 88b7f65..c772738 100755 --- a/simpla/LicenseAdmin.php +++ b/simpla/LicenseAdmin.php @@ -14,42 +14,50 @@ class LicenseAdmin extends Simpla { - public function fetch() - { - - if($this->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'); - } - + public function fetch() + { + if ($this->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 19adca3..be82a17 100755 --- a/simpla/ManagerAdmin.php +++ b/simpla/ManagerAdmin.php @@ -14,64 +14,52 @@ class ManagerAdmin extends Simpla { - public function fetch() - { - if($this->request->method('post')) - { - $manager = new stdClass(); - $manager->old_login = $this->request->post('old_login'); - $manager->login = $this->request->post('login'); + public function fetch() + { + if ($this->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'); + 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'); + // Обновляем права только другим менеджерам + $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->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'); - } + 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 56064e0..7d181ed 100755 --- a/simpla/ManagersAdmin.php +++ b/simpla/ManagersAdmin.php @@ -13,35 +13,33 @@ class ManagersAdmin extends Simpla { - public function fetch() - { + public function fetch() + { + if ($this->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($this->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'); + } - 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); - $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'); - } + return $this->body = $this->design->fetch('managers.tpl'); + } } diff --git a/simpla/OrderAdmin.php b/simpla/OrderAdmin.php index 4ec6065..c78af27 100755 --- a/simpla/OrderAdmin.php +++ b/simpla/OrderAdmin.php @@ -15,246 +15,248 @@ class OrderAdmin extends Simpla { - public function fetch() - { - $order = new stdClass; - if($this->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, '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; - - $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'); - } + public function fetch() + { + $order = new stdClass; + if ($this->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, '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; + } + + $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 d479365..c0b5195 100755 --- a/simpla/OrdersAdmin.php +++ b/simpla/OrdersAdmin.php @@ -13,141 +13,138 @@ class OrdersAdmin extends Simpla { - public function fetch() - { - $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); - } - - // Фильтр по метке - $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'); - } + public function fetch() + { + $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); + } + + // Фильтр по метке + $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 de48076..a2431bc 100755 --- a/simpla/OrdersLabelAdmin.php +++ b/simpla/OrdersLabelAdmin.php @@ -13,43 +13,34 @@ class OrdersLabelAdmin extends Simpla { - public function fetch() - { - $label = new stdClass; - $label->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)) - { - $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)); - } + public function fetch() + { + $label = new stdClass; + $label->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)) { + $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('label', $label); + return $this->design->fetch('orders_label.tpl'); + } } - diff --git a/simpla/OrdersLabelsAdmin.php b/simpla/OrdersLabelsAdmin.php index e741d73..0b35e3a 100755 --- a/simpla/OrdersLabelsAdmin.php +++ b/simpla/OrdersLabelsAdmin.php @@ -14,37 +14,38 @@ class OrdersLabelsAdmin extends Simpla { - public function fetch() - { - // Обработка действий - if($this->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'); - } + public function fetch() + { + // Обработка действий + if ($this->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 49c5336..f154057 100755 --- a/simpla/PageAdmin.php +++ b/simpla/PageAdmin.php @@ -13,71 +13,59 @@ class PageAdmin extends Simpla { - public function fetch() - { - $page = new stdClass; - if($this->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'); + public function fetch() + { + $page = new stdClass; + if ($this->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; - } - } + ## Не допустить одинаковые 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); + $this->design->assign('page', $page); - $menus = $this->pages->get_menus(); - $this->design->assign('menus', $menus); + $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'); - } + // Текущее меню + 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 7349c28..d47f98e 100755 --- a/simpla/PagesAdmin.php +++ b/simpla/PagesAdmin.php @@ -14,63 +14,62 @@ class PagesAdmin extends Simpla { - public function fetch() - { + public function fetch() + { - // Меню - $menus = $this->pages->get_menus(); - $this->design->assign('menus', $menus); + // Меню + $menus = $this->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); + // Текущее меню + $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)); + // Обработка действий + 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; - } - } + // Действия с выбранными + $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)); - // Отображение - $pages = $this->pages->get_pages(array('menu_id'=>$menu->id)); + $this->design->assign('pages', $pages); - $this->design->assign('pages', $pages); - - return $this->design->fetch('pages.tpl'); - } + return $this->design->fetch('pages.tpl'); + } } diff --git a/simpla/PaymentMethodAdmin.php b/simpla/PaymentMethodAdmin.php index c6f7900..c9a3a40 100755 --- a/simpla/PaymentMethodAdmin.php +++ b/simpla/PaymentMethodAdmin.php @@ -14,72 +14,59 @@ class PaymentMethodAdmin extends Simpla { - public function fetch() - { - $payment_method = new stdClass; - if($this->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'); + public function fetch() + { + $payment_method = new stdClass; + if ($this->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'); + $payment_settings = $this->request->post('payment_settings'); - if(!$payment_deliveries = $this->request->post('payment_deliveries')) - $payment_deliveries = array(); + if (!$payment_deliveries = $this->request->post('payment_deliveries')) { + $payment_deliveries = array(); + } - if(empty($payment_method->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); + if (empty($payment_method->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); + $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'); - } + $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 47b815b..e369be0 100755 --- a/simpla/PaymentMethodsAdmin.php +++ b/simpla/PaymentMethodsAdmin.php @@ -14,48 +14,48 @@ class PaymentMethodsAdmin extends Simpla { - public function fetch() - { - // Обработка действий - if($this->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'); - } + public function fetch() + { + // Обработка действий + if ($this->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 ff54bdf..8ec9089 100755 --- a/simpla/PostAdmin.php +++ b/simpla/PostAdmin.php @@ -13,60 +13,50 @@ class PostAdmin extends Simpla { - public function fetch() - { - $post = new stdClass; - if($this->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'); - } + public function fetch() + { + $post = new stdClass; + if ($this->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 ca23fc9..92e5bbc 100755 --- a/simpla/ProductAdmin.php +++ b/simpla/ProductAdmin.php @@ -13,384 +13,353 @@ class ProductAdmin extends Simpla { - public function fetch() - { - - $options = array(); - $product_categories = array(); - $variants = array(); - $images = array(); - $product_features = array(); - $related_products = array(); - - if($this->request->method('post') && !empty($_POST)) - { - $product = new stdClass; - $product->id = $this->request->post('id', 'integer'); - $product->name = $this->request->post('name'); - $product->visible = $this->request->post('visible', 'boolean'); - $product->featured = $this->request->post('featured'); - $product->brand_id = $this->request->post('brand_id', 'integer'); - - $product->url = trim($this->request->post('url', 'string')); - $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'); - - // Варианты товара - if($this->request->post('variants')) - foreach($this->request->post('variants') as $n=>$va) - { - foreach($va as $i=>$v) - { - if(empty($variants[$i])) - $variants[$i] = new stdClass; - $variants[$i]->$n = $v; - } - } - - // Категории товара - $product_categories = $this->request->post('categories'); - if(is_array($product_categories)) - { - foreach($product_categories as $c) - { - $x = new stdClass; - $x->id = $c; - $pc[] = $x; - } - $product_categories = $pc; - } - - // Свойства товара - $options = $this->request->post('options'); - if(is_array($options)) - { - foreach($options as $f_id=>$val) - { - $po[$f_id] = new stdClass; - $po[$f_id]->feature_id = $f_id; - $po[$f_id]->value = $val; - } - $options = $po; - } - - // Связанные товары - if(is_array($this->request->post('related_products'))) - { - foreach($this->request->post('related_products') as $p) - { - $rp[$p] = new stdClass; - $rp[$p]->product_id = $product->id; - $rp[$p]->related_id = $p; - } - $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)); - } - else - { - if(empty($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); - $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(); - 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($variant->id)) - $this->variants->update_variant($variant->id, $variant); - else - { - $variant->product_id = $product->id; - $variant->id = $this->variants->add_variant($variant); - } - $variant = $this->variants->get_variant($variant->id); - if(!empty($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($)) - - // Отсортировать варианты - 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); - } - - // Порядок изображений - if($images = $this->request->post('images')) - { - $i=0; - foreach($images as $id) - { - $this->products->update_image($id, array('position'=>$i)); - $i++; - } - } - // Загрузка изображений - 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); - } - else - { - $this->design->assign('error', 'error uploading image'); - } - } - } - // Загрузка изображений из интернета и 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); - } - } - } - $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)) - 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'); - if(is_array($new_features_names) && is_array($new_features_values)) - { - foreach($new_features_names as $i=>$name) - { - $value = trim($new_features_values[$i]); - if(!empty($name) && !empty($value)) - { - $query = $this->db->placehold("SELECT * FROM __features WHERE name=? LIMIT 1", trim($name)); - $this->db->query($query); - $feature_id = $this->db->result('id'); - if(empty($feature_id)) - { - $feature_id = $this->features->add_feature(array('name'=>trim($name))); - } - $this->features->add_feature_category($feature_id, reset($product_categories)->id); - $this->features->update_option($product->id, $feature_id, $value); - } - } - // Свойства товара - $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++); - } - } - } - - //header('Location: '.$this->request->url(array('message_success'=>'updated'))); - } - else - { - $id = $this->request->get('id', 'integer'); - $product = $this->products->get_product(intval($id)); - - 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)); - } - else - { - // Сразу активен - $product = new stdClass; - $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; - else - $product_categories = array(1); - } - if(empty($product->brand_id) && $brand_id=$this->request->get('brand_id')) - { - $product->brand_id = $brand_id; - } - - if(!empty($related_products)) - { - foreach($related_products as &$r_p) - $r_products[$r_p->related_id] = &$r_p; - $temp_products = $this->products->get_products(array('id'=>array_keys($r_products), 'limit' => count(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(); - foreach($options as $option) - $temp_options[$option->feature_id] = $option; - $options = $temp_options; - } - - - $this->design->assign('product', $product); - - $this->design->assign('product_categories', $product_categories); - $this->design->assign('product_variants', $variants); - $this->design->assign('product_images', $images); - $this->design->assign('options', $options); - $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); - 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'); - } + public function fetch() + { + $options = array(); + $product_categories = array(); + $variants = array(); + $images = array(); + $product_features = array(); + $related_products = array(); + + if ($this->request->method('post') && !empty($_POST)) { + $product = new stdClass; + $product->id = $this->request->post('id', 'integer'); + $product->name = $this->request->post('name'); + $product->visible = $this->request->post('visible', 'boolean'); + $product->featured = $this->request->post('featured'); + $product->brand_id = $this->request->post('brand_id', 'integer'); + + $product->url = trim($this->request->post('url', 'string')); + $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'); + + // Варианты товара + if ($this->request->post('variants')) { + foreach ($this->request->post('variants') as $n=>$va) { + foreach ($va as $i=>$v) { + if (empty($variants[$i])) { + $variants[$i] = new stdClass; + } + $variants[$i]->$n = $v; + } + } + } + + // Категории товара + $product_categories = $this->request->post('categories'); + if (is_array($product_categories)) { + foreach ($product_categories as $c) { + $x = new stdClass; + $x->id = $c; + $pc[] = $x; + } + $product_categories = $pc; + } + + // Свойства товара + $options = $this->request->post('options'); + if (is_array($options)) { + foreach ($options as $f_id=>$val) { + $po[$f_id] = new stdClass; + $po[$f_id]->feature_id = $f_id; + $po[$f_id]->value = $val; + } + $options = $po; + } + + // Связанные товары + if (is_array($this->request->post('related_products'))) { + foreach ($this->request->post('related_products') as $p) { + $rp[$p] = new stdClass; + $rp[$p]->product_id = $product->id; + $rp[$p]->related_id = $p; + } + $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)); + } + } else { + if (empty($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); + $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(); + 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($variant->id)) { + $this->variants->update_variant($variant->id, $variant); + } else { + $variant->product_id = $product->id; + $variant->id = $this->variants->add_variant($variant); + } + $variant = $this->variants->get_variant($variant->id); + if (!empty($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($)) + + // Отсортировать варианты + 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); + } + } + + // Порядок изображений + if ($images = $this->request->post('images')) { + $i=0; + foreach ($images as $id) { + $this->products->update_image($id, array('position'=>$i)); + $i++; + } + } + // Загрузка изображений + 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); + } else { + $this->design->assign('error', 'error uploading image'); + } + } + } + // Загрузка изображений из интернета и 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); + } + } + } + } + $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)) { + 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'); + if (is_array($new_features_names) && is_array($new_features_values)) { + foreach ($new_features_names as $i=>$name) { + $value = trim($new_features_values[$i]); + if (!empty($name) && !empty($value)) { + $query = $this->db->placehold("SELECT * FROM __features WHERE name=? LIMIT 1", trim($name)); + $this->db->query($query); + $feature_id = $this->db->result('id'); + if (empty($feature_id)) { + $feature_id = $this->features->add_feature(array('name'=>trim($name))); + } + $this->features->add_feature_category($feature_id, reset($product_categories)->id); + $this->features->update_option($product->id, $feature_id, $value); + } + } + // Свойства товара + $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++); + } + } + } + } + + //header('Location: '.$this->request->url(array('message_success'=>'updated'))); + } else { + $id = $this->request->get('id', 'integer'); + $product = $this->products->get_product(intval($id)); + + 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)); + } else { + // Сразу активен + $product = new stdClass; + $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; + } else { + $product_categories = array(1); + } + } + if (empty($product->brand_id) && $brand_id=$this->request->get('brand_id')) { + $product->brand_id = $brand_id; + } + + if (!empty($related_products)) { + foreach ($related_products as &$r_p) { + $r_products[$r_p->related_id] = &$r_p; + } + $temp_products = $this->products->get_products(array('id'=>array_keys($r_products), 'limit' => count(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(); + foreach ($options as $option) { + $temp_options[$option->feature_id] = $option; + } + $options = $temp_options; + } + + + $this->design->assign('product', $product); + + $this->design->assign('product_categories', $product_categories); + $this->design->assign('product_variants', $variants); + $this->design->assign('product_images', $images); + $this->design->assign('options', $options); + $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); + } + 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'); + } } diff --git a/simpla/ProductsAdmin.php b/simpla/ProductsAdmin.php index d3e7d31..e336ba4 100755 --- a/simpla/ProductsAdmin.php +++ b/simpla/ProductsAdmin.php @@ -13,266 +13,265 @@ class ProductsAdmin extends Simpla { - public function fetch() - { - - $filter = array(); - $filter['page'] = max(1, $this->request->get('page', 'integer')); - - $filter['limit'] = $this->settings->products_num_admin; - - // Категории - $categories = $this->categories->get_categories_tree(); - $this->design->assign('categories', $categories); - - // Все бренды - $all_brands = $this->brands->get_brands(); - $this->design->assign('all_brands', $all_brands); - - // Текущая категория - $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'])); - - } - else - { - $brands = $all_brands; - } - - $this->design->assign('brands', $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'); - } + public function fetch() + { + $filter = array(); + $filter['page'] = max(1, $this->request->get('page', 'integer')); + + $filter['limit'] = $this->settings->products_num_admin; + + // Категории + $categories = $this->categories->get_categories_tree(); + $this->design->assign('categories', $categories); + + // Все бренды + $all_brands = $this->brands->get_brands(); + $this->design->assign('all_brands', $all_brands); + + // Текущая категория + $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'])); + } else { + $brands = $all_brands; + } + + $this->design->assign('brands', $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 b3d99ca..5a4f75b 100755 --- a/simpla/SettingsAdmin.php +++ b/simpla/SettingsAdmin.php @@ -13,95 +13,84 @@ class SettingsAdmin extends Simpla { - private $allowed_image_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico'); - - public function fetch() - { - $this->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'); - } - + private $allowed_image_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico'); + + public function fetch() + { + $this->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 686c3ee..e4a00e4 100755 --- a/simpla/StatsAdmin.php +++ b/simpla/StatsAdmin.php @@ -14,8 +14,8 @@ class StatsAdmin extends Simpla { - public function fetch() - { - return $this->design->fetch('stats.tpl'); - } + public function fetch() + { + return $this->design->fetch('stats.tpl'); + } } diff --git a/simpla/StylesAdmin.php b/simpla/StylesAdmin.php index 2d4b31c..2746a80 100755 --- a/simpla/StylesAdmin.php +++ b/simpla/StylesAdmin.php @@ -13,75 +13,69 @@ class StylesAdmin extends Simpla { - public function fetch() - { - $styles_dir = 'design/'.$this->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'); - } - + public function fetch() + { + $styles_dir = 'design/'.$this->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 742f26d..15df772 100755 --- a/simpla/TemplatesAdmin.php +++ b/simpla/TemplatesAdmin.php @@ -13,75 +13,69 @@ class TemplatesAdmin extends Simpla { - public function fetch() - { - $templates_dir = 'design/'.$this->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'); - } - + public function fetch() + { + $templates_dir = 'design/'.$this->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 ce02144..c7cfa45 100755 --- a/simpla/ThemeAdmin.php +++ b/simpla/ThemeAdmin.php @@ -13,135 +13,134 @@ class ThemeAdmin extends Simpla { - private $themes_dir = 'design/'; - private $compiled_dir = 'compiled/'; + private $themes_dir = 'design/'; + private $compiled_dir = 'compiled/'; - public function fetch() - { - if($this->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]); + public function fetch() + { + if ($this->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'; - } + 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'); + $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; - } - } - } + 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(); + $themes = $this->get_themes(); - // Если нет прав на запись - передаем в дизайн предупреждение - if(!is_writable($this->themes_dir)) - { - $this->design->assign('message_error', 'permissions'); - } + // Если нет прав на запись - передаем в дизайн предупреждение + 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'); - } + $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_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; + 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; - } + 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; - } + 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 cf8432f..451f11a 100755 --- a/simpla/UserAdmin.php +++ b/simpla/UserAdmin.php @@ -13,79 +13,64 @@ class UserAdmin extends Simpla { - public function fetch() - { - $user = new stdClass; - if(!empty($_POST['user_info'])) - { - $user->id = $this->request->post('id', 'integer'); - $user->enabled = $this->request->post('enabled', 'boolean'); - $user->name = $this->request->post('name'); - $user->email = $this->request->post('email'); - $user->group_id = $this->request->post('group_id'); + public function fetch() + { + $user = new stdClass; + if (!empty($_POST['user_info'])) { + $user->id = $this->request->post('id', 'integer'); + $user->enabled = $this->request->post('enabled', 'boolean'); + $user->name = $this->request->post('name'); + $user->email = $this->request->post('email'); + $user->group_id = $this->request->post('group_id'); - 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; - } - } - } + 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)); + $id = $this->request->get('id', 'integer'); + if (!empty($id)) { + $user = $this->users->get_user(intval($id)); + } - if(!empty($user)) - { - $this->design->assign('user', $user); + if (!empty($user)) { + $this->design->assign('user', $user); - $orders = $this->orders->get_orders(array('user_id'=>$user->id)); - $this->design->assign('orders', $orders); + $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'); - } + $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 a2d04ff..2a33024 100755 --- a/simpla/UsersAdmin.php +++ b/simpla/UsersAdmin.php @@ -13,83 +13,86 @@ class UsersAdmin extends Simpla { - public function fetch() - { + public function fetch() + { + if ($this->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; + } + } + } + } - if($this->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; + } - 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 = 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; + } - $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); + } - // Поиск - $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']); - // Сортировка пользователей, сохраняем в сессии, чтобы текущая сортировка не сбрасывалась - 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_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); - $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'); - } + return $this->body = $this->design->fetch('users.tpl'); + } } diff --git a/simpla/ajax/add_order_product.php b/simpla/ajax/add_order_product.php index 1919e31..da84338 100755 --- a/simpla/ajax/add_order_product.php +++ b/simpla/ajax/add_order_product.php @@ -1,61 +1,62 @@ -managers->access('orders')) - return false; - - $keyword = $simpla->request->get('query', 'string'); - - $keywords = explode(' ', $keyword); - $keyword_sql = ''; - foreach($keywords as $keyword) - { - $kw = $simpla->db->escape(trim($keyword)); - $keyword_sql .= $simpla->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%'))"); - } - - - $simpla->db->query('SELECT p.id, p.name, i.filename as image FROM __products p - LEFT JOIN __images i ON i.product_id=p.id AND i.position=(SELECT MIN(position) FROM __images WHERE product_id=p.id LIMIT 1) - LEFT JOIN __variants pv ON pv.product_id=p.id AND (pv.stock IS NULL OR pv.stock>0) - WHERE 1 '.$keyword_sql.' AND pv.id - GROUP BY p.id - ORDER BY p.name LIMIT ?', $limit); - foreach($simpla->db->results() as $product) - $products[$product->id] = $product; - - $variants = array(); - if(!empty($products)) - { - $simpla->db->query('SELECT v.id, v.name, v.sku, v.price, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.product_id FROM __variants v WHERE v.product_id in(?@) AND (v.stock IS NULL OR v.stock>0) AND v.price>0 ORDER BY v.position', $simpla->settings->max_order_amount, array_keys($products)); - $variants = $simpla->db->results(); - } - - foreach($variants as $variant) - if(isset($products[$variant->product_id])) - $products[$variant->product_id]->variants[] = $variant; - - $suggestions = array(); - foreach($products as $product) - { - if(!empty($product->variants)) - { - $suggestion = new stdClass; - if(!empty($product->image)) - $product->image = $simpla->design->resize_modifier($product->image, 35, 35); - $suggestion->value = $product->name; - $suggestion->data = $product; - $suggestions[] = $suggestion; - } - } - - $res = new stdClass; - $res->query = $keyword; - $res->suggestions = $suggestions; - header("Content-type: application/json; charset=UTF-8"); - header("Cache-Control: must-revalidate"); - header("Pragma: no-cache"); - header("Expires: -1"); - print json_encode($res); +managers->access('orders')) { + return false; + } + + $keyword = $simpla->request->get('query', 'string'); + + $keywords = explode(' ', $keyword); + $keyword_sql = ''; + foreach ($keywords as $keyword) { + $kw = $simpla->db->escape(trim($keyword)); + $keyword_sql .= $simpla->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%'))"); + } + + + $simpla->db->query('SELECT p.id, p.name, i.filename as image FROM __products p + LEFT JOIN __images i ON i.product_id=p.id AND i.position=(SELECT MIN(position) FROM __images WHERE product_id=p.id LIMIT 1) + LEFT JOIN __variants pv ON pv.product_id=p.id AND (pv.stock IS NULL OR pv.stock>0) + WHERE 1 '.$keyword_sql.' AND pv.id + GROUP BY p.id + ORDER BY p.name LIMIT ?', $limit); + foreach ($simpla->db->results() as $product) { + $products[$product->id] = $product; + } + + $variants = array(); + if (!empty($products)) { + $simpla->db->query('SELECT v.id, v.name, v.sku, v.price, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.product_id FROM __variants v WHERE v.product_id in(?@) AND (v.stock IS NULL OR v.stock>0) AND v.price>0 ORDER BY v.position', $simpla->settings->max_order_amount, array_keys($products)); + $variants = $simpla->db->results(); + } + + foreach ($variants as $variant) { + if (isset($products[$variant->product_id])) { + $products[$variant->product_id]->variants[] = $variant; + } + } + + $suggestions = array(); + foreach ($products as $product) { + if (!empty($product->variants)) { + $suggestion = new stdClass; + if (!empty($product->image)) { + $product->image = $simpla->design->resize_modifier($product->image, 35, 35); + } + $suggestion->value = $product->name; + $suggestion->data = $product; + $suggestions[] = $suggestion; + } + } + + $res = new stdClass; + $res->query = $keyword; + $res->suggestions = $suggestions; + header("Content-type: application/json; charset=UTF-8"); + header("Cache-Control: must-revalidate"); + header("Pragma: no-cache"); + header("Expires: -1"); + print json_encode($res); diff --git a/simpla/ajax/export.php b/simpla/ajax/export.php index 21305bf..d7b56e2 100755 --- a/simpla/ajax/export.php +++ b/simpla/ajax/export.php @@ -1,195 +1,188 @@ - 'Категория', - 'name'=> 'Товар', - 'price'=> 'Цена', - 'url'=> 'Адрес', - 'visible'=> 'Видим', - 'featured'=> 'Рекомендуемый', - 'brand'=> 'Бренд', - 'variant'=> 'Вариант', - 'compare_price'=> 'Старая цена', - 'sku'=> 'Артикул', - 'stock'=> 'Склад', - 'meta_title'=> 'Заголовок страницы', - 'meta_keywords'=> 'Ключевые слова', - 'meta_description'=> 'Описание страницы', - 'annotation'=> 'Аннотация', - 'body'=> 'Описание', - 'images'=> 'Изображения' - ); - - private $column_delimiter = ';'; - private $subcategory_delimiter = '/'; - private $products_count = 10; - private $export_files_dir = '../files/export/'; - private $filename = 'export.csv'; - - public function fetch() - { - - if(!$this->managers->access('export')) - return array('error' => 'Permission denied'); - - // Эксель кушает только 1251 - $this->db->query('SET NAMES cp1251'); - - // Страница, которую экспортируем - $page = $this->request->get('page', 'integer'); - if(empty($page) || $page==1) - { - $page = 1; - // Если начали сначала - удалим старый файл экспорта - if(is_writable($this->export_files_dir.$this->filename)) - unlink($this->export_files_dir.$this->filename); - } - - // Открываем файл экспорта на добавление - $f = fopen($this->export_files_dir.$this->filename, 'ab'); - - // - foreach($this->columns_names as $key => $value) - $this->columns_names[$key] = $this->convert_str_encoding($value, 'windows-1251', 'UTF-8', $key); - - // Добавим в список колонок свойства товаров - $features = $this->features->get_features(); - foreach($features as $feature) - $this->columns_names[$feature->name] = $feature->name; - - // Если начали сначала - добавим в первую строку названия колонок - if($page == 1) - { - fputcsv($f, $this->columns_names, $this->column_delimiter); - } - - // Все товары - $products = array(); - foreach($this->products->get_products(array('page'=>$page, 'limit'=>$this->products_count)) as $p) - { - $products[$p->id] = (array)$p; - - // Свойства товаров - $options = $this->features->get_product_options($p->id); - foreach($options as $option) - { - if(!isset($products[$option->product_id][$option->name])) - $products[$option->product_id][$option->name] = str_replace(',', '.', trim($option->value)); - } - - } - - - if(!empty($products)) - { - // Категории товаров - foreach($products as $p_id=>&$product) - { - $categories = array(); - $cats = $this->categories->get_product_categories($p_id); - foreach($cats as $category) - { - $path = array(); - $cat = $this->categories->get_category((int)$category->category_id); - if(!empty($cat)) - { - // Вычисляем составляющие категории - foreach($cat->path as $p) - $path[] = str_replace($this->subcategory_delimiter, '\\'.$this->subcategory_delimiter, $p->name); - // Добавляем категорию к товару - $categories[] = implode('/', $path); - } - } - $product['category'] = implode(', ', $categories); - } - - // Изображения товаров - $images = $this->products->get_images(array('product_id'=>array_keys($products))); - foreach($images as $image) - { - // Добавляем изображения к товару чезер запятую - if(empty($products[$image->product_id]['images'])) - $products[$image->product_id]['images'] = $image->filename; - else - $products[$image->product_id]['images'] .= ', '.$image->filename; - } - - $variants = $this->variants->get_variants(array('product_id'=>array_keys($products))); - - foreach($variants as $variant) - { - if(isset($products[$variant->product_id])) - { - $v = array(); - $v['variant'] = $variant->name; - $v['price'] = $variant->price; - $v['compare_price'] = $variant->compare_price; - $v['sku'] = $variant->sku; - $v['stock'] = $variant->stock; - if($variant->infinity) - $v['stock'] = ''; - $products[$variant->product_id]['variants'][] = $v; - } - } - - foreach($products as &$product) - { - $variants = $product['variants']; - unset($product['variants']); - - if(isset($variants)) - foreach($variants as $variant) - { - $result = array(); - $result = $product; - foreach($variant as $name=>$value) - $result[$name]=$value; - - foreach($this->columns_names as $internal_name=>$column_name) - { - if(isset($result[$internal_name])) - $res[$internal_name] = $result[$internal_name]; - else - $res[$internal_name] = ''; - } - fputcsv($f, $res, $this->column_delimiter); - - } - } - } - - $total_products = $this->products->count_products(); - - if($this->products_count*$page < $total_products) - return array('end'=>false, 'page'=>$page, 'totalpages'=>$total_products/$this->products_count); - else - return array('end'=>true, 'page'=>$page, 'totalpages'=>$total_products/$this->products_count); - - fclose($f); - - } - -} - -$export_ajax = new ExportAjax(); -$data = $export_ajax->fetch(); - -header("Content-type: application/json; charset=utf-8"); -header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); -header("Pragma: no-cache"); -header("Expires: -1"); -$json = json_encode($data); -print $json; + 'Категория', + 'name'=> 'Товар', + 'price'=> 'Цена', + 'url'=> 'Адрес', + 'visible'=> 'Видим', + 'featured'=> 'Рекомендуемый', + 'brand'=> 'Бренд', + 'variant'=> 'Вариант', + 'compare_price'=> 'Старая цена', + 'sku'=> 'Артикул', + 'stock'=> 'Склад', + 'meta_title'=> 'Заголовок страницы', + 'meta_keywords'=> 'Ключевые слова', + 'meta_description'=> 'Описание страницы', + 'annotation'=> 'Аннотация', + 'body'=> 'Описание', + 'images'=> 'Изображения' + ); + + private $column_delimiter = ';'; + private $subcategory_delimiter = '/'; + private $products_count = 10; + private $export_files_dir = '../files/export/'; + private $filename = 'export.csv'; + + public function fetch() + { + if (!$this->managers->access('export')) { + return array('error' => 'Permission denied'); + } + + // Эксель кушает только 1251 + $this->db->query('SET NAMES cp1251'); + + // Страница, которую экспортируем + $page = $this->request->get('page', 'integer'); + if (empty($page) || $page==1) { + $page = 1; + // Если начали сначала - удалим старый файл экспорта + if (is_writable($this->export_files_dir.$this->filename)) { + unlink($this->export_files_dir.$this->filename); + } + } + + // Открываем файл экспорта на добавление + $f = fopen($this->export_files_dir.$this->filename, 'ab'); + + // + foreach ($this->columns_names as $key => $value) { + $this->columns_names[$key] = $this->convert_str_encoding($value, 'windows-1251', 'UTF-8', $key); + } + + // Добавим в список колонок свойства товаров + $features = $this->features->get_features(); + foreach ($features as $feature) { + $this->columns_names[$feature->name] = $feature->name; + } + + // Если начали сначала - добавим в первую строку названия колонок + if ($page == 1) { + fputcsv($f, $this->columns_names, $this->column_delimiter); + } + + // Все товары + $products = array(); + foreach ($this->products->get_products(array('page'=>$page, 'limit'=>$this->products_count)) as $p) { + $products[$p->id] = (array)$p; + + // Свойства товаров + $options = $this->features->get_product_options($p->id); + foreach ($options as $option) { + if (!isset($products[$option->product_id][$option->name])) { + $products[$option->product_id][$option->name] = str_replace(',', '.', trim($option->value)); + } + } + } + + + if (!empty($products)) { + // Категории товаров + foreach ($products as $p_id=>&$product) { + $categories = array(); + $cats = $this->categories->get_product_categories($p_id); + foreach ($cats as $category) { + $path = array(); + $cat = $this->categories->get_category((int)$category->category_id); + if (!empty($cat)) { + // Вычисляем составляющие категории + foreach ($cat->path as $p) { + $path[] = str_replace($this->subcategory_delimiter, '\\'.$this->subcategory_delimiter, $p->name); + } + // Добавляем категорию к товару + $categories[] = implode('/', $path); + } + } + $product['category'] = implode(', ', $categories); + } + + // Изображения товаров + $images = $this->products->get_images(array('product_id'=>array_keys($products))); + foreach ($images as $image) { + // Добавляем изображения к товару чезер запятую + if (empty($products[$image->product_id]['images'])) { + $products[$image->product_id]['images'] = $image->filename; + } else { + $products[$image->product_id]['images'] .= ', '.$image->filename; + } + } + + $variants = $this->variants->get_variants(array('product_id'=>array_keys($products))); + + foreach ($variants as $variant) { + if (isset($products[$variant->product_id])) { + $v = array(); + $v['variant'] = $variant->name; + $v['price'] = $variant->price; + $v['compare_price'] = $variant->compare_price; + $v['sku'] = $variant->sku; + $v['stock'] = $variant->stock; + if ($variant->infinity) { + $v['stock'] = ''; + } + $products[$variant->product_id]['variants'][] = $v; + } + } + + foreach ($products as &$product) { + $variants = $product['variants']; + unset($product['variants']); + + if (isset($variants)) { + foreach ($variants as $variant) { + $result = array(); + $result = $product; + foreach ($variant as $name=>$value) { + $result[$name]=$value; + } + + foreach ($this->columns_names as $internal_name=>$column_name) { + if (isset($result[$internal_name])) { + $res[$internal_name] = $result[$internal_name]; + } else { + $res[$internal_name] = ''; + } + } + fputcsv($f, $res, $this->column_delimiter); + } + } + } + } + + $total_products = $this->products->count_products(); + + if ($this->products_count*$page < $total_products) { + return array('end'=>false, 'page'=>$page, 'totalpages'=>$total_products/$this->products_count); + } else { + return array('end'=>true, 'page'=>$page, 'totalpages'=>$total_products/$this->products_count); + } + + fclose($f); + } +} + +$export_ajax = new ExportAjax(); +$data = $export_ajax->fetch(); + +header("Content-type: application/json; charset=utf-8"); +header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); +header("Pragma: no-cache"); +header("Expires: -1"); +$json = json_encode($data); +print $json; diff --git a/simpla/ajax/export_users.php b/simpla/ajax/export_users.php index f9def2e..6124e52 100755 --- a/simpla/ajax/export_users.php +++ b/simpla/ajax/export_users.php @@ -1,99 +1,100 @@ - 'Имя', - 'email' => 'Email', - 'group_name' => 'Группа', - 'discount' => 'Скидка', - 'enabled' => 'Активен', - 'created' => 'Дата', - 'last_ip' => 'Последний IP' - ); - - private $column_delimiter = ';'; - private $users_count = 10; - private $export_files_dir = '../files/export_users/'; - private $filename = 'users.csv'; - - public function fetch() - { - if(!$this->managers->access('users')) - return array('error' => 'Permission denied'); - - // Эксель кушает только 1251 - $this->db->query('SET NAMES cp1251'); - - // Страница, которую экспортируем - $page = $this->request->get('page', 'integer'); - if(empty($page) || $page==1) - { - $page = 1; - // Если начали сначала - удалим старый файл экспорта - if(is_writable($this->export_files_dir.$this->filename)) - unlink($this->export_files_dir.$this->filename); - } - - // Открываем файл экспорта на добавление - $f = fopen($this->export_files_dir.$this->filename, 'ab'); - - foreach($this->columns_names as $key => $value) - $this->columns_names[$key] = $this->convert_str_encoding($value, 'windows-1251', 'UTF-8', $key); - - // Если начали сначала - добавим в первую строку названия колонок - if($page == 1) - { - fputcsv($f, $this->columns_names, $this->column_delimiter); - } - - $filter = array(); - $filter['page'] = $page; - $filter['limit'] = $this->users_count; - if($this->request->get('group_id')) - $filter['group_id'] = intval($this->request->get('group_id')); - $filter['sort'] = $this->request->get('sort'); - $filter['keyword'] = $this->request->get('keyword'); - - // Выбираем пользователей - $users = array(); - foreach($this->users->get_users($filter) as $u) - { - $str = array(); - foreach($this->columns_names as $n=>$c) - $str[] = $u->$n; - - fputcsv($f, $str, $this->column_delimiter); - } - - $total_users = $this->users->count_users($filter); - - if($this->users_count*$page < $total_users) - return array('end'=>false, 'page'=>$page, 'totalpages'=>$total_users/$this->users_count); - else - return array('end'=>true, 'page'=>$page, 'totalpages'=>$total_users/$this->users_count); - - fclose($f); - - } - -} - -$export_ajax = new ExportAjax(); -$json = json_encode($export_ajax->fetch()); -header("Content-type: application/json; charset=utf-8"); -header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); -header("Pragma: no-cache"); -header("Expires: -1"); -print $json; + 'Имя', + 'email' => 'Email', + 'group_name' => 'Группа', + 'discount' => 'Скидка', + 'enabled' => 'Активен', + 'created' => 'Дата', + 'last_ip' => 'Последний IP' + ); + + private $column_delimiter = ';'; + private $users_count = 10; + private $export_files_dir = '../files/export_users/'; + private $filename = 'users.csv'; + + public function fetch() + { + if (!$this->managers->access('users')) { + return array('error' => 'Permission denied'); + } + + // Эксель кушает только 1251 + $this->db->query('SET NAMES cp1251'); + + // Страница, которую экспортируем + $page = $this->request->get('page', 'integer'); + if (empty($page) || $page==1) { + $page = 1; + // Если начали сначала - удалим старый файл экспорта + if (is_writable($this->export_files_dir.$this->filename)) { + unlink($this->export_files_dir.$this->filename); + } + } + + // Открываем файл экспорта на добавление + $f = fopen($this->export_files_dir.$this->filename, 'ab'); + + foreach ($this->columns_names as $key => $value) { + $this->columns_names[$key] = $this->convert_str_encoding($value, 'windows-1251', 'UTF-8', $key); + } + + // Если начали сначала - добавим в первую строку названия колонок + if ($page == 1) { + fputcsv($f, $this->columns_names, $this->column_delimiter); + } + + $filter = array(); + $filter['page'] = $page; + $filter['limit'] = $this->users_count; + if ($this->request->get('group_id')) { + $filter['group_id'] = intval($this->request->get('group_id')); + } + $filter['sort'] = $this->request->get('sort'); + $filter['keyword'] = $this->request->get('keyword'); + + // Выбираем пользователей + $users = array(); + foreach ($this->users->get_users($filter) as $u) { + $str = array(); + foreach ($this->columns_names as $n=>$c) { + $str[] = $u->$n; + } + + fputcsv($f, $str, $this->column_delimiter); + } + + $total_users = $this->users->count_users($filter); + + if ($this->users_count*$page < $total_users) { + return array('end'=>false, 'page'=>$page, 'totalpages'=>$total_users/$this->users_count); + } else { + return array('end'=>true, 'page'=>$page, 'totalpages'=>$total_users/$this->users_count); + } + + fclose($f); + } +} + +$export_ajax = new ExportAjax(); +$json = json_encode($export_ajax->fetch()); +header("Content-type: application/json; charset=utf-8"); +header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); +header("Pragma: no-cache"); +header("Expires: -1"); +print $json; diff --git a/simpla/ajax/get_features.php b/simpla/ajax/get_features.php index 9e73b7a..4296490 100755 --- a/simpla/ajax/get_features.php +++ b/simpla/ajax/get_features.php @@ -1,34 +1,35 @@ -request->get('category_id', 'integer'); - $product_id = $simpla->request->get('product_id', 'integer'); - - if(!empty($category_id)) - $features = $simpla->features->get_features(array('category_id'=>$category_id)); - else - $features = $simpla->features->get_features(); - - $options = array(); - if(!empty($product_id)) - { - $opts = $simpla->features->get_product_options($product_id); - foreach($opts as $opt) - $options[$opt->feature_id] = $opt; - } - - foreach($features as &$f) - { - if(isset($options[$f->id])) - $f->value = $options[$f->id]->value; - else - $f->value = ''; - } - - header("Content-type: application/json; charset=UTF-8"); - header("Cache-Control: must-revalidate"); - header("Pragma: no-cache"); - header("Expires: -1"); - print json_encode($features); +request->get('category_id', 'integer'); + $product_id = $simpla->request->get('product_id', 'integer'); + + if (!empty($category_id)) { + $features = $simpla->features->get_features(array('category_id'=>$category_id)); + } else { + $features = $simpla->features->get_features(); + } + + $options = array(); + if (!empty($product_id)) { + $opts = $simpla->features->get_product_options($product_id); + foreach ($opts as $opt) { + $options[$opt->feature_id] = $opt; + } + } + + foreach ($features as &$f) { + if (isset($options[$f->id])) { + $f->value = $options[$f->id]->value; + } else { + $f->value = ''; + } + } + + header("Content-type: application/json; charset=UTF-8"); + header("Cache-Control: must-revalidate"); + header("Pragma: no-cache"); + header("Expires: -1"); + print json_encode($features); diff --git a/simpla/ajax/get_images.php b/simpla/ajax/get_images.php index c474a78..a9c06c9 100755 --- a/simpla/ajax/get_images.php +++ b/simpla/ajax/get_images.php @@ -1,46 +1,46 @@ -responseData->results as $result) - $images[] = urldecode(str_replace('%2520', '%20', $result->url)); - -header("Content-type: application/json; charset=UTF-8"); -header("Cache-Control: must-revalidate"); -header("Pragma: no-cache"); -header("Expires: -1"); - -print(json_encode($images)); \ No newline at end of file +responseData->results as $result) { + $images[] = urldecode(str_replace('%2520', '%20', $result->url)); + } +} + +header("Content-type: application/json; charset=UTF-8"); +header("Cache-Control: must-revalidate"); +header("Pragma: no-cache"); +header("Expires: -1"); + +print(json_encode($images)); diff --git a/simpla/ajax/get_info.php b/simpla/ajax/get_info.php index a64ed05..22b32f2 100755 --- a/simpla/ajax/get_info.php +++ b/simpla/ajax/get_info.php @@ -11,22 +11,23 @@ // Для использования прокси используйте строки: -define("USE_PROXY", 0); // 1 = использовать прокси -define("PROXY", 'xxx.xxx.xxx.xxx:80'); -define("PROXY_USER", 'login:password'); +define("USE_PROXY", 0); // 1 = использовать прокси +define("PROXY", 'xxx.xxx.xxx.xxx:80'); +define("PROXY_USER", 'login:password'); // Настройка региона в маркете -define("REGION", '213'); // 213 - москва, список регионов: http://search.yaca.yandex.ru/geo.c2n -define("DOMAIN", 'market.yandex.ru'); // для украины нужно market.yandex.ua - +define("REGION", '213'); // 213 - москва, список регионов: http://search.yaca.yandex.ru/geo.c2n +define("DOMAIN", 'market.yandex.ru'); // для украины нужно market.yandex.ua + session_start(); // Временный файл для хранения cookies // Так как временный файл существует до окончания выполнения скрипта, // сохраняем его содержимое в сессию $cookies_filename = tempnam(sys_get_temp_dir(), 'yandex_market_cookies'); -if(!empty($_SESSION['yandex_market_cookies'])) - file_put_contents($cookies_filename, $_SESSION['yandex_market_cookies']); +if (!empty($_SESSION['yandex_market_cookies'])) { + file_put_contents($cookies_filename, $_SESSION['yandex_market_cookies']); +} // Для изменения региона нужно обратиться сюда $url = 'http://tune.yandex.ru/region/?retpath=http%3A%2F%2Fmarket.yandex.ru'; @@ -34,13 +35,13 @@ // Ключевое слово для поиска $keyword = ''; -if(!empty($_GET['keyword'])) - $keyword = $_GET['keyword']; +if (!empty($_GET['keyword'])) { + $keyword = $_GET['keyword']; +} // Если нам запостили капчу, отправим ее на проверку -if(!empty($_GET['captcha'])) -{ - $page = get_page("http://".DOMAIN."/checkcaptcha?key=".urlencode($_SESSION['captcha_key'])."&retpath=".urlencode(html_entity_decode($_SESSION['captcha_retpath']))."&rep=".urlencode($_GET['captcha'])); +if (!empty($_GET['captcha'])) { + $page = get_page("http://".DOMAIN."/checkcaptcha?key=".urlencode($_SESSION['captcha_key'])."&retpath=".urlencode(html_entity_decode($_SESSION['captcha_retpath']))."&rep=".urlencode($_GET['captcha'])); } // Адрес страницы с результатами поиска @@ -49,35 +50,30 @@ $page = get_page($url); //print $page; -if(preg_match('/src="(http:.*captchaimg[^"]*)" alt=""\/>/ui', $page, $match)) -{ - $captcha_image = $match[1]; - - if(preg_match('/
/ui', $page, $match)) { + $captcha_image = $match[1]; + + if (preg_match('/
captcha = base64_encode(get_page($captcha_image)); - //print "
"; +if (!empty($captcha_image)) { + $result->captcha = base64_encode(get_page($captcha_image)); + //print "
"; } $result->product = parse_product($page); header("Content-type: application/json; charset=UTF-8"); header("Cache-Control: must-revalidate"); header("Pragma: no-cache"); -header("Expires: -1"); +header("Expires: -1"); print(json_encode($result)); @@ -85,151 +81,146 @@ // Функция забирает содержимое страницы по указанному URL function get_page($url, $level=0) { - // Имя временного файла, в котором хранятся куки для CURL - global $cookies_filename; - - // Максимальный уровень рекурсии - $max_level = 20; - if($level >= $max_level) - return false; - - // Должен быть установлен curl - if(!function_exists('curl_init')) - { - trigger_error("curl does not exists"); - return false; - } - - // Инициализируем curl - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_HEADER, true); - curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"); - curl_setopt($ch, CURLOPT_TIMEOUT, 10); - curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies_filename); - curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies_filename); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', - 'Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3', - 'Connection: keep-alive' - )); - - // Нужно установить регион - $cookies_content = file_get_contents($cookies_filename); - $new_cookies_content = preg_replace('/(yandex_gid).*/', "$1\t".REGION, $cookies_content); - if($new_cookies_content == $cookies_content) - $new_cookies_content .= "\n.yandex.ua\tTRUE\t/\tFALSE\t1\tyandex_gid\t".REGION."\n.yandex.ru\tTRUE\t/\tFALSE\t0\tyandex_gid\t".REGION; - file_put_contents($cookies_filename, $new_cookies_content); - - // Яндекс любит рефереров и реже банит, если реферер правдоподобный - // Указываем реферером адрес, запрошенный в прошлый раз - if(!empty($_SESSION['yandex_market_last_visited_url'])) - curl_setopt($ch, CURLOPT_REFERER, $_SESSION['yandex_market_last_visited_url']); - - - // Настройки прокси: - if(USE_PROXY) - { - curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); - curl_setopt($ch, CURLOPT_PROXY, PROXY); - curl_setopt($ch, CURLOPT_PROXYUSERPWD, PROXY_USER); - } - - // Выполняем запрос по адресу - $data = curl_exec($ch); - /* - if(!$data) - { - trigger_error(curl_error($ch)); - return false; - } - */ - - // Проверяем код ответа для проверки, нет ли редиректа - $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - // Больше нам curl не нужен - curl_close($ch); - - // Записываем в сессию куки, которые отложил curl во временный файл - $_SESSION['yandex_market_cookies'] = file_get_contents($cookies_filename); - - // Отделяем тело страницы от заголовка - $dataArray = explode("\r\n\r\n", $data, 2); - - // Делим ответ на заголовок и тело - if(count($dataArray)!=2) - return false; - - list($header, $body) = $dataArray; - - // В случае редиректа рекурсивно следуем за яндексом - if($httpCode == 301 || $httpCode == 302) - { - $matches = array(); - preg_match('/Location:([^\n]*)/', $header, $matches); - if(isset($matches[1])) - { - // Рекурсивно запрашиваем страницу по адресу редиректа - $body = get_page(trim($matches[1]), $level+1); - } - } - // В случае 404 пробуем еще несколько раз - яндекс часто глючит и отдает 404 - if($httpCode == 404) - { - $body = get_page($url, $level+1); - } - - // Сохраняем последний посещенный URL для реферера - $_SESSION['yandex_market_last_visited_url'] = $url; - - // Отдаем тело страницы - return $body; + // Имя временного файла, в котором хранятся куки для CURL + global $cookies_filename; + + // Максимальный уровень рекурсии + $max_level = 20; + if ($level >= $max_level) { + return false; + } + + // Должен быть установлен curl + if (!function_exists('curl_init')) { + trigger_error("curl does not exists"); + return false; + } + + // Инициализируем curl + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_HEADER, true); + curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"); + curl_setopt($ch, CURLOPT_TIMEOUT, 10); + curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies_filename); + curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies_filename); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3', + 'Connection: keep-alive' + )); + + // Нужно установить регион + $cookies_content = file_get_contents($cookies_filename); + $new_cookies_content = preg_replace('/(yandex_gid).*/', "$1\t".REGION, $cookies_content); + if ($new_cookies_content == $cookies_content) { + $new_cookies_content .= "\n.yandex.ua\tTRUE\t/\tFALSE\t1\tyandex_gid\t".REGION."\n.yandex.ru\tTRUE\t/\tFALSE\t0\tyandex_gid\t".REGION; + } + file_put_contents($cookies_filename, $new_cookies_content); + + // Яндекс любит рефереров и реже банит, если реферер правдоподобный + // Указываем реферером адрес, запрошенный в прошлый раз + if (!empty($_SESSION['yandex_market_last_visited_url'])) { + curl_setopt($ch, CURLOPT_REFERER, $_SESSION['yandex_market_last_visited_url']); + } + + + // Настройки прокси: + if (USE_PROXY) { + curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); + curl_setopt($ch, CURLOPT_PROXY, PROXY); + curl_setopt($ch, CURLOPT_PROXYUSERPWD, PROXY_USER); + } + + // Выполняем запрос по адресу + $data = curl_exec($ch); + /* + if(!$data) + { + trigger_error(curl_error($ch)); + return false; + } + */ + + // Проверяем код ответа для проверки, нет ли редиректа + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + // Больше нам curl не нужен + curl_close($ch); + + // Записываем в сессию куки, которые отложил curl во временный файл + $_SESSION['yandex_market_cookies'] = file_get_contents($cookies_filename); + + // Отделяем тело страницы от заголовка + $dataArray = explode("\r\n\r\n", $data, 2); + + // Делим ответ на заголовок и тело + if (count($dataArray)!=2) { + return false; + } + + list($header, $body) = $dataArray; + + // В случае редиректа рекурсивно следуем за яндексом + if ($httpCode == 301 || $httpCode == 302) { + $matches = array(); + preg_match('/Location:([^\n]*)/', $header, $matches); + if (isset($matches[1])) { + // Рекурсивно запрашиваем страницу по адресу редиректа + $body = get_page(trim($matches[1]), $level+1); + } + } + // В случае 404 пробуем еще несколько раз - яндекс часто глючит и отдает 404 + if ($httpCode == 404) { + $body = get_page($url, $level+1); + } + + // Сохраняем последний посещенный URL для реферера + $_SESSION['yandex_market_last_visited_url'] = $url; + + // Отдаем тело страницы + return $body; } // Функция отдает результат парсинга страницы function parse_product($page) { - // Если это страница товара, ишем описание - if(preg_match_all('/