PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/scripts/invoices/rebuild_merge_pdf.php

https://github.com/asterix14/dolibarr
PHP | 401 lines | 280 code | 61 blank | 60 comment | 70 complexity | c223bb20a44159e864d91d748e5c7571 MD5 | raw file
Possible License(s): LGPL-2.0
  1. #!/usr/bin/php
  2. <?php
  3. /*
  4. * Copyright (C) 2009-2010 Laurent Destailleur <eldy@users.sourceforge.net>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file scripts/invoices/rebuild_merge_pdf.php
  21. * \ingroup facture
  22. * \brief Script to rebuild PDF and merge PDF files into one
  23. */
  24. $sapi_type = php_sapi_name();
  25. $script_file = basename(__FILE__);
  26. $path=dirname(__FILE__).'/';
  27. // Test if batch mode
  28. if (substr($sapi_type, 0, 3) == 'cgi') {
  29. echo "Error: You ar usingr PH for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
  30. exit;
  31. }
  32. // Include Dolibarr environment
  33. require_once($path."../../htdocs/master.inc.php");
  34. // After this $db is an opened handler to database. We close it at end of file.
  35. require_once(DOL_DOCUMENT_ROOT."/cron/functions_cron.lib.php");
  36. require_once(DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
  37. require_once(DOL_DOCUMENT_ROOT."/core/modules/facture/modules_facture.php");
  38. require_once(DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php');
  39. // Load main language strings
  40. $langs->load("main");
  41. // Global variables
  42. $version='1.24';
  43. $error=0;
  44. // -------------------- START OF YOUR CODE HERE --------------------
  45. @set_time_limit(0);
  46. print "***** ".$script_file." (".$version.") *****\n";
  47. // Check parameters
  48. if (! isset($argv[1]))
  49. {
  50. usage();
  51. exit;
  52. }
  53. $diroutputpdf=$conf->facture->dir_output . '/temp';
  54. $newmodel=''; // To force a new model
  55. $newlangid='en_EN'; // To force a new lang id
  56. $filter=array();
  57. $option='';
  58. foreach ($argv as $key => $value)
  59. {
  60. $found=false;
  61. // Define options
  62. if (preg_match('/^lang=/i',$value))
  63. {
  64. $found=true;
  65. $valarray=explode('=',$value);
  66. $newlangid=$valarray[1];
  67. print 'Use language '.$newlangid.".\n";
  68. }
  69. if ($value == 'filter=all')
  70. {
  71. $found=true;
  72. $option.=(empty($option)?'':'_').'all';
  73. $filter[]='all';
  74. print 'Rebuild PDF for all invoices'."\n";
  75. }
  76. if ($value == 'filter=date')
  77. {
  78. $found=true;
  79. $option.=(empty($option)?'':'_').'date_'.$argv[$key+1].'_'.$argv[$key+2];
  80. $filter[]='date';
  81. $dateafterdate=dol_stringtotime($argv[$key+1]);
  82. $datebeforedate=dol_stringtotime($argv[$key+2]);
  83. print 'Rebuild PDF for invoices validated between '.dol_print_date($dateafterdate,'day')." and ".dol_print_date($datebeforedate,'day').".\n";
  84. }
  85. if ($value == 'filter=payments')
  86. {
  87. $found=true;
  88. $option.=(empty($option)?'':'_').'payments_'.$argv[$key+1].'_'.$argv[$key+2];
  89. $filter[]='payments';
  90. $paymentdateafter=dol_stringtotime($argv[$key+1]);
  91. $paymentdatebefore=dol_stringtotime($argv[$key+2]);
  92. print 'Rebuild PDF for invoices with at least one payment between '.dol_print_date($paymentdateafter,'day')." and ".dol_print_date($paymentdatebefore,'day').".\n";
  93. }
  94. if ($value == 'filter=nopayment')
  95. {
  96. $found=true;
  97. $option.=(empty($option)?'':'_').'nopayment';
  98. $filter[]='nopayment';
  99. print 'Rebuild PDF for invoices with no payment done yet.'."\n";
  100. }
  101. if ($value == 'filter=nodeposit')
  102. {
  103. $found=true;
  104. $option.=(empty($option)?'':'_').'nodeposit';
  105. $filter[]='nodeposit';
  106. print 'Exclude deposit invoices'."\n";
  107. }
  108. if ($value == 'filter=noreplacement')
  109. {
  110. $found=true;
  111. $option.=(empty($option)?'':'_').'noreplacement';
  112. $filter[]='noreplacement';
  113. print 'Exclude replacement invoices'."\n";
  114. }
  115. if ($value == 'filter=nocreditnote')
  116. {
  117. $found=true;
  118. $option.=(empty($option)?'':'_').'nocreditnote';
  119. $filter[]='nocreditnote';
  120. print 'Exclude credit note invoices'."\n";
  121. }
  122. if (! $found && preg_match('/filter=/i',$value))
  123. {
  124. usage();
  125. exit;
  126. }
  127. }
  128. // Check if an option and a filter has been provided
  129. if (empty($option) && count($filter) <= 0)
  130. {
  131. usage();
  132. exit;
  133. }
  134. // Check if there is no uncompatible choice
  135. if (in_array('payments',$filter) && in_array('nopayment',$filter))
  136. {
  137. usage();
  138. exit;
  139. }
  140. // Define SQL and SQL order request to select invoices
  141. $sql = "SELECT DISTINCT f.rowid, f.facnumber";
  142. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  143. $sqlwhere='';
  144. $sqlorder='';
  145. if (in_array('all',$filter))
  146. {
  147. $sqlorder = " ORDER BY f.facnumber ASC";
  148. }
  149. if (in_array('date',$filter))
  150. {
  151. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  152. else $sqlwhere.=" AND";
  153. $sqlwhere.= " f.fk_statut > 0";
  154. $sqlwhere.= " AND f.datef >= ".$db->idate($dateafterdate);
  155. $sqlwhere.= " AND f.datef <= ".$db->idate($datebeforedate);
  156. $sqlorder = " ORDER BY f.datef ASC";
  157. }
  158. if (in_array('nopayment',$filter))
  159. {
  160. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  161. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  162. else $sqlwhere.=" AND";
  163. $sqlwhere.= " f.fk_statut > 0";
  164. $sqlwhere.= " AND pf.fk_paiement IS NULL";
  165. }
  166. if (in_array('payments',$filter))
  167. {
  168. $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf,";
  169. $sql.= " ".MAIN_DB_PREFIX."paiement as p";
  170. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  171. else $sqlwhere.=" AND";
  172. $sqlwhere.= " f.fk_statut > 0";
  173. $sqlwhere.= " AND f.rowid = pf.fk_facture";
  174. $sqlwhere.= " AND pf.fk_paiement = p.rowid";
  175. $sqlwhere.= " AND p.datep >= ".$db->idate($paymentdateafter);
  176. $sqlwhere.= " AND p.datep <= ".$db->idate($paymentdatebefore);
  177. $sqlorder = " ORDER BY p.datep ASC";
  178. }
  179. if (in_array('nodeposit',$filter))
  180. {
  181. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  182. else $sqlwhere.=" AND";
  183. $sqlwhere.=' type <> 3';
  184. }
  185. if (in_array('noreplacement',$filter))
  186. {
  187. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  188. else $sqlwhere.=" AND";
  189. $sqlwhere.=' type <> 1';
  190. }
  191. if (in_array('nocreditnote',$filter))
  192. {
  193. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  194. else $sqlwhere.=" AND";
  195. $sqlwhere.=' type <> 2';
  196. }
  197. if ($sqlwhere) $sql.=$sqlwhere;
  198. if ($sqlorder) $sql.=$sqlorder;
  199. //print $sql; exit;
  200. dol_syslog("scripts/invoices/rebuild_merge.php: sql=",$sql);
  201. print '--- start'."\n";
  202. // Start of transaction
  203. //$db->begin();
  204. $error = 0;
  205. $files = array() ; // liste les fichiers
  206. dol_syslog("scripts/invoices/rebuild_merge.php sql=".$sql);
  207. if ( $resql=$db->query($sql) )
  208. {
  209. $num = $db->num_rows($resql);
  210. $cpt = 0;
  211. $oldemail = '';
  212. $message = '';
  213. $total = '';
  214. if ($num)
  215. {
  216. // First loop on each resultset to build PDF
  217. // -----------------------------------------
  218. while ($cpt < $num)
  219. {
  220. $obj = $db->fetch_object($resql);
  221. $fac = new Facture($db);
  222. $result=$fac->fetch($obj->rowid);
  223. if ($result > 0)
  224. {
  225. $outputlangs = $langs;
  226. if (! empty($newlangid))
  227. {
  228. if ($outputlangs->defaultlang != $newlangid)
  229. {
  230. $outputlangs = new Translate("",$conf);
  231. $outputlangs->setDefaultLang($newlangid);
  232. }
  233. }
  234. print "Build PDF for invoice ".$obj->facnumber." - Lang = ".$outputlangs->defaultlang."\n";
  235. $result=facture_pdf_create($db, $fac, '', $newmodel?$newmodel:$fac->modelpdf, $outputlangs);
  236. // Add file into files array
  237. $files[] = $conf->facture->dir_output.'/'.$fac->ref.'/'.$fac->ref.'.pdf';
  238. }
  239. if ($result <= 0)
  240. {
  241. print "Error: Failed to build PDF for invoice ".$fac->ref."\n";
  242. }
  243. $cpt++;
  244. }
  245. // Now, build a merged files with all files in $files array
  246. //---------------------------------------------------------
  247. // Create empty PDF
  248. $pdf=pdf_getInstance();
  249. if (class_exists('TCPDF'))
  250. {
  251. $pdf->setPrintHeader(false);
  252. $pdf->setPrintFooter(false);
  253. }
  254. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  255. if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);
  256. //$pdf->SetCompression(false);
  257. //$pdf->Open();
  258. //$pdf->AddPage();
  259. //$title=$langs->trans("BillsCustomersUnpaid");
  260. //if ($option=='late') $title=$langs->trans("BillsCustomersUnpaid");
  261. //$pdf->MultiCell(100, 3, $title, 0, 'J');
  262. // Add all others
  263. foreach($files as $file)
  264. {
  265. print "Merge PDF file for invoice ".$file."\n";
  266. // Charge un document PDF depuis un fichier.
  267. $pagecount = $pdf->setSourceFile($file);
  268. for ($i = 1; $i <= $pagecount; $i++)
  269. {
  270. $tplidx = $pdf->importPage($i);
  271. $s = $pdf->getTemplatesize($tplidx);
  272. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  273. $pdf->useTemplate($tplidx);
  274. }
  275. }
  276. // Create output dir if not exists
  277. create_exdir($diroutputpdf);
  278. // Save merged file
  279. $filename='mergedpdf';
  280. if (! empty($option)) $filename.='_'.$option;
  281. if ($pagecount)
  282. {
  283. $file=$diroutputpdf.'/'.$filename.'.pdf';
  284. $pdf->Output($file,'F');
  285. if (! empty($conf->global->MAIN_UMASK))
  286. @chmod($file, octdec($conf->global->MAIN_UMASK));
  287. }
  288. print "Merged PDF has been built in ".$file."\n";
  289. }
  290. else
  291. {
  292. print "No invoices with payments in this range.\n";
  293. }
  294. }
  295. else
  296. {
  297. dol_print_error($db);
  298. dol_syslog("scripts/invoices/rebuild_merge.php: Error");
  299. }
  300. // -------------------- END OF YOUR CODE --------------------
  301. if (! $error)
  302. {
  303. //$db->commit();
  304. print '--- end ok'."\n";
  305. }
  306. else
  307. {
  308. print '--- end error code='.$error."\n";
  309. //$db->rollback();
  310. }
  311. $db->close();
  312. return $error;
  313. /**
  314. * Show usage of script
  315. *
  316. * @return unknown
  317. */
  318. function usage()
  319. {
  320. global $script_file;
  321. print "Rebuild PDF files for some invoices and merge PDF files into one.\n";
  322. print "\n";
  323. print "To build/merge PDF for invoices in a date range:\n";
  324. print "Usage: ".$script_file." filter=date dateafter datebefore [lang=langcode]\n";
  325. print "To build/merge PDF for invoices with at least one payment in a date range:\n";
  326. print "Usage: ".$script_file." filter=payments dateafter datebefore [lang=langcode]\n";
  327. print "To build/merge PDF for all invoices, use filter=all\n";
  328. print "Usage: ".$script_file." filter=all\n";
  329. print "To build/merge PDF for invoices with no payments, use filter=nopayment\n";
  330. print "Usage: ".$script_file." filter=nopayment\n";
  331. print "To exclude credit notes, use filter=nocreditnote\n";
  332. print "To exclude replacement invoices, use filter=noreplacement\n";
  333. print "To exclude deposit invoices, use filter=nodeposit\n";
  334. print "\n";
  335. print "Example: ".$script_file." filter=payments 20080101 20081231 lang=fr_FR\n";
  336. print "Example: ".$script_file." filter=all lang=it_IT\n";
  337. print "\n";
  338. print "Note that some filters can be cumulated.\n";
  339. }
  340. ?>