Passed
Push — 1.11.x ( eeca46...b6143c )
by Julito
09:37
created

FormValidator::addNumeric()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 4
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class FormValidator
6
 * create/manipulate/validate user input.
7
 */
8
class FormValidator extends HTML_QuickForm
9
{
10
    const LAYOUT_HORIZONTAL = 'horizontal';
11
    const LAYOUT_INLINE = 'inline';
12
    const LAYOUT_BOX = 'box';
13
    const LAYOUT_BOX_NO_LABEL = 'box-no-label';
14
15
    public $with_progress_bar = false;
16
    private $layout;
17
18
    /**
19
     * Constructor.
20
     *
21
     * @param string $name        Name of the form
22
     * @param string $method      (optional) Method ('post' (default) or 'get')
23
     * @param string $action      (optional) Action (default is $PHP_SELF)
24
     * @param string $target      (optional) Form's target defaults to '_self'
25
     * @param mixed  $attributes  (optional) Extra attributes for <form> tag
26
     * @param string $layout
27
     * @param bool   $trackSubmit (optional) Whether to track if the form was
28
     *                            submitted by adding a special hidden field (default = true)
29
     */
30
    public function __construct(
31
        $name,
32
        $method = 'post',
33
        $action = '',
34
        $target = '',
35
        $attributes = [],
36
        $layout = self::LAYOUT_HORIZONTAL,
37
        $trackSubmit = true
38
    ) {
39
        // Default form class.
40
        if (is_array($attributes) && !isset($attributes['class']) || empty($attributes)) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (is_array($attributes) &...) || empty($attributes), Probably Intended Meaning: is_array($attributes) &&... || empty($attributes))
Loading history...
41
            $attributes['class'] = 'form-horizontal';
42
        }
43
44
        if (isset($attributes['class']) && strpos($attributes['class'], 'form-search') !== false) {
45
            $layout = 'inline';
46
        }
47
48
        $this->setLayout($layout);
49
50
        switch ($layout) {
51
            case self::LAYOUT_HORIZONTAL:
52
                $attributes['class'] = 'form-horizontal';
53
                break;
54
            case self::LAYOUT_INLINE:
55
            case self::LAYOUT_BOX:
56
                $attributes['class'] = 'form-inline';
57
                break;
58
        }
59
60
        parent::__construct($name, $method, $action, $target, $attributes, $trackSubmit);
61
62
        // Modify the default templates
63
        $renderer = &$this->defaultRenderer();
64
65
        // Form template
66
        $formTemplate = $this->getFormTemplate();
67
        $renderer->setFormTemplate($formTemplate);
68
69
        // Element template
70
        if (isset($attributes['class']) && $attributes['class'] == 'form-inline') {
71
            $elementTemplate = ' {label}  {element} ';
72
            $renderer->setElementTemplate($elementTemplate);
73
        } elseif (isset($attributes['class']) && $attributes['class'] == 'form-search') {
74
            $elementTemplate = ' {label}  {element} ';
75
            $renderer->setElementTemplate($elementTemplate);
76
        } else {
77
            $renderer->setElementTemplate($this->getDefaultElementTemplate());
78
79
            // Display a gray div in the buttons
80
            $templateSimple = '<div class="form-actions">{label} {element}</div>';
81
            $renderer->setElementTemplate($templateSimple, 'submit_in_actions');
82
83
            //Display a gray div in the buttons + makes the button available when scrolling
84
            $templateBottom = '<div class="form-actions bottom_actions bg-form">{label} {element}</div>';
85
            $renderer->setElementTemplate($templateBottom, 'submit_fixed_in_bottom');
86
87
            //When you want to group buttons use something like this
88
            /* $group = array();
89
              $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
90
              $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));
91
              $form->addGroup($group, 'buttons_in_action');
92
             */
93
            $renderer->setElementTemplate($templateSimple, 'buttons_in_action');
94
95
            $templateSimpleRight = '<div class="form-actions"> <div class="pull-right">{label} {element}</div></div>';
96
            $renderer->setElementTemplate($templateSimpleRight, 'buttons_in_action_right');
97
        }
98
99
        //Set Header template
100
        $renderer->setHeaderTemplate('<legend>{header}</legend>');
101
102
        //Set required field template
103
        $this->setRequiredNote(
104
            '<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>'
105
        );
106
107
        $noteTemplate = <<<EOT
108
	<div class="form-group">
109
		<div class="col-sm-offset-2 col-sm-10">{requiredNote}</div>
110
	</div>
111
EOT;
112
        $renderer->setRequiredNoteTemplate($noteTemplate);
113
    }
114
115
    /**
116
     * @return string
117
     */
118
    public function getFormTemplate()
119
    {
120
        return '<form{attributes}>
121
        <fieldset>
122
            {content}
123
        </fieldset>
124
        {hidden}
125
        </form>';
126
    }
127
128
    /**
129
     * @todo this function should be added in the element class
130
     *
131
     * @return string
132
     */
133
    public function getDefaultElementTemplate()
134
    {
135
        return '
136
            <div class="form-group {error_class}">
137
                <label {label-for} class="col-sm-2 control-label {extra_label_class}" >
138
                    <!-- BEGIN required --><span class="form_required">*</span><!-- END required -->
139
                    {label}
140
                </label>
141
                <div class="col-sm-8">
142
                    {icon}
143
                    {element}
144
                    <!-- BEGIN label_2 -->
145
                        <p class="help-block">{label_2}</p>
146
                    <!-- END label_2 -->
147
148
                    <!-- BEGIN error -->
149
                        <span class="help-inline help-block">{error}</span>
150
                    <!-- END error -->
151
                </div>
152
                <div class="col-sm-2">
153
                    <!-- BEGIN label_3 -->
154
                        {label_3}
155
                    <!-- END label_3 -->
156
                </div>
157
            </div>';
158
    }
159
160
    /**
161
     * @return string
162
     */
163
    public function getLayout()
164
    {
165
        return $this->layout;
166
    }
167
168
    /**
169
     * @param string $layout
170
     */
171
    public function setLayout($layout)
172
    {
173
        $this->layout = $layout;
174
    }
175
176
    /**
177
     * Adds a text field to the form.
178
     * A trim-filter is attached to the field.
179
     *
180
     * @param string|array $label      The label for the form-element
181
     * @param string       $name       The element name
182
     * @param bool         $required   (optional)    Is the form-element required (default=true)
183
     * @param array        $attributes (optional)    List of attributes for the form-element
184
     *
185
     * @return HTML_QuickForm_text
186
     */
187
    public function addText($name, $label, $required = true, $attributes = [], $createElement = false)
188
    {
189
        if ($createElement) {
190
            $element = $this->createElement('text', $name, $label, $attributes);
191
        } else {
192
            $element = $this->addElement('text', $name, $label, $attributes);
193
        }
194
195
        $this->applyFilter($name, 'trim');
196
        if ($required) {
197
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
198
        }
199
200
        return $element;
201
    }
202
203
    /**
204
     * Add hidden course params.
205
     */
206
    public function addCourseHiddenParams()
207
    {
208
        $this->addHidden('cidReq', api_get_course_id());
209
        $this->addHidden('id_session', api_get_session_id());
210
    }
