html.formsetup.class.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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 boolean
  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. return true;
  294. }
  295. /**
  296. * From old
  297. * Method was used to test module builder convertion to this form usage.
  298. *
  299. * @param string $confKey the conf name to store
  300. * @param array $params an array of params from old modulBuilder params
  301. * @return bool
  302. */
  303. public function addItemFromParams($confKey, $params)
  304. {
  305. if (empty($confKey) || empty($params['type'])) { return false; }
  306. /*
  307. * Exemple from old module builder setup page
  308. * // 'MYMODULE_MYPARAM1'=>array('type'=>'string', 'css'=>'minwidth500' ,'enabled'=>1),
  309. // 'MYMODULE_MYPARAM2'=>array('type'=>'textarea','enabled'=>1),
  310. //'MYMODULE_MYPARAM3'=>array('type'=>'category:'.Categorie::TYPE_CUSTOMER, 'enabled'=>1),
  311. //'MYMODULE_MYPARAM4'=>array('type'=>'emailtemplate:thirdparty', 'enabled'=>1),
  312. //'MYMODULE_MYPARAM5'=>array('type'=>'yesno', 'enabled'=>1),
  313. //'MYMODULE_MYPARAM5'=>array('type'=>'thirdparty_type', 'enabled'=>1),
  314. //'MYMODULE_MYPARAM6'=>array('type'=>'securekey', 'enabled'=>1),
  315. //'MYMODULE_MYPARAM7'=>array('type'=>'product', 'enabled'=>1),
  316. */
  317. $item = new FormSetupItem($confKey);
  318. // need to be ignored from scrutinizer setTypeFromTypeString was created as deprecated to incite developper to use object oriented usage
  319. /** @scrutinizer ignore-deprecated */ $item->setTypeFromTypeString($params['type']);
  320. if (!empty($params['enabled'])) {
  321. $item->enabled = $params['enabled'];
  322. }
  323. if (!empty($params['css'])) {
  324. $item->cssClass = $params['css'];
  325. }
  326. $this->items[$item->confKey] = $item;
  327. return true;
  328. }
  329. /**
  330. * Used to export param array for /core/actions_setmoduleoptions.inc.php template
  331. * Method exists only for manage setup convertion
  332. *
  333. * @return array $arrayofparameters for /core/actions_setmoduleoptions.inc.php
  334. */
  335. public function exportItemsAsParamsArray()
  336. {
  337. $arrayofparameters = array();
  338. foreach ($this->items as $item) {
  339. $arrayofparameters[$item->confKey] = array(
  340. 'type' => $item->getType(),
  341. 'enabled' => $item->enabled
  342. );
  343. }
  344. return $arrayofparameters;
  345. }
  346. /**
  347. * Reload for each item default conf
  348. * note: this will override custom configuration
  349. *
  350. * @return bool
  351. */
  352. public function reloadConfs()
  353. {
  354. if (!array($this->items)) { return false; }
  355. foreach ($this->items as $item) {
  356. $item->loadValueFromConf();
  357. }
  358. return true;
  359. }
  360. /**
  361. * Create a new item
  362. * the tagret is useful with hooks : that allow externals modules to add setup items on good place
  363. *
  364. * @param string $confKey the conf key used in database
  365. * @param string $targetItemKey target item used to place the new item beside
  366. * @param bool $insertAfterTarget insert before or after target item ?
  367. * @return FormSetupItem the new setup item created
  368. */
  369. public function newItem($confKey, $targetItemKey = false, $insertAfterTarget = false)
  370. {
  371. $item = new FormSetupItem($confKey);
  372. // set item rank if not defined as last item
  373. if (empty($item->rank)) {
  374. $item->rank = $this->getCurentItemMaxRank() + 1;
  375. $this->setItemMaxRank($item->rank); // set new max rank if needed
  376. }
  377. // try to get rank from target column, this will override item->rank
  378. if (!empty($targetItemKey)) {
  379. if (isset($this->items[$targetItemKey])) {
  380. $targetItem = $this->items[$targetItemKey];
  381. $item->rank = $targetItem->rank; // $targetItem->rank will be increase after
  382. if ($targetItem->rank >= 0 && $insertAfterTarget) {
  383. $item->rank++;
  384. }
  385. }
  386. // calc new rank for each item to make place for new item
  387. foreach ($this->items as $fItem) {
  388. if ($item->rank <= $fItem->rank) {
  389. $fItem->rank = $fItem->rank + 1;
  390. $this->setItemMaxRank($fItem->rank); // set new max rank if needed
  391. }
  392. }
  393. }
  394. $this->items[$item->confKey] = $item;
  395. return $this->items[$item->confKey];
  396. }
  397. /**
  398. * Sort items according to rank
  399. *
  400. * @return bool
  401. */
  402. public function sortingItems()
  403. {
  404. // Sorting
  405. return uasort($this->items, array($this, 'itemSort'));
  406. }
  407. /**
  408. * getCurentItemMaxRank
  409. *
  410. * @param bool $cache To use cache or not
  411. * @return int
  412. */
  413. public function getCurentItemMaxRank($cache = true)
  414. {
  415. if (empty($this->items)) {
  416. return 0;
  417. }
  418. if ($cache && $this->maxItemRank > 0) {
  419. return $this->maxItemRank;
  420. }
  421. $this->maxItemRank = 0;
  422. foreach ($this->items as $item) {
  423. $this->maxItemRank = max($this->maxItemRank, $item->rank);
  424. }
  425. return $this->maxItemRank;
  426. }
  427. /**
  428. * set new max rank if needed
  429. *
  430. * @param int $rank the item rank
  431. * @return int|void new max rank
  432. */
  433. public function setItemMaxRank($rank)
  434. {
  435. $this->maxItemRank = max($this->maxItemRank, $rank);
  436. }
  437. /**
  438. * get item position rank from item key
  439. *
  440. * @param string $itemKey the item key
  441. * @return int rank on success and -1 on error
  442. */
  443. public function getLineRank($itemKey)
  444. {
  445. if (!isset($this->items[$itemKey]->rank)) {
  446. return -1;
  447. }
  448. return $this->items[$itemKey]->rank;
  449. }
  450. /**
  451. * uasort callback function to Sort params items
  452. *
  453. * @param FormSetupItem $a formSetup item
  454. * @param FormSetupItem $b formSetup item
  455. * @return int Return compare result
  456. */
  457. public function itemSort(FormSetupItem $a, FormSetupItem $b)
  458. {
  459. if (empty($a->rank)) {
  460. $a->rank = 0;
  461. }
  462. if (empty($b->rank)) {
  463. $b->rank = 0;
  464. }
  465. if ($a->rank == $b->rank) {
  466. return 0;
  467. }
  468. return ($a->rank < $b->rank) ? -1 : 1;
  469. }
  470. }
  471. /**
  472. * This class help to create item for class formSetup
  473. */
  474. class FormSetupItem
  475. {
  476. /**
  477. * @var DoliDB Database handler.
  478. */
  479. public $db;
  480. /** @var Translate */
  481. public $langs;
  482. /** @var int */
  483. public $entity;
  484. /** @var Form */
  485. public $form;
  486. /** @var string $confKey the conf key used in database */
  487. public $confKey;
  488. /** @var string|false $nameText */
  489. public $nameText = false;
  490. /** @var string $helpText */
  491. public $helpText = '';
  492. /** @var string $fieldValue */
  493. public $fieldValue;
  494. /** @var string $defaultFieldValue */
  495. public $defaultFieldValue = null;
  496. /** @var array $fieldAttr fields attribute only for compatible fields like input text */
  497. public $fieldAttr = array();
  498. /** @var bool|string set this var to override field output will override $fieldInputOverride and $fieldOutputOverride too */
  499. public $fieldOverride = false;
  500. /** @var bool|string set this var to override field input */
  501. public $fieldInputOverride = false;
  502. /** @var bool|string set this var to override field output */
  503. public $fieldOutputOverride = false;
  504. /** @var int $rank */
  505. public $rank = 0;
  506. /** @var array set this var for options on select and multiselect items */
  507. public $fieldOptions = array();
  508. /** @var callable $saveCallBack */
  509. public $saveCallBack;
  510. /** @var callable $setValueFromPostCallBack */
  511. public $setValueFromPostCallBack;
  512. /**
  513. * @var string $errors
  514. */
  515. public $errors = array();
  516. /**
  517. * TODO each type must have setAs{type} method to help configuration
  518. * And set var as protected when its done configuration must be done by method
  519. * this is important for retrocompatibility of futures versions
  520. * @var string $type 'string', 'textarea', 'category:'.Categorie::TYPE_CUSTOMER', 'emailtemplate', 'thirdparty_type'
  521. */
  522. protected $type = 'string';
  523. public $enabled = 1;
  524. public $cssClass = '';
  525. /**
  526. * Constructor
  527. *
  528. * @param string $confKey the conf key used in database
  529. */
  530. public function __construct($confKey)
  531. {
  532. global $langs, $db, $conf, $form;
  533. $this->db = $db;
  534. if (!empty($form) && is_object($form) && get_class($form) == 'Form') { // the form class has a cache inside so I am using it to optimize
  535. $this->form = $form;
  536. } else {
  537. $this->form = new Form($this->db);
  538. }
  539. $this->langs = $langs;
  540. $this->entity = $conf->entity;
  541. $this->confKey = $confKey;
  542. $this->loadValueFromConf();
  543. }
  544. /**
  545. * load conf value from databases
  546. * @return bool
  547. */
  548. public function loadValueFromConf()
  549. {
  550. global $conf;
  551. if (isset($conf->global->{$this->confKey})) {
  552. $this->fieldValue = getDolGlobalString($this->confKey);
  553. return true;
  554. } else {
  555. $this->fieldValue = null;
  556. return false;
  557. }
  558. }
  559. /**
  560. * reload conf value from databases is an aliase of loadValueFromConf
  561. * @deprecated
  562. * @return bool
  563. */
  564. public function reloadValueFromConf()
  565. {
  566. return $this->loadValueFromConf();
  567. }
  568. /**
  569. * Save const value based on htdocs/core/actions_setmoduleoptions.inc.php
  570. *
  571. * @return int -1 if KO, 1 if OK
  572. */
  573. public function saveConfValue()
  574. {
  575. global $hookmanager;
  576. $parameters = array();
  577. $reshook = $hookmanager->executeHooks('formSetupBeforeSaveConfValue', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  578. if ($reshook < 0) {
  579. $this->setErrors($hookmanager->errors);
  580. return -1;
  581. }
  582. if ($reshook > 0) {
  583. return $reshook;
  584. }
  585. if (!empty($this->saveCallBack) && is_callable($this->saveCallBack)) {
  586. return call_user_func($this->saveCallBack, $this);
  587. }
  588. // Modify constant only if key was posted (avoid resetting key to the null value)
  589. if ($this->type != 'title') {
  590. $result = dolibarr_set_const($this->db, $this->confKey, $this->fieldValue, 'chaine', 0, '', $this->entity);
  591. if ($result < 0) {
  592. return -1;
  593. } else {
  594. return 1;
  595. }
  596. }
  597. return 0;
  598. }
  599. /**
  600. * Set an override function for saving data
  601. *
  602. * @param callable $callBack a callable function
  603. * @return void
  604. */
  605. public function setSaveCallBack(callable $callBack)
  606. {
  607. $this->saveCallBack = $callBack;
  608. }
  609. /**
  610. * Set an override function for get data from post
  611. * @param callable $callBack a callable function
  612. * @return void
  613. */
  614. public function setValueFromPostCallBack(callable $callBack)
  615. {
  616. $this->setValueFromPostCallBack = $callBack;
  617. }
  618. /**
  619. * Save const value based on htdocs/core/actions_setmoduleoptions.inc.php
  620. * @return int -1 if KO, 0 nothing to do , 1 if OK
  621. */
  622. public function setValueFromPost()
  623. {
  624. if (!empty($this->setValueFromPostCallBack) && is_callable($this->setValueFromPostCallBack)) {
  625. return call_user_func($this->setValueFromPostCallBack);
  626. }
  627. // Modify constant only if key was posted (avoid resetting key to the null value)
  628. if ($this->type != 'title') {
  629. if (preg_match('/category:/', $this->type)) {
  630. if (GETPOST($this->confKey, 'int') == '-1') {
  631. $val_const = '';
  632. } else {
  633. $val_const = GETPOST($this->confKey, 'int');
  634. }
  635. } elseif ($this->type == 'multiselect') {
  636. $val = GETPOST($this->confKey, 'array');
  637. if ($val && is_array($val)) {
  638. $val_const = implode(',', $val);
  639. } else {
  640. $val_const = '';
  641. }
  642. } elseif ($this->type == 'html') {
  643. $val_const = GETPOST($this->confKey, 'restricthtml');
  644. } else {
  645. $val_const = GETPOST($this->confKey, 'alpha');
  646. }
  647. // TODO add value check with class validate
  648. $this->fieldValue = $val_const;
  649. return 1;
  650. }
  651. return 0;
  652. }
  653. /**
  654. * Get help text or generate it
  655. * @return int|string
  656. */
  657. public function getHelpText()
  658. {
  659. if (!empty($this->helpText)) { return $this->helpText; }
  660. return (($this->langs->trans($this->confKey . 'Tooltip') != $this->confKey . 'Tooltip') ? $this->langs->trans($this->confKey . 'Tooltip') : '');
  661. }
  662. /**
  663. * Get field name text or generate it
  664. * @return false|int|string
  665. */
  666. public function getNameText()
  667. {
  668. if (!empty($this->nameText)) { return $this->nameText; }
  669. return (($this->langs->trans($this->confKey) != $this->confKey) ? $this->langs->trans($this->confKey) : $this->langs->trans('MissingTranslationForConfKey', $this->confKey));
  670. }
  671. /**
  672. * generate input field
  673. * @return bool|string
  674. */
  675. public function generateInputField()
  676. {
  677. global $conf;
  678. if (!empty($this->fieldOverride)) {
  679. return $this->fieldOverride;
  680. }
  681. if (!empty($this->fieldInputOverride)) {
  682. return $this->fieldInputOverride;
  683. }
  684. // Set default value
  685. if (is_null($this->fieldValue)) {
  686. $this->fieldValue = $this->defaultFieldValue;
  687. }
  688. $this->fieldAttr['name'] = $this->confKey;
  689. $this->fieldAttr['id'] = 'setup-'.$this->confKey;
  690. $this->fieldAttr['value'] = $this->fieldValue;
  691. $out = '';
  692. if ($this->type == 'title') {
  693. $out.= $this->generateOutputField(); // title have no input
  694. } elseif ($this->type == 'multiselect') {
  695. $out.= $this->generateInputFieldMultiSelect();
  696. } elseif ($this->type == 'select') {
  697. $out.= $this->generateInputFieldSelect();
  698. } elseif ($this->type == 'selectUser') {
  699. $out.= $this->generateInputFieldSelectUser();
  700. } elseif ($this->type == 'textarea') {
  701. $out.= $this->generateInputFieldTextarea();
  702. } elseif ($this->type== 'html') {
  703. $out.= $this->generateInputFieldHtml();
  704. } elseif ($this->type== 'color') {
  705. $out.= $this->generateInputFieldColor();
  706. } elseif ($this->type == 'yesno') {
  707. if (!empty($conf->use_javascript_ajax)) {
  708. $out.= ajax_constantonoff($this->confKey);
  709. } else {
  710. $out.= $this->form->selectyesno($this->confKey, $this->fieldValue, 1);
  711. }
  712. } elseif (preg_match('/emailtemplate:/', $this->type)) {
  713. $out.= $this->generateInputFieldEmailTemplate();
  714. } elseif (preg_match('/category:/', $this->type)) {
  715. $out.=$this->generateInputFieldCategories();
  716. } elseif (preg_match('/thirdparty_type/', $this->type)) {
  717. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
  718. $formcompany = new FormCompany($this->db);
  719. $out.= $formcompany->selectProspectCustomerType($this->fieldValue, $this->confKey);
  720. } elseif ($this->type == 'securekey') {
  721. $out.= $this->generateInputFieldSecureKey();
  722. } elseif ($this->type == 'product') {
  723. if (isModEnabled("product") || isModEnabled("service")) {
  724. $selected = (empty($this->fieldValue) ? '' : $this->fieldValue);
  725. $out.= $this->form->select_produits($selected, $this->confKey, '', 0, 0, 1, 2, '', 0, array(), 0, '1', 0, $this->cssClass, 0, '', null, 1);
  726. }
  727. } else {
  728. $out.= $this->generateInputFieldText();
  729. }
  730. return $out;
  731. }
  732. /**
  733. * generatec default input field
  734. * @return string
  735. */
  736. public function generateInputFieldText()
  737. {
  738. if (empty($this->fieldAttr)) { $this->fieldAttr['class'] = 'flat '.(empty($this->cssClass) ? 'minwidth200' : $this->cssClass); }
  739. return '<input '.FormSetup::generateAttributesStringFromArray($this->fieldAttr).' />';
  740. }
  741. /**
  742. * generate input field for textarea
  743. * @return string
  744. */
  745. public function generateInputFieldTextarea()
  746. {
  747. $out = '<textarea class="flat" name="'.$this->confKey.'" id="'.$this->confKey.'" cols="50" rows="5" wrap="soft">' . "\n";
  748. $out.= dol_htmlentities($this->fieldValue);
  749. $out.= "</textarea>\n";
  750. return $out;
  751. }
  752. /**
  753. * generate input field for html
  754. * @return string
  755. */
  756. public function generateInputFieldHtml()
  757. {
  758. global $conf;
  759. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  760. $doleditor = new DolEditor($this->confKey, $this->fieldValue, '', 160, 'dolibarr_notes', '', false, false, isModEnabled('fckeditor'), ROWS_5, '90%');
  761. return $doleditor->Create(1);
  762. }
  763. /**
  764. * generate input field for categories
  765. * @return string
  766. */
  767. public function generateInputFieldCategories()
  768. {
  769. global $conf;
  770. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  771. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  772. $formother = new FormOther($this->db);
  773. $tmp = explode(':', $this->type);
  774. $out= img_picto('', 'category', 'class="pictofixedwidth"');
  775. $out.= $formother->select_categories($tmp[1], $this->fieldValue, $this->confKey, 0, $this->langs->trans('CustomersProspectsCategoriesShort'));
  776. return $out;
  777. }
  778. /**
  779. * generate input field for email template selector
  780. * @return string
  781. */
  782. public function generateInputFieldEmailTemplate()
  783. {
  784. global $conf, $user;
  785. $out = '';
  786. if (preg_match('/emailtemplate:/', $this->type)) {
  787. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  788. $formmail = new FormMail($this->db);
  789. $tmp = explode(':', $this->type);
  790. $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, 1); // We set lang=null to get in priority record with no lang
  791. $arrayOfMessageName = array();
  792. if (is_array($formmail->lines_model)) {
  793. foreach ($formmail->lines_model as $modelMail) {
  794. $moreonlabel = '';
  795. if (!empty($arrayOfMessageName[$modelMail->label])) {
  796. $moreonlabel = ' <span class="opacitymedium">(' . $this->langs->trans("SeveralLangugeVariatFound") . ')</span>';
  797. }
  798. // The 'label' is the key that is unique if we exclude the language
  799. $arrayOfMessageName[$modelMail->id] = $this->langs->trans(preg_replace('/\(|\)/', '', $modelMail->label)) . $moreonlabel;
  800. }
  801. }
  802. $out .= $this->form->selectarray($this->confKey, $arrayOfMessageName, $this->fieldValue, 'None', 0, 0, '', 0, 0, 0, '', '', 1);
  803. }
  804. return $out;
  805. }
  806. /**
  807. * generate input field for secure key
  808. * @return string
  809. */
  810. public function generateInputFieldSecureKey()
  811. {
  812. global $conf;
  813. $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">';
  814. if (!empty($conf->use_javascript_ajax)) {
  815. $out.= '&nbsp;'.img_picto($this->langs->trans('Generate'), 'refresh', 'id="generate_token'.$this->confKey.'" class="linkobject"');
  816. }
  817. // Add button to autosuggest a key
  818. include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  819. $out .= dolJSToSetRandomPassword($this->confKey, 'generate_token'.$this->confKey);
  820. return $out;
  821. }
  822. /**
  823. * @return string
  824. */
  825. public function generateInputFieldMultiSelect()
  826. {
  827. $TSelected = array();
  828. if ($this->fieldValue) {
  829. $TSelected = explode(',', $this->fieldValue);
  830. }
  831. return $this->form->multiselectarray($this->confKey, $this->fieldOptions, $TSelected, 0, 0, '', 0, 0, 'style="min-width:100px"');
  832. }
  833. /**
  834. * @return string
  835. */
  836. public function generateInputFieldSelect()
  837. {
  838. return $this->form->selectarray($this->confKey, $this->fieldOptions, $this->fieldValue);
  839. }
  840. /**
  841. * @return string
  842. */
  843. public function generateInputFieldSelectUser()
  844. {
  845. return $this->form->select_dolusers($this->fieldValue, $this->confKey);
  846. }
  847. /**
  848. * get the type : used for old module builder setup conf style conversion and tests
  849. * 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
  850. * to be sure we can manage evolution easily
  851. *
  852. * @return string
  853. */
  854. public function getType()
  855. {
  856. return $this->type;
  857. }
  858. /**
  859. * set the type from string : used for old module builder setup conf style conversion and tests
  860. * because this two class will quickly evolve it's important to not set directly $this->type (will be protected) so this method exist
  861. * to be sure we can manage evolution easily
  862. *
  863. * @param string $type possible values based on old module builder setup : 'string', 'textarea', 'category:'.Categorie::TYPE_CUSTOMER', 'emailtemplate', 'thirdparty_type'
  864. * @deprecated yes this setTypeFromTypeString came deprecated because it exists only for manage setup convertion
  865. * @return bool
  866. */
  867. public function setTypeFromTypeString($type)
  868. {
  869. $this->type = $type;
  870. return true;
  871. }
  872. /**
  873. * Add error
  874. *
  875. * @param array|string $errors the error text
  876. * @return null
  877. */
  878. public function setErrors($errors)
  879. {
  880. if (is_array($errors)) {
  881. if (!empty($errors)) {
  882. foreach ($errors as $error) {
  883. $this->setErrors($error);
  884. }
  885. }
  886. } elseif (!empty($errors)) {
  887. $this->errors[] = $errors;
  888. }
  889. }
  890. /**
  891. * generateOutputField
  892. *
  893. * @return bool|string Generate the output html for this item
  894. */
  895. public function generateOutputField()
  896. {
  897. global $conf, $user, $langs;
  898. if (!empty($this->fieldOverride)) {
  899. return $this->fieldOverride;
  900. }
  901. if (!empty($this->fieldOutputOverride)) {
  902. return $this->fieldOutputOverride;
  903. }
  904. $out = '';
  905. if ($this->type == 'title') {
  906. // nothing to do
  907. } elseif ($this->type == 'textarea') {
  908. $out.= dol_nl2br($this->fieldValue);
  909. } elseif ($this->type == 'multiselect') {
  910. $out.= $this->generateOutputFieldMultiSelect();
  911. } elseif ($this->type == 'select') {
  912. $out.= $this->generateOutputFieldSelect();
  913. } elseif ($this->type == 'selectUser') {
  914. $out.= $this->generateOutputFieldSelectUser();
  915. } elseif ($this->type== 'html') {
  916. $out.= $this->fieldValue;
  917. } elseif ($this->type== 'color') {
  918. $out.= $this->generateOutputFieldColor();
  919. } elseif ($this->type == 'yesno') {
  920. if (!empty($conf->use_javascript_ajax)) {
  921. $out.= ajax_constantonoff($this->confKey);
  922. } else {
  923. if ($this->fieldValue == 1) {
  924. $out.= $langs->trans('yes');
  925. } else {
  926. $out.= $langs->trans('no');
  927. }
  928. }
  929. } elseif (preg_match('/emailtemplate:/', $this->type)) {
  930. if ($this->fieldValue > 0) {
  931. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  932. $formmail = new FormMail($this->db);
  933. $tmp = explode(':', $this->type);
  934. $template = $formmail->getEMailTemplate($this->db, $tmp[1], $user, $this->langs, $this->fieldValue);
  935. if (is_numeric($template) && $template < 0) {
  936. $this->setErrors($formmail->errors);
  937. }
  938. $out.= $this->langs->trans($template->label);
  939. }
  940. } elseif (preg_match('/category:/', $this->type)) {
  941. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  942. $c = new Categorie($this->db);
  943. $result = $c->fetch($this->fieldValue);
  944. if ($result < 0) {
  945. $this->setErrors($c->errors);
  946. }
  947. $ways = $c->print_all_ways(' &gt;&gt; ', 'none', 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  948. $toprint = array();
  949. foreach ($ways as $way) {
  950. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>';
  951. }
  952. $out.='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  953. } elseif (preg_match('/thirdparty_type/', $this->type)) {
  954. if ($this->fieldValue==2) {
  955. $out.= $this->langs->trans("Prospect");
  956. } elseif ($this->fieldValue==3) {
  957. $out.= $this->langs->trans("ProspectCustomer");
  958. } elseif ($this->fieldValue==1) {
  959. $out.= $this->langs->trans("Customer");
  960. } elseif ($this->fieldValue==0) {
  961. $out.= $this->langs->trans("NorProspectNorCustomer");
  962. }
  963. } elseif ($this->type == 'product') {
  964. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  965. $product = new Product($this->db);
  966. $resprod = $product->fetch($this->fieldValue);
  967. if ($resprod > 0) {
  968. $out.= $product->ref;
  969. } elseif ($resprod < 0) {
  970. $this->setErrors($product->errors);
  971. }
  972. } else {
  973. $out.= $this->fieldValue;
  974. }
  975. return $out;
  976. }
  977. /**
  978. * generateOutputFieldMultiSelect
  979. *
  980. * @return string
  981. */
  982. public function generateOutputFieldMultiSelect()
  983. {
  984. $outPut = '';
  985. $TSelected = array();
  986. if (!empty($this->fieldValue)) {
  987. $TSelected = explode(',', $this->fieldValue);
  988. }
  989. if (!empty($TSelected)) {
  990. foreach ($TSelected as $selected) {
  991. if (!empty($this->fieldOptions[$selected])) {
  992. $outPut.= dolGetBadge('', $this->fieldOptions[$selected], 'info').' ';
  993. }
  994. }
  995. }
  996. return $outPut;
  997. }
  998. /**
  999. * generateOutputFieldColor
  1000. *
  1001. * @return string
  1002. */
  1003. public function generateOutputFieldColor()
  1004. {
  1005. $this->fieldAttr['disabled']=null;
  1006. return $this->generateInputField();
  1007. }
  1008. /**
  1009. * generateInputFieldColor
  1010. *
  1011. * @return string
  1012. */
  1013. public function generateInputFieldColor()
  1014. {
  1015. $this->fieldAttr['type']= 'color';
  1016. return $this->generateInputFieldText();
  1017. }
  1018. /**
  1019. * generateOutputFieldSelect
  1020. *
  1021. * @return string
  1022. */
  1023. public function generateOutputFieldSelect()
  1024. {
  1025. $outPut = '';
  1026. if (!empty($this->fieldOptions[$this->fieldValue])) {
  1027. $outPut = $this->fieldOptions[$this->fieldValue];
  1028. }
  1029. return $outPut;
  1030. }
  1031. /**
  1032. * generateOutputFieldSelectUser
  1033. *
  1034. * @return string
  1035. */
  1036. public function generateOutputFieldSelectUser()
  1037. {
  1038. $outPut = '';
  1039. $user = new User($this->db);
  1040. $user->fetch($this->fieldValue);
  1041. $outPut = $user->firstname . " " . $user->lastname;
  1042. return $outPut;
  1043. }
  1044. /*
  1045. * METHODS FOR SETTING DISPLAY TYPE
  1046. */
  1047. /**
  1048. * Set type of input as string
  1049. *
  1050. * @return self
  1051. */
  1052. public function setAsString()
  1053. {
  1054. $this->type = 'string';
  1055. return $this;
  1056. }
  1057. /**
  1058. * Set type of input as color
  1059. *
  1060. * @return self
  1061. */
  1062. public function setAsColor()
  1063. {
  1064. $this->type = 'color';
  1065. return $this;
  1066. }
  1067. /**
  1068. * Set type of input as textarea
  1069. *
  1070. * @return self
  1071. */
  1072. public function setAsTextarea()
  1073. {
  1074. $this->type = 'textarea';
  1075. return $this;
  1076. }
  1077. /**
  1078. * Set type of input as html editor
  1079. *
  1080. * @return self
  1081. */
  1082. public function setAsHtml()
  1083. {
  1084. $this->type = 'html';
  1085. return $this;
  1086. }
  1087. /**
  1088. * Set type of input as emailtemplate selector
  1089. *
  1090. * @param string $templateType email template type
  1091. * @return self
  1092. */
  1093. public function setAsEmailTemplate($templateType)
  1094. {
  1095. $this->type = 'emailtemplate:'.$templateType;
  1096. return $this;
  1097. }
  1098. /**
  1099. * Set type of input as thirdparty_type selector
  1100. *
  1101. * @return self
  1102. */
  1103. public function setAsThirdpartyType()
  1104. {
  1105. $this->type = 'thirdparty_type';
  1106. return $this;
  1107. }
  1108. /**
  1109. * Set type of input as Yes
  1110. *
  1111. * @return self
  1112. */
  1113. public function setAsYesNo()
  1114. {
  1115. $this->type = 'yesno';
  1116. return $this;
  1117. }
  1118. /**
  1119. * Set type of input as secure key
  1120. *
  1121. * @return self
  1122. */
  1123. public function setAsSecureKey()
  1124. {
  1125. $this->type = 'securekey';
  1126. return $this;
  1127. }
  1128. /**
  1129. * Set type of input as product
  1130. *
  1131. * @return self
  1132. */
  1133. public function setAsProduct()
  1134. {
  1135. $this->type = 'product';
  1136. return $this;
  1137. }
  1138. /**
  1139. * Set type of input as a category selector
  1140. * TODO add default value
  1141. *
  1142. * @param int $catType Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  1143. * @return self
  1144. */
  1145. public function setAsCategory($catType)
  1146. {
  1147. $this->type = 'category:'.$catType;
  1148. return $this;
  1149. }
  1150. /**
  1151. * Set type of input as a simple title. No data to store
  1152. *
  1153. * @return self
  1154. */
  1155. public function setAsTitle()
  1156. {
  1157. $this->type = 'title';
  1158. return $this;
  1159. }
  1160. /**
  1161. * Set type of input as a simple title. No data to store
  1162. *
  1163. * @param array $fieldOptions A table of field options
  1164. * @return self
  1165. */
  1166. public function setAsMultiSelect($fieldOptions)
  1167. {
  1168. if (is_array($fieldOptions)) {
  1169. $this->fieldOptions = $fieldOptions;
  1170. }
  1171. $this->type = 'multiselect';
  1172. return $this;
  1173. }
  1174. /**
  1175. * Set type of input as a simple title. No data to store
  1176. *
  1177. * @param array $fieldOptions A table of field options
  1178. * @return self
  1179. */
  1180. public function setAsSelect($fieldOptions)
  1181. {
  1182. if (is_array($fieldOptions)) {
  1183. $this->fieldOptions = $fieldOptions;
  1184. }
  1185. $this->type = 'select';
  1186. return $this;
  1187. }
  1188. /**
  1189. * Set type of input as a simple title. No data to store
  1190. *
  1191. * @return self
  1192. */
  1193. public function setAsSelectUser()
  1194. {
  1195. $this->type = 'selectUser';
  1196. return $this;
  1197. }
  1198. }