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
26/**
27 *	    \file       htdocs/core/class/commondocgenerator.class.php
28 *		\ingroup    core
29 *		\brief      File of parent class for documents generators
30 */
31
32
33/**
34 *	Parent class for documents generators
35 */
36abstract class CommonDocGenerator
37{
38	/**
39	 * @var string Error code (or message)
40	 */
41	public $error = '';
42
43	/**
44	 * @var string[]    Array of error strings
45	 */
46	public $errors = array();
47
48	/**
49	 * @var DoliDB Database handler.
50	 */
51	protected $db;
52
53	/**
54	 * @var Extrafields object
55	 */
56	public $extrafieldsCache;
57
58	/**
59	 *	Constructor
60	 *
61	 *  @param		DoliDB		$db      Database handler
62	 */
63	public function __construct($db)
64	{
65		$this->db = $db;
66	}
67
68
69	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
70	/**
71	 * Define array with couple substitution key => substitution value
72	 *
73	 * @param   User		$user           User
74	 * @param   Translate	$outputlangs    Language object for output
75	 * @return	array						Array of substitution key->code
76	 */
77	public function get_substitutionarray_user($user, $outputlangs)
78	{
79		// phpcs:enable
80		global $conf, $extrafields;
81
82		$logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
83
84		$array_user = array(
85			'myuser_lastname'=>$user->lastname,
86			'myuser_firstname'=>$user->firstname,
87			'myuser_fullname'=>$user->getFullName($outputlangs, 1),
88			'myuser_login'=>$user->login,
89			'myuser_phone'=>$user->office_phone,
90	   		'myuser_address'=>$user->address,
91	   		'myuser_zip'=>$user->zip,
92	   		'myuser_town'=>$user->town,
93	   		'myuser_country'=>$user->country,
94			'myuser_country_code'=>$user->country_code,
95	   		'myuser_state'=>$user->state,
96			'myuser_state_code'=>$user->state_code,
97			'myuser_fax'=>$user->office_fax,
98			'myuser_mobile'=>$user->user_mobile,
99			'myuser_email'=>$user->email,
100			'myuser_logo'=>$logotouse,
101			'myuser_job'=>$user->job,
102			'myuser_web'=>''	// url not exist in $user object
103		);
104		// Retrieve extrafields
105		if (is_array($user->array_options) && count($user->array_options)) {
106			$array_user = $this->fill_substitutionarray_with_extrafields($user, $array_user, $extrafields, 'myuser', $outputlangs);
107		}
108		return $array_user;
109	}
110
111
112	/**
113	 * Define array with couple substitution key => substitution value
114	 *
115	 * @param   Adherent	$member         Member
116	 * @param   Translate	$outputlangs    Language object for output
117	 * @return	array						Array of substitution key->code
118	 */
119	public function getSubstitutionarrayMember($member, $outputlangs)
120	{
121		global $conf, $extrafields;
122
123		if ($member->photo) {
124			$logotouse = $conf->adherent->dir_output.'/'.get_exdir(0, 0, 0, 1, $member, 'user').'/photos/'.$member->photo;
125		} else {
126			$logotouse = DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.png';
127		}
128
129		$array_member = array(
130			'mymember_lastname' => $member->lastname,
131			'mymember_firstname' => $member->firstname,
132			'mymember_fullname' => $member->getFullName($outputlangs, 1),
133			'mymember_login' => $member->login,
134			'mymember_address' => $member->address,
135			'mymember_zip' => $member->zip,
136			'mymember_town' => $member->town,
137			'mymember_country_code' => $member->country_code,
138			'mymember_country' => $member->country,
139			'mymember_state_code' => $member->state_code,
140			'mymember_state' => $member->state,
141			'mymember_phone_perso' => $member->phone_perso,
142			'mymember_phone_pro' => $member->phone,
143			'mymember_phone_mobile' => $member->phone_mobile,
144			'mymember_email' => $member->email,
145			'mymember_logo' => $logotouse,
146			'mymember_gender' => $member->gender,
147			'mymember_birth_locale' => dol_print_date($member->birth, 'day', 'tzuser', $outputlangs),
148			'mymember_birth' => dol_print_date($member->birth, 'day', 'tzuser'),
149		);
150		// Retrieve extrafields
151		if (is_array($member->array_options) && count($member->array_options)) {
152			$array_member = $this->fill_substitutionarray_with_extrafields($member, $array_member, $extrafields, 'mymember', $outputlangs);
153		}
154		return $array_member;
155	}
156
157
158	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
159	/**
160	 * Define array with couple substitution key => substitution value
161	 *
162	 * @param   Societe		$mysoc			Object thirdparty
163	 * @param   Translate	$outputlangs    Language object for output
164	 * @return	array						Array of substitution key->code
165	 */
166	public function get_substitutionarray_mysoc($mysoc, $outputlangs)
167	{
168		// phpcs:enable
169		global $conf;
170
171		if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code))
172		{
173			$mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code);
174		}
175		if (empty($mysoc->country) && !empty($mysoc->country_code))
176		{
177			$mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
178		}
179		if (empty($mysoc->state) && !empty($mysoc->state_code))
180		{
181			$mysoc->state = getState($mysoc->state_code, 0);
182		}
183
184		$logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
185
186		return array(
187			'mycompany_logo'=>$logotouse,
188			'mycompany_name'=>$mysoc->name,
189			'mycompany_email'=>$mysoc->email,
190			'mycompany_phone'=>$mysoc->phone,
191			'mycompany_fax'=>$mysoc->fax,
192			'mycompany_address'=>$mysoc->address,
193			'mycompany_zip'=>$mysoc->zip,
194			'mycompany_town'=>$mysoc->town,
195			'mycompany_country'=>$mysoc->country,
196			'mycompany_country_code'=>$mysoc->country_code,
197			'mycompany_state'=>$mysoc->state,
198			'mycompany_state_code'=>$mysoc->state_code,
199			'mycompany_web'=>$mysoc->url,
200			'mycompany_juridicalstatus'=>$mysoc->forme_juridique,
201			'mycompany_managers'=>$mysoc->managers,
202			'mycompany_capital'=>$mysoc->capital,
203			'mycompany_barcode'=>$mysoc->barcode,
204			'mycompany_idprof1'=>$mysoc->idprof1,
205			'mycompany_idprof2'=>$mysoc->idprof2,
206			'mycompany_idprof3'=>$mysoc->idprof3,
207			'mycompany_idprof4'=>$mysoc->idprof4,
208			'mycompany_idprof5'=>$mysoc->idprof5,
209			'mycompany_idprof6'=>$mysoc->idprof6,
210			'mycompany_vatnumber'=>$mysoc->tva_intra,
211			'mycompany_object'=>$mysoc->object,
212			'mycompany_note_private'=>$mysoc->note_private,
213			//'mycompany_note_public'=>$mysoc->note_public,        // Only private not exists for "mysoc" but both for thirdparties
214		);
215	}
216
217
218	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
219	/**
220	 * Define array with couple substitution key => substitution value
221	 *
222	 * @param	Societe		$object			Object
223	 * @param   Translate	$outputlangs    Language object for output
224	 * @param   string		$array_key	    Name of the key for return array
225	 * @return	array						Array of substitution key->code
226	 */
227	public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company')
228	{
229		// phpcs:enable
230		global $conf, $extrafields;
231
232		if (empty($object->country) && !empty($object->country_code))
233		{
234			$object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
235		}
236		if (empty($object->state) && !empty($object->state_code))
237		{
238			$object->state = getState($object->state_code, 0);
239		}
240
241		$array_thirdparty = array(
242			'company_name'=>$object->name,
243			'company_name_alias' => $object->name_alias,
244			'company_email'=>$object->email,
245			'company_phone'=>$object->phone,
246			'company_fax'=>$object->fax,
247			'company_address'=>$object->address,
248			'company_zip'=>$object->zip,
249			'company_town'=>$object->town,
250			'company_country'=>$object->country,
251			'company_country_code'=>$object->country_code,
252			'company_state'=>$object->state,
253			'company_state_code'=>$object->state_code,
254			'company_web'=>$object->url,
255			'company_barcode'=>$object->barcode,
256			'company_vatnumber'=>$object->tva_intra,
257			'company_customercode'=>$object->code_client,
258			'company_suppliercode'=>$object->code_fournisseur,
259			'company_customeraccountancycode'=>$object->code_compta,
260			'company_supplieraccountancycode'=>$object->code_compta_fournisseur,
261			'company_juridicalstatus'=>$object->forme_juridique,
262			'company_outstanding_limit'=>$object->outstanding_limit,
263			'company_capital'=>$object->capital,
264			'company_idprof1'=>$object->idprof1,
265			'company_idprof2'=>$object->idprof2,
266			'company_idprof3'=>$object->idprof3,
267			'company_idprof4'=>$object->idprof4,
268			'company_idprof5'=>$object->idprof5,
269			'company_idprof6'=>$object->idprof6,
270			'company_note_public'=>$object->note_public,
271			'company_note_private'=>$object->note_private,
272			'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''),
273			'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '')
274		);
275
276		// Retrieve extrafields
277		if (is_array($object->array_options) && count($object->array_options))
278		{
279			$object->fetch_optionals();
280
281			$array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs);
282		}
283		return $array_thirdparty;
284	}
285
286	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
287	/**
288	 * Define array with couple substitution key => substitution value
289	 *
290	 * @param	Contact 	$object        	contact
291	 * @param	Translate 	$outputlangs   	object for output
292	 * @param   string		$array_key	    Name of the key for return array
293	 * @return	array 						Array of substitution key->code
294	 */
295	public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object')
296	{
297		// phpcs:enable
298		global $conf, $extrafields;
299
300		if (empty($object->country) && !empty($object->country_code))
301		{
302			$object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
303		}
304		if (empty($object->state) && !empty($object->state_code))
305		{
306			$object->state = getState($object->state_code, 0);
307		}
308
309		$array_contact = array(
310			$array_key.'_fullname' => $object->getFullName($outputlangs, 1),
311			$array_key.'_lastname' => $object->lastname,
312			$array_key.'_firstname' => $object->firstname,
313			$array_key.'_address' => $object->address,
314			$array_key.'_zip' => $object->zip,
315			$array_key.'_town' => $object->town,
316			$array_key.'_state_id' => $object->state_id,
317			$array_key.'_state_code' => $object->state_code,
318			$array_key.'_state' => $object->state,
319			$array_key.'_country_id' => $object->country_id,
320			$array_key.'_country_code' => $object->country_code,
321			$array_key.'_country' => $object->country,
322			$array_key.'_poste' => $object->poste,
323			$array_key.'_socid' => $object->socid,
324			$array_key.'_statut' => $object->statut,
325			$array_key.'_code' => $object->code,
326			$array_key.'_email' => $object->email,
327			$array_key.'_jabberid' => $object->jabberid, // deprecated
328			$array_key.'_phone_pro' => $object->phone_pro,
329			$array_key.'_phone_perso' => $object->phone_perso,
330			$array_key.'_phone_mobile' => $object->phone_mobile,
331			$array_key.'_fax' => $object->fax,
332			$array_key.'_birthday' => $object->birthday,
333			$array_key.'_default_lang' => $object->default_lang,
334			$array_key.'_note_public' => $object->note_public,
335			$array_key.'_note_private' => $object->note_private,
336			$array_key.'_civility' => $object->civility,
337		);
338
339		// Retrieve extrafields
340		if (is_array($object->array_options) && count($object->array_options))
341		{
342			$object->fetch_optionals();
343
344			$array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs);
345		}
346		return $array_contact;
347	}
348
349
350	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
351	/**
352	 * Define array with couple substitution key => substitution value
353	 *
354	 * @param   Translate	$outputlangs    Language object for output
355	 * @return	array						Array of substitution key->code
356	 */
357	public function get_substitutionarray_other($outputlangs)
358	{
359		// phpcs:enable
360		global $conf;
361
362		$now = dol_now('gmt'); // gmt
363		$array_other = array(
364			// Date in default language
365			'current_date'=>dol_print_date($now, 'day', 'tzuser'),
366			'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'),
367   			'current_server_date'=>dol_print_date($now, 'day', 'tzserver'),
368   			'current_server_datehour'=>dol_print_date($now, 'dayhour', 'tzserver'),
369			// Date in requested output language
370			'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs),
371   			'current_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzuser', $outputlangs),
372   			'current_server_date_locale'=>dol_print_date($now, 'day', 'tzserver', $outputlangs),
373   			'current_server_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzserver', $outputlangs),
374		);
375
376
377		foreach ($conf->global as $key => $val)
378		{
379			if (isASecretKey($key)) $newval = '*****forbidden*****';
380			else $newval = $val;
381			$array_other['__['.$key.']__'] = $newval;
382		}
383
384		return $array_other;
385	}
386
387
388	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
389	/**
390	 * Define array with couple substitution key => substitution value
391	 *
392	 * @param   Object			$object             Main object to use as data source
393	 * @param   Translate		$outputlangs        Lang object to use for output
394	 * @param   string		    $array_key	        Name of the key for return array
395	 * @return	array								Array of substitution
396	 */
397	public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
398	{
399		// phpcs:enable
400		global $conf, $extrafields;
401
402		$sumpayed = $sumdeposit = $sumcreditnote = '';
403		$already_payed_all = 0;
404		$remain_to_pay = 0;
405		if ($object->element == 'facture')
406		{
407			$invoice_source = new Facture($this->db);
408			if ($object->fk_facture_source > 0)
409			{
410				$invoice_source->fetch($object->fk_facture_source);
411			}
412			$sumpayed = $object->getSommePaiement();
413			$sumdeposit = $object->getSumDepositsUsed();
414			$sumcreditnote = $object->getSumCreditNotesUsed();
415			$already_payed_all = $sumpayed + $sumdeposit + $sumcreditnote;
416			$remain_to_pay = $sumpayed - $sumdeposit - $sumcreditnote;
417
418			if ($object->fk_account > 0) {
419				require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
420				$bank_account = new Account($this->db);
421				$bank_account->fetch($object->fk_account);
422			}
423		}
424
425		$date = ($object->element == 'contrat' ? $object->date_contrat : $object->date);
426
427		$resarray = array(
428		$array_key.'_id'=>$object->id,
429		$array_key.'_ref'=>$object->ref,
430		$array_key.'_ref_ext'=>$object->ref_ext,
431		$array_key.'_ref_customer'=>(!empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
432		$array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
433		$array_key.'_source_invoice_ref'=>$invoice_source->ref,
434		// Dates
435		$array_key.'_hour'=>dol_print_date($date, 'hour'),
436		$array_key.'_date'=>dol_print_date($date, 'day'),
437		$array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'),
438		$array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''),
439		$array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''),
440		$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
441		$array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''),
442		$array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''),
443		$array_key.'_date_delivery_planed'=>(!empty($object->date_livraison) ?dol_print_date($object->date_livraison, 'day') : ''),
444		$array_key.'_date_close'=>(!empty($object->date_cloture) ?dol_print_date($object->date_cloture, 'dayhour') : ''),
445
446		$array_key.'_payment_mode_code'=>$object->mode_reglement_code,
447		$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),
448		$array_key.'_payment_term_code'=>$object->cond_reglement_code,
449		$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)),
450
451		$array_key.'_incoterms'=>(method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''),
452
453		$array_key.'_bank_iban'=>$bank_account->iban,
454		$array_key.'_bank_bic'=>$bank_account->bic,
455		$array_key.'_bank_label'=>$bank_account->label,
456		$array_key.'_bank_number'=>$bank_account->number,
457		$array_key.'_bank_proprio'=>$bank_account->proprio,
458
459		$array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs),
460		$array_key.'_total_vat_locale'=>(!empty($object->total_vat) ?price($object->total_vat, 0, $outputlangs) : price($object->total_tva, 0, $outputlangs)),
461		$array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs),
462		$array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs),
463		$array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs),
464
465		$array_key.'_total_ht'=>price2num($object->total_ht),
466		$array_key.'_total_vat'=>(!empty($object->total_vat) ?price2num($object->total_vat) : price2num($object->total_tva)),
467		$array_key.'_total_localtax1'=>price2num($object->total_localtax1),
468		$array_key.'_total_localtax2'=>price2num($object->total_localtax2),
469		$array_key.'_total_ttc'=>price2num($object->total_ttc),
470
471		$array_key.'_multicurrency_code' => $object->multicurrency_code,
472		$array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx),
473		$array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht),
474		$array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva),
475		$array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc),
476		$array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs),
477		$array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs),
478		$array_key.'_multicurrency_total_ttc_locale' => price($object->multicurrency_total_ttc, 0, $outputlangs),
479
480		$array_key.'_note_private'=>$object->note,
481		$array_key.'_note_public'=>$object->note_public,
482		$array_key.'_note'=>$object->note_public, // For backward compatibility
483
484		// Payments
485		$array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs),
486		$array_key.'_already_payed'=>price2num($sumpayed),
487		$array_key.'_already_deposit_locale'=>price($sumdeposit, 0, $outputlangs),
488		$array_key.'_already_deposit'=>price2num($sumdeposit),
489		$array_key.'_already_creditnote_locale'=>price($sumcreditnote, 0, $outputlangs),
490		$array_key.'_already_creditnote'=>price2num($sumcreditnote),
491
492		$array_key.'_already_payed_all_locale'=>price(price2num($already_payed_all, 'MT'), 0, $outputlangs),
493		$array_key.'_already_payed_all'=> price2num($already_payed_all, 'MT'),
494
495		// Remain to pay with all know information (except open direct debit requests)
496		$array_key.'_remain_to_pay_locale'=>price(price2num($object->total_ttc - $remain_to_pay, 'MT'), 0, $outputlangs),
497		$array_key.'_remain_to_pay'=>price2num($object->total_ttc - $remain_to_pay, 'MT')
498		);
499
500		if (method_exists($object, 'getTotalDiscount')) {
501			$resarray[$array_key.'_total_discount_ht_locale'] = price($object->getTotalDiscount(), 0, $outputlangs);
502			$resarray[$array_key.'_total_discount_ht'] = price2num($object->getTotalDiscount());
503		} else {
504			$resarray[$array_key.'_total_discount_ht_locale'] = '';
505			$resarray[$array_key.'_total_discount_ht'] = '';
506		}
507
508		// Fetch project information if there is a project assigned to this object
509		if ($object->element != "project" && !empty($object->fk_project) && $object->fk_project > 0)
510		{
511			if (!is_object($object->project))
512			{
513				$object->fetch_projet();
514			}
515
516			$resarray[$array_key.'_project_ref'] = $object->project->ref;
517			$resarray[$array_key.'_project_title'] = $object->project->title;
518			$resarray[$array_key.'_project_description'] = $object->project->description;
519			$resarray[$array_key.'_project_date_start'] = dol_print_date($object->project->date_start, 'day');
520			$resarray[$array_key.'_project_date_end'] = dol_print_date($object->project->date_end, 'day');
521		}
522
523		// Add vat by rates
524		if (is_array($object->lines) && count($object->lines) > 0)
525		{
526			$totalUp = 0;
527			foreach ($object->lines as $line)
528			{
529				// $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility
530				if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0;
531				$resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
532				$resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
533				// $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
534				$vatformated = vatrate($line->tva_tx);
535				if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0;
536				$resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva;
537				$resarray[$array_key.'_total_vat_locale_'.$vatformated] = price($resarray[$array_key.'_total_vat_'.$vatformated]);
538
539				$totalUp += $line->subprice * $line->qty;
540			}
541
542			// @GS: Calculate total up and total discount percentage
543			// Note that this added fields correspond to nothing in Dolibarr (Dolibarr manage discount on lines not globally)
544			$resarray['object_total_up'] = $totalUp;
545			$resarray['object_total_up_locale'] = price($resarray['object_total_up'], 0, $outputlangs);
546			if (method_exists($object, 'getTotalDiscount')) {
547				$totalDiscount = $object->getTotalDiscount();
548			} else {
549				$totalDiscount = 0;
550			}
551			if (!empty($totalUp) && !empty($totalDiscount)) {
552				$resarray['object_total_discount'] = round(100 / $totalUp * $totalDiscount, 2);
553				$resarray['object_total_discount_locale'] = price($resarray['object_total_discount'], 0, $outputlangs);
554			} else {
555				$resarray['object_total_discount'] = '';
556				$resarray['object_total_discount_locale'] = '';
557			}
558		}
559
560		// Retrieve extrafields
561		if (is_array($object->array_options) && count($object->array_options))
562		{
563			$object->fetch_optionals();
564
565			$resarray = $this->fill_substitutionarray_with_extrafields($object, $resarray, $extrafields, $array_key, $outputlangs);
566		}
567
568		return $resarray;
569	}
570
571	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
572	/**
573	 *	Define array with couple substitution key => substitution value
574	 *
575	 *	@param  Object			$line				Object line
576	 *	@param  Translate		$outputlangs        Lang object to use for output
577	 *  @param  int				$linenumber			The number of the line for the substitution of "object_line_pos"
578	 *  @return	array								Return a substitution array
579	 */
580	public function get_substitutionarray_lines($line, $outputlangs, $linenumber = 0)
581	{
582		// phpcs:enable
583		global $conf;
584
585		$resarray = array(
586			'line_pos' => $linenumber,
587			'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
588
589			'line_product_ref'=>(empty($line->product_ref) ? '' : $line->product_ref),
590			'line_product_ref_fourn'=>(empty($line->ref_fourn) ? '' : $line->ref_fourn), // for supplier doc lines
591			'line_product_label'=>(empty($line->product_label) ? '' : $line->product_label),
592			'line_product_type'=>(empty($line->product_type) ? '' : $line->product_type),
593			'line_product_barcode'=>(empty($line->product_barcode) ? '' : $line->product_barcode),
594
595			'line_desc'=>$line->desc,
596			'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
597			'line_localtax1_rate'=>vatrate($line->localtax1_tx),
598			'line_localtax2_rate'=>vatrate($line->localtax1_tx),
599			'line_up'=>price2num($line->subprice),
600			'line_up_locale'=>price($line->subprice, 0, $outputlangs),
601			'line_total_up'=>price2num($line->subprice * $line->qty),
602			'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs),
603			'line_qty'=>$line->qty,
604			'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
605			'line_price_ht'=>price2num($line->total_ht),
606			'line_price_ttc'=>price2num($line->total_ttc),
607			'line_price_vat'=>price2num($line->total_tva),
608			'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs),
609			'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs),
610			'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs),
611			// Dates
612			'line_date_start'=>dol_print_date($line->date_start, 'day'),
613			'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzserver', $outputlangs),
614			'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'),
615			'line_date_end'=>dol_print_date($line->date_end, 'day'),
616			'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs),
617			'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'),
618
619			'line_multicurrency_code' => price2num($line->multicurrency_code),
620			'line_multicurrency_subprice' => price2num($line->multicurrency_subprice),
621			'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht),
622			'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva),
623			'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc),
624			'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs),
625			'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs),
626			'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs),
627			'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs),
628		);
629
630		// Units
631		if (!empty($conf->global->PRODUCT_USE_UNITS))
632		{
633			  $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long'));
634			  $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short'));
635		}
636
637		// Retrieve extrafields
638		$extrafieldkey = $line->table_element;
639		$array_key = "line";
640		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
641		$extrafields = new ExtraFields($this->db);
642		$extrafields->fetch_name_optionals_label($extrafieldkey, true);
643		$line->fetch_optionals();
644
645		$resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
646
647		// Check if the current line belongs to a supplier order
648		if (get_class($line) == 'CommandeFournisseurLigne')
649		{
650			// Add the product supplier extrafields to the substitutions
651			$extrafields->fetch_name_optionals_label("product_fournisseur_price");
652			$extralabels = $extrafields->attributes["product_fournisseur_price"]['label'];
653
654			if (!empty($extralabels) && is_array($extralabels))
655			{
656				$columns = "";
657
658				foreach ($extralabels as $key => $label)
659				{
660					$columns .= "$key, ";
661				}
662
663				if ($columns != "")
664				{
665					$columns = substr($columns, 0, strlen($columns) - 2);
666					$resql = $this->db->query("SELECT ".$columns." FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields AS ex INNER JOIN ".MAIN_DB_PREFIX."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$this->db->escape($line->ref_supplier)."'");
667
668					if ($this->db->num_rows($resql) > 0)
669					{
670						$resql = $this->db->fetch_object($resql);
671
672						foreach ($extralabels as $key => $label)
673						{
674							$resarray['line_product_supplier_'.$key] = $resql->{$key};
675						}
676					}
677				}
678			}
679		}
680
681		// Load product data optional fields to the line -> enables to use "line_options_{extrafield}"
682		if (isset($line->fk_product) && $line->fk_product > 0)
683		{
684			$tmpproduct = new Product($this->db);
685			$result = $tmpproduct->fetch($line->fk_product);
686			foreach ($tmpproduct->array_options as $key=>$label)
687				$resarray["line_product_".$key] = $label;
688		}
689
690		return $resarray;
691	}
692
693	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
694	/**
695	 * Define array with couple substitution key => substitution value
696	 *
697	 * @param   Expedition		$object             Main object to use as data source
698	 * @param   Translate		$outputlangs        Lang object to use for output
699	 * @param   array			$array_key	        Name of the key for return array
700	 * @return	array								Array of substitution
701	 */
702	public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object')
703	{
704		// phpcs:enable
705		global $conf, $extrafields;
706		dol_include_once('/core/lib/product.lib.php');
707		$object->list_delivery_methods($object->shipping_method_id);
708		$calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth);
709
710		$array_shipment = array(
711			$array_key.'_id'=>$object->id,
712			$array_key.'_ref'=>$object->ref,
713			$array_key.'_ref_ext'=>$object->ref_ext,
714			$array_key.'_ref_customer'=>$object->ref_customer,
715			$array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'),
716			$array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'),
717			$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
718			$array_key.'_total_ht'=>price($object->total_ht),
719			$array_key.'_total_vat'=>price($object->total_tva),
720			$array_key.'_total_ttc'=>price($object->total_ttc),
721			$array_key.'_total_discount_ht' => price($object->getTotalDiscount()),
722			$array_key.'_note_private'=>$object->note_private,
723			$array_key.'_note'=>$object->note_public,
724			$array_key.'_tracking_number'=>$object->tracking_number,
725			$array_key.'_tracking_url'=>$object->tracking_url,
726			$array_key.'_shipping_method'=>$object->listmeths[0]['libelle'],
727			$array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units),
728			$array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units),
729			$array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units),
730			$array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units),
731			$array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'),
732		);
733
734		// Add vat by rates
735		foreach ($object->lines as $line)
736		{
737			if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0;
738			$array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
739		}
740
741		// Retrieve extrafields
742		if (is_array($object->array_options) && count($object->array_options))
743		{
744			$object->fetch_optionals();
745
746			$array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs);
747		}
748
749		// Add infor from $object->xxx where xxx has been loaded by fetch_origin() of shipment
750		if (!empty($object->commande) && is_object($object->commande)) {
751			$array_shipment['order_ref'] = $object->commande->ref;
752			$array_shipment['order_ref_customer'] = $object->commande->ref_customer;
753		}
754
755		return $array_shipment;
756	}
757
758
759	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
760	/**
761	 *  Define array with couple substitution key => substitution value
762	 *
763	 *	@param  ExpeditionLigne	$line				Object line
764	 *	@param  Translate		$outputlangs        Lang object to use for output
765	 *	@return	array								Substitution array
766	 */
767	public function get_substitutionarray_shipment_lines($line, $outputlangs)
768	{
769		// phpcs:enable
770		global $conf;
771		dol_include_once('/core/lib/product.lib.php');
772
773		$resarray = array(
774			'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
775			'line_product_ref'=>$line->product_ref,
776			'line_product_label'=>$line->product_label,
777			'line_desc'=>$line->desc,
778			'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
779			'line_up'=>price($line->subprice),
780			'line_total_up'=>price($line->subprice * $line->qty),
781			'line_qty'=>$line->qty,
782			'line_qty_shipped'=>$line->qty_shipped,
783			'line_qty_asked'=>$line->qty_asked,
784			'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
785			'line_price_ht'=>price($line->total_ht),
786			'line_price_ttc'=>price($line->total_ttc),
787			'line_price_vat'=>price($line->total_tva),
788			'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units),
789			'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units),
790			'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units),
791			'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units),
792		);
793
794		// Retrieve extrafields
795		$extrafieldkey = $line->element;
796		$array_key = "line";
797		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
798		$extrafields = new ExtraFields($this->db);
799		$extrafields->fetch_name_optionals_label($extrafieldkey, true);
800		$line->fetch_optionals();
801
802		$resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
803
804		// Load product data optional fields to the line -> enables to use "line_product_options_{extrafield}"
805		if (isset($line->fk_product) && $line->fk_product > 0)
806		{
807			$tmpproduct = new Product($this->db);
808			$result = $tmpproduct->fetch($line->fk_product);
809			foreach ($tmpproduct->array_options as $key=>$label)
810				$resarray["line_product_".$key] = $label;
811		}
812
813		return $resarray;
814	}
815
816
817	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
818	/**
819	 * Define array with couple substitution key => substitution value
820	 *
821	 * @param   Object		$object    		Dolibarr Object
822	 * @param   Translate	$outputlangs    Language object for output
823	 * @param   boolean		$recursive    	Want to fetch child array or child object
824	 * @return	array						Array of substitution key->code
825	 */
826	public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true)
827	{
828		// phpcs:enable
829		$array_other = array();
830		if (!empty($object)) {
831			foreach ($object as $key => $value) {
832				if (!empty($value)) {
833					if (!is_array($value) && !is_object($value)) {
834						$array_other['object_'.$key] = $value;
835					}
836					if (is_array($value) && $recursive) {
837						$array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false);
838					}
839				}
840			}
841		}
842		return $array_other;
843	}
844
845
846	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
847	/**
848	 *	Fill array with couple extrafield key => extrafield value
849	 *
850	 *	@param  Object			$object				Object with extrafields (must have $object->array_options filled)
851	 *	@param  array			$array_to_fill      Substitution array
852	 *  @param  Extrafields		$extrafields        Extrafields object
853	 *  @param  string			$array_key	        Prefix for name of the keys into returned array
854	 *  @param  Translate		$outputlangs        Lang object to use for output
855	 *	@return	array								Substitution array
856	 */
857	public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs)
858	{
859		// phpcs:enable
860		global $conf;
861
862		if (is_array($extrafields->attributes[$object->table_element]['label'])) {
863			foreach ($extrafields->attributes[$object->table_element]['label'] as $key=>$label)
864			{
865				if ($extrafields->attributes[$object->table_element]['type'][$key] == 'price')
866				{
867					$object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]);
868					$object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency);
869					//Add value to store price with currency
870					$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency']));
871				} elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select')
872				{
873					$object->array_options['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]];
874				} elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') {
875					$valArray = explode(',', $object->array_options['options_'.$key]);
876					$output = array();
877					foreach ($extrafields->attributes[$object->table_element]['param'][$key]['options'] as $keyopt=>$valopt) {
878						if (in_array($keyopt, $valArray)) {
879							$output[] = $valopt;
880						}
881					}
882					$object->array_options['options_'.$key] = implode(', ', $output);
883				} elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'date')
884				{
885					if (strlen($object->array_options['options_'.$key]) > 0)
886					{
887						$date = $object->array_options['options_'.$key];
888						$object->array_options['options_'.$key] = dol_print_date($date, 'day'); // using company output language
889						$object->array_options['options_'.$key.'_locale'] = dol_print_date($date, 'day', 'tzserver', $outputlangs); // using output language format
890						$object->array_options['options_'.$key.'_rfc'] = dol_print_date($date, 'dayrfc'); // international format
891					} else {
892						$object->array_options['options_'.$key] = '';
893						$object->array_options['options_'.$key.'_locale'] = '';
894						$object->array_options['options_'.$key.'_rfc'] = '';
895					}
896					$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
897					$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
898				} elseif ($extrafields->attributes[$object->table_element]['label'][$key] == 'datetime')
899				{
900					$datetime = $object->array_options['options_'.$key];
901					$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
902					$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
903					$object->array_options['options_'.$key.'_rfc'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhourrfc') : ''); // international format
904					$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
905					$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
906				} elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'link')
907				{
908					$id = $object->array_options['options_'.$key];
909					if ($id != "")
910					{
911						$param = $extrafields->attributes[$object->table_element]['param'][$key];
912						$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
913						$InfoFieldList = explode(":", $param_list[0]);
914						$classname = $InfoFieldList[0];
915						$classpath = $InfoFieldList[1];
916						if (!empty($classpath))
917						{
918							dol_include_once($InfoFieldList[1]);
919							if ($classname && class_exists($classname))
920							{
921								$tmpobject = new $classname($this->db);
922								$tmpobject->fetch($id);
923								// completely replace the id with the linked object name
924								$object->array_options['options_'.$key] = $tmpobject->name;
925							}
926						}
927					}
928				}
929
930				$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
931			}
932		}
933
934		return $array_to_fill;
935	}
936
937
938	/**
939	 * Rect pdf
940	 *
941	 * @param	TCPDF	$pdf			Object PDF
942	 * @param	float	$x				Abscissa of first point
943	 * @param	float	$y		        Ordinate of first point
944	 * @param	float	$l				??
945	 * @param	float	$h				??
946	 * @param	int		$hidetop		1=Hide top bar of array and title, 0=Hide nothing, -1=Hide only title
947	 * @param	int		$hidebottom		Hide bottom
948	 * @return	void
949	 */
950	public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0)
951	{
952		if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y);
953		$pdf->line($x + $l, $y, $x + $l, $y + $h);
954		if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h);
955		$pdf->line($x, $y + $h, $x, $y);
956	}
957
958
959	/**
960	 *  uasort callback function to Sort columns fields
961	 *
962	 *  @param	array			$a    			PDF lines array fields configs
963	 *  @param	array			$b    			PDF lines array fields configs
964	 *  @return	int								Return compare result
965	 */
966	public function columnSort($a, $b)
967	{
968		if (empty($a['rank'])) { $a['rank'] = 0; }
969		if (empty($b['rank'])) { $b['rank'] = 0; }
970		if ($a['rank'] == $b['rank']) {
971			return 0;
972		}
973		return ($a['rank'] > $b['rank']) ? -1 : 1;
974	}
975
976	/**
977	 *   	Prepare Array Column Field
978	 *
979	 *   	@param	object			$object				common object
980	 *   	@param	Translate		$outputlangs		langs
981	 *      @param	int				$hidedetails		Do not show line details
982	 *      @param	int				$hidedesc			Do not show desc
983	 *      @param	int				$hideref			Do not show ref
984	 *      @return	null
985	 */
986	public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
987	{
988		global $conf;
989
990		$this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref);
991
992
993		// Sorting
994		uasort($this->cols, array($this, 'columnSort'));
995
996		// Positionning
997		$curX = $this->page_largeur - $this->marge_droite; // start from right
998
999		// Array width
1000		$arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche;
1001
1002		// Count flexible column
1003		$totalDefinedColWidth = 0;
1004		$countFlexCol = 0;
1005		foreach ($this->cols as $colKey =>& $colDef)
1006		{
1007			if (!$this->getColumnStatus($colKey)) continue; // continue if disabled
1008
1009			if (!empty($colDef['scale'])) {
1010				// In case of column width is defined by percentage
1011				$colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100);
1012			}
1013
1014			if (empty($colDef['width'])) {
1015				$countFlexCol++;
1016			} else {
1017				$totalDefinedColWidth += $colDef['width'];
1018			}
1019		}
1020
1021		foreach ($this->cols as $colKey =>& $colDef)
1022		{
1023			// setting empty conf with default
1024			if (!empty($colDef['title'])) {
1025				$colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']);
1026			} else {
1027				$colDef['title'] = $this->defaultTitlesFieldsStyle;
1028			}
1029
1030			// setting empty conf with default
1031			if (!empty($colDef['content'])) {
1032				$colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']);
1033			} else {
1034				$colDef['content'] = $this->defaultContentsFieldsStyle;
1035			}
1036
1037			if ($this->getColumnStatus($colKey))
1038			{
1039				// In case of flexible column
1040				if (empty($colDef['width'])) {
1041					$colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol;
1042				}
1043
1044				// Set positions
1045				$lastX = $curX;
1046				$curX = $lastX - $colDef['width'];
1047				$colDef['xStartPos'] = $curX;
1048				$colDef['xEndPos']   = $lastX;
1049			}
1050		}
1051	}
1052
1053	/**
1054	 *  get column content width from column key
1055	 *
1056	 *  @param	string      $colKey     the column key
1057	 *  @return	float                   width in mm
1058	 */
1059	public function getColumnContentWidth($colKey)
1060	{
1061		$colDef = $this->cols[$colKey];
1062		return  $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1];
1063	}
1064
1065
1066	/**
1067	 *  get column content X (abscissa) left position from column key
1068	 *
1069	 *  @param	string    $colKey    		the column key
1070	 *  @return	float      X position in mm
1071	 */
1072	public function getColumnContentXStart($colKey)
1073	{
1074		$colDef = $this->cols[$colKey];
1075		return  $colDef['xStartPos'] + $colDef['content']['padding'][3];
1076	}
1077
1078	/**
1079	 *   	get column position rank from column key
1080	 *
1081	 *   	@param	string		$colKey    		the column key
1082	 *      @return	int         rank on success and -1 on error
1083	 */
1084	public function getColumnRank($colKey)
1085	{
1086		if (!isset($this->cols[$colKey]['rank'])) return -1;
1087		return  $this->cols[$colKey]['rank'];
1088	}
1089
1090	/**
1091	 *  get column position rank from column key
1092	 *
1093	 *  @param	string		$newColKey    	the new column key
1094	 *  @param	array		$defArray    	a single column definition array
1095	 *  @param	string		$targetCol    	target column used to place the new column beside
1096	 *  @param	bool		$insertAfterTarget    	insert before or after target column ?
1097	 *  @return	int         new rank on success and -1 on error
1098	 */
1099	public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false)
1100	{
1101		// prepare wanted rank
1102		$rank = -1;
1103
1104		// try to get rank from target column
1105		if (!empty($targetCol)) {
1106			$rank = $this->getColumnRank($targetCol);
1107			if ($rank >= 0 && $insertAfterTarget) { $rank++; }
1108		}
1109
1110		// get rank from new column definition
1111		if ($rank < 0 && !empty($defArray['rank'])) {
1112			$rank = $defArray['rank'];
1113		}
1114
1115		// error: no rank
1116		if ($rank < 0) { return -1; }
1117
1118		foreach ($this->cols as $colKey =>& $colDef)
1119		{
1120			if ($rank <= $colDef['rank'])
1121			{
1122				$colDef['rank'] = $colDef['rank'] + 1;
1123			}
1124		}
1125
1126		$defArray['rank'] = $rank;
1127		$this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys
1128
1129		return $rank;
1130	}
1131
1132
1133	/**
1134	 *  print standard column content
1135	 *
1136	 *  @param	TCPDF		    $pdf    	pdf object
1137	 *  @param	float		$curY    	curent Y position
1138	 *  @param	string		$colKey    	the column key
1139	 *  @param	string		$columnText   column text
1140	 *  @return	null
1141	 */
1142	public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '')
1143	{
1144		global $hookmanager;
1145
1146		$parameters = array(
1147			'curY' => &$curY,
1148			'columnText' => $columnText,
1149			'colKey' => $colKey,
1150			'pdf' => &$pdf,
1151		);
1152		$reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook
1153		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1154		if (!$reshook)
1155		{
1156			if (empty($columnText)) return;
1157			$pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position
1158			$colDef = $this->cols[$colKey];
1159			// save curent cell padding
1160			$curentCellPaddinds = $pdf->getCellPaddings();
1161			// set cell padding with column content definition
1162			$pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]);
1163			$pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']);
1164
1165			// restore cell padding
1166			$pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
1167		}
1168	}
1169
1170
1171	/**
1172	 *  print description column content
1173	 *
1174	 *  @param	TCPDF		$pdf    	pdf object
1175	 *  @param	float		$curY    	curent Y position
1176	 *  @param	string		$colKey    	the column key
1177	 *  @param  object      $object CommonObject
1178	 *  @param  int         $i  the $object->lines array key
1179	 *  @param  Translate $outputlangs    Output language
1180	 *  @param  int $hideref hide ref
1181	 *  @param  int $hidedesc hide desc
1182	 *  @param  int $issupplierline if object need supplier product
1183	 *  @return null
1184	 */
1185	public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0)
1186	{
1187		// load desc col params
1188		$colDef = $this->cols[$colKey];
1189		// save curent cell padding
1190		$curentCellPaddinds = $pdf->getCellPaddings();
1191		// set cell padding with column content definition
1192		$pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]);
1193
1194		// line description
1195		pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline);
1196		$posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0];
1197
1198		// restore cell padding
1199		$pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
1200
1201		// Display extrafield if needed
1202		$params = array(
1203			'display'         => 'list',
1204			'printableEnable' => array(3),
1205			'printableEnableNotEmpty' => array(4)
1206		);
1207		$extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params);
1208		if (!empty($extrafieldDesc)) {
1209			$this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc);
1210		}
1211	}
1212
1213	/**
1214	 *  get extrafield content for pdf writeHtmlCell compatibility
1215	 *  usage for PDF line columns and object note block
1216	 *
1217	 *  @param	object		$object     common object
1218	 *  @param	string		$extrafieldKey    	the extrafield key
1219	 *  @return	string
1220	 */
1221	public function getExtrafieldContent($object, $extrafieldKey)
1222	{
1223		global $hookmanager;
1224
1225		if (empty($object->table_element)) { return; }
1226
1227		$extrafieldsKeyPrefix = "options_";
1228
1229		// Cleanup extrafield key to remove prefix if present
1230		$pos = strpos($extrafieldKey, $extrafieldsKeyPrefix);
1231		if ($pos === 0) {
1232			$extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix));
1233		}
1234
1235		$extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey;
1236
1237
1238		// Load extrafiels if not allready does
1239		if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
1240		if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
1241		$extrafields = $this->extrafieldsCache;
1242
1243		$extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element);
1244
1245		// 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 ...
1246		if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') {
1247			// for lack of anything better we cleanup all html tags
1248			$extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent);
1249		}
1250
1251		$parameters = array(
1252			'object' => $object,
1253			'extrafields' => $extrafields,
1254			'extrafieldKey' => $extrafieldKey,
1255			'extrafieldOutputContent' =>& $extrafieldOutputContent
1256		);
1257		$reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook
1258		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1259		if ($reshook)
1260		{
1261			$extrafieldOutputContent = $hookmanager->resPrint;
1262		}
1263
1264		return $extrafieldOutputContent;
1265	}
1266
1267
1268	/**
1269	 *  display extrafields columns content
1270	 *
1271	 *  @param	object		$object    	line of common object
1272	 *  @param Translate $outputlangs    Output language
1273	 *  @param array $params    array of additionals parameters
1274	 *  @return	double  max y value
1275	 */
1276	public function getExtrafieldsInHtml($object, $outputlangs, $params = array())
1277	{
1278		global $hookmanager;
1279
1280		if (empty($object->table_element)) {
1281			return;
1282		}
1283
1284		// Load extrafiels if not allready does
1285		if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
1286		if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
1287		$extrafields = $this->extrafieldsCache;
1288
1289		$defaultParams = array(
1290			'style'         => '',
1291			'display'         => 'auto', // auto, table, list
1292			'printableEnable' => array(1),
1293			'printableEnableNotEmpty' => array(2),
1294
1295			'table'         => array(
1296				'maxItemsInRow' => 2,
1297				'cellspacing'   => 0,
1298				'cellpadding'   => 0,
1299				'border'        => 0,
1300				'labelcolwidth' => '25%',
1301				'arrayOfLineBreakType' => array('text', 'html')
1302			),
1303
1304			'list'         => array(
1305				'separator' => '<br/>'
1306			),
1307
1308			'auto'         => array(
1309				'list' => 0, // 0 for default
1310				'table' => 4 // if there more than x extrafield to display
1311			),
1312		);
1313
1314		$params = $params + $defaultParams;
1315
1316
1317		/**
1318		 * @var $extrafields ExtraFields
1319		 */
1320
1321		$html = '';
1322		$fields = array();
1323
1324		if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label'])) {
1325			foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label)
1326			{
1327				// Enable extrafield ?
1328				$enabled = 0;
1329				$disableOnEmpty = 0;
1330				if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
1331					$printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
1332					if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) {
1333						$enabled = 1;
1334					}
1335
1336					if (in_array($printable, $params['printableEnableNotEmpty'])) {
1337						$disableOnEmpty = 1;
1338					}
1339				}
1340
1341				if (empty($enabled)) {
1342					continue;
1343				}
1344
1345				$field = new stdClass();
1346				$field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]);
1347				$field->content = $this->getExtrafieldContent($object, $key);
1348				$field->label = $outputlangs->transnoentities($label);
1349				$field->type = $extrafields->attributes[$object->table_element]['type'][$key];
1350
1351				// dont display if empty
1352				if ($disableOnEmpty && empty($field->content)) {
1353					continue;
1354				}
1355
1356				$fields[] = $field;
1357			}
1358		}
1359
1360		if (!empty($fields))
1361		{
1362			// Sort extrafields by rank
1363			uasort($fields, function ($a, $b) {
1364				return  ($a->rank > $b->rank) ? 1 : -1;
1365			});
1366
1367			// define some HTML content with style
1368			$html .= !empty($params['style']) ? '<style>'.$params['style'].'</style>' : '';
1369
1370			// auto select display format
1371			if ($params['display'] == 'auto') {
1372				$lastNnumbItems = 0;
1373				foreach ($params['auto'] as $display => $numbItems) {
1374					if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) {
1375						$lastNnumbItems = $numbItems;
1376						$params['display'] = $display;
1377					}
1378				}
1379			}
1380
1381			if ($params['display'] == 'list') {
1382				// Display in list format
1383				$i = 0;
1384				foreach ($fields as $field) {
1385					$html .= !empty($i) ? $params['list']['separator'] : '';
1386					$html .= '<strong>'.$field->label.' : </strong>';
1387					$html .= $field->content;
1388					$i++;
1389				}
1390			} elseif ($params['display'] == 'table') {
1391				// Display in table format
1392				$html .= '<table class="extrafield-table" cellspacing="'.$params['table']['cellspacing'].'" cellpadding="'.$params['table']['cellpadding'].'" border="'.$params['table']['border'].'">';
1393
1394				$html .= "<tr>";
1395				$itemsInRow = 0;
1396				$maxItemsInRow = $params['table']['maxItemsInRow'];
1397				foreach ($fields as $field) {
1398					//$html.= !empty($html)?'<br/>':'';
1399					if ($itemsInRow >= $maxItemsInRow) {
1400						// start a new line
1401						$html .= "</tr><tr>";
1402						$itemsInRow = 0;
1403					}
1404
1405					// for some type we need line break
1406					if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) {
1407						if ($itemsInRow > 0) {
1408							// close table row and empty cols
1409							for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) {
1410								$html .= "<td></td><td></td>";
1411							}
1412							$html .= "</tr>";
1413
1414							// start a new line
1415							$html .= "<tr>";
1416						}
1417
1418						$itemsInRow = $maxItemsInRow;
1419						$html .= '<td colspan="'.($maxItemsInRow * 2 - 1).'">';
1420						$html .= '<strong>'.$field->label.' :</strong> ';
1421						$html .= $field->content;
1422						$html .= "</td>";
1423					} else {
1424						$itemsInRow++;
1425						$html .= '<td width="'.$params['table']['labelcolwidth'].'" class="extrafield-label">';
1426						$html .= '<strong>'.$field->label.' :</strong>';
1427						$html .= "</td>";
1428
1429
1430						$html .= '<td  class="extrafield-content">';
1431						$html .= $field->content;
1432						$html .= "</td>";
1433					}
1434				}
1435				$html .= "</tr>";
1436
1437				$html .= '</table>';
1438			}
1439		}
1440
1441		return $html;
1442	}
1443
1444
1445	/**
1446	 *  get column status from column key
1447	 *
1448	 *  @param	string			$colKey    		the column key
1449	 *  @return	float      width in mm
1450	 */
1451	public function getColumnStatus($colKey)
1452	{
1453		if (!empty($this->cols[$colKey]['status'])) {
1454			return true;
1455		} else return  false;
1456	}
1457
1458	/**
1459	 * Print standard column content
1460	 *
1461	 * @param TCPDI	    $pdf            Pdf object
1462	 * @param float     $tab_top        Tab top position
1463	 * @param float     $tab_height     Default tab height
1464	 * @param Translate $outputlangs    Output language
1465	 * @param int       $hidetop        Hide top
1466	 * @return float                    Height of col tab titles
1467	 */
1468	public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0)
1469	{
1470		global $hookmanager, $conf;
1471
1472		foreach ($this->cols as $colKey => $colDef) {
1473			$parameters = array(
1474				'colKey' => $colKey,
1475				'pdf' => $pdf,
1476				'outputlangs' => $outputlangs,
1477				'tab_top' => $tab_top,
1478				'tab_height' => $tab_height,
1479				'hidetop' => $hidetop
1480			);
1481
1482			$reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook
1483			if ($reshook < 0) {
1484				setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1485			} elseif (empty($reshook)) {
1486				if (!$this->getColumnStatus($colKey)) continue;
1487
1488				// get title label
1489				$colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']);
1490
1491				// Add column separator
1492				if (!empty($colDef['border-left'])) {
1493					$pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height);
1494				}
1495
1496				if (empty($hidetop)) {
1497					// save curent cell padding
1498					$curentCellPaddinds = $pdf->getCellPaddings();
1499
1500					// Add space for lines (more if we need to show a second alternative language)
1501					global $outputlangsbis;
1502					if (is_object($outputlangsbis)) {
1503						// set cell padding with column title definition
1504						$pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5);
1505					} else {
1506						// set cell padding with column title definition
1507						$pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
1508					}
1509
1510					$pdf->SetXY($colDef['xStartPos'], $tab_top);
1511					$textWidth = $colDef['width'];
1512					$pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']);
1513
1514					// Add variant of translation if $outputlangsbis is an object
1515					if (is_object($outputlangsbis) && trim($colDef['title']['label'])) {
1516						$pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
1517						$pdf->SetXY($colDef['xStartPos'], $pdf->GetY());
1518						$textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']);
1519						$pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']);
1520					}
1521
1522					$this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight);
1523
1524					// restore cell padding
1525					$pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
1526				}
1527			}
1528		}
1529
1530		return $this->tabTitleHeight;
1531	}
1532
1533
1534
1535	/**
1536	 *  Define Array Column Field for extrafields
1537	 *
1538	 *  @param	object			$object    		common object det
1539	 *  @param	Translate		$outputlangs    langs
1540	 *  @param	int			   $hidedetails		Do not show line details
1541	 *  @return	null
1542	 */
1543	public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0)
1544	{
1545		global $conf;
1546
1547		if (!empty($hidedetails)) {
1548			return;
1549		}
1550
1551		if (empty($object->table_element)) {
1552			return;
1553		}
1554
1555		// Load extrafiels if not allready does
1556		if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
1557		if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
1558		$extrafields = $this->extrafieldsCache;
1559
1560
1561		if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) {
1562			foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label)
1563			{
1564				// Dont display separator yet even is set to be displayed (not compatible yet)
1565				if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate')
1566				{
1567					continue;
1568				}
1569
1570				// Enable extrafield ?
1571				$enabled = 0;
1572				if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
1573					$printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
1574					if ($printable === 1 || $printable === 2) {
1575						$enabled = 1;
1576					}
1577					// Note : if $printable === 3 or 4 so, it's displayed after line description not in cols
1578				}
1579
1580				if (!$enabled) { continue; } // don't wast resourses if we don't need them...
1581
1582				// Load language if required
1583				if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]);
1584
1585				// TODO : add more extrafield customisation capacities for PDF like width, rank...
1586
1587				// set column definition
1588				$def = array(
1589					'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]),
1590					'width' => 25, // in mm
1591					'status' => boolval($enabled),
1592					'title' => array(
1593						'label' => $outputlangs->transnoentities($label)
1594					),
1595					'content' => array(
1596						'align' => 'C'
1597					),
1598					'border-left' => true, // add left line separator
1599				);
1600
1601				$alignTypeRight = array('double', 'int', 'price');
1602				if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) {
1603					$def['content']['align'] = 'R';
1604				}
1605
1606				$alignTypeLeft = array('text', 'html');
1607				if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) {
1608					$def['content']['align'] = 'L';
1609				}
1610
1611
1612				// for extrafields we use rank of extrafield to place it on PDF
1613				$this->insertNewColumnDef("options_".$key, $def);
1614			}
1615		}
1616	}
1617}
1618