<?php
/* Copyright (C) 2014 Ethic-Web <c.sahuc@ethicweb.com>
*/

/**
 *	\file       htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
 *	\ingroup    societe
 *	\brief      File of class to build ODT documents for third parties
 */

require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';


/**
 *	Class to build documents using ODF templates generator
 */
 
  function text_decode($text){
		return html_entity_decode($text, ENT_QUOTES, 'UTF-8');
	}
	

	
function strcoupe($str,$pos){
	if ( strlen($str)>$pos)
	{
		$str=substr($str,0,$pos);
		$pos=strrpos($str," ");
		$str=substr($str,0,$pos);
	
		return $str;
	}
	else return $str;
}
class doc_generic_courrier_odt
{
	var $emetteur;	// Objet societe qui emet

	var $phpmin = array(5,2,0);	// Minimum version of PHP required by module
	var $version = 'dolibarr';


	/**
	 *	Constructor
	 *
	 *  @param		DoliDB		$db      Database handler
	 */
	function __construct($db)
	{
		global $conf,$langs,$mysoc;

		$langs->load("odfRelance@relanceTiers");

		$this->db = $db;
		$this->name = "ODT/ODS templates";
		$this->description = $langs->trans("DocumentModelOdt");
		$this->scandir = 'FACTURE_ADDON_PDF_ODT_PATH';	// Name of constant that is used to save list of directories to scan

		// Dimension page pour format A4
		$this->type = 'odt';
		$this->page_largeur = 0;
		$this->page_hauteur = 0;
		$this->format = array($this->page_largeur,$this->page_hauteur);
		$this->marge_gauche=0;
		$this->marge_droite=0;
		$this->marge_haute=0;
		$this->marge_basse=0;

		$this->option_logo = 1;                    // Affiche logo
		$this->option_tva = 0;                     // Gere option tva FACTURE_TVAOPTION
		$this->option_modereg = 0;                 // Affiche mode reglement
		$this->option_condreg = 0;                 // Affiche conditions reglement
		$this->option_codeproduitservice = 0;      // Affiche code produit-service
		$this->option_multilang = 1;               // Dispo en plusieurs langues
		$this->option_escompte = 0;                // Affiche si il y a eu escompte
		$this->option_credit_note = 0;             // Support credit notes
		$this->option_freetext = 1;				   // Support add of a personalised text
		$this->option_draft_watermark = 0;		   // Support add of a watermark on drafts

		// Recupere emetteur
		$this->emetteur=$mysoc;
		if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // Par defaut, si n'etait pas defini
	}


