html.formsetup.class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. <?php
  2. /* Copyright (C) 2021 John BOTELLA <john.botella@atm-consulting.fr>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * This class help you create setup render
  19. */
  20. class FormSetup
  21. {
  22. /**
  23. * @var DoliDB Database handler.
  24. */
  25. public $db;
  26. /** @var FormSetupItem[] */
  27. public $items = array();
  28. /**
  29. * @var int
  30. */
  31. public $setupNotEmpty = 0;
  32. /** @var Translate */
  33. public $langs;
  34. /** @var Form */
  35. public $form;
  36. /** @var int */
  37. protected $maxItemRank;
  38. /**
  39. * this is an html string display before output form
  40. * @var string
  41. */
  42. public $htmlBeforeOutputForm = '';
  43. /**
  44. * this is an html string display after output form
  45. * @var string
  46. */
  47. public $htmlAfterOutputForm = '';
  48. /**
  49. * this is an html string display on buttons zone
  50. * @var string
  51. */
  52. public $htmlOutputMoreButton = '';
  53. /**
  54. *
  55. * @var array
  56. */
  57. public $formAttributes = array(
  58. 'action' => '', // set in __construct
  59. 'method' => 'POST'
  60. );
  61. /**
  62. * an list of hidden inputs used only in edit mode
  63. * @var array
  64. */
  65. public $formHiddenInputs = array();
  66. /**
  67. * Constructor
  68. *
  69. * @param DoliDB $db Database handler
  70. * @param Translate $outputLangs if needed can use another lang
  71. */
  72. public function __construct($db, $outputLangs = false)
  73. {
  74. global $langs;
  75. $this->db = $db;
  76. $this->form = new Form($this->db);
  77. $this->formAttributes['action'] = $_SERVER["PHP_SELF"];
  78. $this->formHiddenInputs['token'] = newToken();
  79. $this->formHiddenInputs['action'] = 'update';
  80. if ($outputLangs) {
  81. $this->langs = $outputLangs;
  82. } else {
  83. $this->langs = $langs;
  84. }
  85. }
  86. /**
  87. * Generate an attributes string form an input array
  88. *
  89. * @param array $attributes an array of attributes keys and values,
  90. * @return string attribute string
  91. */
  92. static public function generateAttributesStringFromArray($attributes)
  93. {
  94. $Aattr = array();
  95. if (is_array($attributes)) {
  96. foreach ($attributes as $attribute => $value) {
  97. if (is_array($value) || is_object($value)) {
  98. continue;
  99. }
  100. $Aattr[] = $attribute.'="'.dol_escape_htmltag($value).'"';
  101. }
  102. }
  103. return !empty($Aattr)?implode(' ', $Aattr):'';
  104. }
  105. /**
  106. * generateOutput
  107. *
  108. * @param bool $editMode true will display output on edit mod
  109. * @return string html output
  110. */
  111. public function generateOutput($editMode = false)
  112. {
  113. global $hookmanager, $action, $langs;
  114. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  115. $parameters = array(
  116. 'editMode' => $editMode
  117. );
  118. $reshook = $hookmanager->executeHooks('formSetupBeforeGenerateOutput', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  119. if ($reshook < 0) {
  120. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  121. }
  122. if ($reshook > 0) {
  123. return $hookmanager->resPrint;
  124. } else {
  125. $out = '<!-- Start generateOutput from FormSetup class -->';
  126. $out.= $this->htmlBeforeOutputForm;
  127. if ($editMode) {
  128. $out.= '<form ' . self::generateAttributesStringFromArray($this->formAttributes) . ' >';
  129. // generate hidden values from $this->formHiddenInputs
  130. if (!empty($this->formHiddenInputs) && is_array($this->formHiddenInputs)) {
  131. foreach ($this->formHiddenInputs as $hiddenKey => $hiddenValue) {
  132. $out.= '<input type="hidden" name="'.dol_escape_htmltag($hiddenKey).'" value="' . dol_escape_htmltag($hiddenValue) . '">';
  133. }
  134. }
  135. }
  136. // generate output table
  137. $out .= $this->generateTableOutput($editMode);
  138. $reshook = $hookmanager->executeHooks('formSetupBeforeGenerateOutputButton', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  139. if ($reshook < 0) {
  140. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  141. }
  142. if ($reshook > 0) {
  143. return $hookmanager->resPrint;
  144. } elseif ($editMode) {
  145. $out .= '<br>'; // Todo : remove this <br/> by adding style to form-setup-button-container css class in all themes
  146. $out .= '<div class="form-setup-button-container center">'; // Todo : remove .center by adding style to form-setup-button-container css class in all themes
  147. $out.= $this->htmlOutputMoreButton;
  148. $out .= '<input class="button button-save" type="submit" value="' . $this->langs->trans("Save") . '">'; // Todo fix dolibarr style for <button and use <button instead of input
  149. $out .= ' &nbsp;&nbsp; ';
  150. $out .= '<a class="button button-cancel" type="submit" href="' . $this->formAttributes['action'] . '">'.$langs->trans('Cancel').'</a>';
  151. $out .= '</div>';
  152. }
  153. if ($editMode) {
  154. $out .= '</form>';
  155. }
  156. $out.= $this->htmlAfterOutputForm;
  157. return $out;
  158. }
  159. }
  160. /**
  161. * generateTableOutput
  162. *
  163. * @param bool $editMode true will display output on edit mod
  164. * @return string html output
  165. */
  166. public function generateTableOutput($editMode = false)
  167. {
  168. global $hookmanager, $action;
  169. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  170. $parameters = array(
  171. 'editMode' => $editMode
  172. );
  173. $reshook = $hookmanager->executeHooks('formSetupBeforeGenerateTableOutput', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  174. if ($reshook < 0) {
  175. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  176. }
  177. if ($reshook > 0) {
  178. return $hookmanager->resPrint;
  179. } else {
  180. $out = '<table class="noborder centpercent">';
  181. $out .= '<thead>';
  182. $out .= '<tr class="liste_titre">';
  183. $out .= ' <td>' . $this->langs->trans("Parameter") . '</td>';
  184. $out .= ' <td>' . $this->langs->trans("Value") . '</td>';
  185. $out .= '</tr>';
  186. $out .= '</thead>';
  187. // Sort items before render
  188. $this->sortingItems();
  189. $out .= '<tbody>';
  190. foreach ($this->items as $item) {
  191. $out .= $this->generateLineOutput($item, $editMode);
  192. }
  193. $out .= '</tbody>';
  194. $out .= '</table>';
  195. return $out;
  196. }
  197. }
  198. /**
  199. * saveConfFromPost
  200. *
  201. * @param bool $noMessageInUpdate display event message on errors and success
  202. * @return int -1 if KO, 1 if OK
  203. */
  204. public function saveConfFromPost($noMessageInUpdate = false)
  205. {
  206. global $hookmanager;
  207. $parameters = array();
  208. $reshook = $hookmanager->executeHooks('formSetupBeforeSaveConfFromPost', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  209. if ($reshook < 0) {
  210. $this->setErrors($hookmanager->errors);
  211. return -1;
  212. }
  213. if ($reshook > 0) {
  214. return $reshook;
  215. }
  216. if (empty($this->items)) {
  217. return null;
  218. }
  219. $this->db->begin();
  220. $error = 0;
  221. foreach ($this->items as $item) {
  222. $res = $item->setValueFromPost();
  223. if ($res > 0) {
  224. $item->saveConfValue();
  225. } elseif ($res < 0) {
  226. $error++;
  227. break;
  228. }
  229. }
  230. if (!$error) {
  231. $this->db->commit();
  232. if (empty($noMessageInUpdate)) {
  233. setEventMessages($this->langs->trans("SetupSaved"), null);
  234. }
  235. return 1;
  236. } else {
  237. $this->db->rollback();
  238. if (empty($noMessageInUpdate)) {
  239. setEventMessages($this->langs->trans("SetupNotSaved"), null, 'errors');
  240. }
  241. return -1;
  242. }
  243. }
  244. /**
  245. * generateLineOutput
  246. *
  247. * @param FormSetupItem $item the setup item
  248. * @param bool $editMode Display as edit mod
  249. * @return string the html output for an setup item
  250. */
  251. public function generateLineOutput($item, $editMode = false)
  252. {
  253. $out = '';
  254. if ($item->enabled==1) {
  255. $trClass = 'oddeven';
  256. if ($item->getType() == 'title') {
  257. $trClass = 'liste_titre';
  258. }
  259. $this->setupNotEmpty++;
  260. $out.= '<tr class="'.$trClass.'">';
  261. $out.= '<td class="col-setup-title">';
  262. $out.= '<span id="helplink'.$item->confKey.'" class="spanforparamtooltip">';
  263. $out.= $this->form->textwithpicto($item->getNameText(), $item->getHelpText(), 1, 'info', '', 0, 3, 'tootips'.$item->confKey);
  264. $out.= '</span>';
  265. $out.= '</td>';
  266. $out.= '<td>';
  267. if ($editMode) {
  268. $out.= $item->generateInputField();
  269. } else {
  270. $out.= $item->generateOutputField();
  271. }
  272. if (!empty($item->errors)) {
  273. // TODO : move set event message in a methode to be called by cards not by this class
  274. setEventMessages(null, $item->errors, 'errors');
  275. }
  276. $out.= '</td>';
  277. $out.= '</tr>';
  278. }
  279. return $out;
  280. }
  281. /**
  282. * Method used to test module builder convertion to this form usage
  283. *
  284. * @param array $params an array of arrays of params from old modulBuilder params
  285. * @return null
  286. */
  287. public function addItemsFromParamsArray($params)
  288. {
  289. if (!is_array($params) || empty($params)) { return false; }
  290. foreach ($params as $confKey => $param) {
  291. $this->addItemFromParams($confKey, $param); // todo manage error
  292. }
  293. }
  294. /**
  295. * From old
  296. * Method was used to test module builder convertion to this form usage.
  297. *
  298. * @param string $confKey the conf name to store
  299. * @param array $params an array of params from old modulBuilder params
  300. * @return bool
  301. */
  302. public function addItemFromParams($confKey, $params)
  303. {
  304. if (empty($confKey) || empty($params['type'])) { return false; }
  305. /*
  306. * Exemple from old module builder setup page
  307. * // 'MYMODULE_MYPARAM1'=>array('type'=>'string', 'css'=>'minwidth500' ,'enabled'=>1),
  308. // 'MYMODULE_MYPARAM2'=>array('type'=>'textarea','enabled'=>1),
  309. //'MYMODULE_MYPARAM3'=>array('type'=>'category:'.Categorie::TYPE_CUSTOMER, 'enabled'=>1),
  310. //'MYMODULE_MYPARAM4'=>array('type'=>'emailtemplate:thirdparty', 'enabled'=>1),
  311. //'MYMODULE_MYPARAM5'=>array('type'=>'yesno', 'enabled'=>1),
  312. //'MYMODULE_MYPARAM5'=>array('type'=>'thirdparty_type', 'enabled'=>1),
  313. //'MYMODULE_MYPARAM6'=>array('type'=>'securekey', 'enabled'=>1),
  314. //'MYMODULE_MYPARAM7'=>array('type'=>'product', 'enabled'=>1),
  315. */
  316. $item = new FormSetupItem($confKey);
  317. // need to be ignored from scrutinizer setTypeFromTypeString was created as deprecated to incite developper to use object oriented usage
  318. /** @scrutinizer ignore-deprecated */ $item->setTypeFromTypeString($params['type']);
  319. if (!empty($params['enabled'])) {
  320. $item->enabled = $params['enabled'];
  321. }
  322. if (!empty($params['css'])) {
  323. $item->cssClass = $params['css'];
  324. }
  325. $this->items[$item->confKey] = $item;
  326. return true;
  327. }
  328. /**
  329. * Used to export param array for /core/actions_setmoduleoptions.inc.php template
  330. * Method exists only for manage setup convertion
  331. *
  332. * @return array $arrayofparameters for /core/actions_setmoduleoptions.inc.php
  333. */
  334. public function exportItemsAsParamsArray()
  335. {
  336. $arrayofparameters = array();
  337. foreach ($this->items as $item) {
  338. $arrayofparameters[$item->confKey] = array(
  339. 'type' => $item->getType(),
  340. 'enabled' => $item->enabled
  341. );
  342. }
  343. return $arrayofparameters;
  344. }
  345. /**
  346. * Reload for each item default conf
  347. * note: this will override custom configuration
  348. *
  349. * @return bool
  350. */
  351. public function reloadConfs()
  352. {
  353. if (!array($this->items)) { return false; }
  354. foreach ($this->items as $item) {
  355. $item->loadValueFromConf();
  356. }
  357. return true;
  358. }
  359. /**
  360. * Create a new item
  361. * the tagret is useful with hooks : that allow externals modules to add setup items on good place
  362. *
  363. * @param string $confKey the conf key used in database
  364. * @param string $targetItemKey target item used to place the new item beside
  365. * @param bool $insertAfterTarget insert before or after target item ?
  366. * @return FormSetupItem the new setup item created
  367. */
  368. public function newItem($confKey, $targetItemKey = false, $insertAfterTarget = false)
  369. {
  370. $item = new FormSetupItem($confKey);
  371. // set item rank if not defined as last item
  372. if (empty($item->rank)) {
  373. $item->rank = $this->getCurentItemMaxRank() + 1;
  374. $this->setItemMaxRank($item->rank); // set new max rank if needed
  375. }
  376. // try to get rank from target column, this will override item->rank
  377. if (!empty($targetItemKey)) {
  378. if (isset($this->items[$targetItemKey])) {
  379. $targetItem = $this->items[$targetItemKey];
  380. $item->rank = $targetItem->rank; // $targetItem->rank will be increase after
  381. if ($targetItem->rank >= 0 && $insertAfterTarget) {
  382. $item->rank++;
  383. }
  384. }
  385. // calc new rank for each item to make place for new item
  386. foreach ($this->items as $fItem) {
  387. if ($item->rank <= $fItem->rank) {
  388. $fItem->rank = $fItem->rank + 1;
  389. $this->setItemMaxRank($fItem->rank); // set new max rank if needed
  390. }
  391. }
  392. }
  393. $this->items[$item->confKey] = $item;
  394. return $this->items[$item->confKey];
  395. }
  396. /**
  397. * Sort items according to rank
  398. *
  399. * @return bool
  400. */
  401. public function sortingItems()
  402. {
  403. // Sorting
  404. return uasort($this->items, array($this, 'itemSort'));
  405. }
  406. /**
  407. * getCurentItemMaxRank
  408. *
  409. * @param bool $cache To use cache or not
  410. * @return int
  411. */
  412. public function getCurentItemMaxRank($cache = true)
  413. {
  414. if (empty($this->items)) {
  415. return 0;
  416. }
  417. if ($cache && $this->maxItemRank > 0) {
  418. return $this->maxItemRank;
  419. }
  420. $this->maxItemRank = 0;
  421. foreach ($this->items as $item) {
  422. $this->maxItemRank = max($this->maxItemRank, $item->rank);
  423. }
  424. return $this->maxItemRank;
  425. }
  426. /**
  427. * set new max rank if needed
  428. *
  429. * @param int $rank the item rank
  430. * @return int|void new max rank
  431. */
  432. public function setItemMaxRank($rank)
  433. {
  434. $this->maxItemRank = max($this->maxItemRank, $rank);
  435. }
  436. /**
  437. * get item position rank from item key
  438. *
  439. * @param string $itemKey the item key
  440. * @return int rank on success and -1 on error
  441. */
  442. public function getLineRank($itemKey)
  443. {
  444. if (!isset($this->items[$itemKey]->rank)) {
  445. return -1;
  446. }
  447. return $this->items[$itemKey]->rank;
  448. }
  449. /**
  450. * uasort callback function to Sort params items
  451. *
  452. * @param FormSetupItem $a formSetup item
  453. * @param FormSetupItem $b formSetup item
  454. * @return int Return compare result
  455. */
  456. public function itemSort(FormSetupItem $a, FormSetupItem $b)
  457. {
  458. if (empty($a->rank)) {
  459. $a->rank = 0;
  460. }
  461. if (empty($b->rank)) {
  462. $b->rank = 0;
  463. }
  464. if ($a->rank == $b->rank) {
  465. return 0;
  466. }
  467. return ($a->rank < $b->rank) ? -1 : 1;
  468. }
  469. }
  470. /**
  471. * This class help to create item for class formSetup
  472. */
  473. class FormSetupItem
  474. {
  475. /**
  476. * @var DoliDB Database handler.
  477. */
  478. public $db;
  479. /** @var Translate */
  480. public $langs;
  481. /** @var int */
  482. public $entity;
  483. /** @var Form */
  484. public $form;
  485. /** @var string $confKey the conf key used in database */
  486. public $confKey;
  487. /** @var string|false $nameText */
  488. public $nameText = false;
  489. /** @var string $helpText */
  490. public $helpText = '';
  491. /** @var string $fieldValue */
  492. public $fieldValue;
  493. /** @var string $defaultFieldValue */
  494. public $defaultFieldValue = null;
  495. /** @var array $fieldAttr fields attribute only for compatible fields like input text */
  496. public $fieldAttr = array();
  497. /** @var bool|string set this var to override field output will override $fieldInputOverride and $fieldOutputOverride too */
  498. public $fieldOverride = false;
  499. /** @var bool|string set this var to override field input */
  500. public $fieldInputOverride = false;
  501. /** @var bool|string set this var to override field output */
  502. public $fieldOutputOverride = false;
  503. /** @var int $rank */
  504. public $rank = 0;
  505. /** @var array set this var for options on select and multiselect items */
  506. public $fieldOptions = array();
  507. /** @var callable $saveCallBack */
  508. public $saveCallBack;
  509. /** @var callable $setValueFromPostCallBack */
  510. public $setValueFromPostCallBack;
  511. /**
  512. * @var string $errors
  513. */
  514. public $errors = array();
  515. /**
  516. * TODO each type must have setAs{type} method to help configuration
  517. * And set var as protected when its done configuration must be done by method
  518. * this is important for retrocompatibility of futures versions
  519. * @var string $type 'string', 'textarea', 'category:'.Categorie::TYPE_CUSTOMER', 'emailtemplate', 'thirdparty_type'
  520. */
  521. protected $type = 'string';
  522. public $enabled = 1;
  523. public $cssClass = '';
  524. /**
  525. * Constructor
  526. *
  527. * @param string $confKey the conf key used in database
  528. */
  529. public function __construct($confKey)
  530. {
  531. global $langs, $db, $conf, $form;
  532. $this->db = $db;
  533. if (!empty($form) && is_object($form) && get_class($form) == 'Form') { // the form class has a cache inside so I am using it to optimize
  534. $this->form = $form;
  535. } else {
  536. $this->form = new Form($this->db);
  537. }
  538. $this->langs = $langs;
  539. $this->entity = $conf->entity;
  540. $this->confKey = $confKey;
  541. $this->loadValueFromConf();
  542. }
  543. /**
  544. * load conf value from databases
  545. * @return bool
  546. */
  547. public function loadValueFromConf()
  548. {
  549. global $conf;
  550. if (isset($conf->global->{$this->confKey})) {
  551. $this->fieldValue = $conf->global->{$this->confKey};
  552. return true;
  553. } else {
  554. $this->fieldValue = null;
  555. return false;
  556. }
  557. }
  558. /**
  559. * reload conf value from databases is an aliase of loadValueFromConf
  560. * @deprecated
  561. * @return bool
  562. */
  563. public function reloadValueFromConf()
  564. {
  565. return $this->loadValueFromConf();
  566. }
  567. /**
  568. * Save const value based on htdocs/core/actions_setmoduleoptions.inc.php
  569. * @return int -1 if KO, 1 if OK
  570. */
  571. public function saveConfValue()
  572. {
  573. global $hookmanager;
  574. $parameters = array();
  575. $reshook = $hookmanager->executeHooks('formSetupBeforeSaveConfValue', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  576. if ($reshook < 0) {
  577. $this->setErrors($hookmanager->errors);
  578. return -1;
  579. }
  580. if ($reshook > 0) {
  581. return $reshook;
  582. }
  583. if (!empty($this->saveCallBack) && is_callable($this->saveCallBack)) {
  584. return call_user_func($this->saveCallBack, $this);
  585. }
  586. // Modify constant only if key was posted (avoid resetting key to the null value)
  587. if ($this->type != 'title') {
  588. $result = dolibarr_set_const($this->db, $this->confKey, $this->fieldValue, 'chaine', 0, '', $this->entity);
  589. if ($result < 0) {
  590. return -1;
  591. } else {
  592. return 1;
  593. }
  594. }
  595. }
  596. /**
  597. * Set an override function for saving data
  598. * @param callable $callBack a callable function
  599. * @return void
  600. */
  601. public function setSaveCallBack(callable $callBack)
  602. {
  603. $this->saveCallBack = $callBack;
  604. }
  605. /**
  606. * Set an override function for get data from post
  607. * @param callable $callBack a callable function
  608. * @return void
  609. */
  610. public function setValueFromPostCallBack(callable $callBack)
  611. {
  612. $this->setValueFromPostCallBack = $callBack;
  613. }
  614. /**
  615. * Save const value based on htdocs/core/actions_setmoduleoptions.inc.php
  616. * @return int -1 if KO, 0 nothing to do , 1 if OK
  617. */
  618. public function setValueFromPost()
  619. {
  620. if (!empty($this->setValueFromPostCallBack) && is_callable($this->setValueFromPostCallBack)) {
  621. return call_user_func($this->setValueFromPostCallBack);
  622. }
  623. // Modify constant only if key was posted (avoid resetting key to the null value)
  624. if ($this->type != 'title') {
  625. if (preg_match('/category:/', $this->type)) {
  626. if (GETPOST($this->confKey, 'int') == '-1') {
  627. $val_const = '';
  628. } else {
  629. $val_const = GETPOST($this->confKey, 'int');
  630. }
  631. } elseif ($this->type == 'multiselect') {
  632. $val = GETPOST($this->confKey, 'array');
  633. if ($val && is_array($val)) {
  634. $val_const = implode(',', $val);
  635. } else {
  636. $val_const = '';
  637. }
  638. } elseif ($this->type == 'html') {
  639. $val_const = GETPOST($this->confKey, 'restricthtml');
  640. } else {
  641. $val_const = GETPOST($this->confKey, 'alpha');
  642. }
  643. // TODO add value check with class validate
  644. $this->fieldValue = $val_const;
  645. return 1;
  646. }
  647. return 0;
  648. }
  649. /**
  650. * Get help text or generate it
  651. * @return int|string
  652. */
  653. public function getHelpText()
  654. {
  655. if (!empty($this->helpText)) { return $this->helpText; }
  656. return (($this->langs->trans($this->confKey . 'Tooltip') != $this->confKey . 'Tooltip') ? $this->langs->trans($this->confKey . 'Tooltip') : '');
  657. }
  658. /**
  659. * Get field name text or generate it
  660. * @return false|int|string
  661. */
  662. public function getNameText()
  663. {
  664. if (!empty($this->nameText)) { return $this->nameText; }
  665. return (($this->langs->trans($this->confKey) != $this->confKey) ? $this->langs->trans($this->confKey) : $this->langs->trans('MissingTranslationForConfKey', $this->confKey));
  666. }
  667. /**
  668. * generate input field
  669. * @return bool|string
  670. */
  671. public function generateInputField()
  672. {
  673. global $conf;
  674. if (!empty($this->fieldOverride)) {
  675. return $this->fieldOverride;
  676. }
  677. if (!empty($this->fieldInputOverride)) {
  678. return $this->fieldInputOverride;
  679. }
  680. // Set default value
  681. if (is_null($this->fieldValue)) {
  682. $this->fieldValue = $this->defaultFieldValue;
  683. }
  684. $this->fieldAttr['name'] = $this->confKey;
  685. $this->fieldAttr['id'] = 'setup-'.$this->confKey;
  686. $this->fieldAttr['value'] = $this->fieldValue;
  687. $out = '';
  688. if ($this->type == 'title') {
  689. $out.= $this->generateOutputField(); // title have no input
  690. } elseif ($this->type == 'multiselect') {
  691. $out.= $this->generateInputFieldMultiSelect();
  692. } elseif ($this->type == 'select') {
  693. $out.= $this->generateInputFieldSelect();
  694. } elseif ($this->type == 'textarea') {
  695. $out.= $this->generateInputFieldTextarea();
  696. } elseif ($this->type== 'html') {
  697. $out.= $this->generateInputFieldHtml();
  698. } elseif ($this->type== 'color') {
  699. $out.= $this->generateInputFieldColor();
  700. } elseif ($this->type == 'yesno') {
  701. if (!empty($conf->use_javascript_ajax)) {
  702. $out.= ajax_constantonoff($this->confKey);
  703. } else {
  704. $out.= $this->form->selectyesno($this->confKey, $this->fieldValue, 1);
  705. }
  706. } elseif (preg_match('/emailtemplate:/', $this->type)) {
  707. $out.= $this->generateInputFieldEmailTemplate();
  708. } elseif (preg_match('/category:/', $this->type)) {
  709. $out.=$this->generateInputFieldCategories();
  710. } elseif (preg_match('/thirdparty_type/', $this->type)) {
  711. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
  712. $formcompany = new FormCompany($this->db);
  713. $out.= $formcompany->selectProspectCustomerType($this->fieldValue, $this->confKey);
  714. } elseif ($this->type == 'securekey') {
  715. $out.= $this->generateInputFieldSecureKey();
  716. } elseif ($this->type == 'product') {
  717. if (isModEnabled("product") || isModEnabled("service")) {
  718. $selected = (empty($this->fieldValue) ? '' : $this->fieldValue);
  719. $out.= $this->form->select_produits($selected, $this->confKey, '', 0, 0, 1, 2, '', 0, array(), 0, '1', 0, $this->cssClass, 0, '', null, 1);
  720. }
  721. } else {
  722. $out.= $this->generateInputFieldText();
  723. }
  724. return $out;
  725. }
  726. /**
  727. * generatec default input field
  728. * @return string
  729. */
  730. public function generateInputFieldText()
  731. {
  732. if (empty($this->fieldAttr)) { $this->fieldAttr['class'] = 'flat '.(empty($this->cssClass) ? 'minwidth200' : $this->cssClass); }
  733. return '<input '.FormSetup::generateAttributesStringFromArray($this->fieldAttr).' />';
  734. }
  735. /**
  736. * generate input field for textarea
  737. * @return string
  738. */
  739. public function generateInputFieldTextarea()
  740. {
  741. $out = '<textarea class="flat" name="'.$this->confKey.'" id="'.$this->confKey.'" cols="50" rows="5" wrap="soft">' . "\n";
  742. $out.= dol_htmlentities($this->fieldValue);
  743. $out.= "</textarea>\n";
  744. return $out;
  745. }
  746. /**
  747. * generate input field for html
  748. * @return string
  749. */
  750. public function generateInputFieldHtml()
  751. {
  752. global $conf;
  753. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  754. $doleditor = new DolEditor($this->confKey, $this->fieldValue, '', 160, 'dolibarr_notes', '', false, false, $conf->fckeditor->enabled, ROWS_5, '90%');
  755. return $doleditor->Create(1);
  756. }
  757. /**
  758. * generate input field for categories
  759. * @return string
  760. */
  761. public function generateInputFieldCategories()
  762. {
  763. global $conf;
  764. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  765. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  766. $formother = new FormOther($this->db);
  767. $tmp = explode(':', $this->type);
  768. $out= img_picto('', 'category', 'class="pictofixedwidth"');
  769. $out.= $formother->select_categories($tmp[1], $this->fieldValue, $this->confKey, 0, $this->langs->trans('CustomersProspectsCategoriesShort'));
  770. return $out;
  771. }
  772. /**
  773. * generate input field for email template selector
  774. * @return string
  775. */
  776. public function generateInputFieldEmailTemplate()
  777. {
  778. global $conf, $user;
  779. $out = '';
  780. if (preg_match('/emailtemplate:/', $this->type)) {
  781. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  782. $formmail = new FormMail($this->db);
  783. $tmp = explode(':', $this->type);
  784. $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, 1); // We set lang=null to get in priority record with no lang
  785. $arrayOfMessageName = array();
  786. if (is_array($formmail->lines_model)) {
  787. foreach ($formmail->lines_model as $modelMail) {
  788. $moreonlabel = '';
  789. if (!empty($arrayOfMessageName[$modelMail->label])) {
  790. $moreonlabel = ' <span class="opacitymedium">(' . $this->langs->trans("SeveralLangugeVariatFound") . ')</span>';
  791. }
  792. // The 'label' is the key that is unique if we exclude the language
  793. $arrayOfMessageName[$modelMail->id] = $this->langs->trans(preg_replace('/\(|\)/', '', $modelMail->label)) . $moreonlabel;
  794. }
  795. }
  796. $out .= $this->form->selectarray($this->confKey, $arrayOfMessageName, $this->fieldValue, 'None', 0, 0, '', 0, 0, 0, '', '', 1);
  797. }
  798. return $out;
  799. }
  800. /**
  801. * generate input field for secure key
  802. * @return string
  803. */
  804. public function generateInputFieldSecureKey()
  805. {
  806. global $conf;
  807. $out = '<input required="required" type="text" class="flat" id="'.$this->confKey.'" name="'.$this->confKey.'" value="'.(GETPOST($this->confKey, 'alpha') ?GETPOST($this->confKey, 'alpha') : $this->fieldValue).'" size="40">';
  808. if (!empty($conf->use_javascript_ajax)) {
  809. $out.= '&nbsp;'.img_picto($this->langs->trans('Generate'), 'refresh', 'id="generate_token'.$this->confKey.'" class="linkobject"');
  810. }
  811. // Add button to autosuggest a key
  812. include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  813. $out .= dolJSToSetRandomPassword($this->confKey, 'generate_token'.$this->confKey);
  814. return $out;
  815. }
  816. /**
  817. * @return string
  818. */
  819. public function generateInputFieldMultiSelect()
  820. {
  821. $TSelected = array();
  822. if ($this->fieldValue) {
  823. $TSelected = explode(',', $this->fieldValue);
  824. }
  825. return $this->form->multiselectarray($this->confKey, $this->fieldOptions, $TSelected, 0, 0, '', 0, 0, 'style="min-width:100px"');
  826. }
  827. /**
  828. * @return string
  829. */
  830. public function generateInputFieldSelect()
  831. {
  832. return $this->form->selectarray($this->confKey, $this->fieldOptions, $this->fieldValue);
  833. }
  834. /**
  835. * get the type : used for old module builder setup conf style conversion and tests
  836. * because this two class will quickly evolve it's important to not set or get directly $this->type (will be protected) so this method exist
  837. * to be sure we can manage evolution easily
  838. *
  839. * @return string
  840. */
  841. public function getType()
  842. {
  843. return $this->type;
  844. }
  845. /**
  846. * set the type from string : used for old module builder setup conf style conversion and tests
  847. * because this two class will quickly evolve it's important to not set directly $this->type (will be protected) so this method exist
  848. * to be sure we can manage evolution easily
  849. * @param string $type possible values based on old module builder setup : 'string', 'textarea', 'category:'.Categorie::TYPE_CUSTOMER', 'emailtemplate', 'thirdparty_type'
  850. * @deprecated yes this setTypeFromTypeString came deprecated because it exists only for manage setup convertion
  851. * @return bool
  852. */
  853. public function setTypeFromTypeString($type)
  854. {
  855. $this->type = $type;
  856. return true;
  857. }
  858. /**
  859. * Add error
  860. * @param array|string $errors the error text
  861. * @return null
  862. */
  863. public function setErrors($errors)
  864. {
  865. if (is_array($errors)) {
  866. if (!empty($errors)) {
  867. foreach ($errors as $error) {
  868. $this->setErrors($error);
  869. }
  870. }
  871. } elseif (!empty($errors)) {
  872. $this->errors[] = $errors;
  873. }
  874. }
  875. /**
  876. * @return bool|string Generate the output html for this item
  877. */
  878. public function generateOutputField()
  879. {
  880. global $conf, $user, $langs;
  881. if (!empty($this->fieldOverride)) {
  882. return $this->fieldOverride;
  883. }
  884. if (!empty($this->fieldOutputOverride)) {
  885. return $this->fieldOutputOverride;
  886. }
  887. $out = '';
  888. if ($this->type == 'title') {
  889. // nothing to do
  890. } elseif ($this->type == 'textarea') {
  891. $out.= dol_nl2br($this->fieldValue);
  892. } elseif ($this->type == 'multiselect') {
  893. $out.= $this->generateOutputFieldMultiSelect();
  894. } elseif ($this->type == 'select') {
  895. $out.= $this->generateOutputFieldSelect();
  896. } elseif ($this->type== 'html') {
  897. $out.= $this->fieldValue;
  898. } elseif ($this->type== 'color') {
  899. $out.= $this->generateOutputFieldColor();
  900. } elseif ($this->type == 'yesno') {
  901. if (!empty($conf->use_javascript_ajax)) {
  902. $out.= ajax_constantonoff($this->confKey);
  903. } else {
  904. if ($this->fieldValue == 1) {
  905. $out.= $langs->trans('yes');
  906. } else {
  907. $out.= $langs->trans('no');
  908. }
  909. }
  910. } elseif (preg_match('/emailtemplate:/', $this->type)) {
  911. if ($this->fieldValue > 0) {
  912. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  913. $formmail = new FormMail($this->db);
  914. $tmp = explode(':', $this->type);
  915. $template = $formmail->getEMailTemplate($this->db, $tmp[1], $user, $this->langs, $this->fieldValue);
  916. if (is_numeric($template) && $template < 0) {
  917. $this->setErrors($formmail->errors);
  918. }
  919. $out.= $this->langs->trans($template->label);
  920. }
  921. } elseif (preg_match('/category:/', $this->type)) {
  922. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  923. $c = new Categorie($this->db);
  924. $result = $c->fetch($this->fieldValue);
  925. if ($result < 0) {
  926. $this->setErrors($c->errors);
  927. }
  928. $ways = $c->print_all_ways(' &gt;&gt; ', 'none', 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  929. $toprint = array();
  930. foreach ($ways as $way) {
  931. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>';
  932. }
  933. $out.='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  934. } elseif (preg_match('/thirdparty_type/', $this->type)) {
  935. if ($this->fieldValue==2) {
  936. $out.= $this->langs->trans("Prospect");
  937. } elseif ($this->fieldValue==3) {
  938. $out.= $this->langs->trans("ProspectCustomer");
  939. } elseif ($this->fieldValue==1) {
  940. $out.= $this->langs->trans("Customer");
  941. } elseif ($this->fieldValue==0) {
  942. $out.= $this->langs->trans("NorProspectNorCustomer");
  943. }
  944. } elseif ($this->type == 'product') {
  945. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  946. $product = new Product($this->db);
  947. $resprod = $product->fetch($this->fieldValue);
  948. if ($resprod > 0) {
  949. $out.= $product->ref;
  950. } elseif ($resprod < 0) {
  951. $this->setErrors($product->errors);
  952. }
  953. } else {
  954. $out.= $this->fieldValue;
  955. }
  956. return $out;
  957. }
  958. /**
  959. * @return string
  960. */
  961. public function generateOutputFieldMultiSelect()
  962. {
  963. $outPut = '';
  964. $TSelected = array();
  965. if (!empty($this->fieldValue)) {
  966. $TSelected = explode(',', $this->fieldValue);
  967. }
  968. if (!empty($TSelected)) {
  969. foreach ($TSelected as $selected) {
  970. if (!empty($this->fieldOptions[$selected])) {
  971. $outPut.= dolGetBadge('', $this->fieldOptions[$selected], 'info').' ';
  972. }
  973. }
  974. }
  975. return $outPut;
  976. }
  977. /**
  978. * @return string
  979. */
  980. public function generateOutputFieldColor()
  981. {
  982. $this->fieldAttr['disabled']=null;
  983. return $this->generateInputField();
  984. }
  985. /**
  986. * @return string
  987. */
  988. public function generateInputFieldColor()
  989. {
  990. $this->fieldAttr['type']= 'color';
  991. return $this->generateInputFieldText();
  992. }
  993. /**
  994. * @return string
  995. */
  996. public function generateOutputFieldSelect()
  997. {
  998. $outPut = '';
  999. if (!empty($this->fieldOptions[$this->fieldValue])) {
  1000. $outPut = $this->fieldOptions[$this->fieldValue];
  1001. }
  1002. return $outPut;
  1003. }
  1004. /*
  1005. * METHODS FOR SETTING DISPLAY TYPE
  1006. */
  1007. /**
  1008. * Set type of input as string
  1009. * @return self
  1010. */
  1011. public function setAsString()
  1012. {
  1013. $this->type = 'string';
  1014. return $this;
  1015. }
  1016. /**
  1017. * Set type of input as color
  1018. * @return self
  1019. */
  1020. public function setAsColor()
  1021. {
  1022. $this->type = 'color';
  1023. return $this;
  1024. }
  1025. /**
  1026. * Set type of input as textarea
  1027. * @return self
  1028. */
  1029. public function setAsTextarea()
  1030. {
  1031. $this->type = 'textarea';
  1032. return $this;
  1033. }
  1034. /**
  1035. * Set type of input as html editor
  1036. * @return self
  1037. */
  1038. public function setAsHtml()
  1039. {
  1040. $this->type = 'html';
  1041. return $this;
  1042. }
  1043. /**
  1044. * Set type of input as emailtemplate selector
  1045. * @param string $templateType email template type
  1046. * @return self
  1047. */
  1048. public function setAsEmailTemplate($templateType)
  1049. {
  1050. $this->type = 'emailtemplate:'.$templateType;
  1051. return $this;
  1052. }
  1053. /**
  1054. * Set type of input as thirdparty_type selector
  1055. * @return self
  1056. */
  1057. public function setAsThirdpartyType()
  1058. {
  1059. $this->type = 'thirdparty_type';
  1060. return $this;
  1061. }
  1062. /**
  1063. * Set type of input as Yes
  1064. * @return self
  1065. */
  1066. public function setAsYesNo()
  1067. {
  1068. $this->type = 'yesno';
  1069. return $this;
  1070. }
  1071. /**
  1072. * Set type of input as secure key
  1073. * @return self
  1074. */
  1075. public function setAsSecureKey()
  1076. {
  1077. $this->type = 'securekey';
  1078. return $this;
  1079. }
  1080. /**
  1081. * Set type of input as product
  1082. * @return self
  1083. */
  1084. public function setAsProduct()
  1085. {
  1086. $this->type = 'product';
  1087. return $this;
  1088. }
  1089. /**
  1090. * Set type of input as a category selector
  1091. * TODO add default value
  1092. * @param int $catType Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  1093. * @return self
  1094. */
  1095. public function setAsCategory($catType)
  1096. {
  1097. $this->type = 'category:'.$catType;
  1098. return $this;
  1099. }
  1100. /**
  1101. * Set type of input as a simple title
  1102. * no data to store
  1103. * @return self
  1104. */
  1105. public function setAsTitle()
  1106. {
  1107. $this->type = 'title';
  1108. return $this;
  1109. }
  1110. /**
  1111. * Set type of input as a simple title
  1112. * no data to store
  1113. * @param array $fieldOptions A table of field options
  1114. * @return self
  1115. */
  1116. public function setAsMultiSelect($fieldOptions)
  1117. {
  1118. if (is_array($fieldOptions)) {
  1119. $this->fieldOptions = $fieldOptions;
  1120. }
  1121. $this->type = 'multiselect';
  1122. return $this;
  1123. }
  1124. /**
  1125. * Set type of input as a simple title
  1126. * no data to store
  1127. * @param array $fieldOptions A table of field options
  1128. * @return self
  1129. */
  1130. public function setAsSelect($fieldOptions)
  1131. {
  1132. if (is_array($fieldOptions)) {
  1133. $this->fieldOptions = $fieldOptions;
  1134. }
  1135. $this->type = 'select';
  1136. return $this;
  1137. }
  1138. }