<?php
// exportpdf.php - display file in pdf
// ------------------------------------------------------------------------
// Copyright (c) 2004, 2005 David Han Sze Chuen, Denis Guinnepain for Air Liquide Medical Systems (Taema)
// Copyright (c) 2005, 2006, 2015 Denis Guinnepain
 
// ------------------------------------------------------------------------
// This file is part of Diamentis

// Diamentis is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.

// Diamentis is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with phpBugTracker; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ------------------------------------------------------------------------
include_once('include.php');
require('fpdf/fpdf.php');

define ('LINE_SPACING', 5);

class PDF extends FPDF
{
//En-tête
var $header_title="Titre";
//Colonne courante
var $col=0;
//Ordonnée du début des colonnes
var $y0;
var $_RightMargin;
var $maxY;
var $firstPage;
var $x_org;
var $y_org;

function Init()
{
   $this->col=0;
   $this->y0=30;
   $this->maxY=30;
   $this->firstPage=$this->PageNo();
}


function SetHeadTitle($new_title)
{
	$this->header_title=$new_title;
}

function Header()
{
    //Logo
//    $this->Image('logo_pb.png',10,8,33);
    //Police Arial gras 15
    $this->SetFont('Arial','B',15);
    //Décalage à droite
    //$this->Cell(80);
    //Titre
    $this->SetLineWidth(0.1);
    $this->SetDrawColor(0,0,0);
    $this->Cell(0,10,$this->header_title,1,0,'C');
    //Saut de ligne
    $this->Ln(20);
}

//Pied de page
function Footer()
{
    //Positionnement à 1,5 cm du bas
    $this->SetY(-15);
    //Police Arial italique 8
    $this->SetFont('Arial','I',8);
    //Numéro de page
    $this->Cell(0,10,'Page '. (1+$this->PageNo()-$this->firstPage),0,0,'C');
}

function InitCol()
{
   $this->col=0;
}

function SetCol($col)
{
    //Positionnement sur une colonne
    $this->col=$col;
    if ($col==1)
    {
       if ($this->maxY>$this->GetY())
       {
          $this->SetY($this->maxY);
       }
       $this->y0=$this->GetY();
    }
    else
    {
       if ($this->maxY<$this->GetY())
       {
          $this->maxY=$this->GetY();
       }
       $this->SetY($this->y0);
    }
    $x=10*$col+($col-1)*90;
    $y=120-$x;
    $this->SetLeftMargin($x);
    $this->SetRightMargin($y);
    $_RightMargin=$y;
    $this->SetX($x);
}

function NextCol()
{
   if ($this->col==1)
   {
      $this->SetCol(2);
   }
   else
   {
      $this->SetCol(1);
   }
}

function SetUniqueCol()
{
    //Positionnement sur une colonne
    $this->SetLeftMargin(10);
    $this->SetRightMargin(10);
    $_RightMargin=10;
    $this->SetX(10);
}

function Section($title)
{
   $this->SetCol(1);
   $this->SetUniqueCol();
   $this->SetFont('Arial','B',14);
   $this->SetFillColor(200,200,200);
   $this->SetDrawColor(0,0,0);
   $this->SetLineWidth(0.1);
   $this->Ln(LINE_SPACING);
   $this->Cell(190,7, $title ,1,1,'L',1);

}

function Chapter($title)
{
    //Positionnement sur une colonne
    $this->SetCol(1);
    $this->SetUniqueCol();
    $this->Ln(3);
    $this->x_org=$this->GetX();
    $this->y_org=$this->GetY();
    $this->SetFont('Arial','',13);
    $this->Write(6,$title);
    $x_dest=$this->GetX();
    $y_dest=$this->GetY();
    $this->SetLineWidth(0.2);
    $this->SetFillColor(200,200,200);
    $height=$y_dest-$this->y_org;
    if ($height>0 && $this->y_org!=30)  //height of the line + error du to approximation
    {
    	$width=210-$this->_RightMargin-$this->x_org;
    }
    else 
    {
        $width=$x_dest-$this->x_org;
    }
    
    $this->Rect($this->x_org,$this->y_org,$width+2,6+$height,'F');    
    $this->SetX($this->x_org);
    $this->Write(6,$title);
    $this->Ln(6);
    $this->SetLineWidth(0.5);
    $this->SetDrawColor(200,200,200);
    $this->Line($this->GetX(),$this->GetY(),210-$this->RightMargin-$this->GetX(),$this->GetY());
    $this->Ln(1);
    $this->SetCol(1);
    $this->col=0;
    
}

function DashAfterCol()
{

   $this->SetLineWidth(0.5);
   $this->SetDrawColor(200,200,200);
   if ($this->maxY<$this->GetY())
   {
      $this->maxY=$this->GetY();
   }
   $this->Line(10,$this->maxY,200,$this->maxY);
   $this->SetCol(1);
   $this->InitCol();
   $this->SetY($this->maxY);

}

function DashAfter()
{

   $this->SetLineWidth(0.5);
   $this->SetDrawColor(200,200,200);
   $this->Line(10,$this->GetY(),200,$this->GetY());

}



function AcceptPageBreak()
{
    //Méthode autorisant ou non le saut de page automatique
    $this->maxY=30;
    $this->y0=30;
    $this->y_org=30;
    return true;
}


}

