<?php
/* $Id: ticket.class.php,v 1.12 2003/11/08 10:56:04 rvt Exp $ */

define("ISOZERODATE", "1000-01-01 00:00:00+00");

class Ticket{
	var $id = -1;
	/*
	constructor
	*/
	function Ticket() {
		//arg 1 : $id
		$arguments = func_get_args();
		switch(func_num_args()) {
			case 0:
			//nothing to do
			break;
			
			case 1:
				$this->setId($arguments[0]);
			break;	
		}
	}
	
	
    function opCreate() {
        global $conn, $smarty, $appconf;

	if(queryRights2_bool('root_modules_tts_write')){
        $currentproj=(int)$_POST["_project"];
        $ticketowner = (int)$_POST["ownervalid"];
        $assigneduser=(int)$_POST["_assigned"];
        $priority=(int)$_POST["_priority"];    
        $severity=(int)$_POST["_severity"];    
        $resolution=(int)$_POST["_resolution"];    
        
        $shortdescription=$conn->QMagic($_POST["short_desc"]);
        $longdescription=$conn->QMagic($_POST["long_desc"]);
    
        $idcategory=0;
    
    
        $id = $conn->GenID('mgw__seq_tts');
    
        $sql="INSERT INTO mgw_tts (id, id_category, id_project, id_priority, id_severity, id_resolution, id_owner, id_assigned, lu_date, owner_name, owner_email, short_desc, long_desc)
             VALUES (".$id.",".$idcategory." , ".$currentproj.", ".$priority.", ".$severity.", ".$resolution.", ".$_SESSION["MGW"]->userid.",".$assigneduser.", ".$conn->DBTimeStamp(time()).", NULL, NULL, ".$shortdescription.", ".$longdescription.")";
    	$this->setId($id);
        if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    return true;
	}
	else{
	    $smarty->assign("errorheader",Lang::getLanguageString("permerror"));
	    $smarty->assign("permerror",Lang::getLanguageString("permerrormsg"));
	    $smarty->display($appconf["gentemplates"] ."/perm_errors.tpl");
	    exit();
	}
    }

    function opComment() {
        global $conn, $smarty, $appconf;

	$id = $conn->GenID('mgw__seq_notes_comments');
	$note_id = isset($_POST["note_id"])?(int) $_POST["note_id"]:0;
	$qcomment = $conn->QMagic($_POST['comment']);

	$sql="INSERT INTO mgw_notes_comments (id, note_id, comment, lu_user, lu_update) VALUES ($id, $note_id, $qcomment, ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";

	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	return true;
    }