211
212
    /**
213
     * The "date_range_picker" element creates 2 hidden fields
214
     * "elementName" + "_start"  and "elementName" + "_end"
215
     * For example if the name is "range", you will have 2 new fields
216
     * when executing $form->getSubmitValues()
217
     * "range_start" and "range_end".
218
     *
219
     * @param string $name
220
     * @param string $label
221
     * @param bool   $required
222
     * @param array  $attributes
223
     */
224
    public function addDateRangePicker($name, $label, $required = true, $attributes = [])
225
    {
226
        $this->addElement('date_range_picker', $name, $label, $attributes);
227
        $this->addElement('hidden', $name.'_start');
228
        $this->addElement('hidden', $name.'_end');
229
230
        if ($required) {
231
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
232
        }
233
    }
234
235
    /**
236
     * @param string $name
237
     * @param string $label
238
     * @param array  $attributes
239
     *
240
     * @return mixed
241
     */
242
    public function addDatePicker($name, $label, $attributes = [])
243
    {
244
        return $this->addElement('DatePicker', $name, $label, $attributes);
245
    }
246
247
    /**
248
     * @param string $name
249
     * @param string $label
250
     * @param array  $attributes
251
     *
252
     * @return mixed
253
     */
254
    public function addSelectLanguage($name, $label, $options = [], $attributes = [])
255
    {
256
        return $this->addElement('SelectLanguage', $name, $label, $options, $attributes);
257
    }
258
259
    /**
260
     * @param string $name
261
     * @param string $label
262
     * @param array  $options
263
     * @param array  $attributes
264
     *
265
     * @throws Exception
266
     *
267
     * @return HTML_QuickForm_element
268
     */
269
    public function addSelectAjax($name, $label, $options = [], $attributes = [])
270
    {
271
        if (!isset($attributes['url'])) {
272
            throw new \Exception('select_ajax needs an URL');
273
        }
274
275
        return $this->addElement(
276
            'select_ajax',
277
            $name,
278
            $label,
279
            $options,
280
            $attributes
281
        );
282
    }
283
284
    /**
285
     * @param string       $name
286
     * @param string|array $label
287
     * @param array        $attributes
288
     *
289
     * @return DateTimePicker
290
     */
291
    public function addDateTimePicker($name, $label, $attributes = [])
292
    {
293
        return $this->addElement('DateTimePicker', $name, $label, $attributes);
294
    }
295
296
    /**
297
     * @param string       $name
298
     * @param string|array $label
299
     * @param array        $attributes
300
     *
301
     * @return DateTimeRangePicker
302
     */
303
    public function addDateTimeRangePicker($name, $label, $attributes = [])
304
    {
305
        return $this->addElement('DateTimeRangePicker', $name, $label, $attributes);
306
    }
307
308
    /**
309
     * @param string $name
310
     * @param string $value
311
     * @param array  $attributes
312
     */
313
    public function addHidden($name, $value, $attributes = [])
314
    {
315
        $this->addElement('hidden', $name, $value, $attributes);
316
    }
317
318
    /**
319
     * @param string       $name
320
     * @param string|array $label
321
     * @param array        $attributes
322
     * @param bool         $required
323
     *
324
     * @return HTML_QuickForm_textarea
325
     */
326
    public function addTextarea($name, $label, $attributes = [], $required = false)
327
    {
328
        $element = $this->addElement('textarea', $name, $label, $attributes);
329
330
        if ($required) {
331
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
332
        }
333
334
        return $element;
335
    }
336
337
    /**
338
     * @param string $name
339
     * @param string $label
340
     * @param string $icon          font-awesome
341
     * @param string $style         default|primary|success|info|warning|danger|link
342
     * @param string $size          large|default|small|extra-small
343
     * @param string $class         Example plus is transformed to icon fa fa-plus
344
     * @param array  $attributes
345
     * @param bool   $createElement
346
     *
347
     * @return HTML_QuickForm_button
348
     */
349
    public function addButton(
350
        $name,
351
        $label,
352
        $icon = 'check',
353
        $style = 'default',
354
        $size = 'default',
355
        $class = null,
356
        $attributes = [],
357
        $createElement = false
358
    ) {
359
        if ($createElement) {
360
            return $this->createElement(
361
                'button',
362
                $name,
363
                $label,
364
                $icon,
365
                $style,
366
                $size,
367
                $class,
368
                $attributes
369
            );
370
        }
371
372
        return $this->addElement(
373
            'button',
374
            $name,
375
            $label,
376
            $icon,
377
            $style,
378
            $size,
379
            $class,
380
            $attributes
381
        );
382
    }
383
384
    /**
385
     * Returns a button with the primary color and a check mark.
386
     *
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 addButtonSave($label, $name = 'submit', $createElement = false)
394
    {
395
        return $this->addButton(
396
            $name,
397
            $label,
398
            'check',
399
            'primary',
400
            null,
401
            null,
402
            [],
403
            $createElement
404
        );
405
    }
406
407
    /**
408
     * Returns a cancel button.
409
     *
410
     * @param string $label         Text appearing on the button
411
     * @param string $name          Element name (for form treatment purposes)
412
     * @param bool   $createElement Whether to use the create or add method
413
     *
414
     * @return HTML_QuickForm_button
415
     */
416
    public function addButtonCancel($label, $name = 'submit', $createElement = false)
417
    {
418
        return $this->addButton(
419
            $name,
420
            $label,
421
            'times',
422
            'danger',
423
            null,
424
            null,
425
            [],
426
            $createElement
427
        );
428
    }
429
430
    /**
431
     * Returns a button with the primary color and a "plus" icon.
432
     *
433
     * @param string $label         Text appearing on the button
434
     * @param string $name          Element name (for form treatment purposes)
435
     * @param bool   $createElement Whether to use the create or add method
436
     * @param array  $attributes    Additional attributes
437
     *
438
     * @return HTML_QuickForm_button
439
     */
440
    public function addButtonCreate($label, $name = 'submit', $createElement = false, $attributes = [])
441
    {
442
        return $this->addButton(
443
            $name,
444
            $label,
445
            'plus',
446
            'primary',
447
            null,
448
            null,
449
            $attributes,
450
            $createElement
451
        );
452
    }
453
454
    /**
455
     * Returns a button with the primary color and a pencil icon.
456
     *
457
     * @param string $label         Text appearing on the button
458
     * @param string $name          Element name (for form treatment purposes)
459
     * @param bool   $createElement Whether to use the create or add method
460
     *
461
     * @return HTML_QuickForm_button
462
     */
463
    public function addButtonUpdate($label, $name = 'submit', $createElement = false)
464
    {
465
        return $this->addButton(
466
            $name,
467
            $label,
468
            'pencil',
469
            'primary',
470
            null,
471
            null,
472
            [],
473
            $createElement
474
        );
475
    }
476
477
    /**
478
     * Returns a button with the danger color and a trash icon.
479
     *
480
     * @param string $label         Text appearing on the button
481
     * @param string $name          Element name (for form treatment purposes)
482
     * @param bool   $createElement Whether to use the create or add method
483
     *
484
     * @return HTML_QuickForm_button
485
     */
486
    public function addButtonDelete($label, $name = 'submit', $createElement = false)
487
    {
488
        return $this->addButton(
489
            $name,
490
            $label,
491
            'trash',
492
            'danger',
493
            null,
494
            null,
495
            [],
496
            $createElement
497
        );
498
    }