	/**
	 * Define array with couple substitution key => substitution value
	 *
	 * @param   Object			$object             Main object to use as data source
	 * @param   Translate		$outputlangs        Lang object to use for output
	 * @return	array								Array of substitution
	 */
	function get_formated_object($object,$outputlangs)
	{
		global $conf,$db;
		$resarray=array(
		'tiers_civilite'=> $object->civility_id,
		'tiers_nom' => $object->nom,
		'tiers_prenom' => $object->prenom,
		'tiers_adr' => $object->address,
		'tiers_cp' => $object->zip,
		'tiers_ville' => $object->town,
		'adr' => $conf->global->ADRESSE_RELANCE_COURRIER,
		'date' => date('d/m/Y'),
		'texte' => 'Bonjour',
		'line_replace' => 'line_'.$object->id,
		'objet' => 'ERREUR'
		);
		
		
		
		
		
		$sql='SELECT  contact_relance,relance_lvl FROM llx_societe WHERE rowid='.$object->id;
		$resql=$db->query($sql);
		if ($resql)
		{
			$row = $db->fetch_row($resql);
			
			
			// INFORMATION CONTACT
			$contact = $row[0];
			
			if($contact)
			{
				$sql_contact='SELECT civilite,lastname,firstname,address,zip,town FROM llx_socpeople WHERE rowid='.$contact;
				$rescont=$db->query($sql_contact);
				if($rescont)
				{
					$rowcont=$db->fetch_row($rescont);
					
					if($rowcont[0]!=''&&$rowcont[0]!=null)$resarray['tiers_civilite']=$rowcont[0];
					if($rowcont[1]!=''&&$rowcont[1]!=null)$resarray['tiers_nom']=$rowcont[1];
					if($rowcont[2]!=''&&$rowcont[2]!=null)$resarray['tiers_prenom']=$rowcont[2];
					if($rowcont[3]!=''&&$rowcont[3]!=null)$resarray['tiers_adr']=$rowcont[3];
					if($rowcont[4]!=''&&$rowcont[4]!=null)$resarray['tiers_cp']=$rowcont[4];
					if($rowcont[5]!=''&&$rowcont[5]!=null)$resarray['tiers_ville']=$rowcont[5];
					
					
				}
			}
			
			//NIVEAU RELANCE
			$sql="SELECT nom,
					SUM(amount) as som,
					relance_lvl,
					relance_total,
					date_relance,
					max(if(paye=0,DATEDIFF(CURDATE(),date),0)) as retard,
					max(dateprel) as lastprel,
					sum(if(fac=1 and paye=0,1,0)) as nb_non_paye,
					socid,
							contact_relance,
							email,
							SUM(-1*amount) as somdue
					FROM(
						SELECT 
							pf.amount,
							f.paye,
							0 as fac,
							f.date_lim_reglement as date, 
							p.datep as dateprel, 
							s.rowid as socid,
							s.nom as nom,
							s.date_relance,
							s.relance_lvl,
									s.email,
							s.contact_relance,
							s.relance_total,
							pf.rowid
								FROM `llx_societe` s 
								inner join llx_facture f on f.fk_soc=s.rowid 
								inner join llx_paiement_facture pf on  pf.fk_facture=f.rowid 
								inner join llx_paiement p on pf.fk_paiement=p.rowid 
								WHERE s.rowid=".$object->id."
								AND f.fk_statut =1
								AND f.paye=0
								AND f.date_lim_reglement < CURDATE()
						UNION ALL 
						SELECT 
							f.total_ttc*(-1) as amount,
							f.paye,
							1 as fac,
							f.date_lim_reglement as date,
							\"0000-00-00\" as dateprel,
							s.rowid as socid,
							s.nom as nom,
							s.date_relance,
							s.relance_lvl,
									s.email,
							s.contact_relance,
							s.relance_total,
							f.rowid
								FROM `llx_societe` s 
								inner join llx_facture f on f.fk_soc=s.rowid 
								WHERE s.rowid=".$object->id."
								AND f.fk_statut =1
								AND f.paye=0
								AND f.total_ttc>0
								AND f.date_lim_reglement < CURDATE()
		UNION ALL 
		SELECT 
			f.total_ttc*(-1) as amount,
			1 AS paye,
			3 as fac,
			f.datef as date,
			\"0000-00-00\" as dateprel,
			s.rowid as socid,
			s.nom as nom,
			s.date_relance,
			s.relance_lvl,
					s.email,
			s.contact_relance,
			s.relance_total,
			f.rowid
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
								AND f.paye =0
					AND f.fk_statut =1
			AND f.total_ttc < 0 
		UNION ALL 
		SELECT 
			r.amount_ttc as amount,
			1 as paye,
			3 as fac,
			r.datec as date,
			\"0000-00-00\" as dateprel,
			s.rowid as socid,
			s.nom as nom,
			s.date_relance,
			s.relance_lvl,
					s.email,
			s.contact_relance,
			s.relance_total,
			r.rowid
				FROM `llx_societe` s 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				WHERE s.rowid=".$object->id."
								AND r.fk_facture IS NULL
				AND r.fk_facture_line IS NULL
				AND r.fk_facture_source IS NULL
		UNION ALL 
		SELECT 
			r.amount_ttc as amount,
			1 as paye,
			3 as fac,
			r.datec as date,
			\"0000-00-00\" as dateprel,
			s.rowid as socid,
			s.nom as nom,
			s.date_relance,
			s.relance_lvl,
					s.email,
			s.contact_relance,
			s.relance_total,
			r.rowid
				FROM `llx_societe` s 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				inner join llx_facture f on f.rowid=r.fk_facture_source
				WHERE s.rowid=".$object->id."
								AND r.fk_facture IS NULL
				AND r.fk_facture_line IS NULL
		UNION ALL 
		SELECT 
			r.amount_ttc as amount,
			1 as paye,
			3 as fac,
			r.datec as date,
			\"0000-00-00\" as dateprel,
			s.rowid as socid,
			s.nom as nom,
			s.date_relance,
			s.relance_lvl,
					s.email,
			s.contact_relance,
			s.relance_total,
			r.rowid
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				inner join llx_facture f2 on f2.rowid=r.fk_facture_source
				WHERE s.rowid=".$object->id."
								AND f.paye =0
					AND f.fk_statut =1
					AND f.total_ttc>0
				AND f.date_lim_reglement < CURDATE()
					AND r.fk_facture = f.rowid
					AND r.fk_facture_line IS NULL
						) as a
						JOIN (SELECT @csum := 0) b
					GROUP BY socid
					HAVING nb_non_paye>0
					AND retard >0";
			$resql=$db->query($sql);
			if ($resql)
			{
				$row = $db->fetch_row($resql);
				if($row)
				{
					$error=0;
					$lvl=$row[2];
					switch($lvl){
						case 1:
							$text=$conf->global->RELANCE_TEXT_COURRIER_1;
							$title=$conf->global->RELANCE_TITLE_COURRIER_1;
						break;
						
						case 2:
							$text=$conf->global->RELANCE_TEXT_COURRIER_2;
							$title=$conf->global->RELANCE_TITLE_COURRIER_2;
						break;
						
						case 3:
							$text=$conf->global->RELANCE_TEXT_COURRIER_3;
							$title=$conf->global->RELANCE_TITLE_COURRIER_3;
						break;
						
						default:
						$error=1;
						break;
					}
					if(!$error)
					{
						$resarray['texte']=str_replace(array("[name]","[balance]","[nb_invoice_unpaid]","[late]","[somme_due]"),array($row[0],converToDoppleDecimal($row[1]).' '.$conf->currency.'',$row[7],$row[5]." ".$outputlangs->trans("jour")."(s)",converToDoppleDecimal($row[11]).' '.$conf->currency.''),$text);
						$resarray['objet']=str_replace(array("[name]","[balance]","[nb_invoice_unpaid]","[late]","[somme_due]"),array($row[0],converToDoppleDecimal($row[1]).' '.$conf->currency.'',$row[7],$row[5]." ".$outputlangs->trans("jour")."(s)",converToDoppleDecimal($row[11]).' '.$conf->currency.''),$title);
						
					}
				}
			}
			
		}
		
		return $resarray;
	}

