<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class forum_api extends ModuleAPI
{
	public $module='forum';
	protected $implemented=array('sitemap', 'search', 'getUserStat');
	
	function sitemap()
	{
		$result=array();
		
		$link=getModulePath($this->module);
		
		$result[$link]=array('changefreq'=>'hourly','lastmod'=>time());
		
		$forums=Db::i()->selectCol("SELECT forum_id AS ARRAY_KEY, last_post_date FROM ?_forum_forums WHERE `closed`=0");
		if ($forums)
		foreach ($forums as $forum_id=>$date) {
			$changefreq=getFreq($date);
			$loc=_url($forum_id, false, false, $link);
			$result[$loc]=array('changefreq'=>$changefreq,'lastmod'=>$date);
		}
		
		$themes=Db::instance()->selectCol(
			"SELECT theme_id AS ARRAY_KEY, last_post_date FROM ?_forum_themes ORDER BY last_post_date DESC LIMIT 10000"
		);
		if ($themes)
		foreach ($themes as $theme_id=>$date) {
			$changefreq=getFreq($date);
			$loc=_url($theme_id, 'theme', false, $link);
			$result[$loc]=array('changefreq'=>$changefreq,'lastmod'=>$date);
		}
		
		$posts=Db::instance()->selectCol("SELECT post_id AS ARRAY_KEY, putdate FROM ?_forum_posts ORDER BY post_id DESC");
		if ($posts)
		foreach ($posts as $post_id=>$date) {
			$changefreq=getFreq($date);
			$loc=_url($post_id, 'post', false, $link);
			$result[$loc]=array('changefreq'=>$changefreq,'lastmod'=>$date);
		}
		return $result;
	}
	
	function search($string)
	{
		$search=Db::i()->select(
			"SELECT fp.theme_id, subject as title, msg as `text`, last_post_date as `date`,
			MATCH(msg) AGAINST(? IN BOOLEAN MODE) as rel
			FROM ?_forum_posts fp
			JOIN ?_forum_themes ft ON fp.theme_id=ft.theme_id
			WHERE MATCH(msg) AGAINST(? IN BOOLEAN MODE)
			GROUP BY fp.theme_id
			ORDER BY rel", $string, $string
		);
		$path=getModulePath($this->module);
		if ($search) {
			foreach ($search as $k=>$v) {
				$search[$k]['path']=_url($v['theme_id'], 'theme', false, $path);
				$search[$k]['text']=getbb($v['text']);
				$search[$k]['title']=htmlspecialchars($v['title']);
			}
		}
		return $search;
	}
	
	function getUserStat($user)
	{
		$module_path=getModulePath($this->module);
		
		$themes=Factory::create('forum.themes');
		$themes=$themes->getCountByUser($user);
		
		$result[]=array(
			'path'=>_url($user->id, 'user_themes', false, $module_path),
			'name'=>_m('Тем в форуме'),
			'count'=>$themes
		);
		
		$posts=Factory::create('forum.posts');
		$posts=$posts->getCountByUser($user);
		
		$result[]=array(
			'path'=>_url($user->id, 'user_posts', false, $module_path),
			'name'=>_m('Сообщений в форуме'),
			'count'=>$posts
		);
		
		return $result;
	}
}