499
500
    /**
501
     * Returns a move style button.
502
     *
503
     * @param string $label         Text appearing on the button
504
     * @param string $name          Element name (for form treatment purposes)
505
     * @param bool   $createElement Whether to use the create or add method
506
     *
507
     * @return HTML_QuickForm_button
508
     */
509
    public function addButtonMove($label, $name = 'submit', $createElement = false)
510
    {
511
        return $this->addButton(
512
            $name,
513
            $label,
514
            'arrow-circle-right',
515
            'primary',
516
            null,
517
            null,
518
            [],
519
            $createElement
520
        );
521
    }
522
523
    /**
524
     * Returns a button with the primary color and a paper-plane icon.
525
     *
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
     * @param array  $attributes
530
     *
531
     * @return HTML_QuickForm_button
532
     */
533
    public function addButtonSend($label, $name = 'submit', $createElement = false, $attributes = [])
534
    {
535
        return $this->addButton(
536
            $name,
537
            $label,
538
            'paper-plane',
539
            'primary',
540
            null,
541
            null,
542
            $attributes,
543
            $createElement
544
        );
545
    }
546
547
    /**
548
     * Returns a button with the default (grey?) color and a magnifier icon.
549
     *
550
     * @param string $label Text appearing on the button
551
     * @param string $name  Element name (for form treatment purposes)
552
     *
553
     * @return HTML_QuickForm_button
554
     */
555
    public function addButtonSearch($label = null, $name = 'submit')
556
    {
557
        if (empty($label)) {
558
            $label = get_lang('Search');
559
        }
560
561
        return $this->addButton($name, $label, 'search', 'default');
562
    }
563
564
    /**
565
     * Returns a button with the primary color and a right-pointing arrow icon.
566
     *
567
     * @param string $label      Text appearing on the button
568
     * @param string $name       Element name (for form treatment purposes)
569
     * @param array  $attributes Additional attributes
570
     *
571
     * @return HTML_QuickForm_button
572
     */
573
    public function addButtonNext($label, $name = 'submit', $attributes = [])
574
    {
575
        return $this->addButton(
576
            $name,
577
            $label,
578
            'arrow-right',
579
            'primary',
580
            null,
581
            null,
582
            $attributes
583
        );
584
    }
585
586
    /**
587
     * Returns a button with the primary color and a check mark icon.
588
     *
589
     * @param string $label         Text appearing on the button
590
     * @param string $name          Element name (for form treatment purposes)
591
     * @param bool   $createElement Whether to use the create or add method
592
     *
593
     * @return HTML_QuickForm_button
594
     */
595
    public function addButtonImport($label, $name = 'submit', $createElement = false)
596
    {
597
        return $this->addButton(
598
            $name,
599
            $label,
600
            'check',
601
            'primary',
602
            null,
603
            null,
604
            [],
605
            $createElement
606
        );
607
    }
608
609
    /**
610
     * Returns a button with the primary color and a check-mark icon.
611
     *
612
     * @param string $label         Text appearing on the button
613
     * @param string $name          Element name (for form treatment purposes)
614
     * @param bool   $createElement Whether to use the create or add method
615
     *
616
     * @return HTML_QuickForm_button
617
     */
618
    public function addButtonExport($label, $name = 'submit', $createElement = false)
619
    {
620
        return $this->addButton(
621
            $name,
622
            $label,
623
            'check',
624
            'primary',
625
            null,
626
            null,
627
            [],
628
            $createElement
629
        );
630
    }
631
632
    /**
633
     * Shortcut to filter button.
634
     *
635
     * @param string $label         Text appearing on the button
636
     * @param string $name          Element name (for form treatment purposes)
637
     * @param bool   $createElement Whether to use the create or add method
638
     *
639
     * @return HTML_QuickForm_button
640
     */
641
    public function addButtonFilter($label, $name = 'submit', $createElement = false)
642
    {
643
        return $this->addButton(
644
            $name,
645
            $label,
646
            'filter',
647
            'primary',
648
            null,
649
            null,
650
            [],
651
            $createElement
652
        );
653
    }
654
655
    /**
656
     * Shortcut to reset button.
657
     *
658
     * @param string $label         Text appearing on the button
659
     * @param string $name          Element name (for form treatment purposes)
660
     * @param bool   $createElement Whether to use the create or add method
661
     *
662
     * @return HTML_QuickForm_button
663
     */
664
    public function addButtonReset($label, $name = 'reset', $createElement = false)
665
    {
666
        $icon = 'eraser';
667
        $style = 'default';
668
        $size = 'default';
669
        $class = null;
670
        $attributes = [];
671
672
        if ($createElement) {
673
            return $this->createElement(
674
                'reset',
675
                $name,
676
                $label,
677
                $icon,
678
                $style,
679
                $size,
680
                $class,
681
                $attributes
682
            );
683
        }
684
685
        return $this->addElement(
686
            'reset',
687
            $name,
688
            $label,
689
            $icon,
690
            $style,
691
            $size,
692
            $class,
693
            $attributes
694
        );
695
    }
696
697
    /**
698
     * Returns a button with the primary color and an upload icon.
699
     *
700
     * @param string $label         Text appearing on the button
701
     * @param string $name          Element name (for form treatment purposes)
702
     * @param bool   $createElement Whether to use the create or add method
703
     *
704
     * @return HTML_QuickForm_button
705
     */
706
    public function addButtonUpload($label, $name = 'submit', $createElement = false)
707
    {
708
        return $this->addButton(
709
            $name,
710
            $label,
711
            'upload',
712
            'primary',
713
            null,
714
            null,
715
            [],
716
            $createElement
717
        );
718
    }
719
720
    /**
721
     * Returns a button with the primary color and a download icon.
722
     *
723
     * @param string $label         Text appearing on the button
724
     * @param string $name          Element name (for form treatment purposes)
725
     * @param bool   $createElement Whether to use the create or add method
726
     *
727
     * @return HTML_QuickForm_button
728
     */
729
    public function addButtonDownload($label, $name = 'submit', $createElement = false)
730
    {
731
        return $this->addButton(
732
            $name,
733
            $label,
734
            'download',
735
            'primary',
736
            null,
737
            null,
738
            [],
739
            $createElement
740
        );
741
    }
742
743
    /**
744
     * Returns a button with the primary color and a magnifier icon.
745
     *
746
     * @param string $label         Text appearing on the button
747
     * @param string $name          Element name (for form treatment purposes)
748
     * @param bool   $createElement Whether to use the create or add method
749
     *
750
     * @return HTML_QuickForm_button
751
     */
752
    public function addButtonPreview($label, $name = 'submit', $createElement = false)
753
    {
754
        return $this->addButton(
755
            $name,
756
            $label,
757
            'search',
758
            'primary',
759
            null,
760
            null,
761
            [],
762
            $createElement
763
        );
764
    }
765
766
    /**
767
     * Returns a button with the primary color and a copy (double sheet) icon.
768
     *
769
     * @param string $label         Text appearing on the button
770
     * @param string $name          Element name (for form treatment purposes)
771
     * @param bool   $createElement Whether to use the create or add method
772
     *
773
     * @return HTML_QuickForm_button
774
     */
775
    public function addButtonCopy($label, $name = 'submit', $createElement = false)
776
    {
777
        return $this->addButton(
778
            $name,
779
            $label,
780
            'copy',
781
            'primary',
782
            null,
783
            null,
784
            [],
785
            $createElement
786
        );
787
    }
