<?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 bug_tracker_main extends ModuleTools
{
	public $ajax_methods=array('subscribe_item', 'unsubscribe_item');
	protected $module;

	public function __construct()
	{
		if (!access('read')) return LabCMS::i()->error403();
		
		$this->module=Factory::create('bug_tracker.module');

		$this->_assign(
			array(
				'bug_types'=>config::get('bug_types'),
				'importances'=>config::get('importances'),
				'statuses'=>config::get('statuses')
			)
		);
		$this->_setRss();
	}
	
	//общий список
	public function main()
	{
		if (isset($_GET['data_type']) && $_GET['data_type']=='xml') return $this->_main_xml();
		$this->_setTpl('bugs_list');
		$page=isset($_GET['var1'])?$_GET['var1']:1;

		$filter=array(
					'type'=>isset($_GET['type'])?intval($_GET['type']):0,
					'importance'=>isset($_GET['importance'])?intval($_GET['importance']):0,
					'status'=>isset($_GET['status'])?intval($_GET['status']):0,
					'version_id'=>isset($_GET['version_id'])?intval($_GET['version_id']):0,
					'author_id'=>isset($_GET['author_id'])?intval($_GET['author_id']):0,
					'order'=>isset($_GET['order'])?$_GET['order']:'',
					'direction'=>isset($_GET['direction'])?$_GET['direction']:'',
		);
		$this->_assign('filter', $filter);
		
		$data=$this->module->getItemsByFilter($filter, $page, config::get('bugs_at_page'));

		if ($data['count']) {
			$this->_assign('bugs', $data['collection']);
			$this->_assign('pager', $this->module->getPager($data['count'], $page, config::get('bugs_at_page')));
		}
		$this->_assign('versions', $this->module->getSupportedVersionsArray());
		

	}
	
	protected function _main_xml()
	{
		$this->_setTpl('string:{$xml}', true);
		LabVars::$break=true;
		LabVars::$forceDisplay=true;
		sendXmlHeaders();
		$url=getServerName();
		
		$rss=array('title'=>'Багтрекер - '.config::get('core.site_name'),
					'link'=>config::get('core.siteUrl')._url(),
					'description'=>"Сообщения багтрекера ".config::get('core.site_name'));
		
		$bug_types=config::get('bug_types');
		$statuses=config::get('statuses');
		$importances=config::get('importances');
		$filter=array('order'=>'update', 'direction'=>'desc');
		$data=$this->module->getItemsByFilter($filter, 1, 50);
		if ($data['count']) {
			foreach ($data['collection'] as $item) {	
				$rss['feed'][]=array(
					'title'=>$item->summary.' ['.date("d/m/Y H:i", $item->last_update).']',
					'description'=>	'Тип: '.$bug_types[$item->type]
					.'<br />Статус: '.$statuses[$item->status]
					.'<br />Важность: '.$importances[$item->importance]
					.'<br />Версия: '.$item->version->name
					.'<br />Автор: '.htmlspecialchars($item->author->login),
					'link'=>config::get('core.siteUrl')._url($item->id, 'item').'#'.$item->last_update,
					'pubDate'=>$item->last_update
				);
									
			}			
		}
		
		$xml=genereteFeed($rss);
		$this->_assign('xml', $xml);
	}
	
	public function new_posts()
	{
		$this->_setTpl('string:{$xml}', true);
		LabVars::$break=true;
		LabVars::$forceDisplay=true;
		
		sendXmlHeaders();
		$rss=array(
			'title'=>'Багтрекер - '.config::get('core.site_name'),
			'link'=>config::get('core.siteUrl')._url(),
			'description'=>"Последние комментарии багтрекера "
			.config::get('core.site_name')
		);
		
		if ($posts=$this->module->getLastPosts()) {
			foreach ($posts as $post) {
				$rss['feed'][]=array('title'=>htmlspecialchars($post->bug->summary),
							'description'=>	'<b>'.htmlspecialchars($post->user->login).'</b><br />'.$post->msg_html,
							'link'=>config::get('core.siteUrl')._url($post->bug->id, 'item').'#btc'.$post->id,
							'pubDate'=>$post->putdate);
			}
		}
		$xml=genereteFeed($rss);
		$this->_assign('xml', $xml);
	}
	
	//версии
	public function versions()
	{
		$this->_setTpl('versions');
		if (!access('perform')) return LabCMS::i()->error403();
		$data=$this->module->getAllVersionsForAdmin();
		if ($data['count']) {
			$this->_assign('versions', $data['collection']);
			//$this->_assign('pager', $this->module->getPager($data['count'], $page, config::get('bugs_at_page')));
		}
		addBreadcrumb(_m('Версии'), _url(null, 'versions'));
	}
	
	public function add_version()
	{
		$this->_setTpl('form');
		if (!access('perform')) return LabCMS::i()->error403();

		$form=$this->module->getVersionEditForm();
		
		if ($form->validate()) {
			$version=$this->module->getVersionEntity($form->getValue());
			$this->module->addVersion($version);
			refresh('', _url(null, 'versions'));
		}
		
		$this->_assign('form', $this->_renderForm($form));
	}
	
	public function edit_version()
	{
		$this->_setTpl('form');
		if (!access('perform')) return LabCMS::i()->error403();
		if (!$version=$this->module->getVersionById($_GET['var1'])) return $this->_error(_m('Версия не найдена'));

		$form=$this->module->getVersionEditForm($version);
		
		if ($form->validate()) {
			$version->set($form->getValue());
			$this->module->updateVersion($version);
			refresh('', _url(null, 'versions'));
		}
		
		$this->_assign('form', $this->_renderForm($form));
	}
	
	public function delete_version()
	{
		if (!access('perform')) return LabCMS::i()->error403();
		User::checkToken();
		if (!$version=$this->module->getVersionById($_GET['var1'])) return $this->_error(_m('Версия не найдена'));
		if ($version->hasItems()) return $this->_error(_m('Имеются записи с этой версией'));
		$this->module->deleteVersion($version);
		refresh('', _url(null, 'versions'));
	}
	
	//просмотр темы
	public function item()
	{
		if (!$item=$this->module->getItemById($_GET['var1'])) return $this->_error(_m('Запись не найдена'));
		if (isset($_GET['data_type']) && $_GET['data_type']=='xml') return $this->_item_xml($item);
		
		if ($_SERVER['REQUEST_METHOD']=='POST' && access('approve, perform')) {
			$item->type=intval($_POST['type']);
			$item->version_id=intval($_POST['version_id']);
			$item->status=intval($_POST['status']);
			$item->importance=intval($_POST['importance']);
			$this->module->updateItem($item);
			refresh('Данные применены', _url($item->id, 'item'), 1);
		}
		
		if (User::i()->isNotGuest()) {
			$subscribe=Factory::create('Subscriber');
			$this->_assign('item_subscribed', $subscribe->getSubscribeStatus($item->getSubsribeId()));
		}
		
		addBreadcrumb($item->summary, _url($item->id, 'item'));
		
		$posts=$this->module->getPostsByItem($item);
		
		$this->_assign('posts', $posts['collection']);
		
		$this->_setRss($item);
		$this->_assign('versions', $this->module->getSupportedVersionsArray());
		$this->_assign('item', $item);
		$this->_setTpl('item');
	}
	
	protected function _item_xml($item)
	{
		$posts=$this->module->getPostsByItem($item);
		
		$this->_setTpl('string:{$xml}', true);
		LabVars::$break=true;
		LabVars::$forceDisplay=true;
		
		sendXmlHeaders();
		
		$bug_types=config::get('bug_types');
		$statuses=config::get('statuses');
		$importances=config::get('importances');
		
		$rss=array(
			'title'=>htmlspecialchars($item->summary),
			'link'=>config::get('core.siteUrl')._url($item->id, 'item', 'xml'),
			'description'=>'Тип: '.$bug_types[$item->type]
			.', Статус: '.$statuses[$item->status]
			.', Важность: '.$importances[$item->importance]
			.', Версия: '.$item->version->name
			.', Автор: '.htmlspecialchars($item->author->login)
		);

		foreach ($posts['collection'] as $post) {
			$rss['feed'][]=array(
				'title'=>htmlspecialchars($post->user->login),
				'description'=>$post->msg_html,
				'link'=>config::get('core.siteUrl')._url($item->id, 'item').'#btc'.$post->id,
				'pubDate'=>$post->putdate
			);	
		}
		
		$xml=genereteFeed($rss);
		$this->_assign('xml', $xml);
	}
	
	public function add()
	{
		if (!access('user')) return LabCMS::i()->error403();
		$item=Factory::create('bug_tracker.item');
		$form=$this->module->getItemAddForm();
		
		if ($form->validate()) {
			$item=$this->module->addItem($form->getValue());
			refresh('', _url($item->id, 'item'));
		}
		
		$this->_assign('form', $this->_renderForm($form));
		$this->_setTpl('form');
	}
	
	public function delete_bug()
	{
		User::checkToken();
		if (!access('moderator')) return LabCMS::i()->error403();
		if (!$item=$this->module->getItemById($_GET['var1']))  return $this->_error(_m('Запись не найдена'));
		$this->module->deleteItem($item);
		refresh();
	}
	
	public function reply()
	{
		if (!$post=$this->module->getPostById($_GET['var1']))  return $this->_error(_m('Запись не найдена'));
		if (!access('user')) return LabCMS::i()->error403();
		
		$form=$this->module->getPostEditForm();
		
		if ($form->validate()) {
			$data=$form->getValue();
			$data['user']=User::i()->getCurrentUser();
			$data['bug']=$post->bug;
			$new_post=$this->module->addPost($data);
			refresh('', _url($post->bug_id, 'item'));
		}
		
		$this->_assign('post', $post);
		$this->_assign('form', $this->_renderForm($form));
		$this->_setTpl('form');
	}
	
	public function edit()
	{
		$post=$this->module->getPostById($_GET['var1']);
		if (!is_object($post)) return $this->_error(_m('Запись не найдена'));
		if (!$post->isAccessEdit()) return LabCMS::i()->error403();
		$form=$this->module->getPostEditForm($post);
		
		if ($form->validate()) {
			$this->module->updatePost($post, $form->getValue());
			refresh('', _url($post->bug_id, 'item'));
		}
		
		$this->_assign('form', $this->_renderForm($form));
		$this->_setTpl('form');
	}
	
	public function delete()
	{
		User::checkToken();
		$post=$this->module->getPostById($_GET['var1']);
		if (!is_object($post)) return $this->_error(_m('Запись не найдена'));
		if (!$post->isAccessDelete()) return LabCMS::i()->error403();
		$this->module->deletePost($post);
		refresh('', _url($post->bug->id, 'item'));
	}
	
	public function ajax()
	{
		if (!in_array($_POST['action'], $this->ajax_methods))
			$this->_json_error(_m('Метод не найден'));
		if (User::i()->isGuest()) $this->_json_error(_m('Доступ запрещен'));
		$method='_json_'.$_POST['action'];
		$result=$this->$method();
		echo real_json_encode($result);
		exit;
	}
	
	protected function _json_subscribe_item()
	{
		if (!$item=$this->module->getItemById($_POST['item_id'])) return $this->_json_error(_m('Запись не найдена'));
		$subsctiber=Factory::create('Subscriber');
		$subsctiber->subscribe($item->getSubsribeId());
		return array('ok'=>1);
	}
	
	protected function _json_unsubscribe_item()
	{
		if (!$item=$this->module->getItemById($_POST['item_id'])) return $this->_json_error(_m('Запись не найдена'));
		$subsctiber=Factory::create('Subscriber');
		$subsctiber->unsubscribe($item->getSubsribeId());
		return array('ok'=>1);
	}
	
	protected function _setRss($item=false)
	{
		if ($item) {
			Tpl::i()->append(
				'feed_rss',
				array('path'=>_url($item->id, 'item', 'xml'),
				'name'=>'Подписаться на тему "'.$item->summary.'"')
			);
		} else {
			Tpl::i()->append(
				'feed_rss',
				array(
					'path'=>_url(false, false, 'xml'),
					'name'=>_m("Последние отчеты багтрекера").' '.config::get('core.site_name')
				)
			);
			Tpl::i()->append(
				'feed_rss',
				array(
					'path'=>_url(false, 'new_posts', 'xml'),
					'name'=>_m("Последние сообщения багтрекера").' '.config::get('core.site_name')
				)
			);
		}
	}
	
	protected function _json_error($msg)
	{
		echo real_json_encode(array('error'=>$msg));
		exit;
	}
}