//function print_file($file,$fc_filtered,$mpfile,$field_conf)
function print_file($file_id)
{
global $db,$STRING,$TITLE,$me,$pdf;

   $pdf->SetHeadTitle($STRING['File'] . " " . APPLICATION_NAME . " $file_id");
   $pdf->SetTitle($STRING['File'] . " " . APPLICATION_NAME );
   $pdf->AliasNbPages();
   $pdf->AddPage();
   $pdf->Init();


	list($mpfile, $field_conf, $fc_filtered, $file) = MPFile::getFile_kit($file_id, null, 'edit_order', 'asc');

//printarray($file);
//printarray($fc_filtered);die;

//Print the description on the whole page
//	$value=$file['created_by']['value'];
	// if nobody is associated
//	if ($value == null) 
//	{
//		$s = $STRING['nobody'];
//	} 
//	else 
//	{
//		$res = $db->getAll("SELECT email, first_name, last_name FROM " . TBL_AUTH_USER . " WHERE user_id = " . $db->quote($value));
//		$rs = array();
//		foreach($res as $r) 
//		{
//			$email = $r['email'];
//			$first_name = $r['first_name'];
//			$last_name = $r['last_name'];
//			$rs[] = "$first_name $last_name ";//<$email>";
//			$s = implode(', ', $rs);
//		} 
//	}
//	$value=$s;

	$pdf->SetUniqueCol();
//	$pdf->SetFont('Arial','I',10);
//	$pdf->Write(LINE_SPACING, $STRING['BUGDISPLAY']['postedby']. " : $value"  );
//	$pdf->Ln(LINE_SPACING);
   if ($file['description']['subproperty']->hidden!=true)
   {
	$pdf->Section($STRING['description_of_file'] . " $file_id : " . $file['title']['value']);
	$pdf->SetLeftMargin(15);
	$pdf->SetFont('Courier','',10);
	$value=$file['description']['value'];
	$pdf->Write(LINE_SPACING, $value);
	$pdf->Ln(LINE_SPACING);
	$pdf->Ln(LINE_SPACING);
	$pdf->Section($TITLE['file_consultation'] );
   }
   else
   {
	$pdf->Section($TITLE['file_consultation'] . " $file_id : " . $file['title']['value']);
   }

	$pdf->SetCol(0);
		


foreach ($fc_filtered as $k => $v )
{
	$link=null;
	$value=null;
	$fid = $file[$k]['field_conf']['field_conf_id'];
	$field_name = $file[$k]['field_conf']['field_name'];
	$expanded_text='';
	if ($field_name=="description")
	{
		continue;
	}
	$prop=$file[$k]['subproperty'];
	if ($prop->label)
	{
		$pdf->Chapter($v['title']);
	}
	else
	{
		switch ($k)
		{
			case 'project_id':
				$value=$db->getOne("SELECT project_name FROM " .TBL_PROJECT. " WHERE project_id=" . $file[$k]['value']);
				break;
			case 'assigned_to':
				$assigned_value = null;
				$assignation = $db->getAll("SELECT u.* FROM " . TBL_ASSIGNATION . " a, " . TBL_AUTH_USER . 
					" u WHERE u.user_id = a.user_id AND a.file_id IN (". $db->quote($file_id) .") ORDER BY first_name, last_name" );
				$assigned_value = array();
				foreach($assignation as $av) 
				{
					$assigned_value[] = $av['user_id'];
				} 				
				// if nobody is associated
				if (empty($assigned_value)) 
				{
					$s = $STRING['nobody'];
				} 
				else 
				{ // if some people are associated
					$res = $db->getAll("SELECT email, first_name, last_name FROM " . TBL_AUTH_USER
						 . " WHERE user_id IN (" . ((is_array($assigned_value))? implode(', ', $assigned_value) : $db->quote($assigned_value))
						 . ") ORDER BY first_name, last_name");

					$rs = array();
					foreach($res as $r) 
					{
						$email = $r['email'];
						$first_name = $r['first_name'];
						$last_name = $r['last_name'];
						$rs[] = "$first_name $last_name <$email>";
						$s = implode(', ', $rs);
					}					
				}
				$value=$s;
				break;
			case 'fd': 
				break;
			default;
				$type=$file[$k]['field_conf']['field_type_title'];
				switch ($type)
				{
					case SELECT_TWINBOX_TYPE:
						//the fid has to be transfert to the twin one
						$sp = &$mpfile->sp_cache[$field_name]; 
						 if (isset($sp->SB_twin_id)) 
						 {
					 		$fid=$sp->SB_twin_id;
							$fid = intval($fid);
						 }
						 else
					 	 {
							 printarray($params);
							 printarray($field_name);
							 printarray($mpfile->sp_cache);
							death('ERROR', '05 build_dynamic_input() : non specified twinbox.');
						 } 
					case SELECTBOX_TYPE:
						if ($fid==22 || $fid==23) //case 'last_modified_by' :case 'created_by' 
						{
							$value=$file[$k]['value'];
						//println("fid vaut $fid et le type est $type et value vaut $value");
						//printarray($file[$k]);
							// if nobody is associated
							if ($value == null) 
							{
								$s = $STRING['nobody'];
							} 
							else 
							{
								$res = $db->getAll("SELECT email, first_name, last_name FROM " . TBL_AUTH_USER . " WHERE user_id = " . $db->quote($value));

								$rs = array();
								foreach($res as $r) 
								{
									$email = $r['email'];
									$first_name = $r['first_name'];
									$last_name = $r['last_name'];
									$rs[] = "$first_name $last_name <$email>";
									$s = implode(', ', $rs);
								} 
							}
							$value=$s;
						}
						else
						{
							$value=$file[$k]['selectbox']['value'];
							$expanded_selectbox_sv_ids = $mpfile->getSv_ids_by_option('expanded');
							if (in_array($file[$k]['value'], $expanded_selectbox_sv_ids))
							{
								$expanded_text=$file[$k]['selectbox']['description'];	
							}
						}
						break;
					case TIMESTAMP_TYPE :
						$value=$file[$k]['value'];
						if (!empty($value)) 
						{
							$time_to_string = timestamp_to_string($value, $mpfile->sp_cache[$k]->time_type);
							$value = htmlspecialchars($time_to_string);
						} 
						else 
						{
							$time_to_string = '';
							$value = '';
						}
						break;

					default:
						$value=$file[$k]['value'];
						break;
				}
				break;
		}

		
		$pdf->NextCol();
		if ($prop->highlight_url)
		{
			$link=$value;
		}
		$pdf->SetFont('Arial','B',11);
		$pdf->Write(LINE_SPACING, $v['title'] . " : ", $link);
		if ( $file[$k]['field_conf']['field_type_title']==STRING_TYPE && $prop->maxlen==0 )
		{
		   $pdf->Ln(LINE_SPACING);
		}
		$pdf->SetFont('Arial','',11);
		$pdf->Write(LINE_SPACING, $value,$link);
		$pdf->Ln(LINE_SPACING);
		if ($expanded_text!='')
		{
			$pdf->Write(LINE_SPACING, $expanded_text);
			$pdf->Ln(LINE_SPACING);
		}
		if ($prop->dashAfter)
		{
		    $pdf->DashAfterCol();
		}
	}
}
// contact list
   $pdf->Chapter($STRING['BUGDISPLAY']['Rest_RO']);

   $pdf->InitCol();
   $pdf->NextCol();
   $ccl = array();
   $sql = "SELECT u.user_id, u.first_name, u.last_name, u.email FROM " . TBL_BUG_CC . " c, " . TBL_AUTH_USER . " u WHERE u.user_id = c.user_id AND c.bug_id = " . $db->quote($file_id) . " order by first_name, last_name";
   $rs = array();
   foreach($db->getAll($sql) as $v) 
   {
      $ccl[] = $v;
      $email = $v['email'];
      $first_name = $v['first_name'];
      $last_name = $v['last_name'];
      $rs[] = "$first_name $last_name <$email>";
      $s = implode(', ', $rs);
   }
	
// if nobody is associated
   if (empty($ccl)) 
   {
      $s = $STRING['nobody'];
   } 

   $pdf->SetFont('Arial','B',11);
   $pdf->Write(LINE_SPACING, $STRING['BUGDISPLAY']['contact_list']);
   $pdf->SetFont('Arial','',11);
   $pdf->Write(LINE_SPACING, " : " . $s);
   $pdf->Ln(LINE_SPACING);



   $bug_dep=array();
   $bug_dep=$db->getCol("SELECT depends_on FROM " . TBL_BUG_DEPENDENCY . " where bug_id = $file_id" );
   $s=array();
   $pdf->NextCol();
   $pdf->SetFont('Arial','B',11);
   $pdf->Write(LINE_SPACING, $STRING['BUGDISPLAY']['bugdependency'] . " : ");
// if nobody is associated
   if (empty($bug_dep)) 
   {
      $s = $STRING['none'];
   }
   else
   {
      $i=0;
      foreach($bug_dep as $v) 
      {
         $i++;
	 if ($i!=1)
	 {
	 	$pdf->Write(LINE_SPACING, ", ");
	 }
	 $link = INSTALL_URL . "/bug.php?op=show&file_id=" . $v;
         $pdf->SetFont('Arial','',11);
         $pdf->Write(LINE_SPACING, $STRING['file'] . " $v", $link);
      }

   }
      $pdf->Ln(LINE_SPACING);





   $pdf->SetCol(1);
   $pdf->SetUniqueCol();
   $pdf->SetFont('Arial','B',11);
   $pdf->Write(LINE_SPACING, $STRING['BUGDISPLAY']['attachments'] );
   $pdf->Ln(LINE_SPACING);
   $pdf->DashAfterCol();

   $attachments = array();
   $rs = $db->query("select file_name, description, file_size from " . TBL_ATTACHMENT . " where bug_id = $file_id");
	
   if ($rs->numRows()) 
   {
	while ($rs->fetchInto($att)) 
	{
	   $attachments[] = $att;
	   $s=$att['file_name'] . ", " . intval($att['file_size']/1000) . "kB";
	   if ($att['description']!="")
	   {
	      $s.=" : " . $att['description'];
	   }
	   $pdf->SetFont('Arial','',11);
           $pdf->Write(LINE_SPACING, $s);
           $pdf->Ln(LINE_SPACING);
	   $pdf->DashAfter();
	   
	}
   }

   if (empty($attachments)) 
   {
      $s = $STRING['BUGDISPLAY']['noattachments'];
      $pdf->SetFont('Arial','',11);
      $pdf->Write(LINE_SPACING, $s);
      $pdf->Ln(LINE_SPACING);
      $pdf->DashAfter();
   }




   $comments= $db->getAll('select comment_text, c.created_date, first_name, last_name from ' . TBL_COMMENT . ' c, ' . TBL_AUTH_USER . " where bug_id = $file_id and c.created_by = user_id order by c.created_date");

   $pdf->Section($STRING['BUGDISPLAY']['comments']);
   $pdf->SetUniqueCol();

   foreach($comments as $r) 
   {
      $first_name = $r['first_name'];
      $last_name = $r['last_name'];
      $pdf->SetFont('Arial','I',10);
      $pdf->SetLeftMargin(10);
      $pdf->Write(LINE_SPACING, $STRING['BUGDISPLAY']['postedby']. " : $first_name $last_name"  );
      $pdf->Ln(LINE_SPACING);
      $pdf->SetLeftMargin(15);
      $pdf->SetFont('Courier','',10);
      $value=$r['comment_text'];
      $pdf->Write(LINE_SPACING, $value);
      $pdf->SetLeftMargin(10);
      $pdf->Ln(LINE_SPACING);
      $pdf->DashAfter();
      
   }
   if (empty($comments))
   {
      $s = $STRING['BUGDISPLAY']['no_comments'];
      $pdf->SetFont('Arial','',11);
      $pdf->Write(LINE_SPACING, $s);
      $pdf->Ln(LINE_SPACING);
      $pdf->DashAfter();
   }

   $history= $db->getAll('SELECT fh.*, au.first_name, au.last_name, au.email FROM ' . TBL_FILE_HISTORY . " fh, " . TBL_AUTH_USER . " au WHERE bug_id = $file_id AND fh.created_by=au.user_id ORDER BY fh.created_date");

   $pdf->Section($TITLE['bughistory']);
   $pdf->SetUniqueCol();
   $pdf->Ln(LINE_SPACING);

   $pdf->SetFont('Arial','',11);
   $pdf->Cell(45,LINE_SPACING, $STRING['who'],1,0,'C',1);
   $pdf->Cell(23,LINE_SPACING, $STRING['what'],1,0,'C',1);
   $pdf->Cell(50,LINE_SPACING, $STRING['old_value'],1,0,'C',1);
   $pdf->Cell(50,LINE_SPACING, $STRING['new_value'],1,0,'C',1);
   $pdf->Cell(22,LINE_SPACING, $STRING['when'],1,1,'C',1);

   foreach($history as $r) 
   {
      $email = $r['email'];
      $first_name = $r['first_name'];
      $last_name = $r['last_name'];
      $pdf->SetFont('Arial','',7);
      $pdf->y0=$pdf->GetY();
      $pdf->maxY=$pdf->GetY();
      $pdf->MultiCell(45,LINE_SPACING/2, "$first_name $last_name \n<$email>",0,'C',0);
      $pdf->maxY=$pdf->GetY();
      $pdf->SetXY(55,$pdf->y0);
      $pdf->MultiCell(23,LINE_SPACING/2, $r['changed_field'],0,'C',0);
      if ($pdf->maxY<$pdf->GetY())
      {
         $pdf->maxY=$pdf->GetY();
      }
      $pdf->SetXY(78,$pdf->y0);
      $pdf->MultiCell(50,LINE_SPACING/2, $r['old_value'],0,'C',0);
      if ($pdf->maxY<$pdf->GetY())
      {
         $pdf->maxY=$pdf->GetY();
      }
      $pdf->SetXY(128,$pdf->y0);
      $pdf->MultiCell(50,LINE_SPACING/2, $r['new_value'],0,'C',0);
      if ($pdf->maxY<$pdf->GetY())
      {
         $pdf->maxY=$pdf->GetY();
      }
      $pdf->SetXY(178,$pdf->y0);
      $pdf->MultiCell(22,LINE_SPACING/2, date(DATE_FORMAT, $r['created_date']) . " " . date(TIME_FORMAT, $r['created_date']),0,'C',0);
      if ($pdf->maxY<$pdf->GetY())
      {
         $pdf->maxY=$pdf->GetY();
      }
      $pdf->SetXY(10,$pdf->maxY);

      $pdf->SetLineWidth(0.1);
      $pdf->SetDrawColor(0,0,0);
      $pdf->Line(10,$pdf->maxY,200,$pdf->maxY);
      $pdf->Line(10,$pdf->y0,10,$pdf->maxY);
      $pdf->Line(55,$pdf->y0,55,$pdf->maxY);
      $pdf->Line(78,$pdf->y0,78,$pdf->maxY);
      $pdf->Line(128,$pdf->y0,128,$pdf->maxY);
      $pdf->Line(178,$pdf->y0,178,$pdf->maxY);
      $pdf->Line(200,$pdf->y0,200,$pdf->maxY);
      
   }
   if (empty($history))
   {
      $s = $STRING['nobughistory'];
      $pdf->SetFont('Arial','',11);
      $pdf->Write(LINE_SPACING, $s);
      $pdf->Ln(LINE_SPACING);
      $pdf->DashAfter();
   }
   $pdf->Section($STRING['endOfFile']);
}


function print_single_file($file_id)
{
   global $pdf;
   $pdf=new PDF();
   print_file($file_id);
   $pdf->Output();
}


function print_multi_files($file_list)
{
   global $pdf;
   $pdf=new PDF();
   foreach ($file_list as $k=>$file_id)
   {
   	print_file($file_id);
   }
   $pdf->Output();
}

//print_multi_files();

?>
