PageRenderTime 42ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/scripts/invoices/rebuild_merge_pdf.php

https://bitbucket.org/speedealing/speedealing
PHP | 423 lines | 301 code | 62 blank | 60 comment | 76 complexity | 624ff96f4aaa198da31cc93774e37deb MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-3.0, MIT
  1. #!/usr/bin/php
  2. <?php
  3. /*
  4. * Copyright (C) 2009-2012 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 3 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 Speedealing 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(FPDFI_PATH.'fpdi_protection.php');
  36. require_once(DOL_DOCUMENT_ROOT."/cron/functions_cron.lib.php");
  37. require_once(DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
  38. require_once(DOL_DOCUMENT_ROOT."/core/modules/facture/modules_facture.php");
  39. require_once(DOL_DOCUMENT_ROOT."/core/lib/date.lib.php");
  40. require_once(DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php');
  41. require_once(DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php');
  42. // Load main language strings
  43. $langs->load("main");
  44. // Global variables
  45. $version='1.24';
  46. $error=0;
  47. // -------------------- START OF YOUR CODE HERE --------------------
  48. @set_time_limit(0);
  49. print "***** ".$script_file." (".$version.") *****\n";
  50. // Check parameters
  51. if (! isset($argv[1]))
  52. {
  53. usage();
  54. exit;
  55. }
  56. $diroutputpdf=$conf->facture->dir_output . '/temp';
  57. $newmodel=''; // To force a new model
  58. $newlangid='en_EN'; // To force a new lang id
  59. $filter=array();
  60. $regenerate='';
  61. $option='';
  62. foreach ($argv as $key => $value)
  63. {
  64. $found=false;
  65. // Define options
  66. if (preg_match('/^lang=/i',$value))
  67. {
  68. $found=true;
  69. $valarray=explode('=',$value);
  70. $newlangid=$valarray[1];
  71. print 'Use language '.$newlangid.".\n";
  72. }
  73. if (preg_match('/^regenerate=(.*)/i',$value,$reg))
  74. {
  75. if (! in_array($reg[1],array('','0','no')))
  76. {
  77. $found=true;
  78. $regenerate=$reg[1];
  79. print 'Regeneration of PDF is requested with template '.$regenerate."\n";
  80. }
  81. }
  82. if ($value == 'filter=all')
  83. {
  84. $found=true;
  85. $option.=(empty($option)?'':'_').'all';
  86. $filter[]='all';
  87. print 'Rebuild PDF for all invoices'."\n";
  88. }
  89. if ($value == 'filter=date')
  90. {
  91. $found=true;
  92. $option.=(empty($option)?'':'_').'date_'.$argv[$key+1].'_'.$argv[$key+2];
  93. $filter[]='date';
  94. $dateafterdate=dol_stringtotime($argv[$key+1]);
  95. $datebeforedate=dol_stringtotime($argv[$key+2]);
  96. print 'Rebuild PDF for invoices validated between '.dol_print_date($dateafterdate,'day')." and ".dol_print_date($datebeforedate,'day').".\n";
  97. }
  98. if ($value == 'filter=payments')
  99. {
  100. $found=true;
  101. $option.=(empty($option)?'':'_').'payments_'.$argv[$key+1].'_'.$argv[$key+2];
  102. $filter[]='payments';
  103. $paymentdateafter=dol_stringtotime($argv[$key+1]);
  104. $paymentdatebefore=dol_stringtotime($argv[$key+2]);
  105. print 'Rebuild PDF for invoices with at least one payment between '.dol_print_date($paymentdateafter,'day')." and ".dol_print_date($paymentdatebefore,'day').".\n";
  106. }
  107. if ($value == 'filter=nopayment')
  108. {
  109. $found=true;
  110. $option.=(empty($option)?'':'_').'nopayment';
  111. $filter[]='nopayment';
  112. print 'Rebuild PDF for invoices with no payment done yet.'."\n";
  113. }
  114. if ($value == 'filter=nodeposit')
  115. {
  116. $found=true;
  117. $option.=(empty($option)?'':'_').'nodeposit';
  118. $filter[]='nodeposit';
  119. print 'Exclude deposit invoices'."\n";
  120. }
  121. if ($value == 'filter=noreplacement')
  122. {
  123. $found=true;
  124. $option.=(empty($option)?'':'_').'noreplacement';
  125. $filter[]='noreplacement';
  126. print 'Exclude replacement invoices'."\n";
  127. }
  128. if ($value == 'filter=nocreditnote')
  129. {
  130. $found=true;
  131. $option.=(empty($option)?'':'_').'nocreditnote';
  132. $filter[]='nocreditnote';
  133. print 'Exclude credit note invoices'."\n";
  134. }
  135. if (! $found && preg_match('/filter=/i',$value))
  136. {
  137. usage();
  138. exit;
  139. }
  140. }
  141. // Check if an option and a filter has been provided
  142. if (empty($option) && count($filter) <= 0)
  143. {
  144. usage();
  145. exit;
  146. }
  147. // Check if there is no uncompatible choice
  148. if (in_array('payments',$filter) && in_array('nopayment',$filter))
  149. {
  150. usage();
  151. exit;
  152. }
  153. // Define SQL and SQL order request to select invoices
  154. $sql = "SELECT DISTINCT f.rowid, f.facnumber";
  155. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  156. $sqlwhere='';
  157. $sqlorder='';
  158. if (in_array('all',$filter))
  159. {
  160. $sqlorder = " ORDER BY f.facnumber ASC";
  161. }
  162. if (in_array('date',$filter))
  163. {
  164. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  165. else $sqlwhere.=" AND";
  166. $sqlwhere.= " f.fk_statut > 0";
  167. $sqlwhere.= " AND f.datef >= '".$db->idate($dateafterdate)."'";
  168. $sqlwhere.= " AND f.datef <= '".$db->idate($datebeforedate)."'";
  169. $sqlorder = " ORDER BY f.datef ASC";
  170. }
  171. if (in_array('nopayment',$filter))
  172. {
  173. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  174. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  175. else $sqlwhere.=" AND";
  176. $sqlwhere.= " f.fk_statut > 0";
  177. $sqlwhere.= " AND pf.fk_paiement IS NULL";
  178. }
  179. if (in_array('payments',$filter))
  180. {
  181. $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf,";
  182. $sql.= " ".MAIN_DB_PREFIX."paiement as p";
  183. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  184. else $sqlwhere.=" AND";
  185. $sqlwhere.= " f.fk_statut > 0";
  186. $sqlwhere.= " AND f.rowid = pf.fk_facture";
  187. $sqlwhere.= " AND pf.fk_paiement = p.rowid";
  188. $sqlwhere.= " AND p.datep >= '".$db->idate($paymentdateafter)."'";
  189. $sqlwhere.= " AND p.datep <= '".$db->idate($paymentdatebefore)."'";
  190. $sqlorder = " ORDER BY p.datep ASC";
  191. }
  192. if (in_array('nodeposit',$filter))
  193. {
  194. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  195. else $sqlwhere.=" AND";
  196. $sqlwhere.=' type <> 3';
  197. }
  198. if (in_array('noreplacement',$filter))
  199. {
  200. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  201. else $sqlwhere.=" AND";
  202. $sqlwhere.=' type <> 1';
  203. }
  204. if (in_array('nocreditnote',$filter))
  205. {
  206. if (empty($sqlwhere)) $sqlwhere=' WHERE ';
  207. else $sqlwhere.=" AND";
  208. $sqlwhere.=' type <> 2';
  209. }
  210. if ($sqlwhere) $sql.=$sqlwhere;
  211. if ($sqlorder) $sql.=$sqlorder;
  212. //print $sql; exit;
  213. dol_syslog("scripts/invoices/rebuild_merge.php: sql=",$sql);
  214. print '--- start'."\n";
  215. // Start of transaction
  216. //$db->begin();
  217. $error = 0;
  218. $files = array() ; // liste les fichiers
  219. dol_syslog("scripts/invoices/rebuild_merge.php sql=".$sql);
  220. if ( $resql=$db->query($sql) )
  221. {
  222. $num = $db->num_rows($resql);
  223. $cpt = 0;
  224. $oldemail = '';
  225. $message = '';
  226. $total = '';
  227. if ($num)
  228. {
  229. // First loop on each resultset to build PDF
  230. // -----------------------------------------
  231. while ($cpt < $num)
  232. {
  233. $obj = $db->fetch_object($resql);
  234. $fac = new Facture($db);
  235. $result=$fac->fetch($obj->rowid);
  236. if ($result > 0)
  237. {
  238. $outputlangs = $langs;
  239. if (! empty($newlangid))
  240. {
  241. if ($outputlangs->defaultlang != $newlangid)
  242. {
  243. $outputlangs = new Translate();
  244. $outputlangs->setDefaultLang($newlangid);
  245. }
  246. }
  247. $filename=$conf->facture->dir_output.'/'.$fac->ref.'/'.$fac->ref.'.pdf';
  248. if ($regenerate || ! dol_is_file($filename))
  249. {
  250. print "Build PDF for invoice ".$obj->facnumber." - Lang = ".$outputlangs->defaultlang."\n";
  251. $result=facture_pdf_create($db, $fac, $newmodel?$newmodel:$fac->modelpdf, $outputlangs);
  252. }
  253. else {
  254. print "PDF for invoice ".$obj->facnumber." already exists\n";
  255. }
  256. // Add file into files array
  257. $files[] = $filename;
  258. }
  259. if ($result <= 0)
  260. {
  261. print "Error: Failed to build PDF for invoice ".$fac->ref."\n";
  262. }
  263. $cpt++;
  264. }
  265. // Now, build a merged files with all files in $files array
  266. //---------------------------------------------------------
  267. // Create empty PDF
  268. $pdf=pdf_getInstance();
  269. if (class_exists('TCPDF'))
  270. {
  271. $pdf->setPrintHeader(false);
  272. $pdf->setPrintFooter(false);
  273. }
  274. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  275. if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);
  276. //$pdf->SetCompression(false);
  277. //$pdf->Open();
  278. //$pdf->AddPage();
  279. //$title=$langs->trans("BillsCustomersUnpaid");
  280. //if ($option=='late') $title=$langs->trans("BillsCustomersUnpaid");
  281. //$pdf->MultiCell(100, 3, $title, 0, 'J');
  282. // Add all others
  283. foreach($files as $file)
  284. {
  285. print "Merge PDF file for invoice ".$file."\n";
  286. // Charge un document PDF depuis un fichier.
  287. $pagecount = $pdf->setSourceFile($file);
  288. for ($i = 1; $i <= $pagecount; $i++)
  289. {
  290. $tplidx = $pdf->importPage($i);
  291. $s = $pdf->getTemplatesize($tplidx);
  292. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  293. $pdf->useTemplate($tplidx);
  294. }
  295. }
  296. // Create output dir if not exists
  297. dol_mkdir($diroutputpdf);
  298. // Save merged file
  299. $filename='mergedpdf';
  300. if (! empty($option)) $filename.='_'.$option;
  301. if ($pagecount)
  302. {
  303. $file=$diroutputpdf.'/'.$filename.'.pdf';
  304. $pdf->Output($file,'F');
  305. if (! empty($conf->global->MAIN_UMASK))
  306. @chmod($file, octdec($conf->global->MAIN_UMASK));
  307. }
  308. print "Merged PDF has been built in ".$file."\n";
  309. }
  310. else
  311. {
  312. print "No invoices with payments in this range.\n";
  313. }
  314. }
  315. else
  316. {
  317. dol_print_error($db);
  318. dol_syslog("scripts/invoices/rebuild_merge.php: Error");
  319. }
  320. // -------------------- END OF YOUR CODE --------------------
  321. if (! $error)
  322. {
  323. //$db->commit();
  324. print '--- end ok'."\n";
  325. }
  326. else
  327. {
  328. print '--- end error code='.$error."\n";
  329. //$db->rollback();
  330. }
  331. $db->close();
  332. return $error;
  333. /**
  334. * Show usage of script
  335. *
  336. * @return unknown
  337. */
  338. function usage()
  339. {
  340. global $script_file;
  341. print "Rebuild PDF files for some invoices and merge PDF files into one.\n";
  342. print "\n";
  343. print "To build/merge PDF for invoices in a date range:\n";
  344. print "Usage: ".$script_file." filter=date dateafter datebefore [lang=langcode]\n";
  345. print "To build/merge PDF for invoices with at least one payment in a date range:\n";
  346. print "Usage: ".$script_file." filter=payments dateafter datebefore [lang=langcode]\n";
  347. print "To build/merge PDF for all invoices, use filter=all\n";
  348. print "Usage: ".$script_file." filter=all\n";
  349. print "To build/merge PDF for invoices with no payments, use filter=nopayment\n";
  350. print "Usage: ".$script_file." filter=nopayment\n";
  351. print "To exclude credit notes, use filter=nocreditnote\n";
  352. print "To exclude replacement invoices, use filter=noreplacement\n";
  353. print "To exclude deposit invoices, use filter=nodeposit\n";
  354. print "To regenerate existing PDF, use regenerate=crabe\n";
  355. print "\n";
  356. print "Example: ".$script_file." filter=payments 20080101 20081231 lang=fr_FR regenerate=yes\n";
  357. print "Example: ".$script_file." filter=all lang=it_IT\n";
  358. print "\n";
  359. print "Note that some filters can be cumulated.\n";
  360. }
  361. ?>