This commit is contained in:
Alan
2026-02-14 19:34:54 +03:00
commit 5c3329238b
867 changed files with 214778 additions and 0 deletions

2
api/.htaccess Normal file
View File

@@ -0,0 +1,2 @@
order deny,allow
deny from all

256
api/Actions.php Normal file
View File

@@ -0,0 +1,256 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Actions extends Simpla
{
/*
*
* Функция возвращает пост по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
public function get_post($id)
{
if(is_int($id))
$where = $this->db->placehold(' WHERE b.id=? ', intval($id));
else
$where = $this->db->placehold(' WHERE b.url=? ', $id);
$query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text, b.meta_title,
b.meta_keywords, b.meta_description, b.visible, b.date, b.image
FROM __actions b $where LIMIT 1");
if($this->db->query($query))
return $this->db->result();
else
return false;
}
/*
*
* Функция возвращает массив постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_posts($filter = array())
{
// По умолчанию
$limit = 1000;
$page = 1;
$post_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
$posts = array();
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(!empty($filter['id']))
$post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible']));
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
$query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text,
b.meta_title, b.meta_keywords, b.meta_description, b.visible,
b.date, b.image
FROM __actions b WHERE 1 $post_id_filter $visible_filter $keyword_filter
ORDER BY date DESC, id DESC $sql_limit");
$this->db->query($query);
return $this->db->results();
}
/*
*
* Функция вычисляет количество постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function count_posts($filter = array())
{
$post_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
if(!empty($filter['id']))
$post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible']));
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$query = "SELECT COUNT(distinct b.id) as count
FROM __actions b WHERE 1 $post_id_filter $visible_filter $keyword_filter";
if($this->db->query($query))
return $this->db->result('count');
else
return false;
}
/*
*
* Создание поста
* @param $post
*
*/
public function add_post($post)
{
if(isset($post->date))
{
$date = $post->date;
unset($post->date);
//$date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format);
$date_query = ', date=NOW()';
}else{
$date_query = '';
}
$query = $this->db->placehold("INSERT INTO __actions SET ?% $date_query", $post);
if(!$this->db->query($query))
return false;
else
return $this->db->insert_id();
}
/*
*
* Обновить пост(ы)
* @param $post
*
*/
public function update_post($id, $post)
{
$query = $this->db->placehold("UPDATE __actions SET ?% WHERE id in(?@) LIMIT ?", $post, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
/*
*
* Удалить пост
* @param $id
*
*/
public function delete_post($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __actions WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
{
$query = $this->db->placehold("DELETE FROM __comments WHERE type='actions' AND object_id=? LIMIT 1", intval($id));
if($this->db->query($query))
return true;
}
}
return false;
}
public function delete_image($id)
{
$query = $this->db->placehold("SELECT image FROM __actions WHERE id=?", intval($id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __actions SET image=NULL WHERE id=?", $id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __actions WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->original_images_dir.$filename);
}
}
}
/*
*
* Следующий пост
* @param $post
*
*/
public function get_next_post($id)
{
$this->db->query("SELECT date FROM __actions WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __actions WHERE date=? AND id>? AND visible ORDER BY id limit 1)
UNION
(SELECT id FROM __actions WHERE date>? AND visible ORDER BY date, id limit 1)",
$date, $id, $date);
$next_id = $this->db->result('id');
if($next_id){
$post = $this->get_post(intval($next_id));
$post->image = Img::get('files/originals/' . $post->image, array('width' => 200, 'height' => 200));
return $post;
}
else
return false;
}
/*
*
* Предыдущий пост
* @param $post
*
*/
public function get_prev_post($id)
{
$this->db->query("SELECT date FROM __actions WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __actions WHERE date=? AND id<? AND visible ORDER BY id DESC limit 1)
UNION
(SELECT id FROM __actions WHERE date<? AND visible ORDER BY date DESC, id DESC limit 1)",
$date, $id, $date);
$prev_id = $this->db->result('id');
if($prev_id){
$post = $this->get_post(intval($prev_id));
$post->image = Img::get('files/originals/' . $post->image, array('width' => 200, 'height' => 200));
return $post;
}
else
return false;
}
}

673
api/Articles.php Normal file
View File

@@ -0,0 +1,673 @@
<?php //exit;
/**
* Simpla CMS
*
* @copyright 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Articles extends Simpla
{
// Список указателей на категории в дереве категорий (ключ = id категории)
private $all_categories;
// Дерево категорий
private $categories_tree;
/*
*
* Функция возвращает пост по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
public function get_article($id)
{
if(is_int($id))
$where = $this->db->placehold(' WHERE a.id=? ', intval($id));
else
$where = $this->db->placehold(' WHERE a.url=? ', $id);
$query = $this->db->placehold("SELECT a.*, c.url category_url, c.name category, a.image
FROM __articles a
LEFT JOIN __article_categories c ON c.id = a.category_id
$where LIMIT 1");
if($this->db->query($query))
return $this->db->result();
else
return false;
}
/*
*
* Функция возвращает массив постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_articles($filter = array())
{
// По умолчанию
$limit = 1000;
$page = 1;
$article_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
$category_filter = '';
$group_by = '';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(!empty($filter['id']))
$article_id_filter = $this->db->placehold('AND a.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND a.visible = ?', intval($filter['visible']));
if(isset($filter['category_id'])){
$category_filter = $this->db->placehold('INNER JOIN __articles_categories pc ON pc.article_id = a.id AND pc.category_id in(?@)', (array)$filter['category_id']);
//$category_filter = $this->db->placehold('AND a.category_id in(?@)', (array)$filter['category_id']);
$group_by = "GROUP BY a.id";
}
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (a.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR a.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
$query = $this->db->placehold("SELECT a.*
FROM __articles a
$category_filter
WHERE 1 $article_id_filter $visible_filter $keyword_filter
$group_by ORDER BY date DESC, id DESC $sql_limit");
$this->db->query($query);
return $this->db->results();
}
/*
*
* Функция вычисляет количество постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function count_articles($filter = array())
{
$post_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
$category_filter = '';
if(!empty($filter['id']))
$post_id_filter = $this->db->placehold('AND a.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND a.visible = ?', intval($filter['visible']));
if(isset($filter['category_id']))
$category_filter = $this->db->placehold('INNER JOIN __articles_categories pc ON pc.article_id = a.id AND pc.category_id in(?@)', (array)$filter['category_id']);
//$category_filter = $this->db->placehold('AND a.category_id in(?@)', (array)$filter['category_id']);
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (a.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR a.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$query = "SELECT COUNT(distinct a.id) as count
FROM __articles a $category_filter WHERE 1 $post_id_filter $visible_filter $keyword_filter";
if($this->db->query($query))
return $this->db->result('count');
else
return false;
}
/*
*
* Создание поста
* @param $post
*
*/
public function add_article($post)
{
if(isset($post->date))
{
$date = $post->date;
unset($post->date);
//$date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format);
$date_query = $this->db->placehold(', date=?', date('Y-m-d H:i:s', strtotime($date) ) ) ;
}
$query = $this->db->placehold("INSERT INTO __articles SET ?% $date_query", $post);
if(!$this->db->query($query))
return false;
else
return $this->db->insert_id();
}
/*
*
* Обновить пост(ы)
* @param $post
*
*/
public function update_article($id, $post)
{
$query = $this->db->placehold("UPDATE __articles SET ?% WHERE id in(?@) LIMIT ?", $post, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
/*
*
* Удалить пост
* @param $id
*
*/
public function delete_article($id)
{
if(!empty($id))
{
// Удаляем связанные
$related = $this->get_related_objects($id);
foreach($related as $r)
$this->delete_related_object($id, $r->related_id);
$query = $this->db->placehold("DELETE FROM __articles WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
{
$query = $this->db->placehold("DELETE FROM __comments WHERE type='article' AND object_id=? LIMIT 1", intval($id));
if($this->db->query($query))
return true;
}
}
return false;
}
/*
*
* Следующий пост
* @param $post
*
*/
public function get_next_article($id, $category=0)
{
$this->db->query("SELECT date FROM __articles WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __articles WHERE date=? AND id>? AND visible ORDER BY id limit 1)
UNION
(SELECT id FROM __articles WHERE date>? AND visible ORDER BY date, id limit 1)",
$date, $id, $date);
$next_id = $this->db->result('id');
if($next_id)
return $this->get_article(intval($next_id));
else
return false;
}
/*
*
* Предыдущий пост
* @param $post
*
*/
public function get_prev_article($id, $category=0)
{
$this->db->query("SELECT date FROM __articles WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __articles WHERE date=? AND id<? AND visible ORDER BY id DESC limit 1)
UNION
(SELECT id FROM __articles WHERE date<? AND visible ORDER BY date DESC, id DESC limit 1)",
$date, $id, $date);
$prev_id = $this->db->result('id');
if($prev_id)
return $this->get_article(intval($prev_id));
else
return false;
}
function get_related_objects($article_id = array())
{
if(empty($article_id))
return array();
$query = $this->db->placehold("SELECT article_id, object_id, type
FROM __article_objects
WHERE article_id in(?@)", (array)$article_id);
$this->db->query($query);
return $this->db->results();
}
function get_related_markas($article_id){
$this->db->query("SELECT * FROM __article_models WHERE model_id=0 AND article_id = " . (int)$article_id);
$rows = $this->db->results();
$res = array();
foreach($rows as $row) $res[] = $this->marka->get_brand( (int)$row->marka_id);
return $res;
}
function get_related_models($article_id){
$this->db->query("SELECT * FROM __article_models WHERE model_id != 0 AND article_id = " . (int)$article_id);
$rows = $this->db->results();
$res = array();
foreach($rows as $row) $res[] = $this->model->get_model( (int)$row->model_id );
return $res;
}
function get_related_pages($article_id)
{
$this->db->query("SELECT * FROM __article_pages WHERE article_id = " . (int)$article_id);
$rows = $this->db->results();
$res = array();
foreach ($rows as $row) $res[] = $this->pages->get_page( (int)$row->page_id );
// remove empty elements
return array_filter($res);
}
function get_related_articles($filter = array())
{
// По умолчанию
$limit = 1000;
$type_filter = '';
$object_id_filter = '';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(!empty($filter['type']))
$type_filter = $this->db->placehold('AND type=?', $filter['type']);
if(!empty($filter['id']))
$object_id_filter = $this->db->placehold('AND object_id=?', (int)$filter['id']);
$sql_limit = $this->db->placehold(' LIMIT ?', $limit);
$query = $this->db->placehold("SELECT article_id, object_id, type
FROM __article_objects
WHERE 1 $object_id_filter $type_filter $sql_limit");
$this->db->query($query);
return $this->db->results();
}
// Функция возвращает связанные товары
public function add_related_object($article_id, $related_id, $type)
{
$query = $this->db->placehold("INSERT IGNORE INTO __article_objects SET article_id=?, object_id=?, type=?", $article_id, $related_id, $type);
$this->db->query($query);
return $related_id;
}
// Удаление связанного товара
public function delete_related_object($article_id, $related_id)
{
$query = $this->db->placehold("DELETE FROM __article_objects WHERE article_id=? AND object_id=? LIMIT 1", intval($article_id), intval($related_id));
$this->db->query($query);
}
// Функция возвращает массив категорий
public function get_categories($id)
{
if(!isset($this->categories_tree))
$this->init_categories();
if(!empty($id))
{
if(isset($this->all_categories[$id]))
return $result = $this->all_categories[$id];
}
return $this->all_categories;
}
// Функция возвращает массив категорий статей
public function get_articles_categories_filter($filter = array())
{
if(!isset($this->categories_tree))
$this->init_categories();
/*mt1sk*/if ($filter['article_id'] == -1) {
return $this->all_categories[0];
} else/*/mt1sk*/
if(!empty($filter['article_id']))
{
$query = $this->db->placehold("SELECT category_id FROM __articles_categories WHERE article_id in(?@) ORDER BY position", (array)$filter['article_id']);
$this->db->query($query);
$categories_ids = $this->db->results('category_id');
$result = array();
foreach($categories_ids as $id)
if(isset($this->all_categories[$id]))
$result[$id] = $this->all_categories[$id];
return $result;
}
return $this->all_categories;
}
// Функция возвращает id категорий для заданной статьи
public function get_article_categories($article_id)
{
$query = $this->db->placehold("SELECT article_id, category_id, position FROM __articles_categories WHERE article_id in(?@) ORDER BY position", (array)$article_id);
$this->db->query($query);
return $this->db->results();
}
// Функция возвращает id категорий для всех статей
public function get_articles_categories()
{
$query = $this->db->placehold("SELECT article_id, category_id, position FROM __articles_categories ORDER BY position");
$this->db->query($query);
return $this->db->results();
}
// Добавить категорию к заданному товару
public function add_article_category($article_id, $category_id, $position=0)
{
$query = $this->db->placehold("INSERT IGNORE INTO __articles_categories SET article_id=?, category_id=?, position=?", $article_id, $category_id, $position);
$this->db->query($query);
}
// Удалить категорию заданного товара
public function delete_article_category($article_id, $category_id)
{
$query = $this->db->placehold("DELETE FROM __articles_categories WHERE article_id=? AND category_id=? LIMIT 1", intval($article_id), intval($category_id));
$this->db->query($query);
}
// Функция возвращает дерево категорий
public function get_categories_tree()
{
if(!isset($this->categories_tree))
$this->init_categories();
return $this->categories_tree;
}
// Функция возвращает заданную категорию
public function get_category($id)
{
if(!isset($this->all_categories))
$this->init_categories();
if(is_int($id) && array_key_exists(intval($id), $this->all_categories))
return $category = $this->all_categories[intval($id)];
elseif(is_string($id))
foreach ($this->all_categories as $category)
if ($category->url == $id)
return $this->get_category((int)$category->id);
return false;
}
// Добавление категории
public function add_category($category)
{
$category = (array)$category;
if(empty($category['url']))
{
$category['url'] = preg_replace("/[\s]+/ui", '_', $category['name']);
$category['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $category['url']));
}
$this->db->query("INSERT INTO __article_categories SET ?%", $category);
$id = $this->db->insert_id();
$this->db->query("UPDATE __article_categories SET position=id WHERE id=?", $id);
$this->init_categories();
return $id;
}
// Изменение категории
public function update_category($id, $category)
{
$query = $this->db->placehold("UPDATE __article_categories SET ?% WHERE id=? LIMIT 1", $category, intval($id));
$this->db->query($query);
$this->init_categories();
return $id;
}
// Удаление категории
public function delete_category($id)
{
if(!$category = $this->get_category(intval($id)))
return false;
foreach($category->children as $id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __article_categories WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __articles_categories WHERE category_id in(?@)", $category->children);
$this->db->query($query);
$this->init_categories();
}
}
return true;
}
// Инициализация категорий, после которой категории будем выбирать из локальной переменной
private function init_categories()
{
// Дерево категорий
$tree = new stdClass();
$tree->subcategories = array();
// Указатели на узлы дерева
$pointers = array();
$pointers[0] = &$tree;
$pointers[0]->path = array();
// Выбираем все категории
// if($_SESSION['admin'] == 'admin')
$query = $this->db->placehold("SELECT * FROM __article_categories ORDER BY parent_id, position");
// else
// $query = $this->db->placehold("SELECT * FROM __article_categories WHERE `visible`=1 ORDER BY parent_id, position");
$this->db->query($query);
$categories = $this->db->results(); //echo '<!--';var_dump($categories); echo '-->';
$finish = false;
// Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть
while(!empty($categories) && !$finish)
{
$flag = false;
// Проходим все выбранные категории
foreach($categories as $k=>$category)
{
if(isset($pointers[$category->parent_id]))
{
// В дерево категорий (через указатель) добавляем текущую категорию
$pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category;
// Путь к текущей категории
$curr = clone($pointers[$category->id]);
$pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr));
// Убираем использованную категорию из массива категорий
unset($categories[$k]);
$flag = true;
}
}
if(!$flag) $finish = true;
}
// Для каждой категории id всех ее деток узнаем
$ids = array_reverse(array_keys($pointers));
foreach($ids as $id)
{
if($id>0)
{
$pointers[$id]->children[] = $id;
if(isset($pointers[$pointers[$id]->parent_id]->children))
$pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children);
else
$pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children;
}
}
unset($pointers[0]);
$this->categories_tree = $tree->subcategories;
$this->all_categories = $pointers;
}
public function delete_image($id)
{
$query = $this->db->placehold("SELECT image FROM __articles WHERE id=?", intval($id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __articles SET image=NULL WHERE id=?", $id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __articles WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->original_images_dir.$filename);
}
}
}
/*
// Функция возвращает массив категорий
public function get_articles_categories($filter = array())
{
if(!isset($this->articles_categories_tree))
$this->init_articles_categories();
return $this->all_articles_categories;
}
// Функция возвращает дерево категорий
public function get_articles_categories_tree()
{
if(!isset($this->articles_categories_tree))
$this->init_articles_categories();
return $this->articles_categories_tree;
}
// Функция возвращает заданную категорию
public function get_articles_category($id)
{
if(!isset($this->all_articles_categories))
$this->init_articles_categories();
if(is_int($id) && array_key_exists(intval($id), $this->all_articles_categories))
return $category = $this->all_articles_categories[intval($id)];
elseif(is_string($id))
foreach ($this->all_articles_categories as $category)
if ($category->url == $id)
return $this->get_articles_category((int)$category->id);
return false;
}
// Добавление категории
public function add_articles_category($category)
{
$category = (array)$category;
if(empty($category['url']))
{
$category['url'] = preg_replace("/[\s]+/ui", '_', $category['name']);
$category['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $category['url']));
}
// Если есть категория с таким URL, добавляем к нему число
while($this->get_articles_category((string)$category['url']))
{
if(preg_match('/(.+)_([0-9]+)$/', $category['url'], $parts))
$category['url'] = $parts[1].'_'.($parts[2]+1);
else
$category['url'] = $category['url'].'_2';
}
$this->db->query("INSERT INTO __articles_categories SET ?%", $category);
$id = $this->db->insert_id();
$this->db->query("UPDATE __articles_categories SET position=id WHERE id=?", $id);
$this->init_articles_categories();
return $id;
}
// Изменение категории
public function update_articles_category($id, $category)
{
$query = $this->db->placehold("UPDATE __articles_categories SET ?% WHERE id=? LIMIT 1", $category, intval($id));
$this->db->query($query);
$this->init_articles_categories();
return $id;
}
// Удаление категории
public function delete_articles_category($id)
{
if(!$category = $this->get_articles_category(intval($id)))
return false;
foreach($category->children as $id)
{
if(!empty($id))
{
$this->delete_image($id);
$query = $this->db->placehold("DELETE FROM __articles_categories WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __products_articles_categories WHERE category_id=?", $id);
$this->db->query($query);
$this->init_articles_categories();
}
}
return true;
}
*/
// Изменение категории
public function update_articles_category($id, $category)
{
$query = $this->db->placehold("UPDATE __article_categories SET ?% WHERE id=? LIMIT 1", $category, intval($id));
$this->db->query($query);
// $this->init_articles_categories();
return $id;
}
// Удалить изображение категории
public function delete_category_image($category_id)
{
$query = $this->db->placehold("SELECT image FROM __article_categories WHERE id=?", $category_id);
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __article_categories SET image=NULL WHERE id=?", $category_id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __article_categories WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->categories_images_dir.$filename);
}
// $this->init_articles_categories();
}
}
}

208
api/ArticlesCategories.php Normal file
View File

@@ -0,0 +1,208 @@
<?php
/**
* Simpla CMS
*
* @copyright 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class ArticlesCategories extends Simpla
{
// Список указателей на категории в дереве категорий (ключ = id категории)
private $all_articles_categories;
// Дерево категорий
private $articles_categories_tree;
// Функция возвращает массив категорий
public function get_articles_categories($filter = array())
{
if(!isset($this->articles_categories_tree))
$this->init_articles_categories();
return $this->all_articles_categories;
}
// Функция возвращает дерево категорий
public function get_articles_categories_tree()
{
if(!isset($this->articles_categories_tree))
$this->init_articles_categories();
return $this->articles_categories_tree;
}
// Функция возвращает заданную категорию
public function get_articles_category($id)
{
if(!isset($this->all_articles_categories))
$this->init_articles_categories();
if(is_int($id) && array_key_exists(intval($id), $this->all_articles_categories))
return $category = $this->all_articles_categories[intval($id)];
elseif(is_string($id))
foreach ($this->all_articles_categories as $category)
if ($category->url == $id)
return $this->get_articles_category((int)$category->id);
return false;
}
// Добавление категории
public function add_articles_category($category)
{
$category = (array)$category;
if(empty($category['url']))
{
$category['url'] = preg_replace("/[\s]+/ui", '_', $category['name']);
$category['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $category['url']));
}
// Если есть категория с таким URL, добавляем к нему число
while($this->get_articles_category((string)$category['url']))
{
if(preg_match('/(.+)_([0-9]+)$/', $category['url'], $parts))
$category['url'] = $parts[1].'_'.($parts[2]+1);
else
$category['url'] = $category['url'].'_2';
}
$this->db->query("INSERT INTO __articles_categories SET ?%", $category);
$id = $this->db->insert_id();
$this->db->query("UPDATE __articles_categories SET position=id WHERE id=?", $id);
$this->init_articles_categories();
return $id;
}
// Изменение категории
public function update_articles_category($id, $category)
{
$query = $this->db->placehold("UPDATE __articles_categories SET ?% WHERE id=? LIMIT 1", $category, intval($id));
$this->db->query($query);
$this->init_articles_categories();
return $id;
}
// Удаление категории
public function delete_articles_category($id)
{
if(!$category = $this->get_articles_category(intval($id)))
return false;
foreach($category->children as $id)
{
if(!empty($id))
{
$this->delete_image($id);
$query = $this->db->placehold("DELETE FROM __articles_categories WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __products_articles_categories WHERE category_id=?", $id);
$this->db->query($query);
$this->init_articles_categories();
}
}
return true;
}
// Удалить изображение категории
public function delete_image($category_id)
{
$query = $this->db->placehold("SELECT image FROM __article_categories WHERE id=?", $category_id);
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __article_categories SET image=NULL WHERE id=?", $category_id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __article_categories WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->categories_images_dir.$filename);
}
$this->init_articles_categories();
}
}
// Инициализация категорий, после которой категории будем выбирать из локальной переменной
private function init_articles_categories()
{
// Дерево категорий
$tree = new stdClass();
$tree->subcategories = array();
// Указатели на узлы дерева
$pointers = array();
$pointers[0] = &$tree;
$pointers[0]->path = array();
// Выбираем все категории
$query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position
FROM __articles_categories c ORDER BY c.parent_id, c.position");
// Выбор категорий с подсчетом количества товаров для каждой. Может тормозить при большом количестве товаров.
// $query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position, COUNT(p.id) as products_count
// FROM __articles_categories c LEFT JOIN __products_categories pc ON pc.category_id=c.id LEFT JOIN __products p ON p.id=pc.product_id AND p.visible GROUP BY c.id ORDER BY c.parent_id, c.position");
$this->db->query($query);
$articles_categories = $this->db->results();
$finish = false;
// Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть
while(!empty($articles_categories) && !$finish)
{
$flag = false;
// Проходим все выбранные категории
foreach($articles_categories as $k=>$category)
{
if(isset($pointers[$category->parent_id]))
{
// В дерево категорий (через указатель) добавляем текущую категорию
$pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category;
// Путь к текущей категории
$curr = $pointers[$category->id];
$pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr));
// Убираем использованную категорию из массива категорий
unset($articles_categories[$k]);
$flag = true;
}
}
if(!$flag) $finish = true;
}
// Для каждой категории id всех ее деток узнаем
$ids = array_reverse(array_keys($pointers));
foreach($ids as $id)
{
if($id>0)
{
$pointers[$id]->children[] = $id;
if(isset($pointers[$pointers[$id]->parent_id]->children))
$pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children);
else
$pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children;
// Добавляем количество товаров к родительской категории, если текущая видима
// if(isset($pointers[$pointers[$id]->parent_id]) && $pointers[$id]->visible)
// $pointers[$pointers[$id]->parent_id]->products_count += $pointers[$id]->products_count;
}
}
unset($pointers[0]);
unset($ids);
$this->articles_categories_tree = $tree->subcategories;
$this->all_articles_categories = $pointers;
}
}

162
api/Banners.php Normal file
View File

@@ -0,0 +1,162 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Banners extends Simpla
{
/*
*
* Функция возвращает пост по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
/******
Получить список групп баннеров
*********/
public function get_groups()
{
$this->db->query("SELECT SQL_CALC_FOUND_ROWS * FROM s_banners_groups ORDER BY `id`;");
$banner_groups = $this->db->results();
$this->db->query("SELECT FOUND_ROWS() as count");
$count_banner_groups = $this->db->result('count');
return array($banner_groups,$count_banner_groups);
}
/******
Получить информацию о группе и список баннеров группы
*********/
public function get_group($id)
{
$this->db->query("SELECT * FROM s_banners_groups WHERE `id` = ? ",(int)$id);
return $this->db->result();
}
/******
Обновление группы
*********/
public function update_group($id, $values)
{
$query = $this->db->placehold("UPDATE __banners_groups SET ?% WHERE id in (?@) LIMIT ?", $values, (array)$id, count((array)$id));
if($this->db->query($query))
{
return $id;
}
}
/******
Удаление группы
*********/
public function delete_group($id)
{
//Находим и удаляем все баннеры ииз группы
list($banners,$counts) = $this->get_banners(array('BannerOfPage'=>1000,'group'=>$id));
foreach($banners as $key=>$value)
{
$this->delete_banner($banners[$key]->id);
}
list($banners,$counts) = $this->get_banners(array('BannerOfPage'=>1000,'group'=>$id)); //Проверяем, все ли баннеры удалены
if($counts > 0)
exit("<h3>ГРУППУ НЕ УДАЛОСЬ УДАЛИТЬ<br>В ГРУППЕ ОСТАЛИСЬ БАННЕРЫ КОТОРЫЕ НЕ УДАЛОСЬ УДАЛИТЬ<br>ПОПРОБУЙТЕ УДАЛИТЬ ВРУЧНУЮ!</h3>");
else
$this->db->query("DELETE FROM __banners_groups WHERE id=? LIMIT 1", intval($id));
}
/******
Получить список баннеров
*********/
public function get_banners($filter = ARRAY())
{
$filter['BannerOfPage'] = isset($filter['BannerOfPage'])?$filter['BannerOfPage']:100;
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', (max(1, $this->request->get('page', 'integer'))-1)*$filter['BannerOfPage'], $filter['BannerOfPage']);
//Фильтруем по группе баннеров
$filter['query'][0] = $this->db->placehold("`id_group`='?'", (int)$filter['group']);
//Фильтруем баннеры где указан параметр "показывать на всех страницах" и "активен"
if(isset($filter['show_all_pages']))
{
$filter['query'][0] .= " AND `visible`='1' AND ( `show_all_pages`='1'";
}
//Фильтруем по категории, бренду и странице
if(isset($filter['category']) && $filter['category']!='')
$filter['query'][] = $this->db->placehold("`categories` regexp '[[:<:]](?)[[:>:]]'", (int)$filter['category']);
if(isset($filter['brand']) && $filter['brand']!='')
$filter['query'][] = $this->db->placehold("`brands` regexp '[[:<:]](?)[[:>:]]'", (int)$filter['brand']);
if(isset($filter['page']) && $filter['page']!='')
$filter['query'][] = $this->db->placehold("`pages` regexp '[[:<:]](?)[[:>:]]'", (int)$filter['page']);
//Собираем значение фильтра в запрос
$filter['query'] = ((isset($filter['query']) && count($filter['query'])>0)?"WHERE ".implode(" OR ",$filter['query']):$filter['query']).(isset($filter['show_all_pages'])?")":'');
//Выполнение запроса
$this->db->query("SELECT SQL_CALC_FOUND_ROWS * FROM s_banners ".$filter['query']." ORDER BY position ".$sql_limit);
$banners = $this->db->results();
$this->db->query("SELECT FOUND_ROWS() as count");
$count_banners = $this->db->result('count');
return array($banners,$count_banners);
}
/******
Получить информацию баннера
*********/
public function get_banner($id)
{
$this->db->query("SELECT * FROM s_banners WHERE `id` = ? ",(int)$id);
return $this->db->result();
}
/******
Обновление баннера
*********/
public function update_banner($id, $values)
{
$query = $this->db->placehold("UPDATE __banners SET ?% WHERE id in (?@) LIMIT ?", $values, (array)$id, count((array)$id));
if($this->db->query($query))
{
return $id;
}
}
/******
Удаление баннера
*********/
public function delete_banner($id)
{
$banner = $this->get_banner($id);
$query = $this->db->placehold("DELETE FROM __banners WHERE id=? LIMIT 1", intval($id));
if($this->delete_image($banner->image) && $this->db->query($query))
{
return true;
}else{
return false;
}
}
/******
Удаление изображения баннера
*********/
function delete_image($imageFileName)
{
if($imageFileName!='' && file_exists($this->config->root_dir.$this->config->banners_images_dir.$imageFileName))
@unlink($this->config->root_dir.$this->config->banners_images_dir.$imageFileName);
return true;
}
}

249
api/Blog.php Normal file
View File

@@ -0,0 +1,249 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Blog extends Simpla
{
/*
*
* Функция возвращает пост по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
public function get_post($id)
{
if(is_int($id))
$where = $this->db->placehold(' WHERE b.id=? ', intval($id));
else
$where = $this->db->placehold(' WHERE b.url=? ', $id);
$query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text, b.meta_title,
b.meta_keywords, b.meta_description, b.visible, b.date, b.image
FROM __blog b $where LIMIT 1");
if($this->db->query($query))
return $this->db->result();
else
return false;
}
/*
*
* Функция возвращает массив постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_posts($filter = array())
{
// По умолчанию
$limit = 1000;
$page = 1;
$post_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
$posts = array();
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(!empty($filter['id']))
$post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible']));
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
$query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text,
b.meta_title, b.meta_keywords, b.meta_description, b.visible,
b.date, b.image
FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter
ORDER BY date DESC, id DESC $sql_limit");
$this->db->query($query);
return $this->db->results();
}
/*
*
* Функция вычисляет количество постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function count_posts($filter = array())
{
$post_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
if(!empty($filter['id']))
$post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible']));
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$query = "SELECT COUNT(distinct b.id) as count
FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter";
if($this->db->query($query))
return $this->db->result('count');
else
return false;
}
/*
*
* Создание поста
* @param $post
*
*/
public function add_post($post)
{
if(isset($post->date))
{
$date = $post->date;
unset($post->date);
//$date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format);
$date_query = ', date=NOW()';
}else{
$date_query = '';
}
$query = $this->db->placehold("INSERT INTO __blog SET ?% $date_query", $post);
if(!$this->db->query($query))
return false;
else
return $this->db->insert_id();
}
/*
*
* Обновить пост(ы)
* @param $post
*
*/
public function update_post($id, $post)
{
$query = $this->db->placehold("UPDATE __blog SET ?% WHERE id in(?@) LIMIT ?", $post, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
/*
*
* Удалить пост
* @param $id
*
*/
public function delete_post($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __blog WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
{
$query = $this->db->placehold("DELETE FROM __comments WHERE type='blog' AND object_id=? LIMIT 1", intval($id));
if($this->db->query($query))
return true;
}
}
return false;
}
public function delete_image($id)
{
$query = $this->db->placehold("SELECT image FROM __blog WHERE id=?", intval($id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __blog SET image=NULL WHERE id=?", $id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __blog WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->original_images_dir.$filename);
}
}
}
/*
*
* Следующий пост
* @param $post
*
*/
public function get_next_post($id)
{
$this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __blog WHERE date=? AND id>? AND visible ORDER BY id limit 1)
UNION
(SELECT id FROM __blog WHERE date>? AND visible ORDER BY date, id limit 1)",
$date, $id, $date);
$next_id = $this->db->result('id');
if($next_id)
return $this->get_post(intval($next_id));
else
return false;
}
/*
*
* Предыдущий пост
* @param $post
*
*/
public function get_prev_post($id)
{
$this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __blog WHERE date=? AND id<? AND visible ORDER BY id DESC limit 1)
UNION
(SELECT id FROM __blog WHERE date<? AND visible ORDER BY date DESC, id DESC limit 1)",
$date, $id, $date);
$prev_id = $this->db->result('id');
if($prev_id)
return $this->get_post(intval($prev_id));
else
return false;
}
}

142
api/Brands.php Normal file
View File