788
789
    /**
790
     * @param string $name
791
     * @param string $label
792
     * @param string $text
793
     * @param array  $attributes
794
     *
795
     * @return HTML_QuickForm_checkbox
796
     */
797
    public function addCheckBox($name, $label, $text = '', $attributes = [])
798
    {
799
        return $this->addElement('checkbox', $name, $label, $text, $attributes);
800
    }
801
802
    /**
803
     * @param string $name
804
     * @param string $label
805
     * @param array  $options
806
     * @param array  $attributes
807
     *
808
     * @return HTML_QuickForm_group
809
     */
810
    public function addCheckBoxGroup($name, $label, $options = [], $attributes = [])
811
    {
812
        $group = [];
813
        foreach ($options as $value => $text) {
814
            $attributes['value'] = $value;
815
            $group[] = $this->createElement(
816
                'checkbox',
817
                $value,
818
                null,
819
                $text,
820
                $attributes
821
            );
822
        }
823
824
        return $this->addGroup($group, $name, $label);
825
    }
826
827
    /**
828
     * @param string $name
829
     * @param string $label
830
     * @param array  $options
831
     * @param array  $attributes
832
     *
833
     * @return HTML_QuickForm_group
834
     */
835
    public function addRadio($name, $label, $options = [], $attributes = [])
836
    {
837
        $group = [];
838
        foreach ($options as $key => $value) {
839
            $group[] = $this->createElement('radio', null, null, $value, $key, $attributes);
840
        }
841
842
        return $this->addGroup($group, $name, $label);
843
    }
844
845
    /**
846
     * @param string $name
847
     * @param string $label
848
     * @param array  $options
849
     * @param array  $attributes
850
     *
851
     * @return HTML_QuickForm_select
852
     */
853
    public function addSelect($name, $label, $options = [], $attributes = [])
854
    {
855
        return $this->addElement('select', $name, $label, $options, $attributes);
856
    }
857
858
    /**
859
     * @param $name
860
     * @param $label
861
     * @param $collection
862
     * @param array  $attributes
863
     * @param bool   $addNoneOption
864
     * @param string $textCallable  set a function getStringValue() by default __toString()
865
     *
866
     * @return HTML_QuickForm_element
867
     */
868
    public function addSelectFromCollection(
869
        $name,
870
        $label,
871
        $collection,
872
        $attributes = [],
873
        $addNoneOption = false,
874
        $textCallable = ''
875
    ) {
876
        $options = [];
877
878
        if ($addNoneOption) {
879
            $options[0] = get_lang('None');
880
        }
881
882
        if (!empty($collection)) {
883
            foreach ($collection as $item) {
884
                $text = $item;
885
                if (!empty($textCallable)) {
886
                    $text = $item->$textCallable();
887
                }
888
                $options[$item->getId()] = $text;
889
            }
890
        }
891
892
        return $this->addElement('select', $name, $label, $options, $attributes);
893
    }
894
895
    /**
896
     * @param string $label
897
     * @param string $text
898
     * @param bool   $createElement
899
     *
900
     * @return HTML_QuickForm_Element
901
     */
902
    public function addLabel($label, $text, $createElement = false)
903
    {
904
        if ($createElement) {
905
            return $this->createElement(
906
                'label',
907
                $label,
908
                $text
909
            );
910
        }
911
912
        return $this->addElement('label', $label, $text);
913
    }
914
915
    /**
916
     * @param string $text
917
     */
918
    public function addHeader($text)
919
    {
920
        if (!empty($text)) {
921
            $this->addElement('header', $text);
922
        }
923
    }
924
925
    /**
926
     * @param string $name
927
     * @param string $label
928
     * @param array  $attributes
929
     *
930
     * @throws Exception if the file doesn't have an id
931
     *
932
     * @return HTML_QuickForm_file
933
     */
934
    public function addFile($name, $label, $attributes = [])
935
    {
936
        $element = $this->addElement('file', $name, $label, $attributes);
937
        if (isset($attributes['crop_image'])) {
938
            $id = $element->getAttribute('id');
939
            if (empty($id)) {
940
                throw new Exception('If you use the crop functionality the element must have an id');
941
            }
942
            $this->addHtml(
943
                '
944
                <div class="form-group" id="'.$id.'-form-group" style="display: none;">
945
                    <div class="col-sm-offset-2 col-sm-8">
946
                        <div id="'.$id.'_crop_image" class="cropCanvas thumbnail">
947
                            <img id="'.$id.'_preview_image">
948
                        </div>
949
                        <button class="btn btn-primary" type="button" name="cropButton" id="'.$id.'_crop_button">
950
                            <em class="fa fa-crop"></em> '.get_lang('CropYourPicture').'
951
                        </button>
952
                    </div>
953
                </div>'
954
            );
955
            $this->addHidden($id.'_crop_result', '');
956
            $this->addHidden($id.'_crop_image_base_64', '');
957
        }
958
959
        return $element;
960
    }
961
962
    /**
963
     * @param string $snippet
964
     */
965
    public function addHtml($snippet)
966
    {
967
        $this->addElement('html', $snippet);
968
    }
969
970
    /**
971
     * Draws a panel of options see the course_info/infocours.php page.
972
     *
973
     * @param string $name      internal name
974
     * @param string $title     visible title
975
     * @param array  $groupList list of group or elements
976
     */
977
    public function addPanelOption($name, $title, $groupList)
