<?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
*/
	if (!access('read')) return LabCMS::i()->error403();

	include dirname(__FILE__)."/config.php";

	Tpl::i()->append('feed_rss', array('path'=>LabCMS::i()->url(false, false, 'xml'), 'name'=>"Последние отчеты багтрекера ".LabCMS::i()->sitename));
	Tpl::i()->append('feed_rss', array('path'=>LabCMS::i()->url(false, 'new_posts', 'xml'), 'name'=>"Последние сообщения багтрекера ".LabCMS::i()->sitename));
	
	if (trim(LabConfig::$mcfg['allowed_types'])) $allowed_types=array_unique(array_map('trim', explode(',', LabConfig::$mcfg['allowed_types'])));
	
	$project_id=1;
	$bug_types=array(1=>"Ошибка", 2=>"Доработка");
	$importances=array(10=>'Если время будет', 20=>'Желательно не затягивать', 30=>'Первоочередное');
	$statuses=array(20=>'Не проверено', 10=>'Подтвержено', 30=>'Завершено', 40=>'Отклонено');

	Tpl::i()->assign("image_path", $config_tn['img_path']);
	Tpl::i()->assign("file_path", $config_tn['file_path']);
/*
var1 - страница
var2 - сортировка
var3 - тип
var4 - важность
var5 - статус
var6 - версия
*/	
	if ($_POST['filter']) refresh('', LabCMS::i()->url(
	array(	1,  //var1
			intval($_GET['var2']),					//var2
			intval($_POST['bug_type']),//var3
			intval($_POST['importance']),//var4
			intval($_POST['status']),//var5
			intval($_POST['version_id'])//var6
	)
	));
	
	Tpl::i()->assign(array('bug_types'=>$bug_types,'importances'=>$importances,'statuses'=>$statuses));
	
	switch($_GET['action'])
	{
		case('edit'):
		case('reply'):
		case('delete'):
			$post_info=Db::i()->selectRow("SELECT p.user_id, msg, post_id, summary, b.bug_id, login, version_id FROM ?_bt_posts p JOIN ?_bt_bugs b ON p.bug_id=b.bug_id JOIN ?_users u ON p.user_id=u.user_id WHERE post_id=?", $_GET['var1']);
		break;
	}

	switch(true)
	{
		case($_GET['action']=='add'):
			if (!access('user')) LabCMS::i()->error403();
			addBreadcrumb('новое сообщение');
			include dirname(__FILE__)."/add_bug.php";
		break;
		
		case($_GET['action']=='reply' && access('user')):
			$mode="reply";
			addBreadcrumb(getbb($post_info['summary'],'nolinks'), LabCMS::i()->url($post_info['bug_id'], 'item'), true);
			addBreadcrumb('ответить', LabCMS::i()->url($post_info['post_id'], 'reply'));
			include dirname(__FILE__)."/edit_post.php";
		break;
		case($_GET['action']=='edit' && (access('moderator') || (access('user') && User::i()->id==$post_info['user_id']))):
			$mode="edit";
			addBreadcrumb(getbb($post_info['summary'],'nolinks'), LabCMS::i()->url($post_info['bug_id'], 'item'), true);
			addBreadcrumb('редактирование сообщения', LabCMS::i()->url($post_info['post_id'], 'edit'));
			include dirname(__FILE__)."/edit_post.php";
		break;
		case($_GET['action']=='delete' && (access('moderator') || (access('user') && User::i()->id==$post_info['user_id']))):
			if ($post_info['post_id']==Db::i()->selectCell("SELECT post_id FROM ?_bt_posts WHERE bug_id=? ORDER BY post_id LIMIT 1", $post_info['bug_id'])) return LabCMS::i()->error("Нельзя удалить первое сообщение ветки");
			$mode="delete";
			include dirname(__FILE__)."/edit_post.php";
		break;
		
		case($_GET['action']=='delete_bug' && access('moderator')):
			$mode="delete_bug";
			include dirname(__FILE__)."/edit_post.php";
		break;
		
		case($_GET['action']=='new_posts' && $_GET['data_type']=='xml'):
			include dirname(__FILE__)."/new_posts_xml.php";
		break;
		case($_GET['action']=='item' && $_GET['data_type']=='xml'):
			include dirname(__FILE__)."/item_xml.php";
		break;
		case($_GET['action']=='item'):
			include dirname(__FILE__)."/item.php";
		break;
	
		case($_GET['action']=='versions' && access('perform')):
			addBreadcrumb('список версий', LabCMS::i()->url(false, 'versions'));
			include dirname(__FILE__)."/versions.php";
		break;
		case($_GET['action']=='add_version' && access('perform')):
			$mode="add";
			addBreadcrumb('список версий', LabCMS::i()->url(false, 'versions'));
			addBreadcrumb('добавление версии', LabCMS::i()->url(false, 'add_version'));
			include dirname(__FILE__)."/edit_version.php";
		break;
		case($_GET['action']=='edit_version' && access('perform')):
			$mode="edit";
			addBreadcrumb('список версий', LabCMS::i()->url(false, 'versions'));
			addBreadcrumb('радактирование версии', LabCMS::i()->url($_GET['var1'], 'add_version'));
			include dirname(__FILE__)."/edit_version.php";
		break;
		case($_GET['action']=='delete_version' && access('perform')):
			$mode="delete";
			include dirname(__FILE__)."/edit_version.php";
		break;
		case($_GET['data_type']=='xml'):
			include dirname(__FILE__)."/bugs_list_xml.php";
		break;

		default:
			include dirname(__FILE__)."/bugs_list.php";
	}
	function upload_image($name, $image)
	{
		global $config_tn;

		$img_info=getimagesize($image);
		if ($img_info[2]>0 && $img_info[2]<4)
		{
			$ext=image_type_to_extension($img_info[2]);
			
			$id=Db::i()->query("INSERT INTO ?_bt_files (file_type, file_name) VALUES(?, ?)", image_type_to_extension($img_info[2], false), $name);

			foreach ($config_tn['images'] as $tn)
			{
				$img=new Image_Resize();
				if ($tn['type'])
				{
					$new_name=$id.".".$tn['type'];
					$img->new_type=$tn['type'];
				}
				else
				{
					$new_name=$id.$ext;
				}
				
				if (!is_dir(LAB_PATH_ROOT.$config_tn['img_path']."/".$tn['path'])) mkdir(LAB_PATH_ROOT.$config_tn['img_path']."/".$tn['path'], 0777, true);
				$img->file= $image;
				$img->file_dest= LAB_PATH_ROOT.$config_tn['img_path']."/".$tn['path']."/".$new_name;
				$img->width=$tn['w'];
				$img->height=$tn['h'];
				if (isset($tn['crop'])) $img->crop=$tn['crop'];
				if ($img->go())
				{
					$done[]= LAB_PATH_ROOT.$config_tn['img_path']."/".$tn['path']."/".$new_name;
					chmod($img->file_dest, 0644);
				}
				else
				{
					$id=Db::i()->query("DELETE FROM ?_bt_files WHERE file_id=?", $id);
					foreach($done as $file)
					{
						unlink($file);
						LabCMS::i()->error("Ошибка генерации превью");
						return false;
					}
				}
			}
			return $id;
		}
		else
		{
			LabCMS::i()->error("Недопустимый формат файла");
		}
		return false;
	}
	
	function upload_file($name, $tmp_name)
	{
		global $allowed_types, $config_tn;
		$info=pathinfo(strtolower($name));
		if ($allowed_types && !in_array($info['extension'], $allowed_types)) LabCMS::i()->error("Данный тип файлов не разрешен для загрузки");
		if (in_array($info['extension'], array('gif', 'jpg', 'jpeg', 'png'))) return upload_image($name, $tmp_name);
		else
		{
			include dirname(__FILE__)."/zip.class.php";
			if (!is_dir(LAB_PATH_ROOT.$config_tn['file_path'])) mkdir(LAB_PATH_ROOT.$config_tn['file_path'], 0777, true);
			
			$id=Db::i()->query("INSERT INTO ?_bt_files (file_type, file_name) VALUES(?, ?)", 'zip', $name);
			
			$zipfile = new zipfile();
			$filedata = file_get_contents($tmp_name);
			$zipfile -> add_file($filedata, basename($name));
			file_put_contents(LAB_PATH_ROOT.$config_tn['file_path'].'/'.$id.'.zip', $zipfile -> file()); 
			chmod(LAB_PATH_ROOT.$config_tn['file_path'].'/'.$id.'.zip', 0644);
			return $id;
		}
		return false;
	}

	function delete_files($ids)
	{
		global $config_tn;
		
		if (!is_array($ids)) $ids=array($ids);
		
		$files=Db::i()->selectCol("SELECT file_id AS ARRAY_KEY, file_type FROM ?_bt_files WHERE file_id IN (?a)", $ids);
		if ($files)
		{
			foreach($files as $id=>$type)
			{
				if (in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) delete_image($id.'.'.$type);
				else @unlink(LAB_PATH_ROOT.$config_tn['file_path']."/".$id.'.'.$type);
			}
			Db::i()->query("DELETE FROM ?_bt_files WHERE file_id IN (?a)", $ids);
		}
	}
	
	function delete_image($file)
	{
		global $config_tn;
		foreach ($config_tn['images'] as $tn)
		{
			@unlink(LAB_PATH_ROOT.$config_tn['img_path']."/".$tn['path']."/".$file);
		}
	}