FormValidator.class.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class FormValidator
  5. * create/manipulate/validate user input.
  6. */
  7. class FormValidator extends HTML_QuickForm
  8. {
  9. const LAYOUT_HORIZONTAL = 'horizontal';
  10. const LAYOUT_INLINE = 'inline';
  11. const LAYOUT_BOX = 'box';
  12. const LAYOUT_BOX_NO_LABEL = 'box-no-label';
  13. public $with_progress_bar = false;
  14. private $layout;
  15. /**
  16. * Constructor
  17. * @param string $name Name of the form
  18. * @param string $method (optional) Method ('post' (default) or 'get')
  19. * @param string $action (optional) Action (default is $PHP_SELF)
  20. * @param string $target (optional) Form's target defaults to '_self'
  21. * @param mixed $attributes (optional) Extra attributes for <form> tag
  22. * @param string $layout
  23. * @param bool $trackSubmit (optional) Whether to track if the form was
  24. * submitted by adding a special hidden field (default = true)
  25. */
  26. public function __construct(
  27. $name,
  28. $method = 'post',
  29. $action = '',
  30. $target = '',
  31. $attributes = array(),
  32. $layout = self::LAYOUT_HORIZONTAL,
  33. $trackSubmit = true
  34. ) {
  35. // Default form class.
  36. if (is_array($attributes) && !isset($attributes['class']) || empty($attributes)) {
  37. $attributes['class'] = 'form-horizontal';
  38. }
  39. if (isset($attributes['class']) && strpos($attributes['class'], 'form-search') !== false) {
  40. $layout = 'inline';
  41. }
  42. $this->setLayout($layout);
  43. switch ($layout) {
  44. case self::LAYOUT_HORIZONTAL:
  45. $attributes['class'] = 'form-horizontal';
  46. break;
  47. case self::LAYOUT_INLINE:
  48. case self::LAYOUT_BOX:
  49. $attributes['class'] = 'form-inline';
  50. break;
  51. }
  52. parent::__construct($name, $method, $action, $target, $attributes, $trackSubmit);
  53. // Modify the default templates
  54. $renderer = & $this->defaultRenderer();
  55. // Form template
  56. $formTemplate = $this->getFormTemplate();
  57. $renderer->setFormTemplate($formTemplate);
  58. // Element template
  59. if (isset($attributes['class']) && $attributes['class'] == 'form-inline') {
  60. $elementTemplate = ' {label} {element} ';
  61. $renderer->setElementTemplate($elementTemplate);
  62. } elseif (isset($attributes['class']) && $attributes['class'] == 'form-search') {
  63. $elementTemplate = ' {label} {element} ';
  64. $renderer->setElementTemplate($elementTemplate);
  65. } else {
  66. $renderer->setElementTemplate($this->getDefaultElementTemplate());
  67. // Display a gray div in the buttons
  68. $templateSimple = '<div class="form-actions">{label} {element}</div>';
  69. $renderer->setElementTemplate($templateSimple, 'submit_in_actions');
  70. //Display a gray div in the buttons + makes the button available when scrolling
  71. $templateBottom = '<div class="form-actions bottom_actions bg-form">{label} {element}</div>';
  72. $renderer->setElementTemplate($templateBottom, 'submit_fixed_in_bottom');
  73. //When you want to group buttons use something like this
  74. /* $group = array();
  75. $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
  76. $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));
  77. $form->addGroup($group, 'buttons_in_action');
  78. */
  79. $renderer->setElementTemplate($templateSimple, 'buttons_in_action');
  80. $templateSimpleRight = '<div class="form-actions"> <div class="pull-right">{label} {element}</div></div>';
  81. $renderer->setElementTemplate($templateSimpleRight, 'buttons_in_action_right');
  82. }
  83. //Set Header template
  84. $renderer->setHeaderTemplate('<legend>{header}</legend>');
  85. //Set required field template
  86. $this->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
  87. $noteTemplate = <<<EOT
  88. <div class="form-group">
  89. <div class="col-sm-offset-2 col-sm-10">{requiredNote}</div>
  90. </div>
  91. EOT;
  92. $renderer->setRequiredNoteTemplate($noteTemplate);
  93. }
  94. /**
  95. * @return string
  96. */
  97. public function getFormTemplate()
  98. {
  99. return '<form{attributes}>
  100. <fieldset>
  101. {content}
  102. </fieldset>
  103. {hidden}
  104. </form>';
  105. }
  106. /**
  107. * @todo this function should be added in the element class
  108. * @return string
  109. */
  110. public function getDefaultElementTemplate()
  111. {
  112. return '
  113. <div class="form-group {error_class}">
  114. <label {label-for} class="col-sm-2 control-label {extra_label_class}" >
  115. <!-- BEGIN required --><span class="form_required">*</span><!-- END required -->
  116. {label}
  117. </label>
  118. <div class="col-sm-8">
  119. {icon}
  120. {element}
  121. <!-- BEGIN label_2 -->
  122. <p class="help-block">{label_2}</p>
  123. <!-- END label_2 -->
  124. <!-- BEGIN error -->
  125. <span class="help-inline">{error}</span>
  126. <!-- END error -->
  127. </div>
  128. <div class="col-sm-2">
  129. <!-- BEGIN label_3 -->
  130. {label_3}
  131. <!-- END label_3 -->
  132. </div>
  133. </div>';
  134. }
  135. /**
  136. * @return string
  137. */
  138. public function getLayout()
  139. {
  140. return $this->layout;
  141. }
  142. /**
  143. * @param string $layout
  144. */
  145. public function setLayout($layout)
  146. {
  147. $this->layout = $layout;
  148. }
  149. /**
  150. * Adds a text field to the form.
  151. * A trim-filter is attached to the field.
  152. * @param string $label The label for the form-element
  153. * @param string $name The element name
  154. * @param bool $required (optional) Is the form-element required (default=true)
  155. * @param array $attributes (optional) List of attributes for the form-element
  156. * @return HTML_QuickForm_text
  157. */
  158. public function addText($name, $label, $required = true, $attributes = array())
  159. {
  160. $element = $this->addElement('text', $name, $label, $attributes);
  161. $this->applyFilter($name, 'trim');
  162. if ($required) {
  163. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  164. }
  165. return $element;
  166. }
  167. /**
  168. * The "date_range_picker" element creates 2 hidden fields
  169. * "elementName" + "_start" and "elementName" + "_end"
  170. * For example if the name is "range", you will have 2 new fields
  171. * when executing $form->getSubmitValues()
  172. * "range_start" and "range_end"
  173. *
  174. * @param string $name
  175. * @param string $label
  176. * @param bool $required
  177. * @param array $attributes
  178. */
  179. public function addDateRangePicker($name, $label, $required = true, $attributes = array())
  180. {
  181. $this->addElement('date_range_picker', $name, $label, $attributes);
  182. $this->addElement('hidden', $name.'_start');
  183. $this->addElement('hidden', $name.'_end');
  184. if ($required) {
  185. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  186. }
  187. }
  188. /**
  189. * @param string $name
  190. * @param string $label
  191. * @param array $attributes
  192. *
  193. * @return mixed
  194. */
  195. public function addDatePicker($name, $label, $attributes = [])
  196. {
  197. return $this->addElement('DatePicker', $name, $label, $attributes);
  198. }
  199. /**
  200. * @param string $name
  201. * @param string $label
  202. * @param array $attributes
  203. *
  204. * @return mixed
  205. */
  206. public function addSelectLanguage($name, $label, $options = [], $attributes = [])
  207. {
  208. return $this->addElement('SelectLanguage', $name, $label, $options, $attributes);
  209. }
  210. /**
  211. * @param string $name
  212. * @param string $label
  213. * @param array $options
  214. * @param array $attributes
  215. * @throws
  216. */
  217. public function addSelectAjax($name, $label, $options = [], $attributes = [])
  218. {
  219. if (!isset($attributes['url'])) {
  220. throw new \Exception('select_ajax needs an URL');
  221. }
  222. $this->addElement(
  223. 'select_ajax',
  224. $name,
  225. $label,
  226. $options,
  227. $attributes
  228. );
  229. }
  230. /**
  231. * @param string $name
  232. * @param string $label
  233. * @param array $attributes
  234. *
  235. * @return mixed
  236. */
  237. public function addDateTimePicker($name, $label, $attributes = [])
  238. {
  239. return $this->addElement('DateTimePicker', $name, $label, $attributes);
  240. }
  241. /**
  242. * @param string $name
  243. * @param string $value
  244. */
  245. public function addHidden($name, $value)
  246. {
  247. $this->addElement('hidden', $name, $value);
  248. }
  249. /**
  250. * @param string $name
  251. * @param string $label
  252. * @param array $attributes
  253. *
  254. * @return HTML_QuickForm_textarea
  255. */
  256. public function addTextarea($name, $label, $attributes = array())
  257. {
  258. return $this->addElement('textarea', $name, $label, $attributes);
  259. }
  260. /**
  261. * @param string $name
  262. * @param string $label
  263. * @param string $icon font-awesome
  264. * @param string $style default|primary|success|info|warning|danger|link
  265. * @param string $size large|default|small|extra-small
  266. * @param string $class Example plus is transformed to icon fa fa-plus
  267. * @param array $attributes
  268. *
  269. * @return HTML_QuickForm_button
  270. */
  271. public function addButton(
  272. $name,
  273. $label,
  274. $icon = 'check',
  275. $style = 'default',
  276. $size = 'default',
  277. $class = null,
  278. $attributes = array(),
  279. $createElement = false
  280. ) {
  281. if ($createElement) {
  282. return $this->createElement(
  283. 'button',
  284. $name,
  285. $label,
  286. $icon,
  287. $style,
  288. $size,
  289. $class,
  290. $attributes
  291. );
  292. }
  293. return $this->addElement(
  294. 'button',
  295. $name,
  296. $label,
  297. $icon,
  298. $style,
  299. $size,
  300. $class,
  301. $attributes
  302. );
  303. }
  304. /**
  305. * Returns a button with the primary color and a check mark
  306. * @param string $label Text appearing on the button
  307. * @param string $name Element name (for form treatment purposes)
  308. * @param bool $createElement Whether to use the create or add method
  309. *
  310. * @return HTML_QuickForm_button
  311. */
  312. public function addButtonSave($label, $name = 'submit', $createElement = false)
  313. {
  314. return $this->addButton(
  315. $name,
  316. $label,
  317. 'check',
  318. 'primary',
  319. null,
  320. null,
  321. array(),
  322. $createElement
  323. );
  324. }
  325. /**
  326. * Returns a cancel button
  327. * @param string $label Text appearing on the button
  328. * @param string $name Element name (for form treatment purposes)
  329. * @param bool $createElement Whether to use the create or add method
  330. *
  331. * @return HTML_QuickForm_button
  332. */
  333. public function addButtonCancel($label, $name = 'submit', $createElement = false)
  334. {
  335. return $this->addButton(
  336. $name,
  337. $label,
  338. 'times',
  339. 'danger',
  340. null,
  341. null,
  342. array(),
  343. $createElement
  344. );
  345. }
  346. /**
  347. * Returns a button with the primary color and a "plus" icon
  348. * @param string $label Text appearing on the button
  349. * @param string $name Element name (for form treatment purposes)
  350. * @param bool $createElement Whether to use the create or add method
  351. * @param array $attributes Additional attributes
  352. *
  353. * @return HTML_QuickForm_button
  354. */
  355. public function addButtonCreate($label, $name = 'submit', $createElement = false, $attributes = array())
  356. {
  357. return $this->addButton(
  358. $name,
  359. $label,
  360. 'plus',
  361. 'primary',
  362. null,
  363. null,
  364. $attributes,
  365. $createElement
  366. );
  367. }
  368. /**
  369. * Returns a button with the primary color and a pencil icon
  370. * @param string $label Text appearing on the button
  371. * @param string $name Element name (for form treatment purposes)
  372. * @param bool $createElement Whether to use the create or add method
  373. * @return HTML_QuickForm_button
  374. */
  375. public function addButtonUpdate($label, $name = 'submit', $createElement = false)
  376. {
  377. return $this->addButton(
  378. $name,
  379. $label,
  380. 'pencil',
  381. 'primary',
  382. null,
  383. null,
  384. array(),
  385. $createElement
  386. );
  387. }
  388. /**
  389. * Returns a button with the danger color and a trash icon
  390. * @param string $label Text appearing on the button
  391. * @param string $name Element name (for form treatment purposes)
  392. * @param bool $createElement Whether to use the create or add method
  393. *
  394. * @return HTML_QuickForm_button
  395. */
  396. public function addButtonDelete($label, $name = 'submit', $createElement = false)
  397. {
  398. return $this->addButton(
  399. $name,
  400. $label,
  401. 'trash',
  402. 'danger',
  403. null,
  404. null,
  405. array(),
  406. $createElement
  407. );
  408. }
  409. /**
  410. * Returns a move style button
  411. * @param string $label Text appearing on the button
  412. * @param string $name Element name (for form treatment purposes)
  413. * @param bool $createElement Whether to use the create or add method
  414. *
  415. * @return HTML_QuickForm_button
  416. */
  417. public function addButtonMove($label, $name = 'submit', $createElement = false)
  418. {
  419. return $this->addButton(
  420. $name,
  421. $label,
  422. 'arrow-circle-right',
  423. 'primary',
  424. null,
  425. null,
  426. array(),
  427. $createElement
  428. );
  429. }
  430. /**
  431. * Returns a button with the primary color and a paper-plane icon
  432. * @param string $label Text appearing on the button
  433. * @param string $name Element name (for form treatment purposes)
  434. * @param bool $createElement Whether to use the create or add method
  435. *
  436. * @return HTML_QuickForm_button
  437. */
  438. public function addButtonSend($label, $name = 'submit', $createElement = false, $attributes = array())
  439. {
  440. return $this->addButton(
  441. $name,
  442. $label,
  443. 'paper-plane',
  444. 'primary',
  445. null,
  446. null,
  447. $attributes,
  448. $createElement
  449. );
  450. }
  451. /**
  452. * Returns a button with the default (grey?) color and a magnifier icon
  453. * @param string $label Text appearing on the button
  454. * @param string $name Element name (for form treatment purposes)
  455. *
  456. * @return HTML_QuickForm_button
  457. */
  458. public function addButtonSearch($label = null, $name = 'submit', $attributes = array())
  459. {
  460. if (empty($label)) {
  461. $label = get_lang('Search');
  462. }
  463. return $this->addButton($name, $label, 'search', 'default', null, null, $attributes);
  464. }
  465. /**
  466. * Returns a button with the primary color and a right-pointing arrow icon
  467. * @param string $label Text appearing on the button
  468. * @param string $name Element name (for form treatment purposes)
  469. * @param array $attributes Additional attributes
  470. * @return HTML_QuickForm_button
  471. */
  472. public function addButtonNext($label, $name = 'submit', $attributes = array())
  473. {
  474. return $this->addButton(
  475. $name,
  476. $label,
  477. 'arrow-right',
  478. 'primary',
  479. null,
  480. null,
  481. $attributes
  482. );
  483. }
  484. /**
  485. * Returns a button with the primary color and a check mark icon
  486. * @param string $label Text appearing on the button
  487. * @param string $name Element name (for form treatment purposes)
  488. * @param bool $createElement Whether to use the create or add method
  489. * @return HTML_QuickForm_button
  490. */
  491. public function addButtonImport($label, $name = 'submit', $createElement = false)
  492. {
  493. return $this->addButton(
  494. $name,
  495. $label,
  496. 'check',
  497. 'primary',
  498. null,
  499. null,
  500. array(),
  501. $createElement
  502. );
  503. }
  504. /**
  505. * Returns a button with the primary color and a check-mark icon
  506. * @param string $label Text appearing on the button
  507. * @param string $name Element name (for form treatment purposes)
  508. * @param bool $createElement Whether to use the create or add method
  509. * @return HTML_QuickForm_button
  510. */
  511. public function addButtonExport($label, $name = 'submit', $createElement = false)
  512. {
  513. return $this->addButton(
  514. $name,
  515. $label,
  516. 'check',
  517. 'primary',
  518. null,
  519. null,
  520. array(),
  521. $createElement
  522. );
  523. }
  524. /**
  525. * Shortcut to filter button
  526. * @param string $label Text appearing on the button
  527. * @param string $name Element name (for form treatment purposes)
  528. * @param bool $createElement Whether to use the create or add method
  529. * @return HTML_QuickForm_button
  530. */
  531. public function addButtonFilter($label, $name = 'submit', $createElement = false)
  532. {
  533. return $this->addButton(
  534. $name,
  535. $label,
  536. 'filter',
  537. 'primary',
  538. null,
  539. null,
  540. array(),
  541. $createElement
  542. );
  543. }
  544. /**
  545. * Shortcut to reset button
  546. * @param string $label Text appearing on the button
  547. * @param string $name Element name (for form treatment purposes)
  548. * @param bool $createElement Whether to use the create or add method
  549. * @return HTML_QuickForm_button
  550. */
  551. public function addButtonReset($label, $name = 'reset', $createElement = false)
  552. {
  553. $icon = 'eraser';
  554. $style = 'default';
  555. $size = 'default';
  556. $class = null;
  557. $attributes = array();
  558. if ($createElement) {
  559. return $this->createElement(
  560. 'reset',
  561. $name,
  562. $label,
  563. $icon,
  564. $style,
  565. $size,
  566. $class,
  567. $attributes
  568. );
  569. }
  570. return $this->addElement(
  571. 'reset',
  572. $name,
  573. $label,
  574. $icon,
  575. $style,
  576. $size,
  577. $class,
  578. $attributes
  579. );
  580. }
  581. /**
  582. * Returns a button with the primary color and an upload icon
  583. * @param string $label Text appearing on the button
  584. * @param string $name Element name (for form treatment purposes)
  585. * @param bool $createElement Whether to use the create or add method
  586. *
  587. * @return HTML_QuickForm_button
  588. */
  589. public function addButtonUpload($label, $name = 'submit', $createElement = false)
  590. {
  591. return $this->addButton(
  592. $name,
  593. $label,
  594. 'upload',
  595. 'primary',
  596. null,
  597. null,
  598. array(),
  599. $createElement
  600. );
  601. }
  602. /**
  603. * Returns a button with the primary color and a download icon
  604. * @param string $label Text appearing on the button
  605. * @param string $name Element name (for form treatment purposes)
  606. * @param bool $createElement Whether to use the create or add method
  607. *
  608. * @return HTML_QuickForm_button
  609. */
  610. public function addButtonDownload($label, $name = 'submit', $createElement = false)
  611. {
  612. return $this->addButton(
  613. $name,
  614. $label,
  615. 'download',
  616. 'primary',
  617. null,
  618. null,
  619. array(),
  620. $createElement
  621. );
  622. }
  623. /**
  624. * Returns a button with the primary color and a magnifier icon
  625. * @param string $label Text appearing on the button
  626. * @param string $name Element name (for form treatment purposes)
  627. * @param bool $createElement Whether to use the create or add method
  628. *
  629. * @return HTML_QuickForm_button
  630. */
  631. public function addButtonPreview($label, $name = 'submit', $createElement = false)
  632. {
  633. return $this->addButton(
  634. $name,
  635. $label,
  636. 'search',
  637. 'primary',
  638. null,
  639. null,
  640. array(),
  641. $createElement
  642. );
  643. }
  644. /**
  645. * Returns a button with the primary color and a copy (double sheet) icon
  646. * @param string $label Text appearing on the button
  647. * @param string $name Element name (for form treatment purposes)
  648. * @param bool $createElement Whether to use the create or add method
  649. *
  650. * @return HTML_QuickForm_button
  651. */
  652. public function addButtonCopy($label, $name = 'submit', $createElement = false)
  653. {
  654. return $this->addButton(
  655. $name,
  656. $label,
  657. 'copy',
  658. 'primary',
  659. null,
  660. null,
  661. array(),
  662. $createElement
  663. );
  664. }
  665. /**
  666. * @param string $name
  667. * @param string $label
  668. * @param string $text
  669. * @param array $attributes
  670. *
  671. * @return HTML_QuickForm_checkbox
  672. */
  673. public function addCheckBox($name, $label, $text = '', $attributes = array())
  674. {
  675. return $this->addElement('checkbox', $name, $label, $text, $attributes);
  676. }
  677. /**
  678. * @param string $name
  679. * @param string $label
  680. * @param array $options
  681. * @param array $attributes
  682. *
  683. * @return HTML_QuickForm_group
  684. */
  685. public function addCheckBoxGroup($name, $label, $options = array(), $attributes = array())
  686. {
  687. $group = array();
  688. foreach ($options as $value => $text) {
  689. $attributes['value'] = $value;
  690. $group[] = $this->createElement(
  691. 'checkbox',
  692. $value,
  693. null,
  694. $text,
  695. $attributes
  696. );
  697. }
  698. return $this->addGroup($group, $name, $label);
  699. }
  700. /**
  701. * @param string $name
  702. * @param string $label
  703. * @param array $options
  704. * @param array $attributes
  705. *
  706. * @return HTML_QuickForm_radio
  707. */
  708. public function addRadio($name, $label, $options = array(), $attributes = array())
  709. {
  710. $group = array();
  711. foreach ($options as $key => $value) {
  712. $group[] = $this->createElement('radio', null, null, $value, $key, $attributes);
  713. }
  714. return $this->addGroup($group, $name, $label);
  715. }
  716. /**
  717. * @param string $name
  718. * @param string $label
  719. * @param array $options
  720. * @param array $attributes
  721. *
  722. * @return HTML_QuickForm_select
  723. */
  724. public function addSelect($name, $label, $options = array(), $attributes = array())
  725. {
  726. return $this->addElement('select', $name, $label, $options, $attributes);
  727. }
  728. /**
  729. * @param $name
  730. * @param $label
  731. * @param $collection
  732. * @param array $attributes
  733. * @param bool $addNoneOption
  734. * @param string $textCallable set a function getStringValue() by default __toString()
  735. *
  736. * @return HTML_QuickForm_element
  737. */
  738. public function addSelectFromCollection(
  739. $name,
  740. $label,
  741. $collection,
  742. $attributes = array(),
  743. $addNoneOption = false,
  744. $textCallable = ''
  745. ) {
  746. $options = [];
  747. if ($addNoneOption) {
  748. $options[0] = get_lang('None');
  749. }
  750. if (!empty($collection)) {
  751. foreach ($collection as $item) {
  752. $text = $item;
  753. if (!empty($textCallable)) {
  754. $text = $item->$textCallable();
  755. }
  756. $options[$item->getId()] = $text;
  757. }
  758. }
  759. return $this->addElement('select', $name, $label, $options, $attributes);
  760. }
  761. /**
  762. * @param string $label
  763. * @param string $text
  764. *
  765. * @return HTML_QuickForm_label
  766. */
  767. public function addLabel($label, $text)
  768. {
  769. return $this->addElement('label', $label, $text);
  770. }
  771. /**
  772. * @param string $text
  773. */
  774. public function addHeader($text)
  775. {
  776. $this->addElement('header', $text);
  777. }
  778. /**
  779. * @param string $name
  780. * @param string $label
  781. * @param array $attributes
  782. * @throws Exception if the file doesn't have an id
  783. */
  784. public function addFile($name, $label, $attributes = array())
  785. {
  786. $element = $this->addElement('file', $name, $label, $attributes);
  787. if (isset($attributes['crop_image'])) {
  788. $id = $element->getAttribute('id');
  789. if (empty($id)) {
  790. throw new Exception('If you use the crop functionality the element must have an id');
  791. }
  792. $this->addHtml('
  793. <div class="form-group">
  794. <label for="cropImage" id="'.$id.'_label_crop_image" class="col-sm-2 control-label"></label>
  795. <div class="col-sm-8">
  796. <div id="'.$id.'_crop_image" class="cropCanvas">
  797. <img id="'.$id.'_preview_image">
  798. </div>
  799. <div>
  800. <button class="btn btn-primary hidden" name="cropButton" id="'.$id.'_crop_button" >
  801. <em class="fa fa-crop"></em> '.
  802. get_lang('CropYourPicture').'
  803. </button>
  804. </div>
  805. </div>
  806. </div>'
  807. );
  808. $this->addHidden($id.'_crop_result', '');
  809. $this->addHidden($id.'_crop_image_base_64', '');
  810. }
  811. }
  812. /**
  813. * @param string $snippet
  814. */
  815. public function addHtml($snippet)
  816. {
  817. $this->addElement('html', $snippet);
  818. }
  819. /**
  820. * Adds a HTML-editor to the form
  821. * @param string $name
  822. * @param string $label The label for the form-element
  823. * @param bool $required (optional) Is the form-element required (default=true)
  824. * @param bool $fullPage (optional) When it is true, the editor loads completed html code for a full page.
  825. * @param array $config (optional) Configuration settings for the online editor.
  826. * @param bool $style
  827. */
  828. public function addHtmlEditor(
  829. $name,
  830. $label,
  831. $required = true,
  832. $fullPage = false,
  833. $config = [],
  834. $style = false
  835. ) {
  836. $attributes = [];
  837. $attributes['rows'] = isset($config['rows']) ? $config['rows'] : 15;
  838. $attributes['cols'] = isset($config['cols']) ? $config['cols'] : 80;
  839. $attributes['cols-size'] = isset($config['cols-size']) ? $config['cols-size'] : [];
  840. $attributes['class'] = isset($config['class']) ? $config['class'] : [];
  841. $this->addElement('html_editor', $name, $label, $attributes, $config);
  842. $this->applyFilter($name, 'trim');
  843. if ($required) {
  844. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  845. }
  846. /** @var HtmlEditor $element */
  847. $element = $this->getElement($name);
  848. if ($style) {
  849. $config['style'] = true;
  850. }
  851. if ($fullPage) {
  852. $config['fullPage'] = true;
  853. }
  854. if ($element->editor) {
  855. $element->editor->processConfig($config);
  856. }
  857. }
  858. /**
  859. * Adds a Google Maps Geolocalization field to the form
  860. *
  861. * @param $name
  862. * @param $label
  863. */
  864. public function addGeoLocationMapField($name, $label)
  865. {
  866. $gMapsPlugin = GoogleMapsPlugin::create();
  867. $geolocalization = $gMapsPlugin->get('enable_api') === 'true';
  868. if ($geolocalization) {
  869. $gmapsApiKey = $gMapsPlugin->get('api_key');
  870. $this->addHtml('<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='.$gmapsApiKey.'" ></script>');
  871. }
  872. $this->addElement(
  873. 'text',
  874. $name,
  875. $label,
  876. ['id' => $name]
  877. );
  878. $this->applyFilter($name, 'stripslashes');
  879. $this->applyFilter($name, 'trim');
  880. $this->addHtml('
  881. <div class="form-group">
  882. <label for="geolocalization_'.$name.'" class="col-sm-2 control-label"></label>
  883. <div class="col-sm-8">
  884. <button class="null btn btn-default " id="geolocalization_'.$name.'" name="geolocalization_'.$name.'" type="submit"><em class="fa fa-map-marker"></em> '.get_lang('Geolocalization').'</button>
  885. <button class="null btn btn-default " id="myLocation_'.$name.'" name="myLocation_'.$name.'" type="submit"><em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'</button>
  886. </div>
  887. </div>
  888. ');
  889. $this->addHtml('
  890. <div class="form-group">
  891. <label for="map_'.$name.'" class="col-sm-2 control-label">
  892. '.$label.' - '.get_lang('Map').'
  893. </label>
  894. <div class="col-sm-8">
  895. <div name="map_'.$name.'" id="map_'.$name.'" style="width:100%; height:300px;">
  896. </div>
  897. </div>
  898. </div>
  899. ');
  900. $this->addHtml(
  901. '<script>
  902. $(document).ready(function() {
  903. if (typeof google === "object") {
  904. var address = $("#' . $name.'").val();
  905. initializeGeo'.$name.'(address, false);
  906. $("#geolocalization_'.$name.'").on("click", function() {
  907. var address = $("#'.$name.'").val();
  908. initializeGeo'.$name.'(address, false);
  909. return false;
  910. });
  911. $("#myLocation_'.$name.'").on("click", function() {
  912. myLocation'.$name.'();
  913. return false;
  914. });
  915. $("#'.$name.'").keypress(function (event) {
  916. if (event.which == 13) {
  917. $("#geolocalization_'.$name.'").click();
  918. return false;
  919. }
  920. });
  921. } else {
  922. $("#map_'.$name.'").html("<div class=\"alert alert-info\">'.get_lang('YouNeedToActivateTheGoogleMapsPluginInAdminPlatformToSeeTheMap').'</div>");
  923. }
  924. });
  925. function myLocation'.$name.'() {
  926. if (navigator.geolocation) {
  927. var geoPosition = function(position) {
  928. var lat = position.coords.latitude;
  929. var lng = position.coords.longitude;
  930. var latLng = new google.maps.LatLng(lat, lng);
  931. initializeGeo'.$name.'(false, latLng)
  932. };
  933. var geoError = function(error) {
  934. alert("Geocode ' . get_lang('Error').': " + error);
  935. };
  936. var geoOptions = {
  937. enableHighAccuracy: true
  938. };
  939. navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
  940. }
  941. }
  942. function initializeGeo'.$name.'(address, latLng) {
  943. var geocoder = new google.maps.Geocoder();
  944. var latlng = new google.maps.LatLng(-34.397, 150.644);
  945. var myOptions = {
  946. zoom: 15,
  947. center: latlng,
  948. mapTypeControl: true,
  949. mapTypeControlOptions: {
  950. style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
  951. },
  952. navigationControl: true,
  953. mapTypeId: google.maps.MapTypeId.ROADMAP
  954. };
  955. map_'.$name.' = new google.maps.Map(document.getElementById("map_'.$name.'"), myOptions);
  956. var parameter = address ? { "address": address } : latLng ? { "latLng": latLng } : false;
  957. if (geocoder && parameter) {
  958. geocoder.geocode(parameter, function(results, status) {
  959. if (status == google.maps.GeocoderStatus.OK) {
  960. if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
  961. map_'.$name.'.setCenter(results[0].geometry.location);
  962. if (!address) {
  963. $("#'.$name.'").val(results[0].formatted_address);
  964. }
  965. var infowindow = new google.maps.InfoWindow({
  966. content: "<b>" + $("#'.$name.'").val() + "</b>",
  967. size: new google.maps.Size(150, 50)
  968. });
  969. var marker = new google.maps.Marker({
  970. position: results[0].geometry.location,
  971. map: map_'.$name.',
  972. title: $("#'.$name.'").val()
  973. });
  974. google.maps.event.addListener(marker, "click", function() {
  975. infowindow.open(map_'.$name.', marker);
  976. });
  977. } else {
  978. alert("' . get_lang("NotFound").'");
  979. }
  980. } else {
  981. alert("Geocode ' . get_lang('Error').': '.get_lang("AddressField").' '.get_lang("NotFound").'");
  982. }
  983. });
  984. }
  985. }
  986. </script>
  987. ');
  988. }
  989. /**
  990. * @param string $name
  991. * @param string $label
  992. *
  993. * @return mixed
  994. */
  995. public function addButtonAdvancedSettings($name, $label = '')
  996. {
  997. $label = !empty($label) ? $label : get_lang('AdvancedParameters');
  998. return $this->addElement('advanced_settings', $name, $label);
  999. }
  1000. /**
  1001. * Adds a progress loading image to the form.
  1002. *
  1003. */
  1004. public function addProgress($delay = 2, $label = '')
  1005. {
  1006. if (empty($label)) {
  1007. $label = get_lang('PleaseStandBy');
  1008. }
  1009. $this->with_progress_bar = true;
  1010. $id = $this->getAttribute('id');
  1011. $this->updateAttributes("onsubmit=\"javascript: addProgress('".$id."')\"");
  1012. $this->addHtml('<script language="javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/upload.js" type="text/javascript"></script>');
  1013. }
  1014. /**
  1015. * This function has been created for avoiding changes directly within QuickForm class.
  1016. * When we use it, the element is threated as 'required' to be dealt during validation.
  1017. * @param array $elements The array of elements
  1018. * @param string $message The message displayed
  1019. */
  1020. public function add_multiple_required_rule($elements, $message)
  1021. {
  1022. $this->_required[] = $elements[0];
  1023. $this->addRule($elements, $message, 'multiple_required');
  1024. }
  1025. /**
  1026. * Displays the form.
  1027. * If an element in the form didn't validate, an error message is showed
  1028. * asking the user to complete the form.
  1029. */
  1030. public function display()
  1031. {
  1032. echo $this->returnForm();
  1033. }
  1034. /**
  1035. * Returns the HTML code of the form.
  1036. * @return string $return_value HTML code of the form
  1037. */
  1038. public function returnForm()
  1039. {
  1040. $returnValue = '';
  1041. /** @var HTML_QuickForm_element $element */
  1042. foreach ($this->_elements as $element) {
  1043. $elementError = parent::getElementError($element->getName());
  1044. if (!is_null($elementError)) {
  1045. $returnValue .= Display::return_message($elementError, 'warning').'<br />';
  1046. break;
  1047. }
  1048. }
  1049. $returnValue .= parent::toHtml();
  1050. // Add div-element which is to hold the progress bar
  1051. $id = $this->getAttribute('id');
  1052. if (isset($this->with_progress_bar) && $this->with_progress_bar) {
  1053. $icon = Display::return_icon('progress_bar.gif');
  1054. // @todo improve UI
  1055. $returnValue .= '<br />
  1056. <div id="loading_div_'.$id.'" class="loading_div" style="display:none;margin-left:40%; margin-top:10px; height:50px;">
  1057. '.$icon.'
  1058. </div>
  1059. ';
  1060. }
  1061. return $returnValue;
  1062. }
  1063. /**
  1064. * Returns the HTML code of the form.
  1065. * If an element in the form didn't validate, an error message is showed
  1066. * asking the user to complete the form.
  1067. *
  1068. * @return string $return_value HTML code of the form
  1069. *
  1070. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, august 2006
  1071. * @author Julio Montoya
  1072. * @deprecated use returnForm()
  1073. */
  1074. public function return_form()
  1075. {
  1076. return $this->returnForm();
  1077. }
  1078. /**
  1079. * Create a form validator based on an array of form data:
  1080. *
  1081. * array(
  1082. * 'name' => 'zombie_report_parameters', //optional
  1083. * 'method' => 'GET', //optional
  1084. * 'items' => array(
  1085. * array(
  1086. * 'name' => 'ceiling',
  1087. * 'label' => 'Ceiling', //optional
  1088. * 'type' => 'date',
  1089. * 'default' => date() //optional
  1090. * ),
  1091. * array(
  1092. * 'name' => 'active_only',
  1093. * 'label' => 'ActiveOnly',
  1094. * 'type' => 'checkbox',
  1095. * 'default' => true
  1096. * ),
  1097. * array(
  1098. * 'name' => 'submit_button',
  1099. * 'type' => 'style_submit_button',
  1100. * 'value' => get_lang('Search'),
  1101. * 'attributes' => array('class' => 'search')
  1102. * )
  1103. * )
  1104. * );
  1105. *
  1106. * @param array $form_data
  1107. * @deprecated use normal FormValidator construct
  1108. *
  1109. * @return FormValidator
  1110. */
  1111. public static function create($form_data)
  1112. {
  1113. if (empty($form_data)) {
  1114. return null;
  1115. }
  1116. $form_name = isset($form_data['name']) ? $form_data['name'] : 'form';
  1117. $form_method = isset($form_data['method']) ? $form_data['method'] : 'POST';
  1118. $form_action = isset($form_data['action']) ? $form_data['action'] : '';
  1119. $form_target = isset($form_data['target']) ? $form_data['target'] : '';
  1120. $form_attributes = isset($form_data['attributes']) ? $form_data['attributes'] : null;
  1121. $form_track_submit = isset($form_data['track_submit']) ? $form_data['track_submit'] : true;
  1122. $reset = null;
  1123. $result = new FormValidator($form_name, $form_method, $form_action, $form_target, $form_attributes, $form_track_submit);
  1124. $defaults = array();
  1125. foreach ($form_data['items'] as $item) {
  1126. $name = $item['name'];
  1127. $type = isset($item['type']) ? $item['type'] : 'text';
  1128. $label = isset($item['label']) ? $item['label'] : '';
  1129. if ($type == 'wysiwyg') {
  1130. $element = $result->addHtmlEditor($name, $label);
  1131. } else {
  1132. $element = $result->addElement($type, $name, $label);
  1133. }
  1134. if (isset($item['attributes'])) {
  1135. $attributes = $item['attributes'];
  1136. $element->setAttributes($attributes);
  1137. }
  1138. if (isset($item['value'])) {
  1139. $value = $item['value'];
  1140. $element->setValue($value);
  1141. }
  1142. if (isset($item['default'])) {
  1143. $defaults[$name] = $item['default'];
  1144. }
  1145. if (isset($item['rules'])) {
  1146. $rules = $item['rules'];
  1147. foreach ($rules as $rule) {
  1148. $message = $rule['message'];
  1149. $type = $rule['type'];
  1150. $format = isset($rule['format']) ? $rule['format'] : null;
  1151. $validation = isset($rule['validation']) ? $rule['validation'] : 'server';
  1152. $force = isset($rule['force']) ? $rule['force'] : false;
  1153. $result->addRule($name, $message, $type, $format, $validation, $reset, $force);
  1154. }
  1155. }
  1156. }
  1157. $result->setDefaults($defaults);
  1158. return $result;
  1159. }
  1160. /**
  1161. * @return HTML_QuickForm_Renderer_Default
  1162. */
  1163. public static function getDefaultRenderer()
  1164. {
  1165. return
  1166. isset($GLOBALS['_HTML_QuickForm_default_renderer']) ?
  1167. $GLOBALS['_HTML_QuickForm_default_renderer'] : null;
  1168. }
  1169. /**
  1170. * Adds a input of type url to the form.
  1171. * @param string $name The label for the form-element
  1172. * @param string $label The element name
  1173. * @param bool $required Optional. Is the form-element required (default=true)
  1174. * @param array $attributes Optional. List of attributes for the form-element
  1175. */
  1176. public function addUrl($name, $label, $required = true, $attributes = array())
  1177. {
  1178. $this->addElement('url', $name, $label, $attributes);
  1179. $this->applyFilter($name, 'trim');
  1180. $this->addRule($name, get_lang('InsertAValidUrl'), 'url');
  1181. if ($required) {
  1182. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1183. }
  1184. }
  1185. /**
  1186. * Adds a text field for letters to the form.
  1187. * A trim-filter is attached to the field.
  1188. * @param string $name The element name
  1189. * @param string $label The label for the form-element
  1190. * @param bool $required Optional. Is the form-element required (default=true)
  1191. * @param array $attributes Optional. List of attributes for the form-element
  1192. */
  1193. public function addTextLettersOnly(
  1194. $name,
  1195. $label,
  1196. $required = false,
  1197. $attributes = []
  1198. ) {
  1199. $attributes = array_merge(
  1200. $attributes,
  1201. [
  1202. 'pattern' => '[a-zA-ZñÑ]+',
  1203. 'title' => get_lang('OnlyLetters')
  1204. ]
  1205. );
  1206. $this->addElement(
  1207. 'text',
  1208. $name,
  1209. [
  1210. $label,
  1211. get_lang('OnlyLetters')
  1212. ],
  1213. $attributes
  1214. );
  1215. $this->applyFilter($name, 'trim');
  1216. if ($required) {
  1217. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1218. }
  1219. $this->addRule(
  1220. $name,
  1221. get_lang('OnlyLetters'),
  1222. 'regex',
  1223. '/^[a-zA-ZñÑ]+$/'
  1224. );
  1225. }
  1226. /**
  1227. * Adds a text field for alphanumeric characters to the form.
  1228. * A trim-filter is attached to the field.
  1229. * @param string $name The element name
  1230. * @param string $label The label for the form-element
  1231. * @param bool $required Optional. Is the form-element required (default=true)
  1232. * @param array $attributes Optional. List of attributes for the form-element
  1233. */
  1234. public function addTextAlphanumeric(
  1235. $name,
  1236. $label,
  1237. $required = false,
  1238. $attributes = []
  1239. ) {
  1240. $attributes = array_merge(
  1241. $attributes,
  1242. [
  1243. 'pattern' => '[a-zA-Z0-9ñÑ]+',
  1244. 'title' => get_lang('OnlyLettersAndNumbers')
  1245. ]
  1246. );
  1247. $this->addElement(
  1248. 'text',
  1249. $name,
  1250. [
  1251. $label,
  1252. get_lang('OnlyLettersAndNumbers')
  1253. ],
  1254. $attributes
  1255. );
  1256. $this->applyFilter($name, 'trim');
  1257. if ($required) {
  1258. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1259. }
  1260. $this->addRule(
  1261. $name,
  1262. get_lang('OnlyLettersAndNumbers'),
  1263. 'regex',
  1264. '/^[a-zA-Z0-9ÑÑ]+$/'
  1265. );
  1266. }
  1267. /**
  1268. * @param string $name
  1269. * @param $label
  1270. * @param bool $required
  1271. * @param array $attributes
  1272. * @param bool $allowNegative
  1273. * @param integer $minValue
  1274. * @param null $maxValue
  1275. */
  1276. public function addFloat(
  1277. $name,
  1278. $label,
  1279. $required = false,
  1280. $attributes = [],
  1281. $allowNegative = false,
  1282. $minValue = null,
  1283. $maxValue = null
  1284. ) {
  1285. $this->addElement(
  1286. 'FloatNumber',
  1287. $name,
  1288. $label,
  1289. $attributes
  1290. );
  1291. $this->applyFilter($name, 'trim');
  1292. if ($required) {
  1293. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1294. }
  1295. // Rule allows "," and "."
  1296. /*$this->addRule(
  1297. $name,
  1298. get_lang('OnlyNumbers'),
  1299. 'regex',
  1300. '/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|(^-?\d\d*\,\d*$)|(^-?\,\d\d*$)/'
  1301. );*/
  1302. if ($allowNegative == false) {
  1303. $this->addRule(
  1304. $name,
  1305. get_lang('NegativeValue'),
  1306. 'compare',
  1307. '>=',
  1308. 'server',
  1309. false,
  1310. false,
  1311. 0
  1312. );
  1313. }
  1314. if (!is_null($minValue)) {
  1315. $this->addRule(
  1316. $name,
  1317. get_lang('UnderMin'),
  1318. 'compare',
  1319. '>=',
  1320. 'server',
  1321. false,
  1322. false,
  1323. $minValue
  1324. );
  1325. }
  1326. if (!is_null($maxValue)) {
  1327. $this->addRule(
  1328. $name,
  1329. get_lang('OverMax'),
  1330. 'compare',
  1331. '<=',
  1332. 'server',
  1333. false,
  1334. false,
  1335. $maxValue
  1336. );
  1337. }
  1338. }
  1339. /**
  1340. * Adds a text field for letters and spaces to the form.
  1341. * A trim-filter is attached to the field.
  1342. * @param string $name The element name
  1343. * @param string $label The label for the form-element
  1344. * @param bool $required Optional. Is the form-element required (default=true)
  1345. * @param array $attributes Optional. List of attributes for the form-element
  1346. */
  1347. public function addTextLettersAndSpaces(
  1348. $name,
  1349. $label,
  1350. $required = false,
  1351. $attributes = []
  1352. ) {
  1353. $attributes = array_merge(
  1354. $attributes,
  1355. [
  1356. 'pattern' => '[a-zA-ZñÑ\s]+',
  1357. 'title' => get_lang('OnlyLettersAndSpaces')
  1358. ]
  1359. );
  1360. $this->addElement(
  1361. 'text',
  1362. $name,
  1363. [
  1364. $label,
  1365. get_lang('OnlyLettersAndSpaces')
  1366. ],
  1367. $attributes
  1368. );
  1369. $this->applyFilter($name, 'trim');
  1370. if ($required) {
  1371. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1372. }
  1373. $this->addRule(
  1374. $name,
  1375. get_lang('OnlyLettersAndSpaces'),
  1376. 'regex',
  1377. '/^[a-zA-ZñÑ\s]+$/'
  1378. );
  1379. }
  1380. /**
  1381. * Adds a text field for alphanumeric and spaces characters to the form.
  1382. * A trim-filter is attached to the field.
  1383. * @param string $name The element name
  1384. * @param string $label The label for the form-element
  1385. * @param bool $required Optional. Is the form-element required (default=true)
  1386. * @param array $attributes Optional. List of attributes for the form-element
  1387. */
  1388. public function addTextAlphanumericAndSpaces(
  1389. $name,
  1390. $label,
  1391. $required = false,
  1392. $attributes = []
  1393. ) {
  1394. $attributes = array_merge(
  1395. $attributes,
  1396. [
  1397. 'pattern' => '[a-zA-Z0-9ñÑ\s]+',
  1398. 'title' => get_lang('OnlyLettersAndNumbersAndSpaces')
  1399. ]
  1400. );
  1401. $this->addElement(
  1402. 'text',
  1403. $name,
  1404. [
  1405. $label,
  1406. get_lang('OnlyLettersAndNumbersAndSpaces')
  1407. ],
  1408. $attributes
  1409. );
  1410. $this->applyFilter($name, 'trim');
  1411. if ($required) {
  1412. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1413. }
  1414. $this->addRule(
  1415. $name,
  1416. get_lang('OnlyLettersAndNumbersAndSpaces'),
  1417. 'regex',
  1418. '/^[a-zA-Z0-9ñÑ\s]+$/'
  1419. );
  1420. }
  1421. /**
  1422. * @param string $url
  1423. */
  1424. public function addMultipleUpload($url)
  1425. {
  1426. $inputName = 'input_file_upload';
  1427. $this->addMultipleUploadJavascript($url, $inputName);
  1428. $this->addHtml('
  1429. <div class="description-upload">
  1430. '.get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadField').'
  1431. </div>
  1432. <span class="btn btn-success fileinput-button">
  1433. <i class="glyphicon glyphicon-plus"></i>
  1434. <span>'.get_lang('AddFiles').'</span>
  1435. <!-- The file input field used as target for the file upload widget -->
  1436. <input id="'.$inputName.'" type="file" name="files[]" multiple>
  1437. </span>
  1438. <div id="dropzone">
  1439. <div class="button-load">
  1440. '.get_lang('UploadFiles').'
  1441. </div>
  1442. </div>
  1443. <br />
  1444. <!-- The global progress bar -->
  1445. <div id="progress" class="progress">
  1446. <div class="progress-bar progress-bar-success"></div>
  1447. </div>
  1448. <div id="files" class="files"></div>
  1449. ');
  1450. }
  1451. /**
  1452. *
  1453. * @param string $url page that will handle the upload
  1454. * @param string $inputName
  1455. */
  1456. private function addMultipleUploadJavascript($url, $inputName)
  1457. {
  1458. $icon = Display::return_icon('file_txt.gif');
  1459. $this->addHtml("
  1460. <script>
  1461. $(function () {
  1462. 'use strict';
  1463. $('#".$this->getAttribute('id')."').submit(function() {
  1464. return false;
  1465. });
  1466. $('#dropzone').on('click', function() {
  1467. $('#".$inputName."').click();
  1468. });
  1469. var url = '".$url."';
  1470. var uploadButton = $('<button/>')
  1471. .addClass('btn btn-primary')
  1472. .prop('disabled', true)
  1473. .text('".addslashes(get_lang('Loading'))."')
  1474. .on('click', function () {
  1475. var \$this = $(this),
  1476. data = \$this.data();
  1477. \$this
  1478. .off('click')
  1479. .text('".addslashes(get_lang('Cancel'))."')
  1480. .on('click', function () {
  1481. \$this.remove();
  1482. data.abort();
  1483. });
  1484. data.submit().always(function () {
  1485. \$this.remove();
  1486. });
  1487. });
  1488. $('#".$inputName."').fileupload({
  1489. url: url,
  1490. dataType: 'json',
  1491. // Enable image resizing, except for Android and Opera,
  1492. // which actually support image resizing, but fail to
  1493. // send Blob objects via XHR requests:
  1494. disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
  1495. previewMaxWidth: 100,
  1496. previewMaxHeight: 100,
  1497. previewCrop: true,
  1498. dropzone: $('#dropzone'),
  1499. }).on('fileuploadadd', function (e, data) {
  1500. data.context = $('<div class=\"row\" style=\"margin-bottom:35px\" />').appendTo('#files');
  1501. $.each(data.files, function (index, file) {
  1502. var node = $('<div class=\"col-sm-5\">').text(file.name);
  1503. node.appendTo(data.context);
  1504. });
  1505. }).on('fileuploadprocessalways', function (e, data) {
  1506. var index = data.index,
  1507. file = data.files[index],
  1508. node = $(data.context.children()[index]);
  1509. if (file.preview) {
  1510. data.context
  1511. .prepend($('<div class=\"col-sm-2\">').html(file.preview))
  1512. ;
  1513. } else {
  1514. data.context
  1515. .prepend($('<div class=\"col-sm-2\">').html('".$icon."'))
  1516. ;
  1517. }
  1518. if (index + 1 === data.files.length) {
  1519. data.context.find('button')
  1520. .text('Upload')
  1521. .prop('disabled', !!data.files.error);
  1522. }
  1523. }).on('fileuploadprogressall', function (e, data) {
  1524. var progress = parseInt(data.loaded / data.total * 100, 10);
  1525. $('#progress .progress-bar').css(
  1526. 'width',
  1527. progress + '%'
  1528. );
  1529. }).on('fileuploaddone', function (e, data) {
  1530. $.each(data.result.files, function (index, file) {
  1531. if (file.url) {
  1532. var link = $('<a>')
  1533. .attr('target', '_blank')
  1534. .prop('href', file.url);
  1535. $(data.context.children()[index]).parent().wrap(link);
  1536. var successMessage = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-success\"/>').text('" . addslashes(get_lang('UplUploadSucceeded'))."'));
  1537. $(data.context.children()[index]).parent().append(successMessage);
  1538. } else if (file.error) {
  1539. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(file.error));
  1540. $(data.context.children()[index]).parent().append(error);
  1541. }
  1542. });
  1543. $('#dropzone').removeClass('hover');
  1544. }).on('fileuploadfail', function (e, data) {
  1545. $.each(data.files, function (index) {
  1546. var failedMessage = '" . addslashes(get_lang('UplUploadFailed'))."';
  1547. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(failedMessage));
  1548. $(data.context.children()[index]).parent().append(error);
  1549. });
  1550. $('#dropzone').removeClass('hover');
  1551. }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
  1552. $('#dropzone').on('dragover', function (e) {
  1553. // dragleave callback implementation
  1554. $('#dropzone').addClass('hover');
  1555. });
  1556. $('#dropzone').on('dragleave', function (e) {
  1557. $('#dropzone').removeClass('hover');
  1558. });
  1559. $('.fileinput-button').hide();
  1560. });
  1561. </script>");
  1562. }
  1563. /**
  1564. * @param string $elementName
  1565. * @param string $groupName if element is inside a group
  1566. * @throws Exception
  1567. */
  1568. public function addPasswordRule($elementName, $groupName = '')
  1569. {
  1570. // Constant defined in old config/profile.conf.php
  1571. if (CHECK_PASS_EASY_TO_FIND === true) {
  1572. $message = get_lang('PassTooEasy').': '.api_generate_password();
  1573. if (!empty($groupName)) {
  1574. $groupObj = $this->getElement($groupName);
  1575. if ($groupObj instanceof HTML_QuickForm_group) {
  1576. $elementName = $groupObj->getElementName($elementName);
  1577. if ($elementName === false) {
  1578. throw new Exception("The $groupName doesn't have the element $elementName");
  1579. }
  1580. $this->_rules[$elementName][] = array(
  1581. 'type' => 'callback',
  1582. 'format' => 'api_check_password',
  1583. 'message' => $message,
  1584. 'validation' => '',
  1585. 'reset' => false,
  1586. 'group' => $groupName
  1587. );
  1588. }
  1589. } else {
  1590. $this->addRule(
  1591. $elementName,
  1592. $message,
  1593. 'callback',
  1594. 'api_check_password'
  1595. );
  1596. }
  1597. }
  1598. }
  1599. }
  1600. /**
  1601. * Cleans HTML text filter
  1602. * @param string $html HTML to clean
  1603. * @param int $mode (optional)
  1604. * @return string The cleaned HTML
  1605. */
  1606. function html_filter($html, $mode = NO_HTML)
  1607. {
  1608. $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode);
  1609. $cleaned_html = kses($html, $allowed_tags);
  1610. return $cleaned_html;
  1611. }
  1612. function html_filter_teacher($html)
  1613. {
  1614. return html_filter($html, TEACHER_HTML);
  1615. }
  1616. function html_filter_student($html)
  1617. {
  1618. return html_filter($html, STUDENT_HTML);
  1619. }
  1620. function html_filter_teacher_fullpage($html)
  1621. {
  1622. return html_filter($html, TEACHER_HTML_FULLPAGE);
  1623. }
  1624. function html_filter_student_fullpage($html)
  1625. {
  1626. return html_filter($html, STUDENT_HTML_FULLPAGE);
  1627. }
  1628. /**
  1629. * Cleans mobile phone number text
  1630. * @param string $mobilePhoneNumber Mobile phone number to clean
  1631. * @return string The cleaned mobile phone number
  1632. */
  1633. function mobile_phone_number_filter($mobilePhoneNumber)
  1634. {
  1635. $mobilePhoneNumber = str_replace(array('+', '(', ')'), '', $mobilePhoneNumber);
  1636. return ltrim($mobilePhoneNumber, '0');
  1637. }