978
    {
979
        $this->addHtml('<div class="panel panel-default">');
980
        $this->addHtml(
981
            '
982
            <div class="panel-heading" role="tab" id="heading-'.$name.'-settings">
983
                <h4 class="panel-title">
984
                    <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion"
985
                       href="#collapse-'.$name.'-settings" aria-expanded="false" aria-controls="collapse-'.$name.'-settings">
986
        '
987
        );
988
        $this->addHtml($title);
989
        $this->addHtml('</a></h4></div>');
990
        $this->addHtml('<div id="collapse-'.$name.'-settings" class="panel-collapse collapse" role="tabpanel"
991
             aria-labelledby="heading-'.$name.'-settings">
992
            <div class="panel-body">
993
        ');
994
995
        foreach ($groupList as $groupName => $group) {
996
            // Add group array
997
            if (!empty($groupName) && is_array($group)) {
998
                $this->addGroup($group, '', $groupName);
999
            }
1000
            // Add element
1001
            if ($group instanceof HTML_QuickForm_element) {
1002
                $this->addElement($group);
1003
            }
1004
        }
1005
1006
        $this->addHtml('</div></div>');
1007
        $this->addHtml('</div>');
1008
    }
1009
1010
    /**
1011
     * Adds a HTML-editor to the form.
1012
     *
1013
     * @param string       $name
1014
     * @param string|array $label    The label for the form-element
1015
     * @param bool         $required (optional) Is the form-element required (default=true)
1016
     * @param bool         $fullPage (optional) When it is true, the editor loads completed html code for a full page
1017
     * @param array        $config   (optional) Configuration settings for the online editor
1018
     */
1019
    public function addHtmlEditor(
1020
        $name,
1021
        $label,
1022
        $required = true,
1023
        $fullPage = false,
1024
        $config = []
1025
    ) {
1026
        $attributes = [];
1027
        $attributes['rows'] = isset($config['rows']) ? $config['rows'] : 15;
1028
        $attributes['cols'] = isset($config['cols']) ? $config['cols'] : 80;
1029
        $attributes['cols-size'] = isset($config['cols-size']) ? $config['cols-size'] : [];
1030
        $attributes['class'] = isset($config['class']) ? $config['class'] : [];
1031
        $attributes['id'] = isset($config['id']) ? $config['id'] : '';
1032
1033
        if (empty($attributes['id'])) {
1034
            $attributes['id'] = $name;
1035
        }
1036
1037
        $this->addElement('html_editor', $name, $label, $attributes, $config);
1038
        $this->applyFilter($name, 'trim');
1039
        if ($required) {
1040
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1041
        }
1042
1043
        /** @var HtmlEditor $element */
1044
        $element = $this->getElement($name);
1045
        $config['style'] = isset($config['style']) ? $config['style'] : false;
1046
        if ($fullPage) {
1047
            $config['fullPage'] = true;
1048
            // Adds editor_content.css in ckEditor
1049
            $config['style'] = true;
1050
        }
1051
1052
        if ($element->editor) {
1053
            $element->editor->processConfig($config);
1054
        }
1055
    }
1056
1057
    /**
1058
     * Adds a Google Maps Geolocalization field to the form.
1059
     *
1060
     * @param      $name
1061
     * @param      $label
1062
     * @param bool $hideGeoLocalizationDetails
1063
     */
1064
    public function addGeoLocationMapField($name, $label, $dataValue, $hideGeoLocalizationDetails = false)
1065
    {
1066
        $gMapsPlugin = GoogleMapsPlugin::create();
1067
        $geolocalization = $gMapsPlugin->get('enable_api') === 'true';
1068
1069
        if ($geolocalization && $gMapsPlugin->javascriptIncluded === false) {
1070
            $gmapsApiKey = $gMapsPlugin->get('api_key');
1071
            $url = '//maps.googleapis.com/maps/api/js?key='.$gmapsApiKey;
1072
            $this->addHtml('<script type="text/javascript" src="'.$url.'" ></script>');
1073
            $gMapsPlugin->javascriptIncluded = true;
1074
        }
1075
1076
        $this->addElement(
1077
            'text',
1078
            $name,
1079
            $label,
1080
            ['id' => $name]
1081
        );
1082
1083
        $this->addHidden(
1084
            $name.'_coordinates',
1085
            '',
1086
            ['id' => $name.'_coordinates']
1087
        );
1088
1089
        $this->applyFilter($name, 'stripslashes');
1090
        $this->applyFilter($name, 'trim');
1091
1092
        $this->addHtml(Extrafield::getLocalizationJavascript($name, $dataValue));
1093
1094
        if ($hideGeoLocalizationDetails) {
1095
            $this->addHtml('<div style="display:none">');
1096
        }
1097
1098
        $this->addHtml(
1099
            Extrafield::getLocalizationInput($name, $label)
1100
        );
1101
1102
        if ($hideGeoLocalizationDetails) {
1103
            $this->addHtml('</div>');
1104
        }
1105
    }
1106
1107
    /**
1108
     * @param string $name
1109
     * @param string $label
1110
     *
1111
     * @return mixed
1112
     */
1113
    public function addButtonAdvancedSettings($name, $label = '')
1114
    {
1115
        $label = !empty($label) ? $label : get_lang('AdvancedParameters');
1116
1117
        return $this->addElement('advanced_settings', $name, $label);
1118
    }
1119
1120
    /**
1121
     * Adds a progress loading image to the form.
1122
     */
1123
    public function addProgress($delay = 2, $label = '')
1124
    {
1125
        if (empty($label)) {
1126
            $label = get_lang('PleaseStandBy');
1127
        }
1128
        $this->with_progress_bar = true;
1129
        $id = $this->getAttribute('id');
1130
1131
        $this->updateAttributes("onsubmit=\"javascript: addProgress('".$id."')\"");
1132
        $this->addHtml('<script language="javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/upload.js" type="text/javascript"></script>');
1133
    }
1134
1135
    /**
1136
     * This function has been created for avoiding changes directly within QuickForm class.
1137
     * When we use it, the element is threated as 'required' to be dealt during validation.
1138
     *
1139
     * @param array  $elements The array of elements
1140
     * @param string $message  The message displayed
1141
     */
1142
    public function add_multiple_required_rule($elements, $message)
1143
    {
1144
        $this->_required[] = $elements[0];
0 ignored issues
show
Bug Best Practice introduced by
The property _required does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
1145
        $this->addRule($elements, $message, 'multiple_required');
1146
    }
1147
1148
    /**
1149
     * Displays the form.
1150
     * If an element in the form didn't validate, an error message is showed
1151
     * asking the user to complete the form.
1152
     */
1153
    public function display()
1154
    {
1155
        echo $this->returnForm();
1156
    }
1157
1158
    /**
1159
     * Returns the HTML code of the form.
1160
     *
1161
     * @return string $return_value HTML code of the form
1162
     */
1163
    public function returnForm()
1164
    {
1165
        $returnValue = '';
1166
1167
        /** @var HTML_QuickForm_element $element */
1168
        foreach ($this->_elements as $element) {
1169
            $elementError = parent::getElementError($element->getName());
1170
            if (!is_null($elementError)) {
1171
                $returnValue .= Display::return_message($elementError, 'warning').'<br />';
1172
                break;
1173
            }
1174
        }
1175
1176
        $returnValue .= parent::toHtml();
1177
        // Add div-element which is to hold the progress bar
1178
        $id = $this->getAttribute('id');
1179
        if (isset($this->with_progress_bar) && $this->with_progress_bar) {
1180
            // Deprecated
1181
            // $icon = Display::return_icon('progress_bar.gif');
1182
1183
            // @todo improve UI
1184
            $returnValue .= '<br />
1185
1186
            <div id="loading_div_'.$id.'" class="loading_div" style="display:none;margin-left:40%; margin-top:10px; height:50px;">
1187
                <div class="wobblebar-loader"></div>
1188
            </div>
1189
            ';
1190
        }
1191
1192
        return $returnValue;
1193
    }
1194
1195
    /**
1196
     * Returns the HTML code of the form.
1197
     * If an element in the form didn't validate, an error message is showed
1198
     * asking the user to complete the form.
1199
     *
1200
     * @return string $return_value HTML code of the form
1201
     *
1202
     * @author Patrick Cool <[email protected]>, Ghent University, august 2006
1203
     * @author Julio Montoya
1204
     *
1205
     * @deprecated use returnForm()
1206
     */
1207
    public function return_form()
1208
    {
1209
        return $this->returnForm();
1210
    }
1211
1212
    /**
1213
     * @return HTML_QuickForm_Renderer_Default
1214
     */
1215
    public static function getDefaultRenderer()
1216
    {
1217
        return
1218
            isset($GLOBALS['_HTML_QuickForm_default_renderer']) ?
1219
                $GLOBALS['_HTML_QuickForm_default_renderer'] : null;
1220
    }
1221
1222
    /**
1223
     * Adds a input of type url to the form.
1224
     *
1225
     * @param string $name       The label for the form-element
1226
     * @param string $label      The element name
1227
     * @param bool   $required   Optional. Is the form-element required (default=true)
1228
     * @param array  $attributes Optional. List of attributes for the form-element
1229
     */
1230
    public function addUrl($name, $label, $required = true, $attributes = [])
1231
    {
1232
        $this->addElement('url', $name, $label, $attributes);
1233
        $this->applyFilter($name, 'trim');
1234
        $this->addRule($name, get_lang('InsertAValidUrl'), 'url');
1235
1236
        if ($required) {
1237
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1238
        }
1239
    }
1240
1241
    /**
1242
     * Adds a text field for letters to the form.
1243
     * A trim-filter is attached to the field.
1244
     *
1245
     * @param string $name       The element name
1246
     * @param string $label      The label for the form-element
1247
     * @param bool   $required   Optional. Is the form-element required (default=true)
1248
     * @param array  $attributes Optional. List of attributes for the form-element
1249
     */
1250
    public function addTextLettersOnly(
1251
        $name,
1252
        $label,
1253
        $required = false,
1254
        $attributes = []
1255
    ) {
1256
        $attributes = array_merge(
1257
            $attributes,
1258
            [
1259
                'pattern' => '[a-zA-ZñÑ]+',
1260
                'title' => get_lang('OnlyLetters'),
1261
            ]
1262
        );
1263
1264
        $this->addElement(
1265
            'text',
1266
            $name,
1267
            [
1268
                $label,
1269
                get_lang('OnlyLetters'),
1270
            ],
1271
            $attributes
1272
        );
1273
1274
        $this->applyFilter($name, 'trim');
1275
1276
        if ($required) {
1277
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1278
        }
1279
1280
        $this->addRule(
1281
            $name,
1282
            get_lang('OnlyLetters'),
1283
            'regex',
1284
            '/^[a-zA-ZñÑ]+$/'
1285
        );
1286
    }
1287
1288
    /**
1289
     * @param string      $name
1290
     * @param string      $label
1291
     * @param array $attributes
1292
     * @param bool  $required
1293
     *
1294
     * @return HTML_QuickForm_element
1295
     */
1296
    public function addNumeric($name, $label, $attributes = [], $required = false)
1297
    {
1298
        $element = $this->addElement('Number', $name, $label, $attributes);
1299
1300
        if ($required) {
1301
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1302
        }
1303
1304
        return $element;
1305
    }
1306
1307
    /**
1308
     * Adds a text field for alphanumeric characters to the form.
1309
     * A trim-filter is attached to the field.
1310
     *
1311
     * @param string $name       The element name
1312
     * @param string $label      The label for the form-element
1313
     * @param bool   $required   Optional. Is the form-element required (default=true)
1314
     * @param array  $attributes Optional. List of attributes for the form-element
1315
     */
1316
    public function addTextAlphanumeric(
1317
        $name,
1318
        $label,
1319
        $required = false,
1320
        $attributes = []
1321
    ) {
1322
        $attributes = array_merge(
1323
            $attributes,
1324
            [
1325
                'pattern' => '[a-zA-Z0-9ñÑ]+',
1326
                'title' => get_lang('OnlyLettersAndNumbers'),
1327
            ]
1328
        );
1329
1330
        $this->addElement(
1331
            'text',
1332
            $name,
1333
            [
1334
                $label,
1335
                get_lang('OnlyLettersAndNumbers'),
1336
            ],
1337
            $attributes
1338
        );
1339
1340
        $this->applyFilter($name, 'trim');
1341
1342
        if ($required) {
1343
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1344
        }
1345
1346
        $this->addRule(
1347
            $name,
1348
            get_lang('OnlyLettersAndNumbers'),
1349
            'regex',
1350
            '/^[a-zA-Z0-9ÑÑ]+$/'
1351
        );
1352
    }
1353
1354
    /**
1355
     * @param string $name
1356
     * @param $label
1357
     * @param bool  $required
1358
     * @param array $attributes
1359
     * @param bool  $allowNegative
1360
     * @param int   $minValue
1361
     * @param null  $maxValue
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $maxValue is correct as it would always require null to be passed?
Loading history...
1362
     */
1363
    public function addFloat(
1364
        $name,
1365
        $label,
1366
        $required = false,
1367
        $attributes = [],
1368
        $allowNegative = false,
1369
        $minValue = null,
1370
        $maxValue = null
1371
    ) {
1372
        $this->addElement(
1373
            'FloatNumber',
1374
            $name,
1375
            $label,
1376
            $attributes
1377
        );
1378
1379
        $this->applyFilter($name, 'trim');
1380
1381
        if ($required) {
1382
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1383
        }
1384
1385
        // Rule allows "," and "."
1386
        /*$this->addRule(
1387
            $name,
1388
            get_lang('OnlyNumbers'),
1389
            'regex',
1390
            '/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|(^-?\d\d*\,\d*$)|(^-?\,\d\d*$)/'
1391
        );*/
1392
1393
        if ($allowNegative == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1394
            $this->addRule(
1395
                $name,
1396
                get_lang('NegativeValue'),
1397
                'compare',
1398
                '>=',
1399
                'server',
1400
                false,
1401
                false,
1402
                0
1403
            );
1404
        }
1405
1406
        if (!is_null($minValue)) {
1407
            $this->addRule(
1408
                $name,
1409
                get_lang('UnderMin'),
1410
                'compare',
1411
                '>=',
1412
                'server',
1413
                false,
1414
                false,
1415
                $minValue
1416
            );
1417
        }
1418
1419
        if (!is_null($maxValue)) {
1420
            $this->addRule(
1421
                $name,
1422
                get_lang('OverMax'),
1423
                'compare',
1424
                '<=',
1425
                'server',
1426
                false,
1427
                false,
1428
                $maxValue
1429
            );
1430
        }
1431
    }
1432
1433
    /**
1434
     * Adds a text field for letters and spaces to the form.
1435
     * A trim-filter is attached to the field.
1436
     *
1437
     * @param string $name       The element name
1438
     * @param string $label      The label for the form-element
1439
     * @param bool   $required   Optional. Is the form-element required (default=true)
1440
     * @param array  $attributes Optional. List of attributes for the form-element
1441
     */
1442
    public function addTextLettersAndSpaces(
1443
        $name,
1444
        $label,
1445
        $required = false,
1446
        $attributes = []
1447
    ) {
1448
        $attributes = array_merge(
1449
            $attributes,
1450
            [
1451
                'pattern' => '[a-zA-ZñÑ\s]+',
1452
                'title' => get_lang('OnlyLettersAndSpaces'),
1453
            ]
1454
        );
1455
1456
        $this->addElement(
1457
            'text',
1458
            $name,
1459
            [
1460
                $label,
1461
                get_lang('OnlyLettersAndSpaces'),
1462
            ],
1463
            $attributes
1464
        );
1465
1466
        $this->applyFilter($name, 'trim');
1467
1468
        if ($required) {
1469
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1470
        }
1471
1472
        $this->addRule(
1473
            $name,
1474
            get_lang('OnlyLettersAndSpaces'),
1475
            'regex',
1476
            '/^[a-zA-ZñÑ\s]+$/'
1477
        );
1478
    }
1479
1480
    /**
1481
     * Adds a text field for alphanumeric and spaces characters to the form.
1482
     * A trim-filter is attached to the field.
1483
     *
1484
     * @param string $name       The element name
1485
     * @param string $label      The label for the form-element
1486
     * @param bool   $required   Optional. Is the form-element required (default=true)
1487
     * @param array  $attributes Optional. List of attributes for the form-element
1488
     */
1489
    public function addTextAlphanumericAndSpaces(
1490
        $name,
1491
        $label,
1492
        $required = false,
1493
        $attributes = []
1494
    ) {
1495
        $attributes = array_merge(
1496
            $attributes,
1497
            [
1498
                'pattern' => '[a-zA-Z0-9ñÑ\s]+',
1499
                'title' => get_lang('OnlyLettersAndNumbersAndSpaces'),
1500
            ]
1501
        );
1502
1503
        $this->addElement(
1504
            'text',
1505
            $name,
1506
            [
1507
                $label,
1508
                get_lang('OnlyLettersAndNumbersAndSpaces'),
1509
            ],
1510
            $attributes
1511
        );
1512
1513
        $this->applyFilter($name, 'trim');
1514
1515
        if ($required) {
1516
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1517
        }
1518
1519
        $this->addRule(
1520
            $name,
1521
            get_lang('OnlyLettersAndNumbersAndSpaces'),
1522
            'regex',
1523
            '/^[a-zA-Z0-9ñÑ\s]+$/'
1524
        );
1525
    }
1526
1527
    /**
1528
     * @param string $url
1529
     * @param string $urlToRedirect after upload redirect to this page
1530
     */
1531
    public function addMultipleUpload($url, $urlToRedirect = '')
1532
    {
1533
        $inputName = 'input_file_upload';
1534
        $this->addMultipleUploadJavascript($url, $inputName, $urlToRedirect);
1535
1536
        $this->addHtml('
1537
            <div class="description-upload">
1538
            '.get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadField').'
1539
            </div>
1540
            <span class="btn btn-success fileinput-button">
1541
                <i class="glyphicon glyphicon-plus"></i>
1542
                <span>'.get_lang('AddFiles').'</span>
1543
                <!-- The file input field used as target for the file upload widget -->
1544
                <input id="'.$inputName.'" type="file" name="files[]" multiple>
1545
            </span>
1546
            <div id="dropzone">
1547
                <div class="button-load">
1548
                '.get_lang('UploadFiles').'
1549
                </div>
1550
            </div>
1551
            <br />
1552
            <!-- The global progress bar -->
1553
            <div id="progress" class="progress">
1554
                <div class="progress-bar progress-bar-success"></div>
1555
            </div>
1556
            <div id="files" class="files"></div>
1557
        ');
1558
    }
1559
1560
    /**
1561
     * @param string $elementName
1562
     * @param string $groupName   if element is inside a group
1563
     *
1564
     * @throws Exception
1565
     */
1566
    public function addPasswordRule($elementName, $groupName = '')
1567
    {
1568
        // Constant defined in old config/profile.conf.php
1569
        if (CHECK_PASS_EASY_TO_FIND === true) {
0 ignored issues
show
Bug introduced by
The constant CHECK_PASS_EASY_TO_FIND was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1570
            $message = get_lang('PassTooEasy').': '.api_generate_password();
1571
1572
            if (!empty($groupName)) {
1573
                $groupObj = $this->getElement($groupName);
1574
1575
                if ($groupObj instanceof HTML_QuickForm_group) {
1576
                    $elementName = $groupObj->getElementName($elementName);
1577
1578
                    if ($elementName === false) {
1579
                        throw new Exception("The $groupName doesn't have the element $elementName");
1580
                    }
1581
1582
                    $this->_rules[$elementName][] = [
0 ignored issues
show
Bug Best Practice introduced by
The property _rules does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
1583
                        'type' => 'callback',
1584
                        'format' => 'api_check_password',
1585
                        'message' => $message,
1586
                        'validation' => '',
1587
                        'reset' => false,
1588
                        'group' => $groupName,
1589
                    ];
1590
                }
1591
            } else {
1592
                $this->addRule(
1593
                    $elementName,
1594
                    $message,
1595
                    'callback',
1596
                    'api_check_password'
1597
                );
1598
            }
1599
        }
1600
    }
1601
1602
    /**
1603
     * Add an element with user ID and avatar to the form.
1604
     * It needs a Chamilo\UserBundle\Entity\User as value. The exported value is the Chamilo\UserBundle\Entity\User ID.
1605
     *
1606
     * @see \UserAvatar
1607
     *
1608
     * @param string $name
1609
     * @param string $label
1610
     * @param string $imageSize Optional. Small, medium or large image
1611
     * @param string $subtitle  Optional. The subtitle for the field
1612
     *
1613
     * @return \UserAvatar
1614
     */
1615
    public function addUserAvatar($name, $label, $imageSize = 'small', $subtitle = '')
1616
    {
1617
        return $this->addElement('UserAvatar', $name, $label, ['image_size' => $imageSize, 'sub_title' => $subtitle]);
1618
    }
1619
1620
    /**
1621
     * @param array $typeList
1622
     */
1623
    public function addEmailTemplate($typeList)
1624
    {
1625
        $mailManager = new MailTemplateManager();
1626
        foreach ($typeList as $type) {
1627
            $list = $mailManager->get_all(
1628
                ['where' => ['type = ? AND url_id = ?' => [$type, api_get_current_access_url_id()]]]
1629
            );
1630
1631
            $options = [get_lang('Select')];
1632
            $name = $type;
1633
            $defaultId = '';
1634
            foreach ($list as $item) {
1635
                $options[$item['id']] = $item['name'];
1636
                $name = $item['name'];
1637
                if (empty($defaultId)) {
1638
                    $defaultId = $item['default_template'] == 1 ? $item['id'] : '';
1639
                }
1640
            }
1641
1642
            $url = api_get_path(WEB_AJAX_PATH).'mail.ajax.php?a=select_option';
1643
            $typeNoDots = 'email_template_option_'.str_replace('.tpl', '', $type);
1644
            $this->addSelect(
1645
                'email_template_option['.$type.']',
1646
                $name,
1647
                $options,
1648
                ['id' => $typeNoDots]
1649
            );
1650
1651
            $templateNoDots = 'email_template_'.str_replace('.tpl', '', $type);
1652
            $templateNoDotsBlock = 'email_template_block_'.str_replace('.tpl', '', $type);
1653
            $this->addHtml('<div id="'.$templateNoDotsBlock.'" style="display:none">');
1654
            $this->addTextarea(
1655
                $templateNoDots,
1656
                get_lang('Preview'),
1657
                ['disabled' => 'disabled ', 'id' => $templateNoDots, 'rows' => '5']
1658
            );
1659
            $this->addHtml('</div>');
1660
1661
            $this->addHtml("<script>
1662
            $(function() {
1663
                var defaultValue = '$defaultId';
1664
                $('#$typeNoDots').val(defaultValue);
1665
                $('#$typeNoDots').selectpicker('render');
1666
                if (defaultValue != '') {
1667
                    var selected = $('#$typeNoDots option:selected').val();
1668
                    $.ajax({
1669
                        url: '$url' + '&id=' + selected+ '&template_name=$type',
1670
                        success: function (data) {
1671
                            $('#$templateNoDots').html(data);
1672
                            $('#$templateNoDotsBlock').show();
1673
                            return;
1674
                        },
1675
                    });
1676
                }
1677
1678
                $('#$typeNoDots').on('change', function(){
1679
                    var selected = $('#$typeNoDots option:selected').val();
1680
                    $.ajax({
1681
                        url: '$url' + '&id=' + selected,
1682
                        success: function (data) {
1683
                            $('#$templateNoDots').html(data);
1684
                            $('#$templateNoDotsBlock').show();
1685
                            return;
1686
                        },
1687
                    });
1688
                });
1689
            });
1690
            </script>");
1691
        }
1692
    }
1693
1694
    /**
1695
     * @param string $url           page that will handle the upload
1696
     * @param string $inputName
1697
     * @param string $urlToRedirect
1698
     */
1699
    private function addMultipleUploadJavascript($url, $inputName, $urlToRedirect = '')
1700
    {
1701
        $redirectCondition = '';
1702
        if (!empty($urlToRedirect)) {
1703
            $redirectCondition = "window.location.replace('$urlToRedirect'); ";
1704
        }
1705
        $icon = Display::return_icon('file_txt.gif');
1706
        $this->addHtml("
1707
        <script>
1708
        $(function () {
1709
            'use strict';
1710
            $('#".$this->getAttribute('id')."').submit(function() {
1711
                return false;
1712
            });
1713
1714
            $('#dropzone').on('click', function() {
1715
                $('#".$inputName."').click();
1716
            });
1717
1718
            var url = '".$url."';
1719
            var uploadButton = $('<button/>')
1720
                .addClass('btn btn-primary')
1721
                .prop('disabled', true)
1722
                .text('".addslashes(get_lang('Loading'))."')
1723
                .on('click', function () {
1724
                    var \$this = $(this),
1725
                    data = \$this.data();
1726
                    \$this
1727
                        .off('click')
1728
                        .text('".addslashes(get_lang('Cancel'))."')
1729
                        .on('click', function () {
1730
                            \$this.remove();
1731
                            data.abort();
1732
                        });
1733
                    data.submit().always(function () {
1734
                        \$this.remove();
1735
                    });
1736
                });
1737
1738
            $('#".$inputName."').fileupload({
1739
                url: url,
1740
                dataType: 'json',
1741
                // Enable image resizing, except for Android and Opera,
1742
                // which actually support image resizing, but fail to
1743
                // send Blob objects via XHR requests:
1744
                disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
1745
                previewMaxWidth: 300,
1746
                previewMaxHeight: 169,
1747
                previewCrop: true,
1748
                dropzone: $('#dropzone'),
1749
            }).on('fileuploadadd', function (e, data) {
1750
                data.context = $('<div class=\"row\" />').appendTo('#files');
1751
                $.each(data.files, function (index, file) {
1752
                    var node = $('<div class=\"col-sm-5 file_name\">').text(file.name);
1753
                    node.appendTo(data.context);
1754
                });
1755
            }).on('fileuploadprocessalways', function (e, data) {
1756
                var index = data.index,
1757
                    file = data.files[index],
1758
                    node = $(data.context.children()[index]);
1759
                if (file.preview) {
1760
                    data.context.prepend($('<div class=\"col-sm-4\">').html(file.preview));
1761
                } else {
1762
                    data.context.prepend($('<div class=\"col-sm-4\">').html('".$icon."'));
1763
                }
1764
                if (index + 1 === data.files.length) {
1765
                    data.context.find('button')
1766
                        .text('Upload')
1767
                        .prop('disabled', !!data.files.error);
1768
                }
1769
            }).on('fileuploadprogressall', function (e, data) {
1770
                var progress = parseInt(data.loaded / data.total * 100, 10);
1771
                $('#progress .progress-bar').css(
1772
                    'width',
1773
                    progress + '%'
1774
                );
1775
            }).on('fileuploaddone', function (e, data) {
1776
                $.each(data.result.files, function (index, file) {
1777
                    if (file.error) {
1778
                        var link = $('<div>')
1779
                            .attr({class : 'panel-image'})                            ;
1780
                        $(data.context.children()[index]).parent().wrap(link);
1781
                        // Update file name with new one from Chamilo
1782
                        $(data.context.children()[index]).parent().find('.file_name').html(file.name);
1783
                        var message = $('<div class=\"col-sm-3\">').html(
1784
                            $('<span class=\"message-image-danger\"/>').text(file.error)
1785
                        );
1786
                        $(data.context.children()[index]).parent().append(message);
1787
1788
                        return;
1789
                    }
1790
                    if (file.url) {
1791
                        var link = $('<a>')
1792
                            .attr({target: '_blank', class : 'panel-image'})
1793
                            .prop('href', file.url);
1794
                        $(data.context.children()[index]).parent().wrap(link);
1795
                    }
1796
                    // Update file name with new one from Chamilo
1797
                    $(data.context.children()[index]).parent().find('.file_name').html(file.name);
1798
                    var message = $('<div class=\"col-sm-3\">').html(
1799
                        $('<span class=\"message-image-success\"/>').text('".addslashes(get_lang('UplUploadSucceeded'))."')
1800
                    );
1801
                    $(data.context.children()[index]).parent().append(message);
1802
                });
1803
                $('#dropzone').removeClass('hover');
1804
                ".$redirectCondition."
1805
            }).on('fileuploadfail', function (e, data) {
1806
                $.each(data.files, function (index) {
1807
                    var failedMessage = '".addslashes(get_lang('UplUploadFailed'))."';
1808
                    var error = $('<div class=\"col-sm-3\">').html(
1809
                        $('<span class=\"alert alert-danger\"/>').text(failedMessage)
1810
                    );
1811
                    $(data.context.children()[index]).parent().append(error);
1812
                });
1813
                $('#dropzone').removeClass('hover');
1814
            }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
1815
1816
            $('#dropzone').on('dragover', function (e) {
1817
                // dragleave callback implementation
1818
                $('#dropzone').addClass('hover');
1819
            });
1820
1821
            $('#dropzone').on('dragleave', function (e) {
1822
                $('#dropzone').removeClass('hover');
1823
            });
1824
            $('.fileinput-button').hide();
1825
        });
1826
        </script>");
1827
    }
1828
}
1829
1830
/**
1831
 * Cleans HTML text filter.
1832
 *
1833
 * @param string $html HTML to clean
1834
 * @param int    $mode (optional)
1835
 *
1836
 * @return string The cleaned HTML
1837
 */
1838
function html_filter($html, $mode = NO_HTML)
1839
{
1840
    $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode);
1841
    $cleaned_html = kses($html, $allowed_tags);
0 ignored issues
show
Bug introduced by
The function kses was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1841
    $cleaned_html = /** @scrutinizer ignore-call */ kses($html, $allowed_tags);
Loading history...
1842
1843
    return $cleaned_html;
1844
}
1845
1846
function html_filter_teacher($html)
1847
{
1848
    return html_filter($html, TEACHER_HTML);
1849
}
1850
1851
function html_filter_student($html)
1852
{
1853
    return html_filter($html, STUDENT_HTML);
1854
}
1855
1856
function html_filter_teacher_fullpage($html)
1857
{
1858
    return html_filter($html, TEACHER_HTML_FULLPAGE);
1859
}
1860
1861
function html_filter_student_fullpage($html)
1862
{
1863
    return html_filter($html, STUDENT_HTML_FULLPAGE);
1864
}
1865
1866
/**
1867
 * Cleans mobile phone number text.
1868
 *
1869
 * @param string $mobilePhoneNumber Mobile phone number to clean
1870
 *
1871
 * @return string The cleaned mobile phone number
1872
 */
1873
function mobile_phone_number_filter($mobilePhoneNumber)
1874
{
1875
    $mobilePhoneNumber = str_replace(['+', '(', ')'], '', $mobilePhoneNumber);
1876
1877
    return ltrim($mobilePhoneNumber, '0');
1878
}
1879