commondocgenerator.class.php 67 KB

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