<?php

/**
 * @package linea21.core
 * @subpackage system
 * @see tcpdf
 * @author linea21 <info@linea21.com>
 * @version $id SVN
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

require('tcpdf.php');

class idd_pdf extends TCPDF {

	// //////////////////////////////////
    // formattage titres item & info
    // //////////////////////////////////
    function FormatSdiItem($libelle)
    {
		$libelle="        ".$libelle;
		$this->SetFont(DOC_POLICE, SDI_ITEM_STYLE, SDI_ITEM_SIZE);
		$this->SetColor('SDI_ITEM_COLOR');
		$this->MultiCell(0,DOC_HEIGHT,$libelle,0,'L',0);
		$this->SetColor('DOC_COLOR');
		$this->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
    }
	
	function FormatSdiInfo($libelle)
    {
        $this->SetColor('BCKG_INFO', 'BCKG');
        $this->SetFont(DOC_POLICE, SDI_INFO_STYLE, SDI_INFO_SIZE);
        $this->SetColor('SDI_INFO_COLOR');
	$this->MultiCell(0,DOC_HEIGHT+1,$libelle,0,'L',1);
	$this->SetColor('DOC_COLOR');
	$this->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
	$this->Ln(DOC_INTERVAL);
    }
	
	// Saut de paragraphe
	function ParagraphBreak()
    {
        $this->SetColor('DOC_COLOR');
		$this->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
		$this->Ln(PARAGRAPH_BREAK);
    }
	
	
    // //////////////////////////////////
    // gestion header & footer
    // //////////////////////////////////
    function Footer()
    {
        global $report_settings;
        global $lang;

        $content = $report_settings['author'];
		if(!empty($report_settings['mail_author']))  {
			$content .= ' ('.$report_settings['mail_author'].')';
			$mailto='mailto:'.$report_settings['mail_author'];
		} else $mailto='';
		$content_comp= !empty($report_settings['service_author']) ? ' -- '.$report_settings['service_author'] : '';
		$content_comp.= !empty($report_settings['adress_author']) ? ' -- '.$report_settings['adress_author'] : '';
		
        $this->SetColor('DOC_COLOR_HEADER');
        $this->SetFont(DOC_POLICE, EM_STYLE, MIN_SIZE);
        $this->SetY(-10);
		$this->Line($this->GetX(), $this->GetY(), $this->GetX()+190, $this->GetY());
		$this->Cell($this->GetStringWidth($content), 4, $content, 0, 0, 'L', 0, $mailto);
		$this->Cell(0, 4, $content_comp, 0, 0, 'L');
		
        // Numéro et nombre de pages
        $this->Cell(0, 4, $lang['divers']['page'].' ' . $this->PageNo() . '/{nb}', 0, 0, 'R');
    } 

    function Header()
    {
        global $report_settings;
        global $lang;
		
        $today = date("d-m-Y");
        $content = formatText($report_settings['title']) .' - '. SITE_CITY_NAME;
		
        $this->SetColor('DOC_COLOR_HEADER');
        $this->SetFont(DOC_POLICE, EM_STYLE, MIN_SIZE);
		
		//$this->Cell(0, 4, $lang['statut']['published_on'].' '. $today, 0, 0, 'L');
		$this->Cell(0, 4, $today, 0, 0, 'L');
        $this->Cell(0, 4, $content, 0, 1, 'R');
		$this->Line($this->GetX(), $this->GetY(), $this->GetX()+190, $this->GetY());
		//$this->Image('inc_report/logo_p.png', $this->GetX(), $this->GetY());
		$this->Ln(PARAGRAPH_BREAK);
    } 
    // //////////////////////////////////
    // gestion dynamique des couleurs
    // //////////////////////////////////
    /**
    * idd_pdf::SetColor()
    * 
    * @param string $ink 
    * @param string $type 'TRACE' | 'FONT' | 'BCKG'
    * @return 
    */
    function SetColor($ink = 'DOC_COLOR', $type = 'FONT')
    {
        switch ($ink) {
            case 'DOC_COLOR':
                $r = 0;
                $g = 0;
                $b = 0;
                break;
			case 'DOC_COLOR_HEADER':
                $r = 34;
                $g = 122;
                $b = 155;
                break;
			case 'DOC_COLOR_BORDER';
				$r = 34;
                $g = 122;
                $b = 155;
                break;
			case 'DOC_TITLE_COLOR';
				$r = 34;
                $g = 122;
                $b = 155;
                break;
			case 'DOC_ADVISE_COLOR':
                $r = 113;
                $g = 114;
                $b = 115;
                break;
            case 'SDI_TITLE_COLOR':
                $r = 82;
                $g = 117;
                $b = 181;
                break;
            case 'SDI_ITEM_COLOR':
                $r = 236;
                $g = 158;
                $b = 22;
                break;
			case 'SDI_INFO_COLOR':
                $r = 255;
                $g = 255;
                $b = 255;
                break;
            case 'BCKG_PROVIDER':
                $r = 226;
                $g = 234;
                $b = 249;
                break;
            case 'BCKG_ITEM':
                $r = 226;
                $g = 234;
                $b = 249;
                break;
			case 'BCKG_INFO':
                $r = 119;
                $g = 152;
                $b = 183;
                break;
        } 
        switch ($type) {
            case 'FONT':
                $this->SetTextColor($r, $g, $b);
                break;
            case 'TRACE':
                $this->SetDrawColor($r, $g, $b);
                break;
            case 'BCKG':
                $this->SetFillColor($r, $g, $b);
                break;
        } 
    }
	
	
    // //////////////////////////////////
    // gestion signets
    // //////////////////////////////////
    var $outlines = array();
    var $OutlineRoot;

    function Bookmark($txt, $level = 0, $y = 0)
    {
        if ($y == -1)
            $y = $this->GetY();
        $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $this->PageNo());
    } 

    function _putbookmarks()
    {
        $nb = count($this->outlines);
        if ($nb == 0)
            return;
        $lru = array();
        $level = 0;
        foreach($this->outlines as $i => $o) {
            if ($o['l'] > 0) {
                $parent = $lru[$o['l']-1]; 
                // Set parent and last pointers
                $this->outlines[$i]['parent'] = $parent;
                $this->outlines[$parent]['last'] = $i;
                if ($o['l'] > $level) {
                    // Level increasing: set first pointer
                    $this->outlines[$parent]['first'] = $i;
                } 
            } else
                $this->outlines[$i]['parent'] = $nb;
            if ($o['l'] <= $level and $i > 0) {
                // Set prev and next pointers
                $prev = $lru[$o['l']];
                $this->outlines[$prev]['next'] = $i;
                $this->outlines[$i]['prev'] = $prev;
            } 
            $lru[$o['l']] = $i;
            $level = $o['l'];
        } 
        // Outline items
        $n = $this->n + 1;
        foreach($this->outlines as $i => $o) {
            $this->_newobj();
            $this->_out('<</Title ' . $this->_textstring($o['t']));
	    //$this->_out('<</Title ' . $this->_escapetext($o['t']));
            $this->_out('/Parent ' . ($n + $o['parent']) . ' 0 R');
            if (isset($o['prev']))
                $this->_out('/Prev ' . ($n + $o['prev']) . ' 0 R');
            if (isset($o['next']))
                $this->_out('/Next ' . ($n + $o['next']) . ' 0 R');
            if (isset($o['first']))
                $this->_out('/First ' . ($n + $o['first']) . ' 0 R');
            if (isset($o['last']))
                $this->_out('/Last ' . ($n + $o['last']) . ' 0 R');
            $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]', 1 + 2 * $o['p'], ($this->h - $o['y']) * $this->k));
            $this->_out('/Count 0>>');
            $this->_out('endobj');
        } 
        // Outline root
        $this->_newobj();
        $this->OutlineRoot = $this->n;
        $this->_out('<</Type /Outlines /First ' . $n . ' 0 R');
        $this->_out('/Last ' . ($n + $lru[0]) . ' 0 R>>');
        $this->_out('endobj');
    } 

    function _putresources()
    {
        parent::_putresources();
        $this->_putbookmarks();
    } 

    function _putcatalog()
    {
        parent::_putcatalog();
        if (count($this->outlines) > 0) {
            $this->_out('/Outlines ' . $this->OutlineRoot . ' 0 R');
            $this->_out('/PageMode /UseOutlines');
        } 
    }
	
	
	
	// //////////////////////////////////
    // creation de l'index
    // //////////////////////////////////
	function CreateIndex($depth=100){
	
	global $lang;
	global $link_array;
	
    //Titre
	$this->SetFont(DOC_POLICE, DOC_TITLE_STYLE, DOC_TITLE_SIZE);
	$this->SetColor('DOC_TITLE_COLOR');
    $this->Cell(0, DOC_HEIGHT, $lang['dashboard']['rap_summary'], 0, 2, 'C');
	$this->SetFont(DOC_POLICE, EM_STYLE, MIN_SIZE);
    $this->Ln(10);
	
	
	

    $size=sizeof($this->outlines)-1; // -1 pour supprimer le bookmark de l'index
    $PageCellSize=$this->GetStringWidth('p. '.$this->outlines[$size-1]['p'])+2;
	
	$cnt_level1=0;
    for ($i=0;$i<$size;$i++){
				
        //Décalage
        $level=$this->outlines[$i]['l'];
		if($level<$depth) {
	        if($level>0)
	            $this->Cell($level*8);
			
			// Titre de l'indicateur
			if($level==0) {
				$cnt_level1++;
				$link=$cnt_level1;
       			$this->SetColor('SDI_ITEM_COLOR');
			} else $link='';

			
			
	        //Libellé
	        $str=$this->outlines[$i]['t'];
	        $strsize=$this->GetStringWidth($str);
	        $avail_size=$this->w-$this->lMargin-$this->rMargin-$PageCellSize-($level*8)-4;
	        while ($strsize>=$avail_size){
	            $str=substr($str,0,-1);
	            $strsize=$this->GetStringWidth($str);
	        }
	        $this->Cell($strsize+2,$this->FontSize+2,$str, 0, 0, 'L', 0, $link);
			$this->SetColor('DOC_TITLE_COLOR');

	        //Points
	        $w=$this->w-$this->lMargin-$this->rMargin-$PageCellSize-($level*8)-($strsize+2);
	        $nb=$w/$this->GetStringWidth('.');
	        $dots=str_repeat('.',$nb);
	        $this->Cell($w,$this->FontSize+2,$dots,0,0,'R');
	
	        //Numéro de page
	        $this->Cell($PageCellSize,$this->FontSize+2,'p. '.$this->outlines[$i]['p'],0,1,'R');
		}
    }
	$this->SetFont(DOC_POLICE, DOC_TITLE_STYLE, DOC_TITLE_SIZE);
}
	
    // //////////////////////////////////
    // Tableau avec multicells
    // //////////////////////////////////
    var $widths;
    var $aligns;

    function SetWidths($w)
    { 
        // Tableau des largeurs de colonnes
        $this->widths = $w;
    } 

    function SetAligns($a)
    { 
        // Tableau des alignements de colonnes
        $this->aligns = $a;
    } 

    function Row($data)
    { 
        // Calcule la hauteur de la ligne
        $nb = 0;
        for($i = 0;$i < count($data);$i++)
        $nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
        $h = 5 * $nb; 
        // Effectue un saut de page si nécessaire
        $this->CheckPageBreak($h); 
        // Dessine les cellules
        for($i = 0;$i < count($data);$i++) {
            $w = $this->widths[$i];
            $a = isset($this->aligns[$i]) ? $this->aligns[$i] : 'L'; 
            // Sauve la position courante
            $x = $this->GetX();
            $y = $this->GetY(); 
            // Dessine le cadre
            $this->Rect($x, $y, $w, $h); 
            // Imprime le texte
            $this->MultiCell($w, 5, $data[$i], 0, $a); 
            // Repositionne à droite
            $this->SetXY($x + $w, $y);
        } 
        // Va à la ligne
        $this->Ln($h);
    } 

    function CheckPageBreak($h)
    { 
        // Si la hauteur h provoque un d�bordement, saut de page manuel
        if ($this->GetY() + $h > $this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    } 

    function NbLines($w, $txt)
    { 
        // Calcule le nombre de lignes qu'occupe un MultiCell de largeur w
        $cw = &$this->CurrentFont['cw'];
        if ($w == 0)
            $w = $this->w - $this->rMargin - $this->x;
        $wmax = ($w-2 * $this->cMargin) * 1000 / $this->FontSize;
        $s = str_replace("\r", '', $txt);
        $nb = strlen($s);
        if ($nb > 0 and $s[$nb-1] == "\n")
            $nb--;
        $sep = -1;
        $i = 0;
        $j = 0;
        $l = 0;
        $nl = 1;
        while ($i < $nb) {
            $c = $s[$i];
            if ($c == "\n") {
                $i++;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
                continue;
            } 
            if ($c == ' ')
                $sep = $i;
            //$l += $cw[$c];
	    $l += $cw[ord($c)]; 
            if ($l > $wmax) {
                if ($sep == -1) {
                    if ($i == $j)
                        $i++;
                } else
                    $i = $sep + 1;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
            } else
                $i++;
        } 
        return $nl;
    }
	
	 
    // //////////////////////////////////
    // import d'image en memoire
    // //////////////////////////////////
    // (c) Xavier Nicolay
    // V1.0 : 2004-01-17
    // CONSTRUCTOR
    function MEM_IMAGE($orientation = 'P', $unit = 'mm', $format = 'A4')
    {
        $this->FPDF($orientation, $unit, $format); 
        // Register var stream protocol (requires PHP>=4.3.2)
        if (function_exists('stream_wrapper_register'))
            stream_wrapper_register('var', 'VariableStream');
    } 
    // PRIVATE FUNCTIONS
    function _readstr($var, &$pos, $n)
    { 
        // Read some bytes from string
        $string = substr($var, $pos, $n);
        $pos += $n;
        return $string;
    } 

    function _readstr_int($var, &$pos)
    { 
        // Read a 4-byte integer from string
        $i = ord($this->_readstr($var, $pos, 1)) << 24;
        $i += ord($this->_readstr($var, $pos, 1)) << 16;
        $i += ord($this->_readstr($var, $pos, 1)) << 8;
        $i += ord($this->_readstr($var, $pos, 1));
        return $i;
    } 

    function _parsemempng($var)
    {
        $pos = 0; 
        // Check signature
        $sig = $this->_readstr($var, $pos, 8);
        if ($sig != chr(137) . 'PNG' . chr(13) . chr(10) . chr(26) . chr(10))
            $this->Error('Not a PNG image'); 
        // Read header chunk
        $this->_readstr($var, $pos, 4);
        $ihdr = $this->_readstr($var, $pos, 4);
        if ($ihdr != 'IHDR')
            $this->Error('Incorrect PNG Image');
        $w = $this->_readstr_int($var, $pos);
        $h = $this->_readstr_int($var, $pos);
        $bpc = ord($this->_readstr($var, $pos, 1));
        if ($bpc > 8)
            $this->Error('16-bit depth not supported: ' . $file);
        $ct = ord($this->_readstr($var, $pos, 1));
        if ($ct == 0)
            $colspace = 'DeviceGray';
        elseif ($ct == 2)
            $colspace = 'DeviceRGB';
        elseif ($ct == 3)
            $colspace = 'Indexed';
        else
            $this->Error('Alpha channel not supported: ' . $file);
        if (ord($this->_readstr($var, $pos, 1)) != 0)
            $this->Error('Unknown compression method: ' . $file);
        if (ord($this->_readstr($var, $pos, 1)) != 0)
            $this->Error('Unknown filter method: ' . $file);
        if (ord($this->_readstr($var, $pos, 1)) != 0)
            $this->Error('Interlacing not supported: ' . $file);
        $this->_readstr($var, $pos, 4);
        $parms = '/DecodeParms <</Predictor 15 /Colors ' . ($ct == 2 ? 3 : 1) . ' /BitsPerComponent ' . $bpc . ' /Columns ' . $w . '>>'; 
        // Scan chunks looking for palette, transparency and image data
        $pal = '';
        $trns = '';
        $data = '';
        do {
            $n = $this->_readstr_int($var, $pos);
            $type = $this->_readstr($var, $pos, 4);
            if ($type == 'PLTE') {
                // Read palette
                $pal = $this->_readstr($var, $pos, $n);
                $this->_readstr($var, $pos, 4);
            } elseif ($type == 'tRNS') {
                // Read transparency info
                $t = $this->_readstr($var, $pos, $n);
                if ($ct == 0)
                    $trns = array(ord(substr($t, 1, 1)));
                elseif ($ct == 2)
                    $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1)));
                else {
                    $pos = strpos($t, chr(0));
                    if (is_int($pos))
                        $trns = array($pos);
                } 
                $this->_readstr($var, $pos, 4);
            } elseif ($type == 'IDAT') {
                // Read image data block
                $data .= $this->_readstr($var, $pos, $n);
                $this->_readstr($var, $pos, 4);
            } elseif ($type == 'IEND')
                break;
            else
                $this->_readstr($var, $pos, $n + 4);
        } while ($n);
        if ($colspace == 'Indexed' and empty($pal))
            $this->Error('Missing palette in ' . $file);
        return array('w' => $w,
            'h' => $h,
            'cs' => $colspace,
            'bpc' => $bpc,
            'f' => 'FlateDecode',
            'parms' => $parms,
            'pal' => $pal,
            'trns' => $trns,
            'data' => $data);
    } 

    /**
    */
    /* PUBLIC FUNCTIONS */
    /**
    */
    function MemImage($data, $x, $y, $w = 0, $h = 0, $link = '')
    { 
        // Put the PNG image stored in $data
        $id = md5($data);
        if (!isset($this->images[$id])) {
            $info = $this->_parsemempng($data);
            $info['i'] = count($this->images) + 1;
            $this->images[$id] = $info;
        } else
            $info = $this->images[$id]; 
        // Automatic width and height calculation if needed
        if ($w == 0 and $h == 0) {
            // Put image at 72 dpi
            $w = $info['w'] / $this->k;
            $h = $info['h'] / $this->k;
        } 
        if ($w == 0)
            $w = $h * $info['w'] / $info['h'];
        if ($h == 0)
            $h = $w * $info['h'] / $info['w'];
            
        $this->_out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q', $w * $this->k, $h * $this->k, $x * $this->k, ($this->h - ($y + $h)) * $this->k, $info['i']));
        if ($link)
            $this->Link($x, $y, $w, $h, $link);
    } 

} 

?>