printsheet.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. /* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2006-2017 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 <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/barcode/printsheet.php
  21. * \ingroup member
  22. * \brief Page to print sheets with barcodes using the document templates into core/modules/printsheets
  23. */
  24. if (!empty($_POST['mode']) && $_POST['mode'] === 'label') { // Page is called to build a PDF and output, we must not renew the token.
  25. if (!defined('NOTOKENRENEWAL')) {
  26. define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
  27. }
  28. }
  29. // Load Dolibarr environment
  30. require '../main.inc.php';
  31. require_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
  32. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/modules/printsheet/modules_labels.php';
  34. require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php';
  35. // Load translation files required by the page
  36. $langs->loadLangs(array('admin', 'members', 'errors'));
  37. // Choice of print year or current year.
  38. $now = dol_now();
  39. $year = dol_print_date($now, '%Y');
  40. $month = dol_print_date($now, '%m');
  41. $day = dol_print_date($now, '%d');
  42. $forbarcode = GETPOST('forbarcode', 'alphanohtml');
  43. $fk_barcode_type = GETPOST('fk_barcode_type', 'int');
  44. $mode = GETPOST('mode', 'aZ09');
  45. $modellabel = GETPOST("modellabel", 'aZ09'); // Doc template to use
  46. $numberofsticker = GETPOST('numberofsticker', 'int');
  47. $mesg = '';
  48. $action = GETPOST('action', 'aZ09');
  49. $producttmp = new Product($db);
  50. $thirdpartytmp = new Societe($db);
  51. // Security check (enable the most restrictive one)
  52. //if ($user->socid > 0) accessforbidden();
  53. //if ($user->socid > 0) $socid = $user->socid;
  54. if (!isModEnabled('barcode')) {
  55. accessforbidden('Module not enabled');
  56. }
  57. if (!$user->hasRight('barcode', 'read')) {
  58. accessforbidden();
  59. }
  60. restrictedArea($user, 'barcode');
  61. /*
  62. * Actions
  63. */
  64. if (GETPOST('submitproduct') && GETPOST('submitproduct')) {
  65. $action = ''; // We reset because we don't want to build doc
  66. if (GETPOST('productid', 'int') > 0) {
  67. $result = $producttmp->fetch(GETPOST('productid', 'int'));
  68. if ($result < 0) {
  69. setEventMessage($producttmp->error, 'errors');
  70. }
  71. $forbarcode = $producttmp->barcode;
  72. $fk_barcode_type = $producttmp->barcode_type;
  73. if (empty($fk_barcode_type) && getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE')) {
  74. $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  75. }
  76. if (empty($forbarcode) || empty($fk_barcode_type)) {
  77. setEventMessages($langs->trans("DefinitionOfBarCodeForProductNotComplete", $producttmp->getNomUrl()), null, 'warnings');
  78. }
  79. }
  80. }
  81. if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty')) {
  82. $action = ''; // We reset because we don't want to build doc
  83. if (GETPOST('socid', 'int') > 0) {
  84. $thirdpartytmp->fetch(GETPOST('socid', 'int'));
  85. $forbarcode = $thirdpartytmp->barcode;
  86. $fk_barcode_type = $thirdpartytmp->barcode_type_code;
  87. if (empty($fk_barcode_type) && getDolGlobalString('GENBARCODE_BARCODETYPE_THIRDPARTY')) {
  88. $fk_barcode_type = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  89. }
  90. if (empty($forbarcode) || empty($fk_barcode_type)) {
  91. setEventMessages($langs->trans("DefinitionOfBarCodeForThirdpartyNotComplete", $thirdpartytmp->getNomUrl()), null, 'warnings');
  92. }
  93. }
  94. }
  95. if ($action == 'builddoc') {
  96. $result = 0;
  97. $error = 0;
  98. if (empty($forbarcode)) { // barcode value
  99. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BarcodeValue")), null, 'errors');
  100. $error++;
  101. }
  102. $MAXLENGTH = 51200; // Limit set to 50Ko
  103. if (dol_strlen($forbarcode) > $MAXLENGTH) { // barcode value
  104. setEventMessages($langs->trans("ErrorFieldTooLong", $langs->transnoentitiesnoconv("BarcodeValue")).' ('.$langs->trans("RequireXStringMax", $MAXLENGTH).')', null, 'errors');
  105. $error++;
  106. }
  107. if (empty($fk_barcode_type)) { // barcode type = barcode encoding
  108. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BarcodeType")), null, 'errors');
  109. $error++;
  110. }
  111. if (!$error) {
  112. // Get encoder (barcode_type_coder) from barcode type id (barcode_type)
  113. $stdobject = new GenericObject($db);
  114. $stdobject->barcode_type = $fk_barcode_type;
  115. $result = $stdobject->fetch_barcode();
  116. if ($result <= 0) {
  117. $error++;
  118. setEventMessages('Failed to get bar code type information '.$stdobject->error, $stdobject->errors, 'errors');
  119. }
  120. }
  121. if (!$error) {
  122. $code = $forbarcode;
  123. $generator = $stdobject->barcode_type_coder; // coder (loaded by fetch_barcode). Engine.
  124. $encoding = strtoupper($stdobject->barcode_type_code); // code (loaded by fetch_barcode). Example 'ean', 'isbn', ...
  125. $diroutput = $conf->barcode->dir_temp;
  126. dol_mkdir($diroutput);
  127. // Generate barcode
  128. $dirbarcode = array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']);
  129. foreach ($dirbarcode as $reldir) {
  130. $dir = dol_buildpath($reldir, 0);
  131. $newdir = dol_osencode($dir);
  132. // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php)
  133. if (!is_dir($newdir)) {
  134. continue;
  135. }
  136. $result = @include_once $newdir.$generator.'.modules.php';
  137. if ($result) {
  138. break;
  139. }
  140. }
  141. // Load barcode class for generating barcode image
  142. $classname = "mod".ucfirst($generator);
  143. $module = new $classname($db);
  144. if ($generator != 'tcpdfbarcode') {
  145. // May be phpbarcode
  146. $template = 'standardlabel';
  147. $is2d = false;
  148. if ($module->encodingIsSupported($encoding)) {
  149. $barcodeimage = $conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png';
  150. dol_delete_file($barcodeimage);
  151. // File is created with full name $barcodeimage = $conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png';
  152. $result = $module->writeBarCode($code, $encoding, 'Y', 4, 1);
  153. if ($result <= 0 || !dol_is_file($barcodeimage)) {
  154. $error++;
  155. setEventMessages('Failed to generate image file of barcode for code='.$code.' encoding='.$encoding.' file='.basename($barcodeimage), null, 'errors');
  156. setEventMessages($module->error, null, 'errors');
  157. }
  158. } else {
  159. $error++;
  160. setEventMessages("Error, encoding ".$encoding." is not supported by encoder ".$generator.'. You must choose another barcode type or install a barcode generation engine that support '.$encoding, null, 'errors');
  161. }
  162. } else {
  163. $template = 'tcpdflabel';
  164. $encoding = $module->getTcpdfEncodingType($encoding); //convert to TCPDF compatible encoding types
  165. $is2d = $module->is2d;
  166. }
  167. }
  168. if (!$error) {
  169. // List of values to scan for a replacement
  170. $substitutionarray = array(
  171. '%LOGIN%' => $user->login,
  172. '%COMPANY%' => $mysoc->name,
  173. '%ADDRESS%' => $mysoc->address,
  174. '%ZIP%' => $mysoc->zip,
  175. '%TOWN%' => $mysoc->town,
  176. '%COUNTRY%' => $mysoc->country,
  177. '%COUNTRY_CODE%' => $mysoc->country_code,
  178. '%EMAIL%' => $mysoc->email,
  179. '%YEAR%' => $year,
  180. '%MONTH%' => $month,
  181. '%DAY%' => $day,
  182. '%DOL_MAIN_URL_ROOT%' => DOL_MAIN_URL_ROOT,
  183. '%SERVER%' => "http://".$_SERVER["SERVER_NAME"]."/",
  184. );
  185. complete_substitutions_array($substitutionarray, $langs);
  186. // For labels
  187. if ($mode == 'label') {
  188. $txtforsticker = "%PHOTO%"; // Photo will be barcode image, %BARCODE% posible when using TCPDF generator
  189. $textleft = make_substitutions((!getDolGlobalString('BARCODE_LABEL_LEFT_TEXT') ? $txtforsticker : $conf->global->BARCODE_LABEL_LEFT_TEXT), $substitutionarray);
  190. $textheader = make_substitutions((!getDolGlobalString('BARCODE_LABEL_HEADER_TEXT') ? '' : $conf->global->BARCODE_LABEL_HEADER_TEXT), $substitutionarray);
  191. $textfooter = make_substitutions((!getDolGlobalString('BARCODE_LABEL_FOOTER_TEXT') ? '' : $conf->global->BARCODE_LABEL_FOOTER_TEXT), $substitutionarray);
  192. $textright = make_substitutions((!getDolGlobalString('BARCODE_LABEL_RIGHT_TEXT') ? '' : $conf->global->BARCODE_LABEL_RIGHT_TEXT), $substitutionarray);
  193. $forceimgscalewidth = (!getDolGlobalString('BARCODE_FORCEIMGSCALEWIDTH') ? 1 : $conf->global->BARCODE_FORCEIMGSCALEWIDTH);
  194. $forceimgscaleheight = (!getDolGlobalString('BARCODE_FORCEIMGSCALEHEIGHT') ? 1 : $conf->global->BARCODE_FORCEIMGSCALEHEIGHT);
  195. $MAXSTICKERS = 1000;
  196. if ($numberofsticker <= $MAXSTICKERS) {
  197. for ($i = 0; $i < $numberofsticker; $i++) {
  198. $arrayofrecords[] = array(
  199. 'textleft'=>$textleft,
  200. 'textheader'=>$textheader,
  201. 'textfooter'=>$textfooter,
  202. 'textright'=>$textright,
  203. 'code'=>$code,
  204. 'encoding'=>$encoding,
  205. 'is2d'=>$is2d,
  206. 'photo'=>!empty($barcodeimage) ? $barcodeimage : '' // Photo must be a file that exists with format supported by TCPDF
  207. );
  208. }
  209. } else {
  210. $mesg = $langs->trans("ErrorQuantityIsLimitedTo", $MAXSTICKERS);
  211. $error++;
  212. }
  213. }
  214. $i++;
  215. // Build and output PDF
  216. if (!$error && $mode == 'label') {
  217. if (!count($arrayofrecords)) {
  218. $mesg = $langs->trans("ErrorRecordNotFound");
  219. }
  220. if (empty($modellabel) || $modellabel == '-1') {
  221. $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE"));
  222. }
  223. $outfile = $langs->trans("BarCode").'_sheets_'.dol_print_date(dol_now(), 'dayhourlog').'.pdf';
  224. if (!$mesg) {
  225. $outputlangs = $langs;
  226. $previousConf = getDolGlobalInt('TCPDF_THROW_ERRORS_INSTEAD_OF_DIE');
  227. $conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE = 1;
  228. // This generates and send PDF to output
  229. // TODO Move
  230. try {
  231. $result = doc_label_pdf_create($db, $arrayofrecords, $modellabel, $outputlangs, $diroutput, $template, dol_sanitizeFileName($outfile));
  232. } catch (Exception $e) {
  233. $mesg = $langs->trans('ErrorGeneratingBarcode');
  234. }
  235. $conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE = $previousConf;
  236. }
  237. }
  238. if ($result <= 0 || $mesg || $error) {
  239. if (empty($mesg)) {
  240. $mesg = 'Error '.$result;
  241. }
  242. setEventMessages($mesg, null, 'errors');
  243. } else {
  244. $db->close();
  245. exit;
  246. }
  247. }
  248. }
  249. /*
  250. * View
  251. */
  252. $form = new Form($db);
  253. llxHeader('', $langs->trans("BarCodePrintsheet"));
  254. print load_fiche_titre($langs->trans("BarCodePrintsheet"), '', 'barcode');
  255. print '<br>';
  256. print '<span class="opacitymedium">'.$langs->trans("PageToGenerateBarCodeSheets", $langs->transnoentitiesnoconv("BuildPageToPrint")).'</span><br>';
  257. print '<br>';
  258. //print img_picto('','puce').' '.$langs->trans("PrintsheetForOneBarCode").'<br>';
  259. //print '<br>';
  260. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; // The target is for brothers that open the file instead of downloading it
  261. print '<input type="hidden" name="mode" value="label">';
  262. print '<input type="hidden" name="action" value="builddoc">';
  263. print '<input type="hidden" name="token" value="'.currentToken().'">'; // The page will not renew the token but force download of a file, so we must use here currentToken
  264. print '<div class="tagtable">';
  265. // Sheet format
  266. print ' <div class="tagtr">';
  267. print ' <div class="tagtd">';
  268. print $langs->trans("DescADHERENT_ETIQUETTE_TYPE").' &nbsp; ';
  269. print '</div><div class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;">';
  270. // List of possible labels (defined into $_Avery_Labels variable set into core/lib/format_cards.lib.php)
  271. $arrayoflabels = array();
  272. foreach (array_keys($_Avery_Labels) as $codecards) {
  273. $labeltoshow = $_Avery_Labels[$codecards]['name'];
  274. //$labeltoshow.=' ('.$_Avery_Labels[$row['code']]['paper-size'].')';
  275. $arrayoflabels[$codecards] = $labeltoshow;
  276. }
  277. asort($arrayoflabels);
  278. print $form->selectarray('modellabel', $arrayoflabels, (GETPOST('modellabel') ? GETPOST('modellabel') : getDolGlobalString('ADHERENT_ETIQUETTE_TYPE')), 1, 0, 0, '', 0, 0, 0, '', '', 1);
  279. print '</div></div>';
  280. // Number of stickers to print
  281. print ' <div class="tagtr">';
  282. print ' <div class="tagtd">';
  283. print $langs->trans("NumberOfStickers").' &nbsp; ';
  284. print '</div><div class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;">';
  285. print '<input size="4" type="text" name="numberofsticker" value="'.(GETPOST('numberofsticker') ? GETPOST('numberofsticker', 'int') : 10).'">';
  286. print '</div></div>';
  287. print '</div>';
  288. print '<br>';
  289. // Add javascript to make choice dynamic
  290. print '<script type="text/javascript">
  291. jQuery(document).ready(function() {
  292. function init_selectors()
  293. {
  294. if (jQuery("#fillmanually:checked").val() == "fillmanually")
  295. {
  296. jQuery("#submitproduct").prop("disabled", true);
  297. jQuery("#submitthirdparty").prop("disabled", true);
  298. jQuery("#search_productid").prop("disabled", true);
  299. jQuery("#socid").prop("disabled", true);
  300. jQuery(".showforproductselector").hide();
  301. jQuery(".showforthirdpartyselector").hide();
  302. }
  303. if (jQuery("#fillfromproduct:checked").val() == "fillfromproduct")
  304. {
  305. jQuery("#submitproduct").removeAttr("disabled");
  306. jQuery("#submitthirdparty").prop("disabled", true);
  307. jQuery("#search_productid").removeAttr("disabled");
  308. jQuery("#socid").prop("disabled", true);
  309. jQuery(".showforproductselector").show();
  310. jQuery(".showforthirdpartyselector").hide();
  311. }
  312. if (jQuery("#fillfromthirdparty:checked").val() == "fillfromthirdparty")
  313. {
  314. jQuery("#submitproduct").prop("disabled", true);
  315. jQuery("#submitthirdparty").removeAttr("disabled");
  316. jQuery("#search_productid").prop("disabled", true);
  317. jQuery("#socid").removeAttr("disabled");
  318. jQuery(".showforproductselector").hide();
  319. jQuery(".showforthirdpartyselector").show();
  320. }
  321. }
  322. init_selectors();
  323. jQuery(".radiobarcodeselect").click(function() {
  324. init_selectors();
  325. });
  326. function init_gendoc_button()
  327. {
  328. if (jQuery("#select_fk_barcode_type").val() > 0 && jQuery("#forbarcode").val())
  329. {
  330. jQuery("#submitformbarcodegen").removeAttr("disabled");
  331. }
  332. else
  333. {
  334. jQuery("#submitformbarcodegen").prop("disabled", true);
  335. }
  336. }
  337. init_gendoc_button();
  338. jQuery("#select_fk_barcode_type").change(function() {
  339. init_gendoc_button();
  340. });
  341. jQuery("#forbarcode").keyup(function() {
  342. init_gendoc_button()
  343. });
  344. });
  345. </script>';
  346. // Checkbox to select from free text
  347. print '<input id="fillmanually" type="radio" '.((!GETPOST("selectorforbarcode") || GETPOST("selectorforbarcode") == 'fillmanually') ? 'checked ' : '').'name="selectorforbarcode" value="fillmanually" class="radiobarcodeselect"><label for="fillmanually"> '.$langs->trans("FillBarCodeTypeAndValueManually").'</label>';
  348. print '<br>';
  349. if ($user->hasRight('produit', 'lire') || $user->hasRight('service', 'lire')) {
  350. print '<input id="fillfromproduct" type="radio" '.((GETPOST("selectorforbarcode") == 'fillfromproduct') ? 'checked ' : '').'name="selectorforbarcode" value="fillfromproduct" class="radiobarcodeselect"><label for="fillfromproduct"> '.$langs->trans("FillBarCodeTypeAndValueFromProduct").'</label>';
  351. print '<br>';
  352. print '<div class="showforproductselector">';
  353. $form->select_produits(GETPOST('productid', 'int'), 'productid', '', '', 0, -1, 2, '', 0, array(), 0, '1', 0, 'minwidth400imp', 1);
  354. print ' &nbsp; <input type="submit" class="button small" id="submitproduct" name="submitproduct" value="'.(dol_escape_htmltag($langs->trans("GetBarCode"))).'">';
  355. print '</div>';
  356. }
  357. if ($user->hasRight('societe', 'lire')) {
  358. print '<input id="fillfromthirdparty" type="radio" '.((GETPOST("selectorforbarcode") == 'fillfromthirdparty') ? 'checked ' : '').'name="selectorforbarcode" value="fillfromthirdparty" class="radiobarcodeselect"><label for="fillfromthirdparty"> '.$langs->trans("FillBarCodeTypeAndValueFromThirdParty").'</label>';
  359. print '<br>';
  360. print '<div class="showforthirdpartyselector">';
  361. print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300');
  362. print ' &nbsp; <input type="submit" id="submitthirdparty" name="submitthirdparty" class="button showforthirdpartyselector small" value="'.(dol_escape_htmltag($langs->trans("GetBarCode"))).'">';
  363. print '</div>';
  364. }
  365. print '<br>';
  366. if ($producttmp->id > 0) {
  367. print $langs->trans("BarCodeDataForProduct", '').' '.$producttmp->getNomUrl(1).'<br>';
  368. }
  369. if ($thirdpartytmp->id > 0) {
  370. print $langs->trans("BarCodeDataForThirdparty", '').' '.$thirdpartytmp->getNomUrl(1).'<br>';
  371. }
  372. print '<div class="tagtable">';
  373. // Barcode type
  374. print ' <div class="tagtr">';
  375. print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  376. print $langs->trans("BarcodeType").' &nbsp; ';
  377. print '</div><div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  378. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';
  379. $formbarcode = new FormBarCode($db);
  380. print $formbarcode->selectBarcodeType($fk_barcode_type, 'fk_barcode_type', 1);
  381. print '</div></div>';
  382. // Barcode value
  383. print ' <div class="tagtr">';
  384. print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  385. print $langs->trans("BarcodeValue").' &nbsp; ';
  386. print '</div><div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  387. print '<input size="16" type="text" name="forbarcode" id="forbarcode" value="'.$forbarcode.'">';
  388. print '</div></div>';
  389. /*
  390. $barcodestickersmask=GETPOST('barcodestickersmask');
  391. print '<br>'.$langs->trans("BarcodeStickersMask").':<br>';
  392. print '<textarea cols="40" type="text" name="barcodestickersmask" value="'.GETPOST('barcodestickersmask').'">'.$barcodestickersmask.'</textarea>';
  393. print '<br>';
  394. */
  395. print '</div>';
  396. print '<br><input type="submit" class="button" id="submitformbarcodegen" '.((GETPOST("selectorforbarcode") && GETPOST("selectorforbarcode")) ? '' : 'disabled ').'value="'.$langs->trans("BuildPageToPrint").'">';
  397. print '</form>';
  398. print '<br>';
  399. // End of page
  400. llxFooter();
  401. $db->close();