<?php
/*
	Stempora web framework
	copyright (c) 2002-2014 Stempora
		web:  www.stempora.com
		mail: support@stempora.com

	$Id: blog/site.php,v 1.0 3/16/2014  11:00:00 stempora Exp $
	description
*/

// dependencies

/**
* description
*
* @library	
* @author Emanuel Giurgea ( emanuel@stempora.com )
* @since 
*/
class CBlog extends CPlugin{
	
	var $tplvars; 

	function CBlog() {
		$this->name = "blog";
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;

		parent::DoEvents();

		if ($_GET["mod"] == $this->name) {


			$this->__init();
			$this->plugins["globalhooks"]->SetModule($this->tpl_module);
			$this->LoadLabels();

			$this->plugins["seo"]->AppendToHead('<link rel="alternate" type="application/rss+xml" title="' . $this->tpl_module["settings"]["set_rss_title"] . '" href="' . $this->tpl_module["link"] .'rss" />');

			switch ($_GET["sub"]) {
				case "topics":
				case "search":
				case "label":
				case "archive":
				case "author":
					return $this->Topics();
				break;

				case "topic":
					return $this->Topic();
				break;

				case "rss":
					return $this->Rss();
				break;


				
			}
		}
		
	}

	function __init() {
		global $_CONF;

		if ($this->__inited) {
			return "";
		}

		$this->__inited = true;
		
		$path = $this->tpl_path;

		$templates = array(
			"topic"					=> "topic.htm",
			"list"					=> "topics.htm",

			"image"					=> "image.htm",

			"author"				=> "author.htm",

			"widget.archive"		=> "widget.archive.htm",
			"widget.author"			=> "widget.author.htm",
			"widget.authors"		=> "widget.authors.htm",
			"widget.comments"		=> "widget.comments.htm",
			"widget.labels"			=> "widget.labels.htm",
			"widget.search"			=> "widget.search.htm",
			"widget.topics"			=> "widget.topics.htm",

			"rss"					=> "rss.xml",

		);

		foreach ($templates as $key => $val) {
			$this->private->templates[$key] = new CTemplateDynamic(
				$path . $val
			);
		}

		$this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo();
	} 
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Topics() {

		global $base;

		$text = $this->GetTexts();
		$meta = $this->GetTopicsMeta();


		if ($meta["error"]) {
			return $this->module->plugins["redirects"]->ErrorPage("404" , true);
		}
		

		$items = $this->GetItems(array(
			"items"		=> $this->tpl_module["settings"]["set_ipp_items"] , 
			"page"		=> $_GET["page"],
			"cond"		=> $meta["cond"],
		));


		$this->module->plugins["breadcrumb"]->Add(
			array(
				"title"		=> $text["text_title"],
				"subtitle"	=> $text["text_subtitle"],
				"show"		=> $text["text_status"],
			),
			array(
				$this->tpl_module["link"]	=> $this->tpl_module["mod_name"],
				$meta["link_first"]	=> $meta["title"],	
			),
			$this->tpl_module["mod_protected"],
			$this->tpl_module
		);

		$items["records"] = $this->ProcessItems($items["records"] , $items , $meta["cond"]);

		$template = &$this->private->templates["list"];

		return $this->module->plugins["layouts"]->Render(
			$this->plugins["layouts"]->Detect(
				$meta["layout"],
				$this->tpl_module["mod_protected"]
			),
			$template->blockREplacE(
				"Main" , 
				array(

					"items"	=> $base->html->Table(
						$template, 
						"" , 
						$items["records"]
					),

					"paging"	=> $this->module->plugins["paging"]->Paging(
						$items["pages"] , 
						$items["page"] , 
						array(
							"first"	=> $meta["link_first"] ,
							"all"	=> $meta["link_all"],
						),
						$items["items"]
					),

					"title"			=> $meta["title"],
					"description"	=> $meta["description"],

				),
				$this->tpl_module["settings"]		
			)
		);
	}	