@@ -0,0 +1,142 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Brands extends Simpla
{
/*
*
* Функция возвращает массив брендов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_brands($filter = array())
{
$brands = array();
$category_id_filter = '';
if(!empty($filter['category_id']))
$category_id_filter = $this->db->placehold('LEFT JOIN __products p ON p.brand_id=b.id LEFT JOIN __products_categories pc ON p.id = pc.product_id WHERE pc.category_id in(?@)', (array)$filter['category_id']);
// Выбираем все бренды
$query = $this->db->placehold("SELECT DISTINCT b.*
FROM __brands b $category_id_filter ORDER BY binary b.name");
$this->db->query($query);
$res = $this->db->results();
if(empty($filter['var']) || $filter['var'] != 'all_brands') return $res;
$out = array();
foreach($res as $row){
$this->db->query( $this->db->placehold("SELECT id FROM __products WHERE brand_id='".$row->id."' AND visible=1 LIMIT 1 ") );
if($this->db->num_rows()) $out[] = $row;
}
return $out;
}
/*
*
* Функция возвращает бренд по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
public function get_brand($id)
{
if(is_int($id))
$filter = $this->db->placehold('id = ?', $id);
else
$filter = $this->db->placehold('url = ?', $id);
$query = "SELECT * FROM __brands WHERE $filter ORDER BY name LIMIT 1";
$this->db->query($query);
return $this->db->result();
}
/*
*
* Добавление бренда
* @param $brand
*
*/
public function add_brand($brand)
{
$brand = (array)$brand;
if(empty($brand['url']))
{
$brand['url'] = preg_replace("/[\s]+/ui", '_', $brand['name']);
$brand['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $brand['url']));
}
$this->db->query("INSERT INTO __brands SET ?%", $brand);
return $this->db->insert_id();
}
/*
*
* Обновление бренда(ов)
* @param $brand
*
*/
public function update_brand($id, $brand)
{
$query = $this->db->placehold("UPDATE __brands SET ?% WHERE id=? LIMIT 1", $brand, intval($id));
$this->db->query($query);
return $id;
}
/*
*
* Удаление бренда
* @param $id
*
*/
public function delete_brand($id)
{
if(!empty($id))
{
$this->delete_image($id);
$query = $this->db->placehold("DELETE FROM __brands WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$query = $this->db->placehold("UPDATE __products SET brand_id=NULL WHERE brand_id=?", $id);
$this->db->query($query);
}
}
/*
*
* Удаление изображения бренда
* @param $id
*
*/
public function delete_image($brand_id)
{
$query = $this->db->placehold("SELECT image FROM __brands WHERE id=?", intval($brand_id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __brands SET image=NULL WHERE id=?", $brand_id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __brands WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->brands_images_dir.$filename);
}
}
}
}

104
api/Callbacks.php Normal file
View File

@@ -0,0 +1,104 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Callbacks extends Simpla
{
public function email_callback_admin($callback_id)
{
if(!($callback = $this->callbacks->get_callback(intval($callback_id))))
return false;
$this->design->assign('callback', $callback);
// Отправляем письмо
$email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_callback_admin.tpl');
$subject = $this->design->get_var('subject');
$this->notify->email($this->settings->comment_email, $subject, $email_template, "$callback->name <$callback->phone>", "$callback->name <$callback->phone>");
}
public function get_callback($id)
{
$query = $this->db->placehold("SELECT c.id, c.name, c.phone, c.message, c.date FROM __callbacks c WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
return $this->db->result();
else
return false;
}
public function get_callbacks($filter = array(), $new_on_top = false)
{
// По умолчанию
$limit = 0;
$page = 1;
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
if($new_on_top)
$sort='DESC';
else
$sort='ASC';
$query = $this->db->placehold("SELECT c.id, c.name, c.phone, c.date, c.message
FROM __callbacks c WHERE 1 ORDER BY c.id $sort $sql_limit");
$this->db->query($query);
return $this->db->results();
}
public function add_callback($callback)
{
$query = $this->db->placehold('INSERT INTO __callbacks
SET ?%,
date = NOW()',
$callback);
if(!$this->db->query($query))
return false;
$id = $this->db->insert_id();
return $id;
}
public function update_callback($id, $callback)
{
$date_query = '';
if(isset($fedback->date))
{
$date = $callback->date;
unset($callback->date);
$date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format);
}
$query = $this->db->placehold("UPDATE __callbacks SET ?% $date_query WHERE id in(?@) LIMIT 1", $callback, (array)$id);
$this->db->query($query);
return $id;
}
public function delete_callback($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __callbacks WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
}
}
}

409
api/Cart.php Normal file
View File

@@ -0,0 +1,409 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Cart extends Simpla
{
/*
*
* Функция возвращает корзину
*
*/
public function get_cart()
{
$cart = new stdClass();
$cart->purchases = array();
$cart->total_price = 0;
$cart->total_weight = 0;
$cart->total_products = 0;
$cart->coupon = null;
$cart->discount = 0;
$cart->coupon_discount = 0;
// Берем из сессии список variant_id=>amount
if(!empty($_SESSION['shopping_cart']))
{
$session_items = $_SESSION['shopping_cart'];
$variants = $this->variants->get_variants(array('id'=>array_keys($session_items)));
if(!empty($variants))
{
foreach($variants as $variant)
{
$items[$variant->id] = new stdClass();
$items[$variant->id]->variant = $variant;
$items[$variant->id]->amount = $session_items[$variant->id]['amount'];
$items[$variant->id]->options = $session_items[$variant->id]['options'];
$products_ids[] = $variant->product_id;
}
$products = array();
foreach($this->products->get_products(array('id'=>$products_ids)) as $p)
$products[$p->id]=$p;
$images = $this->products->get_images(array('product_id'=>$products_ids));
foreach($images as $image)
$products[$image->product_id]->images[$image->id] = $image;
foreach($items as $variant_id=>$item)
{
$purchase = null;
if(!empty($products[$item->variant->product_id]))
{
$purchase = new stdClass();
$purchase->product = $products[$item->variant->product_id];
$purchase->variant = $item->variant;
$purchase->amount = $item->amount;
$purchase->options = unserialize($item->options);
//$feat = $this->features->get_product_options($item->variant->product_id);
$feat = $this->features->get_features(array('category_id'=>$cat->id,'in_variant'=>1));
foreach($feat AS $fe){
$purchase->features[$fe->id] = $fe;
}
$cart->purchases[] = $purchase;
$cart->total_price += $item->variant->price*$item->amount;
$cart->total_weight += $item->variant->weight*$item->amount;
$cart->total_products += $item->amount;
}
}
// Пользовательская скидка
$cart->discount = 0;
if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id'])))
$cart->discount = $user->discount;
$cart->total_price *= (100-$cart->discount)/100;
// Скидка по купону
if(isset($_SESSION['coupon_code']))
{
$cart->coupon = $this->coupons->get_coupon($_SESSION['coupon_code']);
if($cart->coupon && $cart->coupon->valid && $cart->total_price>=$cart->coupon->min_order_price)
{
if($cart->coupon->type=='absolute')
{
// Абсолютная скидка не более суммы заказа
$cart->coupon_discount = $cart->total_price>$cart->coupon->value?$cart->coupon->value:$cart->total_price;
$cart->total_price = max(0, $cart->total_price-$cart->coupon->value);
}
else
{
$cart->coupon_discount = $cart->total_price * ($cart->coupon->value)/100;
$cart->total_price = $cart->total_price-$cart->coupon_discount;
}
}
else
{
unset($_SESSION['coupon_code']);
}
}
}
}
return $cart;
}
/*
*
* Добавление варианта товара в корзину
*
*/
public function add_item($variant_id, $amount = 1,$options = array())
{
$amount = max(1, $amount);
if(isset($_SESSION['shopping_cart'][$variant_id]['amount']))
$amount = max(1, $amount+$_SESSION['shopping_cart'][$variant_id]['amount']);
// Выберем товар из базы, заодно убедившись в его существовании
$variant = $this->variants->get_variant($variant_id);
// Если товар существует, добавим его в корзину
if(!empty($variant) && ($variant->stock>0) )
{
// Не дадим больше чем на складе
$amount = min($amount, $variant->stock);
$options = serialize($options);
$_SESSION['shopping_cart'][$variant_id] = intval($amount);
$_SESSION['shopping_cart'][$variant_id] = array('amount'=>intval($amount),'options'=>$options);
}
}
/*
*
* Обновление количества товара
*
*/
public function update_item($variant_id, $amount = 1,$options = array())
{
$amount = max(1, $amount);
// Выберем товар из базы, заодно убедившись в его существовании
$variant = $this->variants->get_variant($variant_id);
// Если товар существует, добавим его в корзину
if(!empty($variant) && $variant->stock>0)
{
// Не дадим больше чем на складе
$amount = min($amount, $variant->stock);
$options = serialize($options);
$_SESSION['shopping_cart'][$variant_id] = array('amount'=>intval($amount),'options'=>$options);
//$_SESSION['shopping_cart'][$variant_id] = intval($amount);
}
}
/*
*
* Удаление товара из корзины
*
*/
public function delete_item($variant_id)
{
unset($_SESSION['shopping_cart'][$variant_id]);
}
/*
*
* Очистка корзины
*
*/
public function empty_cart()
{
unset($_SESSION['shopping_cart']);
unset($_SESSION['coupon_code']);
}
/*
*
* Применить купон
*
*/
public function apply_coupon($coupon_code)
{
$coupon = $this->coupons->get_coupon((string)$coupon_code);
if($coupon && $coupon->valid)
{
$_SESSION['coupon_code'] = $coupon->code;
}
else
{
unset($_SESSION['coupon_code']);
}
}
public function getCity2(){
$city = array(
"city--moskva"=>"Москва",
"city--sankt-peterburg"=>"Санкт-Петербург",
"city--abakan"=>"Абакан",
"city--anadyr"=>"Анадырь",
"city--anapa"=>"Анапа",
"city--arhangelsk"=>"Архангельск",
"city--astrahan"=>"Астрахань",
"city--barnaul"=>"Барнаул",
"city--belgorod"=>"Белгород",
"city--birobidzhan"=>"Биробиджан",
"city--blagoveshhensk"=>"Благовещенск",
"city--brjansk"=>"Брянск",
"city--velikij-novgorod"=>"Великий Новгород ",
"city--vladivostok"=>"Владивосток",
"city--vladikavkaz"=>"Владикавказ",
"city--vladimir"=>"Владимир",
"city--volgograd"=>"Волгоград",
"city--vologda"=>"Вологда",
"city--vorkuta"=>"Воркута",
"city--voronezh"=>"Воронеж",
"city--gorno-altajsk"=>"Горно-Алтайск",
"city--groznyj"=>"Грозный",
"city--dudinka"=>"Дудинка",
"city--ekaterinburg"=>"Екатеринбург",
"city--elizovo"=>"Елизово",
"city--ivanovo"=>"Иваново",
"city--izhevsk"=>"Ижевск",
"city--irkutsk"=>"Иркутск",
"city--ioshkar-ola"=>"Йошкар-Ола",
"city--kazan"=>"Казань",
"city--kaliningrad"=>"Калининград",
"city--kaluga"=>"Калуга",
"city--kemerovo"=>"Кемерово",
"city--kirov"=>"Киров",
"city--kostomuksha"=>"Костомукша",
"city--kostroma"=>"Кострома",
"city--krasnodar"=>"Краснодар",
"city--krasnojarsk"=>"Красноярск",
"city--kurgan"=>"Курган",
"city--kursk"=>"Курск",
"city--kyzyl"=>"Кызыл",
"city--lipeck"=>"Липецк",
"city--magadan"=>"Магадан",
"city--magnitogorsk"=>"Магнитогорск",
"city--majkop"=>"Майкоп",
"city--mahachkala"=>"Махачкала",
"city--mirnyj"=>"Мирный",
"city--murmansk"=>"Мурманск",
"city--mytishhi"=>"Мытищи",
"city--naberezhnye-chelny"=>"Набережные Челны",
"city--nadym"=>"Надым",
"city--nazran"=>"Назрань",
"city--nalchik"=>"Нальчик",
"city--narjan-mar"=>"Нарьян-Мар",
"city--nerjungri"=>"Нерюнгри",
"city--neftejugansk"=>"Нефтеюганск",
"city--nizhnevartovsk"=>"Нижневартовск",
"city--nizhnij-novgorod"=>"Нижний Новгород",
"city--novokuzneck"=>"Новокузнецк",
"city--novorossijsk"=>"Новороссийск",
"city--novosibirsk"=>"Новосибирск",
"city--novyj-urengoj"=>"Новый Уренгой",
"city--norilsk"=>"Норильск",
"city--nojabrsk"=>"Ноябрьск",
"city--omsk"=>"Омск",
"city--orel"=>"Орел",
"city--orenburg"=>"Оренбург",
"city--penza"=>"Пенза",
"city--perm"=>"Пермь",
"city--petrozavodsk"=>"Петрозаводск",
"city--petropavlovsk-kamchatskij"=>"Петропавловск-Камчатский",
"city--pskov"=>"Псков",
"city--rostov-na-donu"=>"Ростов-на-Дону",
"city--rjazan"=>"Рязань",
"city--salehard"=>"Салехард",
"city--samara"=>"Самара",
"city--saransk"=>"Саранск",
"city--saratov"=>"Саратов",
"city--smolensk"=>"Смоленск",
"city--sochi"=>"Сочи",
"city--stavropol"=>"Ставрополь",
"city--strezhevoj"=>"Стрежевой",
"city--surgut"=>"Сургут",
"city--syktyvkar"=>"Сыктывкар",
"city--tambov"=>"Тамбов",
"city--tver"=>"Тверь",
"city--toljatti"=>"Тольятти",
"city--tomsk"=>"Томск",
"city--tula"=>"Тула",
"city--tynda"=>"Тында",
"city--tjumen"=>"Тюмень",
"city--ulan-udje"=>"Улан-Удэ",
"city--uljanovsk"=>"Ульяновск",
"city--usinsk"=>"Усинск",
"city--ufa"=>"Уфа",
"city--khabarovsk"=>"Хабаровск",
"city--khanty-mansijsk"=>"Ханты-Мансийск",
"city--kholmsk"=>"Холмск",
"city--cheboksary"=>"Чебоксары",
"city--cheljabinsk"=>"Челябинск",
"city--cherepovec"=>"Череповец",
"city--cherkessk"=>"Черкесск",
"city--chita"=>"Чита",
"city--elista"=>"Элиста",
"city--yuzhno-sahalinsk"=>"Южно-Сахалинск",
"city--yakutsk"=>"Якутск",
"city--yaroslavl"=>"Ярославль",
"region--respublika-adygeja"=>"Адыгея респ.",
"region--respublika-altaj"=>"Алтай респ.",
"region--altajskij-kraj"=>"Алтайский край",
"region--amurskaja-oblast"=>"Амурская обл.",
"region--arhangelskaja-oblast"=>"Архангельская обл.",
"region--astrahanskaja-oblast"=>"Астраханская обл.",
"region--respublika-bashkortostan"=>"Башкортостан респ.",
"region--belgorodskaja-oblast"=>"Белгородская обл.",
"region--brjanskaja-oblast"=>"Брянская обл.",
"region--respublika-burjatija"=>"Бурятия респ.",
"region--vladimirskaja-oblast"=>"Владимирская обл.",
"region--volgogradskaja-oblast"=>"Волгоградская обл.",
"region--vologodskaja-oblast"=>"Вологодская обл.",
"region--voronezhskaja-oblast"=>"Воронежская обл.",
"region--respublika-dagestan"=>"Дагестан респ.",
"region--evrejskaja-ao"=>"Еврейская авт.обл.",
"region--zabajkalskij-kraj"=>"Забайкальский край",
"region--ivanovskaja-oblast"=>"Ивановская обл.",
"region--respublika-ingushetija"=>"Ингушетия респ.",
"region--irkutskaja-oblast"=>"Иркутская обл.",
"region--kabardino-balkarskaja-respublika"=>"Кабардино-Балкарская респ.",
"region--kaliningradskaja-oblast"=>"Калининградская обл.",
"region--respublika-kalmykija"=>"Калмыкия респ.",
"region--kaluzhskaja-oblast"=>"Калужская обл.",
"region--kamchatskij-kraj"=>"Камчатский край",
"region--karachaevo-cherkesskaja-respublika"=>"Карачаево-Черкесская респ.",
"region--respublika-karelija"=>"Карелия респ.",
"region--kemerovskaja-oblast"=>"Кемеровская обл.",
"region--kirovskaja-oblast"=>"Кировская обл.",
"region--respublika-komi"=>"Коми респ.",
"region--kostromskaja-oblast"=>"Костромская обл.",
"region--krasnodarskij-kraj"=>"Краснодарский край",
"region--krasnojarskij-kraj"=>"Красноярский край",
"region--kurganskaja-oblast"=>"Курганская обл.",
"region--kurskaja-oblast"=>"Курская обл.",
"region--leningradskaja-oblast"=>"Ленинградская обл.",
"region--lipeckaja-oblast"=>"Липецкая обл.",
"region--magadanskaja-oblast"=>"Магаданская обл.",
"region--respublika-marij-el"=>"Марий Эл респ.",
"region--respublika-mordovija"=>"Мордовия респ.",
"region--moskovskaja-oblast"=>"Московская обл.",
"region--murmanskaja-oblast"=>"Мурманская обл.",
"region--neneckij-ao"=>"Ненецкий АО",
"region--nizhegorodskaja-oblast"=>"Нижегородская обл.",
"region--novgorodskaja-oblast"=>"Новгородская обл.",
"region--novosibirskaja-oblast"=>"Новосибирская обл.",
"region--omskaja-oblast"=>"Омская обл.",
"region--orenburgskaja-oblast"=>"Оренбургская обл.",
"region--orlovskaja-oblast"=>"Орловская обл.",
"region--penzenskaja-oblast"=>"Пензенская обл.",
"region--permskij-kraj"=>"Пермский край",
"region--primorskij-kraj"=>"Приморский край",
"region--pskovskaja-oblast"=>"Псковская обл.",
"region--rostovskaja-oblast"=>"Ростовская обл.",
"region--rjazanskaja-oblast"=>"Рязанская обл.",
"region--samarskaja-oblast"=>"Самарская обл.",
"region--saratovskaja-oblast"=>"Саратовская обл.",
"region--respublika-saha-yakutija"=>"Саха (Якутия) респ.",
"region--sahalinskaja-oblast"=>"Сахалинская обл.",
"region--sverdlovskaja-oblast"=>"Свердловская обл.",
"region--respublika-sev.osetija-alanija"=>"Северная Осетия - Алания респ.",
"region--smolenskaja-oblast"=>"Смоленская обл.",
"region--stavropolskij-kraj"=>"Ставропольский край",
"region--tambovskaja-oblast"=>"Тамбовская обл.",
"region--respublika-tatarstan"=>"Татарстан респ.",
"region--tverskaja-oblast"=>"Тверская обл.",
"region--tomskaja-oblast"=>"Томская обл.",
"region--tulskaja-oblast"=>"Тульская обл.",
"region--respublika-tyva"=>"Тыва респ.",
"region--tjumenskaja-oblast"=>"Тюменская обл.",
"region--udmurtskaja-respublika"=>"Удмуртская респ.",
"region--uljanovskaja-oblast"=>"Ульяновская обл.",
"region--khabarovskij-kraj"=>"Хабаровский край",
"region--respublika-khakasija"=>"Хакасия респ.",
"region--khanty-mansijskij-ao"=>"Ханты-Мансийский АО - Югра",
"region--cheljabinskaja-oblast"=>"Челябинская обл.",
"region--chechenskaja-respublika"=>"Чеченская респ.",
"region--chuvashskaja-respublika"=>"Чувашия респ.",
"region--chukotskij-ao"=>"Чукотский АО",
"region--yamalo-neneckij-ao"=>"Ямало-Ненецкий АО",
"region--yaroslavskaja-oblast"=>"Ярославская обл."
);
return $city;
}
}

259
api/Categories.php Normal file
View File

@@ -0,0 +1,259 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Categories extends Simpla
{
// Список указателей на категории в дереве категорий (ключ = id категории)
private $all_categories;
// Дерево категорий
private $categories_tree;
// Функция возвращает массив категорий
public function get_categories($filter = array())
{
if(!isset($this->categories_tree))
$this->init_categories();
if(!empty($filter['product_id']))
{
$query = $this->db->placehold("SELECT category_id FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$filter['product_id']);
$this->db->query($query);
$categories_ids = $this->db->results('category_id');
$result = array();
foreach($categories_ids as $id)
if(isset($this->all_categories[$id]))
$result[$id] = $this->all_categories[$id];
return $result;
}
return $this->all_categories;
}
// Функция возвращает id категорий для заданного товара
public function get_product_categories($product_id)
{
$query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories WHERE product_id in(?@) ORDER BY position", (array)$product_id);
$this->db->query($query);
return $this->db->results();
}
// Функция возвращает id категорий для всех товаров
public function get_products_categories()
{
$query = $this->db->placehold("SELECT product_id, category_id, position FROM __products_categories ORDER BY position");
$this->db->query($query);
return $this->db->results();
}
// Функция возвращает дерево категорий
public function get_categories_tree()
{
if(!isset($this->categories_tree))
$this->init_categories();
return $this->categories_tree;
}
// Функция возвращает заданную категорию
public function get_category($id)
{
if(!isset($this->all_categories))
$this->init_categories();
if(is_int($id) && array_key_exists(intval($id), $this->all_categories))
return $category = $this->all_categories[intval($id)];
elseif(is_string($id))
foreach ($this->all_categories as $category)
if ($category->url == $id)
return $this->get_category((int)$category->id);
return false;
}
// Добавление категории
public function add_category($category)
{
$category = (array)$category;
if(empty($category['url']))
{
$category['url'] = preg_replace("/[\s]+/ui", '_', $category['name']);
$category['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $category['url']));
}
// Если есть категория с таким URL, добавляем к нему число
while($this->get_category((string)$category['url']))
{
if(preg_match('/(.+)_([0-9]+)$/', $category['url'], $parts))
$category['url'] = $parts[1].'_'.($parts[2]+1);
else
$category['url'] = $category['url'].'_2';
}
$this->db->query("INSERT INTO __categories SET ?%", $category);
$id = $this->db->insert_id();
$this->db->query("UPDATE __categories SET position=id WHERE id=?", $id);
unset($this->categories_tree);
unset($this->all_categories);
return $id;
}
// Изменение категории
public function update_category($id, $category)
{
$query = $this->db->placehold("UPDATE __categories SET ?% WHERE id=? LIMIT 1", $category, intval($id));
$this->db->query($query);
unset($this->categories_tree);
unset($this->all_categories);
return $id;
}
// Удаление категории
public function delete_category($ids)
{
$ids = (array) $ids;
foreach($ids as $id)
{
if($category = $this->get_category(intval($id)))
$this->delete_image($category->children);
if(!empty($category->children))
{
$query = $this->db->placehold("DELETE FROM __categories WHERE id in(?@)", $category->children);
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __products_categories WHERE category_id in(?@)", $category->children);
$this->db->query($query);
}
}
unset($this->categories_tree);
unset($this->all_categories);
return true;
}
// Добавить категорию к заданному товару
public function add_product_category($product_id, $category_id, $position=0)
{
$query = $this->db->placehold("INSERT IGNORE INTO __products_categories SET product_id=?, category_id=?, position=?", $product_id, $category_id, $position);
$this->db->query($query);
}
// Удалить категорию заданного товара
public function delete_product_category($product_id, $category_id)
{
$query = $this->db->placehold("DELETE FROM __products_categories WHERE product_id=? AND category_id=? LIMIT 1", intval($product_id), intval($category_id));
$this->db->query($query);
}
// Удалить изображение категории
public function delete_image($categories_ids)
{
$categories_ids = (array) $categories_ids;
$query = $this->db->placehold("SELECT image FROM __categories WHERE id in(?@)", $categories_ids);
$this->db->query($query);
$filenames = $this->db->results('image');
if(!empty($filenames))
{
$query = $this->db->placehold("UPDATE __categories SET image=NULL WHERE id in(?@)", $categories_ids);
$this->db->query($query);
foreach($filenames as $filename)
{
$query = $this->db->placehold("SELECT count(*) as count FROM __categories WHERE image=?", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->categories_images_dir.$filename);
}
}
unset($this->categories_tree);
unset($this->all_categories);
}
}
// Инициализация категорий, после которой категории будем выбирать из локальной переменной
private function init_categories()
{
// Дерево категорий
$tree = new stdClass();
$tree->subcategories = array();
// Указатели на узлы дерева
$pointers = array();
$pointers[0] = &$tree;
$pointers[0]->path = array();
// Выбираем все категории
$query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position, c.ym, c.menu, c.category_h1, c.text_bottom, c.anons, c.menu_name, c.from_subs, c.how2show
FROM __categories c ORDER BY c.parent_id, c.position");
// Выбор категорий с подсчетом количества товаров для каждой. Может тормозить при большом количестве товаров.
// $query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position, COUNT(p.id) as products_count
// FROM __categories c LEFT JOIN __products_categories pc ON pc.category_id=c.id LEFT JOIN __products p ON p.id=pc.product_id AND p.visible GROUP BY c.id ORDER BY c.parent_id, c.position");
$this->db->query($query);
$categories = $this->db->results();
$finish = false;
// Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть
while(!empty($categories) && !$finish)
{
$flag = false;
// Проходим все выбранные категории
foreach($categories as $k=>$category)
{
$category->__css_class = $category->visible == 1 ? 'a-visible' : 'a-invisible';
if(isset($pointers[$category->parent_id]))
{
// В дерево категорий (через указатель) добавляем текущую категорию
$pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category;
// Путь к текущей категории
$curr = $pointers[$category->id];
$pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr));
// Убираем использованную категорию из массива категорий
unset($categories[$k]);
$flag = true;
}
}
if(!$flag) $finish = true;
}
// Для каждой категории id всех ее деток узнаем
$ids = array_reverse(array_keys($pointers));
foreach($ids as $id)
{
if($id>0)
{
$pointers[$id]->children[] = $id;
if(isset($pointers[$pointers[$id]->parent_id]->children))
$pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children);
else
$pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children;
// Добавляем количество товаров к родительской категории, если текущая видима
// if(isset($pointers[$pointers[$id]->parent_id]) && $pointers[$id]->visible)
// $pointers[$pointers[$id]->parent_id]->products_count += $pointers[$id]->products_count;
}
}
unset($pointers[0]);
unset($ids);
$this->categories_tree = $tree->subcategories;
$this->all_categories = $pointers;
}
}

149
api/Comments.php Normal file
View File

