FormValidator.class.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  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. * @return string
  108. */
  109. public function getDefaultElementTemplate()
  110. {
  111. return '
  112. <div class="form-group {error_class}">
  113. <label {label-for} class="col-sm-2 control-label {extra_label_class}" >
  114. <!-- BEGIN required --><span class="form_required">*</span><!-- END required -->
  115. {label}
  116. </label>
  117. <div class="col-sm-8">
  118. {icon}
  119. {element}
  120. <!-- BEGIN label_2 -->
  121. <p class="help-block">{label_2}</p>
  122. <!-- END label_2 -->
  123. <!-- BEGIN error -->
  124. <span class="help-inline">{error}</span>
  125. <!-- END error -->
  126. </div>
  127. <div class="col-sm-2">
  128. <!-- BEGIN label_3 -->
  129. {label_3}
  130. <!-- END label_3 -->
  131. </div>
  132. </div>';
  133. }
  134. /**
  135. * @return string
  136. */
  137. public function getLayout()
  138. {
  139. return $this->layout;
  140. }
  141. /**
  142. * @param string $layout
  143. */
  144. public function setLayout($layout)
  145. {
  146. $this->layout = $layout;
  147. }
  148. /**
  149. * Adds a text field to the form.
  150. * A trim-filter is attached to the field.
  151. * @param string $label The label for the form-element
  152. * @param string $name The element name
  153. * @param bool $required (optional) Is the form-element required (default=true)
  154. * @param array $attributes (optional) List of attributes for the form-element
  155. */
  156. public function addText($name, $label, $required = true, $attributes = array())
  157. {
  158. $this->addElement('text', $name, $label, $attributes);
  159. $this->applyFilter($name, 'trim');
  160. if ($required) {
  161. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  162. }
  163. }
  164. /**
  165. * The "date_range_picker" element creates 2 hidden fields
  166. * "elementName" + "_start" and "elementName" + "_end"
  167. * For example if the name is "range", you will have 2 new fields
  168. * when executing $form->getSubmitValues()
  169. * "range_start" and "range_end"
  170. *
  171. * @param string $name
  172. * @param string $label
  173. * @param bool $required
  174. * @param array $attributes
  175. */
  176. public function addDateRangePicker($name, $label, $required = true, $attributes = array())
  177. {
  178. $this->addElement('date_range_picker', $name, $label, $attributes);
  179. $this->addElement('hidden', $name.'_start');
  180. $this->addElement('hidden', $name.'_end');
  181. if ($required) {
  182. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  183. }
  184. }
  185. /**
  186. * @param string $name
  187. * @param string $label
  188. * @param array $attributes
  189. *
  190. * @return mixed
  191. */
  192. public function addDatePicker($name, $label, $attributes = [])
  193. {
  194. return $this->addElement('DatePicker', $name, $label, $attributes);
  195. }
  196. /**
  197. * @param string $name
  198. * @param string $label
  199. * @param array $attributes
  200. *
  201. * @return mixed
  202. */
  203. public function addSelectLanguage($name, $label, $options = [], $attributes = [])
  204. {
  205. return $this->addElement('SelectLanguage', $name, $label, $options, $attributes);
  206. }
  207. /**
  208. * @param $name
  209. * @param $label
  210. * @param array $options
  211. * @param array $attributes
  212. * @throws
  213. */
  214. public function addSelectAjax($name, $label, $options = [], $attributes = [])
  215. {
  216. if (!isset($attributes['url'])) {
  217. throw new \Exception('select_ajax needs an URL');
  218. }
  219. $this->addElement(
  220. 'select_ajax',
  221. $name,
  222. $label,
  223. $options,
  224. $attributes
  225. );
  226. }
  227. /**
  228. * @param string $name
  229. * @param string $label
  230. * @param array $attributes
  231. *
  232. * @return mixed
  233. */
  234. public function addDateTimePicker($name, $label, $attributes = [])
  235. {
  236. return $this->addElement('DateTimePicker', $name, $label, $attributes);
  237. }
  238. /**
  239. * @param string $name
  240. * @param string $value
  241. */
  242. public function addHidden($name, $value)
  243. {
  244. $this->addElement('hidden', $name, $value);
  245. }
  246. /**
  247. * @param string $name
  248. * @param string $label
  249. * @param array $attributes
  250. *
  251. * @return HTML_QuickForm_textarea
  252. */
  253. public function addTextarea($name, $label, $attributes = array())
  254. {
  255. return $this->addElement('textarea', $name, $label, $attributes);
  256. }
  257. /**
  258. * @param string $name
  259. * @param string $label
  260. * @param string $icon font-awesome
  261. * @param string $style default|primary|success|info|warning|danger|link
  262. * @param string $size large|default|small|extra-small
  263. * @param string $class Example plus is transformed to icon fa fa-plus
  264. * @param array $attributes
  265. *
  266. * @return HTML_QuickForm_button
  267. */
  268. public function addButton(
  269. $name,
  270. $label,
  271. $icon = 'check',
  272. $style = 'default',
  273. $size = 'default',
  274. $class = null,
  275. $attributes = array(),
  276. $createElement = false
  277. ) {
  278. if ($createElement) {
  279. return $this->createElement(
  280. 'button',
  281. $name,
  282. $label,
  283. $icon,
  284. $style,
  285. $size,
  286. $class,
  287. $attributes
  288. );
  289. }
  290. return $this->addElement(
  291. 'button',
  292. $name,
  293. $label,
  294. $icon,
  295. $style,
  296. $size,
  297. $class,
  298. $attributes
  299. );
  300. }
  301. /**
  302. * Returns a button with the primary color and a check mark
  303. * @param string $label Text appearing on the button
  304. * @param string $name Element name (for form treatment purposes)
  305. * @param bool $createElement Whether to use the create or add method
  306. *
  307. * @return HTML_QuickForm_button
  308. */
  309. public function addButtonSave($label, $name = 'submit', $createElement = false)
  310. {
  311. return $this->addButton(
  312. $name,
  313. $label,
  314. 'check',
  315. 'primary',
  316. null,
  317. null,
  318. array(),
  319. $createElement
  320. );
  321. }
  322. /**
  323. * Returns a cancel button
  324. * @param string $label Text appearing on the button
  325. * @param string $name Element name (for form treatment purposes)
  326. * @param bool $createElement Whether to use the create or add method
  327. *
  328. * @return HTML_QuickForm_button
  329. */
  330. public function addButtonCancel($label, $name = 'submit', $createElement = false)
  331. {
  332. return $this->addButton(
  333. $name,
  334. $label,
  335. 'times',
  336. 'danger',
  337. null,
  338. null,
  339. array(),
  340. $createElement
  341. );
  342. }
  343. /**
  344. * Returns a button with the primary color and a "plus" icon
  345. * @param string $label Text appearing on the button
  346. * @param string $name Element name (for form treatment purposes)
  347. * @param bool $createElement Whether to use the create or add method
  348. * @param array $attributes Additional attributes
  349. *
  350. * @return HTML_QuickForm_button
  351. */
  352. public function addButtonCreate($label, $name = 'submit', $createElement = false, $attributes = array())
  353. {
  354. return $this->addButton(
  355. $name,
  356. $label,
  357. 'plus',
  358. 'primary',
  359. null,
  360. null,
  361. $attributes,
  362. $createElement
  363. );
  364. }
  365. /**
  366. * Returns a button with the primary color and a pencil icon
  367. * @param string $label Text appearing on the button
  368. * @param string $name Element name (for form treatment purposes)
  369. * @param bool $createElement Whether to use the create or add method
  370. * @return HTML_QuickForm_button
  371. */
  372. public function addButtonUpdate($label, $name = 'submit', $createElement = false)
  373. {
  374. return $this->addButton(
  375. $name,
  376. $label,
  377. 'pencil',
  378. 'primary',
  379. null,
  380. null,
  381. array(),
  382. $createElement
  383. );
  384. }
  385. /**
  386. * Returns a button with the danger color and a trash icon
  387. * @param string $label Text appearing on the button
  388. * @param string $name Element name (for form treatment purposes)
  389. * @param bool $createElement Whether to use the create or add method
  390. *
  391. * @return HTML_QuickForm_button
  392. */
  393. public function addButtonDelete($label, $name = 'submit', $createElement = false)
  394. {
  395. return $this->addButton(
  396. $name,
  397. $label,
  398. 'trash',
  399. 'danger',
  400. null,
  401. null,
  402. array(),
  403. $createElement
  404. );
  405. }
  406. /**
  407. * Returns a button with the primary color and a paper-plane icon
  408. * @param string $label Text appearing on the button
  409. * @param string $name Element name (for form treatment purposes)
  410. * @param bool $createElement Whether to use the create or add method
  411. *
  412. * @return HTML_QuickForm_button
  413. */
  414. public function addButtonSend($label, $name = 'submit', $createElement = false, $attributes = array())
  415. {
  416. return $this->addButton(
  417. $name,
  418. $label,
  419. 'paper-plane',
  420. 'primary',
  421. null,
  422. null,
  423. $attributes,
  424. $createElement
  425. );
  426. }
  427. /**
  428. * Returns a button with the default (grey?) color and a magnifier icon
  429. * @param string $label Text appearing on the button
  430. * @param string $name Element name (for form treatment purposes)
  431. *
  432. * @return HTML_QuickForm_button
  433. */
  434. public function addButtonSearch($label = null, $name = 'submit')
  435. {
  436. if (empty($label)) {
  437. $label = get_lang('Search');
  438. }
  439. return $this->addButton($name, $label, 'search', 'default');
  440. }
  441. /**
  442. * Returns a button with the primary color and a right-pointing arrow icon
  443. * @param string $label Text appearing on the button
  444. * @param string $name Element name (for form treatment purposes)
  445. * @param array $attributes Additional attributes
  446. * @return HTML_QuickForm_button
  447. */
  448. public function addButtonNext($label, $name = 'submit', $attributes = array())
  449. {
  450. return $this->addButton($name, $label, 'arrow-right', 'primary', null, null, $attributes);
  451. }
  452. /**
  453. * Returns a button with the primary color and a check mark icon
  454. * @param string $label Text appearing on the button
  455. * @param string $name Element name (for form treatment purposes)
  456. * @param bool $createElement Whether to use the create or add method
  457. * @return HTML_QuickForm_button
  458. */
  459. public function addButtonImport($label, $name = 'submit', $createElement = false)
  460. {
  461. return $this->addButton(
  462. $name,
  463. $label,
  464. 'check',
  465. 'primary',
  466. null,
  467. null,
  468. array(),
  469. $createElement
  470. );
  471. }
  472. /**
  473. * Returns a button with the primary color and a check-mark icon
  474. * @param string $label Text appearing on the button
  475. * @param string $name Element name (for form treatment purposes)
  476. * @param bool $createElement Whether to use the create or add method
  477. * @return HTML_QuickForm_button
  478. */
  479. public function addButtonExport($label, $name = 'submit', $createElement = false)
  480. {
  481. return $this->addButton(
  482. $name,
  483. $label,
  484. 'check',
  485. 'primary',
  486. null,
  487. null,
  488. array(),
  489. $createElement
  490. );
  491. }
  492. /**
  493. * Shortcut to filter button
  494. * @param string $label Text appearing on the button
  495. * @param string $name Element name (for form treatment purposes)
  496. * @param bool $createElement Whether to use the create or add method
  497. * @return HTML_QuickForm_button
  498. */
  499. public function addButtonFilter($label, $name = 'submit', $createElement = false)
  500. {
  501. return $this->addButton(
  502. $name,
  503. $label,
  504. 'filter',
  505. 'primary',
  506. null,
  507. null,
  508. array(),
  509. $createElement
  510. );
  511. }
  512. /**
  513. * Shortcut to reset button
  514. * @param string $label Text appearing on the button
  515. * @param string $name Element name (for form treatment purposes)
  516. * @param bool $createElement Whether to use the create or add method
  517. * @return HTML_QuickForm_button
  518. */
  519. public function addButtonReset($label, $name = 'reset', $createElement = false)
  520. {
  521. $icon = 'eraser';
  522. $style = 'default';
  523. $size = 'default';
  524. $class = null;
  525. $attributes = array();
  526. if ($createElement) {
  527. return $this->createElement(
  528. 'reset',
  529. $name,
  530. $label,
  531. $icon,
  532. $style,
  533. $size,
  534. $class,
  535. $attributes
  536. );
  537. }
  538. return $this->addElement(
  539. 'reset',
  540. $name,
  541. $label,
  542. $icon,
  543. $style,
  544. $size,
  545. $class,
  546. $attributes
  547. );
  548. }
  549. /**
  550. * Returns a button with the primary color and an upload icon
  551. * @param string $label Text appearing on the button
  552. * @param string $name Element name (for form treatment purposes)
  553. * @param bool $createElement Whether to use the create or add method
  554. *
  555. * @return HTML_QuickForm_button
  556. */
  557. public function addButtonUpload($label, $name = 'submit', $createElement = false)
  558. {
  559. return $this->addButton(
  560. $name,
  561. $label,
  562. 'upload',
  563. 'primary',
  564. null,
  565. null,
  566. array(),
  567. $createElement
  568. );
  569. }
  570. /**
  571. * Returns a button with the primary color and a download icon
  572. * @param string $label Text appearing on the button
  573. * @param string $name Element name (for form treatment purposes)
  574. * @param bool $createElement Whether to use the create or add method
  575. *
  576. * @return HTML_QuickForm_button
  577. */
  578. public function addButtonDownload($label, $name = 'submit', $createElement = false)
  579. {
  580. return $this->addButton(
  581. $name,
  582. $label,
  583. 'download',
  584. 'primary',
  585. null,
  586. null,
  587. array(),
  588. $createElement
  589. );
  590. }
  591. /**
  592. * Returns a button with the primary color and a magnifier icon
  593. * @param string $label Text appearing on the button
  594. * @param string $name Element name (for form treatment purposes)
  595. * @param bool $createElement Whether to use the create or add method
  596. *
  597. * @return HTML_QuickForm_button
  598. */
  599. public function addButtonPreview($label, $name = 'submit', $createElement = false)
  600. {
  601. return $this->addButton(
  602. $name,
  603. $label,
  604. 'search',
  605. 'primary',
  606. null,
  607. null,
  608. array(),
  609. $createElement
  610. );
  611. }
  612. /**
  613. * Returns a button with the primary color and a copy (double sheet) icon
  614. * @param string $label Text appearing on the button
  615. * @param string $name Element name (for form treatment purposes)
  616. * @param bool $createElement Whether to use the create or add method
  617. *
  618. * @return HTML_QuickForm_button
  619. */
  620. public function addButtonCopy($label, $name = 'submit', $createElement = false)
  621. {
  622. return $this->addButton(
  623. $name,
  624. $label,
  625. 'copy',
  626. 'primary',
  627. null,
  628. null,
  629. array(),
  630. $createElement
  631. );
  632. }
  633. /**
  634. * @param string $name
  635. * @param string $label
  636. * @param string $text
  637. * @param array $attributes
  638. *
  639. * @return HTML_QuickForm_checkbox
  640. */
  641. public function addCheckBox($name, $label, $text = '', $attributes = array())
  642. {
  643. return $this->addElement('checkbox', $name, $label, $text, $attributes);
  644. }
  645. /**
  646. * @param string $name
  647. * @param string $label
  648. * @param array $options
  649. * @param array $attributes
  650. *
  651. * @return HTML_QuickForm_group
  652. */
  653. public function addCheckBoxGroup($name, $label, $options = array(), $attributes = array())
  654. {
  655. $group = array();
  656. foreach ($options as $value => $text) {
  657. $attributes['value'] = $value;
  658. $group[] = $this->createElement('checkbox', $value, null, $text, $attributes);
  659. }
  660. return $this->addGroup($group, $name, $label);
  661. }
  662. /**
  663. * @param string $name
  664. * @param string $label
  665. * @param array $options
  666. * @param array $attributes
  667. *
  668. * @return HTML_QuickForm_radio
  669. */
  670. public function addRadio($name, $label, $options = array(), $attributes = array())
  671. {
  672. $group = array();
  673. foreach ($options as $key => $value) {
  674. $group[] = $this->createElement('radio', null, null, $value, $key, $attributes);
  675. }
  676. return $this->addGroup($group, $name, $label);
  677. }
  678. /**
  679. * @param string $name
  680. * @param string $label
  681. * @param array $options
  682. * @param array $attributes
  683. *
  684. * @return HTML_QuickForm_select
  685. */
  686. public function addSelect($name, $label, $options = array(), $attributes = array())
  687. {
  688. return $this->addElement('select', $name, $label, $options, $attributes);
  689. }
  690. /**
  691. * @param $name
  692. * @param $label
  693. * @param $collection
  694. * @param array $attributes
  695. * @param bool $addNoneOption
  696. * @param string $textCallable set a function getStringValue() by default __toString()
  697. *
  698. * @return HTML_QuickForm_element
  699. */
  700. public function addSelectFromCollection(
  701. $name,
  702. $label,
  703. $collection,
  704. $attributes = array(),
  705. $addNoneOption = false,
  706. $textCallable = ''
  707. ) {
  708. $options = [];
  709. if ($addNoneOption) {
  710. $options[0] = get_lang('None');
  711. }
  712. if (!empty($collection)) {
  713. foreach ($collection as $item) {
  714. $text = $item;
  715. if (!empty($textCallable)) {
  716. $text = $item->$textCallable();
  717. }
  718. $options[$item->getId()] = $text;
  719. }
  720. }
  721. return $this->addElement('select', $name, $label, $options, $attributes);
  722. }
  723. /**
  724. * @param string $label
  725. * @param string $text
  726. *
  727. * @return HTML_QuickForm_label
  728. */
  729. public function addLabel($label, $text)
  730. {
  731. return $this->addElement('label', $label, $text);
  732. }
  733. /**
  734. * @param string $text
  735. */
  736. public function addHeader($text)
  737. {
  738. $this->addElement('header', $text);
  739. }
  740. /**
  741. * @param string $name
  742. * @param string $label
  743. * @param array $attributes
  744. * @throws Exception if the file doesn't have an id
  745. */
  746. public function addFile($name, $label, $attributes = array())
  747. {
  748. $element = $this->addElement('file', $name, $label, $attributes);
  749. if (isset($attributes['crop_image'])) {
  750. $id = $element->getAttribute('id');
  751. if (empty($id)) {
  752. throw new Exception('If you use the crop functionality the element must have an id');
  753. }
  754. $this->addHtml('
  755. <div class="form-group">
  756. <label for="cropImage" id="'.$id.'_label_crop_image" class="col-sm-2 control-label"></label>
  757. <div class="col-sm-8">
  758. <div id="'.$id.'_crop_image" class="cropCanvas">
  759. <img id="'.$id.'_preview_image">
  760. </div>
  761. <div>
  762. <button class="btn btn-primary hidden" name="cropButton" id="'.$id.'_crop_button" >
  763. <em class="fa fa-crop"></em> '.
  764. get_lang('CropYourPicture').'
  765. </button>
  766. </div>
  767. </div>
  768. </div>'
  769. );
  770. $this->addHidden($id.'_crop_result', '');
  771. }
  772. }
  773. /**
  774. * @param string $snippet
  775. */
  776. public function addHtml($snippet)
  777. {
  778. $this->addElement('html', $snippet);
  779. }
  780. /**
  781. * Adds a HTML-editor to the form
  782. * @param string $name
  783. * @param string $label The label for the form-element
  784. * @param bool $required (optional) Is the form-element required (default=true)
  785. * @param bool $fullPage (optional) When it is true, the editor loads completed html code for a full page.
  786. * @param array $config (optional) Configuration settings for the online editor.
  787. * @param bool $style
  788. */
  789. public function addHtmlEditor($name, $label, $required = true, $fullPage = false, $config = array(), $style = false)
  790. {
  791. $config['rows'] = isset($config['rows']) ? $config['rows'] : 15;
  792. $config['cols'] = isset($config['cols']) ? $config['cols'] : 80;
  793. $this->addElement('html_editor', $name, $label, $config, $style);
  794. $this->applyFilter($name, 'trim');
  795. if ($required) {
  796. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  797. }
  798. /** @var HtmlEditor $element */
  799. $element = $this->getElement($name);
  800. if ($style) {
  801. $config['style'] = true;
  802. }
  803. if ($fullPage) {
  804. $config['fullPage'] = true;
  805. }
  806. if ($element->editor) {
  807. $element->editor->processConfig($config);
  808. }
  809. }
  810. /**
  811. * @param string $name
  812. * @param string $label
  813. *
  814. * @return mixed
  815. */
  816. public function addButtonAdvancedSettings($name, $label = '')
  817. {
  818. $label = !empty($label) ? $label : get_lang('AdvancedParameters');
  819. return $this->addElement('advanced_settings', $name, $label);
  820. }
  821. /**
  822. * Adds a progress loading image to the form.
  823. *
  824. */
  825. public function addProgress($delay = 2, $label = '')
  826. {
  827. if (empty($label)) {
  828. $label = get_lang('PleaseStandBy');
  829. }
  830. $this->with_progress_bar = true;
  831. $id = $this->getAttribute('id');
  832. $this->updateAttributes("onsubmit=\"javascript: addProgress('" . $id . "')\"");
  833. $this->addHtml('<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/upload.js" type="text/javascript"></script>');
  834. }
  835. /**
  836. * This function has been created for avoiding changes directly within QuickForm class.
  837. * When we use it, the element is threated as 'required' to be dealt during validation.
  838. * @param array $element The array of elements
  839. * @param string $message The message displayed
  840. */
  841. public function add_multiple_required_rule($elements, $message)
  842. {
  843. $this->_required[] = $elements[0];
  844. $this->addRule($elements, $message, 'multiple_required');
  845. }
  846. /**
  847. * Displays the form.
  848. * If an element in the form didn't validate, an error message is showed
  849. * asking the user to complete the form.
  850. */
  851. public function display()
  852. {
  853. echo $this->returnForm();
  854. }
  855. /**
  856. * Returns the HTML code of the form.
  857. * @return string $return_value HTML code of the form
  858. */
  859. public function returnForm()
  860. {
  861. $returnValue = '';
  862. /** @var HTML_QuickForm_element $element */
  863. foreach ($this->_elements as $element) {
  864. $elementError = parent::getElementError($element->getName());
  865. if (!is_null($elementError)) {
  866. $returnValue .= Display::return_message($elementError, 'warning').'<br />';
  867. break;
  868. }
  869. }
  870. $returnValue .= parent::toHtml();
  871. // Add div-element which is to hold the progress bar
  872. $id = $this->getAttribute('id');
  873. if (isset($this->with_progress_bar) && $this->with_progress_bar) {
  874. $icon = Display::return_icon('progress_bar.gif');
  875. // @todo improve UI
  876. $returnValue .= '<br />
  877. <div id="loading_div_'.$id.'" class="loading_div" style="display:none;margin-left:40%; margin-top:10px; height:50px;">
  878. '.$icon.'
  879. </div>
  880. ';
  881. }
  882. return $returnValue;
  883. }
  884. /**
  885. * Returns the HTML code of the form.
  886. * If an element in the form didn't validate, an error message is showed
  887. * asking the user to complete the form.
  888. *
  889. * @return string $return_value HTML code of the form
  890. *
  891. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, august 2006
  892. * @author Julio Montoya
  893. * @deprecated use returnForm()
  894. */
  895. public function return_form()
  896. {
  897. return $this->returnForm();
  898. }
  899. /**
  900. * Create a form validator based on an array of form data:
  901. *
  902. * array(
  903. * 'name' => 'zombie_report_parameters', //optional
  904. * 'method' => 'GET', //optional
  905. * 'items' => array(
  906. * array(
  907. * 'name' => 'ceiling',
  908. * 'label' => 'Ceiling', //optional
  909. * 'type' => 'date',
  910. * 'default' => date() //optional
  911. * ),
  912. * array(
  913. * 'name' => 'active_only',
  914. * 'label' => 'ActiveOnly',
  915. * 'type' => 'checkbox',
  916. * 'default' => true
  917. * ),
  918. * array(
  919. * 'name' => 'submit_button',
  920. * 'type' => 'style_submit_button',
  921. * 'value' => get_lang('Search'),
  922. * 'attributes' => array('class' => 'search')
  923. * )
  924. * )
  925. * );
  926. *
  927. * @param array $form_data
  928. * @deprecated use normal FormValidator construct
  929. *
  930. * @return FormValidator
  931. */
  932. public static function create($form_data)
  933. {
  934. if (empty($form_data)) {
  935. return null;
  936. }
  937. $form_name = isset($form_data['name']) ? $form_data['name'] : 'form';
  938. $form_method = isset($form_data['method']) ? $form_data['method'] : 'POST';
  939. $form_action = isset($form_data['action']) ? $form_data['action'] : '';
  940. $form_target = isset($form_data['target']) ? $form_data['target'] : '';
  941. $form_attributes = isset($form_data['attributes']) ? $form_data['attributes'] : null;
  942. $form_track_submit = isset($form_data['track_submit']) ? $form_data['track_submit'] : true;
  943. $reset = null;
  944. $result = new FormValidator($form_name, $form_method, $form_action, $form_target, $form_attributes, $form_track_submit);
  945. $defaults = array();
  946. foreach ($form_data['items'] as $item) {
  947. $name = $item['name'];
  948. $type = isset($item['type']) ? $item['type'] : 'text';
  949. $label = isset($item['label']) ? $item['label'] : '';
  950. if ($type == 'wysiwyg') {
  951. $element = $result->addHtmlEditor($name, $label);
  952. } else {
  953. $element = $result->addElement($type, $name, $label);
  954. }
  955. if (isset($item['attributes'])) {
  956. $attributes = $item['attributes'];
  957. $element->setAttributes($attributes);
  958. }
  959. if (isset($item['value'])) {
  960. $value = $item['value'];
  961. $element->setValue($value);
  962. }
  963. if (isset($item['default'])) {
  964. $defaults[$name] = $item['default'];
  965. }
  966. if (isset($item['rules'])) {
  967. $rules = $item['rules'];
  968. foreach ($rules as $rule) {
  969. $message = $rule['message'];
  970. $type = $rule['type'];
  971. $format = isset($rule['format']) ? $rule['format'] : null;
  972. $validation = isset($rule['validation']) ? $rule['validation'] : 'server';
  973. $force = isset($rule['force']) ? $rule['force'] : false;
  974. $result->addRule($name, $message, $type, $format, $validation, $reset, $force);
  975. }
  976. }
  977. }
  978. $result->setDefaults($defaults);
  979. return $result;
  980. }
  981. /**
  982. * @return HTML_QuickForm_Renderer_Default
  983. */
  984. public static function getDefaultRenderer()
  985. {
  986. return
  987. isset($GLOBALS['_HTML_QuickForm_default_renderer']) ?
  988. $GLOBALS['_HTML_QuickForm_default_renderer'] : null;
  989. }
  990. /**
  991. * Adds a input of type url to the form.
  992. * @param type $name The label for the form-element
  993. * @param type $label The element name
  994. * @param type $required Optional. Is the form-element required (default=true)
  995. * @param type $attributes Optional. List of attributes for the form-element
  996. */
  997. public function addUrl($name, $label, $required = true, $attributes = array())
  998. {
  999. $this->addElement('url', $name, $label, $attributes);
  1000. $this->applyFilter($name, 'trim');
  1001. $this->addRule($name, get_lang('InsertAValidUrl'), 'url');
  1002. if ($required) {
  1003. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1004. }
  1005. }
  1006. /**
  1007. * Adds a text field for letters to the form.
  1008. * A trim-filter is attached to the field.
  1009. * @param string $name The element name
  1010. * @param string $label The label for the form-element
  1011. * @param bool $required Optional. Is the form-element required (default=true)
  1012. * @param array $attributes Optional. List of attributes for the form-element
  1013. */
  1014. public function addTextLettersOnly(
  1015. $name,
  1016. $label,
  1017. $required = false,
  1018. $attributes = []
  1019. ) {
  1020. $attributes = array_merge(
  1021. $attributes,
  1022. [
  1023. 'pattern' => '[a-zA-ZñÑ]+',
  1024. 'title' => get_lang('OnlyLetters')
  1025. ]
  1026. );
  1027. $this->addElement(
  1028. 'text',
  1029. $name,
  1030. [
  1031. $label,
  1032. get_lang('OnlyLetters')
  1033. ],
  1034. $attributes
  1035. );
  1036. $this->applyFilter($name, 'trim');
  1037. if ($required) {
  1038. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1039. }
  1040. $this->addRule(
  1041. $name,
  1042. get_lang('OnlyLetters'),
  1043. 'regex',
  1044. '/^[a-zA-ZñÑ]+$/'
  1045. );
  1046. }
  1047. /**
  1048. * Adds a text field for alphanumeric characters to the form.
  1049. * A trim-filter is attached to the field.
  1050. * @param string $name The element name
  1051. * @param string $label The label for the form-element
  1052. * @param bool $required Optional. Is the form-element required (default=true)
  1053. * @param array $attributes Optional. List of attributes for the form-element
  1054. */
  1055. public function addTextAlphanumeric(
  1056. $name,
  1057. $label,
  1058. $required = false,
  1059. $attributes = []
  1060. ) {
  1061. $attributes = array_merge(
  1062. $attributes,
  1063. [
  1064. 'pattern' => '[a-zA-Z0-9ñÑ]+',
  1065. 'title' => get_lang('OnlyLettersAndNumbers')
  1066. ]
  1067. );
  1068. $this->addElement(
  1069. 'text',
  1070. $name,
  1071. [
  1072. $label,
  1073. get_lang('OnlyLettersAndNumbers')
  1074. ],
  1075. $attributes
  1076. );
  1077. $this->applyFilter($name, 'trim');
  1078. if ($required) {
  1079. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1080. }
  1081. $this->addRule(
  1082. $name,
  1083. get_lang('OnlyLettersAndNumbers'),
  1084. 'regex',
  1085. '/^[a-zA-Z0-9ÑÑ]+$/'
  1086. );
  1087. }
  1088. /**
  1089. * Adds a text field for letters and spaces to the form.
  1090. * A trim-filter is attached to the field.
  1091. * @param string $name The element name
  1092. * @param string $label The label for the form-element
  1093. * @param bool $required Optional. Is the form-element required (default=true)
  1094. * @param array $attributes Optional. List of attributes for the form-element
  1095. */
  1096. public function addTextLettersAndSpaces(
  1097. $name,
  1098. $label,
  1099. $required = false,
  1100. $attributes = []
  1101. ) {
  1102. $attributes = array_merge(
  1103. $attributes,
  1104. [
  1105. 'pattern' => '[a-zA-ZñÑ\s]+',
  1106. 'title' => get_lang('OnlyLettersAndSpaces')
  1107. ]
  1108. );
  1109. $this->addElement(
  1110. 'text',
  1111. $name,
  1112. [
  1113. $label,
  1114. get_lang('OnlyLettersAndSpaces')
  1115. ],
  1116. $attributes
  1117. );
  1118. $this->applyFilter($name, 'trim');
  1119. if ($required) {
  1120. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1121. }
  1122. $this->addRule(
  1123. $name,
  1124. get_lang('OnlyLettersAndSpaces'),
  1125. 'regex',
  1126. '/^[a-zA-ZñÑ\s]+$/'
  1127. );
  1128. }
  1129. /**
  1130. * Adds a text field for alphanumeric and spaces characters to the form.
  1131. * A trim-filter is attached to the field.
  1132. * @param string $name The element name
  1133. * @param string $label The label for the form-element
  1134. * @param bool $required Optional. Is the form-element required (default=true)
  1135. * @param array $attributes Optional. List of attributes for the form-element
  1136. */
  1137. public function addTextAlphanumericAndSpaces(
  1138. $name,
  1139. $label,
  1140. $required = false,
  1141. $attributes = []
  1142. ) {
  1143. $attributes = array_merge(
  1144. $attributes,
  1145. [
  1146. 'pattern' => '[a-zA-Z0-9ñÑ\s]+',
  1147. 'title' => get_lang('OnlyLettersAndNumbersAndSpaces')
  1148. ]
  1149. );
  1150. $this->addElement(
  1151. 'text',
  1152. $name,
  1153. [
  1154. $label,
  1155. get_lang('OnlyLettersAndNumbersAndSpaces')
  1156. ],
  1157. $attributes
  1158. );
  1159. $this->applyFilter($name, 'trim');
  1160. if ($required) {
  1161. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1162. }
  1163. $this->addRule(
  1164. $name,
  1165. get_lang('OnlyLettersAndNumbersAndSpaces'),
  1166. 'regex',
  1167. '/^[a-zA-Z0-9ñÑ\s]+$/'
  1168. );
  1169. }
  1170. /**
  1171. * @param string $url
  1172. */
  1173. public function addMultipleUpload($url)
  1174. {
  1175. $inputName = 'input_file_upload';
  1176. $this->addMultipleUploadJavascript($url, $inputName);
  1177. $this->addHtml('
  1178. <div class="description-upload">'.get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadField').'</div>
  1179. <span class="btn btn-success fileinput-button">
  1180. <i class="glyphicon glyphicon-plus"></i>
  1181. <span>'.get_lang('AddFiles').'</span>
  1182. <!-- The file input field used as target for the file upload widget -->
  1183. <input id="'.$inputName.'" type="file" name="files[]" multiple>
  1184. </span>
  1185. <br />
  1186. <br />
  1187. <div id="dropzone">
  1188. <div class="button-load">
  1189. '.get_lang('UploadFiles').'
  1190. </div>
  1191. </div>
  1192. <br />
  1193. <!-- The global progress bar -->
  1194. <div id="progress" class="progress">
  1195. <div class="progress-bar progress-bar-success"></div>
  1196. </div>
  1197. <div id="files" class="files"></div>
  1198. ');
  1199. }
  1200. /**
  1201. *
  1202. * @param string $url page that will handle the upload
  1203. * @param string $inputName
  1204. */
  1205. private function addMultipleUploadJavascript($url, $inputName)
  1206. {
  1207. $icon = Display::return_icon('file_txt.gif');
  1208. $this->addHtml("
  1209. <script>
  1210. $(function () {
  1211. 'use strict';
  1212. $('#".$this->getAttribute('id')."').submit(function(){
  1213. return false;
  1214. });
  1215. $('#dropzone').on('click', function() {
  1216. $('#".$inputName."').click();
  1217. });
  1218. var url = '".$url."';
  1219. var uploadButton = $('<button/>')
  1220. .addClass('btn btn-primary')
  1221. .prop('disabled', true)
  1222. .text('".addslashes(get_lang('Loading'))."')
  1223. .on('click', function () {
  1224. var \$this = $(this),
  1225. data = \$this.data();
  1226. \$this
  1227. .off('click')
  1228. .text('".addslashes(get_lang('Cancel'))."')
  1229. .on('click', function () {
  1230. \$this.remove();
  1231. data.abort();
  1232. });
  1233. data.submit().always(function () {
  1234. \$this.remove();
  1235. });
  1236. });
  1237. $('#".$inputName."').fileupload({
  1238. url: url,
  1239. dataType: 'json',
  1240. autoUpload: true,
  1241. // Enable image resizing, except for Android and Opera,
  1242. // which actually support image resizing, but fail to
  1243. // send Blob objects via XHR requests:
  1244. disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
  1245. previewMaxWidth: 100,
  1246. previewMaxHeight: 100,
  1247. previewCrop: true,
  1248. dropzone: $('#dropzone')
  1249. }).on('fileuploadadd', function (e, data) {
  1250. data.context = $('<div class=\"row\" style=\"margin-bottom:35px\" />').appendTo('#files');
  1251. $.each(data.files, function (index, file) {
  1252. var node = $('<div class=\"col-sm-5\">').text(file.name);
  1253. node.appendTo(data.context);
  1254. }
  1255. );
  1256. }).on('fileuploadprocessalways', function (e, data) {
  1257. var index = data.index,
  1258. file = data.files[index],
  1259. node = $(data.context.children()[index]);
  1260. if (file.preview) {
  1261. data.context
  1262. .prepend($('<div class=\"col-sm-2\">').html(file.preview))
  1263. ;
  1264. } else {
  1265. data.context
  1266. .prepend($('<div class=\"col-sm-2\">').html('".$icon."'))
  1267. ;
  1268. }
  1269. if (index + 1 === data.files.length) {
  1270. data.context.find('button')
  1271. .text('Upload')
  1272. .prop('disabled', !!data.files.error);
  1273. }
  1274. }).on('fileuploadprogressall', function (e, data) {
  1275. var progress = parseInt(data.loaded / data.total * 100, 10);
  1276. $('#progress .progress-bar').css(
  1277. 'width',
  1278. progress + '%'
  1279. );
  1280. }).on('fileuploaddone', function (e, data) {
  1281. $.each(data.result.files, function (index, file) {
  1282. if (file.url) {
  1283. var link = $('<a>')
  1284. .attr('target', '_blank')
  1285. .prop('href', file.url);
  1286. $(data.context.children()[index]).parent().wrap(link);
  1287. var successMessage = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-success\"/>').text('" . addslashes(get_lang('UplUploadSucceeded')) . "'));
  1288. $(data.context.children()[index]).parent().append(successMessage);
  1289. } else if (file.error) {
  1290. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(file.error));
  1291. $(data.context.children()[index]).parent().append(error);
  1292. }
  1293. });
  1294. }).on('fileuploadfail', function (e, data) {
  1295. $.each(data.files, function (index) {
  1296. var failedMessage = '" . addslashes(get_lang('UplUploadFailed')) . "';
  1297. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(failedMessage));
  1298. $(data.context.children()[index]).parent().append(error);
  1299. });
  1300. }).prop('disabled', !$.support.fileInput)
  1301. .parent().addClass($.support.fileInput ? undefined : 'disabled');
  1302. $('.fileinput-button').hide();
  1303. });
  1304. </script>");
  1305. }
  1306. }
  1307. /**
  1308. * Cleans HTML text filter
  1309. * @param string $html HTML to clean
  1310. * @param int $mode (optional)
  1311. * @return string The cleaned HTML
  1312. */
  1313. function html_filter($html, $mode = NO_HTML)
  1314. {
  1315. $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode);
  1316. //$cleaned_html = kses($html, $allowed_tags);
  1317. return $html;
  1318. return $cleaned_html;
  1319. }
  1320. function html_filter_teacher($html)
  1321. {
  1322. return html_filter($html, TEACHER_HTML);
  1323. }
  1324. function html_filter_student($html)
  1325. {
  1326. return html_filter($html, STUDENT_HTML);
  1327. }
  1328. function html_filter_teacher_fullpage($html)
  1329. {
  1330. return html_filter($html, TEACHER_HTML_FULLPAGE);
  1331. }
  1332. function html_filter_student_fullpage($html)
  1333. {
  1334. return html_filter($html, STUDENT_HTML_FULLPAGE);
  1335. }
  1336. /**
  1337. * Cleans mobile phone number text
  1338. * @param string $mobilePhoneNumber Mobile phone number to clean
  1339. * @return string The cleaned mobile phone number
  1340. */
  1341. function mobile_phone_number_filter($mobilePhoneNumber)
  1342. {
  1343. $mobilePhoneNumber = str_replace(array('+', '(', ')'), '', $mobilePhoneNumber);
  1344. return ltrim($mobilePhoneNumber, '0');
  1345. }