<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2016 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

require_once (dirname(__FILE__).'/url/OWLLink.php');
require_once (dirname(__FILE__).'/classes/OWLPost.php');
require_once (dirname(__FILE__).'/classes/OWLCategory.php');
require_once (dirname(__FILE__).'/classes/OWLComment.php');
require_once (dirname(__FILE__).'/classes/OWLTag.php');
include_once(dirname(__FILE__).'/sql/SampleData.php');
class OWLBlog extends Module
{
	private $tabParentClass = null;
	private $tabClassBlog = 'AdminOWLBlog';
	private $tabNameBlog = null;
	private $_html_categories = '';
	private $psVersion = false;
	private $classTab = array();
	private $owlLink;
	private $html = '';
	private $imageType;
	private $myHook = array('displayLeftColumn');
	private $myHookRegister = array('footer', 'displayLeftColumn', 'displayRightColumn');
	public function __construct()
	{
		$this->name = 'owlblog';
		$this->displayName = $this->l('OWL Blog');
		$this->description = $this->l('OWL Blog Module');
		$this->bootstrap = true;
		$this->version = '1.6.0';
		$this->author = 'owltheme';
		$this->controllers = array('categoryPost', 'post', 'rss', 'tag');
		$this->tab = 'others';
		$this->owlLink = new OWLLink();
		$this->imageType = 'jpg';
		parent::__construct();
	}
	/*install*/
	public function existsTab($tabClass)
	{
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT id_tab AS id 
		FROM `'._DB_PREFIX_.'tab` t 
		WHERE LOWER(t.`class_name`) = \''.pSQL($tabClass).'\'');
		if (count($result) == 0) 
			return false;
		return true;
	}
	public function installDb()
	{
		/* create table */
		$sql = array();
		require_once(dirname(__FILE__).'/sql/install.php');
		foreach ($sql as $sq)
			if (!Db::getInstance()->Execute($sq))
				return false;
		/* init category home */
		$id_shop_default = (int)Configuration::get('PS_SHOP_DEFAULT');
		$sql = ' INSERT INTO '._DB_PREFIX_.'owl_blog_category(id_owl_blog_category,category_parent, level_depth, id_shop_default,active, position, allow_comment) VALUES(1, 0, 0, '.$id_shop_default.', 1, 0, 1) ';
		Db::getInstance()->execute($sql);
		$shops = Shop::getShops();
		foreach ($shops as $shop)
		{
			$sql = ' INSERT INTO '._DB_PREFIX_.'owl_blog_category_shop(id_owl_blog_category,id_shop,position) VALUES(1,'.$shop['id_shop'].',0) ';
			Db::getInstance()->execute($sql);
			foreach (Language::getLanguages(false) as $lang)
			{
				$sql = ' INSERT INTO '._DB_PREFIX_.'owl_blog_category_lang(id_owl_blog_category, id_lang, id_shop, name,link_rewrite) VALUES(1, '.$lang['id_lang'].', '.$shop['id_shop'].' , "Blog Home", "blog-home") ';
				Db::getInstance()->execute($sql);
			}
		}
		$sample_data = new SampleDataBlog();
		$sample_data->initData();
		$sample_data->installConfiguration();
		return true;
	}
	public function deleteImage()
	{
		#category
		$save_path = _PS_MODULE_DIR_.'owlblog/views/img/media/categories/';
		#folder src
		$images = glob($save_path.'src/'.'*.'.$this->imageType.'');
		foreach ($images as $image)
			unlink($save_path.'src/'.basename($image));
		#folder cache
		$images = glob($save_path.'cache/'.'*.'.$this->imageType.'');
		$imageNotDel = array('');
		foreach ($images as $image)
		{
			$pos = strpos(basename($image), 'no_image_');
			if ($pos === false)
				unlink($save_path.'cache/'.basename($image));
		}
		#post
		$save_path = _PS_MODULE_DIR_.'owlblog/views/img/media/posts/';
		#folder src
		$images = glob($save_path.'src/'.'*.'.$this->imageType.'');
		foreach ($images as $image)
			unlink($save_path.'src/'.basename($image));
		#folder cache
		$images = glob($save_path.'cache/'.'*.'.$this->imageType.'');
		foreach ($images as $image)
		{
			$pos = strpos(basename($image), 'no_image_');
			if ($pos === false)
				unlink($save_path.'cache/'.basename($image));
		}
	}
	
	public function installTabBlog()
	{
		if (!$this->existsTab('AdminOWLBlog'))
			if (!$this->addTab('OWL Blog', 'AdminOWLBlog', 0))
				return false;
		if (!$this->existsTab('AdminOWLCategory'))
			if (!$this->addTab('Blog Category', 'AdminOWLCategory', $this->getIdTabFromClassName('AdminOWLBlog')))
				return false;
		if (!$this->existsTab('AdminOWLPost'))
			if (!$this->addTab('Blog Post', 'AdminOWLPost', $this->getIdTabFromClassName('AdminOWLBlog')))
				return false;
		if (!$this->existsTab('AdminOWLComment'))
			if (!$this->addTab('Blog Comment', 'AdminOWLComment', $this->getIdTabFromClassName('AdminOWLBlog')))
				return false;
		if (!$this->existsTab('AdminOWLTags'))
			if (!$this->addTab('Blog Tag', 'AdminOWLTags', $this->getIdTabFromClassName('AdminOWLBlog')))
				return false;
		return true;
	}
	public function getIdTabFromClassName($tabName)
	{
		$sql = 'SELECT id_tab FROM '._DB_PREFIX_.'tab WHERE class_name="'.$tabName.'"';
		$tab = Db::getInstance()->getRow($sql);
		return $tab['id_tab'];
	}
	private function addTab($tabName, $tabClass, $id_parent)
	{
		$tab = new Tab();	
		$langs = Language::getLanguages();
		foreach ($langs as $lang)
			$tab->name[$lang['id_lang']] = $tabName;
		$tab->class_name = $tabClass;
		$tab->module = $this->name;
		$tab->id_parent = $id_parent;
		if (!$tab->save())
			return false;
		return true;
	}
	public function install()
	{
		if (!parent::install())
			return false;
		if (!$this->installDb() || !$this->installTabBlog() || !$this->registerHook('header') || !$this->registerHook('moduleRoutes') || !$this->registerHook('actionShopDataDuplication') || !$this->registerHook('actionShopDataDuplication') || !$this->registerHook('displayBackOfficeHeader'))
				return false;
		foreach ($this->myHookRegister as $hook)
			if (!$this->registerHook($hook))
				return false;
		$this->deleteImage();
		return true;
	}
	/*end install*/
	/*uninstall*/
	public function uninstallDb()
	{
		$sql = array();
		require_once(dirname(__FILE__).'/sql/uninstall.php');
		foreach ($sql as $sq)
			if (!Db::getInstance()->Execute($sq))
				return false;
		return true;
	}
	public function uninstallConfiguration()
	{
		Configuration::deleteByName('OWL_SHOW_BLOCK_CATEGORY');
		return true;
	}
	private function removeTab($tab_class)
	{
		$id_tab = Tab::getIdFromClassName($tab_class);
		if ($id_tab != 0)
		{
			$tab = new Tab($id_tab);
			$tab->delete();
			return true;
		}
		return false;
	}
	public function uninstall()
	{
		if (!parent::uninstall())
			return false;
		if (!$this->removeTab('AdminOWLBlog'))
			return false;
		if (!$this->removeTab('AdminOWLCategory'))
			return false;
		if (!$this->removeTab('AdminOWLPost'))
			return false;
		if (!$this->removeTab('AdminOWLComment'))
			return false;
		if (!$this->removeTab('AdminOWLTags'))
			return false;
		if (!$this->uninstallDb() || !$this->uninstallConfiguration())
			return false;
		$this->deleteImage();
		return true;
	}
	public function getCategories($id_lang, $id_shop)
	{
		$sql = 'SELECT * FROM '._DB_PREFIX_.'owl_blog_category a
				LEFT JOIN '._DB_PREFIX_.'owl_blog_category_lang b
				ON a.id_owl_blog_category = b.id_owl_blog_category AND b.id_shop = '.$id_shop.' AND b.id_lang='.$id_lang.'
				LEFT JOIN '._DB_PREFIX_.'owl_blog_category_shop c
				ON ( a.id_owl_blog_category = c.id_owl_blog_category AND c.id_shop = '.$id_shop.')
				WHERE a.active=1 AND b.id_lang='.$id_lang.' AND c.id_shop = '.$id_shop.'
				ORDER BY c.position ASC
				';
		$data = Db::getInstance()->ExecuteS($sql);
		return $data;
	}
	public function imageResizeThumb($src_path, $des_path, $new_width, $new_height)
	{
		ImageManager::resize($src_path, $des_path, $new_width, $new_height);
	}
	public function postProcess()
	{
		$id_lang = $this->context->language->id;
		$id_shop = $this->context->shop->id;
		if (Tools::getValue('submitConfiguration'))
		{
			$option_arr = $this->getOptions();
			$options = Tools::jsonEncode($option_arr);
			Configuration::updateValue('OWL_BLOG_CONFIG', $options);
			$src_no_image = _PS_MODULE_DIR_.'owlblog/views/img/media/posts/';
			$src_path = _PS_MODULE_DIR_.'owlblog/views/img/media/posts/src/';
			$des_path = _PS_MODULE_DIR_.'owlblog/views/img/media/posts/cache/';
			$src_path_cat = _PS_MODULE_DIR_.'owlblog/views/img/media/categories/src/';
			$des_path_cat = _PS_MODULE_DIR_.'owlblog/views/img/media/categories/cache/';
			
			//echo '<pre>'; print_r($option_arr); die;
			$sm = $option_arr['OWL_IMG_SMALL_SIZE'];
			$sm_h = $option_arr['OWL_IMG_SMALL_H_SIZE'];
			$md = $option_arr['OWL_IMG_MEDIUM_SIZE'];
			$md_h = $option_arr['OWL_IMG_MEDIUM_H_SIZE'];
			$lg = $option_arr['OWL_IMG_LARGE_SIZE'];
			$lg_h = $option_arr['OWL_IMG_LARGE_H_SIZE'];
			$cat_img = $option_arr['OWL_IMG_CATEGORY_SIZE'];
			$cat_img_h = $option_arr['OWL_IMG_CATEGORY_H_SIZE'];
			
			$this->imageResizeThumb($src_no_image.'no_image.jpg', $des_path.'no_image_small.'.$this->imageType, $sm, $sm_h);
			$this->imageResizeThumb($src_no_image.'no_image.jpg', $des_path.'no_image_medium.'.$this->imageType, $md, $md_h);
			$this->imageResizeThumb($src_no_image.'no_image.jpg', $des_path.'no_image_large.'.$this->imageType, $lg, $lg_h);
			
			$postObj = new OWLPost();
			$posts = $postObj->getIdAllPost($id_lang, $id_shop);
			foreach ($posts as $post)
			{
				$id = $post['id_owl_blog_post'];
				$this->imageResizeThumb($src_path.$id.'.'.$this->imageType, $des_path.$id.'_'.$id_shop.'_small.'.$this->imageType, $sm, $sm_h);
				$this->imageResizeThumb($src_path.$id.'.'.$this->imageType, $des_path.$id.'_'.$id_shop.'_medium.'.$this->imageType, $md, $md_h);
				$this->imageResizeThumb($src_path.$id.'.'.$this->imageType, $des_path.$id.'_'.$id_shop.'_large.'.$this->imageType, $lg, $lg_h);
			}
			$catObj = new OWLCategory();
			$cats = $catObj->getIdAllCat($id_lang, $id_shop);
			foreach ($cats as $cat)
			{
				$id = $cat['id_owl_blog_category'];
				$this->imageResizeThumb($src_path_cat.$id.'.'.$this->imageType, $des_path_cat.$id.'_'.$id_shop.'_category.'.$this->imageType, $cat_img, $cat_img_h);
			}
		}
		elseif (Tools::isSubmit('saveConfirmation'))
			$this->html = $this->displayConfirmation($this->l('Configs updated successfully'));
		elseif (Tools::isSubmit('saveError'))
			$this->html = $this->displayError($this->l('Configs updated error'));
	}
	public function isInt($value)
	{
		return ((string)(int)$value === (string)$value || $value === false);
	}
	public function getContent()
	{
		return $this->postProcess().$this->displayForm();
	}
	public function displayForm()
	{
		$this->context->controller->addCss($this->_path.'views/css/admin/owlblog.css', 'all');
		$options_str = Configuration::get('OWL_BLOG_CONFIG');
		$options_arr = Tools::jsonDecode($options_str, 1);
		$link_main = $options_arr['OWL_MAIN_BLOG_URL'];
		$main_blog_url = $this->owlLink->getMainBlogUrl($link_main);
		$this->context->smarty->assign(
			array(
				'options_arr' => $options_arr,
				'main_blog_url' => $main_blog_url
				)
		);
		return $this->display(__FILE__, 'views/templates/admin/blog_config.tpl');
	}
	
	public	function getOptions()
	{
		$option_arr = array();
		$option_arr['OWL_MAIN_BLOG_URL'] = Tools::getValue('OWL_MAIN_BLOG_URL', 'owlblog');
		$option_arr['OWL_POSTS_PER_PAGE'] = Tools::getValue('OWL_POSTS_PER_PAGE', 4);
		$option_arr['OWL_DISPLAY_CAPTCHA'] = Tools::getValue('OWL_DISPLAY_CAPTCHA', 1);
		$option_arr['OWL_COMMENTS_VALIDATE'] = Tools::getValue('OWL_COMMENTS_VALIDATE', 1);
		$option_arr['OWL_ALLOW_COMMENTS_BY_GUESTS'] = Tools::getValue('OWL_ALLOW_COMMENTS_BY_GUESTS', 1);
		$option_arr['OWL_IMG_SMALL_SIZE'] = Tools::getValue('OWL_IMG_SMALL_SIZE', 270);
		$option_arr['OWL_IMG_SMALL_H_SIZE'] = Tools::getValue('OWL_IMG_SMALL_H_SIZE', 187);
		$option_arr['OWL_IMG_MEDIUM_SIZE'] = Tools::getValue('OWL_IMG_MEDIUM_SIZE', 376);
		$option_arr['OWL_IMG_MEDIUM_H_SIZE'] = Tools::getValue('OWL_IMG_MEDIUM_H_SIZE', 260);
		$option_arr['OWL_IMG_LARGE_SIZE'] = Tools::getValue('OWL_IMG_LARGE_SIZE', 870);
		$option_arr['OWL_IMG_LARGE_H_SIZE'] = Tools::getValue('OWL_IMG_LARGE_H_SIZE', 603);
		$option_arr['OWL_IMG_CATEGORY_SIZE'] = Tools::getValue('OWL_IMG_CATEGORY_SIZE', 870);
		$option_arr['OWL_IMG_CATEGORY_H_SIZE'] = Tools::getValue('OWL_IMG_CATEGORY_H_SIZE', 603);
		$option_arr['BLOCK_CATEG_DHTML'] = Tools::getValue('BLOCK_CATEG_DHTML', 1);
		$option_arr['OWL_NUMBER_TAG_DISPLAYED'] = Tools::getValue('OWL_NUMBER_TAG_DISPLAYED', 10);
		$option_arr['OWL_OP_LASTEST_POST'] = Tools::getValue('OWL_OP_LASTEST_POST', 3);
		$option_arr['OWL_NUMBER_CURRENT_COMMENT'] = Tools::getValue('OWL_NUMBER_CURRENT_COMMENT', 3);
		$option_arr['CATEGORY_RSS_NUMBER'] = Tools::getValue('CATEGORY_RSS_NUMBER', 3);
		return $option_arr;
	}
	
	public static function getCheckboxCatalog($arrCheck, $categories, $current, $id_category = 1, $level, $has_suite = array())
	{
		$done = array();
		static $irow;
		if (!isset($done[$current['infos']['category_parent']]))
			$done[$current['infos']['category_parent']] = 0;
		$done[$current['infos']['category_parent']] += 1;
		if (isset($categories[$current['infos']['category_parent']]))
			$todo = count($categories[$current['infos']['category_parent']]);
		$doneC = $done[$current['infos']['category_parent']];
		if ($id_category != 1)
		{
			$result = '
			<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
				<td>
					<input type="checkbox" name="categoryBox[]" class="categoryBox" id="categoryBox_'.$id_category.'" value="'.$id_category.'"'.(in_array($id_category, $arrCheck) ? ' checked="checked"' : '').'/>
				</td>
				<td>
					'.$id_category.'
				</td>
				<td>';
				for ($i = 2; $i < $level; $i++)
					if (isset($has_suite[$i - 2]))
						$result .= '<img src="../img/admin/lvl_'.$has_suite[$i - 2].'.gif" alt="" />';
				$result .= '<img style="vertical-align:middle" src="../img/admin/'.($level == 1 ? 'lv1.gif' : 'lv2_'.($todo == $doneC ? 'f' : 'b').'.gif').'" alt="" /> &nbsp;
				<label for="categoryBox_'.$id_category.'" class="t">'.Tools::stripslashes($current['infos']['name']).'</label></td>
			</tr>';
		}
		else
			$result = '';
		if ($level > 1)
			$has_suite[] = ($todo == $doneC ? 0 : 1);
		if (isset($categories[$id_category]))
			foreach ($categories[$id_category] as $key => $row)
				if ($key != 'infos')
				{
					$level += 1;
					$result .= self::getCheckboxCatalog($arrCheck, $categories, $categories[$id_category][$key], $key, $level, $has_suite);
				}
		
		return $result;
	}
	public function hookModuleRoutes($params)
	{
		return array(
		'owl_main_url' => array(
			'controller' =>	'categoryPost',
			'params' => array(
				'fc' => 'module',
				'module' => 'owlblog',
			),
			'rule' =>		'{mainlink}.html',
			'keywords' => array(
				'mainlink' =>	array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'mainlink'),
			),
		),
		'owl_category' => array(
			'controller' =>	null,
			'rule' =>		'module/{module}{/:controller}/{rewrite}-{id_owl_blog_category}.html',
			'keywords' => array(
				'module' =>			array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'module'),
				'controller' =>		array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'controller'),
				'id_owl_blog_category' =>				array('regexp' => '[0-9]+', 'param' => 'id_owl_blog_category'),
				'rewrite' =>		array('regexp' => '[_a-zA-Z0-9-\pL]*'),
			),
			'params' => array(
				'fc' => 'module',
			),
		),
		'owl_blog_post' => array(
			'controller' =>	null,
			'rule' =>		'module/{module}{/:controller}/{id_owl_blog_post}-{category_parent}-{rewrite}.html',
			'keywords' => array(
				'module' =>			array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'module'),
				'controller' =>		array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'controller'),
				'category_parent' =>		array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'category_parent'),
				'id_owl_blog_post' =>				array('regexp' => '[0-9]+', 'param' => 'id_owl_blog_post'),
				'rewrite' =>		array('regexp' => '[_a-zA-Z0-9-\pL]*'),
			),
			'params' => array(
				'fc' => 'module',
			),
		),
		'owl_tag' => array(
			'controller' =>	null,
			'rule' =>		'module/{module}{/:controller}/{id_owl_blog_tag}-{name}.html',
			'keywords' => array(
				'module' =>			array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'module'),
				'controller' =>		array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'controller'),
				'id_owl_blog_tag' =>				array('regexp' => '[0-9]+', 'param' => 'id_owl_blog_tag'),
				'name' =>		array('regexp' => '[_a-zA-Z0-9_-]+'),
			), 
			'params' => array(
				'fc' => 'module',
			),
		),
		'owl_rss' => array(
			'controller' =>	null,
			'rule' =>		'module/{module}{/:controller}/{idrss}.html',
			'keywords' => array(
				'module' =>			array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'module'),
				'controller' =>		array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'controller'),
				'idrss' =>				array('regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'idrss')
			), 
			'params' => array(
				'fc' => 'module',
			),
		)
		);
	}
	public function getTree($resultParents, $resultIds, $maxDepth, $id_category = 1, $currentDepth = 0)
	{
		$children = array();
		if (isset($resultParents[$id_category]) && count($resultParents[$id_category]) && ($maxDepth == 0 || $currentDepth < $maxDepth))
			foreach ($resultParents[$id_category] as $subcat)
				$children[] = $this->getTree($resultParents, $resultIds, $maxDepth, $subcat['id_owl_blog_category'], $currentDepth + 1);
		if (!isset($resultIds[$id_category]))
			return false;
		return array('id' => $id_category, 'link' => $this->owlLink->getCategoryPostLink($id_category, $resultIds[$id_category]['link_rewrite']),
			'name' => $resultIds[$id_category]['name'],
			'desc' => '',
			'children' => $children,
			'link_rewrite' => $resultIds[$id_category]['link_rewrite']);
	}
	public static function getLastestPost($id_lang = null, $id_shop = null, $post_length = 4, $img = 'medium')
	{
		$posts = Db::getInstance()->ExecuteS('
			SELECT ps.*,pl.*,p.* FROM '._DB_PREFIX_.'owl_blog_post p
			INNER JOIN '._DB_PREFIX_.'owl_blog_post_lang pl
			ON (p.id_owl_blog_post=pl.id_owl_blog_post AND pl.id_lang = '.$id_lang.' AND pl.id_shop = '.$id_shop.')
			INNER JOIN '._DB_PREFIX_.'owl_blog_post_shop ps
			ON (p.id_owl_blog_post=ps.id_owl_blog_post AND ps.id_shop = '.$id_shop.')
			WHERE ps.active = 1
			ORDER BY p.date_add DESC
			LIMIT 0, '.$post_length.'
		');
		$posts_new = array();
		$postObj = new OWLPost();
		foreach ($posts as $post)
		{
			$post['date_add'] = $postObj->formatDateAdd($post['date_add']);
			$author = new Employee($post['author']);
			$post['author'] = $author->firstname.' '.$author->lastname;
			$postOb = new OWLPost($post['id_owl_blog_post']);
			$post['count_comment'] = $postOb->getCountComment($id_lang, $id_shop);
			$link = new OWLLink();
			$post['link'] = $link->getLinkPostDetail($post['id_owl_blog_post'], $post['link_rewrite'], $post['id_owl_blog_category']);
			
			$save_path = _PS_MODULE_DIR_.'owlblog/views/img/media/posts/src/'.$post['id_owl_blog_post'];
			$url_path = 'views/img/media/posts/cache/'.$post['id_owl_blog_post'].'_'.$id_shop;
			if (file_exists($save_path.'.jpg'))
				$post['image'] = $url_path.'_'.$img.'.jpg';
			else
				$post['image'] = 'views/img/media/posts/cache/no_image_'.$img.'.jpg';
			$posts_new[] = $post;
		}
		return $posts_new;
	}
	public function getCurrentComments($id_lang = null, $id_shop = null, $nb = 5)
	{
		$comments = Db::getInstance()->ExecuteS('
			SELECT c.*,cl.* FROM '._DB_PREFIX_.'owl_blog_comment c
			INNER JOIN '._DB_PREFIX_.'owl_blog_comment_lang cl
			ON (c.id_owl_blog_comment = cl.id_owl_blog_comment AND cl.id_lang = '.$id_lang.')
			WHERE c.id_shop = '.$id_shop.' AND c.active = 1
			ORDER BY c.date_add DESC
			LIMIT 0, '.$nb.'
		');
		$result = array();
		$postObj = new OWLPost();
		foreach ($comments as $comment)
		{
			$post_comment = new OWLPost($comment['id_owl_blog_post']);
			$comment['date_add'] = $postObj->formatDateAdd($comment['date_add']);
			$comment['name_post'] = $post_comment->name[$id_lang];
			$comment['link_post'] = $this->owlLink->getLinkPostDetail($post_comment->id_owl_blog_post, $post_comment->link_rewrite[$id_lang], $post_comment->id_owl_blog_category);
			$imep = 'medium';
			if ($imep != 'none')
			{
					$save_path = _PS_MODULE_DIR_.'owlblog/views/img/media/posts/src/'.$post_comment->id_owl_blog_post;
					$url_path = 'views/img/media/posts/cache/'.$post_comment->id_owl_blog_post.'_'.$id_shop;
					if (file_exists($save_path.'.'.$this->imageType))
						$comment['image_post'] = $url_path.'_'.$imep.'.'.$this->imageType;
			}
			$result[] = $comment;
		}
		return $result;
	}
	public function getContentForHook()
	{
		$id_lang = $this->context->language->id;
		$id_shop = $this->context->shop->id;
		$this->context->smarty->assign('owl_path', $this->_path);
		$options_str = Configuration::get('OWL_BLOG_CONFIG');
		$options_arr = Tools::jsonDecode($options_str, 1);
		/*get categories*/
		
		$result = $this->getCategories($id_lang, $id_shop);
		$resultParents = array();
		$resultIds = array();
		foreach ($result as &$row)
		{
			$resultParents[$row['category_parent']][] = &$row;
			$resultIds[$row['id_owl_blog_category']] = &$row;
		}
		$block_categ_tree = $this->getTree($resultParents, $resultIds, 4);
		unset($resultParents);
		unset($resultIds);
		$is_dhtml = ($options_arr['BLOCK_CATEG_DHTML'] == 1 ? true : false);
		$id_owl_blog_category = Tools::getValue('id_owl_blog_category');
		$id_owl_blog_post = Tools::getValue('id_owl_blog_post');
		if (Tools::isSubmit('id_owl_blog_category'))
		{
			$this->context->cookie->last_visited_blog_category = $id_owl_blog_category;
			$this->context->smarty->assign('id_owl_blog_category_current', $this->context->cookie->last_visited_blog_category);
		}
		if (Tools::isSubmit('id_owl_blog_post'))
		{
			$this->context->cookie->last_visited_blog_category = Tools::getValue('category_parent');
			$this->smarty->assign('id_owl_blog_category_current', (int)$this->context->cookie->last_visited_blog_category);
		}
		$this->context->smarty->assign('owl_blockCategTree', $block_categ_tree);
		if (file_exists(_PS_THEME_DIR_.'modules/owlblog/views/templates/hook/blockcategories.tpl'))
			$this->context->smarty->assign('owl_branche_tpl_path', _PS_THEME_DIR_.'modules/blockcategories/category-tree-branch.tpl');
		else
			$this->context->smarty->assign('owl_branche_tpl_path', _PS_MODULE_DIR_.'owlblog/views/templates/hook/category-tree-branch.tpl');
		$this->context->smarty->assign('owl_isDhtml', $is_dhtml);
		
		/*get post lastest*/
		$lastest_posts = OWLBlog::getLastestPost($id_lang, $id_shop, $options_arr['OWL_OP_LASTEST_POST'], 'small');
		$this->context->smarty->assign('lastest_posts', $lastest_posts);
		$this->context->smarty->assign('owl_image_size_relate_posts', 'small');
		$this->context->smarty->assign('OWL_SHOW_BLOCK_LASTEST', 1);
		/*get tags*/
		$tags = $this->getMainTags($id_lang, $id_shop, $options_arr['OWL_NUMBER_TAG_DISPLAYED']);
		$this->context->smarty->assign('tags', $tags);
		/*get comments current*/ 
		$nb = $options_arr['OWL_NUMBER_CURRENT_COMMENT'];
		$comments = $this->getCurrentComments($id_lang, $id_shop, $nb);
		$this->context->smarty->assign('blockcomments', $comments);
	}
	public function getMainTags($id_lang = null, $id_shop = null, $nb = 10)
	{
		$tags = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
		SELECT t.name,t.id_owl_blog_tag, COUNT(pt.id_owl_blog_tag) AS times
		FROM `'._DB_PREFIX_.'owl_blog_post_tag` pt
		LEFT JOIN `'._DB_PREFIX_.'owl_blog_tag` t ON (t.id_owl_blog_tag = pt.id_owl_blog_tag)
		LEFT JOIN `'._DB_PREFIX_.'owl_blog_post` p ON (p.id_owl_blog_post = pt.id_owl_blog_post )
		WHERE t.`id_lang` = '.$id_lang.' AND (pt.id_owl_blog_post IN (SELECT ps.id_owl_blog_post FROM '._DB_PREFIX_.'owl_blog_post_shop ps WHERE ps.id_shop = '.$id_shop.')) 
		GROUP BY t.id_owl_blog_tag
		ORDER BY times DESC
		LIMIT 0, '.$nb);
		$tags_new = array();
		foreach ($tags as $tag)
		{
			$tag['link'] = $this->owlLink->getTagLink($tag['id_owl_blog_tag'], $tag['name']);
			$tags_new[] = $tag;
		}
		return $tags_new;
	}
	public function hookActionShopDataDuplication($params)
	{
		/* duplicate category for shop */
		Db::getInstance()->execute('
		INSERT IGNORE INTO '._DB_PREFIX_.'owl_blog_category_shop (id_owl_blog_category, id_shop, position)
		SELECT id_owl_blog_category, '.$params['new_id_shop'].', position
		FROM '._DB_PREFIX_.'owl_blog_category_shop
		WHERE id_shop = '.$params['old_id_shop']);
		Db::getInstance()->execute('
		INSERT IGNORE INTO '._DB_PREFIX_.'owl_blog_category_lang (id_owl_blog_category, id_lang, id_shop, name, description, meta_title, meta_description, meta_keywords, link_rewrite)
		SELECT id_owl_blog_category, id_lang, '.$params['new_id_shop'].', name, description, meta_title, meta_description, meta_keywords, link_rewrite
		FROM '._DB_PREFIX_.'owl_blog_category_lang
		WHERE id_shop = '.$params['old_id_shop']);
		Db::getInstance()->execute('
		INSERT IGNORE INTO '._DB_PREFIX_.'owl_blog_post_shop (id_owl_blog_post, id_shop, id_owl_blog_category,id_shop_default, date_add, position, active, related_posts, related_products)
		SELECT id_owl_blog_post, '.$params['new_id_shop'].', id_owl_blog_category, id_shop_default, date_add, position, active, related_posts, related_products
		FROM '._DB_PREFIX_.'owl_blog_post_shop
		WHERE id_shop = '.$params['old_id_shop']);
		Db::getInstance()->execute('
		INSERT IGNORE INTO '._DB_PREFIX_.'owl_blog_post_lang (id_owl_blog_post, id_lang, id_shop, name, description, meta_title, meta_description, meta_keywords, link_rewrite)
		SELECT id_owl_blog_post, id_lang, '.$params['new_id_shop'].', name, description, meta_title, meta_description, meta_keywords, link_rewrite
		FROM '._DB_PREFIX_.'owl_blog_post_lang
		WHERE id_shop = '.$params['old_id_shop']);
	}
	public function hookDisplayLeftColumn()
	{
		$this->getContentForHook();
		return $this->display(__FILE__, 'views/templates/hook/columnleft.tpl');
	}
	public function hookDisplayRightColumn()
	{
		$this->getContentForHook();
		return $this->display(__FILE__, 'views/templates/hook/columnleft.tpl');
	}
	public function hookHeader($params)
	{		
		$this->context->controller->addCSS($this->_path.'views/css/owlblogstyle.css');
	}
	public function hookdisplayBackOfficeHeader($params)
	{
		$this->context->controller->addCSS($this->_path.'views/css/admin/owlblog.css');
	}
}