@@ -0,0 +1,149 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Comments extends Simpla
{
// Возвращает комментарий по id
public function get_comment($id)
{
$query = $this->db->placehold("SELECT c.id, c.object_id, c.name, c.ip, c.type, c.text, c.date, c.approved FROM __comments c WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
return $this->db->result();
else
return false;
}
// Возвращает комментарии, удовлетворяющие фильтру
public function get_comments($filter = array())
{
// По умолчанию
$limit = 0;
$page = 1;
$object_id_filter = '';
$type_filter = '';
$keyword_filter = '';
$approved_filter = '';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(isset($filter['ip']))
$ip = $this->db->placehold("OR c.ip=?", $filter['ip']);
if(isset($filter['approved']))
$approved_filter = $this->db->placehold("AND (c.approved=? $ip)", intval($filter['approved']));
if($limit)
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
else
$sql_limit = '';
if(!empty($filter['object_id']))
$object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']);
if(!empty($filter['type']))
$type_filter = $this->db->placehold('AND c.type=?', $filter['type']);
if(!empty($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR c.text LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" ');
}
$sort='DESC';
$query = $this->db->placehold("SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.text, c.approved
FROM __comments c WHERE 1 $object_id_filter $type_filter $keyword_filter $approved_filter ORDER BY id $sort $sql_limit");
$this->db->query($query);
return $this->db->results();
}
// Количество комментариев, удовлетворяющих фильтру
public function count_comments($filter = array())
{
$object_id_filter = '';
$type_filter = '';
$approved_filter = '';
$keyword_filter = '';
if(!empty($filter['object_id']))
$object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']);
if(!empty($filter['type']))
$type_filter = $this->db->placehold('AND c.type=?', $filter['type']);
if(isset($filter['approved']))
$approved_filter = $this->db->placehold('AND c.approved=?', intval($filter['approved']));
if(!empty($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR c.text LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" ');
}
$query = $this->db->placehold("SELECT count(distinct c.id) as count
FROM __comments c WHERE 1 $object_id_filter $type_filter $keyword_filter $approved_filter", $this->settings->date_format);
$this->db->query($query);
return $this->db->result('count');
}
// Добавление комментария
public function add_comment($comment)
{
$query = $this->db->placehold('INSERT INTO __comments
SET ?%,
date = NOW()',
$comment);
if(!$this->db->query($query))
return false;
$id = $this->db->insert_id();
return $id;
}
// Изменение комментария
public function update_comment($id, $comment)
{
$date_query = '';
if(isset($comment->date))
{
$date = $comment->date;
unset($comment->date);
$date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format);
}
$query = $this->db->placehold("UPDATE __comments SET ?% $date_query WHERE id in(?@) LIMIT 1", $comment, (array)$id);
$this->db->query($query);
return $id;
}
// Удаление комментария
public function delete_comment($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __comments WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
}
}
}

109
api/Config.php Normal file
View File

@@ -0,0 +1,109 @@
<?php
/**
* Класс-обертка для конфигурационного файла с настройками магазина
* В отличие от класса Settings, Config оперирует низкоуровневыми настройками, например найстройками базы данных.
*
*
* @copyright 2013 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Config
{
public $version = '2.2.4';
// Файл для хранения настроек
public $config_file = 'config/config.php';
private $vars = array();
// В конструкторе записываем настройки файла в переменные этого класса
// для удобного доступа к ним. Например: $simpla->config->db_user
public function __construct()
{
// Читаем настройки из дефолтного файла
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/' . $this->config_file);
// Записываем настройку как переменную класса
foreach($ini as $var=>$value)
$this->vars[$var] = $value;
// Вычисляем DOCUMENT_ROOT вручную, так как иногда в нем находится что-то левое
$localpath=getenv("SCRIPT_NAME");
$absolutepath=getenv("SCRIPT_FILENAME");
$_SERVER['DOCUMENT_ROOT']=substr($absolutepath,0,strpos($absolutepath,$localpath));
// Адрес сайта - тоже одна из настроек, но вычисляем его автоматически, а не берем из файла
$script_dir1 = realpath(dirname(dirname(__FILE__)));
$script_dir2 = realpath($_SERVER['DOCUMENT_ROOT']);
$subdir = trim(substr($script_dir1, strlen($script_dir2)), "/\\");
// Протокол
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'? 'https' : 'http';
if($_SERVER["SERVER_PORT"] == 443)
$protocol = 'https';
$this->vars['protocol'] = $protocol;
$this->vars['root_url'] = $protocol.'://'.rtrim($_SERVER['HTTP_HOST']);
if(!empty($subdir))
$this->vars['root_url'] .= '/'.$subdir;
// Подпапка в которую установлена симпла относительно корня веб-сервера
$this->vars['subfolder'] = $subdir.'/';
// Определяем корневую директорию сайта
$this->vars['root_dir'] = dirname(dirname(__FILE__)).'/';
// Максимальный размер загружаемых файлов
$max_upload = (int)(ini_get('upload_max_filesize'));
$max_post = (int)(ini_get('post_max_size'));
$memory_limit = (int)(ini_get('memory_limit'));
$this->vars['max_upload_filesize'] = min($max_upload, $max_post, $memory_limit)*1024*1024;
// Соль (разная для каждой копии сайта, изменяющаяся при изменении config-файла)
$s = stat($_SERVER['DOCUMENT_ROOT'] . '/' . $this->config_file);
$this->vars['salt'] = md5(md5_file($_SERVER['DOCUMENT_ROOT'] . '/' . $this->config_file).$s['dev'].$s['ino'].$s['uid'].$s['mtime']);
//echo '<!--'; var_dump($this->vars); echo '-->';
}
// Магическим методов возвращаем нужную переменную
public function __get($name)
{
if(isset($this->vars[$name]))
return $this->vars[$name];
else
return null;
}
// Магическим методов задаём нужную переменную
public function __set($name, $value)
{
# Запишем конфиги
if(isset($this->vars[$name]))
{
$conf = file_get_contents($this->config_file);
$conf = preg_replace("/".$name."\s*=.*\n/i", $name.' = '.$value."\r\n", $conf);
$cf = fopen($this->config_file, 'w');
fwrite($cf, $conf);
fclose($cf);
$this->vars[$name] = $value;
}
}
public function token($text)
{
return md5($text.$this->salt);
}
public function check_token($text, $token)
{
if(!empty($token) && $token === $this->token($text))
return true;
return false;
}
}

171
api/Coupons.php Normal file
View File

@@ -0,0 +1,171 @@
<?php
/**
* Simpla CMS
*
* @copyright 2012 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Coupons extends Simpla
{
/*
*
* Функция возвращает купон по его id или url
* (в зависимости от типа аргумента, int - id, string - code)
* @param $id id или code купона
*
*/
public function get_coupon($id)
{
if(gettype($id) == 'string')
$where = $this->db->placehold('WHERE c.code=? ', $id);
else
$where = $this->db->placehold('WHERE c.id=? ', $id);
$query = $this->db->placehold("SELECT c.id, c.code, c.value, c.type, c.expire, min_order_price, c.single, c.usages,
((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single)) AS valid
FROM __coupons c $where LIMIT 1");
if($this->db->query($query))
return $this->db->result();
else
return false;
}
/*
*
* Функция возвращает массив купонов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_coupons($filter = array())
{
// По умолчанию
$limit = 1000;
$page = 1;
$coupon_id_filter = '';
$valid_filter = '';
$keyword_filter = '';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(!empty($filter['id']))
$coupon_id_filter = $this->db->placehold('AND c.id in(?@)', (array)$filter['id']);
if(isset($filter['valid']))
if($filter['valid'])
$valid_filter = $this->db->placehold('AND ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))');
else
$valid_filter = $this->db->placehold('AND NOT ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))');
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
$query = $this->db->placehold("SELECT c.id, c.code, c.value, c.type, c.expire, min_order_price, c.single, c.usages,
((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single)) AS valid
FROM __coupons c WHERE 1 $coupon_id_filter $valid_filter $keyword_filter
ORDER BY valid DESC, id DESC $sql_limit",
$this->settings->date_format);
$this->db->query($query);
return $this->db->results();
}
/*
*
* Функция вычисляет количество постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function count_coupons($filter = array())
{
$coupon_id_filter = '';
$valid_filter = '';
if(!empty($filter['id']))
$coupon_id_filter = $this->db->placehold('AND c.id in(?@)', (array)$filter['id']);
if(isset($filter['valid']))
$valid_filter = $this->db->placehold('AND ((DATE(NOW()) <= DATE(c.expire) OR c.expire IS NULL) AND (c.usages=0 OR NOT c.single))');
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$query = "SELECT COUNT(distinct c.id) as count
FROM __coupons c WHERE 1 $coupon_id_filter $valid_filter";
if($this->db->query($query))
return $this->db->result('count');
else
return false;
}
/*
*
* Создание купона
* @param $coupon
*
*/
public function add_coupon($coupon)
{
if(empty($coupon->single))
$coupon->single = 0;
$query = $this->db->placehold("INSERT INTO __coupons SET ?% $date_query", $coupon);
if(!$this->db->query($query))
return false;
else
return $this->db->insert_id();
}
/*
*
* Обновить купон(ы)
* @param $id, $coupon
*
*/
public function update_coupon($id, $coupon)
{
$query = $this->db->placehold("UPDATE __coupons SET ?% WHERE id in(?@) LIMIT ?", $coupon, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
/*
*
* Удалить купон
* @param $id
*
*/
public function delete_coupon($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __coupons WHERE id=? LIMIT 1", intval($id));
return $this->db->query($query);
}
}
}

526
api/Database.php Normal file
View File

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

89
api/Delivery.php Normal file
View File

@@ -0,0 +1,89 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Delivery extends Simpla
{
public function get_delivery($id)
{
$query = $this->db->placehold("SELECT id, name, description, free_from, price, enabled, position, separate_payment, ems FROM __delivery WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
return $this->db->result();
}
public function get_deliveries($filter = array())
{
// По умолчанию
$enabled_filter = '';
if(!empty($filter['enabled']))
$enabled_filter = $this->db->placehold('AND enabled=?', intval($filter['enabled']));
$query = "SELECT id, name, description, free_from, price, enabled, position, separate_payment, ems
FROM __delivery WHERE 1 $enabled_filter ORDER BY position";
$this->db->query($query);
return $this->db->results();
}
public function update_delivery($id, $delivery)
{
$query = $this->db->placehold("UPDATE __delivery SET ?% WHERE id in(?@)", $delivery, (array)$id);
$this->db->query($query);
return $id;
}
public function add_delivery($delivery)
{
$query = $this->db->placehold('INSERT INTO __delivery
SET ?%',
$delivery);
if(!$this->db->query($query))
return false;
$id = $this->db->insert_id();
$this->db->query("UPDATE __delivery SET position=id WHERE id=?", intval($id));
return $id;
}
public function delete_delivery($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __delivery WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
}
}
public function get_delivery_payments($id)
{
$query = $this->db->placehold("SELECT payment_method_id FROM __delivery_payment WHERE delivery_id=?", intval($id));
$this->db->query($query);
return $this->db->results('payment_method_id');
}
public function update_delivery_payments($id, $payment_methods_ids)
{
$query = $this->db->placehold("DELETE FROM __delivery_payment WHERE delivery_id=?", intval($id));
$this->db->query($query);
if(is_array($payment_methods_ids))
foreach($payment_methods_ids as $p_id)
$this->db->query("INSERT INTO __delivery_payment SET delivery_id=?, payment_method_id=?", $id, $p_id);
}
}

403
api/Design.php Normal file
View File

@@ -0,0 +1,403 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once $_SERVER['DOCUMENT_ROOT'] . '/lib/Img.php';
require_once('Simpla.php');
require_once('Smarty/libs/Smarty.class.php');
class Design extends Simpla
{
public $smarty;
public function __construct()
{
parent::__construct();
//error_reporting(E_ALL | E_STRICT);
// Создаем и настраиваем Смарти
$this->smarty = new Smarty();
$this->smarty->compile_check = $this->config->smarty_compile_check;
$this->smarty->caching = $this->config->smarty_caching;
$this->smarty->cache_lifetime = $this->config->smarty_cache_lifetime;
$this->smarty->debugging = $this->config->smarty_debugging;
$this->smarty->error_reporting = E_ALL & ~E_NOTICE;
// Берем тему из настроек
$theme = $this->settings->theme;
$this->smarty->compile_dir = $this->config->root_dir.'/compiled/'.$theme;
$this->smarty->template_dir = $this->config->root_dir.'/design/'.$theme.'/html';
// Создаем папку для скомпилированных шаблонов текущей темы
if(!is_dir($this->smarty->compile_dir))
mkdir($this->smarty->compile_dir, 0777);
$this->smarty->cache_dir = 'cache';
$this->smarty->registerPlugin('modifier', 'resizeImg', array($this, 'resize_modifier_img'));
$this->smarty->registerPlugin('modifier', 'resizeProduct', array($this, 'resize_modifier_product'));
$this->smarty->registerPlugin('modifier', 'resize_category', array($this, 'resize_modifier_cat_img'));
$this->smarty->registerPlugin('modifier', 'resizepost', array($this, 'resize_modifier_post'));
$this->smarty->registerPlugin('modifier', 'resizearticle', array($this, 'resize_modifier_article'));
$this->smarty->registerPlugin('modifier', 'resizepage', array($this, 'resize_modifier_page'));
$this->smarty->registerPlugin('modifier', 'resize', array($this, 'resize_modifier'));
$this->smarty->registerPlugin('modifier', 'token', array($this, 'token_modifier'));
$this->smarty->registerPlugin('modifier', 'plural', array($this, 'plural_modifier'));
$this->smarty->registerPlugin('function', 'url', array($this, 'url_modifier'));
$this->smarty->registerPlugin('function', 'pagurl', array($this, 'pagurl_modifier'));
$this->smarty->registerPlugin('modifier', 'first', array($this, 'first_modifier'));
$this->smarty->registerPlugin('modifier', 'cut', array($this, 'cut_modifier'));
$this->smarty->registerPlugin('modifier', 'date', array($this, 'date_modifier'));
$this->smarty->registerPlugin('modifier', 'time', array($this, 'time_modifier'));
$this->smarty->registerPlugin('modifier', 'gallery', array($this, 'pageGallery'));
}
public function resize_modifier_img($filename, $width=0, $height=0, $crop = false, $watermark=false){
$params = array(
'width' => $width,
'height' => $height,
'crop' => $crop,
'watermark' => $watermark
);
$filename = str_replace('%2F', '/', $filename);
return Img::get($filename, $params);
}
public function resize_modifier_cat_img($filename, $width=0, $height=0, $crop = false, $watermark=false){
$params = array(
'width' => $width,
'height' => $height,
'crop' => $crop,
'watermark' => $watermark
);
$filename = 'files/categories/' . str_replace('%2F', '/', $filename);
return Img::get($filename, $params);
}
public function resize_modifier_product($filename, $width=0, $height=0, $crop = false, $watermark=false){
$params = array(
'width' => $width,
'height' => $height,
'crop' => $crop,
'watermark' => $watermark
);
$filename = 'files/originals/' . str_replace('%2F', '/', $filename);
return Img::get($filename, $params);
}
function pageGallery($id){
return $id;
}
public function assign($var, $value)
{
return $this->smarty->assign($var, $value);
}
public function fetch($template)
{
// Передаем в дизайн то, что может понадобиться в нем
$this->design->assign('config', $this->config);
$this->design->assign('settings', $this->settings);
require_once($_SERVER['DOCUMENT_ROOT'] . '/mobiledetect/Mobile_Detect.php');
$detect = new Mobile_Detect;
$this->smarty->assign('detect', $detect);
//echo $this->design->smarty->getTemplateVars('service_menu');
// echo '<!--99999'; print_r( $smarty->getTemplateVars() ); echo '--->';
return $this->smarty->fetch($template);
}
public function set_templates_dir($dir)
{
$this->smarty->template_dir = $dir;
}
public function set_compiled_dir($dir)
{
$this->smarty->compile_dir = $dir;
}
public function get_var($name)
{
return $this->smarty->getTemplateVars($name);
}
private function is_mobile_browser()
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$http_accept = isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:'';
if(eregi('iPad', $user_agent))
return false;
if(stristr($user_agent, 'windows') && !stristr($user_agent, 'windows ce'))
return false;
if(eregi('windows ce|iemobile|mobile|symbian|mini|wap|pda|psp|up.browser|up.link|mmp|midp|phone|pocket', $user_agent))
return true;
if(stristr($http_accept, 'text/vnd.wap.wml') || stristr($http_accept, 'application/vnd.wap.xhtml+xml'))
return true;
if(!empty($_SERVER['HTTP_X_WAP_PROFILE']) || !empty($_SERVER['HTTP_PROFILE']) || !empty($_SERVER['X-OperaMini-Features']) || !empty($_SERVER['UA-pixels']))
return true;
$agents = array(
'acs-'=>'acs-',
'alav'=>'alav',
'alca'=>'alca',
'amoi'=>'amoi',
'audi'=>'audi',
'aste'=>'aste',
'avan'=>'avan',
'benq'=>'benq',
'bird'=>'bird',
'blac'=>'blac',
'blaz'=>'blaz',
'brew'=>'brew',
'cell'=>'cell',
'cldc'=>'cldc',
'cmd-'=>'cmd-',
'dang'=>'dang',
'doco'=>'doco',
'eric'=>'eric',
'hipt'=>'hipt',
'inno'=>'inno',
'ipaq'=>'ipaq',
'java'=>'java',
'jigs'=>'jigs',
'kddi'=>'kddi',
'keji'=>'keji',
'leno'=>'leno',
'lg-c'=>'lg-c',
'lg-d'=>'lg-d',
'lg-g'=>'lg-g',
'lge-'=>'lge-',
'maui'=>'maui',
'maxo'=>'maxo',
'midp'=>'midp',
'mits'=>'mits',
'mmef'=>'mmef',
'mobi'=>'mobi',
'mot-'=>'mot-',
'moto'=>'moto',
'mwbp'=>'mwbp',
'nec-'=>'nec-',
'newt'=>'newt',
'noki'=>'noki',
'opwv'=>'opwv',
'palm'=>'palm',
'pana'=>'pana',
'pant'=>'pant',
'pdxg'=>'pdxg',
'phil'=>'phil',
'play'=>'play',
'pluc'=>'pluc',
'port'=>'port',
'prox'=>'prox',
'qtek'=>'qtek',
'qwap'=>'qwap',
'sage'=>'sage',
'sams'=>'sams',
'sany'=>'sany',
'sch-'=>'sch-',
'sec-'=>'sec-',
'send'=>'send',
'seri'=>'seri',
'sgh-'=>'sgh-',
'shar'=>'shar',
'sie-'=>'sie-',
'siem'=>'siem',
'smal'=>'smal',
'smar'=>'smar',
'sony'=>'sony',
'sph-'=>'sph-',
'symb'=>'symb',
't-mo'=>'t-mo',
'teli'=>'teli',
'tim-'=>'tim-',
'tosh'=>'tosh',
'treo'=>'treo',
'tsm-'=>'tsm-',
'upg1'=>'upg1',
'upsi'=>'upsi',
'vk-v'=>'vk-v',
'voda'=>'voda',
'wap-'=>'wap-',
'wapa'=>'wapa',
'wapi'=>'wapi',
'wapp'=>'wapp',
'wapr'=>'wapr',
'webc'=>'webc',
'winw'=>'winw',
'winw'=>'winw',
'xda-'=>'xda-'
);
if(!empty($agents[substr($_SERVER['HTTP_USER_AGENT'], 0, 4)]))
return true;
}
public function resize_modifier_post($filename, $width=0, $height=0, $set_watermark=false,$crop = false)
{
$resized_filename = $this->image->add_resize_params($filename, $width, $height, $set_watermark, $crop);
$resized_filename_encoded = $resized_filename;
if(substr($resized_filename_encoded, 0, 7) == 'http://')
$resized_filename_encoded = rawurlencode($resized_filename_encoded);
$resized_filename_encoded = rawurlencode($resized_filename_encoded);
return $this->config->root_url.'/'.$this->config->post_images_dir.$resized_filename_encoded.'?'.$this->config->token($resized_filename);
}
public function resize_modifier_article($filename, $width=0, $height=0, $set_watermark=false,$crop = false)
{
return $this->image->resizeArticle($filename, $width, $height);
}
public function resize_modifier_page($filename, $width=0, $height=0, $watermark=false, $crop = false)
{
$params = array(
'width' => $width,
'height' => $height,
'crop' => $crop,
'watermark' => $watermark
);
$filename = 'files/originals/' . str_replace('%2F', '/', $filename);
return Img::get($filename, $params);
$resized_filename = $this->image->add_resize_params($filename, $width, $height, $set_watermark, $crop);
$resized_filename_encoded = $resized_filename;
if(substr($resized_filename_encoded, 0, 7) == 'http://')
$resized_filename_encoded = rawurlencode($resized_filename_encoded);
$resized_filename_encoded = rawurlencode($resized_filename_encoded);
return $this->config->root_url.'/'.$this->config->page_images_dir.$resized_filename_encoded.'?'.$this->config->token($resized_filename);
}
public function resize_modifier($filename, $width=0, $height=0, $set_watermark=false, $crop = false)
{
$resized_filename = $this->image->add_resize_params($filename, $width, $height, $set_watermark, $crop);
$resized_filename_encoded = $resized_filename;
if(substr($resized_filename_encoded, 0, 7) == 'http://')
$resized_filename_encoded = rawurlencode($resized_filename_encoded);
$resized_filename_encoded = rawurlencode($resized_filename_encoded);
if($width == 50 && $height == 50) return $this->config->root_url.'/'.$this->config->resized_images_dir.$resized_filename_encoded;
return $this->config->root_url.'/'.$this->config->resized_images_dir.$resized_filename_encoded.'?'.$this->config->token($resized_filename);
}
public function token_modifier($text)
{
return $this->config->token($text);
}
public function url_modifier($params)
{
if(is_array(reset($params)))
$url = $this->request->url(reset($params));
else
$url = $this->request->url($params);
return $url;
}
public function pagurl_modifier($params = null)
{
$u = explode('?', $_SERVER['REQUEST_URI']);
$url = $x = trim($u[0], '/');
$url = explode('/', $url);
if(strpos($x, '/page-') !== false) array_pop($url);
$uri = $params ? '/' . implode('/', $url) . '/page-' . $params['page'] . '/' : '/' . implode('/', $url) . '/';
return empty($u[1]) ? $uri : $uri . '?' . $u[1];
}
public function plural_modifier($number, $singular, $plural1, $plural2=null)
{
$number = abs($number);
if(!empty($plural2))
{
$p1 = $number%10;
$p2 = $number%100;
if($number == 0)
return $plural1;
if($p1==1 && !($p2>=11 && $p2<=19))
return $singular;
elseif($p1>=2 && $p1<=4 && !($p2>=11 && $p2<=19))
return $plural2;
else
return $plural1;
}else
{
if($number == 1)
return $singular;
else
return $plural1;
}
}
public function first_modifier($params = array())
{
if(!is_array($params))
return false;
return reset($params);
}
public function cut_modifier($array, $num=1)
{
if($num>=0)
return array_slice($array, $num, count($array)-$num, true);
else
return array_slice($array, 0, count($array)+$num, true);
}
public function date_modifier($date, $format = null)
{
if(empty($date))
$date = date("Y-m-d");
return date(empty($format)?$this->settings->date_format:$format, strtotime($date));
}
public function time_modifier($date, $format = null)
{
return date(empty($format)?'H:i':$format, strtotime($date));
}
}

205
api/Features.old Normal file
View File

@@ -0,0 +1,205 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Features extends Simpla
{
function get_features($filter = array())
{
$category_id_filter = '';
if(isset($filter['category_id']))
$category_id_filter = $this->db->placehold('AND id in(SELECT feature_id FROM __categories_features AS cf WHERE cf.category_id in(?@))', (array)$filter['category_id']);
$in_filter_filter = '';
if(isset($filter['in_filter']))
$in_filter_filter = $this->db->placehold('AND f.in_filter=?', intval($filter['in_filter']));
$id_filter = '';
if(!empty($filter['id']))
$id_filter = $this->db->placehold('AND f.id in(?@)', (array)$filter['id']);
// Выбираем свойства
$query = $this->db->placehold("SELECT id, name, position, in_filter FROM __features AS f
WHERE 1
$category_id_filter $in_filter_filter $id_filter ORDER BY f.position");
$this->db->query($query);
return $this->db->results();
}
function get_feature($id)
{
// Выбираем свойство
$query = $this->db->placehold("SELECT id, name, position, in_filter FROM __features WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$feature = $this->db->result();
return $feature;
}
function get_feature_categories($id)
{
$query = $this->db->placehold("SELECT cf.category_id as category_id FROM __categories_features cf
WHERE cf.feature_id = ?", $id);
$this->db->query($query);
return $this->db->results('category_id');
}
public function add_feature($feature)
{
$query = $this->db->placehold("INSERT INTO __features SET ?%", $feature);
$this->db->query($query);
$id = $this->db->insert_id();
$query = $this->db->placehold("UPDATE __features SET position=id WHERE id=? LIMIT 1", $id);
$this->db->query($query);
return $id;
}
public function update_feature($id, $feature)
{
$query = $this->db->placehold("UPDATE __features SET ?% WHERE id in(?@) LIMIT ?", (array)$feature, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
public function delete_feature($id = array())
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __features WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __options WHERE feature_id=?", intval($id));
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", intval($id));
$this->db->query($query);
}
}
public function delete_option($product_id, $feature_id)
{
$query = $this->db->placehold("DELETE FROM __options WHERE product_id=? AND feature_id=? LIMIT 1", intval($product_id), intval($feature_id));
$this->db->query($query);
}
public function update_option($product_id, $feature_id, $value)
{
if($value != '')
$query = $this->db->placehold("REPLACE INTO __options SET value=?, product_id=?, feature_id=?", $value, intval($product_id), intval($feature_id));
else
$query = $this->db->placehold("DELETE FROM __options WHERE feature_id=? AND product_id=?", intval($feature_id), intval($product_id));
return $this->db->query($query);
}
public function add_feature_category($id, $category_id)
{
$query = $this->db->placehold("INSERT IGNORE INTO __categories_features SET feature_id=?, category_id=?", $id, $category_id);
$this->db->query($query);
}
public function update_feature_categories($id, $categories)
{
$id = intval($id);
$query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", $id);
$this->db->query($query);
if(is_array($categories))
{
$values = array();
foreach($categories as $category)
$values[] = "($id , ".intval($category).")";
$query = $this->db->placehold("INSERT INTO __categories_features (feature_id, category_id) VALUES ".implode(', ', $values));
$this->db->query($query);
// Удалим значения из options
$query = $this->db->placehold("DELETE o FROM __options o
LEFT JOIN __products_categories pc ON pc.product_id=o.product_id
WHERE o.feature_id=? AND pc.category_id not in(?@)", $id, $categories);
$this->db->query($query);
}
else
{
// Удалим значения из options
$query = $this->db->placehold("DELETE o FROM __options o WHERE o.feature_id=?", $id);
$this->db->query($query);
}
}
public function get_options($filter = array())
{
$feature_id_filter = '';
$product_id_filter = '';
$category_id_filter = '';
$visible_filter = '';
$brand_id_filter = '';
$features_filter = '';
if(empty($filter['feature_id']) && empty($filter['product_id']))
return array();
$group_by = '';
if(isset($filter['feature_id']))
$group_by = 'GROUP BY feature_id, value';
if(isset($filter['feature_id']))
$feature_id_filter = $this->db->placehold('AND po.feature_id in(?@)', (array)$filter['feature_id']);
if(isset($filter['product_id']))
$product_id_filter = $this->db->placehold('AND po.product_id in(?@)', (array)$filter['product_id']);
if(isset($filter['category_id']))
$category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id=po.product_id AND pc.category_id in(?@)', (array)$filter['category_id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('INNER JOIN __products p ON p.id=po.product_id AND visible=?', intval($filter['visible']));
if(isset($filter['brand_id']))
$brand_id_filter = $this->db->placehold('AND po.product_id in(SELECT id FROM __products WHERE brand_id in(?@))', (array)$filter['brand_id']);
if(isset($filter['features']))
foreach($filter['features'] as $feature=>$value)
{
$features_filter .= $this->db->placehold('AND (po.feature_id=? OR po.product_id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? )) ', $feature, $feature, $value);
}
$query = $this->db->placehold("SELECT po.product_id, po.feature_id, po.value, count(po.product_id) as count
FROM __options po
$visible_filter
$category_id_filter
WHERE 1 $feature_id_filter $product_id_filter $brand_id_filter $features_filter GROUP BY po.feature_id, po.value ORDER BY value=0, -value DESC, value");
$this->db->query($query);
$res = $this->db->results();
return $res;
}
public function get_product_options($product_id)
{
$query = $this->db->placehold("SELECT f.id as feature_id, f.name, po.value, po.product_id FROM __options po LEFT JOIN __features f ON f.id=po.feature_id
WHERE po.product_id in(?@) ORDER BY f.position", (array)$product_id);
$this->db->query($query);
$res = $this->db->results();
return $res;
}
}

304
api/Features.php Normal file
View File

@@ -0,0 +1,304 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Features extends Simpla
{
function get_features($filter = array())
{
$category_id_filter = '';
if(isset($filter['category_id']))
$category_id_filter = $this->db->placehold('AND id in(SELECT feature_id FROM __categories_features AS cf WHERE cf.category_id in(?@))', (array)$filter['category_id']);
$in_filter_filter = '';
if(isset($filter['in_filter']))
$in_filter_filter = $this->db->placehold(' AND f.in_filter=?', intval($filter['in_filter']));
if(isset($filter['on_main']))
$in_filter_filter.= $this->db->placehold(' AND f.on_main=?', intval($filter['on_main']));
if(isset($filter['on_prod']))
$in_filter_filter.= $this->db->placehold(' AND f.on_prod=?', intval($filter['on_prod']));
$id_filter = '';
if(!empty($filter['id']))
$id_filter = $this->db->placehold('AND f.id in(?@)', (array)$filter['id']);
// Выбираем свойства
$query = $this->db->placehold("SELECT id, name, position, in_filter
, on_prod, on_main, multiselect, in_variant, in_compare, isrange, slider, unit, istext, image, nameselect
FROM __features AS f
WHERE 1
$category_id_filter $in_filter_filter $id_filter ORDER BY f.position");
$this->db->query($query);
return $this->db->results();
}
function get_feature($id)
{
// Выбираем свойство
$query = $this->db->placehold("SELECT id, name, position, in_filter
, on_prod, on_main, multiselect, in_variant, in_compare, isrange, slider, unit, istext, image, nameselect
FROM __features WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$feature = $this->db->result();
return $feature;
}
function get_feature_categories($id)
{
$query = $this->db->placehold("SELECT cf.category_id as category_id FROM __categories_features cf
WHERE cf.feature_id = ?", $id);
$this->db->query($query);
return $this->db->results('category_id');
}
public function add_feature($feature)
{
$query = $this->db->placehold("INSERT INTO __features SET ?%", $feature);
$this->db->query($query);
$id = $this->db->insert_id();
$query = $this->db->placehold("UPDATE __features SET position=id WHERE id=? LIMIT 1", $id);
$this->db->query($query);
return $id;
}
public function update_feature($id, $feature)
{
$query = $this->db->placehold("UPDATE __features SET ?% WHERE id in(?@) LIMIT ?", (array)$feature, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
public function delete_feature($id = array())
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __features WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __options WHERE feature_id=?", intval($id));
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", intval($id));
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __variants_options WHERE id_feature=?", intval($id));
$this->db->query($query);
}
}
public function delete_option($product_id, $feature_id)
{
$query = $this->db->placehold("DELETE FROM __options WHERE product_id=? AND feature_id=? LIMIT 1", intval($product_id), intval($feature_id));
$this->db->query($query);
}
public function update_option($product_id, $feature_id, $value)
{
if($value != '')
$query = $this->db->placehold("REPLACE INTO __options SET value=?, product_id=?, feature_id=?", $value, intval($product_id), intval($feature_id));
else
$query = $this->db->placehold("DELETE FROM __options WHERE feature_id=? AND product_id=?", intval($feature_id), intval($product_id));
return $this->db->query($query);
}
public function add_feature_category($id, $category_id)
{
$query = $this->db->placehold("INSERT IGNORE INTO __categories_features SET feature_id=?, category_id=?", $id, $category_id);
$this->db->query($query);
}
public function update_feature_categories($id, $categories)
{
$id = intval($id);
$query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", $id);
$this->db->query($query);
if(is_array($categories))
{
$values = array();
foreach($categories as $category)
$values[] = "($id , ".intval($category).")";
$query = $this->db->placehold("INSERT INTO __categories_features (feature_id, category_id) VALUES ".implode(', ', $values));
$this->db->query($query);
// Удалим значения из options
$query = $this->db->placehold("DELETE o FROM __options o
LEFT JOIN __products_categories pc ON pc.product_id=o.product_id
WHERE o.feature_id=? AND pc.category_id not in(?@)", $id, $categories);
$this->db->query($query);
}
else
{
// Удалим значения из options
$query = $this->db->placehold("DELETE o FROM __options o WHERE o.feature_id=?", $id);
$this->db->query($query);
}
}
public function get_options($filter = array())
{
$feature_id_filter = '';
$product_id_filter = '';
$category_id_filter = '';
$visible_filter = '';
$brand_id_filter = '';
$features_filter = '';
$in_filter_filter = '';
if(empty($filter['feature_id']) && empty($filter['product_id']))
return array();
$group_by = '';
if(isset($filter['feature_id']))
$group_by = 'GROUP BY feature_id, value';
if(isset($filter['feature_id']))
$feature_id_filter = $this->db->placehold('AND po.feature_id in(?@)', (array)$filter['feature_id']);
if(isset($filter['product_id']))
$product_id_filter = $this->db->placehold('AND po.product_id in(?@)', (array)$filter['product_id']);
if(isset($filter['category_id']))
$category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id=po.product_id AND pc.category_id in(?@)', (array)$filter['category_id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('INNER JOIN __products p ON p.id=po.product_id AND visible=?', intval($filter['visible']));
if(isset($filter['brand_id']))
$brand_id_filter = $this->db->placehold('AND po.product_id in(SELECT id FROM __products WHERE brand_id in(?@))', (array)$filter['brand_id']);
if(isset($filter['on_main']))
$in_filter_filter.= $this->db->placehold(' AND f.on_main=?', intval($filter['on_main']));
if(isset($filter['on_prod']))
$in_filter_filter.= $this->db->placehold(' AND f.on_prod=?', intval($filter['on_prod']));
if(isset($filter['features']))
foreach($filter['features'] as $feature=>$value)
{
$features_filter .= $this->db->placehold('AND (po.feature_id=? OR po.product_id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? )) ', $feature, $feature, $value);
}
$query = $this->db->placehold("SELECT po.product_id, po.feature_id, po.value, count(po.product_id) as count
, f.on_prod, f.on_main, f.multiselect, f.in_variant, f.in_compare, f.isrange, f.slider, f.unit, f.istext, f.image
FROM __options po LEFT JOIN __features f ON f.id=po.feature_id
$visible_filter
$category_id_filter
WHERE 1 $feature_id_filter $product_id_filter $brand_id_filter $features_filter $in_filter_filter GROUP BY po.feature_id, po.value ORDER BY value=0, -value DESC, value");
$this->db->query($query);
$res = $this->db->results();
$all = array();
foreach($res AS $k=>$re){
if($re->isrange==1){
$v = floatval(ereg_replace("[^-0-9\.]","",$re->value));
$all[$re->feature_id][] = $v;
$res[$k]->value = $v;
}
}
foreach($res AS $k=>$re){
if($re->isrange==1)
if(sizeof($all[$re->feature_id]) > 0){
$res[$k]->min = min($all[$re->feature_id]);
$res[$k]->max = max($all[$re->feature_id]);
}else{
$res[$k]->min = 0;
$res[$k]->max = 0;
}
}
return $res;
}
public function get_product_options($product_id, $face = 0)
{
$and = '';
if($face){
$and =' AND f.on_prod = 1 ';
}
$query = $this->db->placehold("SELECT f.id as feature_id, f.name, po.value, po.product_id
, f.on_prod, f.on_main, f.multiselect, f.in_variant, f.in_compare, f.isrange, f.slider, f.unit, f.istext, f.image , f.nameselect
FROM __options po LEFT JOIN __features f ON f.id=po.feature_id ".$and."
WHERE po.product_id in(?@) ORDER BY f.position", (array)$product_id);
$this->db->query($query);
$res = $this->db->results();
foreach($res AS $k=>$re){
if($re->isrange==1){
$res[$k]->value = floatval(ereg_replace("[^-0-9\.]","",$re->value));
}
}
return $res;
}
public function delete_image($id)
{
$query = $this->db->placehold("SELECT image FROM __features WHERE id=?", intval($id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __features SET image=NULL WHERE id=?", $id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __features WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->features_images_dir.$filename);
}
}
}
public function delete_variant_options($product_id)
{
$query = $this->db->placehold("DELETE o FROM __variants_options o
LEFT JOIN __variants va ON va.id = o.id_veriant
WHERE va.product_id in(?@)", (array)$product_id);
$this->db->query($query);
}
public function update_variant_option($id_veriant, $feature_id, $value)
{
if($value != '')
$query = $this->db->placehold("REPLACE INTO __variants_options SET value=?, id_veriant=?, id_feature=?", $value, intval($id_veriant), intval($feature_id));
else
$query = $this->db->placehold("DELETE FROM __variants_options WHERE id_feature=? AND id_veriant=?", intval($feature_id), intval($id_veriant));
return $this->db->query($query);
}
public function get_product_variant_options($product_id)
{
$query = $this->db->placehold("SELECT f.id as feature_id, f.name, po.value, po.id_veriant, f.nameselect FROM __features f LEFT JOIN __variants_options po ON f.id=po.id_feature LEFT JOIN __variants va ON va.id = po.id_veriant
WHERE va.product_id in(?@) ORDER BY po.position, f.position ", (array)$product_id);
$this->db->query($query);
$res = $this->db->results();
return $res;
}
}

119
api/Feedbacks.php Normal file
View File

@@ -0,0 +1,119 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Feedbacks extends Simpla
{
public function get_feedback($id)
{
$query = $this->db->placehold("SELECT f.id, f.name, f.email, f.ip, f.message, f.date FROM __feedbacks f WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
return $this->db->result();
else
return false;
}
public function get_feedbacks($filter = array(), $new_on_top = false)
{
// По умолчанию
$limit = 0;
$page = 1;
$keyword_filter = '';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
if(!empty($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND f.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR f.message LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR f.email LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" ');
}
if($new_on_top)
$sort='DESC';
else
$sort='ASC';
$query = $this->db->placehold("SELECT f.id, f.name, f.email, f.ip, f.message, f.date
FROM __feedbacks f WHERE 1 $keyword_filter ORDER BY f.id $sort $sql_limit");
$this->db->query($query);
return $this->db->results();
}
public function count_feedbacks($filter = array())
{
$keyword_filter = '';
if(!empty($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND f.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR f.message LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR f.email LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" ');
}
$query = $this->db->placehold("SELECT count(distinct f.id) as count
FROM __feedbacks f WHERE 1 $keyword_filter");
$this->db->query($query);
return $this->db->result('count');
}
public function add_feedback($feedback)
{
$query = $this->db->placehold('INSERT INTO __feedbacks
SET ?%,
date = NOW()',
$feedback);
if(!$this->db->query($query))
return false;
$id = $this->db->insert_id();
return $id;
}
public function update_feedback($id, $feedback)
{
$date_query = '';
if(isset($fedback->date))
{
$date = $feedback->date;
unset($feedback->date);
$date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format);
}
$query = $this->db->placehold("UPDATE __feedbacks SET ?% $date_query WHERE id in(?@) LIMIT 1", $feedback, (array)$id);
$this->db->query($query);
return $id;
}
public function delete_feedback($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __feedbacks WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
}
}
}

567
api/Image.php Normal file
View File

@@ -0,0 +1,567 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once ('Simpla.php');
if(!class_exists('SimpleImage')) include $_SERVER['DOCUMENT_ROOT'].'/api/SimpleImage.php';
class Image extends Simpla
{
private $allowed_extentions = array(
'png',
'gif',
'jpg',
'jpeg',
'ico');
public function __construct()
{
parent::__construct();
}
/**
* Создание превью изображения
* @param $filename файл с изображением (без пути к файлу)
* @param max_w максимальная ширина
* @param max_h максимальная высота
* @return $string имя файла превью
*/
function resizepost($filename)
{
list($source_file, $width, $height, $set_watermark) = $this->get_resize_params($filename);
// Если вайл удаленный (http://), зальем его себе
if (substr($source_file, 0, 7) == 'http://')
{
// Имя оригинального файла
if (!$original_file = $this->download_image($source_file))
return false;
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
}
else
{
$original_file = $source_file;
}
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
// Пути к папкам с картинками
$originals_dir = $this->config->root_dir . $this->config->original_images_dir;
$preview_dir = $this->config->root_dir . $this->config->post_images_dir;
if (class_exists('Imagick') && $this->config->use_imagick)
$this->image_constrain_imagick($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height);
else
$this->image_constrain_gd($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height);
return $preview_dir . $resized_file;
}
function resizepage($filename)
{
list($source_file, $width, $height, $set_watermark) = $this->get_resize_params($filename);
// Если вайл удаленный (http://), зальем его себе
if (substr($source_file, 0, 7) == 'http://')
{
// Имя оригинального файла
if (!$original_file = $this->download_image($source_file))
return false;
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
}
else
{
$original_file = $source_file;
}
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
// Пути к папкам с картинками
$originals_dir = $this->config->root_dir . $this->config->original_images_dir;
$preview_dir = $this->config->root_dir . $this->config->page_images_dir;
if (class_exists('Imagick') && $this->config->use_imagick)
$this->image_constrain_imagick($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height);
else
$this->image_constrain_gd($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height);
return $preview_dir . $resized_file;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function resizecat($filename)
{
//list($source_file, $width , $height, $set_watermark) = $this->get_resize_params($filename); //echo $source_file;exit;
// Если вайл удаленный (http://), зальем его себе
/*
if(substr($source_file, 0, 7) == 'http://')
{
// Имя оригинального файла
if(!$original_file = $this->download_image($source_file))
return false;
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
}
else
{
$original_file = $source_file;
}
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
*/
$width = 252;
$height = 252;
$original_file = $filename;
$resized_file = $this->add_resize_params($filename, $width, $height, $set_watermark);
// Пути к папкам с картинками
$originals_dir = $this->config->root_dir . $this->config->categories_images_dir;
$preview_dir = $this->config->root_dir . $this->config->categories_images_dir;
if (class_exists('Imagick') && $this->config->use_imagick)
$this->image_constrain_imagick($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height);
else
$this->image_constrain_gd($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height);
return $preview_dir . $resized_file;
//echo $preview_dir .'999'. $resized_file;
}
function resizeArticle($filename, $width, $height)
{
$original_file = $filename;
$resized_file = $this->add_resize_params($filename, $width, $height, $set_watermark);
// Пути к папкам с картинками
$originals_dir = $this->config->root_dir . 'files/article_photo/';
$preview_dir = $this->config->root_dir . 'files/article_photo/';
if(is_file($preview_dir . $resized_file)) return '/files/article_photo/' . $resized_file;
$img = new SimpleImage($originals_dir . $filename);
if($width == $height) $img->square_crop($width)->save($preview_dir . $resized_file);
else $img->best_fit($width, $height)->save($preview_dir . $resized_file);
return '/files/article_photo/' . $resized_file;
//echo $preview_dir .'999'. $resized_file;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function resize($filename, $imgs_dir = '')
{
$imgs_dir = $imgs_dir ? $imgs_dir : $this->config->resized_images_dir;
$orig_dir = $imgs_dir ? $imgs_dir : $this->config->original_images_dir;
list($source_file, $width, $height, $set_watermark) = $this->get_resize_params($filename);
// Если вайл удаленный (http://), зальем его себе
if (substr($source_file, 0, 7) == 'http://')
{
// Имя оригинального файла
if (!$original_file = $this->download_image($source_file))
return false;
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
}
else
{
$original_file = $source_file;
} echo $original_file;
$resized_file = $this->add_resize_params($original_file, $width, $height, $set_watermark);
// Пути к папкам с картинками
$originals_dir = $this->config->root_dir . $this->config->original_images_dir;
$preview_dir = $this->config->root_dir . $this->config->resized_images_dir;
$watermark_offet_x = $this->settings->watermark_offset_x;
$watermark_offet_y = $this->settings->watermark_offset_y;
$sharpen = min(100, $this->settings->images_sharpen) / 100;
$watermark_transparency = 1 - min(100, $this->settings->watermark_transparency) / 100;
if ($set_watermark && is_file($this->config->watermark_file))
$watermark = $this->config->root_dir . $this->config->watermark_file;
else
$watermark = null;
if (class_exists('Imagick') && $this->config->use_imagick)
$this->image_constrain_imagick($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height, $watermark, $watermark_offet_x, $watermark_offet_y, $watermark_transparency, $sharpen);
else
$this->image_constrain_gd($originals_dir . $original_file, $preview_dir . $resized_file, $width, $height, $watermark, $watermark_offet_x, $watermark_offet_y, $watermark_transparency);
//echo $preview_dir . '1'. $resized_file;
return $preview_dir . $resized_file;
}
public function add_resize_params($filename, $width = 0, $height = 0, $set_watermark = false)
{
if ('.' != ($dirname = pathinfo($filename, PATHINFO_DIRNAME)))
$file = $dirname . '/' . pathinfo($filename, PATHINFO_FILENAME);
else
$file = pathinfo($filename, PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if ($width > 0 || $height > 0)
$resized_filename = $file . '.' . ($width > 0 ? $width : '') . 'x' . ($height > 0 ? $height : '') . ($set_watermark ? 'w' : '') . '.' . $ext;
else
$resized_filename = $file . '.' . ($set_watermark ? 'w.' : '') . $ext;
return $resized_filename;
}
public function get_resize_params($filename)
{
// Определаяем параметры ресайза
if (!preg_match('/(.+)\.([0-9]*)x([0-9]*)(w)?\.([^\.]+)$/', $filename, $matches))
return false;
$file = $matches[1]; // имя запрашиваемого файла
$width = $matches[2]; // ширина будущего изображения
$height = $matches[3]; // высота будущего изображения
$set_watermark = $matches[4] == 'w'; // ставить ли водяной знак
$ext = $matches[5]; // расширение файла
return array(
$file . '.' . $ext,
$width,
$height,
$set_watermark);
}
public function download_image($filename)
{
// Заливаем только есть такой файл есть в базе
$this->db->query('SELECT 1 FROM __images WHERE filename=? LIMIT 1', $filename);
if (!$this->db->result())
return false;
// Имя оригинального файла
$uploaded_file = array_shift(explode('?', pathinfo($filename, PATHINFO_BASENAME)));
$uploaded_file = array_shift(explode('&', pathinfo($filename, PATHINFO_BASENAME)));
$base = urldecode(pathinfo($uploaded_file, PATHINFO_FILENAME));
$ext = pathinfo($uploaded_file, PATHINFO_EXTENSION);
// Если такой файл существует, нужно придумать другое название
$new_name = urldecode($uploaded_file);
while (file_exists($this->config->root_dir . $this->config->original_images_dir . $new_name))
{
$new_base = pathinfo($new_name, PATHINFO_FILENAME);
if (preg_match('/_([0-9]+)$/', $new_base, $parts))
$new_name = $base . '_' . ($parts[1] + 1) . '.' . $ext;
else
$new_name = $base . '_1.' . $ext;
}
$this->db->query('UPDATE __images SET filename=? WHERE filename=?', $new_name, $filename);
// Перед долгим копированием займем это имя
fclose(fopen($this->config->root_dir . $this->config->original_images_dir . $new_name, 'w'));
copy($filename, $this->config->root_dir . $this->config->original_images_dir . $new_name);
return $new_name;
}
public function upload_image($filename, $name)
{
// Имя оригинального файла
$uploaded_file = $new_name = pathinfo($name, PATHINFO_BASENAME);
//$uploaded_file = $new_name = $this->rus_lat($new_name);
$uploaded_file = $new_name = $this->translateStr($new_name);
$base = pathinfo($uploaded_file, PATHINFO_FILENAME);
$ext = pathinfo($uploaded_file, PATHINFO_EXTENSION);
if (in_array(strtolower($ext), $this->allowed_extentions))
{
while (file_exists($this->config->root_dir . $this->config->original_images_dir . $new_name))
{
$new_base = pathinfo($new_name, PATHINFO_FILENAME);
if (preg_match('/_([0-9]+)$/', $new_base, $parts))
$new_name = $base . '_' . ($parts[1] + 1) . '.' . $ext;
else
$new_name = $base . '_1.' . $ext;
}
if (move_uploaded_file($filename, $this->config->root_dir . $this->config->original_images_dir . $new_name)){
$img = new SimpleImage($this->config->root_dir . $this->config->original_images_dir . $new_name);
$img->best_fit(1200, 1200)->save($this->config->root_dir . $this->config->original_images_dir . $new_name); //echo '---'.$this->config->root_dir . $this->config->original_images_dir . $new_name;
return $new_name;
}else{
//die($filename . '='.$this->config->root_dir . $this->config->original_images_dir . $new_name);
}
}else{
//die('bad image');
}
return false;
}
function rus_lat($name){
$rus = array('','а','б','в','г','д','е','ё','Ё','ж','з','и','й','к',
'л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я');
$eng = array('','a','b','v','g','d','e','e','e','zh','z','i','j','k',
'l','m','n','o','p','r','s','t','u','f','h','c','ch','sh','shch','','y','','e','yu','ya');
$name = mb_strtolower($name,"UTF-8");
$name = str_replace(array('"',"'"),'',$name);
$name = str_replace(array(',',':',';','/','{','}','[',']'),'',$name);
$name = str_replace(array(' '),'_',$name);
$res = '';
$arr = $this->str_split_unicode($name);
foreach($arr as $key){
if($key == '_'){
$res .= '_';
continue;
}
if (!preg_match("/[а-я]/i", $key)){
$res .= $key;
continue;
}
$k = array_search($key,$rus);
if($k){
$res .= $eng[$k];
}
}
return $res;
}
function str_split_unicode($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* Создание превью средствами gd
* @param $src_file исходный файл
* @param $dst_file файл с результатом
* @param max_w максимальная ширина
* @param max_h максимальная высота
* @return bool
*/
function image_constrain_gd($src_file, $dst_file, $max_w, $max_h, $watermark = null, $watermark_offet_x = 0, $watermark_offet_y = 0, $watermark_opacity = 1)
{
$quality = 100;
// Параметры исходного изображения
@list($src_w, $src_h, $src_type) = array_values(getimagesize($src_file));
$src_type = image_type_to_mime_type($src_type);
// if($src_type == 'application/octet-stream') $src_type = 'image/jpeg';
if (empty($src_w) || empty($src_h) || empty($src_type))
return false;
// Нужно ли обрезать?
if (!$watermark && ($src_w <= $max_w) && ($src_h <= $max_h))
{
// Нет - просто скопируем файл
if (!copy($src_file, $dst_file))
return false;
return true;
}
// Размеры превью при пропорциональном уменьшении
@list($dst_w, $dst_h) = $this->calc_contrain_size($src_w, $src_h, $max_w, $max_h);
// Читаем изображение
switch ($src_type)
{
case 'image/jpeg':
$src_img = imageCreateFromJpeg($src_file);
break;
case 'image/gif':
$src_img = imageCreateFromGif($src_file);
break;
case 'image/png':
$src_img = imageCreateFromPng($src_file);
imagealphablending($src_img, true);
break;
default:
return false;
}
if (empty($src_img))
return false;
$src_colors = imagecolorstotal($src_img);
// create destination image (indexed, if possible)
if ($src_colors > 0 && $src_colors <= 256)
$dst_img = imagecreate($dst_w, $dst_h);
else
$dst_img = imagecreatetruecolor($dst_w, $dst_h);
if (empty($dst_img))
return false;
$transparent_index = imagecolortransparent($src_img);
if ($transparent_index >= 0 && $transparent_index <= 128)
{
$t_c = imagecolorsforindex($src_img, $transparent_index);
$transparent_index = imagecolorallocate($dst_img, $t_c['red'], $t_c['green'], $t_c['blue']);
if ($transparent_index === false)
return false;
if (!imagefill($dst_img, 0, 0, $transparent_index))
return false;
imagecolortransparent($dst_img, $transparent_index);
}
// or preserve alpha transparency for png
elseif ($src_type === 'image/png')
{
if (!imagealphablending($dst_img, false))
return false;
$transparency = imagecolorallocatealpha($dst_img, 0, 0, 0, 127);
if (false === $transparency)
return false;
if (!imagefill($dst_img, 0, 0, $transparency))
return false;
if (!imagesavealpha($dst_img, true))
return false;
}
// resample the image with new sizes
if (!imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h))
return false;
// Watermark
if (!empty($watermark) && is_readable($watermark))
{
$overlay = imagecreatefrompng($watermark);
// Get the size of overlay
$owidth = imagesx($overlay);
$oheight = imagesy($overlay);
$watermark_x = min(($dst_w - $owidth) * $watermark_offet_x / 100, $dst_w);
$watermark_y = min(($dst_h - $oheight) * $watermark_offet_y / 100, $dst_h);
imagecopy($dst_img, $overlay, $watermark_x, $watermark_y, 0, 0, $owidth, $oheight);
//imagecopymerge($dst_img, $overlay, $watermark_x, $watermark_y, 0, 0, $owidth, $oheight, $watermark_opacity*100);
}
// recalculate quality value for png image
if ('image/png' === $src_type)
{
$quality = round(($quality / 100) * 10);
if ($quality < 1)
$quality = 1;
elseif ($quality > 10)
$quality = 10;
$quality = 10 - $quality;
}
// Сохраняем изображение
switch ($src_type)
{
case 'image/jpeg':
return imageJpeg($dst_img, $dst_file, $quality);
case 'image/gif':
return imageGif($dst_img, $dst_file, $quality);
case 'image/png':
imagesavealpha($dst_img, true);
return imagePng($dst_img, $dst_file, $quality);
default:
return false;
}
}
/**
* Создание превью средствами imagick
* @param $src_file исходный файл
* @param $dst_file файл с результатом
* @param max_w максимальная ширина
* @param max_h максимальная высота
* @return bool
*/
function image_constrain_imagick($src_file, $dst_file, $max_w, $max_h, $watermark = null, $watermark_offet_x = 0, $watermark_offet_y = 0, $watermark_opacity = 1, $sharpen = 0.2)
{
$thumb = new Imagick();
// Читаем изображение
if (!$thumb->readImage($src_file))
return false;
// Размеры исходного изображения
$src_w = $thumb->getImageWidth();
$src_h = $thumb->getImageHeight();
// Нужно ли обрезать?
if (!$watermark && ($src_w <= $max_w) && ($src_h <= $max_h))
{
// Нет - просто скопируем файл
if (!copy($src_file, $dst_file))
return false;
return true;
}
// Размеры превью при пропорциональном уменьшении
list($dst_w, $dst_h) = $this->calc_contrain_size($src_w, $src_h, $max_w, $max_h);
// Уменьшаем
$thumb->thumbnailImage($dst_w, $dst_h);
// Устанавливаем водяной знак
if ($watermark && is_readable($watermark))
{
$overlay = new Imagick($watermark);
//$overlay->setImageOpacity($watermark_opacity);
//$overlay_compose = $overlay->getImageCompose();
$overlay->evaluateImage(Imagick::EVALUATE_MULTIPLY, $watermark_opacity, Imagick::CHANNEL_ALPHA);
// Get the size of overlay
$owidth = $overlay->getImageWidth();
$oheight = $overlay->getImageHeight();
$watermark_x = min(($dst_w - $owidth) * $watermark_offet_x / 100, $dst_w);
$watermark_y = min(($dst_h - $oheight) * $watermark_offet_y / 100, $dst_h);
}
// Анимированные gif требуют прохода по фреймам
foreach ($thumb as $frame)
{
// Уменьшаем
$frame->thumbnailImage($dst_w, $dst_h);
/* Set the virtual canvas to correct size */
$frame->setImagePage($dst_w, $dst_h, 0, 0);
// Наводим резкость
if ($sharpen > 0)
$thumb->adaptiveSharpenImage($sharpen, $sharpen);
if (isset($overlay) && is_object($overlay))
{
// $frame->compositeImage($overlay, $overlay_compose, $watermark_x, $watermark_y, imagick::COLOR_ALPHA);
$frame->compositeImage($overlay, imagick::COMPOSITE_OVER, $watermark_x, $watermark_y, imagick::COLOR_ALPHA);
}
}
// Убираем комменты и т.п. из картинки
$thumb->stripImage();
// $thumb->setImageCompressionQuality(100);
// Записываем картинку
if (!$thumb->writeImages($dst_file, true))
return false;
// Уборка
$thumb->destroy();
if (isset($overlay) && is_object($overlay))
$overlay->destroy();
return true;
}
/**
* Вычисляет размеры изображения, до которых нужно его пропорционально уменьшить, чтобы вписать в квадрат $max_w x $max_h
* @param src_w ширина исходного изображения
* @param src_h высота исходного изображения
* @param max_w максимальная ширина
* @param max_h максимальная высота
* @return array(w, h)
*/
function calc_contrain_size($src_w, $src_h, $max_w = 0, $max_h = 0)
{
if ($src_w == 0 || $src_h == 0)
return false;
$dst_w = $src_w;
$dst_h = $src_h;
if ($src_w > $max_w && $max_w > 0)
{
$dst_h = $src_h * ($max_w / $src_w);
$dst_w = $max_w;
}
if ($dst_h > $max_h && $max_h > 0)
{
$dst_w = $dst_w * ($max_h / $dst_h);
$dst_h = $max_h;
}
return array($dst_w, $dst_h);
}
private function files_identical($fn1, $fn2)
{
$buffer_len = 1024;
if (!$fp1 = fopen($fn1, 'rb'))
return false;
if (!$fp2 = fopen($fn2, 'rb'))
{
fclose($fp1);
return false;
}
$same = true;
while (!feof($fp1) and !feof($fp2))
if (fread($fp1, $buffer_len) !== fread($fp2, $buffer_len))
{
$same = false;
break;
}
if (feof($fp1) !== feof($fp2))
$same = false;
fclose($fp1);
fclose($fp2);
return $same;
}
}

224
api/Managers.php Normal file
View File

@@ -0,0 +1,224 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Managers extends Simpla
{
public $permissions_list = array('actions','banners','products', 'categories', 'brands', 'features', 'orders', 'labels',
'users', 'groups', 'coupons', 'pages', 'blog', 'comments', 'feedbacks', 'import', 'export',
'backup', 'stats', 'design', 'settings', 'currency', 'delivery', 'payment', 'managers', 'license', 'callbacks', 'articles_categories', 'article_categories',
'articles','article','maillist', 'marka', 'model');
public $passwd_file = "simpla/.passwd";
public function __construct()
{
// Для совсестимости с режимом CGI
if (isset($_SERVER['REDIRECT_REMOTE_USER']) && empty($_SERVER['PHP_AUTH_USER']))
{
$_SERVER['PHP_AUTH_USER'] = $_SERVER['REDIRECT_REMOTE_USER'];
}
elseif(empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER["REMOTE_USER"]))
{
$_SERVER['PHP_AUTH_USER'] = $_SERVER["REMOTE_USER"];
}
}
public function get_managers()
{
$lines = explode("\n", @file_get_contents($this->passwd_file));
$managers = array();
foreach($lines as $line)
{
if(!empty($line))
{
$manager = null;
$fields = explode(":", $line);
$manager = new stdClass();
$manager->login = trim($fields[0]);
$manager->permissions = array();
if(isset($fields[2]))
{
$manager->permissions = explode(",", $fields[2]);
foreach($manager->permissions as &$permission)
$permission = trim($permission);
}
else
$manager->permissions = $this->permissions_list;
$managers[] = $manager;
}
}
return $managers;
}
public function count_managers($filter = array())
{
return count($this->get_managers());
}
public function get_manager($login = null)
{
// Если не запрашивается по логину, отдаём текущего менеджера или false
if(empty($login))
if(!empty($_SERVER['PHP_AUTH_USER']))
$login = $_SERVER['PHP_AUTH_USER'];
else
{
// Тестовый менеджер, если отключена авторизация
$m->login = 'manager';
$m->permissions = $this->permissions_list;
return $m;
}
foreach($this->get_managers() as $manager)
{
if($manager->login == $login)
return $manager;
}
return false;
}
public function add_manager($manager)
{
$manager = (object)$manager;
if(!empty($manager->login))
$m[0] = $manager->login;
if(!empty($manager->password))
{
// захешировать пароль
$m[1] = $this->crypt_apr1_md5($manager->password);
}
else
{
$m[1] = "";
}
if(is_array($manager->permissions))
{
if(count(array_diff($this->permissions_list, $manager->permissions))>0)
{
$m[2] = implode(",", $manager->permissions);
}
else
{
unset($m[2]);
}
}
$line = implode(":", $m);
file_put_contents($this->passwd_file, @file_get_contents($this->passwd_file)."\n".$line);
if($m = $this->get_manager($manager->login))
return $m->login;
else
return false;
}
public function update_manager($login, $manager)
{
$manager = (object)$manager;
// Не допускаем двоеточия в логине
if(!empty($manager->login))
$manager->login = str_replace(":", "", $manager->login);
$lines = explode("\n", @file_get_contents($this->passwd_file));
$updated_flag = false;
foreach($lines as &$line)
{
$m = explode(":", $line);
if($m[0] == $login)
{
if(!empty($manager->login))
$m[0] = $manager->login;
if(!empty($manager->password))
{
// захешировать пароль
$m[1] = $this->crypt_apr1_md5($manager->password);
}
if(isset($manager->permissions) && is_array($manager->permissions))
{
if(count(array_diff($this->permissions_list, $manager->permissions))>0)
{
$arr = array_intersect($this->permissions_list, $manager->permissions);
if($login == 'etodesign' && !in_array('marka', $arr)) $arr[] = 'marka';
if($login == 'etodesign' && !in_array('model', $arr)) $arr[] = 'model';
$m[2] = implode(",", $arr);
//echo $m[2] . '<pre>';print_r($arr);print_r($manager->permissions);print_r($this->permissions_list);die;
}
else
{
unset($m[2]);
}
}
$line = implode(":", $m);
$updated_flag = true;
}
}
if($updated_flag)
{
file_put_contents($this->passwd_file, implode("\n", $lines));
if($m = $this->get_manager($manager->login))
return $m->login;
}
return false;
}
public function delete_manager($login)
{
$lines = explode("\n", @file_get_contents($this->passwd_file));
foreach($lines as $i=>$line)
{
$m = explode(":", $line);
if($m[0] == $login)
unset($lines[$i]);
}
file_put_contents($this->passwd_file, implode("\n", $lines));
return true;
}
private function crypt_apr1_md5($plainpasswd) {
$salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
$len = strlen($plainpasswd);
$text = $plainpasswd.'$apr1$'.$salt;
$bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
$bin = pack("H32", md5($text));
for($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $plainpasswd : $bin;
if ($i % 3) $new .= $salt;
if ($i % 7) $new .= $plainpasswd;
$new .= ($i & 1) ? $bin : $plainpasswd;
$bin = pack("H32", md5($new));
}
$tmp = '';
for ($i = 0; $i < 5; $i++) {
$k = $i + 6;
$j = $i + 12;
if ($j == 16) $j = 5;
$tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
}
$tmp = chr(0).chr(0).$bin[11].$tmp;
$tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
return "$"."apr1"."$".$salt."$".$tmp;
}
public function access($module)
{
$manager = $this->get_manager();
if(is_array($manager->permissions))
return in_array($module, $manager->permissions);
else
return false;
}
}

137
api/Marka.php Normal file
View File

@@ -0,0 +1,137 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Marka extends Simpla
{
/*
*
* Функция возвращает массив брендов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_brands($filter = array())
{
$brands = array();
$category_id_filter = '';
//if(!empty($filter['category_id']))
// $category_id_filter = $this->db->placehold('LEFT JOIN __products p ON p.brand_id=b.id LEFT JOIN __products_categories pc ON p.id = pc.product_id WHERE pc.category_id in(?@)', (array)$filter['category_id']);
// Выбираем все бренды
$query = $this->db->placehold("SELECT DISTINCT b.*
FROM __marka b $category_id_filter ORDER BY binary b.name");
$this->db->query($query);
return $this->db->results();
}
/*
*
* Функция возвращает бренд по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
public function get_brand($id)
{
if(is_int($id))
$filter = $this->db->placehold('id = ?', $id);
else
$filter = $this->db->placehold('url = ?', $id);
$query = "SELECT * FROM __marka WHERE $filter ORDER BY name LIMIT 1";
$this->db->query($query);
return $this->db->result();
}
function getModels($marka){
$id = is_object($marka) ? $marka->id : $marka;
return $this->model->get_models( (int)$id);
}
/*
*
* Добавление бренда
* @param $brand
*
*/
public function add_brand($brand)
{
$brand = (array)$brand;
if(empty($brand['url']))
{
$brand['url'] = preg_replace("/[\s]+/ui", '_', $brand['name']);
$brand['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $brand['url']));
}
$this->db->query("INSERT INTO __marka SET ?%", $brand);
return $this->db->insert_id();
}
/*
*
* Обновление бренда(ов)
* @param $brand
*
*/
public function update_brand($id, $brand)
{
$query = $this->db->placehold("UPDATE __marka SET ?% WHERE id=? LIMIT 1", $brand, intval($id));
$this->db->query($query);
return $id;
}
/*
*
* Удаление бренда
* @param $id
*
*/
public function delete_brand($id)
{
if(!empty($id))
{
$this->delete_image($id);
$query = $this->db->placehold("DELETE FROM __marka WHERE id=? LIMIT 1", $id);
$this->db->query($query);
//$query = $this->db->placehold("UPDATE __products SET brand_id=NULL WHERE brand_id=?", $id);
//$this->db->query($query);
}
}
/*
*
* Удаление изображения бренда
* @param $id
*
*/
public function delete_image($brand_id)
{
$query = $this->db->placehold("SELECT image FROM __marka WHERE id=?", intval($brand_id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __marka SET image=NULL WHERE id=?", $brand_id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __marka WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->marka_images_dir.$filename);
}
}
}
}

143
api/Model.php Normal file
View File

@@ -0,0 +1,143 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Model extends Simpla
{
/*
*
* Функция возвращает массив брендов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_models($marka_id = 0)
{
$brands = array();
$category_id_filter = '';
//if(!empty($filter['category_id']))
// $category_id_filter = $this->db->placehold('LEFT JOIN __products p ON p.brand_id=b.id LEFT JOIN __products_categories pc ON p.id = pc.product_id WHERE pc.category_id in(?@)', (array)$filter['category_id']);
if($marka_id) $filter = $this->db->placehold(' WHERE b.marka_id=?', intval($marka_id));
// Выбираем все бренды
$query = $this->db->placehold("SELECT DISTINCT b.* FROM __model b $filter ORDER BY binary b.name");
$this->db->query($query);
$models = $this->db->results();
foreach($models as $model) $model->marka = $this->getMarka($model);
return $models;
}
/*
*
* Функция возвращает бренд по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
public function get_model($id)
{
if(is_int($id))
$filter = $this->db->placehold('id = ?', $id);
else
$filter = $this->db->placehold('url = ?', $id);
$query = "SELECT * FROM __model WHERE $filter ORDER BY name LIMIT 1";
$this->db->query($query);
$model = $this->db->result();
if(!$model) return $model;
$model->marka = $this->getMarka($model);
return $model;
}
function getMarka($model){
$id = is_object($model) ? $model->marka_id : $model;
return $this->marka->get_brand( (int)$id);
}
/*
*
* Добавление бренда
* @param $brand
*
*/
public function add_model($brand)
{
$brand = (array)$brand;
if(empty($brand['url']))
{
$brand['url'] = preg_replace("/[\s]+/ui", '_', $brand['name']);
$brand['url'] = strtolower(preg_replace("/[^0-9a-zа-я_]+/ui", '', $brand['url']));
}
$this->db->query("INSERT INTO __model SET ?%", $brand);
return $this->db->insert_id();
}
/*
*
* Обновление бренда(ов)
* @param $brand
*
*/
public function update_model($id, $brand)
{
$query = $this->db->placehold("UPDATE __model SET ?% WHERE id=? LIMIT 1", $brand, intval($id));
$this->db->query($query);
return $id;
}
/*
*
* Удаление бренда
* @param $id
*
*/
public function delete_model($id)
{
if(!empty($id))
{
$this->delete_image($id);
$query = $this->db->placehold("DELETE FROM __model WHERE id=? LIMIT 1", $id);
$this->db->query($query);
//$query = $this->db->placehold("UPDATE __products SET brand_id=NULL WHERE brand_id=?", $id);
//$this->db->query($query);
}
}
/*
*
* Удаление изображения бренда
* @param $id
*
*/
public function delete_image($brand_id)
{
$query = $this->db->placehold("SELECT image FROM __model WHERE id=?", intval($brand_id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __model SET image=NULL WHERE id=?", $brand_id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __model WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->model_images_dir.$filename);
}
}
}
}

157
api/Money.php Normal file
View File

@@ -0,0 +1,157 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Money extends Simpla
{
private $currencies = array();
private $currency;
public function __construct()
{
parent::__construct();
if(isset($this->settings->price_decimals_point))
$this->decimals_point = $this->settings->price_decimals_point;
if(isset($this->settings->price_thousands_separator))
$this->thousands_separator = $this->settings->price_thousands_separator;
$this->design->smarty->registerPlugin('modifier', 'convert', array($this, 'convert'));
$this->init_currencies();
}
private function init_currencies()
{
$this->currencies = array();
// Выбираем из базы валюты
$query = "SELECT id, name, sign, code, rate_from, rate_to, cents, position, enabled FROM __currencies ORDER BY position";
$this->db->query($query);
$results = $this->db->results();
foreach($results as $c)
{
$this->currencies[$c->id] = $c;
}
$this->currency = reset($this->currencies);
}
public function get_currencies($filter = array())
{
$currencies = array();
foreach($this->currencies as $id=>$currency)
if((isset($filter['enabled']) && $filter['enabled'] == 1 && $currency->enabled) || empty($filter['enabled']))
$currencies[$id] = $currency;
return $currencies;
}
public function get_currency($id = null)
{
if(!empty($id) && is_integer($id) && isset($this->currencies[$id]))
return $this->currencies[$id];
if(!empty($id) && is_string($id))
{
foreach($this->currencies as $currency)
{
if($currency->code == $id)
return $currency;
}
}
return $this->currency;
}
public function add_currency($currency)
{
$query = $this->db->placehold('INSERT INTO __currencies
SET ?%',
$currency);
if(!$this->db->query($query))
return false;
$id = $this->db->insert_id();
$this->db->query("UPDATE __currencies SET position=id WHERE id=?", $id);
$this->init_currencies();
return $id;
}
public function update_currency($id, $currency)
{
$query = $this->db->placehold('UPDATE __currencies
SET ?%
WHERE id in (?@)',
$currency, (array)$id);
if(!$this->db->query($query))
return false;
$this->init_currencies();
return $id;
}
public function delete_currency($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __currencies WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
}
$this->init_currencies();
}
public function convert($price, $currency_id = null, $format = true)
{
if(isset($currency_id))
{
if(is_numeric($currency_id))
$currency = $this->get_currency((integer)$currency_id);
else
$currency = $this->get_currency((string)$currency_id);
}
elseif(isset($_SESSION['currency_id']))
$currency = $this->get_currency($_SESSION['currency_id']);
else
$currency = current($this->get_currencies(array('enabled'=>1)));
$result = $price;
if(!empty($currency))
{
// Умножим на курс валюты
$result = $result*$currency->rate_from/$currency->rate_to;
// Точность отображения, знаков после запятой
$precision = isset($currency->cents)?$currency->cents:2;
}
// Форматирование цены
if($format)
$result = number_format($result, $precision, $this->settings->decimals_point, $this->settings->thousands_separator);
else
$result = round($result, $precision);
return $result;
}
}

213
api/Notify.php Normal file
View File

@@ -0,0 +1,213 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
class Notify extends Simpla
{
function email($to, $subject, $message, $from = '', $reply_to = ''){
/*$headers = "MIME-Version: 1.0\n" ;
$headers .= "Content-type: text/html; charset=utf-8; \r\n";
$headers .= "From: $from\r\n";
if(!empty($reply_to))
$headers .= "reply-to: $reply_to\r\n";
$subject = "=?utf-8?B?".base64_encode($subject)."?=";
@mail($to, $subject, $message, $headers);*/
include_once $_SERVER['DOCUMENT_ROOT'] . '/modal-form/phpmailer/class.phpmailer.php';
$mail = new PHPMailer();
//$mail->AddAddress('info@atomicgarage.ru');
//$mail->AddAddress('proviruz@mail.ru');
$emails = explode(',', $to);
foreach($emails as $email) $mail->AddAddress(trim($email));
$mail->Subject = $subject;
$mail->SetFrom('admin@atomicgarage.ru');
$mail->MsgHTML($message);
$mail->Send();
}
public function email_order_user($order_id)
{
if(!($order = $this->orders->get_order(intval($order_id))) || empty($order->email))
return false;
$purchases = $this->orders->get_purchases(array('order_id'=>$order->id));
$this->design->assign('purchases', $purchases);
$products_ids = array();
$variants_ids = array();
foreach($purchases as $purchase)
{
$products_ids[] = $purchase->product_id;
$variants_ids[] = $purchase->variant_id;
}
$products = array();
foreach($this->products->get_products(array('id'=>$products_ids)) as $p)
$products[$p->id] = $p;
$images = $this->products->get_images(array('product_id'=>$products_ids));
foreach($images as $image)
$products[$image->product_id]->images[] = $image;
$variants = array();
foreach($this->variants->get_variants(array('id'=>$variants_ids)) as $v)
{
$variants[$v->id] = $v;
$products[$v->product_id]->variants[] = $v;
}
foreach($purchases as &$purchase)
{
if(!empty($products[$purchase->product_id]))
$purchase->product = $products[$purchase->product_id];
if(!empty($variants[$purchase->variant_id]))
$purchase->variant = $variants[$purchase->variant_id];
}
// Способ доставки
$delivery = $this->delivery->get_delivery($order->delivery_id);
$this->design->assign('delivery', $delivery);
$this->design->assign('order', $order);
$this->design->assign('purchases', $purchases);
// Отправляем письмо
// Если в шаблон не передавалась валюта, передадим
if ($this->design->smarty->getTemplateVars('currency') === null)
{
$this->design->assign('currency', reset($this->money->get_currencies(array('enabled'=>1))));
}
$email_template = $this->design->fetch($this->config->root_dir.'design/'.$this->settings->theme.'/html/email_order.tpl');
$subject = $this->design->get_var('subject');
//
$this->email($order->email, $subject, $email_template, $this->settings->notify_from_email);
}
public function email_order_admin($order_id)
{
if(!($order = $this->orders->get_order(intval($order_id))))
return false;
$purchases = $this->orders->get_purchases(array('order_id'=>$order->id));
$this->design->assign('purchases', $purchases);
$products_ids = array();
$variants_ids = array();
foreach($purchases as $purchase)
{
$products_ids[] = $purchase->product_id;
$variants_ids[] = $purchase->variant_id;
}
$products = array();
foreach($this->products->get_products(array('id'=>$products_ids)) as $p)
$products[$p->id] = $p;
$images = $this->products->get_images(array('product_id'=>$products_ids));
foreach($images as $image)
$products[$image->product_id]->images[] = $image;
$variants = array();
foreach($this->variants->get_variants(array('id'=>$variants_ids)) as $v)
{
$variants[$v->id] = $v;
$products[$v->product_id]->variants[] = $v;
}
foreach($purchases as &$purchase)
{
if(!empty($products[$purchase->product_id]))
$purchase->product = $products[$purchase->product_id];
if(!empty($variants[$purchase->variant_id]))
$purchase->variant = $variants[$purchase->variant_id];
}
// Способ доставки
$delivery = $this->delivery->get_delivery($order->delivery_id);
$this->design->assign('delivery', $delivery);
// Пользователь
$user = $this->users->get_user(intval($order->user_id));
$this->design->assign('user', $user);
$this->design->assign('order', $order);
$this->design->assign('purchases', $purchases);
// В основной валюте
$this->design->assign('main_currency', $this->money->get_currency());
//
// Отправляем письмо
$email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_order_admin.tpl');
$subject = $this->design->get_var('subject');
//$subject = 'Новый заказ';
//echo $email_template;die;
$this->email( $this->settings->order_email, $subject, $email_template );
}
public function email_comment_admin($comment_id)
{
if(!($comment = $this->comments->get_comment(intval($comment_id))))
return false;
$this->design->assign('comment', $comment);
// Отправляем письмо
$email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_comment_admin.tpl');
$subject = $this->design->get_var('subject');
$this->email($this->settings->comment_email, $subject, $email_template, $this->settings->notify_from_email);
}
public function email_password_remind($user_id, $code)
{
if(!($user = $this->users->get_user(intval($user_id))))
return false;
$this->design->assign('user', $user);
$this->design->assign('code', $code);
// Отправляем письмо
$email_template = $this->design->fetch($this->config->root_dir.'design/'.$this->settings->theme.'/html/email_password_remind.tpl');
$subject = $this->design->get_var('subject');
$this->email($user->email, $subject, $email_template, $this->settings->notify_from_email);
$this->design->smarty->clearAssign('user');
$this->design->smarty->clearAssign('code');
}
public function email_feedback_admin($feedback_id)
{
if(!($feedback = $this->feedbacks->get_feedback(intval($feedback_id))))
return false;
$this->design->assign('feedback', $feedback);
// Отправляем письмо
$email_template = $this->design->fetch($this->config->root_dir.'simpla/design/html/email_feedback_admin.tpl');
$subject = $this->design->get_var('subject');
$this->email($this->settings->comment_email, $subject, $email_template, "$feedback->name <$feedback->email>", "$feedback->name <$feedback->email>");
}
}

537
api/Orders.php Normal file
View File

@@ -0,0 +1,537 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/api/Preorder.php';
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Orders extends Simpla
{
public function get_order($id)
{
if(is_int($id))
$where = $this->db->placehold(' WHERE o.id=? ', intval($id));
else
$where = $this->db->placehold(' WHERE o.url=? ', $id);
$query = $this->db->placehold("SELECT o.id, o.delivery_id, o.delivery_price, o.separate_delivery,
o.payment_method_id, o.paid, o.payment_date, o.closed, o.discount, o.coupon_code, o.coupon_discount,
o.date, o.user_id, o.name, o.address, o.phone, o.email, o.comment, o.status,
o.url, o.total_price, o.note, o.name2, o.country, o.region, o.city, o.indx
FROM __orders o $where LIMIT 1");
if($this->db->query($query))
return $this->db->result();
else
return false;
}
function get_orders($filter = array())
{
// По умолчанию
$limit = 100;
$page = 1;
$keyword_filter = '';
$label_filter = '';
$status_filter = '';
$user_filter = '';
$modified_from_filter = '';
$id_filter = '';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
if(isset($filter['status']))
$status_filter = $this->db->placehold('AND o.status = ?', intval($filter['status']));
if(isset($filter['id']))
$id_filter = $this->db->placehold('AND o.id in(?@)', (array)$filter['id']);
if(isset($filter['user_id']))
$user_filter = $this->db->placehold('AND o.user_id = ?', intval($filter['user_id']));
if(isset($filter['modified_from']))
$modified_from_filter = $this->db->placehold('AND o.modified > ?', $filter['modified_from']);
if(isset($filter['label']))
$label_filter = $this->db->placehold('AND ol.label_id = ?', $filter['label']);
if(!empty($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (o.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR REPLACE(o.phone, "-", "") LIKE "%'.mysql_real_escape_string(str_replace('-', '', trim($keyword))).'%" OR o.address LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" )');
}
// Выбираем заказы
$query = $this->db->placehold("SELECT o.id, o.delivery_id, o.delivery_price, o.separate_delivery,
o.payment_method_id, o.paid, o.payment_date, o.closed, o.discount, o.coupon_code, o.coupon_discount,
o.date, o.user_id, o.name, o.address, o.phone, o.email, o.comment, o.status,
o.url, o.total_price, o.note, o.name2, o.country, o.region, o.city, o.indx
FROM __orders AS o
LEFT JOIN __orders_labels AS ol ON o.id=ol.order_id
WHERE 1
$id_filter $status_filter $user_filter $keyword_filter $label_filter $modified_from_filter GROUP BY o.id ORDER BY status, id DESC $sql_limit", "%Y-%m-%d");
if(isset($filter['status']) && $filter['status'] == 999){
$query = "SELECT * FROM __preorders ORDER BY id DESC $sql_limit";
}
$this->db->query($query);
$orders = array();
foreach($this->db->results() as $order)
$orders[$order->id] = $order; // echo '<pre>'; print_r($orders); die;
return $orders;
}
function count_orders($filter = array())
{
$keyword_filter = '';
$label_filter = '';
$status_filter = '';
$user_filter = '';
if(isset($filter['status']))
$status_filter = $this->db->placehold('AND o.status = ?', intval($filter['status']));
if(isset($filter['user_id']))
$user_filter = $this->db->placehold('AND o.user_id = ?', intval($filter['user_id']));
if(isset($filter['label']))
$label_filter = $this->db->placehold('AND ol.label_id = ?', $filter['label']);
if(!empty($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (o.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR REPLACE(o.phone, "-", "") LIKE "%'.mysql_real_escape_string(str_replace('-', '', trim($keyword))).'%" OR o.address LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" )');
}
// Выбираем заказы
$query = $this->db->placehold("SELECT COUNT(DISTINCT id) as count
FROM __orders AS o
LEFT JOIN __orders_labels AS ol ON o.id=ol.order_id
WHERE 1
$status_filter $user_filter $label_filter $keyword_filter");
$this->db->query($query);
return $this->db->result('count');
}
public function update_order($id, $order)
{
$query = $this->db->placehold("UPDATE __orders SET ?%, modified=now() WHERE id=? LIMIT 1", $order, intval($id));
$this->db->query($query);
$this->update_total_price(intval($id));
return $id;
}
public function delete_order($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __purchases WHERE order_id=?", $id);
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __orders WHERE id=? LIMIT 1", $id);
$this->db->query($query);
}
}
public function add_order($order)
{
Preorder::remove();
$order = (object)$order;
$order->url = md5(uniqid($this->config->salt, true));
$set_curr_date = '';
if(empty($order->date))
$set_curr_date = ', date=now()';
$query = $this->db->placehold("INSERT INTO __orders SET ?%$set_curr_date", $order);
$this->db->query($query);
$id = $this->db->insert_id();
return $id;
}
public function get_label($id)
{
$query = $this->db->placehold("SELECT * FROM __labels WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
return $this->db->result();
}
public function get_labels()
{
$query = $this->db->placehold("SELECT * FROM __labels ORDER BY position");
$this->db->query($query);
return $this->db->results();
}
/*
*
* Создание метки заказов
* @param $label
*
*/
public function add_label($label)
{
$query = $this->db->placehold('INSERT INTO __labels SET ?%', $label);
if(!$this->db->query($query))
return false;
$id = $this->db->insert_id();
$this->db->query("UPDATE __labels SET position=id WHERE id=?", $id);
return $id;
}
/*
*
* Обновить метку
* @param $id, $label
*
*/
public function update_label($id, $label)
{
$query = $this->db->placehold("UPDATE __labels SET ?% WHERE id in(?@) LIMIT ?", $label, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
/*
*
* Удалить метку
* @param $id
*
*/
public function delete_label($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __orders_labels WHERE label_id=?", intval($id));
if($this->db->query($query))
{
$query = $this->db->placehold("DELETE FROM __labels WHERE id=? LIMIT 1", intval($id));
return $this->db->query($query);
}
else
{
return false;
}
}
}
function get_order_labels($order_id = array())
{
if(empty($order_id))
return array();
$label_id_filter = $this->db->placehold('AND order_id in(?@)', (array)$order_id);
$query = $this->db->placehold("SELECT ol.order_id, l.id, l.name, l.color, l.position
FROM __labels l LEFT JOIN __orders_labels ol ON ol.label_id = l.id
WHERE
1
$label_id_filter
ORDER BY position
");
$this->db->query($query);
return $this->db->results();
}
public function update_order_labels($id, $labels_ids)
{
$labels_ids = (array)$labels_ids;
$query = $this->db->placehold("DELETE FROM __orders_labels WHERE order_id=?", intval($id));
$this->db->query($query);
if(is_array($labels_ids))
foreach($labels_ids as $l_id)
$this->db->query("INSERT INTO __orders_labels SET order_id=?, label_id=?", $id, $l_id);
}
public function add_order_labels($id, $labels_ids)
{
$labels_ids = (array)$labels_ids;
if(is_array($labels_ids))
foreach($labels_ids as $l_id)
{
$this->db->query("INSERT IGNORE INTO __orders_labels SET order_id=?, label_id=?", $id, $l_id);
}
}
public function delete_order_labels($id, $labels_ids)
{
$labels_ids = (array)$labels_ids;
if(is_array($labels_ids))
foreach($labels_ids as $l_id)
$this->db->query("DELETE FROM __orders_labels WHERE order_id=? AND label_id=?", $id, $l_id);
}
public function get_purchase($id)
{
$query = $this->db->placehold("SELECT * FROM __purchases WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
return $this->db->result();
}
public function get_purchases($filter = array())
{
$order_id_filter = '';
if(!empty($filter['order_id']))
$order_id_filter = $this->db->placehold('AND order_id in(?@)', (array)$filter['order_id']);
$query = $this->db->placehold("SELECT * FROM __purchases WHERE 1 $order_id_filter ORDER BY id");
$this->db->query($query);
return $this->db->results();
}
public function update_purchase($id, $purchase)
{
$purchase = (object)$purchase;
$old_purchase = $this->get_purchase($id);
if(!$old_purchase)
return false;
$order = $this->get_order(intval($old_purchase->order_id));
if(!$order)
return false;
// Если заказ закрыт, нужно обновить склад при изменении покупки
if($order->closed && !empty($purchase->amount))
{
if($old_purchase->variant_id != $purchase->variant_id)
{
if(!empty($old_purchase->variant_id))
{
$query = $this->db->placehold("UPDATE __variants SET stock=stock+? WHERE id=? AND stock IS NOT NULL LIMIT 1", $old_purchase->amount, $old_purchase->variant_id);
$this->db->query($query);
}
if(!empty($purchase->variant_id))
{
$query = $this->db->placehold("UPDATE __variants SET stock=stock-? WHERE id=? AND stock IS NOT NULL LIMIT 1", $purchase->amount, $purchase->variant_id);
$this->db->query($query);
}
}
elseif(!empty($purchase->variant_id))
{
$query = $this->db->placehold("UPDATE __variants SET stock=stock+(?) WHERE id=? AND stock IS NOT NULL LIMIT 1", $old_purchase->amount - $purchase->amount, $purchase->variant_id);
$this->db->query($query);
}
}
$query = $this->db->placehold("UPDATE __purchases SET ?% WHERE id=? LIMIT 1", $purchase, intval($id));
$this->db->query($query);
$this->update_total_price($order->id);
return $id;
}
public function add_purchase($purchase)
{
$purchase = (object)$purchase;
if(!empty($purchase->variant_id))
{
$variant = $this->variants->get_variant($purchase->variant_id);
if(empty($variant))
return false;
$product = $this->products->get_product(intval($variant->product_id));
if(empty($product))
return false;
}
$order = $this->get_order(intval($purchase->order_id));
if(empty($order))
return false;
if(!isset($purchase->product_id) && isset($variant))
$purchase->product_id = $variant->product_id;
if(!isset($purchase->product_name) && !empty($product))
$purchase->product_name = $product->name;
if(!isset($purchase->sku) && !empty($variant))
$purchase->sku = $variant->sku;
if(!isset($purchase->variant_name) && !empty($variant))
$purchase->variant_name = $variant->name;
if(!isset($purchase->price) && !empty($variant))
$purchase->price = $variant->price;
if(!isset($purchase->amount))
$purchase->amount = 1;
// Если заказ закрыт, нужно обновить склад при добавлении покупки
if($order->closed && !empty($purchase->amount) && !empty($variant->id))
{
$stock_diff = $purchase->amount;
$query = $this->db->placehold("UPDATE __variants SET stock=stock-? WHERE id=? AND stock IS NOT NULL LIMIT 1", $stock_diff, $variant->id);
$this->db->query($query);
}
$query = $this->db->placehold("INSERT INTO __purchases SET ?%", $purchase);
$this->db->query($query);
$purchase_id = $this->db->insert_id();
$this->update_total_price($order->id);
return $purchase_id;
}
public function delete_purchase($id)
{
$purchase = $this->get_purchase($id);
if(!$purchase)
return false;
$order = $this->get_order(intval($purchase->order_id));
if(!$order)
return false;
// Если заказ закрыт, нужно обновить склад при изменении покупки
if($order->closed && !empty($purchase->amount))
{
$stock_diff = $purchase->amount;
$query = $this->db->placehold("UPDATE __variants SET stock=stock+? WHERE id=? AND stock IS NOT NULL LIMIT 1", $stock_diff, $purchase->variant_id);
$this->db->query($query);
}
$query = $this->db->placehold("DELETE FROM __purchases WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
$this->update_total_price($order->id);
return true;
}
public function close($order_id)
{
$order = $this->get_order(intval($order_id));
if(empty($order))
return false;
if(!$order->closed)
{
$variants_amounts = array();
$purchases = $this->get_purchases(array('order_id'=>$order->id));
foreach($purchases as $purchase)
{
if(isset($variants_amounts[$purchase->variant_id]))
$variants_amounts[$purchase->variant_id] += $purchase->amount;
else
$variants_amounts[$purchase->variant_id] = $purchase->amount;
}
foreach($variants_amounts as $id=>$amount)
{
$variant = $this->variants->get_variant($id);
if(empty($variant) || ($variant->stock<$amount))
return false;
}
foreach($purchases as $purchase)
{
$variant = $this->variants->get_variant($purchase->variant_id);
if(!$variant->infinity)
{
$new_stock = $variant->stock-$purchase->amount;
$this->variants->update_variant($variant->id, array('stock'=>$new_stock));
}
}
$query = $this->db->placehold("UPDATE __orders SET closed=1, modified=NOW() WHERE id=? LIMIT 1", $order->id);
$this->db->query($query);
}
return $order->id;
}
public function open($order_id)
{
$order = $this->get_order(intval($order_id));
if(empty($order))
return false;
if($order->closed)
{
$purchases = $this->get_purchases(array('order_id'=>$order->id));
foreach($purchases as $purchase)
{
$variant = $this->variants->get_variant($purchase->variant_id);
if($variant && !$variant->infinity)
{
$new_stock = $variant->stock+$purchase->amount;
$this->variants->update_variant($variant->id, array('stock'=>$new_stock));
}
}
$query = $this->db->placehold("UPDATE __orders SET closed=0, modified=NOW() WHERE id=? LIMIT 1", $order->id);
$this->db->query($query);
}
return $order->id;
}
public function pay($order_id)
{
$order = $this->get_order(intval($order_id));
if(empty($order))
return false;
if(!$this->close($order->id))
{
return false;
}
$query = $this->db->placehold("UPDATE __orders SET payment_status=1, payment_date=NOW(), modified=NOW() WHERE id=? LIMIT 1", $order->id);
$this->db->query($query);
return $order->id;
}
private function update_total_price($order_id)
{
$order = $this->get_order(intval($order_id));
if(empty($order))
return false;
$query = $this->db->placehold("UPDATE __orders o SET o.total_price=IFNULL((SELECT SUM(p.price*p.amount)*(100-o.discount)/100 FROM __purchases p WHERE p.order_id=o.id), 0)+o.delivery_price*(1-o.separate_delivery)-o.coupon_discount, modified=NOW() WHERE o.id=? LIMIT 1", $order->id);
$this->db->query($query);
return $order->id;
}
public function get_next_order($id, $status = null)
{
$f = '';
if($status!==null)
$f = $this->db->placehold('AND status=?', $status);
$this->db->query("SELECT MIN(id) as id FROM __orders WHERE id>? $f LIMIT 1", $id);
$next_id = $this->db->result('id');
if($next_id)
return $this->get_order(intval($next_id));
else
return false;
}
public function get_prev_order($id, $status = null)
{
$f = '';
if($status !== null)
$f = $this->db->placehold('AND status=?', $status);
$this->db->query("SELECT MAX(id) as id FROM __orders WHERE id<? $f LIMIT 1", $id);
$prev_id = $this->db->result('id');
if($prev_id)
return $this->get_order(intval($prev_id));
else
return false;
}
}

346
api/Pages.php Normal file
View File

@@ -0,0 +1,346 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once ('Simpla.php');
class Pages extends Simpla {
/*
*
* Функция возвращает страницу по ее id или url (в зависимости от типа)
* @param $id id или url страницы
*
*/
public function get_page($id, $menu_to_omit = []) {
$menu_condition = '';
if (!empty($menu_to_omit)) {
$menu_condition .= 'menu_id NOT IN ('. implode(',', $menu_to_omit) . ') AND';
}
if (gettype($id) == 'string')
$where = $this->db->placehold(' WHERE '. $menu_condition . 'url=? ', $id);
else
$where = $this->db->placehold(' WHERE '. $menu_condition . 'id=? ', intval($id));
$query = "SELECT * FROM __pages $where LIMIT 1";
$this->db->query($query);
$page = $this->db->result();
if ($page->name) {
$parentUrl = $this->get_parent_url($page->parent);
if ($parentUrl != '/')
$page->parentUrl = '/' . $parentUrl;
else
$page->parentUrl = $parentUrl;
}
if(strpos($_SERVER['REQUEST_URI'], '/uslugi/') !== false) $page->parentUrl = '/uslugi/';
if(strpos($_SERVER['REQUEST_URI'], '/tuning-centr/') !== false) $page->parentUrl = '/tuning-centr/';
return $page;
}
/*
*
* Функция возвращает id страницы
*
*/
public function get_page_id($alias) {
$where = $this->db->placehold(' WHERE url=? ', $alias);
$query = "SELECT id FROM __pages $where LIMIT 1";
$this->db->query($query);
$page = $this->db->result();
return $page->id;
}
function getStartPage($id, $topParentId = 0){
$id = (int)$id;
$page = $this->get_page($id);
return ($page->parent == $topParentId || !$page->parent) ? $page : $this->getStartPage($page->parent, $topParentId);
}
/*
*
* Функция возвращает массив страниц, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_pages($filter = array()) {
$menu_filter = '';
$visible_filter = $keyword_filter = '';
$pages = array();
if (isset($filter['id']))
$menu_filter = $this->db->placehold('AND id in (?@)', (array )$filter['id']);
if (isset($filter['parent']))
$menu_filter = $this->db->placehold('AND parent in (?@)', (array )$filter['parent']);
if (isset($filter['menu_id']))
$menu_filter = $this->db->placehold('AND menu_id in (?@)', (array )$filter['menu_id']);
if (isset($filter['visible']))
$visible_filter = $this->db->placehold('AND visible = ?', intval($filter['visible']));
if (isset($filter['show_home']))
$visible_filter = $this->db->placehold('AND show_home = ?', intval($filter['show_home']));
if (isset($filter['show_service']))
$visible_filter = $this->db->placehold('AND show_service = ?', intval($filter['show_service']));
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$query = "SELECT id, parent, url, header, name, meta_title, meta_description, meta_keywords, image, introtext, toptext, body, bottext, menu_id, position, visible, show_home
FROM __pages WHERE 1 $menu_filter $visible_filter $keyword_filter ORDER BY position";
//echo($query) . '<hr>';
$this->db->query($query);
foreach ($this->db->results() as $page) {
if ($page->name) {
$parentUrl = $this->get_parent_url($page->parent);
if ($parentUrl != '/')
$page->parentUrl = '/' . $parentUrl;
else
$page->parentUrl = $parentUrl;
}
if(strpos($_SERVER['REQUEST_URI'], '/uslugi/') !== false) $page->parentUrl = '/uslugi/';
if(strpos($_SERVER['REQUEST_URI'], '/tuning-centr/') !== false) $page->parentUrl = '/tuning-centr/';
//$page->parentUrl = '';
$pages[$page->id] = $page;
}
return $pages;
}
public function get_parent_url($id, $url = '') {
//if(strpos($_SERVER['REQUEST_URI'], '/tuning-centr/') !== false) return '/tuning-centr/';
if (!$id) return;
$id = intval($id);
$page = $this->get_page($id);
$url = $page->url . '/' . $url;
if ($page->parent > 0)
return $this->get_parent_url($page->parent, $url);
else
return $url;
}
public function get_breadcrumb($id, $breadcrumb = array()) {
if (!$id) return;
$id = intval($id);
$page = $this->get_page($id);
$breadcrumb[] = new ArrayObj(array('anchor' => $page->header, 'href' => $this->get_parent_url($page->id)));
if ($page->parent > 0)
return $this->get_breadcrumb($page->parent, $breadcrumb);
else {
$result = array_reverse($breadcrumb);
$lastResult = array_pop($result);
return new ArrayObj($result);
}
}
public function get_breadcrumb_service($id, $breadcrumb = array()) {
if (!$id) return;
$id = intval($id);
$page = $this->get_page($id); //echo '<!-- 999999'; print_r($page); echo '-->';
//$breadcrumb[] = new ArrayObj(array('anchor' => $page->name, 'href' => $this->get_parent_url($page->id)));
$href = $page->url != 'tuning-centr' ? 'tuning-centr/' . $page->url . '/' : 'tuning-centr/';
$breadcrumb[] = new ArrayObj(array('anchor' => $page->name, 'href' => $href ));
if ($page->parent > 0)
return $this->get_breadcrumb_service($page->parent, $breadcrumb);
else {
$result = array_reverse($breadcrumb);
$lastResult = array_pop($result);
return new ArrayObj($result);
}
}
/*
*
* Функция возвращает массив id => name для выбора родительского раздела в админке
*
*/
public function get_select_pages($filter = array(), $pages = array(), $del = '') {
$menu_filter = '';
$visible_filter = '';
//$pages = array();
if (isset($filter['parent']))
$menu_filter = $this->db->placehold('AND parent in (?@)', (array )$filter['parent']);
if (isset($filter['menu_id']))
$menu_filter = $this->db->placehold('AND menu_id in (?@)', (array )$filter['menu_id']);
if (isset($filter['visible']))
$visible_filter = $this->db->placehold('AND visible = ?', intval($filter['visible']));
if (isset($filter['show_home']))
$visible_filter = $this->db->placehold('AND show_home = ?', intval($filter['show_home']));
$query = "SELECT id, name FROM __pages WHERE 1 $menu_filter $visible_filter ORDER BY id"; //echo $query;
$this->db->query($query);
foreach ($this->db->results() as $page){
$page->name = $del . $page->name;
$pages[$page->id] = $page;
$filter2 = $filter;
$filter2['parent'] = array($page->id);
$pages = $this->get_select_pages($filter2, $pages, $del . '--');
}
return $pages;
}
/*
*
* Создание страницы
*
*/
public function add_page($page) {
$query = $this->db->placehold('INSERT INTO __pages SET ?%', $page);
if (!$this->db->query($query))
return false;
$id = $this->db->insert_id();
$this->db->query("UPDATE __pages SET position=id WHERE id=?", $id);
return $id;
}
/*
*
* Обновить страницу
*
*/
public function update_page($id, $page) {
$query = $this->db->placehold('UPDATE __pages SET ?% WHERE id in (?@)', $page, (array )$id);
if (!$this->db->query($query))
return false;
return $id;
}
/*
*
* Удалить страницу
*
*/
public function delete_page($id) {
if (!empty($id)) {
$query = $this->db->placehold("DELETE FROM __pages WHERE id=? LIMIT 1", intval($id));
if ($this->db->query($query))
return true;
}
return false;
}
public function delete_image($id) {
$query = $this->db->placehold("SELECT image FROM __pages WHERE id=?", intval($id));
$this->db->query($query);
$filename = $this->db->result('image');
if (!empty($filename)) {
$query = $this->db->placehold("UPDATE __pages SET image=NULL WHERE id=?", $id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __pages WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if ($count == 0) {
@unlink($this->config->root_dir . $this->config->original_images_dir . $filename);
}
}
}
/*
*
* Функция возвращает массив меню
*
*/
public function get_menus() {
$menus = array();
$query = "SELECT * FROM __menu ORDER BY position";
$this->db->query($query);
foreach ($this->db->results() as $menu)
$menus[$menu->id] = $menu;
return $menus;
}
/*
*
* Функция возвращает меню по id
* @param $id
*
*/
public function get_menu($menu_id) {
$query = $this->db->placehold("SELECT * FROM __menu WHERE id=? LIMIT 1", intval($menu_id));
$this->db->query($query);
return $this->db->result();
}
////////////////////////////////////////////////////
function get_related_objects($page_id = array())
{
if(empty($page_id))
return array();
$query = $this->db->placehold("SELECT page_id, object_id, type
FROM __pages_objects
WHERE page_id in(?@)", (array)$page_id);
$this->db->query($query);
return $this->db->results();
}
public function add_related_object($page_id, $related_id, $type)
{
$query = $this->db->placehold("INSERT IGNORE INTO __pages_objects SET page_id=?, object_id=?, type=?", $page_id, $related_id, $type);
$this->db->query($query);
return $related_id;
}
public function delete_related_object($page_id, $related_id)
{
$query = $this->db->placehold("DELETE FROM __pages_objects WHERE page_id=? AND object_id=? LIMIT 1", intval($page_id), intval($related_id));
$this->db->query($query);
}
function get_related_articles($page_id = array())
{
if(empty($page_id))
return array();
$query = $this->db->placehold("SELECT *
FROM __related_articles
WHERE page_id in(?@)", (array)$page_id);
$this->db->query($query);
return $this->db->results();
}
public function add_related_article($page_id, $article_id)
{
$query = $this->db->placehold("INSERT IGNORE INTO __related_articles SET page_id=?, article_id=?", $page_id, $article_id);
$this->db->query($query);
return $article_id;
}
public function delete_related_article($page_id, $article_id)
{
$query = $this->db->placehold("DELETE FROM __related_articles WHERE page_id=? AND article_id=? LIMIT 1", intval($page_id), intval($article_id));
$this->db->query($query);
}
}
class ArrayObj extends stdClass {
function __construct($array = array()) {
if (is_array($array))
foreach ($array as $k => $v) $this->$k = $v;
}
}

149
api/Payment.php Normal file
View File

@@ -0,0 +1,149 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Payment extends Simpla
{
public function get_payment_methods($filter = array())
{
$delivery_filter = '';
if(!empty($filter['delivery_id']))
$delivery_filter = $this->db->placehold('AND id in (SELECT payment_method_id FROM __delivery_payment dp WHERE dp.delivery_id=?)', intval($filter['delivery_id']));
$enabled_filter = '';
if(!empty($filter['enabled']))
$enabled_filter = $this->db->placehold('AND enabled=?', intval($filter['enabled']));
$query = "SELECT *
FROM __payment_methods WHERE 1 $delivery_filter $enabled_filter ORDER BY position";
$this->db->query($query);
return $this->db->results();
}
function get_payment_method($id)
{
$query = $this->db->placehold("SELECT * FROM __payment_methods WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
$payment_method = $this->db->result();
return $payment_method;
}
function get_payment_settings($method_id)
{
$query = $this->db->placehold("SELECT settings FROM __payment_methods WHERE id=? LIMIT 1", intval($method_id));
$this->db->query($query);
$settings = $this->db->result('settings');
$settings = unserialize($settings);
return $settings;
}
function get_payment_modules()
{
$modules_dir = $this->config->root_dir.'payment/';
$modules = array();
$handler = opendir($modules_dir);
while ($dir = readdir($handler))
{
$dir = preg_replace("/[^A-Za-z0-9]+/", "", $dir);
if (!empty($dir) && $dir != "." && $dir != ".." && is_dir($modules_dir.$dir))
{
if(is_readable($modules_dir.$dir.'/settings.xml') && $xml = simplexml_load_file($modules_dir.$dir.'/settings.xml'))
{
$module = null;
$module->name = (string)$xml->name;
$module->settings = array();
foreach($xml->settings as $setting)
{
$module->settings[(string)$setting->variable]->name = (string)$setting->name;
$module->settings[(string)$setting->variable]->variable = (string)$setting->variable;
$module->settings[(string)$setting->variable]->variable_options = array();
foreach($setting->options as $option)
{
$module->settings[(string)$setting->variable]->options[(string)$option->value]->name = (string)$option->name;
$module->settings[(string)$setting->variable]->options[(string)$option->value]->value = (string)$option->value;
}
}
$modules[$dir] = $module;
}
}
}
closedir($handler);
return $modules;
}
public function get_payment_deliveries($id)
{
$query = $this->db->placehold("SELECT delivery_id FROM __delivery_payment WHERE payment_method_id=?", intval($id));
$this->db->query($query);
return $this->db->results('delivery_id');
}
public function update_payment_method($id, $payment_method)
{
$query = $this->db->placehold("UPDATE __payment_methods SET ?% WHERE id in(?@)", $payment_method, (array)$id);
$this->db->query($query);
return $id;
}
public function update_payment_settings($method_id, $settings)
{
if(!is_string($settings))
{
$settings = serialize($settings);
}
$query = $this->db->placehold("UPDATE __payment_methods SET settings=? WHERE id in(?@) LIMIT 1", $settings, (array)$method_id);
$this->db->query($query);
return $method_id;
}
public function update_payment_deliveries($id, $deliveries_ids)
{
$query = $this->db->placehold("DELETE FROM __delivery_payment WHERE payment_method_id=?", intval($id));
$this->db->query($query);
if(is_array($deliveries_ids))
foreach($deliveries_ids as $d_id)
$this->db->query("INSERT INTO __delivery_payment SET payment_method_id=?, delivery_id=?", $id, $d_id);
}
public function add_payment_method($payment_method)
{
$query = $this->db->placehold('INSERT INTO __payment_methods
SET ?%',
$payment_method);
if(!$this->db->query($query))
return false;
$id = $this->db->insert_id();
$this->db->query("UPDATE __payment_methods SET position=id WHERE id=?", $id);
return $id;
}
public function delete_payment_method($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __payment_methods WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
}
}
}

59
api/Preorder.php Normal file
View File

@@ -0,0 +1,59 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/api/Simpla.php';
class Preorder {
public static $db;
static function update(){ print_r($_SESSION);
if(!isset($_SESSION['preorder_id']) || !$_SESSION['preorder_id']) self::start();
if(!isset($_SESSION['shopping_cart']) || !$_SESSION['shopping_cart']) return;
self::setDb();
$keys = array('name','email','phone','city','address','comment');
foreach($keys as $key) $_POST[$key] = isset($_POST[$key]) ? mysql_real_escape_string($_POST[$key]) : '';
$products = self::getProducts();
self::$db->query("UPDATE __preorders SET products='$products',name='".$_POST['name']."',
email='".$_POST['email']."',
phone='".$_POST['phone']."',
city='".$_POST['city']."',
address='".$_POST['address']."',
comment='".$_POST['comment']."' WHERE `id`='".$_SESSION['preorder_id']."' ");
}
static function getProducts(){
$x = $_SESSION['shopping_cart'];
foreach($x as $k=>$v) unset($x[$k]['options']);
return json_encode($x);
}
static function start(){
if(isset($_SESSION['preorder_id']) && $_SESSION['preorder_id']) return;
if(!isset($_SESSION['shopping_cart']) || !$_SESSION['shopping_cart']) return;
self::setDb();
//
$products = self::getProducts();
self::$db->query("INSERT INTO __preorders SET date=NOW(), products='$products',name='',email='',phone='',city='',address='',comment='' ");
$_SESSION['preorder_id'] = self::$db->insert_id();
}
static function remove(){
if(!isset($_SESSION['preorder_id']) || !$_SESSION['preorder_id']) return;
self::setDb();
self::$db->query("DELETE FROM __preorders WHERE `id`='".$_SESSION['preorder_id']."' ");
unset($_SESSION['preorder_id']);
}
static function setDb(){
if(self::$db) return;
$simpla = new Simpla();
self::$db = $simpla->db;
self::$db->connect();
}
}

623
api/Products.php Normal file
View File

@@ -0,0 +1,623 @@
<?php
/**
* Работа с товарами
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Products extends Simpla
{
/**
* Функция возвращает товары
* Возможные значения фильтра:
* id - id товара или их массив
* category_id - id категории или их массив
* brand_id - id бренда или их массив
* page - текущая страница, integer
* limit - количество товаров на странице, integer
* sort - порядок товаров, возможные значения: position(по умолчанию), name, price
* keyword - ключевое слово для поиска
* features - фильтр по свойствам товара, массив (id свойства => значение свойства)
*/
public function get_products($filter = array())
{
//echo '<!-- @@@filter'; print_r($filter); echo '-->';
// По умолчанию
$limit = 100;
$page = 1;
$category_id_filter = '';
$brand_id_filter = '';
$product_id_filter = '';
$features_filter = '';
$keyword_filter = '';
$visible_filter = '';
$visible_filter = '';
$is_featured_filter = '';
$discounted_filter = '';
$in_stock_filter = '';
$group_by = '';
$order = 'p.position DESC';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(empty($filter['nolimit'])) $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
if(!empty($filter['id']))
$product_id_filter = $this->db->placehold('AND p.id in(?@)', (array)$filter['id']);
if(!empty($filter['category_id']))
{
$category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']);
$group_by = "GROUP BY p.id";
}
if(!empty($filter['brand_id']))
$brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']);
if(!empty($filter['featured']))
$is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured']));
if(!empty($filter['discounted']))
$discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted']));
if(!empty($filter['in_stock']))
$in_stock_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock']));
if(!empty($filter['visible']))
$visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible']));
if(!empty($filter['sort']))
switch ($filter['sort'])
{
case 'views':
$order = 'p.views DESC';break;
case 'position':
$order = 'p.position DESC';
break;
case 'name':
$order = 'p.name';
break;
case 'created':
$order = 'p.created DESC';
break;
case 'price':
//$order = 'pv.price IS NULL, pv.price=0, pv.price';
$order = '(SELECT pv.price FROM __variants pv WHERE (pv.stock IS NULL OR pv.stock>0) AND p.id = pv.product_id AND pv.position=(SELECT MIN(position) FROM __variants WHERE (stock>0 OR stock IS NULL) AND product_id=p.id LIMIT 1) LIMIT 1)';
break;
}
if(!empty($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (p.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR p.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
if(!empty($filter['features']) && !empty($filter['features']))
foreach($filter['features'] as $feature=>$value)
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value);
if(!empty($filter['from']))
if(is_array($filter['from']))
foreach($filter['from'] as $feature=>$value)
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value >= ? ) ', $feature, $value);
if(!empty($filter['to']))
if(is_array($filter['to']))
foreach($filter['to'] as $feature=>$value)
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value <= ? ) ', $feature, $value);
$query = "SELECT
p.id,
p.ym,
p.url,
p.brand_id,
p.name,
p.annotation,
p.body,
p.position,
p.created as created,
p.visible,
p.featured,
p.meta_title,
p.meta_keywords,
p.meta_description,
p.views,
p.product_h1,
b.name as brand,
b.url as brand_url
FROM __products p
$category_id_filter
LEFT JOIN __brands b ON p.brand_id = b.id
WHERE
1
$product_id_filter
$brand_id_filter
$features_filter
$keyword_filter
$is_featured_filter
$discounted_filter
$in_stock_filter
$visible_filter
$group_by
ORDER BY $order
$sql_limit";
//echo $query; //die;
$query = $this->db->placehold($query);
$this->db->query($query);
return $this->db->results();
}
/**
* Функция возвращает количество товаров
* Возможные значения фильтра:
* category_id - id категории или их массив
* brand_id - id бренда или их массив
* keyword - ключевое слово для поиска
* features - фильтр по свойствам товара, массив (id свойства => значение свойства)
*/
public function count_products($filter = array())
{
$category_id_filter = '';
$brand_id_filter = '';
$keyword_filter = '';
$visible_filter = '';
$is_featured_filter = '';
$in_stock_filter = '';
$discounted_filter = '';
$features_filter = '';
if(!empty($filter['category_id']))
$category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']);
if(!empty($filter['brand_id']))
$brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']);
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (p.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR p.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
if(!empty($filter['featured']))
$is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured']));
if(!empty($filter['in_stock']))
$in_stock_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock']));
if(!empty($filter['discounted']))
$discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted']));
if(!empty($filter['visible']))
$visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible']));
if(!empty($filter['features']) && !empty($filter['features']))
foreach($filter['features'] as $feature=>$value)
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value);
if(!empty($filter['from']))
if(is_array($filter['from']))
foreach($filter['from'] as $feature=>$value)
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value >= ? ) ', $feature, $value);
if(!empty($filter['to']))
if(is_array($filter['to']))
foreach($filter['to'] as $feature=>$value)
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value <= ? ) ', $feature, $value);
$query = "SELECT count(distinct p.id) as count
FROM __products AS p
$category_id_filter
WHERE 1
$brand_id_filter
$keyword_filter
$is_featured_filter
$in_stock_filter
$discounted_filter
$visible_filter
$features_filter ";
$this->db->query($query);
return $this->db->result('count');
}
/**
* Функция возвращает товар по id
* @param $id
* @retval object
*/
public function get_product($id)
{
if(is_int($id))
$filter = $this->db->placehold('p.id = ?', $id);
else
$filter = $this->db->placehold('p.url = ?', $id);
$query = "SELECT DISTINCT
p.id,
p.url,
p.ym,
p.brand_id,
p.name,
p.annotation,
p.body,
p.position,
p.created as created,
p.visible,
p.featured,
p.meta_title,
p.meta_keywords,
p.meta_description,
p.product_h1,
p.views
FROM __products AS p
LEFT JOIN __brands b ON p.brand_id = b.id
WHERE $filter
GROUP BY p.id
LIMIT 1";
$this->db->query($query);
$product = $this->db->result();
return $product;
}
public function update_product($id, $product)
{
$query = $this->db->placehold("UPDATE __products SET ?% WHERE id in (?@) LIMIT ?", $product, (array)$id, count((array)$id));
if($this->db->query($query))
return $id;
else
return false;
}
public function update_views($id)
{
$this->db->query("UPDATE __products SET views=views+1 WHERE id=?", $id);
return true;
}
public function add_product($product)
{
$product = (array) $product;
if(empty($product['url']))
{
$product['url'] = preg_replace("/[\s]+/ui", '-', $product['name']);
$product['url'] = strtolower(preg_replace("/[^0-9a-zа\-]+/ui", '', $product['url']));
}
// Если есть товар с таким URL, добавляем к нему число
while($this->get_product((string)$product['url']))
{
if(preg_match('/(.+)_([0-9]+)$/', $product['url'], $parts))
$product['url'] = $parts[1].'_'.($parts[2]+1);
else
$product['url'] = $product['url'].'_2';
}
if($this->db->query("INSERT INTO __products SET ?%", $product))
{
$id = $this->db->insert_id();
$this->db->query("UPDATE __products SET position=id WHERE id=?", $id);
return $id;
}
else
return false;
}
/*
*
* Удалить товар
*
*/
public function delete_product($id)
{
if(!empty($id))
{
// Удаляем варианты
$variants = $this->variants->get_variants(array('product_id'=>$id));
foreach($variants as $v)
$this->variants->delete_variant($v->id);
// Удаляем изображения
$images = $this->get_images(array('product_id'=>$id));
foreach($images as $i)
$this->delete_image($i->id);
// Удаляем категории
$categories = $this->categories->get_categories(array('product_id'=>$id));
foreach($categories as $c)
$this->categories->delete_product_category($id, $c->id);
// Удаляем свойства
$options = $this->features->get_options(array('product_id'=>$id));
foreach($options as $o)
$this->features->delete_option($id, $o->feature_id);
// Удаляем связанные товары
$related = $this->get_related_products($id);
foreach($related as $r)
$this->delete_related_product($id, $r->related_id);
// Удаляем отзывы
$comments = $this->comments->get_comments(array('object_id'=>$id, 'type'=>'product'));
foreach($comments as $c)
$this->comments->delete_comment($c->id);
// Удаляем из покупок
$this->db->query('UPDATE __purchases SET product_id=NULL WHERE product_id=?', intval($id));
// Удаляем товар
$query = $this->db->placehold("DELETE FROM __products WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
return true;
}
return false;
}
public function duplicate_product($id)
{
$product = $this->get_product($id);
$product->id = null;
$product->created = null;
// Сдвигаем товары вперед и вставляем копию на соседнюю позицию
$this->db->query('UPDATE __products SET position=position+1 WHERE position>?', $product->position);
$new_id = $this->products->add_product($product);
$this->db->query('UPDATE __products SET position=? WHERE id=?', $product->position+1, $new_id);
// Очищаем url
$this->db->query('UPDATE __products SET url="" WHERE id=?', $new_id);
// Дублируем категории
$categories = $this->categories->get_product_categories($id);
foreach($categories as $c)
$this->categories->add_product_category($new_id, $c->category_id);
// Дублируем изображения
$images = $this->get_images(array('product_id'=>$id));
foreach($images as $image)
$this->add_image($new_id, $image->filename);
// Дублируем варианты
$variants = $this->variants->get_variants(array('product_id'=>$id));
foreach($variants as $variant)
{
$variant->product_id = $new_id;
unset($variant->id);
if($variant->infinity)
$variant->stock = null;
unset($variant->infinity);
$this->variants->add_variant($variant);
}
// Дублируем свойства
$options = $this->features->get_options(array('product_id'=>$id));
foreach($options as $o)
$this->features->update_option($new_id, $o->feature_id, $o->value);
// Дублируем связанные товары
$related = $this->get_related_products($id);
foreach($related as $r)
$this->add_related_product($new_id, $r->related_id);
// Дублируем связанные товары
$videos = $this->get_videos($id);
foreach($videos as $r)
$this->add_video($new_id, $videos->value);
return $new_id;
}
function get_related_products($product_id = array())
{
if(empty($product_id))
return array();
$product_id_filter = $this->db->placehold('AND product_id in(?@)', (array)$product_id);
$query = $this->db->placehold("SELECT product_id, related_id, position
FROM __related_products
WHERE
1
$product_id_filter
ORDER BY position
");
$this->db->query($query);
return $this->db->results();
}
// Функция возвращает связанные товары
public function add_related_product($product_id, $related_id, $position=0)
{
$query = $this->db->placehold("INSERT IGNORE INTO __related_products SET product_id=?, related_id=?, position=?", $product_id, $related_id, $position);
$this->db->query($query);
return $related_id;
}
// Удаление связанного товара
public function delete_related_product($product_id, $related_id)
{
$query = $this->db->placehold("DELETE FROM __related_products WHERE product_id=? AND related_id=? LIMIT 1", intval($product_id), intval($related_id));
$this->db->query($query);
}
function get_videos($product_id = array())
{
if(empty($product_id))
return array();
$product_id_filter = $this->db->placehold('AND product_id in(?@)', (array)$product_id);
$query = $this->db->placehold("SELECT product_id, value, position
FROM __videos
WHERE
1
$product_id_filter
ORDER BY position
");
$this->db->query($query);
return $this->db->results();
}
// Функция возвращает связанные товары
public function add_video($product_id, $value, $position=0)
{
$query = $this->db->placehold("INSERT IGNORE INTO __videos SET product_id=?, value=?, position=?", $product_id, $value, $position);
$this->db->query($query);
return $this->db->insert_id();
}
// Удаление связанного товара
public function delete_video($product_id)
{
$query = $this->db->placehold("DELETE FROM __related_products WHERE id=? LIMIT 1", intval($product_id));
$this->db->query($query);
}
function get_images($filter = array())
{
$product_id_filter = '';
$group_by = '';
if(!empty($filter['product_id']))
$product_id_filter = $this->db->placehold('AND i.product_id in(?@)', (array)$filter['product_id']);
// images
$query = $this->db->placehold("SELECT i.id, i.product_id, i.name, i.filename, i.position
FROM __images AS i WHERE 1 $product_id_filter $group_by ORDER BY i.product_id, i.position");
$this->db->query($query);
return $this->db->results();
}
public function add_image($product_id, $filename, $name = '')
{
$query = $this->db->placehold("SELECT id FROM __images WHERE product_id=? AND filename=?", $product_id, $filename);
$this->db->query($query);
$id = $this->db->result('id');
if(empty($id))
{
$query = $this->db->placehold("INSERT INTO __images SET product_id=?, filename=?", $product_id, $filename);
$this->db->query($query);
$id = $this->db->insert_id();
$query = $this->db->placehold("UPDATE __images SET position=id WHERE id=?", $id);
$this->db->query($query);
}
return($id);
}
public function update_image($id, $image)
{
$query = $this->db->placehold("UPDATE __images SET ?% WHERE id=?", $image, $id);
$this->db->query($query);
return($id);
}
public function delete_image($id)
{
$query = $this->db->placehold("SELECT filename FROM __images WHERE id=?", $id);
$this->db->query($query);
$filename = $this->db->result('filename');
$query = $this->db->placehold("DELETE FROM __images WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __images WHERE filename=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
$file = pathinfo($filename, PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
// Удалить все ресайзы
$rezised_images = glob($this->config->root_dir.$this->config->resized_images_dir.$file."*.".$ext);
if(is_array($rezised_images))
foreach (glob($this->config->root_dir.$this->config->resized_images_dir.$file."*.".$ext) as $f)
@unlink($f);
@unlink($this->config->root_dir.$this->config->original_images_dir.$filename);
}
}
/*
*
* Следующий товар
*
*/
public function get_next_product($id)
{
$this->db->query("SELECT position FROM __products WHERE id=? LIMIT 1", $id);
$position = $this->db->result('position');
$this->db->query("SELECT pc.category_id FROM __products_categories pc WHERE product_id=? ORDER BY position LIMIT 1", $id);
$category_id = $this->db->result('category_id');
$query = $this->db->placehold("SELECT id FROM __products p, __products_categories pc
WHERE pc.product_id=p.id AND p.position>?
AND pc.position=(SELECT MIN(pc2.position) FROM __products_categories pc2 WHERE pc.product_id=pc2.product_id)
AND pc.category_id=?
AND p.visible ORDER BY p.position limit 1", $position, $category_id);
$this->db->query($query);
return $this->get_product((integer)$this->db->result('id'));
}
/*
*
* Предыдущий товар
*
*/
public function get_prev_product($id)
{
$this->db->query("SELECT position FROM __products WHERE id=? LIMIT 1", $id);
$position = $this->db->result('position');
$this->db->query("SELECT pc.category_id FROM __products_categories pc WHERE product_id=? ORDER BY position LIMIT 1", $id);
$category_id = $this->db->result('category_id');
$query = $this->db->placehold("SELECT id FROM __products p, __products_categories pc
WHERE pc.product_id=p.id AND p.position<?
AND pc.position=(SELECT MIN(pc2.position) FROM __products_categories pc2 WHERE pc.product_id=pc2.product_id)
AND pc.category_id=?
AND p.visible ORDER BY p.position DESC limit 1", $position, $category_id);
$this->db->query($query);
return $this->get_product((integer)$this->db->result('id')); }
}

318
api/Request.php Normal file
View File

@@ -0,0 +1,318 @@
<?php
/**
* Класс-обертка для обращения к переменным _GET, _POST, _FILES
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Request extends Simpla
{
/**
* Конструктор, чистка слешей
*/
public function __construct()
{
parent::__construct();
$_POST = $this->stripslashes_recursive($_POST);
$_GET = $this->stripslashes_recursive($_GET);
}
/**
* Определение request-метода обращения к странице (GET, POST)
* Если задан аргумент функции (название метода, в любом регистре), возвращает true или false
* Если аргумент не задан, возвращает имя метода
* Пример:
*
* if($simpla->request->method('post'))
* print 'Request method is POST';
*
*/
public function method($method = null)
{
if(!empty($method))
return strtolower($_SERVER['REQUEST_METHOD']) == strtolower($method);
return $_SERVER['REQUEST_METHOD'];
}
/**
* Возвращает переменную _GET, отфильтрованную по заданному типу, если во втором параметре указан тип фильтра
* Второй параметр $type может иметь такие значения: integer, string, boolean
* Если $type не задан, возвращает переменную в чистом виде
*/
public function get($name, $type = null)
{
$val = null;
if(isset($_GET[$name]))
$val = $_GET[$name];
if(!empty($type) && is_array($val))
$val = reset($val);
if($type == 'string'){
$val = str_replace('/', '', $val);
return strval(preg_replace('/[^\p{L}\p{Nd}\d\s_\-\.\%\S]/ui', '', $val));
//return strval(preg_replace('/[^\p{L}\p{Nd}\d\s_\-\.\%\s]/ui', '', $val));
}
if($type == 'integer')
return intval($val);
if($type == 'boolean')
return !empty($val);
return $val;
}
/**
* Возвращает переменную _POST, отфильтрованную по заданному типу, если во втором параметре указан тип фильтра
* Второй параметр $type может иметь такие значения: integer, string, boolean
* Если $type не задан, возвращает переменную в чистом виде
*/
public function post($name = null, $type = null)
{
$val = null;
if(!empty($name) && isset($_POST[$name]))
$val = $_POST[$name];
elseif(empty($name))
$val = file_get_contents('php://input');
if($type == 'string')
return strval(preg_replace('/[^\p{L}\p{Nd}\d\s_\-\.\%\s]/ui', '', $val));
if($type == 'integer')
return intval($val);
if($type == 'boolean')
return !empty($val);
return $val;
}
/**
* Возвращает переменную _FILES
* Обычно переменные _FILES являются двухмерными массивами, поэтому можно указать второй параметр,
* например, чтобы получить имя загруженного файла: $filename = $simpla->request->files('myfile', 'name');
*/
public function files($name, $name2 = null)
{
if(!empty($name2) && !empty($_FILES[$name][$name2]))
return $_FILES[$name][$name2];
elseif(empty($name2) && !empty($_FILES[$name]))
return $_FILES[$name];
else
return null;
}
/**
* Рекурсивная чистка магических слешей
*/
private function stripslashes_recursive($var)
{
if(get_magic_quotes_gpc())
{
$res = null;
if(is_array($var))
foreach($var as $k=>$v)
$res[stripcslashes($k)] = $this->stripslashes_recursive($v);
else
$res = stripcslashes($var);
}
else
{
$res = $var;
}
return $res;
}
/**
* Проверка сессии
*/
public function check_session()
{
if(!empty($_POST))
{
if(empty($_POST['session_id']) || $_POST['session_id'] != session_id())
{
unset($_POST);
return false;
}
}
return true;
}
/**
* URL
*/
public function url($params = array())
{
$url = parse_url($_SERVER["REQUEST_URI"]);
parse_str($url['query'], $query);
if(0 && get_magic_quotes_gpc())
foreach($query as &$v)
{
if(!is_array($v))
$v = stripslashes(urldecode($v));
}
foreach($params as $name=>$value)
$query[$name] = $value;
$query_is_empty = true;
foreach($query as $name=>$value)
if($value!='' && $value!=null)
$query_is_empty = false;
if(!$query_is_empty)
$url['query'] = http_build_query($query);
else
$url['query'] = null;
$result = http_build_url(null, $url);
return $result;
}
}
if (!function_exists('http_build_url'))
{
define('HTTP_URL_REPLACE', 1); // Replace every part of the first URL when there's one of the second URL
define('HTTP_URL_JOIN_PATH', 2); // Join relative paths
define('HTTP_URL_JOIN_QUERY', 4); // Join query strings
define('HTTP_URL_STRIP_USER', 8); // Strip any user authentication information
define('HTTP_URL_STRIP_PASS', 16); // Strip any password authentication information
define('HTTP_URL_STRIP_AUTH', 32); // Strip any authentication information
define('HTTP_URL_STRIP_PORT', 64); // Strip explicit port numbers
define('HTTP_URL_STRIP_PATH', 128); // Strip complete path
define('HTTP_URL_STRIP_QUERY', 256); // Strip query string
define('HTTP_URL_STRIP_FRAGMENT', 512); // Strip any fragments (#identifier)
define('HTTP_URL_STRIP_ALL', 1024); // Strip anything but scheme and host
// Build an URL
// The parts of the second URL will be merged into the first according to the flags argument.
//
// @param mixed (Part(s) of) an URL in form of a string or associative array like parse_url() returns
// @param mixed Same as the first argument
// @param int A bitmask of binary or'ed HTTP_URL constants (Optional)HTTP_URL_REPLACE is the default
// @param array If set, it will be filled with the parts of the composed url like parse_url() would return
function http_build_url($url, $parts=array(), $flags=HTTP_URL_REPLACE, &$new_url=false)
{
$keys = array('user','pass','port','path','query','fragment');
// HTTP_URL_STRIP_ALL becomes all the HTTP_URL_STRIP_Xs
if ($flags & HTTP_URL_STRIP_ALL)
{
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
$flags |= HTTP_URL_STRIP_PORT;
$flags |= HTTP_URL_STRIP_PATH;
$flags |= HTTP_URL_STRIP_QUERY;
$flags |= HTTP_URL_STRIP_FRAGMENT;
}
// HTTP_URL_STRIP_AUTH becomes HTTP_URL_STRIP_USER and HTTP_URL_STRIP_PASS
else if ($flags & HTTP_URL_STRIP_AUTH)
{
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
}
// Parse the original URL
$parse_url = parse_url($url);
// Scheme and Host are always replaced
if (isset($parts['scheme']))
$parse_url['scheme'] = $parts['scheme'];
if (isset($parts['host']))
$parse_url['host'] = $parts['host'];
// (If applicable) Replace the original URL with it's new parts
if ($flags & HTTP_URL_REPLACE)
{
foreach ($keys as $key)
{
if (isset($parts[$key]))
$parse_url[$key] = $parts[$key];
}
}
else
{
// Join the original URL path with the new path
if (isset($parts['path']) && ($flags & HTTP_URL_JOIN_PATH))
{
if (isset($parse_url['path']))
$parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '', $parse_url['path']), '/') . '/' . ltrim($parts['path'], '/');
else
$parse_url['path'] = $parts['path'];
}
// Join the original query string with the new query string
if (isset($parts['query']) && ($flags & HTTP_URL_JOIN_QUERY))
{
if (isset($parse_url['query']))
$parse_url['query'] .= '&' . $parts['query'];
else
$parse_url['query'] = $parts['query'];
}
}
// Strips all the applicable sections of the URL
// Note: Scheme and Host are never stripped
foreach ($keys as $key)
{
if ($flags & (int)constant('HTTP_URL_STRIP_' . strtoupper($key)))
unset($parse_url[$key]);
}
$new_url = $parse_url;
return
((isset($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '')
.((isset($parse_url['user'])) ? $parse_url['user'] . ((isset($parse_url['pass'])) ? ':' . $parse_url['pass'] : '') .'@' : '')
.((isset($parse_url['host'])) ? $parse_url['host'] : '')
.((isset($parse_url['port'])) ? ':' . $parse_url['port'] : '')
.((isset($parse_url['path'])) ? $parse_url['path'] : '')
.((isset($parse_url['query'])) ? '?' . $parse_url['query'] : '')
.((isset($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '')
;
}
}
if(!function_exists('http_build_query')) {
function http_build_query($data,$prefix=null,$sep='',$key='') {
$ret = array();
foreach((array)$data as $k => $v) {
$k = urlencode($k);
if(is_int($k) && $prefix != null) {
$k = $prefix.$k;
};
if(!empty($key)) {
$k = $key."[".$k."]";
};
if(is_array($v) || is_object($v)) {
array_push($ret,http_build_query($v,"",$sep,$k));
}
else {
array_push($ret,$k."=".urlencode($v));
};
};
if(empty($sep)) {
$sep = ini_get("arg_separator.output");
};
return implode($sep, $ret);
};
};

707
api/Services.php Normal file
View File

@@ -0,0 +1,707 @@
<?php
require_once('Simpla.php');
class Services extends Simpla
{
public $menu_id = 3;
public $root_id = 28;
public $services_brands = array(
//1 => array('id' => 1, 'name' => 'Alfa Romeo','url' => 'alfa-romeo', 'image' => ''),
2 => array('id' => 2, 'name' => 'Audi', 'url' => 'audi', 'image' => 'audi.png'),
3 => array('id' => 3, 'name' => 'Bentley', 'url' => 'bentley', 'image' => 'bentley.png'),
4 => array('id' => 4, 'name' => 'BMW', 'url' => 'bmw', 'image' => 'bmw.png'),
5 => array('id' => 5, 'name' => 'Cadillac', 'url' => 'cadillac', 'image' => 'cadillac.png'),
55 => array('id' => 55, 'name' => 'Changan', 'url' => 'changan', 'image' => 'changan.png'),
6 => array('id' => 6, 'name' => 'Chery','url' => 'chery', 'image' => 'chery.png'),
7 => array('id' => 7, 'name' => 'Chevrolet', 'url' => 'chevrolet', 'image' => 'chevrolet.png'),
8 => array('id' => 8, 'name' => 'Chrysler', 'url' => 'chrysler', 'image' => 'chrysler.png'),
9 => array('id' => 9, 'name' => 'Citroen', 'url' => 'citroen', 'image' => 'citroen.png'),
//10 => array('id' => 10, 'name' => 'Daewoo','url' => 'daewoo', 'image' => ''),
11 => array('id' => 11, 'name' => 'Dodge', 'url' => 'dodge', 'image' => 'dodge.png'),
56 => array('id' => 56, 'name' => 'Dongfeng', 'url' => 'Dongfeng', 'image' => 'dongfeng.png'),
54 => array('id' => 54, 'name' => 'Exeed', 'url' => 'exeed', 'image' => 'exeed.png'),
12 => array('id' => 12, 'name' => 'Ferrari', 'url' => 'ferrari', 'image' => 'ferrari.png'),
13 => array('id' => 13, 'name' => 'Fiat', 'url' => 'fiat', 'image' => 'fiat.png'),
53 => array('id' => 53, 'name' => 'Ford', 'url' => 'ford', 'image' => 'ford.png'),
57 => array('id' => 57, 'name' => 'GAC', 'url' => 'gac', 'image' => 'gac.png'),
14 => array('id' => 14, 'name' => 'Geely', 'url' => 'geely', 'image' => 'geely.png'),
//15 => array('id' => 15, 'name' => 'GMC','url' => 'gmc', 'image' => ''),
16 => array('id' => 16, 'name' => 'Great Wall','url' => 'great-wall', 'image' => 'great-wall.png'),
17 => array('id' => 17, 'name' => 'Haval', 'url' => 'haval', 'image' => 'haval.png'),
18 => array('id' => 18, 'name' => 'Honda', 'url' => 'honda', 'image' => 'honda.png'),
19 => array('id' => 19, 'name' => 'Hummer', 'url' => 'hummer', 'image' => 'hummer.png'),
20 => array('id' => 20, 'name' => 'Hyundai', 'url' => 'hyundai', 'image' => 'hyundai.png'),
58 => array('id' => 58, 'name' => 'Haima', 'url' => 'haima', 'image' => 'haima.png'),
21 => array('id' => 21, 'name' => 'Infiniti', 'url' => 'infiniti', 'image' => 'infiniti.png'),
22 => array('id' => 22, 'name' => 'Jaguar', 'url' => 'jaguar', 'image' => 'jaguar.png'),
59 => array('id' => 59, 'name' => 'JAC', 'url' => 'jac', 'image' => 'jac.png'),
60 => array('id' => 60, 'name' => 'Jaecoo', 'url' => 'jaecoo', 'image' => 'jaecoo.png'),
61 => array('id' => 61, 'name' => 'Jetour', 'url' => 'jetour', 'image' => 'jetour.png'),
62 => array('id' => 62, 'name' => 'Jetta', 'url' => 'jetta', 'image' => 'jetta.png'),
23 => array('id' => 23, 'name' => 'Jeep', 'url' => 'jeep', 'image' => 'jeep.png'),
63 => array('id' => 63, 'name' => 'JMC', 'url' => 'jmc', 'image' => 'jmc.png'),
64 => array('id' => 64, 'name' => 'Kaiyi', 'url' => 'kaiyi', 'image' => 'kaiyi.png'),
24 => array('id' => 24, 'name' => 'Kia', 'url' => 'kia', 'image' => 'kia.png'),
25 => array('id' => 25, 'name' => 'Land Rover', 'url' => 'land-rover', 'image' => 'land-rover.png'),
26 => array('id' => 26, 'name' => 'Lexus', 'url' => 'lexus', 'image' => 'lexus.png'),
27 => array('id' => 27, 'name' => 'LiXiang','url' => 'lixiang', 'image' => 'LiXiang.png'),
65 => array('id' => 65, 'name' => 'Livan', 'url' => 'livan', 'image' => 'livan.png'),
28 => array('id' => 28, 'name' => 'Mazda', 'url' => 'mazda', 'image' => 'mazda.png'),
29 => array('id' => 29, 'name' => 'Mercedes-Benz', 'url' => 'mercedes-benz', 'image' => 'mercedes-benz.png'),
30 => array('id' => 30, 'name' => 'Mini', 'url' => 'mini', 'image' => 'mini.png'),
31 => array('id' => 31, 'name' => 'Mitsubishi', 'url' => 'mitsubishi', 'image' => 'mitsubishi.png'),
32 => array('id' => 32, 'name' => 'Nissan', 'url' => 'nissan', 'image' => 'nissan.png'),
66 => array('id' => 66, 'name' => 'OMODA', 'url' => 'omoda', 'image' => 'omoda.png'),
33 => array('id' => 33, 'name' => 'Opel', 'url' => 'opel', 'image' => 'opel.png'),
34 => array('id' => 34, 'name' => 'Peugeot', 'url' => 'peugeot', 'image' => 'peugeot.png'),
35 => array('id' => 35, 'name' => 'Porsche', 'url' => 'porsche', 'image' => 'porsche.png'),
36 => array('id' => 36, 'name' => 'Renault', 'url' => 'renault', 'image' => 'renault.png'),
//37 => array('id' => 37, 'name' => 'Saab','url' => 'saab', 'image' => 'saab.png'),
38 => array('id' => 38, 'name' => 'Scania', 'url' => 'scania', 'image' => 'scania.png'),
//39 => array('id' => 39, 'name' => 'Seat','url' => 'seat', 'image' => ''),
40 => array('id' => 40, 'name' => 'Skoda', 'url' => 'skoda', 'image' => 'skoda.png'),
41 => array('id' => 41, 'name' => 'Smart', 'url' => 'smart', 'image' => 'smart.png'),
//42 => array('id' => 42, 'name' => 'SsangYong','url' => 'ssangyong', 'image' => 'ssangyong.png'),
43 => array('id' => 43, 'name' => 'Subaru', 'url' => 'subaru', 'image' => 'subaru.png'),
44 => array('id' => 44, 'name' => 'Suzuki', 'url' => 'suzuki', 'image' => 'suzuki.png'),
67 => array('id' => 67, 'name' => 'Tank', 'url' => 'tank', 'image' => 'tank.png'),
45 => array('id' => 45, 'name' => 'Tesla', 'url' => 'tesla', 'image' => 'tesla.png'),
46 => array('id' => 46, 'name' => 'Toyota', 'url' => 'toyota', 'image' => 'toyota.png'),
47 => array('id' => 47, 'name' => 'Volkswagen', 'url' => 'volkswagen', 'image' => 'volkswagen.png'),
48 => array('id' => 48, 'name' => 'Volvo', 'url' => 'volvo', 'image' => 'volvo.png'),
68 => array('id' => 68, 'name' => 'VOYAH', 'url' => 'voyah', 'image' => 'voyah.png'),
49 => array('id' => 49, 'name' => 'Zeekr','url' => 'zeekr', 'image' => 'Zeekr.png'),
50 => array('id' => 50, 'name' => 'ГАЗ', 'url' => 'gaz', 'image' => 'gaz.png'),
51 => array('id' => 51, 'name' => 'Лада (ВАЗ)', 'url' => 'lada-vaz', 'image' => 'lada-vaz.png'),
52 => array('id' => 52, 'name' => 'Мототехника', 'url' => 'mototehnika', 'image' => 'moto.png'),
//53 => array('id' => 53, 'name' => 'УАЗ','url' => 'uaz', 'image' => ''),
);
private $_root_url = 'tuning-centr/';
private $_tree;
/**
* @var array
*/
private $_services;
public function count($filters)
{
$filter = $this->_prepare_filters($filters);
$this->db->query("SELECT COUNT(DISTINCT p.id) as count FROM __pages p" .
$filter->where);
return (int)$this->db->result('count');
}
public function all($filters)
{
$filter = $this->_prepare_filters($filters);
$this->db->query(
"SELECT *" .
" FROM __pages p" .
$filter->where .
$filter->order .
$filter->limit
);
return $this->db->results();
}
/**
* Возвращает данные страницы услуг по её id или url
*
* @param string|int $id ID или url страницы данные которой необходимо получить
* @return object
*/
public function get($id)
{
if (empty($id)) {
//главная страница услуг
$id = $this->root_id;
$conditions = '1';
} else {
$conditions = 'menu_id=' . $this->menu_id;
}
if (is_string($id)) {
$conditions .= $this->db->placehold(' AND url=?', $id);
} else {
$conditions .= $this->db->placehold(' AND id=?', intval($id));
}
$query = "SELECT * FROM __pages WHERE $conditions LIMIT 1";
$this->db->query($query);
return $this->db->result();
}
public function get_root_url() {
return $this->_root_url;
}
/**
* Возвращает краткие данные "брендовых" страниц услуги
* @param int $id ID услуги
* @param array $filter Фильтры получаемых данных, в виде колонка=>значение
* @return array
*/
public function get_brands_pages($id, $filter = array())
{
$this->_build_tree();
if (!isset($this->_services[$id]))
return array();
$conditions = $this->db->placehold('parent=? AND brand_id>0', intval($id));
foreach ($filter as $col => $val) {
$conditions .= $this->db->placehold(" AND $col=?", $val);
}
$this->db->query("SELECT `id`, `brand_id`, `url`, `parent`, `visible`, `name` FROM __pages WHERE $conditions ORDER BY `position`");
return $this->db->results();
}
/**
* Возвращает данные всех предков услуги.
* Url каждой услуги включает корень.
* @param int $id ID услуги
* @return array
*/
public function get_path_to($id)
{
$this->_build_tree();
$results = array();
if(array_key_exists($id, $this->_services)) {
$breadcrumbs = $this->_services[$id]->path;
foreach ($breadcrumbs as $breadcrumb) {
$results[] = (object)array(
'id' => $breadcrumb->id,
'parent' => $breadcrumb->parent,
'name' => $breadcrumb->name,
'url' => intval($breadcrumb->id) !== $this->root_id ? $this->_root_url . $breadcrumb->url : trim($this->_root_url, '/'),
);
}
}
return $results;
}
public function get_all_brands()
{
$results = array();
foreach ($this->services_brands as $brand) {
$results[] = (object)$brand;
}
return $results;
}
/**
* Возвращает дерево всех страниц услуг
* @return array
*/
public function get_tree()
{
$this->_build_tree();
return $this->_tree;
}
public function get_all_services()
{
$this->_build_tree();
return $this->_services;
}
/**
* Возвращает услуги привязанные к главной странице.
* Форматирование возвращаемых данных зависит от параметра $with_roots.
* @param $visible_only
* @param bool $with_roots Флаг определяющий будут ли услуги возвращены как дети их корневых услуг или просто списком
* @return array
*/
public function get_home_services($visible_only = false, $with_roots = false)
{
$results = array();
$items = $this->services->all(array('show_home' => 1, 'visible' => 1));
foreach ($items as $item) {
if ($visible_only && !$this->is_visible($item->id))
continue;
if ($with_roots) {
$root = $this->_services[$item->id]->path[1];
if (!isset($results[$root->id])) {
$results[$root->id] = $this->get(intval($root->id));
$results[$root->id]->children = array();
}
if(!array_key_exists($item->id, $results))
$results[$root->id]->children[] = $item;
} else
$results[] = $item;
}
return $results;
}
/**
* Возвращает услуги главной страницы услуг (отмеченные как "в услугах").
* Форматирование возвращаемых данных зависит от параметра $with_roots.
* @param $visible_only
* @param bool $with_roots Флаг определяющий будут ли услуги возвращены как дети их корневых услуг или просто списком
* @return array
*/
public function get_main_services($visible_only = false, $with_roots = false)
{
$results = array();
$items = $this->services->all(array('show_service' => 1, 'visible' => 1));
foreach ($items as $item) {
if ($visible_only && !$this->is_visible($item->id))
continue;
if ($with_roots) {
$root = $this->_services[$item->id]->path[1];
if (!isset($results[$root->id])) {
$results[$root->id] = $this->get(intval($root->id));
$results[$root->id]->children = array();
}
if(!array_key_exists($item->id, $results))
$results[$root->id]->children[] = $item;
} else
$results[] = $item;
}
return $results;
}
public function get_brand($brand_id)
{
if (array_key_exists($brand_id, $this->services_brands))
return (object)$this->services_brands[$brand_id];
return false;
}
/**
* Возвращает данные брендов привязанных к странице услуги
* @param int $id ID услуги
* @return array
*/
public function get_service_brands($id)
{
$conditions = $this->db->placehold('p.parent=? AND p.brand_id>0', intval($id));
$this->db->query("SELECT * FROM __pages p WHERE $conditions ");
$results = array();
foreach ($this->db->results() as $page) {
if (array_key_exists($page->brand_id, $this->services_brands)) {
$brand = (object)$this->services_brands[$page->brand_id];
$brand->page_id = $page->id;
$brand->page_url = $page->url;
$brand->page_visible = $page->visible;
$results[] = $brand;
}
}
return $results;
}
/**
* Создаёт новые или удаляет существующие "брендовые" страницы услуги.
* К услуге будут привязаны только бренды ID которых перечислены в $brands.
* Если массив $brands не содержит элементов, то будут удалены все "брендовые" страницы услуги.
* @param int $id ID страницы услуги
* @param array $brands ID брендов, для которых должны быть сгенерированы страницы.
* @return void
*/
public function create_brands_pages($id, $brands)
{
$delete_conditions = $this->db->placehold('menu_id=? AND parent=? AND brand_id>0', $this->menu_id, intval($id));
if (is_array($brands) && !empty($brands)) {
$ids = array();
foreach ($brands as $brand_id) {
$ids[] = intval($brand_id);
$this->create_brand_page($id, intval($brand_id));
}
$delete_conditions .= $this->db->placehold(' AND brand_id NOT IN (?@)', $ids);
}
//Удаляем все брендовые страницы, которые не были перечислены в $brands
$this->db->query("DELETE FROM __pages WHERE $delete_conditions");
}
public function create_brand_page($id, $brand_id)
{
// страница услуги
if (!($page = $this->services->get(intval($id))))
return;
//проверяем существует ли "брендовая" страница услуги
$conditions = $this->db->placehold('parent=? AND brand_id=?', intval($id), intval($brand_id));
if ($this->count(array('where' => $conditions)) === 0) {// страницы не существует
if (array_key_exists($brand_id, $this->services_brands)) {
$brand = (object)$this->services_brands[$brand_id];
$service = array(
'parent' => $id,
'brand_id' => $brand_id,
'menu_id' => $this->menu_id,
'url' => $page->url . '/' . $brand->url,
'name' => $brand->name,
'header' => $page->name . ' ' . $brand->name,
'meta_title' => $page->name . ' ' . $brand->name . ' в Санкт-Петербурге | Тюнинг центр'
);
$this->pages->add_page($service);
}
}
}
public function update($id, $service)
{
$old_service = $this->get(intval($id));
$query = $this->db->placehold("UPDATE __pages SET ?% WHERE id=? LIMIT 1", $service, intval($id));
$this->db->query($query);
$service = (object)$service;
//был изменён родитель или позиция
if((isset($service->parent) && intval($old_service->parent) !== intval($service->parent))
|| (isset($service->position)) && intval($old_service->position) !== intval($service->position))
$this->fix_positions();
//была изменен статус видимости
if(isset($service->visible) && intval($old_service->visible) !== intval($service->visible))
$this->set_visible($id, $service->visible);
return $id;
}
/**
* Удаляет все услуги с указанными id, а также всех их потомков
* @param $ids
* @param bool $recursive Разрешено ли удалять узлы имеющие детей (по умолчанию - запрещено)
* @return void
*/
public function delete($ids, $recursive = false)
{
$ids = (array)$ids;
foreach ($ids as $id) {
$service = $this->get(intval($id));
if (!empty($service)) {
// получаем ID детей
$this->db->query('SELECT id FROM __pages WHERE parent=' . $service->id);
$children = $this->db->results('id');
$has_children = count($children) > 0;
// если есть дети и удаление не рекурсивное - пропускаем узел
if (!$recursive && $has_children)
continue;
if ($has_children) {
// рекурсивно удаляем потомков
$this->delete($children, $recursive);
} else {
// узел без детей - удаляем
$this->_delete_internal(intval($id));
$this->_unset_tree();
}
}
}
}
public function move($id, $options)
{
$this->_build_tree();
$id = intval($id);
$new_parent = intval($options['parent']);
$relative_position = intval($options['position']);
if (isset($id, $this->_services) && isset($id, $this->_services[$new_parent])) {
$service = $this->_services[$id];
// новый родитель
$parent = $this->_services[$new_parent];
// нод место которого должен занять перемещаемый
if (isset($parent->children[$relative_position])) {
$target_node = $parent->children[$relative_position];
$insert_position = intval($target_node->position);
} else {
// добавление в самую нижнюю позицию
$target_node = null;
$insert_position = $parent->position + (isset($parent->descendants) ? count($parent->descendants) : 1);
}
if (intval($service->parent) !== $new_parent) {
// у нода будет другой родитель
$conditions = $this->db->placehold('parent=?, position=? WHERE id=?', $new_parent, $insert_position, intval($service->id));
$this->db->query('UPDATE __pages SET ' . $conditions);
if ($target_node)
$this->db->query('UPDATE __pages SET position=' . $insert_position + 1 . ' WHERE id=' . intval($target_node->id));
} else {
// родитель не меняется
$i = 0;
foreach ($parent->children as $node) {
//$this->db->query('UPDATE __pages SET position=position+? WHERE id=?');
if ($node->id !== $service->id) {
$i = ($i === $relative_position) ? $relative_position + 1 : $i;
$this->db->query('UPDATE __pages SET position=? WHERE id=?', $i, intval($node->id));
++$i;
} else {
$this->db->query('UPDATE __pages SET position=? WHERE id=?', $relative_position, intval($node->id));
}
}
}
$this->fix_positions();
$this->_unset_tree();
return true;
}
return false;
}
/**
* Возвращает реальный статус видимости услуги, в зависимости от статуса её родителей
* @param $id
* @return bool
*/
public function is_visible($id)
{
$this->_build_tree();
if (!array_key_exists($id, $this->_services) || !$this->_services[$id]->visible)
return false;
foreach ($this->_services[intval($id)]->path as $serv) {
if (!$serv->visible)
return false;
}
return true;
}
/**
* Есть ли дети у указанной услуги
* @param int $id
* @return bool
*/
public function has_children($id)
{
$this->_build_tree();
return array_key_exists($id, $this->_services) && !empty($this->_services[$id]->children);
}
/**
* Включает и отключает услугу
* @param $id
* @param $status
* @return void
*/
public function set_visible($id, $status) {
$this->_build_tree();
$visible = intval(boolval($status));
$service = $this->get(intval($id));
if($service) {
$query = 'UPDATE __pages SET visible=' . $visible . ' WHERE id=';
//если услуга не брендовая, включаем/отключаем всех её родителей/потомков
if(!$service->brand_id) {
$target_id = intval($service->id);
if ($visible) { //включение услуги
foreach ($this->_services[$target_id]->path as $serv)
$this->db->query($query . $serv->id);
} else { //отключение услуги
foreach ($this->_services[$target_id]->descendants as $s_id)
$this->db->query($query . $s_id);
}
} else { //брендовая услуга
$target_id = intval($service->parent);
if ($visible) { //включение предков родителя
foreach ($this->_services[$target_id]->path as $serv)
$this->db->query($query . $serv->id);
//включение самого родителя
$this->db->query($query . $target_id);
}
}
// обновляем статус самой услуги
$this->db->query( $query . $service->id);
}
$this->_unset_tree();
}
public function fix_positions($tree = null, &$pos = 0, $level=1)
{
if ($tree === null) {
$this->_unset_tree();
$tree = $this->_build_tree();
$pos = 0;
$level = 1;
}
foreach ($tree as $node) {
$this->db->query('UPDATE __pages SET level='. $level .', position=' . ++$pos . ' WHERE id=' . intval($node->id));
if ($node->children) {
$this->fix_positions($node->children, $pos, $level+1);
}
}
}
private function _delete_internal($id)
{
//удаляем связанные объекты
$this->db->query('DELETE FROM __pages_objects WHERE page_id=' . $id);
//удаляем саму страницу
$this->db->query('DELETE FROM __pages WHERE id=' . $id);
}
private function _build_tree()
{
if (!is_null($this->_tree))
return $this->_tree;
$this->db->query(
"SELECT p.id, p.parent, p.brand_id, p.name, p.url, p.visible, p.position" .
" FROM __pages p" .
" WHERE (menu_id=" . $this->menu_id . " OR p.id=" . $this->root_id . ") AND p.brand_id=0" .
" ORDER BY p.parent, p.position"
);
$services = $this->db->results();
if (empty($services)) {
return array();
}
// Дерево категорий
$tree = $services[0];
unset($services[0]);
$tree->children = array();
$pointers = array();
$pointers[$this->root_id] = &$tree;
$pointers[$this->root_id]->path = array($tree);
$finish = false;
// строим дерево
while (!empty($services) && !$finish) {
$flag = false;
foreach ($services as $k => $service) {
if (isset($pointers[$service->parent])) {
$pointers[$service->parent]->children[] = ($pointers[$service->id] = $service);
$curr = $pointers[$service->id];
$pointers[$service->id]->path = array_merge((array)$pointers[$service->parent]->path, array($curr));
unset($services[$k]);
$flag = true;
}
}
if (!$flag) $finish = true;
}
// добавляем ID всех потомков к нодам
$ids = array_reverse(array_keys($pointers));
foreach ($ids as $id) {
if ($id != $this->root_id) {
$pointers[$id]->descendants[] = $id;
if (isset($pointers[$pointers[$id]->parent]->descendants))
$pointers[$pointers[$id]->parent]->descendants = array_merge($pointers[$id]->descendants, $pointers[$pointers[$id]->parent]->descendants);
else
$pointers[$pointers[$id]->parent]->descendants = $pointers[$id]->descendants;
}
}
unset($ids);
// получаем полный url к каждой странице попутно подчищая лишние ID и устанавливая реальный статус видимости элемента
foreach ($pointers as $service) {
if (!isset($service->children))
unset($service->descendants);
/*
$current_url = $service->url;
foreach ($service->path as $serv) {
if (substr($serv->url, -1) !== '/') {
$current_url .= $serv->url . '/';
} else {
$current_url = $serv->url;
}
}
$service->url = $current_url;*/
}
$this->_tree = $tree->children;
$this->_services = $pointers;
return $this->_tree;
}
private function _unset_tree()
{
unset($this->_tree);
unset($this->_services);
}
private function _prepare_filters($filter)
{
$filters = new stdClass();
$where = 'menu_id=' . $this->menu_id;
if (array_key_exists('where', $filter)) {
$where = $filter['where'];
} else {
if (array_key_exists('ids', $filter)) {
if (is_array($filter['ids']) && !empty($filter['ids']))
$where .= $this->db->placehold(' AND p.id IN (?@)', $filter['ids']);
else
$where .= $this->db->placehold(' AND p.id IN (NULL)');
}
if (array_key_exists('visible', $filter)) {// активные/архивные контракты
$where .= $this->db->placehold(' AND p.visible=?', intval($filter['visible']));
}
if (array_key_exists('branded', $filter)) {
$where .= ' AND p.brand_id>0';
}
if (array_key_exists('show_service', $filter)) {
$where .= ' AND p.show_service=' . intval($filter['show_service']);
}
if (array_key_exists('show_home', $filter)) {
$where .= ' AND p.show_home=' . intval($filter['show_home']);
}
if (array_key_exists('parent', $filter)) {
$where .= $this->db->placehold(' AND p.parent=?', intval($filter['parent']));
}
if (array_key_exists('brand_id', $filter)) {
$where .= $this->db->placehold(' AND p.brand_id=?', intval($filter['brand_id']));
}
// поисковый запрос
if (isset($filter['keyword'])) {
$keywords = explode(' ', $filter['keyword']);
foreach ($keywords as $keyword) {
$escaped_keyword = $this->db->escape(trim($keyword));
if (!empty($escaped_keyword)) {
$where .= ' AND (p.name LIKE "%' . $escaped_keyword . '%" OR p.header LIKE "%' . $escaped_keyword . '%")';
}
}
}
}
$filters->where = ' WHERE ' . $where;
if (isset($filter['order']) && is_string($filter['order'])) {
$order = $filter['order'];
} else{
// сортировка по-умолчанию
$order = 'level, position';
}
$filters->order = !empty($order) ? ' ORDER BY ' . $order : '';
// навигация
$filters->limit = '';
if (isset($filter['limit'])) {
$limit = max(1, intval($filter['limit']));
if (isset($filter['page'])) {
$page = max(1, intval($filter['page']));
$limit = $this->db->placehold('?, ? ', ($page - 1) * $limit, $limit);
}
$filters->limit = ' LIMIT ' . $limit;
}
return $filters;
}
}

57
api/Settings.php Normal file
View File

@@ -0,0 +1,57 @@
<?php
/**
* Управление настройками магазина, хранящимися в базе данных
* В отличие от класса Config оперирует настройками доступными админу и хранящимися в базе данных.
*
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Settings extends Simpla
{
private $vars = array();
function __construct()
{
parent::__construct();
// Выбираем из базы настройки
$this->db->query('SELECT name, value FROM __settings');
// и записываем их в переменную
foreach($this->db->results() as $result)
if(!($this->vars[$result->name] = @unserialize($result->value)))
$this->vars[$result->name] = $result->value;
}
public function __get($name)
{
if($res = parent::__get($name))
return $res;
if(isset($this->vars[$name]))
return $this->vars[$name];
else
return null;
}
public function __set($name, $value)
{
$this->vars[$name] = $value;
if(is_array($value))
$value = serialize($value);
$this->db->query('SELECT count(*) as count FROM __settings WHERE name=?', $name);
if($this->db->result('count')>0)
$this->db->query('UPDATE __settings SET value=? WHERE name=?', $value, $name);
else
$this->db->query('INSERT INTO __settings SET value=?, name=?', $value, $name);
}
}

246
api/Shares.php Normal file
View File

@@ -0,0 +1,246 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Shares extends Simpla
{
/*
*
* Функция возвращает пост по его id или url
* (в зависимости от типа аргумента, int - id, string - url)
* @param $id id или url поста
*
*/
public function get_post($id)
{
if(is_int($id))
$where = $this->db->placehold(' WHERE b.id=? ', intval($id));
else
$where = $this->db->placehold(' WHERE b.url=? ', $id);
$query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text, b.meta_title,
b.meta_keywords, b.meta_description, b.visible, b.date, b.image
FROM __blog b $where LIMIT 1");
if($this->db->query($query))
return $this->db->result();
else
return false;
}
/*
*
* Функция возвращает массив постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function get_posts($filter = array())
{
// По умолчанию
$limit = 1000;
$page = 1;
$post_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
$posts = array();
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(!empty($filter['id']))
$post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible']));
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
$query = $this->db->placehold("SELECT b.id, b.url, b.name, b.annotation, b.text,
b.meta_title, b.meta_keywords, b.meta_description, b.visible,
b.date, b.image
FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter
ORDER BY date DESC, id DESC $sql_limit");
$this->db->query($query);
return $this->db->results();
}
/*
*
* Функция вычисляет количество постов, удовлетворяющих фильтру
* @param $filter
*
*/
public function count_posts($filter = array())
{
$post_id_filter = '';
$visible_filter = '';
$keyword_filter = '';
if(!empty($filter['id']))
$post_id_filter = $this->db->placehold('AND b.id in(?@)', (array)$filter['id']);
if(isset($filter['visible']))
$visible_filter = $this->db->placehold('AND b.visible = ?', intval($filter['visible']));
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (b.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR b.meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
}
$query = "SELECT COUNT(distinct b.id) as count
FROM __blog b WHERE 1 $post_id_filter $visible_filter $keyword_filter";
if($this->db->query($query))
return $this->db->result('count');
else
return false;
}
/*
*
* Создание поста
* @param $post
*
*/
public function add_post($post)
{
if(isset($post->date))
{
$date = $post->date;
unset($post->date);
$date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format);
}
$query = $this->db->placehold("INSERT INTO __blog SET ?% $date_query", $post);
if(!$this->db->query($query))
return false;
else
return $this->db->insert_id();
}
/*
*
* Обновить пост(ы)
* @param $post
*
*/
public function update_post($id, $post)
{
$query = $this->db->placehold("UPDATE __blog SET ?% WHERE id in(?@) LIMIT ?", $post, (array)$id, count((array)$id));
$this->db->query($query);
return $id;
}
/*
*
* Удалить пост
* @param $id
*
*/
public function delete_post($id)
{
if(!empty($id))
{
$query = $this->db->placehold("DELETE FROM __blog WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
{
$query = $this->db->placehold("DELETE FROM __comments WHERE type='blog' AND object_id=? LIMIT 1", intval($id));
if($this->db->query($query))
return true;
}
}
return false;
}
public function delete_image($id)
{
$query = $this->db->placehold("SELECT image FROM __blog WHERE id=?", intval($id));
$this->db->query($query);
$filename = $this->db->result('image');
if(!empty($filename))
{
$query = $this->db->placehold("UPDATE __blog SET image=NULL WHERE id=?", $id);
$this->db->query($query);
$query = $this->db->placehold("SELECT count(*) as count FROM __blog WHERE image=? LIMIT 1", $filename);
$this->db->query($query);
$count = $this->db->result('count');
if($count == 0)
{
@unlink($this->config->root_dir.$this->config->original_images_dir.$filename);
}
}
}
/*
*
* Следующий пост
* @param $post
*
*/
public function get_next_post($id)
{
$this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __blog WHERE date=? AND id>? AND visible ORDER BY id limit 1)
UNION
(SELECT id FROM __blog WHERE date>? AND visible ORDER BY date, id limit 1)",
$date, $id, $date);
$next_id = $this->db->result('id');
if($next_id)
return $this->get_post(intval($next_id));
else
return false;
}
/*
*
* Предыдущий пост
* @param $post
*
*/
public function get_prev_post($id)
{
$this->db->query("SELECT date FROM __blog WHERE id=? LIMIT 1", $id);
$date = $this->db->result('date');
$this->db->query("(SELECT id FROM __blog WHERE date=? AND id<? AND visible ORDER BY id DESC limit 1)
UNION
(SELECT id FROM __blog WHERE date<? AND visible ORDER BY date DESC, id DESC limit 1)",
$date, $id, $date);
$prev_id = $this->db->result('id');
if($prev_id)
return $this->get_post(intval($prev_id));
else
return false;
}
}

128
api/Simpla.php Normal file
View File

@@ -0,0 +1,128 @@
<?php
/**
* Основной класс Simpla для доступа к API Simpla
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
// include $_SERVER['DOCUMENT_ROOT'].'/api/claviska/SimpleImage.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/lib/Img.php';
class Simpla
{
// Свойства - Классы API
private $classes = array(
//'articles_categories' => 'ArticlesCategories',
'articles' => 'Articles',
//'article' => 'Article',
'banners' => 'Banners',
'config' => 'Config',
'request' => 'Request',
'db' => 'Database',
'settings' => 'Settings',
'design' => 'Design',
'products' => 'Products',
'variants' => 'Variants',
'categories' => 'Categories',
'brands' => 'Brands',
'features' => 'Features',
'money' => 'Money',
'pages' => 'Pages',
'blog' => 'Blog',
'actions' => 'Actions',
'shares' => 'Shares',
'cart' => 'Cart',
'image' => 'Image',
'delivery' => 'Delivery',
'payment' => 'Payment',
'orders' => 'Orders',
'preorders' => 'Preorders',
'users' => 'Users',
'coupons' => 'Coupons',
'comments' => 'Comments',
'feedbacks' => 'Feedbacks',
'notify' => 'Notify',
'managers' => 'Managers',
'callbacks' => 'Callbacks',
'marka' => 'Marka',
'model' => 'Model',
'services' => 'Services',
);
// Созданные объекты
private static $objects = array();
/**
* Конструктор оставим пустым, но определим его на случай обращения parent::__construct() в классах API
*/
public function __construct()
{
//error_reporting(E_ALL & !E_STRICT);
}
/**
* Магический метод, создает нужный объект API
*/
public function __get($name)
{
// Если такой объект уже существует, возвращаем его
if(isset(self::$objects[$name]))
{
return(self::$objects[$name]);
}
// Если запрошенного API не существует - ошибка
if(!array_key_exists($name, $this->classes))
{ //echo($name);
return null;
}
// Определяем имя нужного класса
$class = $this->classes[$name];
// Подключаем его
include_once($_SERVER['DOCUMENT_ROOT'] . '/api/'.$class.'.php');
// Сохраняем для будущих обращений к нему
self::$objects[$name] = new $class();
// Возвращаем созданный объект
return self::$objects[$name];
}
function getUniqueFileName($path, $name){
$ext = '.' . mb_strtolower(substr(strrchr($name, '.'), 1));
$name = substr($name, 0, -strlen(strrchr ($name, ".")));
$path = rtrim($path, '/') . '/';
$num = $fix = '';
while(is_file($path . $name . $fix . $ext)) $fix = '_' . ++$num;
return $name . $fix . $ext;
}
function translateStr($str){
$translate = array(
'а'=>'a','б'=>'b','в'=>'v','г'=>'g','д'=>'d','е'=>'e','ё'=>'e','ж'=>'zh','з'=>'z','и'=>'i','й'=>'i','к'=>'k','л'=>'l','м'=>'m','н'=>'n','о'=>'o','п'=>'p',
'р'=>'r','с'=>'s','т'=>'t','у'=>'u','ф'=>'f','х'=>'kh','ц'=>'tc','ч'=>'ch','ш'=>'sh','щ'=>'shch','ь'=>'','ы'=>'y','ъ'=>'','э'=>'e','ю'=>'iu','я'=>'ia'
);
$str = mb_strtolower($str, "UTF-8");
$str = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
$res = array();
foreach($str as $letter){
if(isset($translate[$letter])) $res[] = $translate[$letter];
else $res[] = preg_match('~[a-z0-9_\.]~', $letter) ? $letter : '-';
}
$str = implode('', $res);
$str = trim($str, '-');
$str = preg_replace('~([\.]+)~', '.', $str);
return preg_replace('~([-]+)~', '-', $str);
}
}

106
api/Simpla_classic.php Normal file
View File

@@ -0,0 +1,106 @@
<?php
/**
* Основной класс для доступа ко всем возможностям Simplacms
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('api/Config.php');
require_once('api/Request.php');
require_once('api/Database.php');
require_once('api/Settings.php');
require_once('api/Design.php');
require_once('api/Money.php');
require_once('api/Pages.php');
require_once('api/Blog.php');
require_once('api/Categories.php');
require_once('api/Features.php');
require_once('api/Cart.php');
require_once('api/Image.php');
require_once('api/Delivery.php');
require_once('api/Payment.php');
require_once('api/Orders.php');
require_once('api/Users.php');
class Simpla
{
public $config; /**< Экземпляр класса Conifg */
public $request; /**< Экземпляр класса Request */
public $db; /**< Экземпляр класса Database */
public $settings; /**< Экземпляр класса Settings */
public $design; /**< Экземпляр класса Design */
public $user; /**< Экземпляр класса User */
public $money; /**< Экземпляр класса Currencies */
public $pages; /**< Экземпляр класса ArticlesModel */
public $brands; /**< Экземпляр класса Brands */
public $blog; /**< Экземпляр класса ArticlesModel */
public $catalog; /**< Экземпляр класса Catalog */
public $features; /**< Экземпляр класса Features */
public $cart; /**< Экземпляр класса Cart */
public $image; /**< Экземпляр класса Cart */
public $delivery; /**< Экземпляр класса Cart */
public $payment; /**< Экземпляр класса Cart */
public $orders; /**< Экземпляр класса Cart */
public $users; /**< Экземпляр класса Cart */
public $services; /**< Экземпляр класса Services */
private static $simpla_instance;
/**
* В конструкторе создаем нужные объекты.
* При повторном вызове конструктора устанавливаем ссылки на уже существующие экземпляры.
* Немного напоминает синглтон - члены класса Simpla всегда ссылаются на одни и те же объекты.
*/
public function __construct()
{
if(self::$simpla_instance)
{
$this->config = &self::$simpla_instance->config;
$this->request = &self::$simpla_instance->request;
$this->categories = &self::$simpla_instance->categories;
$this->db = &self::$simpla_instance->db;
$this->settings = &self::$simpla_instance->settings;
$this->design = &self::$simpla_instance->design;
$this->image = &self::$simpla_instance->image;
$this->money = &self::$simpla_instance->money;
$this->pages = &self::$simpla_instance->pages;
$this->blog = &self::$simpla_instance->blog;
$this->catalog = &self::$simpla_instance->catalog;
$this->features = &self::$simpla_instance->features;
$this->cart = &self::$simpla_instance->cart;
$this->delivery = &self::$simpla_instance->delivery;
$this->payment = &self::$simpla_instance->payment;
$this->orders = &self::$simpla_instance->orders;
$this->users = &self::$simpla_instance->users;
$this->services = &self::$simpla_instance->services;
}
else
{
self::$simpla_instance = $this;
$this->config = new Config();
$this->request = new Request();
$this->categories = new Categories();
$this->db = new Database();
$this->settings = new Settings();
$this->design = new Design();
$this->image = new Image();
$this->money = new Money();
$this->pages = new Pages();
$this->blog = new Blog();
$this->catalog = new Catalog();
$this->features = new Features();
$this->cart = new Cart();
$this->delivery = new Delivery();
$this->payment = new Payment();
$this->orders = new Orders();
$this->users = new Users();
$this->services = new Services();
}
}
}

784
api/SimpleImage.php Normal file
View File

@@ -0,0 +1,784 @@
<?php
/*
The PHP SimpleImage class - v2
By Cory LaViska for A Beautiful Site, LLC. (http://www.abeautifulsite.net/)
License:
This software is dual-licensed under the GNU General Public License and
the MIT License and is copyright A Beautiful Site, LLC.
*/
class SimpleImage {
private $image, $filename, $original_info, $width, $height;
function __construct($filename = null) {
if( $filename ) $this->load($filename);
}
function __destruct() {
if( $this->image ) imagedestroy($this->image);
}
//
// Load an image
//
// $filename - the image to be loaded (required)
//
public function load($filename) {
// Require GD library
if( !extension_loaded('gd') ) throw new Exception('Required extension GD is not loaded.');
$this->filename = $filename;
$info = getimagesize($this->filename);
switch( $info['mime'] ) {
case 'image/gif':
$this->image = imagecreatefromgif($this->filename);
break;
case 'image/jpeg':
$this->image = imagecreatefromjpeg($this->filename);
break;
case 'image/png':
$this->image = imagecreatefrompng($this->filename);
break;
default:
throw new Exception('Invalid image: ' . $this->filename);
break;
}
$this->original_info = array(
'width' => $info[0],
'height' => $info[1],
'orientation' => $this->get_orientation(),
'exif' => function_exists('exif_read_data') ? $this->exif = @exif_read_data($this->filename) : null,
'format' => preg_replace('/^image\//', '', $info['mime']),
'mime' => $info['mime']
);
$this->width = $info[0];
$this->height = $info[1];
imagesavealpha($this->image, true);
imagealphablending($this->image, true);
return $this;
}
//
// Save an image
//
// $filename - the filename to save to (defaults to original file)
// $quality - 0-9 for PNG, 0-100 for JPEG
//
// Notes:
//
// The resulting format will be determined by the file extension.
//
public function save($filename = null, $quality = null) {
if( !$filename ) $filename = $this->filename;
// Determine format via file extension (fall back to original format)
$format = $this->file_ext($filename);
if( !$format ) $format = $this->original_info['format'];
// Determine output format
switch( $format ) {
case 'gif':
$result = imagegif($this->image, $filename);
break;
case 'jpg':
case 'jpeg':
if( $quality === null ) $quality = 90;
$quality = $this->keep_within($quality, 0, 90);
$result = imagejpeg($this->image, $filename, $quality);
break;
case 'png':
if( $quality === null ) $quality = 9;
$quality = $this->keep_within($quality, 0, 9);
imagealphablending($this->image, false);
imagesavealpha($this->image,true);
$result = imagepng($this->image, $filename, $quality);
break;
default:
throw new Exception('Unsupported format');
}
if( !$result ) throw new Exception('Unable to save image: ' . $filename);
return $this;
}
//
// Get info about the original image
//
// Returns
//
// array(
// width => 320,
// height => 200,
// orientation => ['portrait', 'landscape', 'square'],
// exif => array(...),
// mime => ['image/jpeg', 'image/gif', 'image/png'],
// format => ['jpeg', 'gif', 'png']
// )
//
public function get_original_info() {
return $this->original_info;
}
//
// Get the current width
//
public function get_width() {
return imagesx($this->image);
}
//
// Get the current height
//
public function get_height() {
return imagesy($this->image);
}
//
// Get the current orientation ('portrait', 'landscape', or 'square')
//
public function get_orientation() {
if( imagesx($this->image) > imagesy($this->image) ) return 'landscape';
if( imagesx($this->image) < imagesy($this->image) ) return 'portrait';
return 'square';
}
//
// Flip an image horizontally or vertically
//
// $direction - 'x' or 'y'
//
public function flip($direction) {
$new = imagecreatetruecolor($this->width, $this->height);
imagealphablending($new, false);
imagesavealpha($new, true);
switch( strtolower($direction) ) {
case 'y':
for( $y = 0; $y < $this->height; $y++ ) imagecopy($new, $this->image, 0, $y, 0, $this->height - $y - 1, $this->width, 1);
break;
default:
for( $x = 0; $x < $this->width; $x++ ) imagecopy($new, $this->image, $x, 0, $this->width - $x - 1, 0, 1, $this->height);
break;
}
$this->image = $new;
return $this;
}
//
// Rotate an image
//
// $angle - 0 - 360 (required)
// $bg_color - hex color for the background
//
public function rotate($angle, $bg_color = '#000000') {
$rgb = $this->hex2rgb($bg_color);
$bg_color = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']);
$new = imagerotate($this->image, -($this->keep_within($angle, -360, 360)), $bg_color);
imagesavealpha($new, true);
imagealphablending($new, true);
$this->width = imagesx($new);
$this->height = imagesy($new);
$this->image = $new;
return $this;
}
//
// Rotates and/or flips an image automatically so the orientation will
// be correct (based on exif 'Orientation')
//
public function auto_orient() {
// Adjust orientation
switch( $this->original_info['exif']['Orientation'] ) {
case 1:
// Do nothing
break;
case 2:
// Flip horizontal
$this->flip('x');
break;
case 3:
// Rotate 180 counterclockwise
$this->rotate(-180);
break;
case 4:
// vertical flip
$this->flip('y');
break;
case 5:
// Rotate 90 clockwise and flip vertically
$this->flip('y');
$this->rotate(90);
break;
case 6:
// Rotate 90 clockwise
$this->rotate(90);
break;
case 7:
// Rotate 90 clockwise and flip horizontally
$this->flip('x');
$this->rotate(90);
break;
case 8:
// Rotate 90 counterclockwise
$this->rotate(-90);
break;
}
return $this;
}
//
// Resize an image to the specified dimensions
//
// $width - the width of the resulting image
// $height - the height of the resulting image
//
public function resize($width, $height) {
//echo $this->image_type . '==' . IMAGETYPE_PNG; die;
$new = imagecreatetruecolor($width, $height);
imagealphablending($new, false);
imagesavealpha($new, true);
imagecopyresampled($new, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
$this->width = $width;
$this->height = $height;
$this->image = $new;
return $this;
}
//
// Fit to width (proportionally resize to specified width)
//
public function fit_to_width($width) {
$aspect_ratio = $this->height / $this->width;
$height = $width * $aspect_ratio;
return $this->resize($width, $height);
}
//
// Fit to height (proportionally resize to specified height)
//
public function fit_to_height($height) {
$aspect_ratio = $this->height / $this->width;
$width = $height / $aspect_ratio;
return $this->resize($width, $height);
}
//
// Best fit (proportionally resize to fit in specified width/height)
//
public function best_fit($max_width, $max_height) {
// If it already fits, there's nothing to do
if( $this->width <= $max_width && $this->height <= $max_height ) return $this;
// Determine aspect ratio
$aspect_ratio = $this->height / $this->width;
// Make width fit into new dimensions
if( $this->width > $max_width ) {
$width = $max_width;
$height = $width * $aspect_ratio;
} else {
$width = $this->width;
$height = $this->height;
}
// Make height fit into new dimensions
if( $height > $max_height ) {
$height = $max_height;
$width = $height / $aspect_ratio;
}
return $this->resize($width, $height);
}
//
// Crop an image
//
// $x1 - left
// $y1 - top
// $x2 - right
// $y2 - bottom
//
public function crop($x1, $y1, $x2, $y2) {
// Determine crop size
if( $x2 < $x1 ) list($x1, $x2) = array($x2, $x1);
if( $y2 < $y1 ) list($y1, $y2) = array($y2, $y1);
$crop_width = $x2 - $x1;
$crop_height = $y2 - $y1;
$new = imagecreatetruecolor($crop_width, $crop_height);
imagealphablending($new, false);
imagesavealpha($new, true);
imagecopyresampled($new, $this->image, 0, 0, $x1, $y1, $crop_width, $crop_height, $crop_width, $crop_height);
$this->width = $crop_width;
$this->height = $crop_height;
$this->image = $new;
return $this;
}
//
// Square crop (great for thumbnails)
//
// $size - the size in pixels of the resulting image (width and height are the same) (optional)
//
public function square_crop($size = null) {
// Calculate measurements
if( $this->width > $this->height ) {
// Landscape
$x_offset = ($this->width - $this->height) / 2;
$y_offset = 0;
$square_size = $this->width - ($x_offset * 2);
} else {
// Portrait
$x_offset = 0;
$y_offset = ($this->height - $this->width) / 2;
$square_size = $this->height - ($y_offset * 2);
}
// Trim to square
$this->crop($x_offset, $y_offset, $x_offset + $square_size, $y_offset + $square_size);
// Resize
if( $size ) $this->resize($size, $size);
return $this;
}
//
// Desaturate (grayscale)
//
public function desaturate() {
imagefilter($this->image, IMG_FILTER_GRAYSCALE);
return $this;
}
//
// Invert
//
public function invert() {
imagefilter($this->image, IMG_FILTER_NEGATE);
return $this;
}
//
// Brightness
//
// $level - darkest = -255, lightest = 255 (required)
//
public function brightness($level) {
imagefilter($this->image, IMG_FILTER_BRIGHTNESS, $this->keep_within($level, -255, 255));
return $this;
}
//
// Contrast
//
// $level - min = -100, max, 100 (required)
//
public function contrast($level) {
imagefilter($this->image, IMG_FILTER_CONTRAST, $this->keep_within($level, -100, 100));
return $this;
}
//
// Colorize (requires PHP 5.2.5+)
//
// $color - any valid hex color (required)
// $opacity - 0 - 1 (required)
//
public function colorize($color, $opacity) {
$rgb = $this->hex2rgb($color);
$alpha = $this->keep_within(127 - (127 * $opacity), 0, 127);
imagefilter($this->image, IMG_FILTER_COLORIZE, $this->keep_within($rgb['r'], 0, 255), $this->keep_within($rgb['g'], 0, 255), $this->keep_within($rgb['b'], 0, 255), $alpha);
return $this;
}
//
// Edge Detect
//
public function edges() {
imagefilter($this->image, IMG_FILTER_EDGEDETECT);
return $this;
}
//
// Emboss
//
public function emboss() {
imagefilter($this->image, IMG_FILTER_EMBOSS);
return $this;
}
//
// Mean Remove
//
public function mean_remove() {
imagefilter($this->image, IMG_FILTER_MEAN_REMOVAL);
return $this;
}
//
// Blur
//
// $type - 'selective' or 'gaussian' (default = selective)
// $passes - the number of times to apply the filter
//
public function blur($type = 'selective', $passes = 1) {
switch( strtolower($type) ) {
case 'gaussian':
$type = IMG_FILTER_GAUSSIAN_BLUR;
break;
default:
$type = IMG_FILTER_SELECTIVE_BLUR;
break;
}
for( $i = 0; $i < $passes; $i++ ) imagefilter($this->image, $type);
return $this;
}
//
// Sketch
//
public function sketch() {
imagefilter($this->image, IMG_FILTER_MEAN_REMOVAL);
return $this;
}
//
// Smooth
//
// $level - min = -10, max = 10
//
public function smooth($level) {
imagefilter($this->image, IMG_FILTER_SMOOTH, $this->keep_within($level, -10, 10));
return $this;
}
//
// Pixelate (requires PHP 5.3+)
//
// $block_size - the size in pixels of each resulting block (default = 10)
//
public function pixelate($block_size = 10) {
imagefilter($this->image, IMG_FILTER_PIXELATE, $block_size, true);
return $this;
}
//
// Sepia
//
public function sepia() {
imagefilter($this->image, IMG_FILTER_GRAYSCALE);
imagefilter($this->image, IMG_FILTER_COLORIZE, 100, 50, 0);
return $this;
}
//
// Overlay (overlay an image on top of another; works with 24-big PNG alpha-transparency)
//
// $overlay_file - the image to use as a overlay (required)
// $position - 'center', 'top', 'left', 'bottom', 'right', 'top left',
// 'top right', 'bottom left', 'bottom right'
// $opacity - overlay opacity (0 - 1)
// $x_offset - horizontal offset in pixels
// $y_offset - vertical offset in pixels
//
public function overlay($overlay_file, $position = 'center', $opacity = 1, $x_offset = 0, $y_offset = 0) {
// Load overlay image
$overlay = new SimpleImage($overlay_file);
// Convert opacity
$opacity = $opacity * 100;
// Determine position
switch( strtolower($position) ) {
case 'top left':
$x = 0 + $x_offset;
$y = 0 + $y_offset;
break;
case 'top right':
$x = $this->width - $overlay->width + $x_offset;
$y = 0 + $y_offset;
break;
case 'top':
$x = ($this->width / 2) - ($overlay->width / 2) + $x_offset;
$y = 0 + $y_offset;
break;
case 'bottom left':
$x = 0 + $x_offset;
$y = $this->height - $overlay->height + $y_offset;
break;
case 'bottom right':
$x = $this->width - $overlay->width + $x_offset;
$y = $this->height - $overlay->height + $y_offset;
break;
case 'bottom':
$x = ($this->width / 2) - ($overlay->width / 2) + $x_offset;
$y = $this->height - $overlay->height + $y_offset;
break;
case 'left':
$x = 0 + $x_offset;
$y = ($this->height / 2) - ($overlay->height / 2) + $y_offset;
break;
case 'right':
$x = $this->width - $overlay->width + $x_offset;
$y = ($this->height / 2) - ($overlay->height / 2) + $y_offset;
break;
case 'center':
default:
$x = ($this->width / 2) - ($overlay->width / 2) + $x_offset;
$y = ($this->height / 2) - ($overlay->height / 2) + $y_offset;
break;
}
$this->imagecopymerge_alpha($this->image, $overlay->image, $x, $y, 0, 0, $overlay->width, $overlay->height, $opacity);
return $this;
}
//
// Text (adds text to an image)
//
// $text - the text to add (required)
// $font_file - the font to use (required)
// $font_size - font size in points
// $color - font color in hex
// $position - 'center', 'top', 'left', 'bottom', 'right', 'top left',
// 'top right', 'bottom left', 'bottom right'
// $x_offset - horizontal offset in pixels
// $y_offset - vertical offset in pixels
//
public function text($text, $font_file, $font_size = '12', $color = '#000000', $position = 'center', $x_offset = 0, $y_offset = 0) {
// todo - this method could be improved to support the text angle
$angle = 0;
$rgb = $this->hex2rgb($color);
$color = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']);
// Determine textbox size
$box = imagettfbbox($font_size, $angle, $font_file, $text);
if( !$box ) throw new Exception('Unable to load font: ' . $font_file);
$box_width = abs($box[6] - $box[2]);
$box_height = abs($box[7] - $box[1]);
// Determine position
switch( strtolower($position) ) {
case 'top left':
$x = 0 + $x_offset;
$y = 0 + $y_offset + $box_height;
break;
case 'top right':
$x = $this->width - $box_width + $x_offset;
$y = 0 + $y_offset + $box_height;
break;
case 'top':
$x = ($this->width / 2) - ($box_width / 2) + $x_offset;
$y = 0 + $y_offset + $box_height;
break;
case 'bottom left':
$x = 0 + $x_offset;
$y = $this->height - $box_height + $y_offset + $box_height;
break;
case 'bottom right':
$x = $this->width - $box_width + $x_offset;
$y = $this->height - $box_height + $y_offset + $box_height;
break;
case 'bottom':
$x = ($this->width / 2) - ($box_width / 2) + $x_offset;
$y = $this->height - $box_height + $y_offset + $box_height;
break;
case 'left':
$x = 0 + $x_offset;
$y = ($this->height / 2) - (($box_height / 2) - $box_height) + $y_offset;
break;
case 'right';
$x = $this->width - $box_width + $x_offset;
$y = ($this->height / 2) - (($box_height / 2) - $box_height) + $y_offset;
break;
case 'center':
default:
$x = ($this->width / 2) - ($box_width / 2) + $x_offset;
$y = ($this->height / 2) - (($box_height / 2) - $box_height) + $y_offset;
break;
}
imagettftext($this->image, $font_size, $angle, $x, $y, $color, $font_file, $text);
return $this;
}
// Same as PHP's imagecopymerge() function, except preserves alpha-transparency in 24-bit PNGs
// Courtest of: http://www.php.net/manual/en/function.imagecopymerge.php#88456
private function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct ) {
$pct /= 100;
// Get image width and height
$w = imagesx($src_im);
$h = imagesy($src_im);
// Turn alpha blending off
imagealphablending($src_im, false);
// Find the most opaque pixel in the image (the one with the smallest alpha value)
$minalpha = 127;
for( $x = 0; $x < $w; $x++ ) {
for( $y = 0; $y < $h; $y++ ) {
$alpha = (imagecolorat( $src_im, $x, $y ) >> 24) & 0xFF;
if( $alpha < $minalpha ) {
$minalpha = $alpha;
}
}
}
// Loop through image pixels and modify alpha for each
for( $x = 0; $x < $w; $x++ ) {
for( $y = 0; $y < $h; $y++ ) {
// Get current alpha value (represents the TANSPARENCY!)
$colorxy = imagecolorat($src_im, $x, $y);
$alpha = ($colorxy >> 24) & 0xFF;
// Calculate new alpha
if( $minalpha !== 127 ) {
$alpha = 127 + 127 * $pct * ($alpha - 127) / (127 - $minalpha);
} else {
$alpha += 127 * $pct;
}
// Get the color index with new alpha
$alphacolorxy = imagecolorallocatealpha($src_im, ($colorxy >> 16) & 0xFF, ($colorxy >> 8) & 0xFF, $colorxy & 0xFF, $alpha);
// Set pixel with the new color + opacity
if( !imagesetpixel($src_im, $x, $y, $alphacolorxy) ) return false;
}
}
imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
}
//
// Ensures $value is always within $min and $max range.
// If lower, $min is returned. If higher, $max is returned.
//
private function keep_within($value, $min, $max) {
if( $value < $min ) return $min;
if( $value > $max ) return $max;
return $value;
}
//
// Returns the file extension of the specified file
//
private function file_ext($filename) {
if( !preg_match('/\./', $filename) ) return '';
return preg_replace('/^.*\./', '', $filename);
}
//
// Converts a hex color value to its RGB equivalent
//
private function hex2rgb($hex_color) {
if( $hex_color[0] == '#' ) $hex_color = substr($hex_color, 1);
if( strlen($hex_color) == 6 ) {
list($r, $g, $b) = array(
$hex_color[0] . $hex_color[1],
$hex_color[2] . $hex_color[3],
$hex_color[4] . $hex_color[5]
);
} elseif( strlen($hex_color) == 3 ) {
list($r, $g, $b) = array(
$hex_color[0] . $hex_color[0],
$hex_color[1] . $hex_color[1],
$hex_color[2] . $hex_color[2]
);
} else {
return false;
}
return array(
'r' => hexdec($r),
'g' => hexdec($g),
'b' => hexdec($b)
);
}
}

212
api/Users.php Normal file
View File

@@ -0,0 +1,212 @@
<?php
/**
* Simpla CMS
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Users extends Simpla
{
// осторожно, при изменении соли испортятся текущие пароли пользователей
private $salt = '8e86a279d6e182b3c811c559e6b15484';
function get_users($filter = array())
{
$limit = 1000;
$page = 1;
$group_id_filter = '';
$keyword_filter = '';
if(isset($filter['limit']))
$limit = max(1, intval($filter['limit']));
if(isset($filter['page']))
$page = max(1, intval($filter['page']));
if(isset($filter['group_id']))
$group_id_filter = $this->db->placehold('AND u.group_id in(?@)', (array)$filter['group_id']);
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND (u.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR u.email LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR u.last_ip LIKE "%'.mysql_real_escape_string(trim($keyword)).'%")');
}
$order = 'u.name';
if(!empty($filter['sort']))
switch ($filter['sort'])
{
case 'date':
$order = 'u.created DESC';
break;
case 'name':
$order = 'u.name';
break;
}
$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
// Выбираем пользователей
$query = $this->db->placehold("SELECT u.id, u.email, u.password, u.name, u.group_id, u.enabled, u.last_ip, u.created, g.discount, g.name as group_name, u.name2, u.phone, u.country, u.region, u.city, u.indx, u.adress FROM __users u
LEFT JOIN __groups g ON u.group_id=g.id
WHERE 1 $group_id_filter $keyword_filter ORDER BY $order $sql_limit");
$this->db->query($query);
return $this->db->results();
}
function count_users($filter = array())
{
$group_id_filter = '';
$keyword_filter = '';
if(isset($filter['group_id']))
$group_id_filter = $this->db->placehold('AND u.group_id in(?@)', (array)$filter['group_id']);
if(isset($filter['keyword']))
{
$keywords = explode(' ', $filter['keyword']);
foreach($keywords as $keyword)
$keyword_filter .= $this->db->placehold('AND u.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR u.email LIKE "%'.mysql_real_escape_string(trim($keyword)).'%"');
}
// Выбираем пользователей
$query = $this->db->placehold("SELECT count(*) as count FROM __users u
LEFT JOIN __groups g ON u.group_id=g.id
WHERE 1 $group_id_filter $keyword_filter ORDER BY u.name");
$this->db->query($query);
return $this->db->result('count');
}
function get_user($id)
{
if(gettype($id) == 'string')
$where = $this->db->placehold(' WHERE u.email=? ', $id);
else
$where = $this->db->placehold(' WHERE u.id=? ', intval($id));
// Выбираем пользователя
$query = $this->db->placehold("SELECT u.id, u.email, u.password, u.name, u.group_id, u.enabled, u.last_ip, u.created, g.discount, g.name as group_name, u.name2, u.phone, u.country, u.region, u.city, u.indx, u.adress FROM __users u LEFT JOIN __groups g ON u.group_id=g.id $where LIMIT 1", $id);
$this->db->query($query);
$user = $this->db->result();
if(empty($user))
return false;
$user->discount *= 1; // Убираем лишние нули, чтобы было 5 вместо 5.00
return $user;
}
public function add_user($user)
{
$user = (array)$user;
if(isset($user['password']))
$user['password'] = md5($this->salt.$user['password'].md5($user['password']));
$query = $this->db->placehold("SELECT count(*) as count FROM __users WHERE email=?", $user['email']);
$this->db->query($query);
if($this->db->result('count') > 0)
return false;
$query = $this->db->placehold("INSERT INTO __users SET ?%", $user);
$this->db->query($query);
return $this->db->insert_id();
}
public function update_user($id, $user)
{
$user = (array)$user;
if(isset($user['password']))
$user['password'] = md5($this->salt.$user['password'].md5($user['password']));
$query = $this->db->placehold("UPDATE __users SET ?% WHERE id=? LIMIT 1", $user, intval($id));
$this->db->query($query);
return $id;
}
/*
*
* Удалить пользователя
* @param $post
*
*/
public function delete_user($id)
{
if(!empty($id))
{
$query = $this->db->placehold("UPDATE __orders SET user_id=NULL WHERE id=? LIMIT 1", intval($id));
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __users WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
return true;
}
return false;
}
function get_groups()
{
// Выбираем группы
$query = $this->db->placehold("SELECT g.id, g.name, g.discount FROM __groups AS g ORDER BY g.discount");
$this->db->query($query);
return $this->db->results();
}
function get_group($id)
{
// Выбираем группу
$query = $this->db->placehold("SELECT * FROM __groups WHERE id=? LIMIT 1", $id);
$this->db->query($query);
$group = $this->db->result();
return $group;
}
public function add_group($group)
{
$query = $this->db->placehold("INSERT INTO __groups SET ?%", $group);
$this->db->query($query);
return $this->db->insert_id();
}
public function update_group($id, $group)
{
$query = $this->db->placehold("UPDATE __groups SET ?% WHERE id=? LIMIT 1", $group, intval($id));
$this->db->query($query);
return $id;
}
public function delete_group($id)
{
if(!empty($id))
{
$query = $this->db->placehold("UPDATE __users SET group_id=NULL WHERE group_id=? LIMIT 1", intval($id));
$this->db->query($query);
$query = $this->db->placehold("DELETE FROM __groups WHERE id=? LIMIT 1", intval($id));
if($this->db->query($query))
return true;
}
return false;
}
public function check_password($email, $password)
{
$encpassword = md5($this->salt.$password.md5($password));
$query = $this->db->placehold("SELECT id FROM __users WHERE email=? AND password=? LIMIT 1", $email, $encpassword);
$this->db->query($query);
if($id = $this->db->result('id'))
return $id;
return false;
}
}

127
api/Variants.old Normal file
View File

@@ -0,0 +1,127 @@
<?php
/**
* Работа с вариантами товаров
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
*/
require_once('Simpla.php');
class Variants extends Simpla
{
public function prices_range($filter = array())
{
$product_id_filter = '';
$instock_filter = '';
if(!empty($filter['product_id']))
$product_id_filter = $this->db->placehold('AND v.product_id in(?@)', (array)$filter['product_id']);
if(!empty($filter['in_stock']) && $filter['in_stock'])
$instock_filter = $this->db->placehold('AND (v.stock>0 OR v.stock IS NULL)');
if(!$product_id_filter)
return array();
$query = $this->db->placehold("SELECT min(price) as min, max(price) as max
FROM __variants AS v
WHERE
1
$product_id_filter
$instock_filter
");
$this->db->query($query);
return $this->db->result();
}
/**
* Функция возвращает варианты товара
* @param $filter
* @retval array
*/
public function get_variants($filter = array())
{
$product_id_filter = '';
$variant_id_filter = '';
$instock_filter = '';
if(!empty($filter['product_id']))
$product_id_filter = $this->db->placehold('AND v.product_id in(?@)', (array)$filter['product_id']);
if(!empty($filter['id']))
$variant_id_filter = $this->db->placehold('AND v.id in(?@)', (array)$filter['id']);
if(!empty($filter['in_stock']) && $filter['in_stock'])
$variant_id_filter = $this->db->placehold('AND (v.stock>0 OR v.stock IS NULL)');
if(!$product_id_filter && !$variant_id_filter)
return array();
$query = $this->db->placehold("SELECT v.id, v.product_id, v.weight , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment, v.position
FROM __variants AS v
WHERE
1
$product_id_filter
$variant_id_filter
ORDER BY v.position
", $this->settings->max_order_amount);
$this->db->query($query);
return $this->db->results();
}
public function get_variant($id)
{
if(empty($id))
return false;
$query = $this->db->placehold("SELECT v.id, v.product_id, v.weight , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment
FROM __variants v WHERE id=?
LIMIT 1", $this->settings->max_order_amount, $id);
$this->db->query($query);
$variant = $this->db->result();
return $variant;
}
public function update_variant($id, $variant)
{
$query = $this->db->placehold("UPDATE __variants SET ?% WHERE id=? LIMIT 1", $variant, intval($id));
$this->db->query($query);
return $id;
}
public function add_variant($variant)
{
$query = $this->db->placehold("INSERT INTO __variants SET ?%", $variant);
$this->db->query($query);
return $this->db->insert_id();
}
public function delete_variant($id)
{
if(!empty($id))
{
$this->delete_attachment($id);
$query = $this->db->placehold("DELETE FROM __variants WHERE id = ? LIMIT 1", intval($id));
$this->db->query($query);
$this->db->query('UPDATE __purchases SET variant_id=NULL WHERE variant_id=?', intval($id));
}
}
public function delete_attachment($id)
{
$query = $this->db->placehold("SELECT attachment FROM __variants WHERE id=?", $id);
$this->db->query($query);
$filename = $this->db->result('attachment');
$query = $this->db->placehold("SELECT 1 FROM __variants WHERE attachment=? AND id!=?", $filename, $id);
$this->db->query($query);
$exists = $this->db->num_rows();
if(!empty($filename) && $exists == 0)
@unlink($this->config->root_dir.'/'.$this->config->downloads_dir.$filename);
$this->update_variant($id, array('attachment'=>null));
}
}

136
api/Variants.php Normal file
View File

@@ -0,0 +1,136 @@
<?php
/**
* Работа с вариантами товаров
*
* @copyright 2011 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* @editor 2014 Vitaly Raevsky
* @link http://bwdesign.ru
* @email vitaly.raevsky@gmail.com
*
*/
require_once('Simpla.php');
class Variants extends Simpla
{
/**
* Функция возвращает варианты товара
* @param $filter
* @retval array
*/
public function get_variants($filter = array())
{
$product_id_filter = '';
$variant_id_filter = '';
$instock_filter = '';
if(!empty($filter['product_id']))
$product_id_filter = $this->db->placehold('AND v.product_id in(?@)', (array)$filter['product_id']);
if(!empty($filter['id']))
$variant_id_filter = $this->db->placehold('AND v.id in(?@)', (array)$filter['id']);
if(!empty($filter['in_stock']) && $filter['in_stock'])
$variant_id_filter = $this->db->placehold('AND (v.stock>0 OR v.stock IS NULL)');
if(!$product_id_filter && !$variant_id_filter)
return array();
$query = $this->db->placehold("SELECT v.id, v.product_id, v.weight , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment, v.position
FROM __variants AS v
WHERE
1
$product_id_filter
$variant_id_filter
ORDER BY v.position
", $this->settings->max_order_amount);
$this->db->query($query);
return $this->db->results();
}
public function get_variant($id)
{
if(empty($id))
return false;
$query = $this->db->placehold("SELECT v.id, v.product_id, v.weight , v.price, NULLIF(v.compare_price, 0) as compare_price, v.sku, IFNULL(v.stock, ?) as stock, (v.stock IS NULL) as infinity, v.name, v.attachment
FROM __variants v WHERE id=?
LIMIT 1", $this->settings->max_order_amount, $id);
$this->db->query($query);
$variant = $this->db->result();
return $variant;
}
public function update_variant($id, $variant)
{
$query = $this->db->placehold("UPDATE __variants SET ?% WHERE id=? LIMIT 1", $variant, intval($id));
$this->db->query($query);
return $id;
}
public function add_variant($variant)
{
$query = $this->db->placehold("INSERT INTO __variants SET ?%", $variant);
$this->db->query($query);
return $this->db->insert_id();
}
public function delete_variant($id)
{
if(!empty($id))
{
$this->delete_attachment($id);
$query = $this->db->placehold("DELETE FROM __variants WHERE id = ? LIMIT 1", intval($id));
$this->db->query($query);
$this->db->query('UPDATE __purchases SET variant_id=NULL WHERE variant_id=?', intval($id));
$this->db->query('DELETE FROM __variants_options WHERE id_veriant = ? ', intval($id));
}
}
public function delete_attachment($id)
{
$query = $this->db->placehold("SELECT attachment FROM __variants WHERE id=?", $id);
$this->db->query($query);
$filename = $this->db->result('attachment');
$query = $this->db->placehold("SELECT 1 FROM __variants WHERE attachment=? AND id!=?", $filename, $id);
$this->db->query($query);
$exists = $this->db->num_rows();
if(!empty($filename) && $exists == 0)
@unlink($this->config->root_dir.'/'.$this->config->downloads_dir.$filename);
$this->update_variant($id, array('attachment'=>null));
}
public function prices_range($filter = array())
{
$product_id_filter = '';
$instock_filter = '';
if(!empty($filter['product_id']))
$product_id_filter = $this->db->placehold('AND v.product_id in(?@)', (array)$filter['product_id']);
if(!empty($filter['in_stock']) && $filter['in_stock'])
$instock_filter = $this->db->placehold('AND (v.stock>0 OR v.stock IS NULL)');
if(!$product_id_filter)
return array();
$query = $this->db->placehold("SELECT min(price) as min, max(price) as max
FROM __variants AS v
WHERE
1
$product_id_filter
$instock_filter
");
$this->db->query($query);
return $this->db->result();
}
}

1812
api/claviska/SimpleImage.php Normal file

File diff suppressed because it is too large Load Diff

1287
api/simple_image_class.php Normal file

File diff suppressed because it is too large Load Diff