printsheet.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. // This generates and send PDF to output
  227. // TODO Move
  228. $result = doc_label_pdf_create($db, $arrayofrecords, $modellabel, $outputlangs, $diroutput, $template, dol_sanitizeFileName($outfile));
  229. }
  230. }
  231. if ($result <= 0 || $mesg || $error) {
  232. if (empty($mesg)) {
  233. $mesg = 'Error '.$result;
  234. }
  235. setEventMessages($mesg, null, 'errors');
  236. } else {
  237. $db->close();
  238. exit;
  239. }
  240. }
  241. }
  242. /*
  243. * View
  244. */
  245. $form = new Form($db);
  246. llxHeader('', $langs->trans("BarCodePrintsheet"));
  247. print load_fiche_titre($langs->trans("BarCodePrintsheet"), '', 'barcode');
  248. print '<br>';
  249. print '<span class="opacitymedium">'.$langs->trans("PageToGenerateBarCodeSheets", $langs->transnoentitiesnoconv("BuildPageToPrint")).'</span><br>';
  250. print '<br>';
  251. //print img_picto('','puce').' '.$langs->trans("PrintsheetForOneBarCode").'<br>';
  252. //print '<br>';
  253. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; // The target is for brothers that open the file instead of downloading it
  254. print '<input type="hidden" name="mode" value="label">';
  255. print '<input type="hidden" name="action" value="builddoc">';
  256. 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
  257. print '<div class="tagtable">';
  258. // Sheet format
  259. print ' <div class="tagtr">';
  260. print ' <div class="tagtd">';
  261. print $langs->trans("DescADHERENT_ETIQUETTE_TYPE").' &nbsp; ';
  262. print '</div><div class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;">';
  263. // List of possible labels (defined into $_Avery_Labels variable set into core/lib/format_cards.lib.php)
  264. $arrayoflabels = array();
  265. foreach (array_keys($_Avery_Labels) as $codecards) {
  266. $labeltoshow = $_Avery_Labels[$codecards]['name'];
  267. //$labeltoshow.=' ('.$_Avery_Labels[$row['code']]['paper-size'].')';
  268. $arrayoflabels[$codecards] = $labeltoshow;
  269. }
  270. asort($arrayoflabels);
  271. print $form->selectarray('modellabel', $arrayoflabels, (GETPOST('modellabel') ? GETPOST('modellabel') : getDolGlobalString('ADHERENT_ETIQUETTE_TYPE')), 1, 0, 0, '', 0, 0, 0, '', '', 1);
  272. print '</div></div>';
  273. // Number of stickers to print
  274. print ' <div class="tagtr">';
  275. print ' <div class="tagtd">';
  276. print $langs->trans("NumberOfStickers").' &nbsp; ';
  277. print '</div><div class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;">';
  278. print '<input size="4" type="text" name="numberofsticker" value="'.(GETPOST('numberofsticker') ? GETPOST('numberofsticker', 'int') : 10).'">';
  279. print '</div></div>';
  280. print '</div>';
  281. print '<br>';
  282. // Add javascript to make choice dynamic
  283. print '<script type="text/javascript">
  284. jQuery(document).ready(function() {
  285. function init_selectors()
  286. {
  287. if (jQuery("#fillmanually:checked").val() == "fillmanually")
  288. {
  289. jQuery("#submitproduct").prop("disabled", true);
  290. jQuery("#submitthirdparty").prop("disabled", true);
  291. jQuery("#search_productid").prop("disabled", true);
  292. jQuery("#socid").prop("disabled", true);
  293. jQuery(".showforproductselector").hide();
  294. jQuery(".showforthirdpartyselector").hide();
  295. }
  296. if (jQuery("#fillfromproduct:checked").val() == "fillfromproduct")
  297. {
  298. jQuery("#submitproduct").removeAttr("disabled");
  299. jQuery("#submitthirdparty").prop("disabled", true);
  300. jQuery("#search_productid").removeAttr("disabled");
  301. jQuery("#socid").prop("disabled", true);
  302. jQuery(".showforproductselector").show();
  303. jQuery(".showforthirdpartyselector").hide();
  304. }
  305. if (jQuery("#fillfromthirdparty:checked").val() == "fillfromthirdparty")
  306. {
  307. jQuery("#submitproduct").prop("disabled", true);
  308. jQuery("#submitthirdparty").removeAttr("disabled");
  309. jQuery("#search_productid").prop("disabled", true);
  310. jQuery("#socid").removeAttr("disabled");
  311. jQuery(".showforproductselector").hide();
  312. jQuery(".showforthirdpartyselector").show();
  313. }
  314. }
  315. init_selectors();
  316. jQuery(".radiobarcodeselect").click(function() {
  317. init_selectors();
  318. });
  319. function init_gendoc_button()
  320. {
  321. if (jQuery("#select_fk_barcode_type").val() > 0 && jQuery("#forbarcode").val())
  322. {
  323. jQuery("#submitformbarcodegen").removeAttr("disabled");
  324. }
  325. else
  326. {
  327. jQuery("#submitformbarcodegen").prop("disabled", true);
  328. }
  329. }
  330. init_gendoc_button();
  331. jQuery("#select_fk_barcode_type").change(function() {
  332. init_gendoc_button();
  333. });
  334. jQuery("#forbarcode").keyup(function() {
  335. init_gendoc_button()
  336. });
  337. });
  338. </script>';
  339. // Checkbox to select from free text
  340. 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>';
  341. print '<br>';
  342. if ($user->hasRight('produit', 'lire') || $user->hasRight('service', 'lire')) {
  343. print '<input id="fillfromproduct" type="radio" '.((GETPOST("selectorforbarcode") == 'fillfromproduct') ? 'checked ' : '').'name="selectorforbarcode" value="fillfromproduct" class="radiobarcodeselect"><label for="fillfromproduct"> '.$langs->trans("FillBarCodeTypeAndValueFromProduct").'</label>';
  344. print '<br>';
  345. print '<div class="showforproductselector">';
  346. $form->select_produits(GETPOST('productid', 'int'), 'productid', '', '', 0, -1, 2, '', 0, array(), 0, '1', 0, 'minwidth400imp', 1);
  347. print ' &nbsp; <input type="submit" class="button small" id="submitproduct" name="submitproduct" value="'.(dol_escape_htmltag($langs->trans("GetBarCode"))).'">';
  348. print '</div>';
  349. }
  350. if ($user->hasRight('societe', 'lire')) {
  351. print '<input id="fillfromthirdparty" type="radio" '.((GETPOST("selectorforbarcode") == 'fillfromthirdparty') ? 'checked ' : '').'name="selectorforbarcode" value="fillfromthirdparty" class="radiobarcodeselect"><label for="fillfromthirdparty"> '.$langs->trans("FillBarCodeTypeAndValueFromThirdParty").'</label>';
  352. print '<br>';
  353. print '<div class="showforthirdpartyselector">';
  354. print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300');
  355. print ' &nbsp; <input type="submit" id="submitthirdparty" name="submitthirdparty" class="button showforthirdpartyselector small" value="'.(dol_escape_htmltag($langs->trans("GetBarCode"))).'">';
  356. print '</div>';
  357. }
  358. print '<br>';
  359. if ($producttmp->id > 0) {
  360. print $langs->trans("BarCodeDataForProduct", '').' '.$producttmp->getNomUrl(1).'<br>';
  361. }
  362. if ($thirdpartytmp->id > 0) {
  363. print $langs->trans("BarCodeDataForThirdparty", '').' '.$thirdpartytmp->getNomUrl(1).'<br>';
  364. }
  365. print '<div class="tagtable">';
  366. // Barcode type
  367. print ' <div class="tagtr">';
  368. print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  369. print $langs->trans("BarcodeType").' &nbsp; ';
  370. print '</div><div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  371. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';
  372. $formbarcode = new FormBarCode($db);
  373. print $formbarcode->selectBarcodeType($fk_barcode_type, 'fk_barcode_type', 1);
  374. print '</div></div>';
  375. // Barcode value
  376. print ' <div class="tagtr">';
  377. print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  378. print $langs->trans("BarcodeValue").' &nbsp; ';
  379. print '</div><div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
  380. print '<input size="16" type="text" name="forbarcode" id="forbarcode" value="'.$forbarcode.'">';
  381. print '</div></div>';
  382. /*
  383. $barcodestickersmask=GETPOST('barcodestickersmask');
  384. print '<br>'.$langs->trans("BarcodeStickersMask").':<br>';
  385. print '<textarea cols="40" type="text" name="barcodestickersmask" value="'.GETPOST('barcodestickersmask').'">'.$barcodestickersmask.'</textarea>';
  386. print '<br>';
  387. */
  388. print '</div>';
  389. print '<br><input type="submit" class="button" id="submitformbarcodegen" '.((GETPOST("selectorforbarcode") && GETPOST("selectorforbarcode")) ? '' : 'disabled ').'value="'.$langs->trans("BuildPageToPrint").'">';
  390. print '</form>';
  391. print '<br>';
  392. // End of page
  393. llxFooter();
  394. $db->close();