1<?php
2/* Copyright (C) 2009-2013 Laurent Destailleur  <eldy@users.sourceforge.net>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 * or see https://www.gnu.org/
17 */
18
19/**
20 *      \file       htdocs/core/lib/invoice2.lib.php
21 *      \ingroup    facture
22 *      \brief      Function to rebuild PDF and merge PDF files into one
23 */
24
25require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
27
28
29/**
30 * Function to build a compiled PDF
31 *
32 * @param	DoliDB		$db						Database handler
33 * @param	Translate	$langs					Object langs
34 * @param	Conf		$conf					Object conf
35 * @param	string		$diroutputpdf			Dir to output file
36 * @param	string		$newlangid				Lang id
37 * @param 	array		$filter					Array with filters
38 * @param 	integer		$dateafterdate			Invoice after date
39 * @param 	integer 	$datebeforedate			Invoice before date
40 * @param 	integer		$paymentdateafter		Payment after date (must includes hour)
41 * @param 	integer		$paymentdatebefore		Payment before date (must includes hour)
42 * @param	int			$usestdout				Add information onto standard output
43 * @param	int			$regenerate				''=Use existing PDF files, 'nameofpdf'=Regenerate all PDF files using the template
44 * @param	string		$filesuffix				Suffix to add into file name of generated PDF
45 * @param	string		$paymentbankid			Only if payment on this bank account id
46 * @param	array		$thirdpartiesid			List of thirdparties id when using filter excludethirdpartiesid	or onlythirdpartiesid
47 * @param	string		$fileprefix				Prefix to add into filename of generated PDF
48 * @return	int									Error code
49 */
50function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, $usestdout, $regenerate = 0, $filesuffix = '', $paymentbankid = '', $thirdpartiesid = '', $fileprefix = 'mergedpdf')
51{
52	$sql = "SELECT DISTINCT f.rowid, f.ref";
53	$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
54	$sqlwhere = '';
55	$sqlorder = '';
56	if (in_array('all', $filter))
57	{
58		$sqlorder = " ORDER BY f.ref ASC";
59	}
60	if (in_array('date', $filter))
61	{
62		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
63		else $sqlwhere .= " AND";
64		$sqlwhere .= " f.fk_statut > 0";
65		$sqlwhere .= " AND f.datef >= '".$db->idate($dateafterdate)."'";
66		$sqlwhere .= " AND f.datef <= '".$db->idate($datebeforedate)."'";
67		$sqlorder = " ORDER BY f.datef ASC";
68	}
69	if (in_array('nopayment', $filter))
70	{
71		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
72		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
73		else $sqlwhere .= " AND";
74		$sqlwhere .= " f.fk_statut > 0";
75		$sqlwhere .= " AND pf.fk_paiement IS NULL";
76	}
77	if (in_array('payments', $filter) || in_array('bank', $filter))
78	{
79		$sql .= ", ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."paiement as p";
80		if (in_array('bank', $filter)) $sql .= ", ".MAIN_DB_PREFIX."bank as b";
81		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
82		else $sqlwhere .= " AND";
83		$sqlwhere .= " f.fk_statut > 0";
84		$sqlwhere .= " AND f.rowid = pf.fk_facture";
85		$sqlwhere .= " AND pf.fk_paiement = p.rowid";
86		if (in_array('payments', $filter))
87		{
88			$sqlwhere .= " AND p.datep >= '".$db->idate($paymentdateafter)."'";
89			$sqlwhere .= " AND p.datep <= '".$db->idate($paymentdatebefore)."'";
90		}
91		if (in_array('bank', $filter))
92		{
93			$sqlwhere .= " AND p.fk_bank = b.rowid";
94			$sqlwhere .= " AND b.fk_account = ".$paymentbankid;
95		}
96		$sqlorder = " ORDER BY p.datep ASC";
97	}
98	if (in_array('nodeposit', $filter))
99	{
100		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
101		else $sqlwhere .= " AND";
102		$sqlwhere .= ' type <> 3';
103	}
104	if (in_array('noreplacement', $filter))
105	{
106		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
107		else $sqlwhere .= " AND";
108		$sqlwhere .= ' type <> 1';
109	}
110	if (in_array('nocreditnote', $filter))
111	{
112		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
113		else $sqlwhere .= " AND";
114		$sqlwhere .= ' type <> 2';
115	}
116	if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid))
117	{
118		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
119		else $sqlwhere .= " AND";
120		$sqlwhere .= ' f.fk_soc NOT IN ('.join(',', $thirdpartiesid).')';
121	}
122	if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid))
123	{
124		if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
125		else $sqlwhere .= " AND";
126		$sqlwhere .= ' f.fk_soc IN ('.join(',', $thirdpartiesid).')';
127	}
128	if ($sqlwhere) $sql .= $sqlwhere;
129	if ($sqlorder) $sql .= $sqlorder;
130
131	//print $sql; exit;
132	dol_syslog("scripts/invoices/rebuild_merge.php:", LOG_DEBUG);
133
134	if ($usestdout) print '--- start'."\n";
135
136	// Start of transaction
137	//$db->begin();
138
139	$error = 0;
140	$result = 0;
141	$files = array(); // liste les fichiers
142
143	dol_syslog("scripts/invoices/rebuild_merge.php", LOG_DEBUG);
144	if ($resql = $db->query($sql))
145	{
146		$num = $db->num_rows($resql);
147		$cpt = 0;
148		$oldemail = '';
149		$message = '';
150		$total = '';
151
152		if ($num)
153		{
154			// First loop on each resultset to build PDF
155			// -----------------------------------------
156
157			while ($cpt < $num)
158			{
159				$obj = $db->fetch_object($resql);
160
161				$fac = new Facture($db);
162				$result = $fac->fetch($obj->rowid);
163				if ($result > 0)
164				{
165					$outputlangs = $langs;
166					if (!empty($newlangid))
167					{
168						if ($outputlangs->defaultlang != $newlangid)
169						{
170							$outputlangs = new Translate("", $conf);
171							$outputlangs->setDefaultLang($newlangid);
172						}
173					}
174					$filename = $conf->facture->dir_output.'/'.$fac->ref.'/'.$fac->ref.'.pdf';
175					if ($regenerate || !dol_is_file($filename))
176					{
177						if ($usestdout) print "Build PDF for invoice ".$obj->ref." - Lang = ".$outputlangs->defaultlang."\n";
178						$result = $fac->generateDocument($regenerate ? $regenerate : $fac->modelpdf, $outputlangs);
179					} else {
180						if ($usestdout) print "PDF for invoice ".$obj->ref." already exists\n";
181					}
182
183					// Add file into files array
184					$files[] = $filename;
185				}
186
187				if ($result <= 0)
188				{
189					$error++;
190					if ($usestdout) print "Error: Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid)."\n";
191					else dol_syslog("Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid), LOG_ERR);
192				}
193
194				$cpt++;
195			}
196
197
198			// Define format of output PDF
199			$formatarray = pdf_getFormat($langs);
200			$page_largeur = $formatarray['width'];
201			$page_hauteur = $formatarray['height'];
202			$format = array($page_largeur, $page_hauteur);
203
204			if ($usestdout) print "Using output PDF format ".join('x', $format)."\n";
205			else dol_syslog("Using output PDF format ".join('x', $format), LOG_ERR);
206
207
208			// Now, build a merged files with all files in $files array
209			//---------------------------------------------------------
210
211			// Create empty PDF
212			$pdf = pdf_getInstance($format);
213			if (class_exists('TCPDF'))
214			{
215				$pdf->setPrintHeader(false);
216				$pdf->setPrintFooter(false);
217			}
218			$pdf->SetFont(pdf_getPDFFont($langs));
219
220			if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);
221			//$pdf->SetCompression(false);
222
223			// Add all others
224			foreach ($files as $file)
225			{
226				if ($usestdout) print "Merge PDF file for invoice ".$file."\n";
227				else dol_syslog("Merge PDF file for invoice ".$file);
228
229				// Charge un document PDF depuis un fichier.
230				$pagecount = $pdf->setSourceFile($file);
231				for ($i = 1; $i <= $pagecount; $i++)
232				{
233					 $tplidx = $pdf->importPage($i);
234					 $s = $pdf->getTemplatesize($tplidx);
235					 $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
236					 $pdf->useTemplate($tplidx);
237				}
238			}
239
240			// Create output dir if not exists
241			dol_mkdir($diroutputpdf);
242
243			// Save merged file
244			$filename = $fileprefix;
245			if (empty($filename)) $filename = 'mergedpdf';
246			if (!empty($filesuffix)) $filename .= '_'.$filesuffix;
247			$file = $diroutputpdf.'/'.$filename.'.pdf';
248
249			if (!$error && $pagecount)
250			{
251				$pdf->Output($file, 'F');
252				if (!empty($conf->global->MAIN_UMASK))
253					@chmod($file, octdec($conf->global->MAIN_UMASK));
254			}
255
256			if ($usestdout)
257			{
258				if (!$error) print "Merged PDF has been built in ".$file."\n";
259				else print "Can't build PDF ".$file."\n";
260			}
261
262			$result = 1;
263		} else {
264			if ($usestdout) print "No invoices found for criteria.\n";
265			else dol_syslog("No invoices found for criteria");
266			$result = 0;
267		}
268	} else {
269		dol_print_error($db);
270		dol_syslog("scripts/invoices/rebuild_merge.php: Error");
271		$error++;
272	}
273
274	if ($error) return -1;
275	else return $result;
276}
277