extrafields.class.php 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. <?php
  2. /* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  5. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  6. * Copyright (C) 2009-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  7. * Copyright (C) 2009-2012 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2013 Florian Henry <forian.henry@open-concept.pro>
  9. * Copyright (C) 2015 Charles-Fr BENKE <charles.fr@benke.fr>
  10. * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  11. * Copyright (C) 2017 Nicolas ZABOURI <info@inovea-conseil.com>
  12. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  26. */
  27. /**
  28. * \file htdocs/core/class/extrafields.class.php
  29. * \ingroup core
  30. * \brief File of class to manage extra fields
  31. */
  32. /**
  33. * Class to manage standard extra fields
  34. */
  35. class ExtraFields
  36. {
  37. /**
  38. * @var DoliDB Database handler.
  39. */
  40. public $db;
  41. /**
  42. * @var array Array with type of element (for what object is the extrafield)
  43. * @deprecated
  44. */
  45. public $attribute_elementtype;
  46. /**
  47. * @var array Array with type of the extra field
  48. * @deprecated
  49. */
  50. public $attribute_type;
  51. /**
  52. * @var array Array with label of extra field
  53. * @deprecated
  54. */
  55. public $attribute_label;
  56. /**
  57. * @var array Array with size of extra field
  58. * @deprecated
  59. */
  60. public $attribute_size;
  61. /**
  62. * @var array Array with list of possible values for some types of extra fields
  63. * @deprecated
  64. */
  65. public $attribute_choice;
  66. /**
  67. * @var array Array to store compute formula for computed fields
  68. * @deprecated
  69. */
  70. public $attribute_computed;
  71. /**
  72. * @var array Array to store default value
  73. * @deprecated
  74. */
  75. public $attribute_default;
  76. /**
  77. * @var array Array to store if attribute is unique or not
  78. * @deprecated
  79. */
  80. public $attribute_unique;
  81. /**
  82. * @var array Array to store if attribute is required or not
  83. * @deprecated
  84. */
  85. public $attribute_required;
  86. /**
  87. * @var array Array to store parameters of attribute (used in select type)
  88. * @deprecated
  89. */
  90. public $attribute_param;
  91. /**
  92. * @var array Array to store position of attribute
  93. * @deprecated
  94. */
  95. public $attribute_pos;
  96. /**
  97. * @var array Array to store if attribute is editable regardless of the document status
  98. * @deprecated
  99. */
  100. public $attribute_alwayseditable;
  101. /**
  102. * @var array Array to store permission to check
  103. * @deprecated
  104. */
  105. public $attribute_perms;
  106. /**
  107. * @var array Array to store language file to translate label of values
  108. * @deprecated
  109. */
  110. public $attribute_langfile;
  111. /**
  112. * @var array Array to store if field is visible by default on list
  113. * @deprecated
  114. */
  115. public $attribute_list;
  116. /**
  117. * @var array Array to store if field is summable
  118. * @deprecated
  119. */
  120. public $attribute_totalizable;
  121. /**
  122. * @var array Array to store entity id of extrafield
  123. * @deprecated
  124. */
  125. public $attribute_entityid;
  126. /**
  127. * @var array New array to store extrafields definition
  128. */
  129. public $attributes;
  130. /**
  131. * @var string Error code (or message)
  132. */
  133. public $error = '';
  134. /**
  135. * @var string[] Array of Error code (or message)
  136. */
  137. public $errors = array();
  138. /**
  139. * @var string DB Error number
  140. */
  141. public $errno;
  142. public static $type2label = array(
  143. 'varchar'=>'String1Line',
  144. 'text'=>'TextLongNLines',
  145. 'html'=>'HtmlText',
  146. 'int'=>'Int',
  147. 'double'=>'Float',
  148. 'date'=>'Date',
  149. 'datetime'=>'DateAndTime',
  150. 'boolean'=>'Boolean',
  151. 'price'=>'ExtrafieldPrice',
  152. 'phone'=>'ExtrafieldPhone',
  153. 'mail'=>'ExtrafieldMail',
  154. 'url'=>'ExtrafieldUrl',
  155. 'password' => 'ExtrafieldPassword',
  156. 'select' => 'ExtrafieldSelect',
  157. 'sellist' => 'ExtrafieldSelectList',
  158. 'radio' => 'ExtrafieldRadio',
  159. 'checkbox' => 'ExtrafieldCheckBox',
  160. 'chkbxlst' => 'ExtrafieldCheckBoxFromList',
  161. 'link' => 'ExtrafieldLink',
  162. 'separate' => 'ExtrafieldSeparator',
  163. );
  164. /**
  165. * Constructor
  166. *
  167. * @param DoliDB $db Database handler
  168. */
  169. public function __construct($db)
  170. {
  171. $this->db = $db;
  172. $this->error = '';
  173. $this->errors = array();
  174. $this->attributes = array();
  175. // For old usage
  176. $this->attribute_elementtype = array();
  177. $this->attribute_type = array();
  178. $this->attribute_label = array();
  179. $this->attribute_size = array();
  180. $this->attribute_computed = array();
  181. $this->attribute_default = array();
  182. $this->attribute_unique = array();
  183. $this->attribute_required = array();
  184. $this->attribute_perms = array();
  185. $this->attribute_langfile = array();
  186. $this->attribute_list = array();
  187. }
  188. /**
  189. * Add a new extra field parameter
  190. *
  191. * @param string $attrname Code of attribute
  192. * @param string $label label of attribute
  193. * @param string $type Type of attribute ('boolean','int','varchar','text','html','date','datehour','price','phone','mail','password','url','select','checkbox','separate',...)
  194. * @param int $pos Position of attribute
  195. * @param string $size Size/length definition of attribute ('5', '24,8', ...). For float, it contains 2 numeric separated with a comma.
  196. * @param string $elementtype Element type. Same value than object->table_element (Example 'member', 'product', 'thirdparty', ...)
  197. * @param int $unique Is field unique or not
  198. * @param int $required Is field required or not
  199. * @param string $default_value Defaulted value (In database. use the default_value feature for default value on screen. Example: '', '0', 'null', 'avalue')
  200. * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
  201. * @param int $alwayseditable Is attribute always editable regardless of the document status
  202. * @param string $perms Permission to check
  203. * @param string $list Visibilty ('0'=never visible, '1'=visible on list+forms, '2'=list only, '3'=form only or 'eval string')
  204. * @param string $help Text with help tooltip
  205. * @param string $computed Computed value
  206. * @param string $entity Entity of extrafields (for multicompany modules)
  207. * @param string $langfile Language file
  208. * @param string $enabled Condition to have the field enabled or not
  209. * @param int $totalizable Is a measure. Must show a total on lists
  210. * @param int $printable Is extrafield displayed on PDF
  211. * @return int <=0 if KO, >0 if OK
  212. */
  213. public function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique = 0, $required = 0, $default_value = '', $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0)
  214. {
  215. if (empty($attrname)) {
  216. return -1;
  217. }
  218. if (empty($label)) {
  219. return -1;
  220. }
  221. if ($type == 'separate') {
  222. $unique = 0;
  223. $required = 0;
  224. } // Force unique and not required if this is a separator field to avoid troubles.
  225. if ($elementtype == 'thirdparty') {
  226. $elementtype = 'societe';
  227. }
  228. if ($elementtype == 'contact') {
  229. $elementtype = 'socpeople';
  230. }
  231. // Create field into database except for separator type which is not stored in database
  232. if ($type != 'separate') {
  233. $result = $this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help);
  234. }
  235. $err1 = $this->errno;
  236. if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate') {
  237. // Add declaration of field into table
  238. $result2 = $this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled, $totalizable, $printable);
  239. $err2 = $this->errno;
  240. if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS')) {
  241. $this->error = '';
  242. $this->errno = 0;
  243. return 1;
  244. } else {
  245. return -2;
  246. }
  247. } else {
  248. return -1;
  249. }
  250. }
  251. /**
  252. * Add a new optional attribute.
  253. * This is a private method. For public method, use addExtraField.
  254. *
  255. * @param string $attrname code of attribute
  256. * @param int $type Type of attribute ('boolean', 'int', 'varchar', 'text', 'html', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...)
  257. * @param string $length Size/length of attribute ('5', '24,8', ...)
  258. * @param string $elementtype Element type ('member', 'product', 'thirdparty', 'contact', ...)
  259. * @param int $unique Is field unique or not
  260. * @param int $required Is field required or not
  261. * @param string $default_value Default value for field (in database)
  262. * @param array $param Params for field (ex for select list : array('options'=>array('value'=>'label of option'))
  263. * @param string $perms Permission
  264. * @param string $list Into list view by default
  265. * @param string $computed Computed value
  266. * @param string $help Help on tooltip
  267. * @return int <=0 if KO, >0 if OK
  268. */
  269. private function create($attrname, $type = 'varchar', $length = 255, $elementtype = 'member', $unique = 0, $required = 0, $default_value = '', $param = '', $perms = '', $list = '0', $computed = '', $help = '')
  270. {
  271. if ($elementtype == 'thirdparty') {
  272. $elementtype = 'societe';
  273. }
  274. if ($elementtype == 'contact') {
  275. $elementtype = 'socpeople';
  276. }
  277. $table = $elementtype.'_extrafields';
  278. if ($elementtype == 'categorie') {
  279. $table = 'categories_extrafields';
  280. }
  281. if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/", $attrname) && !is_numeric($attrname)) {
  282. if ($type == 'boolean') {
  283. $typedb = 'int';
  284. $lengthdb = '1';
  285. } elseif ($type == 'price') {
  286. $typedb = 'double';
  287. $lengthdb = '24,8';
  288. } elseif ($type == 'phone') {
  289. $typedb = 'varchar';
  290. $lengthdb = '20';
  291. } elseif ($type == 'mail') {
  292. $typedb = 'varchar';
  293. $lengthdb = '128';
  294. } elseif ($type == 'url') {
  295. $typedb = 'varchar';
  296. $lengthdb = '255';
  297. } elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) {
  298. $typedb = 'varchar';
  299. $lengthdb = '255';
  300. } elseif ($type == 'link') {
  301. $typedb = 'int';
  302. $lengthdb = '11';
  303. } elseif ($type == 'html') {
  304. $typedb = 'text';
  305. $lengthdb = $length;
  306. } elseif ($type == 'password') {
  307. $typedb = 'varchar';
  308. $lengthdb = '128';
  309. } else {
  310. $typedb = $type;
  311. $lengthdb = $length;
  312. if ($type == 'varchar' && empty($lengthdb)) {
  313. $lengthdb = '255';
  314. }
  315. }
  316. $field_desc = array(
  317. 'type'=>$typedb,
  318. 'value'=>$lengthdb,
  319. 'null'=>($required ? 'NOT NULL' : 'NULL'),
  320. 'default' => $default_value
  321. );
  322. $result = $this->db->DDLAddField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
  323. if ($result > 0) {
  324. if ($unique) {
  325. $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
  326. $resql = $this->db->query($sql, 1, 'dml');
  327. }
  328. return 1;
  329. } else {
  330. $this->error = $this->db->lasterror();
  331. $this->errno = $this->db->lasterrno();
  332. return -1;
  333. }
  334. } else {
  335. return 0;
  336. }
  337. }
  338. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  339. /**
  340. * Add description of a new optional attribute
  341. *
  342. * @param string $attrname code of attribute
  343. * @param string $label label of attribute
  344. * @param int $type Type of attribute ('int', 'varchar', 'text', 'html', 'date', 'datehour', 'float')
  345. * @param int $pos Position of attribute
  346. * @param string $size Size/length of attribute ('5', '24,8', ...)
  347. * @param string $elementtype Element type ('member', 'product', 'thirdparty', ...)
  348. * @param int $unique Is field unique or not
  349. * @param int $required Is field required or not
  350. * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
  351. * @param int $alwayseditable Is attribute always editable regardless of the document status
  352. * @param string $perms Permission to check
  353. * @param string $list Visibily
  354. * @param string $help Help on tooltip
  355. * @param string $default Default value (in database. use the default_value feature for default value on screen).
  356. * @param string $computed Computed value
  357. * @param string $entity Entity of extrafields
  358. * @param string $langfile Language file
  359. * @param string $enabled Condition to have the field enabled or not
  360. * @param int $totalizable Is a measure. Must show a total on lists
  361. * @param int $printable Is extrafield displayed on PDF
  362. * @return int <=0 if KO, >0 if OK
  363. * @throws Exception
  364. */
  365. private function create_label($attrname, $label = '', $type = '', $pos = 0, $size = 0, $elementtype = 'member', $unique = 0, $required = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0)
  366. {
  367. // phpcs:enable
  368. global $conf, $user;
  369. if ($elementtype == 'thirdparty') {
  370. $elementtype = 'societe';
  371. }
  372. if ($elementtype == 'contact') {
  373. $elementtype = 'socpeople';
  374. }
  375. // Clean parameters
  376. if (empty($pos)) {
  377. $pos = 0;
  378. }
  379. if (empty($list)) {
  380. $list = '0';
  381. }
  382. if (empty($required)) {
  383. $required = 0;
  384. }
  385. if (empty($unique)) {
  386. $unique = 0;
  387. }
  388. if (empty($printable)) {
  389. $printable = 0;
  390. }
  391. if (empty($alwayseditable)) {
  392. $alwayseditable = 0;
  393. }
  394. if (empty($totalizable)) {
  395. $totalizable = 0;
  396. }
  397. if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname) && !is_numeric($attrname)) {
  398. if (is_array($param) && count($param) > 0) {
  399. $params = serialize($param);
  400. } elseif (strlen($param) > 0) {
  401. $params = trim($param);
  402. } else {
  403. $params = '';
  404. }
  405. $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
  406. $sql .= " name,";
  407. $sql .= " label,";
  408. $sql .= " type,";
  409. $sql .= " pos,";
  410. $sql .= " size,";
  411. $sql .= " entity,";
  412. $sql .= " elementtype,";
  413. $sql .= " fieldunique,";
  414. $sql .= " fieldrequired,";
  415. $sql .= " param,";
  416. $sql .= " alwayseditable,";
  417. $sql .= " perms,";
  418. $sql .= " langs,";
  419. $sql .= " list,";
  420. $sql .= " printable,";
  421. $sql .= " fielddefault,";
  422. $sql .= " fieldcomputed,";
  423. $sql .= " fk_user_author,";
  424. $sql .= " fk_user_modif,";
  425. $sql .= " datec,";
  426. $sql .= " enabled,";
  427. $sql .= " help,";
  428. $sql .= " totalizable";
  429. $sql .= " )";
  430. $sql .= " VALUES('".$this->db->escape($attrname)."',";
  431. $sql .= " '".$this->db->escape($label)."',";
  432. $sql .= " '".$this->db->escape($type)."',";
  433. $sql .= " ".((int) $pos).",";
  434. $sql .= " '".$this->db->escape($size)."',";
  435. $sql .= " ".($entity === '' ? $conf->entity : $entity).",";
  436. $sql .= " '".$this->db->escape($elementtype)."',";
  437. $sql .= " ".((int) $unique).",";
  438. $sql .= " ".((int) $required).",";
  439. $sql .= " '".$this->db->escape($params)."',";
  440. $sql .= " ".((int) $alwayseditable).",";
  441. $sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").",";
  442. $sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").",";
  443. $sql .= " '".$this->db->escape($list)."',";
  444. $sql .= " '".$this->db->escape($printable)."',";
  445. $sql .= " ".($default ? "'".$this->db->escape($default)."'" : "null").",";
  446. $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").",";
  447. $sql .= " ".(is_object($user) ? $user->id : 0).",";
  448. $sql .= " ".(is_object($user) ? $user->id : 0).",";
  449. $sql .= "'".$this->db->idate(dol_now())."',";
  450. $sql .= " ".($enabled ? "'".$this->db->escape($enabled)."'" : "1").",";
  451. $sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null").",";
  452. $sql .= " ".($totalizable ? 'TRUE' : 'FALSE');
  453. $sql .= ')';
  454. dol_syslog(get_class($this)."::create_label", LOG_DEBUG);
  455. if ($this->db->query($sql)) {
  456. return 1;
  457. } else {
  458. $this->error = $this->db->lasterror();
  459. $this->errno = $this->db->lasterrno();
  460. return -1;
  461. }
  462. }
  463. }
  464. /**
  465. * Delete an optional attribute
  466. *
  467. * @param string $attrname Code of attribute to delete
  468. * @param string $elementtype Element type ('member', 'product', 'thirdparty', 'contact', ...)
  469. * @return int < 0 if KO, 0 if nothing is done, 1 if OK
  470. */
  471. public function delete($attrname, $elementtype = 'member')
  472. {
  473. if ($elementtype == 'thirdparty') {
  474. $elementtype = 'societe';
  475. }
  476. if ($elementtype == 'contact') {
  477. $elementtype = 'socpeople';
  478. }
  479. $table = $elementtype.'_extrafields';
  480. if ($elementtype == 'categorie') {
  481. $table = 'categories_extrafields';
  482. }
  483. $error = 0;
  484. if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) {
  485. $result = $this->delete_label($attrname, $elementtype);
  486. if ($result < 0) {
  487. $this->error = $this->db->lasterror();
  488. $this->errors[] = $this->db->lasterror();
  489. $error++;
  490. }
  491. if (!$error) {
  492. $sql = "SELECT COUNT(rowid) as nb";
  493. $sql .= " FROM ".MAIN_DB_PREFIX."extrafields";
  494. $sql .= " WHERE elementtype = '".$this->db->escape($elementtype)."'";
  495. $sql .= " AND name = '".$this->db->escape($attrname)."'";
  496. //$sql.= " AND entity IN (0,".$conf->entity.")"; Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table
  497. $resql = $this->db->query($sql);
  498. if ($resql) {
  499. $obj = $this->db->fetch_object($resql);
  500. if ($obj->nb <= 0) {
  501. $result = $this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key
  502. if ($result < 0) {
  503. $this->error = $this->db->lasterror();
  504. $this->errors[] = $this->db->lasterror();
  505. $error++;
  506. }
  507. }
  508. }
  509. }
  510. return $result;
  511. } else {
  512. return 0;
  513. }
  514. }
  515. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  516. /**
  517. * Delete description of an optional attribute
  518. *
  519. * @param string $attrname Code of attribute to delete
  520. * @param string $elementtype Element type ('member', 'product', 'thirdparty', ...)
  521. * @return int < 0 if KO, 0 if nothing is done, 1 if OK
  522. */
  523. private function delete_label($attrname, $elementtype = 'member')
  524. {
  525. // phpcs:enable
  526. global $conf;
  527. if ($elementtype == 'thirdparty') {
  528. $elementtype = 'societe';
  529. }
  530. if ($elementtype == 'contact') {
  531. $elementtype = 'socpeople';
  532. }
  533. if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) {
  534. $sql = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
  535. $sql .= " WHERE name = '".$this->db->escape($attrname)."'";
  536. $sql .= " AND entity IN (0,".$conf->entity.')';
  537. $sql .= " AND elementtype = '".$this->db->escape($elementtype)."'";
  538. dol_syslog(get_class($this)."::delete_label", LOG_DEBUG);
  539. $resql = $this->db->query($sql);
  540. if ($resql) {
  541. return 1;
  542. } else {
  543. dol_print_error($this->db);
  544. return -1;
  545. }
  546. } else {
  547. return 0;
  548. }
  549. }
  550. /**
  551. * Modify type of a personalized attribute
  552. *
  553. * @param string $attrname Name of attribute
  554. * @param string $label Label of attribute
  555. * @param string $type Type of attribute ('boolean', 'int', 'varchar', 'text', 'html', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...)
  556. * @param int $length Length of attribute
  557. * @param string $elementtype Element type ('member', 'product', 'thirdparty', 'contact', ...)
  558. * @param int $unique Is field unique or not
  559. * @param int $required Is field required or not
  560. * @param int $pos Position of attribute
  561. * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
  562. * @param int $alwayseditable Is attribute always editable regardless of the document status
  563. * @param string $perms Permission to check
  564. * @param string $list Visibility
  565. * @param string $help Help on tooltip
  566. * @param string $default Default value (in database. use the default_value feature for default value on screen).
  567. * @param string $computed Computed value
  568. * @param string $entity Entity of extrafields
  569. * @param string $langfile Language file
  570. * @param string $enabled Condition to have the field enabled or not
  571. * @param int $totalizable Is extrafield totalizable on list
  572. * @param int $printable Is extrafield displayed on PDF
  573. * @return int >0 if OK, <=0 if KO
  574. * @throws Exception
  575. */
  576. public function update($attrname, $label, $type, $length, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0)
  577. {
  578. global $hookmanager;
  579. if ($elementtype == 'thirdparty') {
  580. $elementtype = 'societe';
  581. }
  582. if ($elementtype == 'contact') {
  583. $elementtype = 'socpeople';
  584. }
  585. $table = $elementtype.'_extrafields';
  586. if ($elementtype == 'categorie') {
  587. $table = 'categories_extrafields';
  588. }
  589. if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) {
  590. if ($type == 'boolean') {
  591. $typedb = 'int';
  592. $lengthdb = '1';
  593. } elseif ($type == 'price') {
  594. $typedb = 'double';
  595. $lengthdb = '24,8';
  596. } elseif ($type == 'phone') {
  597. $typedb = 'varchar';
  598. $lengthdb = '20';
  599. } elseif ($type == 'mail') {
  600. $typedb = 'varchar';
  601. $lengthdb = '128';
  602. } elseif ($type == 'url') {
  603. $typedb = 'varchar';
  604. $lengthdb = '255';
  605. } elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) {
  606. $typedb = 'varchar';
  607. $lengthdb = '255';
  608. } elseif ($type == 'html') {
  609. $typedb = 'text';
  610. } elseif ($type == 'link') {
  611. $typedb = 'int';
  612. $lengthdb = '11';
  613. } elseif ($type == 'password') {
  614. $typedb = 'varchar';
  615. $lengthdb = '50';
  616. } else {
  617. $typedb = $type;
  618. $lengthdb = $length;
  619. }
  620. $field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required ? 'NOT NULL' : 'NULL'), 'default'=>$default);
  621. if (is_object($hookmanager)) {
  622. $hookmanager->initHooks(array('extrafieldsdao'));
  623. $parameters = array('field_desc'=>&$field_desc, 'table'=>$table, 'attr_name'=>$attrname, 'label'=>$label, 'type'=>$type, 'length'=>$length, 'unique'=>$unique, 'required'=>$required, 'pos'=>$pos, 'param'=>$param, 'alwayseditable'=>$alwayseditable, 'perms'=>$perms, 'list'=>$list, 'help'=>$help, 'default'=>$default, 'computed'=>$computed, 'entity'=>$entity, 'langfile'=>$langfile, 'enabled'=>$enabled, 'totalizable'=>$totalizable, 'printable'=>$printable);
  624. $reshook = $hookmanager->executeHooks('updateExtrafields', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  625. if ($reshook < 0) {
  626. $this->error = $this->db->lasterror();
  627. return -1;
  628. }
  629. }
  630. if ($type != 'separate') { // No table update when separate type
  631. $result = $this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
  632. }
  633. if ($result > 0 || $type == 'separate') {
  634. if ($label) {
  635. $result = $this->update_label($attrname, $label, $type, $length, $elementtype, $unique, $required, $pos, $param, $alwayseditable, $perms, $list, $help, $default, $computed, $entity, $langfile, $enabled, $totalizable, $printable);
  636. }
  637. if ($result > 0) {
  638. $sql = '';
  639. if ($unique) {
  640. $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
  641. } else {
  642. $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname;
  643. }
  644. dol_syslog(get_class($this).'::update', LOG_DEBUG);
  645. $resql = $this->db->query($sql, 1, 'dml');
  646. return 1;
  647. } else {
  648. $this->error = $this->db->lasterror();
  649. return -1;
  650. }
  651. } else {
  652. $this->error = $this->db->lasterror();
  653. return -1;
  654. }
  655. } else {
  656. return 0;
  657. }
  658. }
  659. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  660. /**
  661. * Modify description of personalized attribute
  662. *
  663. * @param string $attrname Name of attribute
  664. * @param string $label Label of attribute
  665. * @param string $type Type of attribute
  666. * @param int $size Length of attribute
  667. * @param string $elementtype Element type ('member', 'product', 'thirdparty', ...)
  668. * @param int $unique Is field unique or not
  669. * @param int $required Is field required or not
  670. * @param int $pos Position of attribute
  671. * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
  672. * @param int $alwayseditable Is attribute always editable regardless of the document status
  673. * @param string $perms Permission to check
  674. * @param string $list Visiblity
  675. * @param string $help Help on tooltip.
  676. * @param string $default Default value (in database. use the default_value feature for default value on screen).
  677. * @param string $computed Computed value
  678. * @param string $entity Entity of extrafields
  679. * @param string $langfile Language file
  680. * @param string $enabled Condition to have the field enabled or not
  681. * @param int $totalizable Is extrafield totalizable on list
  682. * @param int $printable Is extrafield displayed on PDF
  683. * @return int <=0 if KO, >0 if OK
  684. * @throws Exception
  685. */
  686. private function update_label($attrname, $label, $type, $size, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '0', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0)
  687. {
  688. // phpcs:enable
  689. global $conf, $user;
  690. dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable.", ".$printable);
  691. // Clean parameters
  692. if ($elementtype == 'thirdparty') {
  693. $elementtype = 'societe';
  694. }
  695. if ($elementtype == 'contact') {
  696. $elementtype = 'socpeople';
  697. }
  698. if (empty($pos)) {
  699. $pos = 0;
  700. }
  701. if (empty($list)) {
  702. $list = '0';
  703. }
  704. if (empty($totalizable)) {
  705. $totalizable = 0;
  706. }
  707. if (empty($required)) {
  708. $required = 0;
  709. }
  710. if (empty($unique)) {
  711. $unique = 0;
  712. }
  713. if (empty($alwayseditable)) {
  714. $alwayseditable = 0;
  715. }
  716. if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) {
  717. $this->db->begin();
  718. if (is_array($param) && count($param) > 0) {
  719. $params = serialize($param);
  720. } elseif (strlen($param) > 0) {
  721. $params = trim($param);
  722. } else {
  723. $params = '';
  724. }
  725. if ($entity === '' || $entity != '0') {
  726. // We dont want on all entities, we delete all and current
  727. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
  728. $sql_del .= " WHERE name = '".$this->db->escape($attrname)."'";
  729. $sql_del .= " AND entity IN (0, ".($entity === '' ? $conf->entity : $entity).")";
  730. $sql_del .= " AND elementtype = '".$this->db->escape($elementtype)."'";
  731. } else {
  732. // We want on all entities ($entities = '0'), we delete on all only (we keep setup specific to each entity)
  733. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
  734. $sql_del .= " WHERE name = '".$this->db->escape($attrname)."'";
  735. $sql_del .= " AND entity = 0";
  736. $sql_del .= " AND elementtype = '".$this->db->escape($elementtype)."'";
  737. }
  738. $resql1 = $this->db->query($sql_del);
  739. $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
  740. $sql .= " name,"; // This is code
  741. $sql .= " entity,";
  742. $sql .= " label,";
  743. $sql .= " type,";
  744. $sql .= " size,";
  745. $sql .= " elementtype,";
  746. $sql .= " fieldunique,";
  747. $sql .= " fieldrequired,";
  748. $sql .= " perms,";
  749. $sql .= " langs,";
  750. $sql .= " pos,";
  751. $sql .= " alwayseditable,";
  752. $sql .= " param,";
  753. $sql .= " list,";
  754. $sql .= " printable,";
  755. $sql .= " totalizable,";
  756. $sql .= " fielddefault,";
  757. $sql .= " fieldcomputed,";
  758. $sql .= " fk_user_author,";
  759. $sql .= " fk_user_modif,";
  760. $sql .= " datec,";
  761. $sql .= " enabled,";
  762. $sql .= " help";
  763. $sql .= ") VALUES (";
  764. $sql .= "'".$this->db->escape($attrname)."',";
  765. $sql .= " ".($entity === '' ? $conf->entity : $entity).",";
  766. $sql .= " '".$this->db->escape($label)."',";
  767. $sql .= " '".$this->db->escape($type)."',";
  768. $sql .= " '".$this->db->escape($size)."',";
  769. $sql .= " '".$this->db->escape($elementtype)."',";
  770. $sql .= " ".$unique.",";
  771. $sql .= " ".$required.",";
  772. $sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").",";
  773. $sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").",";
  774. $sql .= " ".$pos.",";
  775. $sql .= " '".$this->db->escape($alwayseditable)."',";
  776. $sql .= " '".$this->db->escape($params)."',";
  777. $sql .= " '".$this->db->escape($list)."', ";
  778. $sql .= " '".$this->db->escape($printable)."', ";
  779. $sql .= " ".($totalizable ? 'TRUE' : 'FALSE').",";
  780. $sql .= " ".(($default != '') ? "'".$this->db->escape($default)."'" : "null").",";
  781. $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").",";
  782. $sql .= " ".$user->id.",";
  783. $sql .= " ".$user->id.",";
  784. $sql .= "'".$this->db->idate(dol_now())."',";
  785. $sql .= "'".$this->db->escape($enabled)."',";
  786. $sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null");
  787. $sql .= ")";
  788. $resql2 = $this->db->query($sql);
  789. if ($resql1 && $resql2) {
  790. $this->db->commit();
  791. return 1;
  792. } else {
  793. $this->db->rollback();
  794. dol_print_error($this->db);
  795. return -1;
  796. }
  797. } else {
  798. return 0;
  799. }
  800. }
  801. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  802. /**
  803. * Load array this->attributes, or old this->attribute_xxx like attribute_label, attribute_type, ...
  804. *
  805. * @param string $elementtype Type of element ('' = all or $object->table_element like 'adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...).
  806. * @param boolean $forceload Force load of extra fields whatever is status of cache.
  807. * @return array Array of attributes keys+label for all extra fields.
  808. */
  809. public function fetch_name_optionals_label($elementtype, $forceload = false)
  810. {
  811. // phpcs:enable
  812. global $conf;
  813. if (empty($elementtype)) {
  814. return array();
  815. }
  816. if ($elementtype == 'thirdparty') {
  817. $elementtype = 'societe';
  818. }
  819. if ($elementtype == 'contact') {
  820. $elementtype = 'socpeople';
  821. }
  822. if ($elementtype == 'order_supplier') {
  823. $elementtype = 'commande_fournisseur';
  824. }
  825. if ($elementtype == 'stock_mouvement') {
  826. $elementtype = 'movement';
  827. }
  828. $array_name_label = array();
  829. // We should not have several time this request. If we have, there is some optimization to do by calling a simple $extrafields->fetch_optionals() in top of code and not into subcode
  830. $sql = "SELECT rowid, name, label, type, size, elementtype, fieldunique, fieldrequired, param, pos, alwayseditable, perms, langs, list, printable, totalizable, fielddefault, fieldcomputed, entity, enabled, help";
  831. $sql .= " FROM ".MAIN_DB_PREFIX."extrafields";
  832. //$sql.= " WHERE entity IN (0,".$conf->entity.")"; // Filter is done later
  833. if ($elementtype) {
  834. $sql .= " WHERE elementtype = '".$this->db->escape($elementtype)."'"; // Filed with object->table_element
  835. }
  836. $sql .= " ORDER BY pos";
  837. $resql = $this->db->query($sql);
  838. if ($resql) {
  839. if ($this->db->num_rows($resql)) {
  840. while ($tab = $this->db->fetch_object($resql)) {
  841. if ($tab->entity != 0 && $tab->entity != $conf->entity) {
  842. // This field is not in current entity. We discard but before we save it into the array of mandatory fields if it is a mandatory field without default value
  843. if ($tab->fieldrequired && is_null($tab->fielddefault)) {
  844. $this->attributes[$tab->elementtype]['mandatoryfieldsofotherentities'][$tab->name] = $tab->type;
  845. }
  846. continue;
  847. }
  848. // We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label']
  849. if ($tab->type != 'separate') {
  850. $array_name_label[$tab->name] = $tab->label;
  851. }
  852. // Old usage
  853. $this->attribute_type[$tab->name] = $tab->type;
  854. $this->attribute_label[$tab->name] = $tab->label;
  855. $this->attribute_size[$tab->name] = $tab->size;
  856. $this->attribute_elementtype[$tab->name] = $tab->elementtype;
  857. $this->attribute_default[$tab->name] = $tab->fielddefault;
  858. $this->attribute_computed[$tab->name] = $tab->fieldcomputed;
  859. $this->attribute_unique[$tab->name] = $tab->fieldunique;
  860. $this->attribute_required[$tab->name] = $tab->fieldrequired;
  861. $this->attribute_param[$tab->name] = ($tab->param ? jsonOrUnserialize($tab->param) : '');
  862. $this->attribute_pos[$tab->name] = $tab->pos;
  863. $this->attribute_alwayseditable[$tab->name] = $tab->alwayseditable;
  864. $this->attribute_perms[$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms);
  865. $this->attribute_langfile[$tab->name] = $tab->langs;
  866. $this->attribute_list[$tab->name] = $tab->list;
  867. $this->attribute_totalizable[$tab->name] = $tab->totalizable;
  868. $this->attribute_entityid[$tab->name] = $tab->entity;
  869. // New usage
  870. $this->attributes[$tab->elementtype]['type'][$tab->name] = $tab->type;
  871. $this->attributes[$tab->elementtype]['label'][$tab->name] = $tab->label;
  872. $this->attributes[$tab->elementtype]['size'][$tab->name] = $tab->size;
  873. $this->attributes[$tab->elementtype]['elementtype'][$tab->name] = $tab->elementtype;
  874. $this->attributes[$tab->elementtype]['default'][$tab->name] = $tab->fielddefault;
  875. $this->attributes[$tab->elementtype]['computed'][$tab->name] = $tab->fieldcomputed;
  876. $this->attributes[$tab->elementtype]['unique'][$tab->name] = $tab->fieldunique;
  877. $this->attributes[$tab->elementtype]['required'][$tab->name] = $tab->fieldrequired;
  878. $this->attributes[$tab->elementtype]['param'][$tab->name] = ($tab->param ? jsonOrUnserialize($tab->param) : '');
  879. $this->attributes[$tab->elementtype]['pos'][$tab->name] = $tab->pos;
  880. $this->attributes[$tab->elementtype]['alwayseditable'][$tab->name] = $tab->alwayseditable;
  881. $this->attributes[$tab->elementtype]['perms'][$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms);
  882. $this->attributes[$tab->elementtype]['langfile'][$tab->name] = $tab->langs;
  883. $this->attributes[$tab->elementtype]['list'][$tab->name] = $tab->list;
  884. $this->attributes[$tab->elementtype]['printable'][$tab->name] = $tab->printable;
  885. $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = ($tab->totalizable ? 1 : 0);
  886. $this->attributes[$tab->elementtype]['entityid'][$tab->name] = $tab->entity;
  887. $this->attributes[$tab->elementtype]['enabled'][$tab->name] = $tab->enabled;
  888. $this->attributes[$tab->elementtype]['help'][$tab->name] = $tab->help;
  889. $this->attributes[$tab->elementtype]['loaded'] = 1;
  890. }
  891. }
  892. if ($elementtype) {
  893. $this->attributes[$elementtype]['loaded'] = 1; // If nothing found, we also save tag 'loaded'
  894. }
  895. } else {
  896. $this->error = $this->db->lasterror();
  897. dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR);
  898. }
  899. return $array_name_label;
  900. }
  901. /**
  902. * Return HTML string to put an input field into a page
  903. * Code very similar with showInputField of common object
  904. *
  905. * @param string $key Key of attribute
  906. * @param string|array $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value); for dates in filter mode, a range array('start'=><timestamp>, 'end'=><timestamp>) should be provided
  907. * @param string $moreparam To add more parameters on html input tag
  908. * @param string $keysuffix Prefix string to add after name and id of field (can be used to avoid duplicate names)
  909. * @param string $keyprefix Suffix string to add before name and id of field (can be used to avoid duplicate names)
  910. * @param string $morecss More css (to defined size of field. Old behaviour: may also be a numeric)
  911. * @param int $objectid Current object id
  912. * @param string $extrafieldsobjectkey If defined (for example $object->table_element), use the new method to get extrafields data
  913. * @param string $mode 1=Used for search filters
  914. * @return string
  915. */
  916. public function showInputField($key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '', $objectid = 0, $extrafieldsobjectkey = '', $mode = 0)
  917. {
  918. global $conf, $langs, $form;
  919. if (!is_object($form)) {
  920. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  921. $form = new Form($this->db);
  922. }
  923. $out = '';
  924. if (!preg_match('/options_$/', $keyprefix)) { // Because we work on extrafields, we add 'options_' to prefix if not already added
  925. $keyprefix = $keyprefix.'options_';
  926. }
  927. if (!empty($extrafieldsobjectkey)) {
  928. $label = $this->attributes[$extrafieldsobjectkey]['label'][$key];
  929. $type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
  930. $size = $this->attributes[$extrafieldsobjectkey]['size'][$key];
  931. $default = $this->attributes[$extrafieldsobjectkey]['default'][$key];
  932. $computed = $this->attributes[$extrafieldsobjectkey]['computed'][$key];
  933. $unique = $this->attributes[$extrafieldsobjectkey]['unique'][$key];
  934. $required = $this->attributes[$extrafieldsobjectkey]['required'][$key];
  935. $param = $this->attributes[$extrafieldsobjectkey]['param'][$key];
  936. $perms = dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
  937. $langfile = $this->attributes[$extrafieldsobjectkey]['langfile'][$key];
  938. $list = dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
  939. $totalizable = $this->attributes[$extrafieldsobjectkey]['totalizable'][$key];
  940. $help = $this->attributes[$extrafieldsobjectkey]['help'][$key];
  941. $hidden = (empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
  942. } else // Old usage
  943. {
  944. $label = $this->attribute_label[$key];
  945. $type = $this->attribute_type[$key];
  946. $size = $this->attribute_size[$key];
  947. $elementtype = $this->attribute_elementtype[$key]; // Seems not used
  948. $default = $this->attribute_default[$key];
  949. $computed = $this->attribute_computed[$key];
  950. $unique = $this->attribute_unique[$key];
  951. $required = $this->attribute_required[$key];
  952. $param = $this->attribute_param[$key];
  953. $langfile = $this->attribute_langfile[$key];
  954. $list = $this->attribute_list[$key];
  955. $totalizable = $this->attribute_totalizable[$key];
  956. $hidden = (empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
  957. }
  958. if ($computed) {
  959. if (!preg_match('/^search_/', $keyprefix)) {
  960. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  961. } else {
  962. return '';
  963. }
  964. }
  965. if (empty($morecss)) {
  966. if ($type == 'date') {
  967. $morecss = 'minwidth100imp';
  968. } elseif ($type == 'datetime' || $type == 'link') {
  969. $morecss = 'minwidth200imp';
  970. } elseif (in_array($type, array('int', 'integer', 'double', 'price'))) {
  971. $morecss = 'maxwidth75';
  972. } elseif ($type == 'password') {
  973. $morecss = 'maxwidth100';
  974. } elseif ($type == 'url') {
  975. $morecss = 'minwidth400';
  976. } elseif ($type == 'boolean') {
  977. $morecss = '';
  978. } else {
  979. if (empty($size) || round($size) < 12) {
  980. $morecss = 'minwidth100';
  981. } elseif (round($size) <= 48) {
  982. $morecss = 'minwidth200';
  983. } else {
  984. $morecss = 'minwidth400';
  985. }
  986. }
  987. }
  988. if (in_array($type, array('date'))) {
  989. $tmp = explode(',', $size);
  990. $newsize = $tmp[0];
  991. $showtime = 0;
  992. // Do not show current date when field not required (see selectDate() method)
  993. if (!$required && $value == '') {
  994. $value = '-1';
  995. }
  996. if ($mode == 1) {
  997. // search filter on a date extrafield shows two inputs to select a date range
  998. $prefill = array(
  999. 'start' => isset($value['start']) ? $value['start'] : '',
  1000. 'end' => isset($value['end']) ? $value['end'] : ''
  1001. );
  1002. $out = '<div ' . ($moreparam ? $moreparam : '') . '><div class="nowrap">';
  1003. $out .= $form->selectDate($prefill['start'], $keyprefix.$key.$keysuffix.'_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
  1004. $out .= '</div><div class="nowrap">';
  1005. $out .= $form->selectDate($prefill['end'], $keyprefix.$key.$keysuffix.'_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"));
  1006. $out .= '</div></div>';
  1007. } else {
  1008. // TODO Must also support $moreparam
  1009. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  1010. }
  1011. } elseif (in_array($type, array('datetime'))) {
  1012. $tmp = explode(',', $size);
  1013. $newsize = $tmp[0];
  1014. $showtime = 1;
  1015. // Do not show current date when field not required (see selectDate() method)
  1016. if (!$required && $value == '') {
  1017. $value = '-1';
  1018. }
  1019. if ($mode == 1) {
  1020. // search filter on a date extrafield shows two inputs to select a date range
  1021. $prefill = array(
  1022. 'start' => isset($value['start']) ? $value['start'] : '',
  1023. 'end' => isset($value['end']) ? $value['end'] : ''
  1024. );
  1025. $out = '<div ' . ($moreparam ? $moreparam : '') . '><div class="nowrap">';
  1026. $out .= $form->selectDate($prefill['start'], $keyprefix.$key.$keysuffix.'_start', 1, 1, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"), 'tzuserrel');
  1027. $out .= '</div><div class="nowrap">';
  1028. $out .= $form->selectDate($prefill['end'], $keyprefix.$key.$keysuffix.'_end', 1, 1, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  1029. $out .= '</div></div>';
  1030. } else {
  1031. // TODO Must also support $moreparam
  1032. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  1033. }
  1034. } elseif (in_array($type, array('int', 'integer'))) {
  1035. $tmp = explode(',', $size);
  1036. $newsize = $tmp[0];
  1037. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').'>';
  1038. } elseif (preg_match('/varchar/', $type)) {
  1039. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').'>';
  1040. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  1041. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  1042. } elseif ($type == 'text') {
  1043. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  1044. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  1045. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  1046. $out = $doleditor->Create(1);
  1047. } else {
  1048. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  1049. }
  1050. } elseif ($type == 'html') {
  1051. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  1052. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  1053. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  1054. $out = $doleditor->Create(1);
  1055. } else {
  1056. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  1057. }
  1058. } elseif ($type == 'boolean') {
  1059. if (empty($mode)) {
  1060. $checked = '';
  1061. if (!empty($value)) {
  1062. $checked = ' checked value="1" ';
  1063. } else {
  1064. $checked = ' value="1" ';
  1065. }
  1066. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  1067. } else {
  1068. $out .= $form->selectyesno($keyprefix.$key.$keysuffix, $value, 1, false, 1);
  1069. }
  1070. } elseif ($type == 'price') {
  1071. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  1072. $value = price($value);
  1073. }
  1074. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  1075. } elseif ($type == 'double') {
  1076. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  1077. $value = price($value);
  1078. }
  1079. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  1080. } elseif ($type == 'select') {
  1081. $out = '';
  1082. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  1083. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1084. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  1085. }
  1086. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  1087. $out .= '<option value="0">&nbsp;</option>';
  1088. foreach ($param['options'] as $key => $val) {
  1089. if ((string) $key == '') {
  1090. continue;
  1091. }
  1092. $valarray = explode('|', $val);
  1093. $val = $valarray[0];
  1094. $parent = '';
  1095. if (!empty($valarray[1])) {
  1096. $parent = $valarray[1];
  1097. }
  1098. $out .= '<option value="'.$key.'"';
  1099. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  1100. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  1101. $out .= '>';
  1102. if ($langfile && $val) {
  1103. $out .= $langs->trans($val);
  1104. } else {
  1105. $out .= $val;
  1106. }
  1107. $out .= '</option>';
  1108. }
  1109. $out .= '</select>';
  1110. } elseif ($type == 'sellist') {
  1111. $out = '';
  1112. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  1113. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1114. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  1115. }
  1116. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  1117. if (is_array($param['options'])) {
  1118. $param_list = array_keys($param['options']);
  1119. $InfoFieldList = explode(":", $param_list[0]);
  1120. $parentName = '';
  1121. $parentField = '';
  1122. // 0 : tableName
  1123. // 1 : label field name
  1124. // 2 : key fields name (if differ of rowid)
  1125. // 3 : key field parent (for dependent lists)
  1126. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  1127. // 5 : id category type
  1128. // 6 : ids categories list separated by comma for category root
  1129. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  1130. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  1131. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  1132. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  1133. } else {
  1134. $keyList = $InfoFieldList[2].' as rowid';
  1135. }
  1136. }
  1137. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  1138. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  1139. $keyList .= ', '.$parentField;
  1140. }
  1141. $filter_categorie = false;
  1142. if (count($InfoFieldList) > 5) {
  1143. if ($InfoFieldList[0] == 'categorie') {
  1144. $filter_categorie = true;
  1145. }
  1146. }
  1147. if ($filter_categorie === false) {
  1148. $fields_label = explode('|', $InfoFieldList[1]);
  1149. if (is_array($fields_label)) {
  1150. $keyList .= ', ';
  1151. $keyList .= implode(', ', $fields_label);
  1152. }
  1153. $sqlwhere = '';
  1154. $sql = 'SELECT '.$keyList;
  1155. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  1156. if (!empty($InfoFieldList[4])) {
  1157. // can use curent entity filter
  1158. if (strpos($InfoFieldList[4], '$ENTITY$') !== false) {
  1159. $InfoFieldList[4] = str_replace('$ENTITY$', $conf->entity, $InfoFieldList[4]);
  1160. }
  1161. // can use SELECT request
  1162. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  1163. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  1164. }
  1165. // current object id can be use into filter
  1166. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  1167. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  1168. } else {
  1169. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  1170. }
  1171. //We have to join on extrafield table
  1172. if (strpos($InfoFieldList[4], 'extra') !== false) {
  1173. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  1174. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  1175. } else {
  1176. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  1177. }
  1178. } else {
  1179. $sqlwhere .= ' WHERE 1=1';
  1180. }
  1181. // Some tables may have field, some other not. For the moment we disable it.
  1182. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  1183. $sqlwhere .= ' AND entity = '.((int) $conf->entity);
  1184. }
  1185. $sql .= $sqlwhere;
  1186. //print $sql;
  1187. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  1188. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  1189. $resql = $this->db->query($sql);
  1190. if ($resql) {
  1191. $out .= '<option value="0">&nbsp;</option>';
  1192. $num = $this->db->num_rows($resql);
  1193. $i = 0;
  1194. while ($i < $num) {
  1195. $labeltoshow = '';
  1196. $obj = $this->db->fetch_object($resql);
  1197. // Several field into label (eq table:code|libelle:rowid)
  1198. $notrans = false;
  1199. $fields_label = explode('|', $InfoFieldList[1]);
  1200. if (is_array($fields_label) && count($fields_label) > 1) {
  1201. $notrans = true;
  1202. foreach ($fields_label as $field_toshow) {
  1203. $labeltoshow .= $obj->$field_toshow.' ';
  1204. }
  1205. } else {
  1206. $labeltoshow = $obj->{$InfoFieldList[1]};
  1207. }
  1208. $labeltoshow = $labeltoshow;
  1209. if ($value == $obj->rowid) {
  1210. if (!$notrans) {
  1211. foreach ($fields_label as $field_toshow) {
  1212. $translabel = $langs->trans($obj->$field_toshow);
  1213. $labeltoshow = $translabel.' ';
  1214. }
  1215. }
  1216. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  1217. } else {
  1218. if (!$notrans) {
  1219. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  1220. $labeltoshow = $translabel;
  1221. }
  1222. if (empty($labeltoshow)) {
  1223. $labeltoshow = '(not defined)';
  1224. }
  1225. if (!empty($InfoFieldList[3]) && $parentField) {
  1226. $parent = $parentName.':'.$obj->{$parentField};
  1227. }
  1228. $out .= '<option value="'.$obj->rowid.'"';
  1229. $out .= ($value == $obj->rowid ? ' selected' : '');
  1230. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  1231. $out .= '>'.$labeltoshow.'</option>';
  1232. }
  1233. $i++;
  1234. }
  1235. $this->db->free($resql);
  1236. } else {
  1237. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  1238. }
  1239. } else {
  1240. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1241. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  1242. $out .= '<option value="0">&nbsp;</option>';
  1243. foreach ($data as $data_key => $data_value) {
  1244. $out .= '<option value="'.$data_key.'"';
  1245. $out .= ($value == $data_key ? ' selected' : '');
  1246. $out .= '>'.$data_value.'</option>';
  1247. }
  1248. }
  1249. }
  1250. $out .= '</select>';
  1251. } elseif ($type == 'checkbox') {
  1252. $value_arr = $value;
  1253. if (!is_array($value)) {
  1254. $value_arr = explode(',', $value);
  1255. }
  1256. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  1257. } elseif ($type == 'radio') {
  1258. $out = '';
  1259. foreach ($param['options'] as $keyopt => $val) {
  1260. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  1261. $out .= ' value="'.$keyopt.'"';
  1262. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  1263. $out .= ($value == $keyopt ? 'checked' : '');
  1264. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  1265. }
  1266. } elseif ($type == 'chkbxlst') {
  1267. if (is_array($value)) {
  1268. $value_arr = $value;
  1269. } else {
  1270. $value_arr = explode(',', $value);
  1271. }
  1272. if (is_array($param['options'])) {
  1273. $param_list = array_keys($param['options']);
  1274. $InfoFieldList = explode(":", $param_list[0]);
  1275. $parentName = '';
  1276. $parentField = '';
  1277. // 0 : tableName
  1278. // 1 : label field name
  1279. // 2 : key fields name (if differ of rowid)
  1280. // 3 : key field parent (for dependent lists)
  1281. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  1282. // 5 : id category type
  1283. // 6 : ids categories list separated by comma for category root
  1284. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  1285. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  1286. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  1287. $keyList .= ', '.$parentField;
  1288. }
  1289. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  1290. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  1291. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  1292. } else {
  1293. $keyList = $InfoFieldList[2].' as rowid';
  1294. }
  1295. }
  1296. $filter_categorie = false;
  1297. if (count($InfoFieldList) > 5) {
  1298. if ($InfoFieldList[0] == 'categorie') {
  1299. $filter_categorie = true;
  1300. }
  1301. }
  1302. if ($filter_categorie === false) {
  1303. $fields_label = explode('|', $InfoFieldList[1]);
  1304. if (is_array($fields_label)) {
  1305. $keyList .= ', ';
  1306. $keyList .= implode(', ', $fields_label);
  1307. }
  1308. $sqlwhere = '';
  1309. $sql = 'SELECT '.$keyList;
  1310. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  1311. if (!empty($InfoFieldList[4])) {
  1312. // can use SELECT request
  1313. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  1314. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  1315. }
  1316. // current object id can be use into filter
  1317. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  1318. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  1319. } elseif (preg_match("#^.*list.php$#", $_SERVER["PHP_SELF"])) {
  1320. // Pattern for word=$ID$
  1321. $word = '\b[a-zA-Z0-9-\.-_]+\b=\$ID\$';
  1322. // Removing space arount =, ( and )
  1323. $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]);
  1324. $nbPreg = 1;
  1325. // While we have parenthesis
  1326. while ($nbPreg != 0) {
  1327. // Init des compteurs
  1328. $nbPregRepl = $nbPregSel = 0;
  1329. // On retire toutes les parenthèses sans = avant
  1330. $InfoFieldList[4] = preg_replace('#([^=])(\([^)^(]*('.$word.')[^)^(]*\))#', '$1 $3 ', $InfoFieldList[4], -1, $nbPregRepl);
  1331. // On retire les espaces autour des = et parenthèses
  1332. $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]);
  1333. // On retire toutes les parenthèses avec = avant
  1334. $InfoFieldList[4] = preg_replace('#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*('.$word.')[^)^(]*\)#', '$1 ', $InfoFieldList[4], -1, $nbPregSel);
  1335. // On retire les espaces autour des = et parenthèses
  1336. $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]);
  1337. // Calcul du compteur général pour la boucle
  1338. $nbPreg = $nbPregRepl + $nbPregSel;
  1339. }
  1340. // Si l'on a un AND ou un OR, avant ou après
  1341. preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition);
  1342. while (!empty($matchCondition[0])) {
  1343. // If the two sides differ but are not empty
  1344. if (!empty($matchCondition[1]) && !empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3]) {
  1345. // Nobody sain would do that without parentheses
  1346. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  1347. } else {
  1348. if (!empty($matchCondition[1])) {
  1349. $boolCond = (($matchCondition[1] == "AND") ? ' AND TRUE ' : ' OR FALSE ');
  1350. $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond.$matchCondition[3], $InfoFieldList[4]);
  1351. } elseif (!empty($matchCondition[3])) {
  1352. $boolCond = (($matchCondition[3] == "AND") ? ' TRUE AND ' : ' FALSE OR');
  1353. $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond, $InfoFieldList[4]);
  1354. } else {
  1355. $InfoFieldList[4] = " TRUE ";
  1356. }
  1357. }
  1358. // Si l'on a un AND ou un OR, avant ou après
  1359. preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition);
  1360. }
  1361. } else {
  1362. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  1363. }
  1364. // We have to join on extrafield table
  1365. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  1366. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  1367. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  1368. } else {
  1369. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  1370. }
  1371. } else {
  1372. $sqlwhere .= ' WHERE 1=1';
  1373. }
  1374. // Some tables may have field, some other not. For the moment we disable it.
  1375. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  1376. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  1377. }
  1378. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  1379. // print $sql;
  1380. $sql .= $sqlwhere;
  1381. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  1382. $resql = $this->db->query($sql);
  1383. if ($resql) {
  1384. $num = $this->db->num_rows($resql);
  1385. $i = 0;
  1386. $data = array();
  1387. while ($i < $num) {
  1388. $labeltoshow = '';
  1389. $obj = $this->db->fetch_object($resql);
  1390. $notrans = false;
  1391. // Several field into label (eq table:code|libelle:rowid)
  1392. $fields_label = explode('|', $InfoFieldList[1]);
  1393. if (is_array($fields_label)) {
  1394. $notrans = true;
  1395. foreach ($fields_label as $field_toshow) {
  1396. $labeltoshow .= $obj->$field_toshow.' ';
  1397. }
  1398. } else {
  1399. $labeltoshow = $obj->{$InfoFieldList[1]};
  1400. }
  1401. $labeltoshow = dol_trunc($labeltoshow, 45);
  1402. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  1403. foreach ($fields_label as $field_toshow) {
  1404. $translabel = $langs->trans($obj->$field_toshow);
  1405. if ($translabel != $obj->$field_toshow) {
  1406. $labeltoshow = dol_trunc($translabel, 18).' ';
  1407. } else {
  1408. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  1409. }
  1410. }
  1411. $data[$obj->rowid] = $labeltoshow;
  1412. } else {
  1413. if (!$notrans) {
  1414. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  1415. if ($translabel != $obj->{$InfoFieldList[1]}) {
  1416. $labeltoshow = dol_trunc($translabel, 18);
  1417. } else {
  1418. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  1419. }
  1420. }
  1421. if (empty($labeltoshow)) {
  1422. $labeltoshow = '(not defined)';
  1423. }
  1424. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  1425. $data[$obj->rowid] = $labeltoshow;
  1426. }
  1427. if (!empty($InfoFieldList[3]) && $parentField) {
  1428. $parent = $parentName.':'.$obj->{$parentField};
  1429. }
  1430. $data[$obj->rowid] = $labeltoshow;
  1431. }
  1432. $i++;
  1433. }
  1434. $this->db->free($resql);
  1435. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  1436. } else {
  1437. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  1438. }
  1439. } else {
  1440. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1441. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  1442. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  1443. }
  1444. }
  1445. } elseif ($type == 'link') {
  1446. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  1447. $showempty = (($required && $default != '') ? 0 : 1);
  1448. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss);
  1449. } elseif ($type == 'password') {
  1450. // If prefix is 'search_', field is used as a filter, we use a common text field.
  1451. $out = '<input style="display:none" type="text" name="fakeusernameremembered">'; // Hidden field to reduce impact of evil Google Chrome autopopulate bug.
  1452. $out .= '<input autocomplete="new-password" type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  1453. }
  1454. if (!empty($hidden)) {
  1455. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  1456. }
  1457. /* Add comments
  1458. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  1459. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  1460. */
  1461. /*if (! empty($help) && $keyprefix != 'search_options_') {
  1462. $out .= $form->textwithpicto('', $help, 1, 'help', '', 0, 3);
  1463. }*/
  1464. return $out;
  1465. }
  1466. /**
  1467. * Return HTML string to put an output field into a page
  1468. *
  1469. * @param string $key Key of attribute
  1470. * @param string $value Value to show
  1471. * @param string $moreparam To add more parameters on html input tag (only checkbox use html input for output rendering)
  1472. * @param string $extrafieldsobjectkey If defined (for example $object->table_element), function uses the new method to get extrafields data
  1473. * @return string Formated value
  1474. */
  1475. public function showOutputField($key, $value, $moreparam = '', $extrafieldsobjectkey = '')
  1476. {
  1477. global $conf, $langs;
  1478. if (!empty($extrafieldsobjectkey)) {
  1479. $label = $this->attributes[$extrafieldsobjectkey]['label'][$key];
  1480. $type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
  1481. $size = $this->attributes[$extrafieldsobjectkey]['size'][$key]; // Can be '255', '24,8'...
  1482. $default = $this->attributes[$extrafieldsobjectkey]['default'][$key];
  1483. $computed = $this->attributes[$extrafieldsobjectkey]['computed'][$key];
  1484. $unique = $this->attributes[$extrafieldsobjectkey]['unique'][$key];
  1485. $required = $this->attributes[$extrafieldsobjectkey]['required'][$key];
  1486. $param = $this->attributes[$extrafieldsobjectkey]['param'][$key];
  1487. $perms = dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
  1488. $langfile = $this->attributes[$extrafieldsobjectkey]['langfile'][$key];
  1489. $list = dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
  1490. $help = $this->attributes[$extrafieldsobjectkey]['help'][$key];
  1491. $hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
  1492. } else // Old usage
  1493. {
  1494. //dol_syslog("Warning: parameter 'extrafieldsobjectkey' is missing", LOG_WARNING);
  1495. $label = $this->attribute_label[$key];
  1496. $type = $this->attribute_type[$key];
  1497. $size = $this->attribute_size[$key];
  1498. $default = $this->attribute_default[$key];
  1499. $computed = $this->attribute_computed[$key];
  1500. $unique = $this->attribute_unique[$key];
  1501. $required = $this->attribute_required[$key];
  1502. $param = $this->attribute_param[$key];
  1503. $perms = dol_eval($this->attribute_perms[$key], 1);
  1504. $langfile = $this->attribute_langfile[$key];
  1505. $list = dol_eval($this->attribute_list[$key], 1);
  1506. $help = ''; // Not supported with old syntax
  1507. $hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
  1508. }
  1509. if ($hidden) {
  1510. return ''; // This is a protection. If field is hidden, we should just not call this method.
  1511. }
  1512. //if ($computed) $value = // $value is already calculated into $value before calling this method
  1513. $showsize = 0;
  1514. if ($type == 'date') {
  1515. $showsize = 10;
  1516. $value = dol_print_date($value, 'day'); // For date without hour, date is always GMT for storage and output
  1517. } elseif ($type == 'datetime') {
  1518. $showsize = 19;
  1519. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  1520. } elseif ($type == 'int') {
  1521. $showsize = 10;
  1522. } elseif ($type == 'double') {
  1523. if (!empty($value)) {
  1524. //$value=price($value);
  1525. $sizeparts = explode(",", $size);
  1526. $number_decimals = $sizeparts[1];
  1527. $value = price($value, 0, $langs, 0, 0, $number_decimals, '');
  1528. }
  1529. } elseif ($type == 'boolean') {
  1530. $checked = '';
  1531. if (!empty($value)) {
  1532. $checked = ' checked ';
  1533. }
  1534. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  1535. } elseif ($type == 'mail') {
  1536. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  1537. } elseif ($type == 'url') {
  1538. $value = dol_print_url($value, '_blank', 32, 1);
  1539. } elseif ($type == 'phone') {
  1540. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  1541. } elseif ($type == 'price') {
  1542. //$value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  1543. if ($value || $value == '0') {
  1544. $value = price($value, 0, $langs, 0, 0, -1);
  1545. }
  1546. } elseif ($type == 'select') {
  1547. $valstr = (!empty($param['options'][$value]) ? $param['options'][$value] : '');
  1548. if (($pos = strpos($valstr, "|")) !== false) {
  1549. $valstr = substr($valstr, 0, $pos);
  1550. }
  1551. if ($langfile && $valstr) {
  1552. $value = $langs->trans($valstr);
  1553. } else {
  1554. $value = $valstr;
  1555. }
  1556. } elseif ($type == 'sellist') {
  1557. $param_list = array_keys($param['options']);
  1558. $InfoFieldList = explode(":", $param_list[0]);
  1559. $selectkey = "rowid";
  1560. $keyList = 'rowid';
  1561. if (count($InfoFieldList) >= 3) {
  1562. $selectkey = $InfoFieldList[2];
  1563. $keyList = $InfoFieldList[2].' as rowid';
  1564. }
  1565. $fields_label = explode('|', $InfoFieldList[1]);
  1566. if (is_array($fields_label)) {
  1567. $keyList .= ', ';
  1568. $keyList .= implode(', ', $fields_label);
  1569. }
  1570. $filter_categorie = false;
  1571. if (count($InfoFieldList) > 5) {
  1572. if ($InfoFieldList[0] == 'categorie') {
  1573. $filter_categorie = true;
  1574. }
  1575. }
  1576. $sql = 'SELECT '.$keyList;
  1577. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  1578. if (strpos($InfoFieldList[4], 'extra') !== false) {
  1579. $sql .= ' as main';
  1580. }
  1581. if ($selectkey == 'rowid' && empty($value)) {
  1582. $sql .= " WHERE ".$selectkey." = 0";
  1583. } elseif ($selectkey == 'rowid') {
  1584. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  1585. } else {
  1586. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  1587. }
  1588. //$sql.= ' AND entity = '.$conf->entity;
  1589. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  1590. $resql = $this->db->query($sql);
  1591. if ($resql) {
  1592. if ($filter_categorie === false) {
  1593. $value = ''; // value was used, so now we reste it to use it to build final output
  1594. $obj = $this->db->fetch_object($resql);
  1595. // Several field into label (eq table:code|libelle:rowid)
  1596. $fields_label = explode('|', $InfoFieldList[1]);
  1597. if (is_array($fields_label) && count($fields_label) > 1) {
  1598. foreach ($fields_label as $field_toshow) {
  1599. $translabel = '';
  1600. if (!empty($obj->$field_toshow)) {
  1601. $translabel = $langs->trans($obj->$field_toshow);
  1602. }
  1603. if ($translabel != $field_toshow) {
  1604. $value .= dol_trunc($translabel, 18).' ';
  1605. } else {
  1606. $value .= $obj->$field_toshow.' ';
  1607. }
  1608. }
  1609. } else {
  1610. $translabel = '';
  1611. if (!empty($obj->{$InfoFieldList[1]})) {
  1612. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  1613. }
  1614. if ($translabel != $obj->{$InfoFieldList[1]}) {
  1615. $value = dol_trunc($translabel, 18);
  1616. } else {
  1617. $value = $obj->{$InfoFieldList[1]};
  1618. }
  1619. }
  1620. } else {
  1621. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1622. $toprint = array();
  1623. $obj = $this->db->fetch_object($resql);
  1624. $c = new Categorie($this->db);
  1625. $c->fetch($obj->rowid);
  1626. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  1627. foreach ($ways as $way) {
  1628. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.img_object('', 'category').' '.$way.'</li>';
  1629. }
  1630. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  1631. }
  1632. } else {
  1633. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  1634. }
  1635. } elseif ($type == 'radio') {
  1636. $value = $param['options'][$value];
  1637. } elseif ($type == 'checkbox') {
  1638. $value_arr = explode(',', $value);
  1639. $value = '';
  1640. $toprint = array();
  1641. if (is_array($value_arr)) {
  1642. foreach ($value_arr as $keyval => $valueval) {
  1643. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  1644. }
  1645. }
  1646. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  1647. } elseif ($type == 'chkbxlst') {
  1648. $value_arr = explode(',', $value);
  1649. $param_list = array_keys($param['options']);
  1650. $InfoFieldList = explode(":", $param_list[0]);
  1651. $selectkey = "rowid";
  1652. $keyList = 'rowid';
  1653. if (count($InfoFieldList) >= 3) {
  1654. $selectkey = $InfoFieldList[2];
  1655. $keyList = $InfoFieldList[2].' as rowid';
  1656. }
  1657. $fields_label = explode('|', $InfoFieldList[1]);
  1658. if (is_array($fields_label)) {
  1659. $keyList .= ', ';
  1660. $keyList .= implode(', ', $fields_label);
  1661. }
  1662. $filter_categorie = false;
  1663. if (count($InfoFieldList) > 5) {
  1664. if ($InfoFieldList[0] == 'categorie') {
  1665. $filter_categorie = true;
  1666. }
  1667. }
  1668. $sql = 'SELECT '.$keyList;
  1669. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  1670. if (strpos($InfoFieldList[4], 'extra') !== false) {
  1671. $sql .= ' as main';
  1672. }
  1673. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  1674. // $sql.= ' AND entity = '.$conf->entity;
  1675. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  1676. $resql = $this->db->query($sql);
  1677. if ($resql) {
  1678. if ($filter_categorie === false) {
  1679. $value = ''; // value was used, so now we reste it to use it to build final output
  1680. $toprint = array();
  1681. while ($obj = $this->db->fetch_object($resql)) {
  1682. // Several field into label (eq table:code|libelle:rowid)
  1683. $fields_label = explode('|', $InfoFieldList[1]);
  1684. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  1685. if (is_array($fields_label) && count($fields_label) > 1) {
  1686. foreach ($fields_label as $field_toshow) {
  1687. $translabel = '';
  1688. if (!empty($obj->$field_toshow)) {
  1689. $translabel = $langs->trans($obj->$field_toshow);
  1690. }
  1691. if ($translabel != $field_toshow) {
  1692. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  1693. } else {
  1694. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  1695. }
  1696. }
  1697. } else {
  1698. $translabel = '';
  1699. if (!empty($obj->{$InfoFieldList[1]})) {
  1700. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  1701. }
  1702. if ($translabel != $obj->{$InfoFieldList[1]}) {
  1703. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  1704. } else {
  1705. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  1706. }
  1707. }
  1708. }
  1709. }
  1710. } else {
  1711. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1712. $toprint = array();
  1713. while ($obj = $this->db->fetch_object($resql)) {
  1714. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  1715. $c = new Categorie($this->db);
  1716. $c->fetch($obj->rowid);
  1717. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  1718. foreach ($ways as $way) {
  1719. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.img_object('', 'category').' '.$way.'</li>';
  1720. }
  1721. }
  1722. }
  1723. }
  1724. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  1725. } else {
  1726. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  1727. }
  1728. } elseif ($type == 'link') {
  1729. $out = '';
  1730. // Only if something to display (perf)
  1731. if ($value) { // If we have -1 here, pb is into insert, not into ouptut (fix insert instead of changing code here to compensate)
  1732. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  1733. $InfoFieldList = explode(":", $param_list[0]);
  1734. $classname = $InfoFieldList[0];
  1735. $classpath = $InfoFieldList[1];
  1736. if (!empty($classpath)) {
  1737. dol_include_once($InfoFieldList[1]);
  1738. if ($classname && class_exists($classname)) {
  1739. $object = new $classname($this->db);
  1740. $object->fetch($value);
  1741. $value = $object->getNomUrl(3);
  1742. }
  1743. } else {
  1744. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  1745. return 'Error bad setup of extrafield';
  1746. }
  1747. }
  1748. } elseif ($type == 'text') {
  1749. $value = dol_htmlentitiesbr($value);
  1750. } elseif ($type == 'html') {
  1751. $value = dol_htmlentitiesbr($value);
  1752. } elseif ($type == 'password') {
  1753. $value = dol_trunc(preg_replace('/./i', '*', $value), 8, 'right', 'UTF-8', 1);
  1754. } else {
  1755. $showsize = round((float) $size);
  1756. if ($showsize > 48) {
  1757. $showsize = 48;
  1758. }
  1759. }
  1760. //print $type.'-'.$size;
  1761. $out = $value;
  1762. return $out;
  1763. }
  1764. /**
  1765. * Return tag to describe alignement to use for this extrafield
  1766. *
  1767. * @param string $key Key of attribute
  1768. * @param string $extrafieldsobjectkey If defined, use the new method to get extrafields data
  1769. * @return string Formated value
  1770. */
  1771. public function getAlignFlag($key, $extrafieldsobjectkey = '')
  1772. {
  1773. global $conf, $langs;
  1774. if (!empty($extrafieldsobjectkey)) {
  1775. $type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
  1776. } else {
  1777. $type = $this->attribute_type[$key];
  1778. }
  1779. $align = '';
  1780. if ($type == 'date') {
  1781. $align = "center";
  1782. } elseif ($type == 'datetime') {
  1783. $align = "center";
  1784. } elseif ($type == 'int') {
  1785. $align = "right";
  1786. } elseif ($type == 'price') {
  1787. $align = "right";
  1788. } elseif ($type == 'double') {
  1789. $align = "right";
  1790. } elseif ($type == 'boolean') {
  1791. $align = "center";
  1792. } elseif ($type == 'radio') {
  1793. $align = "center";
  1794. } elseif ($type == 'checkbox') {
  1795. $align = "center";
  1796. } elseif ($type == 'price') {
  1797. $align = "right";
  1798. }
  1799. return $align;
  1800. }
  1801. /**
  1802. * Return HTML string to print separator extrafield
  1803. *
  1804. * @param string $key Key of attribute
  1805. * @param string $object Object
  1806. * @param int $colspan Value of colspan to use (it must includes the first column with title)
  1807. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  1808. * @return string HTML code with line for separator
  1809. */
  1810. public function showSeparator($key, $object, $colspan = 2, $display_type = 'card')
  1811. {
  1812. global $langs;
  1813. if ($display_type=='card') {
  1814. $tagtype='tr';
  1815. $tagtype_dyn='td';
  1816. } elseif ($display_type=='line') {
  1817. $tagtype='div';
  1818. $tagtype_dyn='span';
  1819. $colspan=0;
  1820. }
  1821. $out = '<'.$tagtype.' id="trextrafieldseparator'.$key.(!empty($object->id)?'_'.$object->id:'').'" class="trextrafieldseparator trextrafieldseparator'.$key.(!empty($object->id)?'_'.$object->id:'').'">';
  1822. $out .= '<'.$tagtype_dyn.' '.(!empty($colspan)?'colspan="' . $colspan . '"':'').'>';
  1823. $out .='<strong>';
  1824. $out .= $langs->trans($this->attributes[$object->table_element]['label'][$key]);
  1825. $out .= '</strong>';
  1826. $out .= '</'.$tagtype_dyn.'>';
  1827. $out .= '</'.$tagtype.'>';
  1828. $extrafield_param = $this->attributes[$object->table_element]['param'][$key];
  1829. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  1830. $extrafield_param_list = array_keys($extrafield_param['options']);
  1831. if (count($extrafield_param_list) > 0) {
  1832. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  1833. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  1834. // Set the collapse_display status to cookie in priority or if ignorecollapsesetup is 1, if cookie and ignorecollapsesetup not defined, use the setup.
  1835. $collapse_display = ((isset($_COOKIE['DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key]) || GETPOST('ignorecollapsesetup', 'int')) ? ($_COOKIE['DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key] ? true : false) : ($extrafield_collapse_display_value == 2 ? false : true));
  1836. $extrafields_collapse_num = $this->attributes[$object->table_element]['pos'][$key].(!empty($object->id)?'_'.$object->id:'');
  1837. if (!empty($conf->use_javascript_ajax)) {
  1838. $out .= '<!-- Add js script to manage the collapse/uncollapse of extrafields separators '.$key.' -->'."\n";
  1839. $out .= '<script type="text/javascript">'."\n";
  1840. $out .= 'jQuery(document).ready(function(){'."\n";
  1841. if ($collapse_display === false) {
  1842. $out .= ' jQuery("#trextrafieldseparator'.$key.(!empty($object->id)?'_'.$object->id:'').' '.$tagtype_dyn.'").prepend("<span class=\"cursorpointer far fa-plus-square\"></span>&nbsp;");'."\n";
  1843. $out .= ' jQuery(".trextrafields_collapse'.$extrafields_collapse_num.'").hide();'."\n";
  1844. } else {
  1845. $out .= ' jQuery("#trextrafieldseparator'.$key.(!empty($object->id)?'_'.$object->id:'').' '.$tagtype_dyn.'").prepend("<span class=\"cursorpointer far fa-minus-square\"></span>&nbsp;");'."\n";
  1846. $out .= ' document.cookie = "DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key.'=1; path='.$_SERVER["PHP_SELF"].'"'."\n";
  1847. }
  1848. $out .= ' jQuery("#trextrafieldseparator'.$key.(!empty($object->id)?'_'.$object->id:'').'").click(function(){'."\n";
  1849. $out .= ' console.log("We click on collapse/uncollapse .trextrafields_collapse'.$extrafields_collapse_num.'");'."\n";
  1850. $out .= ' jQuery(".trextrafields_collapse'.$extrafields_collapse_num.'").toggle(300, function(){'."\n";
  1851. $out .= ' if (jQuery(".trextrafields_collapse'.$extrafields_collapse_num.'").is(":hidden")) {'."\n";
  1852. $out .= ' jQuery("#trextrafieldseparator'.$key.(!empty($object->id)?'_'.$object->id:'').' '.$tagtype_dyn.' span").addClass("fa-plus-square").removeClass("fa-minus-square");'."\n";
  1853. $out .= ' document.cookie = "DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key.'=0; path='.$_SERVER["PHP_SELF"].'"'."\n";
  1854. $out .= ' } else {'."\n";
  1855. $out .= ' jQuery("#trextrafieldseparator'.$key.(!empty($object->id)?'_'.$object->id:'').' '.$tagtype_dyn.' span").addClass("fa-minus-square").removeClass("fa-plus-square");'."\n";
  1856. $out .= ' document.cookie = "DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key.'=1; path='.$_SERVER["PHP_SELF"].'"'."\n";
  1857. $out .= ' }'."\n";
  1858. $out .= ' });'."\n";
  1859. $out .= ' });'."\n";
  1860. $out .= '});'."\n";
  1861. $out .= '</script>'."\n";
  1862. }
  1863. }
  1864. }
  1865. }
  1866. return $out;
  1867. }
  1868. /**
  1869. * Fill array_options property of object by extrafields value (using for data sent by forms)
  1870. *
  1871. * @param array $extralabels Deprecated (old $array of extrafields, now set this to null)
  1872. * @param object $object Object
  1873. * @param string $onlykey Only some keys are filled:$this
  1874. * 'string' => When we make update of only one extrafield ($action = 'update_extras'), calling page can set this to avoid to have other extrafields being reset.
  1875. * '@GETPOSTISSET' => When we make update of extrafields ($action = 'update'), calling page can set this to avoid to have fields not into POST being reset.
  1876. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  1877. */
  1878. public function setOptionalsFromPost($extralabels, &$object, $onlykey = '')
  1879. {
  1880. global $_POST, $langs;
  1881. $nofillrequired = 0; // For error when required field left blank
  1882. $error_field_required = array();
  1883. if (isset($this->attributes[$object->table_element]['label']) && is_array($this->attributes[$object->table_element]['label'])) {
  1884. $extralabels = $this->attributes[$object->table_element]['label'];
  1885. }
  1886. if (is_array($extralabels)) {
  1887. // Get extra fields
  1888. foreach ($extralabels as $key => $value) {
  1889. if (!empty($onlykey) && $onlykey != '@GETPOSTISSET' && $key != $onlykey) {
  1890. continue;
  1891. }
  1892. if (!empty($onlykey) && $onlykey == '@GETPOSTISSET' && !GETPOSTISSET('options_'.$key)) {
  1893. continue;
  1894. }
  1895. $key_type = $this->attributes[$object->table_element]['type'][$key];
  1896. if ($key_type == 'separate') {
  1897. continue;
  1898. }
  1899. $enabled = 1;
  1900. if (isset($this->attributes[$object->table_element]['list'][$key])) {
  1901. $enabled = dol_eval($this->attributes[$object->table_element]['list'][$key], 1);
  1902. }
  1903. $perms = 1;
  1904. if (isset($this->attributes[$object->table_element]['perms'][$key])) {
  1905. $perms = dol_eval($this->attributes[$object->table_element]['perms'][$key], 1);
  1906. }
  1907. if (empty($enabled)) {
  1908. continue;
  1909. }
  1910. if (empty($perms)) {
  1911. continue;
  1912. }
  1913. if ($this->attributes[$object->table_element]['required'][$key]) { // Value is required
  1914. // Check if functionally empty without using GETPOST (depending on the type of extrafield, a
  1915. // technically non-empty value may be treated as empty functionally).
  1916. // value can be alpha, int, array, etc...
  1917. if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] != 'select' && $_POST["options_".$key] != '0')
  1918. || (!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'select')
  1919. || (!is_array($_POST["options_".$key]) && isset($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'sellist' && $_POST['options_'.$key] == '0')
  1920. || (is_array($_POST["options_".$key]) && empty($_POST["options_".$key]))) {
  1921. //print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key];
  1922. $nofillrequired++;
  1923. $error_field_required[] = $langs->transnoentitiesnoconv($value);
  1924. }
  1925. }
  1926. if (in_array($key_type, array('date'))) {
  1927. // Clean parameters
  1928. $value_key = dol_mktime(12, 0, 0, GETPOST("options_".$key."month", 'int'), GETPOST("options_".$key."day", 'int'), GETPOST("options_".$key."year", 'int'));
  1929. } elseif (in_array($key_type, array('datetime'))) {
  1930. // Clean parameters
  1931. $value_key = dol_mktime(GETPOST("options_".$key."hour", 'int'), GETPOST("options_".$key."min", 'int'), GETPOST("options_".$key."sec", 'int'), GETPOST("options_".$key."month", 'int'), GETPOST("options_".$key."day", 'int'), GETPOST("options_".$key."year", 'int'), 'tzuserrel');
  1932. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  1933. $value_arr = GETPOST("options_".$key, 'array'); // check if an array
  1934. if (!empty($value_arr)) {
  1935. $value_key = implode($value_arr, ',');
  1936. } else {
  1937. $value_key = '';
  1938. }
  1939. } elseif (in_array($key_type, array('price', 'double'))) {
  1940. $value_arr = GETPOST("options_".$key, 'alpha');
  1941. $value_key = price2num($value_arr);
  1942. } elseif (in_array($key_type, array('html'))) {
  1943. $value_key = GETPOST("options_".$key, 'restricthtml');
  1944. } elseif (in_array($key_type, array('text'))) {
  1945. $value_key = GETPOST("options_".$key, 'alphanohtml');
  1946. } else {
  1947. $value_key = GETPOST("options_".$key);
  1948. if (in_array($key_type, array('link')) && $value_key == '-1') {
  1949. $value_key = '';
  1950. }
  1951. }
  1952. $object->array_options["options_".$key] = $value_key;
  1953. }
  1954. if ($nofillrequired) {
  1955. $langs->load('errors');
  1956. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  1957. return -1;
  1958. } else {
  1959. return 1;
  1960. }
  1961. } else {
  1962. return 0;
  1963. }
  1964. }
  1965. /**
  1966. * return array_options array of data of extrafields value of object sent by a search form
  1967. *
  1968. * @param array|string $extrafieldsobjectkey array of extrafields (old usage) or value of object->table_element (new usage)
  1969. * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  1970. * @param string $keysuffix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  1971. * @return array|int array_options set or 0 if no value
  1972. */
  1973. public function getOptionalsFromPost($extrafieldsobjectkey, $keyprefix = '', $keysuffix = '')
  1974. {
  1975. global $_POST;
  1976. if (is_string($extrafieldsobjectkey) && !empty($this->attributes[$extrafieldsobjectkey]['label']) && is_array($this->attributes[$extrafieldsobjectkey]['label'])) {
  1977. $extralabels = $this->attributes[$extrafieldsobjectkey]['label'];
  1978. } else {
  1979. $extralabels = $extrafieldsobjectkey;
  1980. }
  1981. if (is_array($extralabels)) {
  1982. $array_options = array();
  1983. // Get extra fields
  1984. foreach ($extralabels as $key => $value) {
  1985. $key_type = '';
  1986. if (is_string($extrafieldsobjectkey)) {
  1987. $key_type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
  1988. }
  1989. if (in_array($key_type, array('date'))) {
  1990. $dateparamname_start = $keysuffix . 'options_' . $key . $keyprefix . '_start';
  1991. $dateparamname_end = $keysuffix . 'options_' . $key . $keyprefix . '_end';
  1992. if (GETPOSTISSET($dateparamname_start . 'year') && GETPOSTISSET($dateparamname_end . 'year')) {
  1993. // values provided as a date pair (start date + end date), each date being broken down as year, month, day, etc.
  1994. $value_key = array(
  1995. 'start' => dol_mktime(0, 0, 0, GETPOST($dateparamname_start . 'month', 'int'), GETPOST($dateparamname_start . 'day', 'int'), GETPOST($dateparamname_start . 'year', 'int')),
  1996. 'end' => dol_mktime(23, 59, 59, GETPOST($dateparamname_end . 'month', 'int'), GETPOST($dateparamname_end . 'day', 'int'), GETPOST($dateparamname_end . 'year', 'int'))
  1997. );
  1998. } elseif (GETPOSTISSET($keysuffix."options_".$key.$keyprefix."year")) {
  1999. // Clean parameters
  2000. $value_key = dol_mktime(12, 0, 0, GETPOST($keysuffix."options_".$key.$keyprefix."month", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."day", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."year", 'int'));
  2001. } else {
  2002. continue; // Value was not provided, we should not set it.
  2003. }
  2004. } elseif (in_array($key_type, array('datetime'))) {
  2005. $dateparamname_start = $keysuffix . 'options_' . $key . $keyprefix . '_start';
  2006. $dateparamname_end = $keysuffix . 'options_' . $key . $keyprefix . '_end';
  2007. if (GETPOSTISSET($dateparamname_start . 'year') && GETPOSTISSET($dateparamname_end . 'year')) {
  2008. // values provided as a date pair (start date + end date), each date being broken down as year, month, day, etc.
  2009. $value_key = array(
  2010. 'start' => dol_mktime(GETPOST($dateparamname_start . 'hour', 'int'), GETPOST($dateparamname_start . 'min', 'int'), GETPOST($dateparamname_start . 'sec', 'int'), GETPOST($dateparamname_start . 'month', 'int'), GETPOST($dateparamname_start . 'day', 'int'), GETPOST($dateparamname_start . 'year', 'int'), 'tzuserrel'),
  2011. 'end' => dol_mktime(GETPOST($dateparamname_end . 'hour', 'int'), GETPOST($dateparamname_start . 'min', 'int'), GETPOST($dateparamname_start . 'sec', 'int'), GETPOST($dateparamname_end . 'month', 'int'), GETPOST($dateparamname_end . 'day', 'int'), GETPOST($dateparamname_end . 'year', 'int'), 'tzuserrel')
  2012. );
  2013. } elseif (GETPOSTISSET($keysuffix."options_".$key.$keyprefix."year")) {
  2014. // Clean parameters
  2015. $value_key = dol_mktime(GETPOST($keysuffix."options_".$key.$keyprefix."hour", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."min", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."sec", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."month", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."day", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."year", 'int'), 'tzuserrel');
  2016. } else {
  2017. continue; // Value was not provided, we should not set it.
  2018. }
  2019. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  2020. if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) {
  2021. continue; // Value was not provided, we should not set it.
  2022. }
  2023. $value_arr = GETPOST($keysuffix."options_".$key.$keyprefix);
  2024. // Make sure we get an array even if there's only one checkbox
  2025. $value_arr = (array) $value_arr;
  2026. $value_key = implode(',', $value_arr);
  2027. } elseif (in_array($key_type, array('price', 'double', 'int'))) {
  2028. if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) {
  2029. continue; // Value was not provided, we should not set it.
  2030. }
  2031. $value_arr = GETPOST($keysuffix."options_".$key.$keyprefix);
  2032. if ($keysuffix != 'search_') { // If value is for a search, we must keep complex string like '>100 <=150'
  2033. $value_key = price2num($value_arr);
  2034. } else {
  2035. $value_key = $value_arr;
  2036. }
  2037. } else {
  2038. if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) {
  2039. continue; // Value was not provided, we should not set it.
  2040. }
  2041. $value_key = GETPOST($keysuffix."options_".$key.$keyprefix);
  2042. }
  2043. $array_options[$keysuffix."options_".$key] = $value_key; // No keyprefix here. keyprefix is used only for read.
  2044. }
  2045. return $array_options;
  2046. }
  2047. return 0;
  2048. }
  2049. }