<?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
*/

include_once dirname(__FILE__).'/config.php';

class bug_tracker_api extends ModuleAPI
{
	public $module='bug_tracker';
	protected $implemented=array('sitemap', 'search', 'getUserStat');
	
	function sitemap()
	{
		$result=array();
		
		$link=getModulePath($this->module);
		
		$result[$link]=array('changefreq'=>'hourly','lastmod'=>time());
		
		$bugs=Db::instance()->selectCol(
			"SELECT bug_id AS ARRAY_KEY, last_update FROM ?_bt_bugs ORDER BY last_update DESC LIMIT 10000"
		);
		if ($bugs)
		foreach ($bugs as $bug_id=>$date) {
			$changefreq=getFreq($date);
			$loc=_url($bug_id, 'item', false, $link);
			$result[$loc]=array('changefreq'=>$changefreq,'lastmod'=>$date);
		}
		
		return $result;
	}
    
	function search($string)
	{
		$search=Db::i()->select(
			"SELECT bp.bug_id, summary as title, msg as `text`, last_update as `date`,
			MATCH(msg) AGAINST(? IN BOOLEAN MODE) as rel
			FROM ?_bt_posts bp
			JOIN ?_bt_bugs bb ON bp.bug_id=bb.bug_id
			WHERE MATCH(msg) AGAINST(? IN BOOLEAN MODE)
			GROUP BY bp.bug_id
			ORDER BY rel", $string, $string
		);
		$path=getModulePath($this->module);
		if ($search) {
			foreach ($search as $k=>$v) {
				$search[$k]['path']=_url($v['bug_id'], 'item', false, $path);
				$search[$k]['text']=getbb($v['text']);
				$search[$k]['title']=htmlspecialchars($v['title']);
			}
		}
		return $search;
	}
    
	function getUserStat($user)
	{
		$module_path=getModulePath($this->module);
		
		$mapper=Factory::create('bug_tracker.mapper');
		$themes=$mapper->getCountItemsByUser($user);
		
		$result[]=array(
			'path'=>_url(array(1, 'author_id'=>$user->id), '', false, $module_path),
			'name'=>_m('Тем в багтрекере'),
			'count'=>$themes
		);
		
		return $result;
	}
}