	function GetItems($params = array()) {
		global $_SESS;
	
		$count	= max(1,$params["items"]);
		$page	= $params["page"];

		$order		= "item_date";
		$order_mode = "desc";
		$fields = "*";

		$cond = " c.item_id=l.item_id AND l.lang_id={$this->tpl_module[lang_id]} AND c.module_id={$this->tpl_module[mod_id]} AND item_status=1 AND item_date <= timestamp(now()) AND c.item_author=a.author_id " . $params["cond"] . " ";

		if (!$_SESS["client"]) {
			$cond .= " AND  item_protect=0 ";
		} 


		if ($_GET["q"]) {
			
			$fields = $this->db->Statement("
				* , 
				MATCH (`item_title`, `item_body` ) AGAINST ('%s' IN BOOLEAN MODE) AS relevance", 
				array($_GET["q"] , $_GET["q"])
			);

			$cond .=  $this->db->Statement( " AND MATCH (item_title , `item_body` ) AGAINST ('%s' IN BOOLEAN MODE) " , array($_GET["q"]));
			$order_mode = "";
			$order = "relevance DESC";
		
		}
		
		

		$item_count = $this->db->RowCount(
			"	{$this->tables['plugin:blog_topics']} as c,
				{$this->tables['plugin:blog_authors']} as a,
				{$this->tables['plugin:blog_topics_lang']} as l
			",
			"	WHERE {$cond}"
		);

		if (!$page && $item_count) {
			$page = 1;
		} else 
			$page = max(1,(int)$page);

		$items = $this->db->QFetchRowArray(
			"SELECT {$fields} " . 
			"FROM 
				{$this->tables['plugin:blog_topics']} as c,
				{$this->tables['plugin:blog_topics_lang']} as l,
				{$this->tables['plugin:blog_authors']} as a

			WHERE 				
				{$cond}
			ORDER BY  {$order} {$order_mode} 
			LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count 
		);

		return array(
			"records"	=> $items, 
			"count"		=> $item_count , 
			"pages"		=> $item_count ? ceil($item_count / $count) : 1,
			"page"		=> $page,

			"ipp"		=> $count
		);

	}

	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessItems($items , $category) {
		global $base;


		if (is_array($items)) {

			$template = &$this->private->templates["list"];

			foreach ($items as $key => $val) {

				$val["link"] = $items[$key]["link"] = $this->tpl_module["link"] . $val["item_url"] . "/" . $val["item_id"] ;
				$val["module_link"] = $this->tpl_module["link"];

				$items[$key]["author"] = $template->blockReplace(
					"Author" .( $val["author_details"] == "1" ? "Link" : ""), 
					$val
				);

				if ($this->tpl_module["settings"]["set_comments"] > 0) {
					$val["item_stats_comments"] = $this->plugins["comments"]->CommentsCount(
						$this->tpl_module["settings"]["set_comments"],
						$val["link"],
						$val["item_stats_comments"]
					);

					$items[$key]["topic_comments"] = $template->blockReplace("Comments" , $val);
				} else {
					$items[$key]["topic_comments"] = "";
				}

				$items[$key]["social_links"] = $this->plugins["socialmedia"] ? $this->plugins["socialmedia"]->Share($val["link"]) : "";
				
				
				$items[$key]["img"] = $this->ItemImage($val , "list");
								
				$items[$key]["date"] = CDate::ToStr("M jS Y" ,$val["item_date"]);
				$items[$key]["time"] = CDate::ToStr("G:i" ,$val["item_date"]);
				$items[$key]["cats"] = "";

				$items[$key]["day"] = CDate::ToStr("d" ,$val["item_date"]);
				$items[$key]["month_3"] = CDate::ToStr("M" ,$val["item_date"]);
				$items[$key]["month"] = CDate::ToStr("F" ,$val["item_date"]);
				$items[$key]["year"] = CDate::ToStr("Y" ,$val["item_date"]);;



				if ($val["item_labels"]) {

					$tmp = explode("," , $val["item_labels"]);

					$cats = array();
					$_cats = array();

					foreach ($this->labels as $k => $v) {
						if (in_array($v["label_id"] , $tmp)) {
							$_cats[] = $v;
						}					
					}

					$cats = $_cats;
					
					/*
					foreach ($tmp as $k => $v) {
						if ($this->labels[$v]) {
							$cats[] = $this->labels[$v];
						}
						
					}*/
				

					if (is_array($cats) && count($cats)) {
						$items[$key]["cats"] = $template->blockreplace(
							"Cats" , 
							array(
								"data"	=> $base->html->table(
									$template,
									"Cats",
									$cats
								)
							)
						);
					}
					
				}
				
				
			}
			
		}
		

		return $items;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ItemImage($item , $type) {
		global $_LANG_ID;

		$template = &$this->private->templates["image"];

		switch ($type) {
			case "list":

				if (!$item["item_image"]) {
					return "";
				}

				if ($item["item_image"] == "1") {

					$items = $this->db->QFetchROwArray(
						"
						SELECT * FROM 
							{$this->tables['plugin:blog_images']} as r,
							{$this->tables['plugin:blog_images_lang']} as l
						WHERE
							r.item_id = l.item_id AND 
							r.item_parent = {$item['item_id']} AND 
							l.lang_id = {$_LANG_ID} 
						ORDER BY 
							item_order ASC
						LIMIT 
							1
						"
					);
				} else {
					$items = $this->db->QFetchROwArray(
						"
						SELECT * FROM 
							{$this->tables['plugin:blog_images']} as r,
							{$this->tables['plugin:blog_images_lang']} as l
						WHERE
							r.item_id = l.item_id AND 
							r.item_parent = {$item['item_id']} AND
							l.lang_id = {$_LANG_ID} 
						ORDER BY 
							item_order ASC
						"
					);
				}								
			break;

			case "details":

				if (!$item["item_image_details"]) {
					$items = $this->db->QFetchROwArray(
						"
						SELECT * FROM 
							{$this->tables['plugin:blog_images']} as r,
							{$this->tables['plugin:blog_images_lang']} as l
						WHERE
							r.item_id = l.item_id AND 
							r.item_parent = {$item['item_id']} AND
							l.lang_id = {$_LANG_ID} 

						ORDER BY 
							item_order ASC
						"
					);
				}

				
			break;
		}
		


		if (!is_array($items)) {
			return "";
		}

		if (count($items) == 1) {
			//simple image / video / youtube



			switch ($items[0]["item_type"]) {

				//image
				case "1":
					$return  = $template->BlockReplace(
						"Image" , 
						$items[0],
						array(
							"title"	=> $items[0]["item_title"] ? $template->blockReplace("Title" , $items[0]) : ""
						)
					);
				break;

				//youtube
				case "2":
					$return  = $template->BlockReplace(
						"Youtube" , 
						$items[0]
					);
				break;

				//vimeo
				case "3":
					$return  = $template->BlockReplace(
						"Vimeo" , 
						$items[0]
					);
				break;

				//audio
				case "4":
					$return  = $template->BlockReplace(
						"Audio" , 
						$items[0]
					);
				break;

			}
			
		} else {

			switch ($type) {
				case "list":
					if ($item["item_image"] == "3") {
						$pref = "GalleryType";
					} else {
						$pref = "SliderType";
					}					
				break;

				case "details":
					if ($item["item_image_details"] == "2") {
						$pref = "GalleryType";
					} else {
						$pref = "SliderType";
					}					
				break;
			}
			
			$pref = "SliderType";

			global $base;

			foreach ($items as $key => $val) {

				switch ($val["item_type"]) {
					case "1": 
						$items[$key]["content"] = $template->blockReplace("SliderImage" , $val); 
//						$items[$key]["tn"] = $template->blockReplace("SliderImageTn" , $val); 
					break;
					case "2": 
						$items[$key]["content"] = $template->blockReplace("SliderYoutube" , $val); 
//						$items[$key]["tn"] = $template->blockReplace("SliderYoutubeTn" , $val); 
					break;
					case "3": 
						$items[$key]["content"] = $template->blockReplace("SliderVimeo" , $val); 
//						$items[$key]["tn"] = $template->blockReplace("SliderVimeoTn" , $val); 
					break;
					case "4": 
						$items[$key]["content"] = $template->blockReplace("SliderAudio" , $val); 
//						$items[$key]["tn"] = $template->blockReplace("SliderAudioTn" , $val); 
					break;						
				}				
			}
			

			$return  = $template->blockReplace(
				"Slider",
				array(
					"content"	=> 				$base->html->Table(
							$template , 
							"Slider" , 
							$items
					),

					"thumbs"	=> $pref == "GalleryType" ? $base->html->Table(
							$template , 
							"Thumbs",
							$items 
					) : "",
				),
				array(
					"count"		=> count($items),
					"slider"	=> $item["item_id"],
					"pref"		=> $template->blockReplace($pref)
				)
			);
		}


		if ($return) {

			return  CTemplateStatic::Replace(
				$return,
				array(
					"link"	=> $item["link"],
				)
			);

		}
		
	
				
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Topic() {
		global $base , $_SESS;

		//first table must be the author as the seo fiels will be overwritted by the blog.
		$topic = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['plugin:blog_authors']} as a , 
				{$this->tables['plugin:blog_authors_lang']} as al , 
				{$this->tables['plugin:blog_topics']} as t , 
				{$this->tables['plugin:blog_topics_lang']} as tl 
				
			WHERE
				t.item_id = tl.item_id AND 
				tl.lang_id = {$this->tpl_module[lang_id]} AND 
				a.author_id = al.author_id AND 
				t.item_author=a.author_id AND 
				al.lang_id = {$this->tpl_module[lang_id]} AND 
				t.module_id = {$this->tpl_module[mod_id]} AND
				t.item_id = %d AND

				t.item_status = 1 AND 
				t.item_date <= timestamp(now())  
				" . ( $_SESS["client"] ? "" : " AND item_protect=0 ") . "

			",
			array($_GET["topic"])
		);


		if (!is_array($topic)) {
			return $this->module->plugins["redirects"]->ErrorPage("404" , true);
		}

		//update the topic views
		$this->db->QueryUpdate(
			$this->tables["plugin:blog_topics"],
			array(
				"item_stats_views"	=> $topic["item_stats_views"] + 1
			),
			"item_id={$topic[item_id]}"
		);

		//process the link 
		$topic["link"] = $this->tpl_module["link"] . $topic["item_url"] . "/" . $topic["item_id"];



		$text = $this->GetTexts();


		$this->module->plugins["breadcrumb"]->Add(
			array(
				"title"	=> $text["text_title"],
				"subtitle"	=> $text["text_subtitle"],
				"show"		=> $text["text_status"],
			),				
			array(
				$this->tpl_module["link"]	=> $this->tpl_module["mod_name"],
				$topic["link"]	=> $topic["item_title"],	
			),
			$this->tpl_module["mod_protected"],
			$this->tpl_module
		);



		$topic["author_link"] = $this->tpl_module["link"] . "authors/" . $topic["author_url"] . "/" ;
		$topic["image"] = $this->ItemImage($topic , "details");
		$topic["social_links"] = $this->plugins["socialmedia"] ? $this->plugins["socialmedia"]->Share($topic["link"]) : "";

		$topic["date"] = CDate::ToStr("M jS Y" ,$topic["item_date"]);
		$topic["time"] = CDate::ToStr("G:i" ,$topic["item_date"]);
		$topic["zone"] = CDate::ToStr("A T" ,$topic["item_date"]);

		$topic["day"] = CDate::ToStr("d" ,$topic["item_date"]);
		$topic["month_3"] = CDate::ToStr("M" ,$topic["item_date"]);
		$topic["month"] = CDate::ToStr("F" ,$topic["item_date"]);
		$topic["year"] = CDate::ToStr("Y" ,$topic["item_date"]);;

		$topic["back_link"] = $this->tpl_module["link"];



		if ($topic["item_comments"]) {
			$topic["comments"] = $this->module->plugins["comments"]->Comments(
				$topic["link"],
				$this->tpl_module["settings"]["set_comments"],
				!$topic["item_comments_new"],
				array(
					"module"	=> $this->tpl_module["mod_id"],
					"reserved"	=> $topic["item_id"],
				)
			);
		} else {
			$topic["comments"] = "";
		}

		
		$template = &$this->private->templates["topic"];

		$topic["author"] = $template->blockReplace(
			"Author" .( $topic["author_details"] == "1" ? "Link" : ""), 
			$topic
		);


		//process categories
		$topic["cats"] = "";

		if ($topic["item_labels"]) {

			$tmp = explode("," , $topic["item_labels"]);

			$cats = array();
			$_cats = array();


			foreach ($this->labels as $k => $v) {
				if (in_array($v["label_id"] , $tmp)) {
					$_cats[] = $v;
				}					
			}

			$cats = $_cats;
							

			if (is_array($cats) && count($cats)) {
				$topic["cats"] = $template->blockreplace(
					"Cats" , 
					array(
						"data"	=> $base->html->table(
							$template,
							"Cats",
							$cats
						)
					)
				);
			}
			
		}


		//process the author box
		if ($topic["item_author_box"]) {


			$topic["author_box"] = $this->private->templates["author"]->blockReplace(
				"Author" , 
				$topic , 
				array(
					"title"	=> $this->private->templates["author"]->blockReplace($topic["author_details"] ? "TitleLink" : "TitleNoLink" , $topic),
					"photo"		=> $this->private->templates["author"]->blockReplace(
						$topic["author_image"] ? "Image" : "NoImage",
						$topic
					)
				)
			);
		} else {
			$topic["author_box"] = "";
		}
		

		$this->plugins["seo"]->PageMeta($topic);


		return $this->module->plugins["layouts"]->Render(
			$this->plugins["layouts"]->Detect(
				$this->tpl_module["settings"]["set_layout_topic"],
				$this->tpl_module["mod_protected"]
			),
			$template->blockREplacE(
				"Main" , 
				$topic,
				array(
				),
				$this->tpl_module["settings"]		
			)
		);


	}

		
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function LoadLabels() {
		global $_LANG_ID;

		$labels = $this->db->QFetchRowArray(
			"SELECT 
				*
			FROM 
				{$this->tables['plugin:blog_labels']} as b ,
				{$this->tables['plugin:blog_labels_lang']} as l
			WHERE
				b.label_id=l.label_id AND 
				l.lang_id={$_LANG_ID} AND 
				label_status = 1 AND 
				b.module_id = {$this->tpl_module[mod_id]}
		
			ORDER BY 
				label_order ASC
			"
		);

		if (is_array($labels)) {

			foreach ($labels as $key => $val) {

				$val["link"] = $this->tpl_module["link"] . $val["label_url"] . "/";

				if ($val["label_all"]) {
					$val["link"] = $this->tpl_module["link"];

					$this->default_label = $val;
				} else {
					$val["link"] = $this->tpl_module["link"] . $val["label_url"] . "/";
				}
												
				$this->labels[$val["label_id"]] = $val;
			}
		}

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetTopicsMeta() {

		switch ($_GET["sub"]) {

			//latest
			case "topics":

				$text = $this->GetTexts();


				$this->plugins["seo"]->PageMeta(
					$text
				);

				return array(
					"link_first"	=> $this->tpl_module["link"],
					"link_all"		=> $this->tpl_module["link"] . "p{PAGE}/",
					"description"	=> $text["text_header"],
					"layout"		=> $this->tpl_module["settings"]["set_layout"],
					"cond"			=> "",
				);

				
			break;

			case "label":

				if (is_array($this->labels)) {
					foreach ($this->labels as $key => $val) {
						if ($val["label_url"] == $_GET["label"]) {
							$label = $val;
						}						
					}					
				}

				if (!is_array($label)) {
					$error = true;
				}
				

				$this->plugins["seo"]->PageMeta(
					$label
				);

				return array(
					"title"			=> $label["label_page_title"],
					"link_first"	=> $label["link"],
					"link_all"		=> $label["link"] . "p{PAGE}/",

					"layout"		=> $this->tpl_module["settings"]["set_layout"],
					"error"			=> $error,

					"description"	=> $label["label_desc"],
					"cond"			=> " AND find_in_set({$label['label_id']} , item_labels ) " 

				);

			break;

			case "search":

				$this->plugins["seo"]->PageMeta(
					array(
						"seo_title"	=> CTemplateStatic::Replace(
							$this->tpl_module["settings"]["lang_search"],
							array(
								"q"		=> urldecode($_GET["q"]),
								"page"	=> $_GET["page"]
							)
						),
						"seo_desc"	=> ""
					)
				);

				$this->plugins["seo"]->AppendToHead("<meta name=\"robots\" content=\"noindex,nofollow\">");

				return array(
					"title"	=> CTemplateStatic::Replace(
						$this->tpl_module["settings"]["lang_search"],
						array(
							"q"		=> urldecode($_GET["q"]),
							"page"	=> $_GET["page"]
						)
					),

					"layout"		=> $this->tpl_module["settings"]["set_layout_search"],
					"link_first"	=> $this->tpl_module["link"] . "search/?q=" . $_GET["q"],
					"link_all"	=> $this->tpl_module["link"] . "search/?q=" . $_GET["q"] . "&page={PAGE}",
				);

			break;

			case "archive":
				//do the checks here 

				$this->plugins["seo"]->AppendToHead("<meta name=\"robots\" content=\"noindex,nofollow\">");

				$month = (int)$_GET["month"];
				$year = (int)$_GET["year"];

				if (!(($month >= 1 ) && ($month <= 12)) ) {
					$error = true;
				}
							
				$this->plugins["seo"]->PageMeta(
					array(
						"seo_title"	=> CDate::ToLangMonth((int)$_GET["month"]) . " " . $_GET["year"],
						"seo_desc"	=> ""
					)
				);

				return array(
					"title"	=> CDate::ToLangMonth((int)$_GET["month"]) . " " . $_GET["year"]/*CTemplateStatic::Replace(
						$this->tpl_module["settings"]["lang_archive" . ($_GET["page"] <= 1 ? "" : "_page") ],
						array(
							"month"			=> $_GET["month"],
							"year"			=> $_GET["year"],
							"month_lang"	=> CDate::ToLangMonth((int)$_GET["month"]),
							"page"			=> $_GET["page"]
						)
					)*/,

					"link_first"	=> $this->tpl_module["link"] . "{$_GET[month]}-{$_GET[year]}/",
					"link_all"	=> $this->tpl_module["link"] . "{$_GET[month]}-{$_GET[year]}/p{PAGE}/",

					"layout"		=> $this->tpl_module["settings"]["set_layout_archive"],
					"error"			=> $error,

					"cond"	=> " AND item_date_month = {$month}  AND item_date_year = {$year} ",
				);
			break;


			case "author":
				//do the checks here 
				$author = $this->db->QFetchArray(
					"SELECT * FROM 
						{$this->tables['plugin:blog_authors']} as a,
						{$this->tables['plugin:blog_authors_lang']} as al
					WHERE
						a.author_id = al.author_id AND 
						al.lang_id = {$this->tpl_module[lang_id]} AND 
						a.author_url LIKE '%s'
					",
					array($_GET["author"])
				);

				if (!is_array($author)) {
					$error = true;

					$this->plugins["seo"]->PageMeta(
						$author
					);


					$author["author_link"] = $author["link"] = $this->tpl_module["link"] . "authors/{$author[author_url]}/";

				} 

				$this->plugins["seo"]->PageMeta($author);


				$template = &$this->private->templates["author"];
										
				return array(
					"title"	=> $author["author_name"],

					"error"			=> $error,

					"layout"		=> $this->tpl_module["settings"]["set_layout_author"],
					"link_first"	=> $this->tpl_module["link"] . "authors/{$author[author_url]}/",
					"link_all"		=> $this->tpl_module["link"] . "authors/{$author[author_url]}/p{PAGE}/",

					"header"		=> $template->blockReplace(
						"Main" ,
						$author , 
						array(
							"image"			=> $template->blockReplace($author["author_image"] ? "Image" : "NoImage" , $author),
							"social_links"	=> $this->plugins["socialmedia"] ? $this->plugins["socialmedia"]->Share($author["link"]) : "",	
						)
					),

					"cond"	=> " AND item_author= {$author[author_id]}  ",
				);
			break;

		}
		
	}



	/* WIDGETS AREA */

	function Widget($widget) {

		$this->__init();
		

		switch ($widget["widget_type"]) {

			//labels
			case "1":				
				//return $this->widgetNews($widget);
				return $this->widgetLabels($widget);
			break;

			//topics
			case "2":				
				return $this->widgetTopics($widget);
			break;

			//latest comments
			case "3":				
				return $this->widgetComments($widget);
			break;

			//search box
			case "6":				
				return $this->widgetSearch($widget);
			break;

			//archive
			case "7":				
				return $this->widgetArchive($widget);
			break;

			//authors
			case "9":				
				return $this->widgetAuthors($widget);
			break;

			//single author
			case "10":				
				return $this->widgetAuthor($widget);
			break;

		}
	}


	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetLabels($widget) {
		global $_LANG_ID , $base;

		$labels = $this->db->QFetchRowArray(
			"SELECT 
				*
			FROM 
				{$this->tables['plugin:blog_labels']} as b ,
				{$this->tables['plugin:blog_labels_lang']} as l
			WHERE
				b.label_id=l.label_id AND 
				l.lang_id={$widget[lang_id]} AND 
				label_status = 1 AND 
				b.module_id = {$widget[widget_module]}
		
			ORDER BY 
				label_order ASC
			"
		);

		$all = array(
			"label_status"		=> "1",
			"label_all"			=> "1",
			"label_title"		=> $widget["mod_settings"]["lang_all_topics"],
			"label_items"		=> "",
		);

		array_unshift($labels , $all);

		if (is_array($labels)) {

			foreach ($labels as $key => $val) {
				
				$labels[$key]["link"] = $widget["link"] . ($val["label_all"] ? "" : $val["label_url"] . "/");

				if ($val["label_id"]) {				
					$labels[$key]["label_items"] = $this->db->RowCount(
							$this->tables["plugin:blog_topics"],
							"WHERE find_in_set( {$val[label_id]}, item_labels ) AND item_status=1 AND item_date <= timestamp(now()) "
					);
				}
			}


			$template = $this->private->templates["widget.labels"];

			return $template->blockreplace(
				"Main" , 
				array(
					"labels"	=> $base->html->Table(
						$template , 
						"", 
						$labels
					),

					"widget_title"	=> $widget["widget_name"],
				),

				$widget["mod_settings"]
			);

		}

		return "";		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetTopics($widget) {
		global $_SESS;

		$this->__init();

		$cnt = max(1, $widget["settings"]["set_items"]);

		switch ($widget["settings"]["set_type"]) {
			//latest
			case "1":
				$order = "item_date DESC";
			break;

			//most viewed
			case "2":
				$order = "item_set_views DESC , item_date DESC";
			break;
		}
		

		$items = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['plugin:blog_topics']} as t , 
				{$this->tables['plugin:blog_topics_lang']} as l ,
				{$this->tables['plugin:blog_authors']} as a , 
				{$this->tables['plugin:blog_authors_lang']} as al 

			WHERE 
				t.item_author=a.author_id AND 
				a.author_id = al.author_id AND 
				al.lang_id = l.lang_id AND 
				t.module_id = {$widget[mod_id]} AND 
				l.lang_id={$widget[lang_id]} AND 
				t.item_id=l.item_id AND
				t.item_status = 1 AND 
				t.item_date <= timestamp(now()) 
				" . ( $_SESS["client"] ? "" : " AND item_protect=0 ") . "

			ORDER BY {$order}
			LIMIT $cnt
			"
		);

		if (is_array($items)) {

			global $base;
			$template = &$this->private->templates["widget.topics"];

			foreach ($items as $key => $val) {
				$items[$key]["image"] = $template->blockReplace($val["item_tn"] ? "Photo" : "NoPhoto" , $val);
				$items[$key]["link"] = $widget["link"] . $val["item_url"] . "/" . $val["item_id"] ;

				$items[$key]["item_brief"] = $val["item_brief"] = strip_tags($val["item_brief"]);

				if (strlen($val["item_brief"]) > $widget["settings"]["set_chars"])
					$items[$key]["item_brief"] = substr($val["item_brief"] , 0, $widget["settings"]["set_chars"]) . "[...]"; 

				$items[$key]["date"]	= CDate::ToStr("j M Y" , $val["item_date"]);
				$items[$key]["time"]	= CDate::ToStr("g:i a" , $val["item_date"]);


				$items[$key]["item_stats_comments"] = $this->plugins["comments"]->CommentsCount(
					$widget["mod_settings"]["set_comments"],
					$items[$key]["link"],
					$items[$key]["item_stats_comments"]
				);

				$val["author_link"] = $widget["link"] . "authors/" . $val["author_url"] . "/" ;


				$items[$key]["author"] = $template->blockReplace($val["author_details"] ? "AuthorLink" : "Author" , $val);

			}
			

			return $template->blockReplace(
				"Main" , 
				array(
					"widget_title"	=> $widget["widget_name"],
					"news"			=> $base->html->table(
						$template , 
						"" , 
						$items
					)
				),
				$widget["mod_settings"]
			);
		}
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetSearch($widget) {

		return $this->private->templates["widget.search"]->BlockReplace(
			"Main" , 
			$widget,
			$widget["mod_settings"],
			array(
				"widget_title"	=> $widget["widget_name"],

			)
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetArchive($widget) {
		global $_SESS;

		//get all topics

		$topics = $this->db->QFetchRowArray(
			"SELECT item_date_month , item_date_year FROM 
				{$this->tables['plugin:blog_topics']} as t , 
				{$this->tables['plugin:blog_topics_lang']} as l 
			WHERE 
				t.module_id = {$widget[mod_id]} AND 
				l.lang_id={$widget[lang_id]} AND 
				t.item_id=l.item_id AND 
				t.item_status = 1 AND 
				t.item_date < timestamp(now())
				" . ( $_SESS["client"] ? "" : " AND item_protect=0 ") . "
			ORDER BY 
			item_date DESC
			"
		);

		if (is_array($topics)) {
			foreach ($topics as $key => $val) {

				$_key = $val["item_date_month"] . "-" . $val["item_date_year"];
				if (!is_array($_count[$_key])) {
					$_count[$_key] = array(
						"month_lang"	=> CDate::ToLangMonth($val["item_date_month"]),
						"month"			=> $val["item_date_month"],
						"month2"		=> $val["item_date_month"] < 10 ? "0" . $val["item_date_month"] : $val["item_date_month"],
						"year"			=> $val["item_date_year"],
						"link"			=> $widget["link"],
					);
				}
				
				$_count[$_key]["count"] ++;
			}
	
			global $base;

			return $this->private->templates["widget.archive"]->blockreplace(
				"Main" , 
				array(
					"labels"	=> $base->html->Table(
						$this->private->templates["widget.archive"], 
						"", 
						$_count
					),

					"widget_title"	=> $widget["widget_name"],
				),
				$widget["mod_settings"]
			);

		}
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetComments($widget) {
		global $_SESS;

		global $base;
		$template = &$this->private->templates["widget.comments"];


		switch ($widget["mod_settings"]["set_comments"]) {
			//local comments
			case "1":
				$comments = $this->plugins["comments"]->getLastLocalComments(
					max(1,$widget["settings"]["set_items"]),
					"",
					$widget["widget_module"]
				);
			break;

			//facebook 
			case "2":

			break;
		}

		if (is_array($comments)) {
			foreach ($comments as $key => $val) {
				$ids[] = $val["comment_reserved"];
			}

			$topics = $this->db->QFetchRowArray(
				"
					SELECT * FROM 
						{$this->tables['plugin:blog_topics']} as t , 
						{$this->tables['plugin:blog_topics_lang']} as l ,
						{$this->tables['plugin:blog_authors']} as a
		
					WHERE 
						t.module_id = {$widget[mod_id]} AND 
						l.lang_id={$widget[lang_id]} AND 
						t.item_author = a.author_id AND
						t.item_id=l.item_id AND 
						t.item_status = 1 AND 
						t.item_date < timestamp(now()) AND 
						t.item_id in (" . implode("," , $ids ) . ") 
						" . ( $_SESS["client"] ? "" : " AND item_protect=0 ") . "
					ORDER BY 
						item_date DESC
				"
			);

			if (is_array($topics)) {
				foreach ($topics as $key => $val) {
					$val["link"] = $widget["link"] . $val["item_url"] . "/" . $val["item_id"];
					$val["link_author"] = $widget["link"] . $val["author_url"] . "/";
					$_topics[$val["item_id"]] = $val;
				}
				
				$topics = $_topics;
			}
			
			foreach ($comments as $key => $val) {

				$val["date"] = CDate::ToStr("j M Y" , $val["comment_date"]);
				$val["time"] = CDate::ToStr("g:i a" , $val["comment_date"]);

				if ($widget["settings"]["set_full"]) {
					$val["topic"] = $template->blockReplace("Topic" , $val);
				} else {
					$val["topic"] = "";
				}
				
				if ($widget["settings"]["set_image"]) {
					$val["class"] = "";
				} else {
					$val["class"] = $template->blockReplace("NoImage" , $val);
				}

				if (strlen($val["comment_body"]) > $widget["settings"]["set_chars"])
					$val["comment_body"] = substr(strip_tags($val["comment_body"]) , 0, $widget["settings"]["set_chars"]) . "[...]";

				if (!is_array($topics[$val["comment_reserved"]])) {
					unset($comments[$key]);
				} else {
					$comments[$key] = array_merge(
						$val , 
						$topics[$val["comment_reserved"]]
					);
				}
			}

			

			if (!is_array($comments)) {
				return "";
			}
			


			return $template->blockreplace(
				"Main" , 
				array(
					"comments"	=> $base->html->Table(
						$template, 
						"", 
						$comments
					),

					"widget_title"	=> $widget["widget_name"],
				),
				$widget["mod_settings"]
			);
		
			
		}
		
		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetAuthors($widget) {

		$authors = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['plugin:blog_authors']} as a,
				{$this->tables['plugin:blog_authors_lang']} as al

			WHERE 
				a.author_id = al.author_id AND 
				al.lang_id = {$widget[lang_id]} AND 
				a.module_id = {$widget[mod_id]}

			ORDER BY 
				a.author_name ASC
			"
		);

		if (is_array($authors)) {

			global $base;

			$template = &$this->private->templates["widget.authors"];

			foreach ($authors as $key => $val) {
				$authors[$key]["image"] = $template->blockReplace($val["author_image"] ? "Image" : "NoImage" , $val);
				$authors[$key]["link"] = $widget["link"] . "authors/{$val[author_url]}/";

				//if (strlen($val["author_brief"]) > $widget["settings"]["set_chars"])
					//$authors[$key]["author_brief"] = substr(strip_tags($val["author_brief"]) , 0, $widget["settings"]["set_chars"]) . "[...]";

			}

			return $template->blockReplace(
				"Main" ,
				array(

					"authors"	=> $base->html->Table(
						$template, 
						"", 
						$authors
					),

					"widget_title"	=> $widget["widget_name"],
					
				),
				$widget["mod_settings"]

			);
		}		

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetAuthor($widget) {

		$author = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['plugin:blog_authors']} as a,
				{$this->tables['plugin:blog_authors_lang']} as al

			WHERE 
				a.author_id = al.author_id AND 
				al.lang_id = {$widget[lang_id]} AND 
				a.module_id = {$widget[mod_id]} AND
				a.author_id = {$widget[settings][set_author]}
			"
		);

		if (is_array($author)) {

			$template = &$this->private->templates["widget.author"];

			$author["image"] = $template->blockReplace($author["author_image"] ? "Image" : "NoImage" , $author);
			$author["link"] = $widget["link"] . "authors/{$author[author_url]}/";

			if (strlen($author["author_brief"]) > $widget["settings"]["set_chars"])
				$author["author_brief"] = substr(strip_tags($author["author_brief"]) , 0, $widget["settings"]["set_chars"]) . "[...]";

			if (!$widget["settings"]["set_title"]) {
				$author["title"] = $template->blockReplace("Title" , $author);
			} else {
				$author["title"] = "";
			}
			

			return $template->blockReplace(
				"Main" ,
				array(
					"widget_title"	=> $widget["settings"]["set_title"] ? $author["author_name"] : $widget["widget_name"],					
				),
				$author,
				$widget["mod_settings"]
			);
		}		


	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function RSS() {
		global $base , $_CONF , $_LANG_RAW;

		$mime = new CMime();
		$mime->Set("xml");

		$template = &$this->private->templates["rss"];

		$items = $this->db->QFetchRowArray(
			"
				SELECT * FROM 
					{$this->tables['plugin:blog_topics']} as t,
					{$this->tables['plugin:blog_topics_lang']} as tl
				WHERE

					t.item_id = tl.item_id AND 
					tl.lang_id = {$this->tpl_module[lang_id]} AND 
					t.item_status = 1 AND 
					t.item_date <= timestamp(now()) AND 
					t.item_protect = 0 
				ORDER BY 
					item_date DESC
				LIMIT 10
			"
		);

		if (is_array($items)) {
			foreach ($items as $key => $val) {
				$items[$key]["link"] = $this->tpl_module["link"] . "{$val[item_url]}/{$val[item_id]}";
				$items[$key]["date"] = CDate::toStr("r" , $val["item_date"] );

				$date = max($val["item_date"] , $date);
			}
			
		}
		

		return $template->blockReplace(
			"Main" , 
			array(
				
				"items"	=> $base->html->table(
					$template , 
					"" , 
					$items
				),

				"date"	=> CDate::toStr("r" , $date ),
				"url"	=> $_CONF["url"],

				"lang"	=> $_LANG_RAW["lang_code"],

				"rss_link"	=> $this->tpl_module["link"] . "rss",
			),

			$this->tpl_module["settings"]
		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function onCommentPost($comment) {

		$this->db->QueryUpdate(
			$this->tables["plugin:blog_topics"],
			array(
				"item_stats_comments"	=> $this->db->RowCount(
					$this->tables["plugin:comments"],
					"WHERE module_id={$comment[module_id]} AND comment_reserved={$comment[comment_reserved]}" 
				)
			),
			"item_id={$comment[comment_reserved]}"
		);
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetAllLinks($module , &$links) {
		
		$links[] = array(
			"url" => $module["link"],
		);

		//topics
		$items = $this->db->QFetchRowArray(
			"SELECT 
				item_url, 
				c.item_id ,  
				author_id , 
				author_url ,
				author_details
			FROM 
				{$this->tables['plugin:blog_authors']},
				{$this->tables['plugin:blog_topics']} as c,
				{$this->tables['plugin:blog_topics_lang']} as l

			WHERE 				
				c.item_id=l.item_id AND 
				l.lang_id={$module[lang_id]} AND 
				c.module_id={$module[mod_id]} AND 
				item_status=1 AND 
				item_date <= timestamp(now()) 
			"
		);


		if (is_array($items)) {
			foreach ($items as $key => $val) {
				$links[] = array(							
					"url"		=> $module["link"] . $val["item_url"] . "/" . $val["item_id"],
				);

				if ($val["author_details"]) {
					$authors[$val["author_id"]] = $val["author_url"];
				}
				
			}
			
		}


		//labels
		$labels = $this->db->QFetchRowArray(
			"SELECT 
				*
			FROM 
				{$this->tables['plugin:blog_labels']} as b ,
				{$this->tables['plugin:blog_labels_lang']} as l
			WHERE
				b.label_id=l.label_id AND 
				l.lang_id={$module[lang_id]} AND 
				label_status = 1 AND 
				b.module_id = {$module[mod_id]}
		
			ORDER BY 
				label_order ASC
			"
		);

		if (is_array($labels)) {

			foreach ($labels as $key => $val) {

				$links[] = array(
					"url" => $module["link"] . $val["label_url"] . "/"
				);
			}
		}

		//authors
		if (is_array($authors)) {
			foreach ($authors as $key => $val) {

				$links[] = array(
					"url" => $module["link"] . $val . "/"
				);

			}
			
		}
			
	}


}

?>