<?php 

require_once('config/lang/eng.php');
require_once('tcpdf.php');


// Extend the TCPDF class to create custom Header and Footer
class TCPDFREP extends TCPDF {
	
		
		public $objmulticopy=array();
		
		public function startMultipleTransaction() {
			$objid = array_push($this->objmulticopy,$this->objclone($this));
			return $objid;
		}

		/**
		* Delete the copy of the current TCPDF object used for undo operation.
		* @access public
		* @since 4.5.029 (2009-03-19)
		*/
		public function commitMultipleTransaction() {
			$lastobj = array_pop($this->objmulticopy);
			$lastobj->_destroy(true, true);
			unset($lastobj);							
		}

		/**
		* This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
		* @return TCPDF object.
		* @access public
		* @since 4.5.029 (2009-03-19)
		*/
		public function rollbackMultipleTransaction() {			
			if (isset($this->objmulticopy) and count($this->objmulticopy)>0) {	
			    $lastobj = array_pop($this->objmulticopy);
				if (isset($lastobj->diskcache) and $lastobj->diskcache) {
					// truncate files to previous values
					foreach ($lastobj->cache_file_lenght as $file => $lenght) {
						$file = substr($file, 1);
						$handle = fopen($file, 'r+');
						ftruncate($handle, $lenght);
					}
				}
				$this->_destroy(true, true, true);								
				return $lastobj;
			}
			return $this;
		}
		
		
		
		public function _destroy($destroyall=false, $preserve_objcopy=false, $preserve_objmulticopy=false) {
			if ($destroyall and isset($this->diskcache) and $this->diskcache and (!$preserve_objcopy) and (!$this->empty_string($this->buffer))) {
				// remove buffer file from cache
				unlink($this->buffer);
			}
			foreach (array_keys(get_object_vars($this)) as $val) {
				if ($destroyall or (
					($val != 'internal_encoding') 
					and ($val != 'state') 
					and ($val != 'bufferlen') 
					and ($val != 'buffer') 
					and ($val != 'diskcache')
					and ($val != 'sign')
					and ($val != 'signature_data')
					and ($val != 'signature_max_lenght')
					and ($val != 'byterange_string')
					)) {
					if ((!$preserve_objcopy or ($val != 'objcopy')) and (($val != 'objmulticopy') or !$preserve_objmulticopy)) {
						unset($this->$val);
					}
				}
			}
		}
		
		function parametros_por_defecto($defaults,$opciones){
			
				if (!is_array($opciones)){
					$opciones=array();
				  }
				
				if (!is_array($defaults)){
					$defaults=array();
				  }
				
				
				  foreach($defaults as $key=>$value){
					if (is_array($value)){
						foreach($value as $key2=>$value2){
							if (!isset($opciones[$key][$key2])){								
								$opciones[$key][$key2]=$value2;
							}	
						}													 
					} else {
					  if (!isset($opciones[$key])){
						$opciones[$key]=$value;
					  }
					}
				  }
		
				return $opciones;
		
		}
		