	/**
	 * Define array with couple substitution key => substitution value
	 *
	 * @param   array		$line			Array of lines
	 * @param   Translate	$outputlangs    Lang object to use for output
	 * @return	array						Return substitution array
	 */
	function get_and_format_lines($object,$outputlangs)
	{
		global $conf;

		$resarray=array();
		$sql= "SELECT title, date, debit, credit, (@csum := @csum + amount)as solde,fac,label FROM(
    SELECT CONCAT(\"->".text_decode($outputlangs->trans("PaiementRel"))." (\",ty.code,\") : \",p.num_paiement,\"-\") as title,
	p.datec as date,
	IF(pf.amount<0,round(pf.amount*(-1),2),'' )as debit,
	IF(pf.amount>0,round(pf.amount,2),'') as credit,round(pf.amount,2) as amount,
	f.rowid,
	0 as fac,
	b.label,
p.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				inner join llx_paiement_facture pf on  pf.fk_facture=f.rowid 
				inner join llx_paiement p on pf.fk_paiement=p.rowid 
				inner join llx_c_paiement ty on ty.id=p.fk_paiement 
				inner join llx_bank b on b.rowid=p.fk_bank 
				WHERE s.rowid=".$object->id." 
				AND f.paye =0
				AND f.fk_statut =1
			AND f.date_lim_reglement < CURDATE()
UNION ALL  SELECT 
CONCAT(\"".text_decode($outputlangs->trans("FactureRel"))." : \",f.facnumber) as title,
f.datef as date,
IF(f.total_ttc>0,round(f.total_ttc,2),'' )as debit,
IF(f.total_ttc<0,round(f.total_ttc*(-1),2),'') as credit,round(f.total_ttc*(-1),2) as amount,
f.rowid, 
1 as fac,
\"\" as label,
f.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
				AND f.paye =0
				AND f.total_ttc>0
				AND f.fk_statut =1
			AND f.date_lim_reglement < CURDATE()
UNION ALL  SELECT 
CONCAT(\"".text_decode($outputlangs->trans("Avoir"))." : \",f.facnumber) as title,
f.datef as date,
IF(f.total_ttc>0,round(f.total_ttc,2),'' )as debit,
IF(f.total_ttc<0,round(f.total_ttc*(-1),2),'') as credit,round(f.total_ttc*(-1),2) as amount,
f.rowid, 
1 as fac,
\"\" as label,
f.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
					AND f.paye =0
					AND f.fk_statut =1
			AND f.total_ttc < 0 
UNION ALL  SELECT 
CONCAT(\"".text_decode($outputlangs->trans("Remise"))." : \",r.description) as title,
r.datec as date,
IF(r.amount_ttc<0,round(r.amount_ttc*(-1),2),'' )as debit,
IF(r.amount_ttc>0,round(r.amount_ttc,2),'') as credit,
round(r.amount_ttc,2) as amount,
999999 as rowid, 
3 as fac,
\"\" as label,
r.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				WHERE s.rowid=".$object->id."
				AND r.fk_facture IS NULL
				AND r.fk_facture_line IS NULL
				AND r.fk_facture_source IS NULL
   
UNION ALL  SELECT 
CONCAT(\"".text_decode($outputlangs->trans("RemiseAvoir"))." : \",f2.facnumber) as title,
r.datec as date,
IF(r.amount_ttc<0,round(r.amount_ttc*(-1),2),'' )as debit,
IF(r.amount_ttc>0,round(r.amount_ttc,2),'') as credit,
round(r.amount_ttc,2) as amount,
999998 as rowid, 
3 as fac,
\"\" as label,
r.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				inner join llx_facture f2 on f2.rowid=r.fk_facture_source
				WHERE s.rowid=".$object->id."
				AND r.fk_facture IS NULL
				AND r.fk_facture_line IS NULL
   
UNION ALL  SELECT 
CONCAT(\"->".text_decode($outputlangs->trans("UtilisationAvoir"))." : \",f2.facnumber) as title,
f.datef as date,
IF(r.amount_ttc<0,round(r.amount_ttc*(-1),2),'' )as debit,
IF(r.amount_ttc>0,round(r.amount_ttc,2),'') as credit,
round(r.amount_ttc,2) as amount,
f.rowid as rowid, 
3 as fac,
\"\" as label,
r.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				inner join llx_facture f2 on f2.rowid=r.fk_facture_source
				WHERE s.rowid=".$object->id."
					AND f.paye =0
					AND f.fk_statut =1
					AND f.total_ttc>0
				AND f.date_lim_reglement < CURDATE()
					AND r.fk_facture = f.rowid
					AND r.fk_facture_line IS NULL
) as a 
JOIN (SELECT @csum := 0) b
				
order by rowid,date,amount;";
				$resql=$this->db->query($sql);
				if ($resql)
				{
					$num = $this->db->num_rows($resql);
					if ($num)
					{
						$i = 0;
						while ($i < $num)
						{
							$row = $this->db->fetch_row($resql);
							
							$date=new DateTime($row[1]);
							$type=$row[6];
								$type=str_replace(array("(",")"),array("",""),$type);
								$type=text_decode($outputlangs->trans($type));
								$descr=strcoupe($row[0].$type,50);	
							
							$ligne=array(
							'line_fulldesc' => $descr,
							'line_date' => $date->format('d/m/Y'),
							'line_debit' => ($row[2]!=''?converToDoppleDecimal($row[2]).' '.$conf->currency.'':''),
							'line_credit' => ($row[3]!=''?converToDoppleDecimal($row[3]).' '.$conf->currency.'':''),
							'line_solde_accu' => converToDoppleDecimal($row[4]).' '.$conf->currency.''
							);
							$resarray=array_merge($resarray,array($ligne));
							$i++;
						}
					}
				}
		return $resarray;
	}
	

	/**
	 *	Function to build a document on disk using the generic odt module.
	 *
	 *	@param		Facture		$object				Object source to build document
	 *	@param		Translate	$outputlangs		Lang output object
	 * 	@param		string		$srctemplatepath	Full path of source filename for generator using a template file
	 *  @param		int			$hidedetails		Do not show line details
	 *  @param		int			$hidedesc			Do not show desc
	 *  @param		int			$hideref			Do not show ref
	 *	@return		int         					1 if OK, <=0 if KO
	 */
	function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
	{
		global $user,$langs,$conf,$mysoc,$hookmanager;

		if (empty($srctemplatepath))
		{
			dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
			return -1;
		}

		// Add odtgeneration hook
		if (! is_object($hookmanager))
		{
			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
			$hookmanager=new HookManager($this->db);
		}
		$hookmanager->initHooks(array('odtgeneration'));
		global $action;

		if (! is_object($outputlangs)) $outputlangs=$langs;
		$sav_charset_output=$outputlangs->charset_output;
		$outputlangs->charset_output='UTF-8';

		$outputlangs->load("odtRelance@relanceTiers");
		$outputlangs->load("payment");
		$outputlangs->load("bank");
		$outputlangs->load("invoice");
		$outputlangs->load("withdrawals");


			$dir = DOL_DATA_ROOT.'/relanceTiers/receipts/odt';
			$objectref = "relance_".date('Y_m_d');
			$file = $dir . "/" . $objectref . ".odt";

			if (! file_exists($dir))
			{
				if (dol_mkdir($dir) < 0)
				{
					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
					return -1;
				}
			}
			if (file_exists($dir))
			{
				$newfile=basename($srctemplatepath);
				$newfiletmp=preg_replace('/\.od(t|s)/i','',$newfile);
				$newfiletmp=preg_replace('/template_/i','',$newfiletmp);
				$newfiletmp=preg_replace('/modele_/i','',$newfiletmp);

				$newfiletmp=$objectref.'_'.$newfiletmp;

				$newfileformat=substr($newfile, strrpos($newfile, '.')+1);
				if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
				{
					$filename=$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.'.$newfileformat;
				}
				else
				{
					$filename=$newfiletmp.'.'.$newfileformat;
				}
				$file=$dir.'/'.$filename;

				dol_mkdir(DOL_DATA_ROOT.'/relanceTiers/temp/odt');


				
				

				// Open and load template
				require_once ODTPHP_PATH.'odf.php';
				try {
					$odfHandler = new odf(
						$srctemplatepath,
						array(
						'PATH_TO_TMP'	  => DOL_DATA_ROOT.'/relanceTiers/temp/odt',
						'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
						'DELIMITER_LEFT'  => '{',
						'DELIMITER_RIGHT' => '}'
						)
					);
				}
				catch(Exception $e)
				{
					$this->error=$e->getMessage();
					return 1;
				}
				
				
				$listTiers = $odfHandler->setSegment('tiers');
				
				//pour le saut de ligne a enlever sur la dernière page
				$count=count($object);
				$i=0;
				//////////
				
				foreach($object as $tiers)
				{
					$i++;
					$array_objet=is_object($tiers)?$this->get_formated_object($tiers,$outputlangs):array();
					
					complete_substitutions_array($array_objet, $outputlangs, $tiers);
					
					// Call the ODTSubstitution hook
					$parameters=array('file'=>$file,'object'=>$tiers,'outputlangs'=>$outputlangs,'substitutionarray'=>&$array_objet);					
					$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $tiers may have been modified by some hooks
					
				//pour le saut de ligne a enlever sur la dernière page
					//if($i==$count)
						//$listTiers->setVars('saut', false, true, 'UTF-8');
						////////
						
					foreach($array_objet as $key=>$value)
					{
					
						try {
								$listTiers->setVars($key, $value, true, 'UTF-8');
							
						}
						catch(OdfException $e)
						{
						}
						catch(SegmentException $e)
						{
						}
					}
					// Replace tags of lines
					
					
					complete_substitutions_array($array_line, $outputlangs, $tiers);
					// Call the ODTSubstitution hook
					$parameters=array('file'=>$file,'object'=>$tiers,'outputlangs'=>$outputlangs,'substitutionarray'=>&$array_line);					
					$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $tiers may have been modified by some hooks
					
					$listTiers->merge();
				}
				$odfHandler->mergeSegment($listTiers);
				
				
				foreach($object as $tiers)
				{
					$array_line=is_object($tiers)?$this->get_and_format_lines($tiers,$outputlangs):array();
					
					complete_substitutions_array($array_line, $outputlangs, $tiers);
					
					
					try
					{
						$listlines = $odfHandler->setSegment('line_'.$tiers->id);
						foreach ($array_line as $line)
						{
							$o=0;
							foreach($line as $key => $val)
							{
							
								try
								{
									$listlines->setVars($key, $val, true, 'UTF-8');
								}
								catch(OdfException $e)
								{
								}
								catch(SegmentException $e)
								{
								}
								$o++;
							}
							if($o>0)$listlines->merge();
						}
						$odfHandler->mergeSegment($listlines);
					}
					catch(OdfException $e)
					{
						$this->error=$e->getMessage();
						dol_syslog($this->error, LOG_WARNING);
						return -1;
					}
				}
				
				
				//pour le saut de ligne 
				//if($count>1)$odfHandler->setVars('saut', true, true, 'UTF-8');
				//a enlever sur la dernière page
				//if($count>0)$odfHandler->setVars('saut', false, true, 'UTF-8');
				////////////
				
				
				
				// Replace labels translated
				//$tmparray=$outputlangs->get_translations_for_substitutions();
				foreach($outputlangs->tab_translate as $key=>$value)
				{
					try {
						$odfHandler->setVars('lang_'.$key, $value, true, 'UTF-8');
					}
					catch(OdfException $e)
					{
					}
					catch(SegmentException $e)
					{
					}
				}
				
				// Call the beforeODTSave hook
				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks

				// Write new file
				if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
					try {
						$odfHandler->exportAsAttachedPDF($file);
					}catch (Exception $e){
						$this->error=$e->getMessage();
						return -1;
					}
				}
				else {
					try {
					$odfHandler->saveToDisk($file);
					}catch (Exception $e){
						$this->error=$e->getMessage();
						return -1;
					}
				}

				if (! empty($conf->global->MAIN_UMASK))
					@chmod($file, octdec($conf->global->MAIN_UMASK));

				$odfHandler=null;	// Destroy object
				return 1;   // Success
			}
			else
			{
				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
				return -1;
			}

		return -1;
	}

}

?>