    function opUpdate() {
        global $conn, $smarty, $appconf;

	$id = isset($_POST["id"])?(int) $_POST["id"]:0;

	$sql = "SELECT owner FROM mgw_notes WHERE id=$id AND (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.")";
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	if((queryRights2_bool('root_modules_tts_modify') && $row["owner"] == $_SESSION["MGW"]->userid) ||
	   (queryRights2_bool('root_modules_tts_modifyothers') && $row["owner"] != $_SESSION["MGW"]->userid)){

        $currentproj=(int)$_POST["_project"];
        $ticketowner = (int)$_POST["ownervalid"];
        $assigneduser=(int)$_POST["_assigned"];
        $priority=(int)$_POST["_priority"];    
        $severity=(int)$_POST["_severity"];    
        $resolution=(int)$_POST["_resolution"];    
            
        $shortdescription=$conn->QMagic($_POST["short_desc"]);
        $longdescription=$conn->QMagic($_POST["long_desc"]);
        
        $id=isset($_POST["_tts"])?(int)$_POST["_tts"]:0;
    
        $icategory=0;
    
        $sql="UPDATE mgw_tts SET id_category=".$icategory.", id_project=".$currentproj.", id_priority=".$priority.", id_severity=".$severity.", id_resolution=".$resolution.",id_owner=".$_SESSION["MGW"]->userid.", id_assigned=".$assigneduser.",  short_desc=".$shortdescription.", long_desc=".$longdescription." WHERE id=".$id;
    
        if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    return true;
	}
	else{
	    $smarty->assign("errorheader",Lang::getLanguageString("permerror"));
	    $smarty->assign("permerror",Lang::getLanguageString("permerrormsg"));
	    $smarty->display($appconf["gentemplates"] ."/perm_errors.tpl");
	    exit();
	}
    }
    
    
	function getGraph() {
		global $conn, $smarty, $appconf;
		
        // graph library
	define('CACHE_DIR',CACHE_FOLDER); // for jpgraph.php itself!
        include (INCLUDEPATH . "jpgraph/jpgraph.php");
        include (INCLUDEPATH . "jpgraph/jpgraph_gantt.php");

        
        // A new graph with automatic size 
        $graph = new GanttGraph(0, 0, "auto"); 
        
        $graph->title->Set(Lang::getLanguageString("historictitle")." ".isset($_GET["id"])?(int) $_GET["id"]:0);
        $graph->ShowHeaders(GANTT_HDAY | GANTT_HWEEK | GANTT_HMONTH); 
        
        $graph->scale->week->SetStyle(WEEKSTYLE_FIRSTDAY);
        $graph->scale->week->SetFont(FF_FONT0);
        $graph->scale->month->SetStyle(MONTHSTYLE_SHORTNAMEYEAR4); 
        $graph->scale->month->SetFontColor("white"); 
        $graph->scale->month->SetBackgroundColor("blue"); 
        
        
        // get projects
        
        $sql="SELECT t.lu_date as project_date, h.id as idinter, h.*, u.* FROM mgw_tts t, mgw_tts_history h, mgw_users u WHERE h.id_tts=".(isset($_GET["id"])?(int) $_GET["id"]:0)." AND h.id_owner=u.id and t.id = h.id_tts ORDER BY h.lu_date";
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $o = 0;
        
        // define color toggle array
        $mycolor[0] = "yellow";
        $mycolor[1] = "green";
        $mycolor[2] = "blue";
        $mycolor[3] = "red";
        while($row = $res->FetchRow()){
            
            //  A new activity on row '0' 
            //    print_r($res->UserTimeStamp($row["start_date"],"Y-m-d"));echo "\n";

        $isozero=$conn->UnixTimeStamp(ISOZERODATE); //RVT
	    if($conn->UnixTimeStamp($row["end_date"])!=$isozero) {//a modifier //RVT
            	//this is the latest action
        		
        		$varname = new GanttBar($o,$row["username"],$res->UserTimeStamp($conn->UnixTimeStamp($row["start_date"]),"Y-m-d"),$res->UserTimeStamp($conn->UnixTimeStamp($row["end_date"]),"Y-m-d")); 
        		$varname->SetPattern(BAND_RDIAG,$mycolor[$row["state"]]); 
        		$varname->SetFillColor($mycolor[$row["state"]]);
				$varname->SetCSIMTarget('index.php?action=detailsInter&id='.$row["idinter"],Lang::getLanguageString("detailinter"). " ".$row["idinter"]);        		
            }
            elseif($conn->UnixTimeStamp($row["start_date"])!=$isozero) { //RVT
        		$varname = new GanttBar($o,$row["username"],$res->UserTimeStamp($conn->UnixTimeStamp($row["start_date"]),"Y-m-d"),date("Y-m-d",time())); 
        		$varname->SetPattern(BAND_RDIAG,$mycolor[$row["state"]]); 
        		$varname->SetFillColor($mycolor[$row["state"]]);
				$varname->SetCSIMTarget('index.php?action=detailsInter&id='.$row["idinter"],Lang::getLanguageString("detailinter"). " ".$row["idinter"]);        		
            }
        
            $graph->Add($varname); 
            $o++;
        }
		return $graph;				
	}

	function getImage() {
        $graph=$this->getGraph();
        return $graph->Stroke(); 
	}
	
	function getGantt() {
		global $conn, $smarty, $appconf;
		
        $graph=$this->getGraph();
        return $graph->GetCSIMAreas(); 
			
	}
    
    function viewHistoric() {
		global $conn, $smarty, $appconf;
				
		$smarty->assign("image", $this->getGantt()); 
		$smarty->assign("id", $this->getId());
		$smarty->display('tts_gantt_view.tpl');    	
    }
    
	function viewSummary() {
		global $conn, $smarty, $appconf;
		global $priority, $severity, $resolution, $status;
		
	
        //declare the array used to display boxes
        $byDate=array();
        $byUser=array();
        $byStatus=array();
        $bySeverity=array();
        $byPriority=array();
        $byResolution=array();    
        
       
        //by priority
        $sql="SELECT id_priority, COUNT(lu_date) AS count FROM mgw_tts GROUP BY id_priority ORDER BY id_priority";
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $i=0;
        $row=array();
        while(!$res->EOF) { 
        	$row[$i] = $res->FetchRow();
        	$row[$i]["id_priority"] = $priority[$row[$i]["id_priority"]];    	
        	 $i++;
        }
        $byPriority=$row;    
        $smarty->assign("priority",$byPriority);
        
        //by severity
        $sql="SELECT id_severity, COUNT(lu_date) AS count FROM mgw_tts GROUP BY id_severity ORDER BY id_severity";
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $i=0;
        $row=array();
        while(!$res->EOF) { 
        	$row[$i] = $res->FetchRow();
        	$row[$i]["id_severity"] = $severity[$row[$i]["id_severity"]];
        	 $i++;
        }
        $bySeverity=$row;    
        $smarty->assign("severity",$bySeverity);
    
        //by resolution
        $sql="SELECT id_resolution, COUNT(lu_date) AS count FROM mgw_tts GROUP BY id_resolution ORDER BY id_resolution";
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $i=0;
        $row=array();
        while(!$res->EOF) { 
        	$row[$i] = $res->FetchRow();
        	$row[$i]["id_resolution"] = $resolution[$row[$i]["id_resolution"]];
        	 $i++;
        }
        $byResolution=$row;    
        $smarty->assign("resolution",$byResolution);
    
    
        //by user
        $sql="SELECT b.username, b.id, COUNT(a.id) AS count 
              FROM mgw_tts a, mgw_users b 
              WHERE a.id_owner=b.id
              GROUP BY b.id, b.username, a.id_owner, a.id_priority
              ORDER BY a.id_priority";
        if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $i=0;
    	//to avoid EALL notice
    	$row2=array();
        while(!$res2->EOF) {
        $row2[$i] = $res2->FetchRow();
            $i++;    
        }
        $byUser=$row2;
        $smarty->assign("user",$byUser);    
        
        //by status
        $sql="SELECT state, COUNT(lu_date) AS count FROM mgw_tts_history WHERE end_date='".ISOZERODATE."' GROUP BY state ORDER BY state"; //RVT
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $i=0;
        $row=array();
        while(!$res->EOF) { 
        	$row[$i] = $res->FetchRow();
        	$row[$i]["state"] = $status[$row[$i]["state"]];
        	 $i++;
        }
        $byStatus=$row;    
        $smarty->assign("status",$byStatus);    
        
         //by day
        $sql="SELECT a.id, a.lu_date FROM mgw_tts a ";
        if(!$res5 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $i=0;
    	//to avoid EALL notice
    	$temp=array();
        while(!$res5->EOF) {
            $row5[$i]= $res5->FetchRow();
            $row5[$i]["lu_date"] =round((date("U",time()) - $res5->UnixTimeStamp($row5[$i]["lu_date"],"U"))/ (3600*24),0);
            $temp[$row5[$i]["lu_date"]]=$temp[$row5[$i]["lu_date"]]+1;                
            $i++;    
        }
        
        $i=0;
    	//to avoid EALL notice
    	$byDay=array();	
    	
        if(count($temp) > 0){
    		while(list($k,$v)=each($temp)) {
    		    $byDay[$i]["num"]=$k;
    		    $byDay[$i]["count"]=$v;        
    		    $i++;
    		}
        }
        $smarty->assign("day",$byDay);
    
        
        $smarty->display("tts_summary.tpl");
			

	}
	
    function viewNewForm() {
        global $conn,$smarty, $appconf;
        global $priority, $severity, $resolution;

	if(queryRights2_bool('root_modules_tts_write')){
	    include(INCLUDEPATH . "mSelectBox.class.php");
        $id="";
        $assignedto="";
    	
        if(isset($_GET["id"]))
    	$id=(int)$_GET["id"];
    	
        if(isset($_GET["assignedto"]))
    	$assignedto=(int)$_GET["assignedto"];
        //project select Box
    	$smarty->assign("idtxt", Lang::getLanguageString("id"));
        $smarty->assign("idval", isset($_GET["id"])?(int)$_GET["id"]:0);	
        $smarty->assign("project","add");
        $smarty->assign("mode","new");
        $smarty->assign("current_tts",$id);
        $smarty->assign("suname","create");
        $smarty->assign("editticket",Lang::getLanguageString("newticket"));
        $smarty->assign("suvalue",Lang::getLanguageString("create"));
        $smarty->assign("suclass","submit");
    
        $projid=0;
        if(isset($_GET["projid"])) {
    	    $projid=(int)$_GET["projid"];
        }
    	
        $sql="SELECT project_id, title FROM mgw_projects";
        $sb6 = new mSelectBox("_project",$projid);
        $sb6->setContentType("sql");
        $sb6->setSQLvalue("project_id");
        $sb6->setSQLcontent("title");
        $sb6->addContent($sql);
        $sb6->addOption("0", Lang::getLanguageString("chooseproject"), "pre");
        $smarty->assign("projectsb", $sb6->draw());
        unset($sb6);
    
        //owner text
        $sql="SELECT * FROM mgw_users WHERE id=".$_SESSION["MGW"]->userid;
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $row = $res->FetchRow();
        $smarty->assign("ownerval",$row["lastname"].", ".$row["firstname"]);
        $smarty->assign("ownervalid",$row["id"]);
    
    
        //user of the project select Box
        $concat=$conn->Concat("lastname", "', '", "firstname");
        // fixing empty array - emailtotom
        $name = array();
        $sql="SELECT $concat AS name, id FROM mgw_users WHERE is_ldap=1";    //need to be modified when there is a table to link users and projects
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $i=1;
        while(!$res->EOF) {
            $name[$res->Fields("id")] = $res->Fields("name");
            $res->MoveNext();
            $i++;
        }
      //  print_r($name);
    
        $sb7 = new mSelectBox("_assigned",$assignedto);
        $sb7->setContentType("arr");
    
        $sb7->addContent($name);
    
        $sb7->addOption("NULL", Lang::getLanguageString("chooseassigned"), "pre");
        $smarty->assign("assignedsb", $sb7->draw());
        unset($sb7);
    
    	//PRIOTITY
        $smarty->assign("priority", Lang::getLanguageString("priority"));
        $sb8 = new mSelectBox("_priority",4);
        $sb8->setContentType("arr");
        $sb8->addContent($priority);
        $smarty->assign("prioritysb", $sb8->draw());
        unset($sb8);    
    
    	//SEVERITY
        $smarty->assign("severity", Lang::getLanguageString("severity"));
        $sb9 = new mSelectBox("_severity",0);
        $sb9->setContentType("arr");
        $sb9->addContent($severity);
        $smarty->assign("severitysb", $sb9->draw());
        unset($sb9);    
    
    	//RESOLUTION
        $smarty->assign("resolution", Lang::getLanguageString("resolution"));
        $sb10 = new mSelectBox("_resolution",0);
        $sb10->setContentType("arr");
        $sb10->addContent($resolution);
        $smarty->assign("resolutionsb", $sb10->draw());
        unset($sb10);    
        
        $smarty->clear_cache("tts_list.tpl",$_SESSION["MGW"]->userid);
        $smarty->clear_cache("tts_en.tpl","new");
        $smarty->display('tts_ticket.tpl','new');

	    return true;
	}
	else{
	    $smarty->assign("errorheader",Lang::getLanguageString("permerror"));
	    $smarty->assign("permerror",Lang::getLanguageString("permerrormsg"));
	    $smarty->display($appconf["gentemplates"] ."/perm_errors.tpl");
	    exit();
	}
    }

    function viewDetails() {
        global $conn,$smarty;

        $sql="SELECT title FROM mgw_projects WHERE project_id=".(isset($_GET["projid"])?(int)$_GET["projid"]:0);
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	        $row = $res->FetchRow();
	        $smarty->assign("projectsb", $row["title"]);
		

        //owner text
        $sql="SELECT * FROM mgw_tts WHERE id=".(isset($_GET["id"])?(int)$_GET["id"]:0) ;
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $row = $res->FetchRow();

//		$concat=$conn->Concat("lastname", "', '", "firstname");
        $sql="SELECT * FROM mgw_users";    //need to be modified when there is a table to link users and projects
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
       // $row = $res->GetRowAssoc(false);

        $i=1;
        while(!$res->EOF) {

            $name[$res->Fields("id")] = $res->Fields("lastname").", ".$res->Fields("firstname");
            $res->movenext();
            $i++;
        }
        $smarty->assign("assignedsb", $name[$row["id_assigned"]]);
        $smarty->assign("ownerval",$name[$row["id_owner"]]);		

		
		
        $sql="SELECT * FROM mgw_tts WHERE id=".(isset($_GET["id"])?(int)$_GET["id"]:0);    //need to be modified when there is a table to link users and projects
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $row = $res->FetchRow();
		

	    $smarty->assign("priority", Lang::getLanguageString("priority"));
	    $smarty->assign("prioritysb", $priority[$row["id_priority"]]);

	    $smarty->assign("severity", Lang::getLanguageString("severity"));
	    $smarty->assign("severitysb", $severity[$row["id_severity"]]);

	    $smarty->assign("resolution", Lang::getLanguageString("resolution"));
	    $smarty->assign("resolutionsb", $resolution[$row["id_resolution"]]);
    
        $smarty->assign("short_descval", $row["short_desc"]);
        $smarty->assign("long_descval", $row["long_desc"]);

        $smarty->assign("idtxt", Lang::getLanguageString("id"));
        $smarty->assign("idval", isset($_GET["id"])?(int)$_GET["id"]:0);
	    $smarty->display('tts_ticket.tpl',$_SESSION["MGW"]->userid."_".(isset($_GET["projid"])?(int)$_GET["projid"]:0)."_".(isset($_GET["id"])?(int)$_GET["id"]:0));

		return true;
    }

    function viewEditForm() {
        global $conn, $smarty, $appconf;
        global $priority, $severity, $resolution;
        
    	$sql = "SELECT * FROM mgw_tts WHERE id=".$this->id;
    	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    	$row = $res->FetchRow();
    
    	if((queryRights2_bool('root_modules_tts_modify') && $row["owner"] == $_SESSION["MGW"]->userid) ||
    	   (queryRights2_bool('root_modules_tts_modifyothers') && $row["owner"] != $_SESSION["MGW"]->userid)){
    	    include_once(INCLUDEPATH . "mSelectBox.class.php");
    
            // Id 
            $smarty->assign("idtxt", Lang::getLanguageString("id"));
            $smarty->assign("idval", isset($_GET["id"])?(int)$_GET["id"]:0);
            
            //project select Box
            $smarty->assign("project","add");
            $smarty->assign("mode","modify");
            $smarty->assign("current_tts",isset($_GET["id"])?(int)$_GET["id"]:0);
            $smarty->assign("suname","modify");
            $smarty->assign("suvalue",Lang::getLanguageString("modify"));
            $smarty->assign("suclass","submit");
            
            $sql="select project_id, title from mgw_projects";
            $sb6 = new mSelectBox("_project",isset($_GET["projid"])?(int)$_GET["projid"]:0);
            $sb6->setContentType("sql");
            $sb6->setSQLvalue("project_id");
            $sb6->setSQLcontent("title");
            $sb6->addContent($sql);
            $sb6->addOption("0", Lang::getLanguageString("chooseproject"), "pre");
            $smarty->assign("projectsb", $sb6->draw());
            unset($sb6);
            
            //owner text
            $sql="select * from mgw_users where id=".$_SESSION["MGW"]->userid;
            if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            $row = $res->FetchRow();
            $smarty->assign("ownerval",$row["lastname"].", ".$row["firstname"]);
            $smarty->assign("ownervalid",$row["id"]);
            //user of the project select Box
            
            $concat=$conn->Concat("lastname", "', '", "firstname");
            $name = array();
        
            $sql="select $concat as name, id from mgw_users where is_ldap=1";    //need to be modified when there is a table to link users and projects
            if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            $i=1;
            while(!$res->EOF) {
                $name[$res->Fields("id")] = $res->Fields("name");
                $res->movenext();
                $i++;
            }
            
            $sql="select * from mgw_tts where id=".(isset($_GET["id"])?(int)$_GET["id"]:0);    //need to be modified when there is a table to link users and projects
            if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            $row = $res->FetchRow();
            
            $sb7 = new mSelectBox("_assigned",isset($_GET["assignedto"])?(int)$_GET["assignedto"]:0);
            $sb7->setContentType("arr");
            $sb7->addContent($name);
            $sb7->addOption("-1", Lang::getLanguageString("chooseassigned"), "pre");
            $smarty->assign("assignedsb", $sb7->draw());
            unset($sb7);
            
            
            //PRIOTITY
            $smarty->assign("priority", Lang::getLanguageString("priority"));
            $sb8 = new mSelectBox("_priority",$row["id_priority"]);
            $sb8->setContentType("arr");
            $sb8->addContent($priority);
            $smarty->assign("prioritysb", $sb8->draw());
            unset($sb8);            
            
            //SEVERITY
            $smarty->assign("severity", Lang::getLanguageString("severity"));
            $sb9 = new mSelectBox("_severity",$row["id_severity"]);
            $sb9->setContentType("arr");
            $sb9->addContent($severity);
            $smarty->assign("severitysb", $sb9->draw());
            unset($sb9);    
            
            //RESOLUTION
            $smarty->assign("resolution", Lang::getLanguageString("resolution"));
            $sb10 = new mSelectBox("_resolution",$row["id_resolution"]);
            $sb10->setContentType("arr");
            $sb10->addContent($resolution);
            $smarty->assign("resolutionsb", $sb10->draw());
            unset($sb10);  
            
            $smarty->assign("short_descval", $row["short_desc"]);
            $smarty->assign("long_descval", $row["long_desc"]);
            
            $smarty->display('tts_ticket.tpl',$_SESSION["MGW"]->userid."_".(isset($_GET["projid"])?(int)$_GET["projid"]:0)."_".isset($_GET["id"])?(int)$_GET["id"]:0);
    
    	    return true;
    	}
    	else{
    	    $smarty->assign("errorheader",Lang::getLanguageString("permerror"));
    	    $smarty->assign("permerror",Lang::getLanguageString("permerrormsg"));
    	    $smarty->display($appconf["gentemplates"] ."/perm_errors.tpl");
    	    exit();
    	}
    }

    function viewList($ownersb, $assignedUsersb, $prioritysb, $severitysb, $resolutionsb) {
        global $conn, $smarty;
        global $priority, $severity, $resolution, $priorityColor;
        
        //to avoid EALL notice
        $urls=array();
        $list=array();
		include_once(INCLUDEPATH . "mSelectBox.class.php");        
    
        // =================================================
        //	              List View
        // =================================================
        // if user wants icons, assign icons if not -> not
        if($_SESSION["MGW"]->settings["iconmode"]==1) {
            $detailsym = "<img src=\"". $appconf["imgpathgeneral"]. "/details_". $_SESSION["MGW"]->settings["iconid"]. ".gif\" border=\"0\" alt=\"".Lang::getLanguageString("details")."\" title=\"".Lang::getLanguageString("details")."\">";
            $editsym = "<img src=\"". $appconf["imgpathgeneral"]. "/edit_". $_SESSION["MGW"]->settings["iconid"]. ".gif\" border=\"0\" alt=\"".Lang::getLanguageString("edit")."\" title=\"".Lang::getLanguageString("edit")."\">";
            $delsym = "<img src=\"". $appconf["imgpathgeneral"]. "/delete_". $_SESSION["MGW"]->settings["iconid"]. ".gif\" border=\"0\" alt=\"".Lang::getLanguageString("delete")."\" title=\"".Lang::getLanguageString("delete")."\">";
            $prevsym = "<img src=\"". $appconf["imgpathgeneral"]. "/left_". $_SESSION["MGW"]->settings["iconid"]. ".gif\" border=\"0\">";
            $nextsym = "<img src=\"". $appconf["imgpathgeneral"]. "/right_". $_SESSION["MGW"]->settings["iconid"]. ".gif\" border=\"0\">";
            $privsym = "<img src=\"" . $appconf["imgpathgeneral"] . "/private_". $_SESSION["MGW"]->settings["iconid"]. ".gif\" alt=\"Private\" border=\"0\">";
            $smarty->assign("iconid", $_SESSION["MGW"]->settings["iconid"]);
            $smarty->assign("iconmode", true);
        } else {
            $detailsym = Lang::getLanguageString("details");
            $editsym = Lang::getLanguageString("edit");
            $delsym = Lang::getLanguageString("delete");
            $privsym = Lang::getLanguageString("private");
            $prevsym = "&lt;&lt;--|";
            $nextsym = "|--&gt;&gt;";
            $smarty->assign("iconmode", false);
        }
        $smarty->assign("prevsym", $prevsym);
        $smarty->assign("nextsym", $nextsym);
    

        
        
        
		//no job occupation needed
    
    
        //construction of the where sentence
        $where = "";
        if($ownersb > -1) {
        	$where.=" and mgw_tts.id_owner = $ownersb";	
        }
        if($assignedUsersb > -1) {
        	$where.=" and mgw_tts.id_assigned = $assignedUsersb";	
        }
        if($prioritysb > -1) {
        	$where.=" and mgw_tts.id_priority = $prioritysb";	
        }
        if($severitysb > -1) {
        	$where.=" and mgw_tts.id_severity = $severitysb";	
        }
        if($resolutionsb > -1) {
        	$where.=" and b.id_resolution = $resolutionsb";	
        }
        
        $sql="SELECT DISTINCT
             b.id_project,
             a.title
             FROM mgw_projects a
	     RIGHT OUTER JOIN mgw_tts b ON a.project_id=b.id_project 
         WHERE b.id_project = b.id_project $where";
    
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        
        $arr_result=array();
        $sav_id_project=0;
        
		$counter = 0;
        while($row = $res->FetchRow()) {
            $counter++;
            $id_project = $row["id_project"];//$res->Fields("id");
            $index=count($arr_result);
            $arr_result[$index][0]["id"]=$row["id_project"];
            $myid=$res->Fields("id"); // huh?
            $arr_result[$index][0]["name"]=$row["title"];
    //      $arr_result[$index][0]["link"]="../projects/index.php?action=details&id=".$res->Fields(id)."&".SID;
            $sql="select mgw_tts.*
                 from mgw_tts
                 where id_project=".$id_project. " $where";
    	//echo $sql;
            if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            //$row = $res2->FetchRow();
            $i=0;
            $arrowner=array();
            $assigned=array();
            $arrid=array();
            while($row2 = $res2->FetchRow()) {
               
                   //echo "<br>aasi : ".$row2["id_assigned"]."  -  ".is_numeric($row2["id_assigned"])."  -" . $row2["short_desc"]."<br>\n";
    
                //is assigned or is the owner member of the bug
                $defassigned[$i]=0;
                $defowner[$i]=0;
    
                if(is_numeric($row2["id_assigned"])){
                    $defassigned[$i]=1;
    		$conass = $conn->Concat('c.lastname', "', '",'c.firstname');
                    $sql="SELECT DISTINCT
                         $conass AS assigned,
                         c.id
                         FROM mgw_tts a,
                         mgw_users c
                         WHERE
                         a.id_assigned=c.id AND
                         a.id=".$row2["id"];
    
                    if(!$res3 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
                    $row3 = $res3->FetchRow();
                    $arrassigned[$i]=$row3;
                    $arrid[$i]=$row3["id"];
                }
                //is assigned or is the owner member of the application
                if($row2["id_owner"]>-1){
                    $defowner[$i]=1;
                    $sql="SELECT ALL
                         $conass AS owner,
                         c.id
                         FROM mgw_tts a,
                         mgw_users c
                         WHERE
                         a.id_owner=c.id and
                         a.id_owner=".$row2["id_owner"];
    
                   if(!$res4 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
                    $row4 = $res4->FetchRow();
                    $arrowner[$i] = $row4;
                    $arrid[$i]=$row4["id"];
    
                } else {//if its own by nobody, take the value submited with the form
                    $defowner[$i]=1;
                    $sql="select distinct a.owner_name as owner, a.owner_email as email, a.id
                         from mgw_tts a
                         where id_project=".$id_project;
                    if(!$res4 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
                    $row4 = $res4->FetchRow();
                    $arrowner[$i] = $row4;
                    $arrid[$i]=$row4["id"];
                }
                $arrid[$i]=$row2["id"];
                $i++;
            }
    
    
            $res2->moveFirst();
            if(isset($defassigned)) $res3->moveFirst();
            if(isset($defowner)) $res4->moveFirst();
            //print_r($arrassigned);
            $i=0;
            while(!$res2->EOF) {
                $arr_result[$index][1][$i]=$res2->FetchRow();
                
                if($defassigned[$i]==1) {
                    $arr_result[$index][2][$i]["assigned"]=$arrassigned[$i]["assigned"];
                }
                if($defowner[$i]==1) {
                    if(!empty($row4["email"])) {
                        $arr_result[$index][2][$i]["owner"]="<a href=\"mailto:".$arrowner[$i]["email"]."\">".$arrowner[$i]["owner"]."</a>";
                    } else {
                        $arr_result[$index][2][$i]["owner"]=$arrowner[$i]["owner"];
                    }
                }
    
                
     
                $arr_result[$index][2][$i]["priorityColor"]=$priorityColor[$arr_result[$index][1][$i]["id_priority"]];
                $arr_result[$index][2][$i]["severity"]=$severity[$arr_result[$index][1][$i]["id_severity"]];
                $arr_result[$index][2][$i]["resolution"]=$resolution[$arr_result[$index][1][$i]["id_resolution"]];                        
                
                $myid=$arrid[$i];
                //print_r($arrid);
                // we do this in order not to convert too much of the $row[] fields
    
                // create Action URLs
                $detlink = "<a href=\"".$_SERVER["PHP_SELF"]."?action=detail&id=$myid&projid=".$id_project."&".SID."\" CLASS=\"edit\">$detailsym</a>";
    
                // modify only for user with appropriate rights
    		if((queryRights2_bool('root_modules_tts_modify') and $row2["id_owner"] ==$_SESSION["MGW"]->userid)
    			 || (queryRights2_bool('root_modules_tts_modifyothers') and $row2["id_owner"] <> $_SESSION["MGW"]->userid)) {
                    $editlink = "<a href=\"".$_SERVER["PHP_SELF"]."?action=editform&projid=".$id_project."&id=$myid&assignedto=".$arrassigned[$i]["id"]."&act=$action&searchterm=$searchterm&list=$list&npage=$npage&".SID."\" CLASS=\"edit\">$editsym</a>";
                }
                else {
                    $editlink = "";
                }
    
                // make a new intervention only for user with appropriate rights
                if((queryRights2_bool('root_modules_tts_modify') and $row2["id_owner"] == $_SESSION["MGW"]->userid)
                        || (queryRights2_bool('root_modules_tts_modifyothers') and $row2["id_owner"] <> $_SESSION["MGW"]->userid)) {
                    $interlink = "<a href=\"".$_SERVER["PHP_SELF"]."?action=newinter&projid=".$id_project."&id=$myid&assignedto=".$arrassigned[$i]["id"]."&act=$action&searchterm=$searchterm&list=$list&npage=$npage&".SID."\" CLASS=\"delete\">".Lang::getLanguageString("newinter")."</a>";
                }
                else {
                    $interlink = "";
                }
    
                $historic = "<a href=\"".$_SERVER["PHP_SELF"]."?action=historic&projid=".$id_project."&id=$myid&assignedto=".$arrassigned[$i]["id"]."&act=$action&searchterm=$searchterm&list=$list&npage=$npage&".SID."\" CLASS=\"edit\">".Lang::getLanguageString("historic")."</a>";
    //          $detail   = "<a href=\"".$_SERVER["PHP_SELF"]."?action=detail&projid=".($index+1)."&id=$myid&assignedto=".$arrassigned[$i]["id"]."&act=$action&searchterm=$searchterm&list=$list&npage=$npage&".SID."\"CLASS=\"edit\">".Lang::getLanguageString("historic")."</a>";
                $space = "&nbsp;&nbsp;";
                $urls[$index][] = $detlink . $space . $editlink .$space . $interlink . $space . $historic;
    
                $mailto[] = "<a href=\"mailto:" . $row["email"] . "\">" . $row["email"] . "</a>";
    
                if($row["ispublic"]==1) $images[] = "&nbsp;";
                else $images[] = $privsym;
    
                $i++;
                if(isset($defassigned)) $res3->moveNext();// a revoir
            }
        }
    
        $smarty->assign("tout",$arr_result);
    
		//ASSIGN COMBOBOXES

            //PRIOTITY
            $smarty->assign("priority", Lang::getLanguageString("priority"));
            $sb8 = new mSelectBox("_priority",$prioritysb);
            $sb8->setContentType("arr");
            $sb8->addContent($priority);
            $smarty->assign("prioritysb", $sb8->draw());
            unset($sb8);            
            
            //SEVERITY
            $smarty->assign("severity", Lang::getLanguageString("severity"));
            $sb9 = new mSelectBox("_severity",$severitysb);
            $sb9->setContentType("arr");
            $sb9->addContent($severity);
            $smarty->assign("severitysb", $sb9->draw());
            unset($sb9);    
            
            //RESOLUTION
            $smarty->assign("resolution", Lang::getLanguageString("resolution"));
            $sb10 = new mSelectBox("_resolution",$resolutionsb);
            $sb10->setContentType("arr");
            $sb10->addContent($resolution);
            $smarty->assign("resolutionsb", $sb10->draw());
            unset($sb10);     

			//OWNER
			$con = $conn->Concat('u.lastname', "', '",'u.firstname');
            $sql="select distinct $con as owner, u.id from mgw_tts t, mgw_users u where t.id_owner=u.id";
            $sb11 = new mSelectBox("_owner",$ownersb);
            $sb11->setContentType("sql");
            $sb11->setSQLvalue("id");
            $sb11->setSQLcontent("owner");
            $sb11->addContent($sql);
            $sb11->addOption("-1", Lang::getLanguageString("undetermined"), "pre");
            $smarty->assign("ownersb", $sb11->draw());
            unset($sb11);
            
            //ID
            $sql="select distinct t.id from mgw_tts t";
            $sb12 = new mSelectBox("_id",-1);
            $sb12->setContentType("sql");
            $sb12->setSQLvalue("id");
            $sb12->setSQLcontent("id");
            $sb12->addContent($sql);
            $sb12->addOption("-1", Lang::getLanguageString("undetermined"), "pre");
            $smarty->assign("idsb", $sb12->draw());
            unset($sb12);

			//ASSIGNED
			$con = $conn->Concat('u.lastname', "', '",'u.firstname');
            $sql="select distinct $con as assigned, u.id from mgw_tts t, mgw_users u where t.id_assigned=u.id";
            $sb12 = new mSelectBox("_assigned",$assignedUsersb);
            $sb12->setContentType("sql");
            $sb12->setSQLvalue("id");
            $sb12->setSQLcontent("assigned");
            $sb12->addContent($sql);
            $sb12->addOption("-1", Lang::getLanguageString("undetermined"), "pre");
            $smarty->assign("assignedsb", $sb12->draw());
            unset($sb12);

  
    
    
        $smarty->assign("hascreaterights", queryRights2_bool('root_modules_tts_write'));
        $smarty->assign('urls', $urls);    
        $smarty->assign('list', $list);    
        
        $smarty->assign('action', Lang::getLanguageString("action"));
        $smarty->assign('suvalue', Lang::getLanguageString("search"));
        $smarty->assign('suclass', "submit");
        
        
    
        $smarty->display("tts_list.tpl",$_SESSION["MGW"]->userid);
    
    
    	return true;
    }
    /********************
	* GETTER and SETTER * 
	*********************/
    function getId() {
    	return $this->id;	
    }
    
    function setId($id) {
    	$this->id = $id;
    }
    
}
?>