		public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false,$prop=array()) {
			
			// *************** FLAG DE SALTO DE PÁGINA ********************************
			$this->saltopag = 0;
			// ************************************************************************
			
			// **************** EVITA EL CHECKEO DE SALTO NORMAL **********************
			$defaults = array('check_pagebreak'=>1);
			// ************************************************************************	
										
			$prop = $this->parametros_por_defecto($defaults,$prop);
			//echo $prop['check_pagebreak'].' - ********* '.$txt.'<br>';			
			if ($this->empty_string($this->lasth) or $reseth) {
				//set row height
				$this->lasth = $this->FontSize * $this->cell_height_ratio;
			}
			if (!$this->empty_string($y)) {
				$this->SetY($y);
			} else {
				$y = $this->GetY();
			}
			
			$resth = 0;
			if ((!$this->InFooter) and (($y + $h) > $this->PageBreakTrigger) and $prop['check_pagebreak']) {
				// spit cell in two pages
				$newh = $this->PageBreakTrigger - $y;
				$resth = $h - $newh; // cell to be printed on the next page
				$h = $newh;
			}
			// get current page number
			$startpage = $this->page;
			if (!$this->empty_string($x)) {
				$this->SetX($x);
			} else {
				$x = $this->GetX();
			}
			if ($this->empty_string($w) OR ($w <= 0)) {
				if ($this->rtl) {
					$w = $this->x - $this->lMargin;
				} else {
					$w = $this->w - $this->rMargin - $this->x;
				}
			}
			// store original margin values
			$lMargin = $this->lMargin;
			$rMargin = $this->rMargin;
			if ($this->rtl) {
				$this->SetRightMargin($this->w - $this->x);
				$this->SetLeftMargin($this->x - $w);
			} else {
				$this->SetLeftMargin($this->x);
				$this->SetRightMargin($this->w - $this->x - $w);
			}
			$starty = $this->y;
			if ($autopadding) {
				// Adjust internal padding
				if ($this->cMargin < ($this->LineWidth / 2)) {
					$this->cMargin = ($this->LineWidth / 2);
				}
				// Add top space if needed
				if (($this->lasth - $this->FontSize) < $this->LineWidth) {
					$this->y += $this->LineWidth / 2;
				}
				// add top padding
				$this->y += $this->cMargin;
			}
			if ($ishtml) { // ******* Write HTML text
			   
				//**************************** Detecta el salto de página durante el proceso de escritura  HTML ***********************				
			    $this->saltopag = 0;
				$pagina = $this->getPage();
				$this->writeHTML($txt, true, 0, $reseth, true, $align);
				$pagina2 = $this->getPage();				
				if($pagina!=$pagina2){$this->saltopag = 1;}
				//*********************************************************************************************************************
				
				$nl = 1;
			} else { // ******* Write simple text
				// vertical alignment
				if ($maxh > 0) {
					// get text height
					$text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, '', '');
					if ($fitcell) {
						$prev_FontSizePt = $this->FontSizePt;
						// try to reduce font size to fit text on cell (use a quick search algorithm)
						$fmin = 1;
						$fmax = $this->FontSizePt;
						$prev_text_height = $text_height;
						$maxit = 100; // max number of iterations
						while ($maxit > 0) {
							$fmid = (($fmax + $fmin) / 2);
							$this->SetFontSize($fmid, false);
							$text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, '', '');
							if (($text_height == $maxh) OR (($text_height < $maxh) AND ($fmin >= ($fmax - 0.01)))) {
								break;
							} elseif ($text_height < $maxh) {
								$fmin = $fmid;
							} else {
								$fmax = $fmid;
							}
							--$maxit;
						}
						$this->SetFontSize($this->FontSizePt);
					}
					if ($text_height < $maxh) {
						if ($valign == 'M') {
							// text vertically aligned on middle
							$this->y += (($maxh - $text_height) / 2);
						} elseif ($valign == 'B') {
							// text vertically aligned on bottom
							$this->y += ($maxh - $text_height);
						}
					}
				}
								
				//**************************** Detecta el salto de página durante el proceso de escritura  ****************************				
				$pagina = $this->getPage();
				$nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh);	
				$pagina2 = $this->getPage();				
				if($pagina!=$pagina2){$this->saltopag = 1;}
				//*********************************************************************************************************************
							
				if ($fitcell) {
					// restore font size
					$this->SetFontSize($prev_FontSizePt);
				}
			}
			if ($autopadding) {
				// add bottom padding
				$this->y += $this->cMargin;
				// Add bottom space if needed
				if (($this->lasth - $this->FontSize) < $this->LineWidth) {
					$this->y += $this->LineWidth / 2;
				}
			}
			// Get end-of-text Y position
			$currentY = $this->y;
			// get latest page number
			$endpage = $this->page;
			
			if ($resth > 0 and $prop['check_pagebreak']) {
			    //echo $prop['check_pagebreak'].' - ok ';
				$skip = ($endpage - $startpage);
				$tmpresth = $resth;
				while ($tmpresth > 0) {
					if ($skip <= 0) {
						// add a page (or trig AcceptPageBreak() for multicolumn mode)
						$this->checkPageBreak($this->PageBreakTrigger + 1);
					}
					$tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
					--$skip;
				}
				$currentY = $this->y;
				$endpage = $this->page;
			}
			// check if a new page has been created
			if ($endpage > $startpage) {
				// design borders around HTML cells.
				for ($page=$startpage; $page <= $endpage; ++$page) {
					$this->setPage($page);
					if ($page == $startpage) {
						// first page
						$this->y = $starty; // put cursor at the beginning of cell on the first page
						$h = $this->h - $starty - $this->bMargin;
						$cborder = $this->getBorderMode($border, $position='start');
					} elseif ($page == $endpage) {
						// last page
						$this->y = $this->tMargin; // put cursor at the beginning of last page
						$h = $currentY - $this->tMargin;
						if ($resth > $h) {
							$h = $resth;
						}
						$cborder = $this->getBorderMode($border, $position='end');
					} else {
						$this->y = $this->tMargin; // put cursor at the beginning of the current page
						$h = $this->h - $this->tMargin - $this->bMargin;
						$resth -= $h;
						$cborder = $this->getBorderMode($border, $position='middle');
					}
					$nx = $x;
					// account for margin changes
					if ($page > $startpage) {
						if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
							$nx = $x + ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
						} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
							$nx = $x + ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
						}
					}
					$this->SetX($nx);
					$ccode = $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, false);
					if ($cborder OR $fill) {
						$pagebuff = $this->getPageBuffer($this->page);
						$pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
						$pend = substr($pagebuff, $this->intmrk[$this->page]);
						$this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
						$this->intmrk[$this->page] += strlen($ccode."\n");
					}
				}
			} else {
				
				$h = max($h, ($currentY - $y));
				
				//echo $this->page.'  Current: '.$currentY.' ****** PageBreakTrigger: '.$this->PageBreakTrigger.' ****** getPageHeight: '.$this->getPageHeight().' *********** '.$txt.'<br>';
								
				
				//********************************************* Devuelve la altura de la celda ****************************************			
				$this->altura_celda = $h;
				//*********************************************************************************************************************
								
				// put cursor at the beginning of text
				$this->SetY($y);
				$this->SetX($x);
				// design a cell around the text
				$ccode = $this->getCellCode($w, $h, '', $border, 1, '', $fill, '', 0, true);
				if ($border OR $fill) {
					if (end($this->transfmrk[$this->page]) !== false) {
						$pagemarkkey = key($this->transfmrk[$this->page]);
						$pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
					} elseif ($this->InFooter) {
						$pagemark = &$this->footerpos[$this->page];
					} else {
						$pagemark = &$this->intmrk[$this->page];
					}
					$pagebuff = $this->getPageBuffer($this->page);
					$pstart = substr($pagebuff, 0, $pagemark);
					$pend = substr($pagebuff, $pagemark);
					$this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
					$pagemark += strlen($ccode."\n");
				}
			}
			// Get end-of-cell Y position
			$currentY = $this->GetY();
			// restore original margin values
			$this->SetLeftMargin($lMargin);
			$this->SetRightMargin($rMargin);
			if ($ln > 0) {
				//Go to the beginning of the next line
				$this->SetY($currentY);
				if ($ln == 2) {
					$this->SetX($x + $w);
				}
			} else {
				// go left or right by case
				$this->setPage($startpage);
				$this->y = $y;
				$this->SetX($x + $w);
			}
			$this->setContentMark();
			return $nl;
		}

		
		public function Header() {
			
			$ormargins = $this->getOriginalMargins();
			$headerfont = $this->getHeaderFont();
			$headerdata = $this->getHeaderData();
			
			$margenes = $this->getMargins();
		    //$pdf->Image('../../shared/imagebank/'.$_SESSION["ls_logo"],$margenes['left'],$margenes['top'], 15, 15);
			
			$this->writeHTML(utf8_encode($headerdata['string']), true, false, false, false, '');			
			if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
			    $ancho = ($this->ancho_logo)?$this->ancho_logo:$_SESSION["ls_width_format2"];
				$alto = ($this->alto_logo)?$this->alto_logo:$_SESSION["ls_height_format2"];
				$this->Image(K_PATH_IMAGES.$headerdata['logo'], $margenes['left'], $this->getHeaderMargin(),$ancho,$alto);
				$imgy = $this->getImageRBY();
			} else {
				$imgy = $this->GetY();
			}
			
			
			$this->SetLineStyle(array('width' => 0.85 / $this->getScaleFactor(), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
			$this->SetY((2.835 / $this->getScaleFactor()) + max($imgy, $this->GetY()));
			if ($this->getRTL()) {
				$this->SetX($ormargins['right']);
			} else {
				$this->SetX($ormargins['left']);
			}
			$this->Cell(0, 0, '', 'T', 0, 'C');
			$this->Ln();			
			if($this->EncabezadoPostLinea){$this->writeHTML(utf8_encode($this->EncabezadoPostLinea), true, false, false, false, '');}									
			$this->SetY($this->y);
			$this->tMargin = $this->y;	
					
			
		}
		
		protected function setHeader() {
			if ($this->print_header) {
				$this->setGraphicVars($this->default_graphic_vars);
				$temp_thead = $this->thead;
				$temp_theadMargins = $this->theadMargins;
				$lasth = $this->lasth;
				$this->_out('q');
				$this->rMargin = $this->original_rMargin;
				$this->lMargin = $this->original_lMargin;				
				$this->cMargin = 0;
				//set current position
				if ($this->rtl) {
					$this->SetXY($this->original_rMargin, $this->header_margin);
				} else {
					$this->SetXY($this->original_lMargin, $this->header_margin);
				}
				$this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
				$this->Header();						
				$this->_out('Q');			
				$this->lasth = $lasth;
				$this->thead = $temp_thead;
				$this->theadMargins = $temp_theadMargins;
				$this->newline = false;
			}
		}
		
		public function Footer() {
			$cur_y = $this->GetY();
			$ormargins = $this->getOriginalMargins();
			$this->SetTextColor(0, 0, 0);
			//set style for cell border
			$line_width = 0.85 / $this->getScaleFactor();
			$this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
			//print document barcode
			$barcode = $this->getBarcode();
			if (!empty($barcode)) {
				$this->Ln($line_width);
				$barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
				$this->write1DBarcode($barcode, 'C128B', $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
			}
			if (empty($this->pagegroups)) {
				$pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
			} else {
				$pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
			}
			$this->SetY($cur_y);
			//Print page number
			$textofooter = '';
			if($this->texto_footer){$textofooter = $this->texto_footer;}
			
			if ($this->getRTL()) {
				$this->SetX($ormargins['right']);
				$this->Cell(0, 0, $textofooter.'     '.$pagenumtxt, 'T', 0, 'L');
			} else {
				$this->SetX($ormargins['left']);
				if($this->texto_footer){	
				    if($this->texto_prefooter){$this->writeHTML(utf8_encode($this->texto_prefooter), true, false, false, false, '');}					
					$this->MultiCell(0, 5, $textofooter, 'T', 'C', 0, 1, '', '', true);					
					$this->MultiCell(0, 5,$pagenumtxt, 0, 'C', 0, 1, '', '', true);				
				}
				else{
					$this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');				
				}
								
								
			}
		}
		
		
		public function decodifica_color($color1) {
        
			$color1 = str_replace("#", '', $color1);
				   
			$valor = 255;
			$r = hexdec(substr($color1, 0, 2));
			$g = hexdec(substr($color1, 2, 2));
			$b = hexdec(substr($color1, 4, 2));
				
			$color = array();
			$color[0] = $r;
			$color[1] = $g;
			$color[2] = $b;
			
			return $color;
       
		}
				
		public function color_fondo($color1) {			
			$matriz = $this->decodifica_color($color1);
			$this->SetFillColor($matriz[0], $matriz[1], $matriz[2]);       
		}
		
		public function color_letra($color1) {			
			$matriz = $this->decodifica_color($color1);			
			$this->SetTextColor($matriz[0], $matriz[1], $matriz[2]);      
		}
		
		public function compat_tinyMCE($texto) {			
					
					$texto = str_replace("<!-- pagebreak -->",'<span style="page-break-before: always;"></span><font size="0.5"><br /></font>',$texto);
					$texto = stripslashes($texto);
					
					return $texto;
		}
	/*
    //Page header
    public function Header() {
        // Logo
		$margenes = $this->getMargins();
        $this->Image('../../shared/imagebank/'.$_SESSION["ls_logo"],$margenes['left'],$margenes['top'],$_SESSION["ls_width"], $_SESSION["ls_height"]);
        //$this->Image($image_file, 10, 10, 15, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
        // Set font
        //$this->SetFont('helvetica', 'B', 20);
        // Title
        //$this->Cell(0, 15, '<< TCPDF Example 003 >>', 0, false, 'C', 0, '', 0, false, 'M', 'M');
    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
	*/
	
}

?>