dolibarr  17.0.4
commondocgenerator.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2003-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2010 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
6  * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
7  * Copyright (C) 2016 Charlie Benke <charlie@patas-monkey.com>
8  * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
9  * Copyright (C) 2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <https://www.gnu.org/licenses/>.
23  * or see https://www.gnu.org/
24  */
25 
36 abstract class CommonDocGenerator
37 {
41  public $name = '';
42 
46  public $error = '';
47 
51  public $errors = array();
52 
56  protected $db;
57 
61  public $extrafieldsCache;
62 
66  public $update_main_doc_field;
67 
71  public $scandir;
72 
73  public $page_hauteur;
74  public $page_largeur;
75  public $marge_gauche;
76  public $marge_droite;
77  public $marge_haute;
78  public $marge_basse;
79 
80  public $option_logo;
81  public $option_tva;
82  public $option_multilang;
83  public $option_freetext;
84  public $option_draft_watermark;
85 
86  public $option_modereg;
87  public $option_condreg;
88  public $option_escompte;
89  public $option_credit_note;
90 
91  public $emetteur;
92 
93 
99  public function __construct($db)
100  {
101  $this->db = $db;
102  }
103 
104 
105  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
113  public function get_substitutionarray_user($user, $outputlangs)
114  {
115  // phpcs:enable
116  global $conf, $extrafields;
117 
118  $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
119 
120  $array_user = array(
121  'myuser_lastname'=>$user->lastname,
122  'myuser_firstname'=>$user->firstname,
123  'myuser_fullname'=>$user->getFullName($outputlangs, 1),
124  'myuser_login'=>$user->login,
125  'myuser_phone'=>$user->office_phone,
126  'myuser_address'=>$user->address,
127  'myuser_zip'=>$user->zip,
128  'myuser_town'=>$user->town,
129  'myuser_country'=>$user->country,
130  'myuser_country_code'=>$user->country_code,
131  'myuser_state'=>$user->state,
132  'myuser_state_code'=>$user->state_code,
133  'myuser_fax'=>$user->office_fax,
134  'myuser_mobile'=>$user->user_mobile,
135  'myuser_email'=>$user->email,
136  'myuser_logo'=>$logotouse,
137  'myuser_job'=>$user->job,
138  'myuser_web'=>'' // url not exist in $user object
139  );
140  // Retrieve extrafields
141  if (is_array($user->array_options) && count($user->array_options)) {
142  $array_user = $this->fill_substitutionarray_with_extrafields($user, $array_user, $extrafields, 'myuser', $outputlangs);
143  }
144  return $array_user;
145  }
146 
147 
155  public function getSubstitutionarrayMember($member, $outputlangs)
156  {
157  global $conf, $extrafields;
158 
159  if ($member->photo) {
160  $logotouse = $conf->adherent->dir_output.'/'.get_exdir(0, 0, 0, 1, $member, 'user').'/photos/'.$member->photo;
161  } else {
162  $logotouse = DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.png';
163  }
164 
165  $array_member = array(
166  'mymember_lastname' => $member->lastname,
167  'mymember_firstname' => $member->firstname,
168  'mymember_fullname' => $member->getFullName($outputlangs, 1),
169  'mymember_login' => $member->login,
170  'mymember_address' => $member->address,
171  'mymember_zip' => $member->zip,
172  'mymember_town' => $member->town,
173  'mymember_country_code' => $member->country_code,
174  'mymember_country' => $member->country,
175  'mymember_state_code' => $member->state_code,
176  'mymember_state' => $member->state,
177  'mymember_phone_perso' => $member->phone_perso,
178  'mymember_phone_pro' => $member->phone,
179  'mymember_phone_mobile' => $member->phone_mobile,
180  'mymember_email' => $member->email,
181  'mymember_logo' => $logotouse,
182  'mymember_gender' => $member->gender,
183  'mymember_birth_locale' => dol_print_date($member->birth, 'day', 'tzuser', $outputlangs),
184  'mymember_birth' => dol_print_date($member->birth, 'day', 'tzuser'),
185  );
186  // Retrieve extrafields
187  if (is_array($member->array_options) && count($member->array_options)) {
188  $array_member = $this->fill_substitutionarray_with_extrafields($member, $array_member, $extrafields, 'mymember', $outputlangs);
189  }
190  return $array_member;
191  }
192 
193 
194  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
202  public function get_substitutionarray_mysoc($mysoc, $outputlangs)
203  {
204  // phpcs:enable
205  global $conf;
206 
207  if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) {
208  $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code);
209  }
210  if (empty($mysoc->country) && !empty($mysoc->country_code)) {
211  $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
212  }
213  if (empty($mysoc->state) && !empty($mysoc->state_code)) {
214  $mysoc->state = getState($mysoc->state_code, 0);
215  }
216 
217  $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
218 
219  return array(
220  'mycompany_logo'=>$logotouse,
221  'mycompany_name'=>$mysoc->name,
222  'mycompany_email'=>$mysoc->email,
223  'mycompany_phone'=>$mysoc->phone,
224  'mycompany_fax'=>$mysoc->fax,
225  'mycompany_address'=>$mysoc->address,
226  'mycompany_zip'=>$mysoc->zip,
227  'mycompany_town'=>$mysoc->town,
228  'mycompany_country'=>$mysoc->country,
229  'mycompany_country_code'=>$mysoc->country_code,
230  'mycompany_state'=>$mysoc->state,
231  'mycompany_state_code'=>$mysoc->state_code,
232  'mycompany_web'=>$mysoc->url,
233  'mycompany_juridicalstatus'=>$mysoc->forme_juridique,
234  'mycompany_managers'=>$mysoc->managers,
235  'mycompany_capital'=>$mysoc->capital,
236  'mycompany_barcode'=>$mysoc->barcode,
237  'mycompany_idprof1'=>$mysoc->idprof1,
238  'mycompany_idprof2'=>$mysoc->idprof2,
239  'mycompany_idprof3'=>$mysoc->idprof3,
240  'mycompany_idprof4'=>$mysoc->idprof4,
241  'mycompany_idprof5'=>$mysoc->idprof5,
242  'mycompany_idprof6'=>$mysoc->idprof6,
243  'mycompany_vatnumber'=>$mysoc->tva_intra,
244  'mycompany_object'=>$mysoc->object,
245  'mycompany_note_private'=>$mysoc->note_private,
246  //'mycompany_note_public'=>$mysoc->note_public, // Only private not exists for "mysoc" but both for thirdparties
247  );
248  }
249 
250 
251  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
261  public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company')
262  {
263  // phpcs:enable
264  global $conf, $extrafields;
265 
266  if (empty($object->country) && !empty($object->country_code)) {
267  $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
268  }
269  if (empty($object->state) && !empty($object->state_code)) {
270  $object->state = getState($object->state_code, 0);
271  }
272 
273  $array_thirdparty = array(
274  'company_name'=>$object->name,
275  'company_name_alias' => $object->name_alias,
276  'company_email'=>$object->email,
277  'company_phone'=>$object->phone,
278  'company_fax'=>$object->fax,
279  'company_address'=>$object->address,
280  'company_zip'=>$object->zip,
281  'company_town'=>$object->town,
282  'company_country'=>$object->country,
283  'company_country_code'=>$object->country_code,
284  'company_state'=>$object->state,
285  'company_state_code'=>$object->state_code,
286  'company_web'=>$object->url,
287  'company_barcode'=>$object->barcode,
288  'company_vatnumber'=>$object->tva_intra,
289  'company_customercode'=>$object->code_client,
290  'company_suppliercode'=>$object->code_fournisseur,
291  'company_customeraccountancycode'=>$object->code_compta,
292  'company_supplieraccountancycode'=>$object->code_compta_fournisseur,
293  'company_juridicalstatus'=>$object->forme_juridique,
294  'company_outstanding_limit'=>$object->outstanding_limit,
295  'company_capital'=>$object->capital,
296  'company_idprof1'=>$object->idprof1,
297  'company_idprof2'=>$object->idprof2,
298  'company_idprof3'=>$object->idprof3,
299  'company_idprof4'=>$object->idprof4,
300  'company_idprof5'=>$object->idprof5,
301  'company_idprof6'=>$object->idprof6,
302  'company_note_public'=>$object->note_public,
303  'company_note_private'=>$object->note_private,
304  'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''),
305  'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '')
306  );
307 
308  // Retrieve extrafields
309  if (is_array($object->array_options) && count($object->array_options)) {
310  $object->fetch_optionals();
311 
312  $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs);
313  }
314  return $array_thirdparty;
315  }
316 
317  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
326  public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object')
327  {
328  // phpcs:enable
329  global $conf, $extrafields;
330 
331  if (empty($object->country) && !empty($object->country_code)) {
332  $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
333  }
334  if (empty($object->state) && !empty($object->state_code)) {
335  $object->state = getState($object->state_code, 0);
336  }
337 
338  $array_contact = array(
339  $array_key.'_fullname' => $object->getFullName($outputlangs, 1),
340  $array_key.'_lastname' => $object->lastname,
341  $array_key.'_firstname' => $object->firstname,
342  $array_key.'_address' => $object->address,
343  $array_key.'_zip' => $object->zip,
344  $array_key.'_town' => $object->town,
345  $array_key.'_state_id' => $object->state_id,
346  $array_key.'_state_code' => $object->state_code,
347  $array_key.'_state' => $object->state,
348  $array_key.'_country_id' => $object->country_id,
349  $array_key.'_country_code' => $object->country_code,
350  $array_key.'_country' => $object->country,
351  $array_key.'_poste' => $object->poste,
352  $array_key.'_socid' => $object->socid,
353  $array_key.'_statut' => $object->statut,
354  $array_key.'_code' => $object->code,
355  $array_key.'_email' => $object->email,
356  $array_key.'_phone_pro' => $object->phone_pro,
357  $array_key.'_phone_perso' => $object->phone_perso,
358  $array_key.'_phone_mobile' => $object->phone_mobile,
359  $array_key.'_fax' => $object->fax,
360  $array_key.'_birthday' => $object->birthday,
361  $array_key.'_default_lang' => $object->default_lang,
362  $array_key.'_note_public' => $object->note_public,
363  $array_key.'_note_private' => $object->note_private,
364  $array_key.'_civility' => $object->civility,
365  );
366 
367  // Retrieve extrafields
368  if (is_array($object->array_options) && count($object->array_options)) {
369  $object->fetch_optionals();
370 
371  $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs);
372  }
373  return $array_contact;
374  }
375 
376 
377  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
384  public function get_substitutionarray_other($outputlangs)
385  {
386  // phpcs:enable
387  global $conf;
388 
389  $now = dol_now('gmt'); // gmt
390  $array_other = array(
391  // Date in default language
392  'current_date'=>dol_print_date($now, 'day', 'tzuser'),
393  'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'),
394  'current_server_date'=>dol_print_date($now, 'day', 'tzserver'),
395  'current_server_datehour'=>dol_print_date($now, 'dayhour', 'tzserver'),
396  // Date in requested output language
397  'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs),
398  'current_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzuser', $outputlangs),
399  'current_server_date_locale'=>dol_print_date($now, 'day', 'tzserver', $outputlangs),
400  'current_server_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzserver', $outputlangs),
401  );
402 
403 
404  foreach ($conf->global as $key => $val) {
405  if (isASecretKey($key)) {
406  $newval = '*****forbidden*****';
407  } else {
408  $newval = $val;
409  }
410  $array_other['__['.$key.']__'] = $newval;
411  }
412 
413  return $array_other;
414  }
415 
416 
417  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
426  public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
427  {
428  // phpcs:enable
429  global $conf, $extrafields;
430 
431  $sumpayed = $sumdeposit = $sumcreditnote = '';
432  $already_payed_all = 0;
433 
434  if ($object->element == 'facture') {
435  $invoice_source = new Facture($this->db);
436  if ($object->fk_facture_source > 0) {
437  $invoice_source->fetch($object->fk_facture_source);
438  }
439  $sumpayed = $object->getSommePaiement();
440  $sumdeposit = $object->getSumDepositsUsed();
441  $sumcreditnote = $object->getSumCreditNotesUsed();
442  $already_payed_all = $sumpayed + $sumdeposit + $sumcreditnote;
443 
444  if ($object->fk_account > 0) {
445  require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
446  $bank_account = new Account($this->db);
447  $bank_account->fetch($object->fk_account);
448  }
449  }
450 
451  $date = (isset($object->element) && $object->element == 'contrat' && isset($object->date_contrat)) ? $object->date_contrat : (isset($object->date) ? $object->date : null);
452 
453  $resarray = array(
454  $array_key.'_id'=>$object->id,
455  $array_key.'_ref' => (property_exists($object, 'ref') ? $object->ref : ''),
456  $array_key.'_label' => (property_exists($object, 'label') ? $object->label : ''),
457  $array_key.'_ref_ext' => (property_exists($object, 'ref_ext') ? $object->ref_ext : ''),
458  $array_key.'_ref_customer'=>(!empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
459  $array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
460  $array_key.'_source_invoice_ref'=>((empty($invoice_source) || empty($invoice_source->ref)) ? '' : $invoice_source->ref),
461  // Dates
462  $array_key.'_hour'=>dol_print_date($date, 'hour'),
463  $array_key.'_date'=>dol_print_date($date, 'day'),
464  $array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'),
465  $array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''),
466  $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''),
467  $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
468  $array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''),
469  $array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''),
470  $array_key.'_date_delivery_planed'=>(!empty($object->date_livraison) ?dol_print_date($object->date_livraison, 'day') : ''),
471  $array_key.'_date_close'=>(!empty($object->date_cloture) ?dol_print_date($object->date_cloture, 'dayhour') : ''),
472 
473  $array_key.'_payment_mode_code'=>$object->mode_reglement_code,
474  $array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) != 'PaymentType'.$object->mode_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) : $object->mode_reglement),
475  $array_key.'_payment_term_code'=>$object->cond_reglement_code,
476  $array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)),
477 
478  $array_key.'_incoterms' => (method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''),
479 
480  $array_key.'_bank_iban'=>$bank_account->iban,
481  $array_key.'_bank_bic'=>$bank_account->bic,
482  $array_key.'_bank_label'=>$bank_account->label,
483  $array_key.'_bank_number'=>$bank_account->number,
484  $array_key.'_bank_proprio'=>$bank_account->proprio,
485 
486  $array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs),
487  $array_key.'_total_vat_locale'=>(!empty($object->total_vat) ?price($object->total_vat, 0, $outputlangs) : price($object->total_tva, 0, $outputlangs)),
488  $array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs),
489  $array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs),
490  $array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs),
491 
492  $array_key.'_total_ht'=>price2num($object->total_ht),
493  $array_key.'_total_vat'=>(!empty($object->total_vat) ?price2num($object->total_vat) : price2num($object->total_tva)),
494  $array_key.'_total_localtax1'=>price2num($object->total_localtax1),
495  $array_key.'_total_localtax2'=>price2num($object->total_localtax2),
496  $array_key.'_total_ttc'=>price2num($object->total_ttc),
497 
498  $array_key.'_multicurrency_code' => $object->multicurrency_code,
499  $array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx),
500  $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht),
501  $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva),
502  $array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc),
503  $array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs),
504  $array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs),
505  $array_key.'_multicurrency_total_ttc_locale' => price($object->multicurrency_total_ttc, 0, $outputlangs),
506 
507  $array_key.'_note_private'=>$object->note,
508  $array_key.'_note_public'=>$object->note_public,
509  $array_key.'_note'=>$object->note_public, // For backward compatibility
510 
511  // Payments
512  $array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs),
513  $array_key.'_already_payed'=>price2num($sumpayed),
514  $array_key.'_already_deposit_locale'=>price($sumdeposit, 0, $outputlangs),
515  $array_key.'_already_deposit'=>price2num($sumdeposit),
516  $array_key.'_already_creditnote_locale'=>price($sumcreditnote, 0, $outputlangs),
517  $array_key.'_already_creditnote'=>price2num($sumcreditnote),
518 
519  $array_key.'_already_payed_all_locale'=>price(price2num($already_payed_all, 'MT'), 0, $outputlangs),
520  $array_key.'_already_payed_all'=> price2num($already_payed_all, 'MT'),
521 
522  // Remain to pay with all known information (except open direct debit requests)
523  $array_key.'_remain_to_pay_locale'=>price(price2num($object->total_ttc - $already_payed_all, 'MT'), 0, $outputlangs),
524  $array_key.'_remain_to_pay'=>price2num($object->total_ttc - $already_payed_all, 'MT')
525  );
526 
527  if (method_exists($object, 'getTotalDiscount') && in_array(get_class($object), array('Propal', 'Proposal', 'Commande', 'Facture', 'SupplierProposal', 'CommandeFournisseur', 'FactureFournisseur'))) {
528  $resarray[$array_key.'_total_discount_ht_locale'] = price($object->getTotalDiscount(), 0, $outputlangs);
529  $resarray[$array_key.'_total_discount_ht'] = price2num($object->getTotalDiscount());
530  } else {
531  $resarray[$array_key.'_total_discount_ht_locale'] = '';
532  $resarray[$array_key.'_total_discount_ht'] = '';
533  }
534 
535  // Fetch project information if there is a project assigned to this object
536  if ($object->element != "project" && !empty($object->fk_project) && $object->fk_project > 0) {
537  if (!is_object($object->project)) {
538  $object->fetch_projet();
539  }
540 
541  $resarray[$array_key.'_project_ref'] = $object->project->ref;
542  $resarray[$array_key.'_project_title'] = $object->project->title;
543  $resarray[$array_key.'_project_description'] = $object->project->description;
544  $resarray[$array_key.'_project_date_start'] = dol_print_date($object->project->date_start, 'day');
545  $resarray[$array_key.'_project_date_end'] = dol_print_date($object->project->date_end, 'day');
546  }
547 
548  // Add vat by rates
549  if (is_array($object->lines) && count($object->lines) > 0) {
550  $totalUp = 0;
551  // Set substitution keys for different VAT rates
552  foreach ($object->lines as $line) {
553  // $line->tva_tx format depends on database field accuracy, no reliable. This is kept for backward compatibility
554  if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) {
555  $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0;
556  }
557  $resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
558  $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
559  // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
560  $vatformated = vatrate($line->tva_tx);
561  if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) {
562  $resarray[$array_key.'_total_vat_'.$vatformated] = 0;
563  }
564  $resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva;
565  $resarray[$array_key.'_total_vat_locale_'.$vatformated] = price($resarray[$array_key.'_total_vat_'.$vatformated]);
566 
567  $totalUp += $line->subprice * $line->qty;
568  }
569 
570  // Calculate total up and total discount percentage
571  // Note that this added fields does not match a field into database in Dolibarr (Dolibarr manage discount on lines not as a global property of object)
572  $resarray['object_total_up'] = $totalUp;
573  $resarray['object_total_up_locale'] = price($resarray['object_total_up'], 0, $outputlangs);
574  if (method_exists($object, 'getTotalDiscount') && in_array(get_class($object), array('Propal', 'Proposal', 'Commande', 'Facture', 'SupplierProposal', 'CommandeFournisseur', 'FactureFournisseur'))) {
575  $totalDiscount = $object->getTotalDiscount();
576  } else {
577  $totalDiscount = 0;
578  }
579  if (!empty($totalUp) && !empty($totalDiscount)) {
580  $resarray['object_total_discount'] = round(100 / $totalUp * $totalDiscount, 2);
581  $resarray['object_total_discount_locale'] = price($resarray['object_total_discount'], 0, $outputlangs);
582  } else {
583  $resarray['object_total_discount'] = '';
584  $resarray['object_total_discount_locale'] = '';
585  }
586  }
587 
588  // Retrieve extrafields
589  if (is_array($object->array_options) && count($object->array_options)) {
590  $object->fetch_optionals();
591 
592  $resarray = $this->fill_substitutionarray_with_extrafields($object, $resarray, $extrafields, $array_key, $outputlangs);
593  }
594 
595  return $resarray;
596  }
597 
598  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
607  public function get_substitutionarray_lines($line, $outputlangs, $linenumber = 0)
608  {
609  // phpcs:enable
610  global $conf;
611 
612  $resarray = array(
613  'line_pos' => $linenumber,
614  'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
615 
616  'line_product_ref'=>(empty($line->product_ref) ? '' : $line->product_ref),
617  'line_product_ref_fourn'=>(empty($line->ref_fourn) ? '' : $line->ref_fourn), // for supplier doc lines
618  'line_product_label'=>(empty($line->product_label) ? '' : $line->product_label),
619  'line_product_type'=>(empty($line->product_type) ? '' : $line->product_type),
620  'line_product_barcode'=>(empty($line->product_barcode) ? '' : $line->product_barcode),
621  'line_product_desc'=>(empty($line->product_desc) ? '' : $line->product_desc),
622 
623  'line_desc'=>$line->desc,
624  'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
625  'line_localtax1_rate'=>vatrate($line->localtax1_tx),
626  'line_localtax2_rate'=>vatrate($line->localtax1_tx),
627  'line_up'=>price2num($line->subprice),
628  'line_up_locale'=>price($line->subprice, 0, $outputlangs),
629  'line_total_up'=>price2num($line->subprice * $line->qty),
630  'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs),
631  'line_qty'=>$line->qty,
632  'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
633  'line_price_ht'=>price2num($line->total_ht),
634  'line_price_ttc'=>price2num($line->total_ttc),
635  'line_price_vat'=>price2num($line->total_tva),
636  'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs),
637  'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs),
638  'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs),
639  // Dates
640  'line_date_start'=>dol_print_date($line->date_start, 'day'),
641  'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzserver', $outputlangs),
642  'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'),
643  'line_date_end'=>dol_print_date($line->date_end, 'day'),
644  'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs),
645  'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'),
646 
647  'line_multicurrency_code' => price2num($line->multicurrency_code),
648  'line_multicurrency_subprice' => price2num($line->multicurrency_subprice),
649  'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht),
650  'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva),
651  'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc),
652  'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs),
653  'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs),
654  'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs),
655  'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs),
656  );
657 
658  // Units
659  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
660  $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long'));
661  $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short'));
662  }
663 
664  // Retrieve extrafields
665  $extrafieldkey = $line->table_element;
666  $array_key = "line";
667  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
668  $extrafields = new ExtraFields($this->db);
669  $extrafields->fetch_name_optionals_label($extrafieldkey, true);
670  $line->fetch_optionals();
671 
672  $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
673 
674  // Check if the current line belongs to a supplier order
675  if (get_class($line) == 'CommandeFournisseurLigne') {
676  // Add the product supplier extrafields to the substitutions
677  $extrafields->fetch_name_optionals_label("product_fournisseur_price");
678  $extralabels = $extrafields->attributes["product_fournisseur_price"]['label'];
679 
680  if (!empty($extralabels) && is_array($extralabels)) {
681  $columns = "";
682 
683  foreach ($extralabels as $key => $label) {
684  $columns .= "$key, ";
685  }
686 
687  if ($columns != "") {
688  $columns = substr($columns, 0, strlen($columns) - 2);
689  $resql = $this->db->query("SELECT ".$columns." FROM ".$this->db->prefix()."product_fournisseur_price_extrafields AS ex INNER JOIN ".$this->db->prefix()."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$this->db->escape($line->ref_supplier)."'");
690 
691  if ($this->db->num_rows($resql) > 0) {
692  $resql = $this->db->fetch_object($resql);
693 
694  foreach ($extralabels as $key => $label) {
695  $resarray['line_product_supplier_'.$key] = $resql->{$key};
696  }
697  }
698  }
699  }
700  }
701 
702  // Load product data optional fields to the line -> enables to use "line_options_{extrafield}"
703  if (isset($line->fk_product) && $line->fk_product > 0) {
704  $tmpproduct = new Product($this->db);
705  $result = $tmpproduct->fetch($line->fk_product);
706  foreach ($tmpproduct->array_options as $key => $label) {
707  $resarray["line_product_".$key] = $label;
708  }
709  }
710 
711  return $resarray;
712  }
713 
714  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
723  public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object')
724  {
725  // phpcs:enable
726  global $conf, $extrafields;
727  dol_include_once('/core/lib/product.lib.php');
728  $object->list_delivery_methods($object->shipping_method_id);
729  $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth);
730 
731  $array_shipment = array(
732  $array_key.'_id'=>$object->id,
733  $array_key.'_ref'=>$object->ref,
734  $array_key.'_ref_ext'=>$object->ref_ext,
735  $array_key.'_ref_customer'=>$object->ref_customer,
736  $array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'),
737  $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'),
738  $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
739  $array_key.'_total_ht'=>price($object->total_ht),
740  $array_key.'_total_vat'=>price($object->total_tva),
741  $array_key.'_total_ttc'=>price($object->total_ttc),
742  $array_key.'_total_discount_ht' => price($object->getTotalDiscount()),
743  $array_key.'_note_private'=>$object->note_private,
744  $array_key.'_note'=>$object->note_public,
745  $array_key.'_tracking_number'=>$object->tracking_number,
746  $array_key.'_tracking_url'=>$object->tracking_url,
747  $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'],
748  $array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units),
749  $array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units),
750  $array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units),
751  $array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units),
752  $array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'),
753  );
754 
755  // Add vat by rates
756  foreach ($object->lines as $line) {
757  if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) {
758  $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0;
759  }
760  $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
761  }
762 
763  // Retrieve extrafields
764  if (is_array($object->array_options) && count($object->array_options)) {
765  $object->fetch_optionals();
766 
767  $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs);
768  }
769 
770  // Add infor from $object->xxx where xxx has been loaded by fetch_origin() of shipment
771  if (!empty($object->commande) && is_object($object->commande)) {
772  $array_shipment['order_ref'] = $object->commande->ref;
773  $array_shipment['order_ref_customer'] = $object->commande->ref_customer;
774  }
775 
776  return $array_shipment;
777  }
778 
779 
780  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
788  public function get_substitutionarray_shipment_lines($line, $outputlangs)
789  {
790  // phpcs:enable
791  global $conf;
792  dol_include_once('/core/lib/product.lib.php');
793 
794  $resarray = array(
795  'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
796  'line_product_ref'=>$line->product_ref,
797  'line_product_label'=>$line->product_label,
798  'line_desc'=>$line->desc,
799  'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
800  'line_up'=>price($line->subprice),
801  'line_total_up'=>price($line->subprice * $line->qty),
802  'line_qty'=>$line->qty,
803  'line_qty_shipped'=>$line->qty_shipped,
804  'line_qty_asked'=>$line->qty_asked,
805  'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
806  'line_price_ht'=>price($line->total_ht),
807  'line_price_ttc'=>price($line->total_ttc),
808  'line_price_vat'=>price($line->total_tva),
809  'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units),
810  'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units),
811  'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units),
812  'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units),
813  );
814 
815  // Retrieve extrafields
816  $extrafieldkey = $line->element;
817  $array_key = "line";
818  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
819  $extrafields = new ExtraFields($this->db);
820  $extrafields->fetch_name_optionals_label($extrafieldkey, true);
821  $line->fetch_optionals();
822 
823  $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
824 
825  // Load product data optional fields to the line -> enables to use "line_product_options_{extrafield}"
826  if (isset($line->fk_product) && $line->fk_product > 0) {
827  $tmpproduct = new Product($this->db);
828  $tmpproduct->fetch($line->fk_product);
829  foreach ($tmpproduct->array_options as $key=>$label)
830  $resarray["line_product_".$key] = $label;
831  }
832 
833  return $resarray;
834  }
835 
836 
837  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
846  public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = 1)
847  {
848  // phpcs:enable
849  $array_other = array();
850  if (!empty($object)) {
851  foreach ($object as $key => $value) {
852  if (in_array($key, array('db', 'fields', 'lines', 'modelpdf', 'model_pdf'))) { // discard some properties
853  continue;
854  }
855  if (!empty($value)) {
856  if (!is_array($value) && !is_object($value)) {
857  $array_other['object_'.$key] = $value;
858  } elseif (is_array($value) && $recursive) {
859  $tmparray = $this->get_substitutionarray_each_var_object($value, $outputlangs, 0);
860  foreach ($tmparray as $key2 => $value2) {
861  $array_other['object_'.$key.'_'.preg_replace('/^object_/', '', $key2)] = $value2;
862  }
863  } elseif (is_object($value) && $recursive) {
864  $tmparray = $this->get_substitutionarray_each_var_object($value, $outputlangs, 0);
865  foreach ($tmparray as $key2 => $value2) {
866  $array_other['object_'.$key.'_'.preg_replace('/^object_/', '', $key2)] = $value2;
867  }
868  }
869  }
870  }
871  }
872 
873  //var_dump($array_other);
874 
875  return $array_other;
876  }
877 
878 
879  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
890  public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs)
891  {
892  // phpcs:enable
893  global $conf;
894 
895  if (is_array($extrafields->attributes[$object->table_element]['label'])) {
896  foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
897  if ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
898  $object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]);
899  $object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency);
900  //Add value to store price with currency
901  $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency']));
902  } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select') {
903  $valueofselectkey = $object->array_options['options_'.$key];
904  if (array_key_exists($valueofselectkey, $extrafields->attributes[$object->table_element]['param'][$key]['options'])) {
905  $object->array_options['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$valueofselectkey];
906  } else {
907  $object->array_options['options_'.$key] = '';
908  }
909  } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') {
910  $valArray = explode(',', $object->array_options['options_'.$key]);
911  $output = array();
912  foreach ($extrafields->attributes[$object->table_element]['param'][$key]['options'] as $keyopt => $valopt) {
913  if (in_array($keyopt, $valArray)) {
914  $output[] = $valopt;
915  }
916  }
917  $object->array_options['options_'.$key] = implode(', ', $output);
918  } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
919  if (strlen($object->array_options['options_'.$key]) > 0) {
920  $date = $object->array_options['options_'.$key];
921  $object->array_options['options_'.$key] = dol_print_date($date, 'day'); // using company output language
922  $object->array_options['options_'.$key.'_locale'] = dol_print_date($date, 'day', 'tzserver', $outputlangs); // using output language format
923  $object->array_options['options_'.$key.'_rfc'] = dol_print_date($date, 'dayrfc'); // international format
924  } else {
925  $object->array_options['options_'.$key] = '';
926  $object->array_options['options_'.$key.'_locale'] = '';
927  $object->array_options['options_'.$key.'_rfc'] = '';
928  }
929  $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
930  $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
931  } elseif ($extrafields->attributes[$object->table_element]['label'][$key] == 'datetime') {
932  $datetime = $object->array_options['options_'.$key];
933  $object->array_options['options_'.$key] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour') : ''); // using company output language
934  $object->array_options['options_'.$key.'_locale'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour', 'tzserver', $outputlangs) : ''); // using output language format
935  $object->array_options['options_'.$key.'_rfc'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhourrfc') : ''); // international format
936  $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
937  $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
938  } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'link') {
939  $id = $object->array_options['options_'.$key];
940  if ($id != "") {
941  $param = $extrafields->attributes[$object->table_element]['param'][$key];
942  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
943  $InfoFieldList = explode(":", $param_list[0]);
944  $classname = $InfoFieldList[0];
945  $classpath = $InfoFieldList[1];
946  if (!empty($classpath)) {
947  dol_include_once($InfoFieldList[1]);
948  if ($classname && class_exists($classname)) {
949  $tmpobject = new $classname($this->db);
950  $tmpobject->fetch($id);
951  // completely replace the id with the linked object name
952  $object->array_options['options_'.$key] = $tmpobject->name;
953  }
954  }
955  }
956  }
957 
958  if (array_key_exists('options_'.$key, $object->array_options)) {
959  $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
960  } else {
961  $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => ''));
962  }
963  }
964  }
965 
966  return $array_to_fill;
967  }
968 
969 
982  public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0)
983  {
984  if (empty($hidetop) || $hidetop == -1) {
985  $pdf->line($x, $y, $x + $l, $y);
986  }
987  $pdf->line($x + $l, $y, $x + $l, $y + $h);
988  if (empty($hidebottom)) {
989  $pdf->line($x + $l, $y + $h, $x, $y + $h);
990  }
991  $pdf->line($x, $y + $h, $x, $y);
992  }
993 
994 
1002  public function columnSort($a, $b)
1003  {
1004  if (empty($a['rank'])) {
1005  $a['rank'] = 0;
1006  }
1007  if (empty($b['rank'])) {
1008  $b['rank'] = 0;
1009  }
1010  if ($a['rank'] == $b['rank']) {
1011  return 0;
1012  }
1013  return ($a['rank'] > $b['rank']) ? -1 : 1;
1014  }
1015 
1026  public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1027  {
1028  global $conf;
1029 
1030  $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref);
1031 
1032 
1033  // Sorting
1034  uasort($this->cols, array($this, 'columnSort'));
1035 
1036  // Positionning
1037  $curX = $this->page_largeur - $this->marge_droite; // start from right
1038 
1039  // Array width
1040  $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche;
1041 
1042  // Count flexible column
1043  $totalDefinedColWidth = 0;
1044  $countFlexCol = 0;
1045  foreach ($this->cols as $colKey => & $colDef) {
1046  if (!$this->getColumnStatus($colKey)) {
1047  continue; // continue if disabled
1048  }
1049 
1050  if (!empty($colDef['scale'])) {
1051  // In case of column width is defined by percentage
1052  $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100);
1053  }
1054 
1055  if (empty($colDef['width'])) {
1056  $countFlexCol++;
1057  } else {
1058  $totalDefinedColWidth += $colDef['width'];
1059  }
1060  }
1061 
1062  foreach ($this->cols as $colKey => & $colDef) {
1063  // setting empty conf with default
1064  if (!empty($colDef['title'])) {
1065  $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']);
1066  } else {
1067  $colDef['title'] = $this->defaultTitlesFieldsStyle;
1068  }
1069 
1070  // setting empty conf with default
1071  if (!empty($colDef['content'])) {
1072  $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']);
1073  } else {
1074  $colDef['content'] = $this->defaultContentsFieldsStyle;
1075  }
1076 
1077  if ($this->getColumnStatus($colKey)) {
1078  // In case of flexible column
1079  if (empty($colDef['width'])) {
1080  $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol;
1081  }
1082 
1083  // Set positions
1084  $lastX = $curX;
1085  $curX = $lastX - $colDef['width'];
1086  $colDef['xStartPos'] = $curX;
1087  $colDef['xEndPos'] = $lastX;
1088  }
1089  }
1090  }
1091 
1098  public function getColumnContentWidth($colKey)
1099  {
1100  $colDef = $this->cols[$colKey];
1101  return $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1];
1102  }
1103 
1104 
1111  public function getColumnContentXStart($colKey)
1112  {
1113  $colDef = $this->cols[$colKey];
1114  return isset($colDef['xStartPos']) ? $colDef['xStartPos'] + $colDef['content']['padding'][3] : null;
1115  }
1116 
1123  public function getColumnRank($colKey)
1124  {
1125  if (!isset($this->cols[$colKey]['rank'])) {
1126  return -1;
1127  }
1128  return $this->cols[$colKey]['rank'];
1129  }
1130 
1140  public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false)
1141  {
1142  // prepare wanted rank
1143  $rank = -1;
1144 
1145  // try to get rank from target column
1146  if (!empty($targetCol)) {
1147  $rank = $this->getColumnRank($targetCol);
1148  if ($rank >= 0 && $insertAfterTarget) {
1149  $rank++;
1150  }
1151  }
1152 
1153  // get rank from new column definition
1154  if ($rank < 0 && !empty($defArray['rank'])) {
1155  $rank = $defArray['rank'];
1156  }
1157 
1158  // error: no rank
1159  if ($rank < 0) {
1160  return -1;
1161  }
1162 
1163  foreach ($this->cols as $colKey => & $colDef) {
1164  if ($rank <= $colDef['rank']) {
1165  $colDef['rank'] = $colDef['rank'] + 1;
1166  }
1167  }
1168 
1169  $defArray['rank'] = $rank;
1170  $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys
1171 
1172  return $rank;
1173  }
1174 
1175 
1185  public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '')
1186  {
1187  global $hookmanager;
1188 
1189  $parameters = array(
1190  'curY' => &$curY,
1191  'columnText' => $columnText,
1192  'colKey' => $colKey,
1193  'pdf' => &$pdf,
1194  );
1195  $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook
1196  if ($reshook < 0) {
1197  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1198  }
1199  if (!$reshook) {
1200  if (empty($columnText)) {
1201  return;
1202  }
1203  $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position
1204  $colDef = $this->cols[$colKey];
1205  // save curent cell padding
1206  $curentCellPaddinds = $pdf->getCellPaddings();
1207  // set cell padding with column content definition
1208  $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]);
1209  $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']);
1210 
1211  // restore cell padding
1212  $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
1213  }
1214  }
1215 
1216 
1231  public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0)
1232  {
1233  // load desc col params
1234  $colDef = $this->cols[$colKey];
1235  // save curent cell padding
1236  $curentCellPaddinds = $pdf->getCellPaddings();
1237  // set cell padding with column content definition
1238  $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]);
1239 
1240  // line description
1241  pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline);
1242  $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0];
1243 
1244  // restore cell padding
1245  $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
1246 
1247  // Display extrafield if needed
1248  $params = array(
1249  'display' => 'list',
1250  'printableEnable' => array(3),
1251  'printableEnableNotEmpty' => array(4)
1252  );
1253  $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params);
1254  if (!empty($extrafieldDesc)) {
1255  $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc);
1256  }
1257  }
1258 
1268  public function getExtrafieldContent($object, $extrafieldKey, $outputlangs = null)
1269  {
1270  global $hookmanager;
1271 
1272  if (empty($object->table_element)) {
1273  return;
1274  }
1275 
1276  $extrafieldsKeyPrefix = "options_";
1277 
1278  // Cleanup extrafield key to remove prefix if present
1279  $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix);
1280  if ($pos === 0) {
1281  $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix));
1282  }
1283 
1284  $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey;
1285 
1286 
1287  // Load extrafiels if not allready does
1288  if (empty($this->extrafieldsCache)) {
1289  $this->extrafieldsCache = new ExtraFields($this->db);
1290  }
1291  if (empty($this->extrafieldsCache->attributes[$object->table_element])) {
1292  $this->extrafieldsCache->fetch_name_optionals_label($object->table_element);
1293  }
1294  $extrafields = $this->extrafieldsCache;
1295 
1296  $extrafieldOutputContent = '';
1297  if (isset($object->array_options[$extrafieldOptionsKey])) $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element);
1298 
1299  // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ...
1300  if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') {
1301  // for lack of anything better we cleanup all html tags
1302  $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent);
1303  }
1304 
1305  $parameters = array(
1306  'object' => $object,
1307  'extrafields' => $extrafields,
1308  'extrafieldKey' => $extrafieldKey,
1309  'extrafieldOutputContent' =>& $extrafieldOutputContent
1310  );
1311  $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook
1312  if ($reshook < 0) {
1313  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1314  }
1315  if ($reshook) {
1316  $extrafieldOutputContent = $hookmanager->resPrint;
1317  }
1318 
1319  return $extrafieldOutputContent;
1320  }
1321 
1322 
1331  public function getExtrafieldsInHtml($object, $outputlangs, $params = array())
1332  {
1333  global $hookmanager;
1334 
1335  if (empty($object->table_element)) {
1336  return;
1337  }
1338 
1339  // Load extrafiels if not allready does
1340  if (empty($this->extrafieldsCache)) {
1341  $this->extrafieldsCache = new ExtraFields($this->db);
1342  }
1343  if (empty($this->extrafieldsCache->attributes[$object->table_element])) {
1344  $this->extrafieldsCache->fetch_name_optionals_label($object->table_element);
1345  }
1346  $extrafields = $this->extrafieldsCache;
1347 
1348  $defaultParams = array(
1349  'style' => '',
1350  'display' => 'auto', // auto, table, list
1351  'printableEnable' => array(1),
1352  'printableEnableNotEmpty' => array(2),
1353 
1354  'table' => array(
1355  'maxItemsInRow' => 2,
1356  'cellspacing' => 0,
1357  'cellpadding' => 0,
1358  'border' => 0,
1359  'labelcolwidth' => '25%',
1360  'arrayOfLineBreakType' => array('text', 'html')
1361  ),
1362 
1363  'list' => array(
1364  'separator' => '<br>'
1365  ),
1366 
1367  'auto' => array(
1368  'list' => 0, // 0 for default
1369  'table' => 4 // if there more than x extrafield to display
1370  ),
1371  );
1372 
1373  $params = $params + $defaultParams;
1374 
1375 
1380  $html = '';
1381  $fields = array();
1382 
1383  if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label'])) {
1384  foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
1385  // Enable extrafield ?
1386  $enabled = 0;
1387  $disableOnEmpty = 0;
1388  if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
1389  $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
1390  if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) {
1391  $enabled = 1;
1392  }
1393 
1394  if (in_array($printable, $params['printableEnableNotEmpty'])) {
1395  $disableOnEmpty = 1;
1396  }
1397  }
1398 
1399  if (empty($enabled)) {
1400  continue;
1401  }
1402 
1403  $field = new stdClass();
1404  $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]);
1405  $field->content = $this->getExtrafieldContent($object, $key, $outputlangs);
1406  $field->label = $outputlangs->transnoentities($label);
1407  $field->type = $extrafields->attributes[$object->table_element]['type'][$key];
1408 
1409  // dont display if empty
1410  if ($disableOnEmpty && empty($field->content)) {
1411  continue;
1412  }
1413 
1414  $fields[] = $field;
1415  }
1416  }
1417 
1418  if (!empty($fields)) {
1419  // Sort extrafields by rank
1420  uasort($fields, function ($a, $b) {
1421  return ($a->rank > $b->rank) ? 1 : -1;
1422  });
1423 
1424  // define some HTML content with style
1425  $html .= !empty($params['style']) ? '<style>'.$params['style'].'</style>' : '';
1426 
1427  // auto select display format
1428  if ($params['display'] == 'auto') {
1429  $lastNnumbItems = 0;
1430  foreach ($params['auto'] as $display => $numbItems) {
1431  if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) {
1432  $lastNnumbItems = $numbItems;
1433  $params['display'] = $display;
1434  }
1435  }
1436  }
1437 
1438  if ($params['display'] == 'list') {
1439  // Display in list format
1440  $i = 0;
1441  foreach ($fields as $field) {
1442  $html .= !empty($i) ? $params['list']['separator'] : '';
1443  $html .= '<strong>'.$field->label.' : </strong>';
1444  $html .= $field->content;
1445  $i++;
1446  }
1447  } elseif ($params['display'] == 'table') {
1448  // Display in table format
1449  $html .= '<table class="extrafield-table" cellspacing="'.$params['table']['cellspacing'].'" cellpadding="'.$params['table']['cellpadding'].'" border="'.$params['table']['border'].'">';
1450 
1451  $html .= "<tr>";
1452  $itemsInRow = 0;
1453  $maxItemsInRow = $params['table']['maxItemsInRow'];
1454  foreach ($fields as $field) {
1455  //$html.= !empty($html)?'<br>':'';
1456  if ($itemsInRow >= $maxItemsInRow) {
1457  // start a new line
1458  $html .= "</tr><tr>";
1459  $itemsInRow = 0;
1460  }
1461 
1462  // for some type we need line break
1463  if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) {
1464  if ($itemsInRow > 0) {
1465  // close table row and empty cols
1466  for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) {
1467  $html .= "<td></td><td></td>";
1468  }
1469  $html .= "</tr>";
1470 
1471  // start a new line
1472  $html .= "<tr>";
1473  }
1474 
1475  $itemsInRow = $maxItemsInRow;
1476  $html .= '<td colspan="'.($maxItemsInRow * 2 - 1).'">';
1477  $html .= '<strong>'.$field->label.' :</strong> ';
1478  $html .= $field->content;
1479  $html .= "</td>";
1480  } else {
1481  $itemsInRow++;
1482  $html .= '<td width="'.$params['table']['labelcolwidth'].'" class="extrafield-label">';
1483  $html .= '<strong>'.$field->label.' :</strong>';
1484  $html .= "</td>";
1485 
1486 
1487  $html .= '<td class="extrafield-content">';
1488  $html .= $field->content;
1489  $html .= "</td>";
1490  }
1491  }
1492  $html .= "</tr>";
1493 
1494  $html .= '</table>';
1495  }
1496  }
1497 
1498  return $html;
1499  }
1500 
1501 
1508  public function getColumnStatus($colKey)
1509  {
1510  if (!empty($this->cols[$colKey]['status'])) {
1511  return true;
1512  } else {
1513  return false;
1514  }
1515  }
1516 
1527  public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0)
1528  {
1529  global $hookmanager, $conf;
1530 
1531  foreach ($this->cols as $colKey => $colDef) {
1532  $parameters = array(
1533  'colKey' => $colKey,
1534  'pdf' => $pdf,
1535  'outputlangs' => $outputlangs,
1536  'tab_top' => $tab_top,
1537  'tab_height' => $tab_height,
1538  'hidetop' => $hidetop
1539  );
1540 
1541  $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook
1542  if ($reshook < 0) {
1543  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1544  } elseif (empty($reshook)) {
1545  if (!$this->getColumnStatus($colKey)) {
1546  continue;
1547  }
1548 
1549  // get title label
1550  $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']);
1551 
1552  // Add column separator
1553  if (!empty($colDef['border-left'])) {
1554  $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height);
1555  }
1556 
1557  if (empty($hidetop)) {
1558  // save curent cell padding
1559  $curentCellPaddinds = $pdf->getCellPaddings();
1560 
1561  // Add space for lines (more if we need to show a second alternative language)
1562  global $outputlangsbis;
1563  if (is_object($outputlangsbis)) {
1564  // set cell padding with column title definition
1565  $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5);
1566  } else {
1567  // set cell padding with column title definition
1568  $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
1569  }
1570  if (isset($colDef['title']['align'])) {
1571  $align = $colDef['title']['align'];
1572  } else {
1573  $align = '';
1574  }
1575  $pdf->SetXY($colDef['xStartPos'], $tab_top);
1576  $textWidth = $colDef['width'];
1577  $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $align);
1578 
1579  // Add variant of translation if $outputlangsbis is an object
1580  if (is_object($outputlangsbis) && trim($colDef['title']['label'])) {
1581  $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
1582  $pdf->SetXY($colDef['xStartPos'], $pdf->GetY());
1583  $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']);
1584  $pdf->MultiCell($textWidth, 2, $textbis, '', $align);
1585  }
1586 
1587  $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight);
1588 
1589  // restore cell padding
1590  $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
1591  }
1592  }
1593  }
1594 
1595  return $this->tabTitleHeight;
1596  }
1597 
1598 
1599 
1608  public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0)
1609  {
1610  global $conf;
1611 
1612  if (!empty($hidedetails)) {
1613  return;
1614  }
1615 
1616  if (empty($object->table_element)) {
1617  return;
1618  }
1619 
1620  // Load extrafiels if not allready does
1621  if (empty($this->extrafieldsCache)) {
1622  $this->extrafieldsCache = new ExtraFields($this->db);
1623  }
1624  if (empty($this->extrafieldsCache->attributes[$object->table_element])) {
1625  $this->extrafieldsCache->fetch_name_optionals_label($object->table_element);
1626  }
1627  $extrafields = $this->extrafieldsCache;
1628 
1629 
1630  if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]) && array_key_exists('label', $extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) {
1631  foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
1632  // Dont display separator yet even is set to be displayed (not compatible yet)
1633  if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') {
1634  continue;
1635  }
1636 
1637  // Enable extrafield ?
1638  $enabled = 0;
1639  if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
1640  $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
1641  if ($printable === 1 || $printable === 2) {
1642  $enabled = 1;
1643  }
1644  // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols
1645  }
1646 
1647  if (!$enabled) {
1648  continue;
1649  } // don't wast resourses if we don't need them...
1650 
1651  // Load language if required
1652  if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) {
1653  $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]);
1654  }
1655 
1656  // TODO : add more extrafield customisation capacities for PDF like width, rank...
1657 
1658  // set column definition
1659  $def = array(
1660  'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]),
1661  'width' => 25, // in mm
1662  'status' => boolval($enabled),
1663  'title' => array(
1664  'label' => $outputlangs->transnoentities($label)
1665  ),
1666  'content' => array(
1667  'align' => 'C'
1668  ),
1669  'border-left' => true, // add left line separator
1670  );
1671 
1672  $alignTypeRight = array('double', 'int', 'price');
1673  if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) {
1674  $def['content']['align'] = 'R';
1675  }
1676 
1677  $alignTypeLeft = array('text', 'html');
1678  if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) {
1679  $def['content']['align'] = 'L';
1680  }
1681 
1682 
1683  // for extrafields we use rank of extrafield to place it on PDF
1684  $this->insertNewColumnDef("options_".$key, $def);
1685  }
1686  }
1687  }
1688 }
Class to manage bank accounts.
Parent class for documents generators.
get_substitutionarray_shipment($object, $outputlangs, $array_key='object')
Define array with couple substitution key => substitution value.
getSubstitutionarrayMember($member, $outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive=1)
Define array with couple substitution key => substitution value.
get_substitutionarray_object($object, $outputlangs, $array_key='object')
Define array with couple substitution key => substitution value.
prepareArrayColumnField($object, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Prepare Array Column Field.
get_substitutionarray_mysoc($mysoc, $outputlangs)
Define array with couple substitution key => substitution value.
getColumnStatus($colKey)
get column status from column key
printStdColumnContent($pdf, &$curY, $colKey, $columnText='')
print standard column content
pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop=0)
Print standard column content.
printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref=0, $hidedesc=0, $issupplierline=0)
print description column content
get_substitutionarray_contact($object, $outputlangs, $array_key='object')
Define array with couple substitution key => substitution value.
get_substitutionarray_other($outputlangs)
Define array with couple substitution key => substitution value.
insertNewColumnDef($newColKey, $defArray, $targetCol=false, $insertAfterTarget=false)
get column position rank from column key
columnSort($a, $b)
uasort callback function to Sort columns fields
fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs)
Fill array with couple extrafield key => extrafield value.
getColumnContentXStart($colKey)
get column content X (abscissa) left position from column key
printRect($pdf, $x, $y, $l, $h, $hidetop=0, $hidebottom=0)
Rect pdf.
getColumnContentWidth($colKey)
get column content width from column key
getColumnRank($colKey)
get column position rank from column key
getExtrafieldContent($object, $extrafieldKey, $outputlangs=null)
get extrafield content for pdf writeHtmlCell compatibility usage for PDF line columns and object note...
get_substitutionarray_lines($line, $outputlangs, $linenumber=0)
Define array with couple substitution key => substitution value.
defineColumnExtrafield($object, $outputlangs, $hidedetails=0)
Define Array Column Field for extrafields.
get_substitutionarray_shipment_lines($line, $outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_thirdparty($object, $outputlangs, $array_key='company')
Define array with couple substitution key => substitution value For example {company_name},...
get_substitutionarray_user($user, $outputlangs)
Define array with couple substitution key => substitution value.
Class to manage standard extra fields.
Class to manage invoices.
Class to manage products or services.
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
getFormeJuridiqueLabel($code)
Retourne le nom traduit de la forme juridique.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
doc_getlinedesc($line, $outputlangs, $hideref=0, $hidedesc=0, $issupplierline=0)
Return line description translated in outputlangs and encoded into UTF8.
Definition: doc.lib.php:41
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages.
isASecretKey($keyname)
Return if string has a name dedicated to store a secret.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_now($mode='auto')
Return date for now.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
pdf_writelinedesc(&$pdf, $object, $i, $outputlangs, $w, $h, $posx, $posy, $hideref=0, $hidedesc=0, $issupplierline=0)
Output line description into PDF.
Definition: pdf.lib.php:1359
measuringUnitString($unit, $measuring_style='', $scale='', $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
$conf db
API class for accounts.
Definition: inc.php:41