dolibarr  9.0.0
printsheet.php
Go to the documentation of this file.
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 <http://www.gnu.org/licenses/>.
18  */
19 
25 require '../main.inc.php';
26 require_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/modules/printsheet/modules_labels.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php';
30 
31 // Load translation files required by the page
32 $langs->loadLangs(array('admin', 'members', 'errors'));
33 
34 // Choice of print year or current year.
35 $now = dol_now();
36 $year=dol_print_date($now,'%Y');
37 $month=dol_print_date($now,'%m');
38 $day=dol_print_date($now,'%d');
39 $forbarcode=GETPOST('forbarcode');
40 $fk_barcode_type=GETPOST('fk_barcode_type');
41 $mode=GETPOST('mode');
42 $modellabel=GETPOST("modellabel"); // Doc template to use
43 $numberofsticker=GETPOST('numberofsticker','int');
44 
45 $mesg='';
46 
47 $action=GETPOST('action','aZ09');
48 
49 $producttmp=new Product($db);
50 $thirdpartytmp=new Societe($db);
51 
52 
53 /*
54  * Actions
55  */
56 
57 if (GETPOST('submitproduct') && GETPOST('submitproduct'))
58 {
59  $action=''; // We reset because we don't want to build doc
60  if (GETPOST('productid') > 0)
61  {
62  $producttmp->fetch(GETPOST('productid'));
63  $forbarcode=$producttmp->barcode;
64  $fk_barcode_type=$producttmp->barcode_type;
65 
66  if (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
67 
68  if (empty($forbarcode) || empty($fk_barcode_type))
69  {
70  setEventMessages($langs->trans("DefinitionOfBarCodeForProductNotComplete",$producttmp->getNomUrl()), null, 'warnings');
71  }
72  }
73 }
74 if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty'))
75 {
76  $action=''; // We reset because we don't want to build doc
77  if (GETPOST('socid') > 0)
78  {
79  $thirdpartytmp->fetch(GETPOST('socid'));
80  $forbarcode=$thirdpartytmp->barcode;
81  $fk_barcode_type=$thirdpartytmp->barcode_type_code;
82 
83  if (empty($fk_barcode_type) && ! empty($conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY)) $fk_barcode_type = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
84 
85  if (empty($forbarcode) || empty($fk_barcode_type))
86  {
87  setEventMessages($langs->trans("DefinitionOfBarCodeForThirdpartyNotComplete",$thirdpartytmp->getNomUrl()), null, 'warnings');
88  }
89  }
90 }
91 
92 if ($action == 'builddoc')
93 {
94  $result=0; $error=0;
95 
96  if (empty($forbarcode)) // barcode value
97  {
98  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BarcodeValue")), null, 'errors');
99  $error++;
100  }
101  if (empty($fk_barcode_type)) // barcode type = barcode encoding
102  {
103  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BarcodeType")), null, 'errors');
104  $error++;
105  }
106 
107  if (! $error)
108  {
109  // Get encoder (barcode_type_coder) from barcode type id (barcode_type)
110  $stdobject=new GenericObject($db);
111  $stdobject->barcode_type=$fk_barcode_type;
112  $result=$stdobject->fetch_barcode();
113  if ($result <= 0)
114  {
115  $error++;
116  setEventMessages('Failed to get bar code type information '.$stdobject->error, $stdobject->errors, 'errors');
117  }
118  }
119 
120  if (! $error)
121  {
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 
126  $diroutput=$conf->barcode->dir_temp;
127  dol_mkdir($diroutput);
128 
129  // Generate barcode
130  $dirbarcode=array_merge(array("/core/modules/barcode/doc/"),$conf->modules_parts['barcode']);
131 
132  foreach($dirbarcode as $reldir)
133  {
134  $dir=dol_buildpath($reldir,0);
135  $newdir=dol_osencode($dir);
136 
137  // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php)
138  if (! is_dir($newdir)) continue;
139 
140  $result=@include_once $newdir.$generator.'.modules.php';
141  if ($result) break;
142  }
143 
144  // Load barcode class for generating barcode image
145  $classname = "mod".ucfirst($generator);
146  $module = new $classname($db);
147  if ($generator != 'tcpdfbarcode')
148  {
149  // May be phpbarcode
150  $template = 'standardlabel';
151  $is2d = false;
152  if ($module->encodingIsSupported($encoding))
153  {
154  $barcodeimage=$conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png';
155  dol_delete_file($barcodeimage);
156  // File is created with full name $barcodeimage = $conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png';
157  $result=$module->writeBarCode($code,$encoding,'Y',4,1);
158  if ($result <= 0 || ! dol_is_file($barcodeimage))
159  {
160  $error++;
161  setEventMessages('Failed to generate image file of barcode for code='.$code.' encoding='.$encoding.' file='.basename($barcodeimage), null, 'errors');
162  setEventMessages($module->error, null, 'errors');
163  }
164  }
165  else
166  {
167  $error++;
168  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');
169  }
170  } else {
171  $template = 'tcpdflabel';
172  $encoding = $module->getTcpdfEncodingType($encoding); //convert to TCPDF compatible encoding types
173  $is2d = $module->is2d;
174  }
175  }
176 
177  if (! $error)
178  {
179  // List of values to scan for a replacement
180  $substitutionarray = array (
181  '%LOGIN%' => $user->login,
182  '%COMPANY%' => $mysoc->name,
183  '%ADDRESS%' => $mysoc->address,
184  '%ZIP%' => $mysoc->zip,
185  '%TOWN%' => $mysoc->town,
186  '%COUNTRY%' => $mysoc->country,
187  '%COUNTRY_CODE%' => $mysoc->country_code,
188  '%EMAIL%' => $mysoc->email,
189  '%YEAR%' => $year,
190  '%MONTH%' => $month,
191  '%DAY%' => $day,
192  '%DOL_MAIN_URL_ROOT%' => DOL_MAIN_URL_ROOT,
193  '%SERVER%' => "http://".$_SERVER["SERVER_NAME"]."/",
194  );
195  complete_substitutions_array($substitutionarray, $langs);
196 
197  // For labels
198  if ($mode == 'label')
199  {
200 
201  $txtforsticker="%PHOTO%"; // Photo will be barcode image, %BARCODE% posible when using TCPDF generator
202  $textleft=make_substitutions((empty($conf->global->BARCODE_LABEL_LEFT_TEXT)?$txtforsticker:$conf->global->BARCODE_LABEL_LEFT_TEXT), $substitutionarray);
203  $textheader=make_substitutions((empty($conf->global->BARCODE_LABEL_HEADER_TEXT)?'':$conf->global->BARCODE_LABEL_HEADER_TEXT), $substitutionarray);
204  $textfooter=make_substitutions((empty($conf->global->BARCODE_LABEL_FOOTER_TEXT)?'':$conf->global->BARCODE_LABEL_FOOTER_TEXT), $substitutionarray);
205  $textright=make_substitutions((empty($conf->global->BARCODE_LABEL_RIGHT_TEXT)?'':$conf->global->BARCODE_LABEL_RIGHT_TEXT), $substitutionarray);
206  $forceimgscalewidth=(empty($conf->global->BARCODE_FORCEIMGSCALEWIDTH)?1:$conf->global->BARCODE_FORCEIMGSCALEWIDTH);
207  $forceimgscaleheight=(empty($conf->global->BARCODE_FORCEIMGSCALEHEIGHT)?1:$conf->global->BARCODE_FORCEIMGSCALEHEIGHT);
208 
209  for ($i=0; $i < $numberofsticker; $i++)
210  {
211  $arrayofrecords[]=array(
212  'textleft'=>$textleft,
213  'textheader'=>$textheader,
214  'textfooter'=>$textfooter,
215  'textright'=>$textright,
216  'code'=>$code,
217  'encoding'=>$encoding,
218  'is2d'=>$is2d,
219  'photo'=>$barcodeimage // Photo must be a file that exists with format supported by TCPDF
220  );
221  }
222  }
223 
224  $i++;
225  $mesg='';
226 
227  // Build and output PDF
228  if ($mode == 'label')
229  {
230  if (! count($arrayofrecords))
231  {
232  $mesg=$langs->trans("ErrorRecordNotFound");
233  }
234  if (empty($modellabel) || $modellabel == '-1')
235  {
236  $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE"));
237  }
238 
239  $outfile = $langs->trans("BarCode").'_sheets_'.dol_print_date(dol_now(),'dayhourlog').'.pdf';
240 
241  if (! $mesg) $result=doc_label_pdf_create($db, $arrayofrecords, $modellabel, $outputlangs, $diroutput, $template, dol_sanitizeFileName($outfile));
242  }
243 
244  if ($result <= 0)
245  {
246  dol_print_error('',$result);
247  }
248 
249  if (! $mesg)
250  {
251  $db->close();
252  exit;
253  }
254  }
255 }
256 
257 
258 /*
259  * View
260  */
261 
262 if (empty($conf->barcode->enabled)) accessforbidden();
263 
264 $form=new Form($db);
265 
266 llxHeader('',$langs->trans("BarCodePrintsheet"));
267 
268 print load_fiche_titre($langs->trans("BarCodePrintsheet"));
269 print '<br>';
270 
271 print $langs->trans("PageToGenerateBarCodeSheets",$langs->transnoentitiesnoconv("BuildPageToPrint")).'<br>';
272 print '<br>';
273 
274 dol_htmloutput_errors($mesg);
275 
276 //print img_picto('','puce').' '.$langs->trans("PrintsheetForOneBarCode").'<br>';
277 //print '<br>';
278 
279 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
280 print '<input type="hidden" name="mode" value="label">';
281 print '<input type="hidden" name="action" value="builddoc">';
282 
283 print '<div class="tagtable">';
284 
285 // Sheet format
286 print ' <div class="tagtr">';
287 print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
288 print $langs->trans("DescADHERENT_ETIQUETTE_TYPE").' &nbsp; ';
289 print '</div><div class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;">';
290 // List of possible labels (defined into $_Avery_Labels variable set into core/lib/format_cards.lib.php)
291 $arrayoflabels=array();
292 foreach(array_keys($_Avery_Labels) as $codecards)
293 {
294  $labeltoshow=$_Avery_Labels[$codecards]['name'];
295  //$labeltoshow.=' ('.$_Avery_Labels[$row['code']]['paper-size'].')';
296  $arrayoflabels[$codecards]=$labeltoshow;
297 }
298 asort($arrayoflabels);
299 print $form->selectarray('modellabel', $arrayoflabels, (GETPOST('modellabel')?GETPOST('modellabel'):$conf->global->ADHERENT_ETIQUETTE_TYPE), 1, 0, 0, '', 0, 0, 0, '', '', 1);
300 print '</div></div>';
301 
302 // Number of stickers to print
303 print ' <div class="tagtr">';
304 print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
305 print $langs->trans("NumberOfStickers").' &nbsp; ';
306 print '</div><div class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;">';
307 print '<input size="4" type="text" name="numberofsticker" value="'.(GETPOST('numberofsticker')?GETPOST('numberofsticker','int'):10).'">';
308 print '</div></div>';
309 
310 print '</div>';
311 
312 
313 print '<br>';
314 
315 
316 // Add javascript to make choice dynamic
317 print '<script type="text/javascript" language="javascript">
318 jQuery(document).ready(function() {
319  function init_selectors()
320  {
321  if (jQuery("#fillmanually:checked").val() == "fillmanually")
322  {
323  jQuery("#submitproduct").prop("disabled", true);
324  jQuery("#submitthirdparty").prop("disabled", true);
325  jQuery("#search_productid").prop("disabled", true);
326  jQuery("#socid").prop("disabled", true);
327  jQuery(".showforproductselector").hide();
328  jQuery(".showforthirdpartyselector").hide();
329  }
330  if (jQuery("#fillfromproduct:checked").val() == "fillfromproduct")
331  {
332  jQuery("#submitproduct").removeAttr("disabled");
333  jQuery("#submitthirdparty").prop("disabled", true);
334  jQuery("#search_productid").removeAttr("disabled");
335  jQuery("#socid").prop("disabled", true);
336  jQuery(".showforproductselector").show();
337  jQuery(".showforthirdpartyselector").hide();
338  }
339  if (jQuery("#fillfromthirdparty:checked").val() == "fillfromthirdparty")
340  {
341  jQuery("#submitproduct").prop("disabled", true);
342  jQuery("#submitthirdparty").removeAttr("disabled");
343  jQuery("#search_productid").prop("disabled", true);
344  jQuery("#socid").removeAttr("disabled");
345  jQuery(".showforproductselector").hide();
346  jQuery(".showforthirdpartyselector").show();
347  }
348  }
349  init_selectors();
350  jQuery(".radiobarcodeselect").click(function() {
351  init_selectors();
352  });
353 
354  function init_gendoc_button()
355  {
356  if (jQuery("#select_fk_barcode_type").val() > 0 && jQuery("#forbarcode").val())
357  {
358  jQuery("#submitformbarcodegen").removeAttr("disabled");
359  }
360  else
361  {
362  jQuery("#submitformbarcodegen").prop("disabled", true);
363  }
364  }
365  init_gendoc_button();
366  jQuery("#select_fk_barcode_type").change(function() {
367  init_gendoc_button();
368  });
369  jQuery("#forbarcode").keyup(function() {
370  init_gendoc_button()
371  });
372 });
373 </script>';
374 
375 // Checkbox to select from free text
376 print '<input id="fillmanually" type="radio" '.((! GETPOST("selectorforbarcode") || GETPOST("selectorforbarcode")=='fillmanually')?'checked ':'').'name="selectorforbarcode" value="fillmanually" class="radiobarcodeselect"> '.$langs->trans("FillBarCodeTypeAndValueManually").' &nbsp; ';
377 print '<br>';
378 
379 if (! empty($user->rights->produit->lire) || ! empty($user->rights->service->lire))
380 {
381  print '<input id="fillfromproduct" type="radio" '.((GETPOST("selectorforbarcode")=='fillfromproduct')?'checked ':'').'name="selectorforbarcode" value="fillfromproduct" class="radiobarcodeselect"> '.$langs->trans("FillBarCodeTypeAndValueFromProduct").' &nbsp; ';
382  print '<br>';
383  print '<div class="showforproductselector">';
384  $form->select_produits(GETPOST('productid'), 'productid', '');
385  print ' &nbsp; <input type="submit" id="submitproduct" name="submitproduct" class="button" value="'.(dol_escape_htmltag($langs->trans("GetBarCode"))).'">';
386  print '</div>';
387 }
388 
389 if (! empty($user->rights->societe->lire))
390 {
391  print '<input id="fillfromthirdparty" type="radio" '.((GETPOST("selectorforbarcode")=='fillfromthirdparty')?'checked ':'').'name="selectorforbarcode" value="fillfromthirdparty" class="radiobarcodeselect"> '.$langs->trans("FillBarCodeTypeAndValueFromThirdParty").' &nbsp; ';
392  print '<br>';
393  print '<div class="showforthirdpartyselector">';
394  print $form->select_company(GETPOST('socid'), 'socid', '', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300');
395  print ' &nbsp; <input type="submit" id="submitthirdparty" name="submitthirdparty" class="button showforthirdpartyselector" value="'.(dol_escape_htmltag($langs->trans("GetBarCode"))).'">';
396  print '</div>';
397 }
398 
399 print '<br>';
400 
401 if ($producttmp->id > 0)
402 {
403  print $langs->trans("BarCodeDataForProduct",'').' '.$producttmp->getNomUrl(1).'<br>';
404 }
405 if ($thirdpartytmp->id > 0)
406 {
407  print $langs->trans("BarCodeDataForThirdparty",'').' '.$thirdpartytmp->getNomUrl(1).'<br>';
408 }
409 
410 print '<div class="tagtable">';
411 
412 // Barcode type
413 print ' <div class="tagtr">';
414 print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
415 print $langs->trans("BarcodeType").' &nbsp; ';
416 print '</div><div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
417 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';
418 $formbarcode = new FormBarCode($db);
419 print $formbarcode->selectBarcodeType($fk_barcode_type, 'fk_barcode_type', 1);
420 print '</div></div>';
421 
422 // Barcode value
423 print ' <div class="tagtr">';
424 print ' <div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
425 print $langs->trans("BarcodeValue").' &nbsp; ';
426 print '</div><div class="tagtd" style="overflow: hidden; white-space: nowrap; max-width: 300px;">';
427 print '<input size="16" type="text" name="forbarcode" id="forbarcode" value="'.$forbarcode.'">';
428 print '</div></div>';
429 
430 /*
431 $barcodestickersmask=GETPOST('barcodestickersmask');
432 print '<br>'.$langs->trans("BarcodeStickersMask").':<br>';
433 print '<textarea cols="40" type="text" name="barcodestickersmask" value="'.GETPOST('barcodestickersmask').'">'.$barcodestickersmask.'</textarea>';
434 print '<br>';
435 */
436 
437 print '</div>';
438 
439 print '<br><input class="button" type="submit" id="submitformbarcodegen" '.((GETPOST("selectorforbarcode") && GETPOST("selectorforbarcode"))?'':'disabled ').'value="'.$langs->trans("BuildPageToPrint").'">';
440 
441 print '</form>';
442 print '<br>';
443 
444 // End of page
445 llxFooter();
446 $db->close();
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
llxFooter()
Empty footer.
Definition: wrapper.php:56
load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
GETPOST($paramname, $check='none', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
print
Draft customers invoices.
Definition: index.php:91
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
dol_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
Print formated error messages to output (Used to show messages on html output).
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
doc_label_pdf_create($db, $arrayofrecords, $modele, $outputlangs, $outputdir='', $template='standardlabel', $filename='tmp_address_sheet.pdf')
Create a document onto disk according to template module.
Class to manage products or services.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Class to manage generation of HTML components Only common components must be here.
Class to manage third parties objects (customers, suppliers, prospects...)
llxHeader()
Empty header.
Definition: wrapper.php:44
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
Definition: files.lib.php:1139
Class to manage barcode HTML.
dol_now($mode='gmt')
Return date for now.
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:451
dol_print_date($time, $format='', $tzoutput='tzserver', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Class of a generic business object.
dol_mkdir($dir, $dataroot='', $newmask=null)
Creation of a directory (this can create recursive subdir)
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...