Passed
Push — preprodparkur ( dfc2a7...433504 )
by Angel Fernando Quiroz
16:29 queued 04:24
created

FormValidator::addButton()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 19
c 1
b 0
f 0
nc 2
nop 8
dl 0
loc 32
rs 9.6333

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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
266
     */
267
    public function addSelectAjax($name, $label, $options = [], $attributes = [])
268
    {
269
        if (!isset($attributes['url'])) {
270
            throw new \Exception('select_ajax needs an URL');
271
        }
272
        $this->addElement(
273
            'select_ajax',
274
            $name,
275
            $label,
276
            $options,
277
            $attributes
278
        );
279
    }
280
281
    /**
282
     * @param string       $name
283
     * @param string|array $label
284
     * @param array        $attributes
285
     *
286
     * @return DateTimePicker
287
     */
288
    public function addDateTimePicker($name, $label, $attributes = [])
289
    {
290
        return $this->addElement('DateTimePicker', $name, $label, $attributes);
291
    }
292
293
    /**
294
     * @param string       $name
295
     * @param string|array $label
296
     * @param array        $attributes
297
     *
298
     * @return DateTimeRangePicker
299
     */
300
    public function addDateTimeRangePicker($name, $label, $attributes = [])
301
    {
302
        return $this->addElement('DateTimeRangePicker', $name, $label, $attributes);
303
    }
304
305
    /**
306
     * @param string $name
307
     * @param string $value
308
     * @param array  $attributes
309
     */
310
    public function addHidden($name, $value, $attributes = [])
311
    {
312
        $this->addElement('hidden', $name, $value, $attributes);
313
    }
314
315
    /**
316
     * @param string       $name
317
     * @param string|array $label
318
     * @param array        $attributes
319
     * @param bool         $required
320
     *
321
     * @return HTML_QuickForm_textarea
322
     */
323
    public function addTextarea($name, $label, $attributes = [], $required = false)
324
    {
325
        $element = $this->addElement('textarea', $name, $label, $attributes);
326
327
        if ($required) {
328
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
329
        }
330
331
        return $element;
332
    }
333
334
    /**
335
     * @param string $name
336
     * @param string $label
337
     * @param string $icon          font-awesome
338
     * @param string $style         default|primary|success|info|warning|danger|link
339
     * @param string $size          large|default|small|extra-small
340
     * @param string $class         Example plus is transformed to icon fa fa-plus
341
     * @param array  $attributes
342
     * @param bool   $createElement
343
     *
344
     * @return HTML_QuickForm_button
345
     */
346
    public function addButton(
347
        $name,
348
        $label,
349
        $icon = 'check',
350
        $style = 'default',
351
        $size = 'default',
352
        $class = null,
353
        $attributes = [],
354
        $createElement = false
355
    ) {
356
        if ($createElement) {
357
            return $this->createElement(
358
                'button',
359
                $name,
360
                $label,
361
                $icon,
362
                $style,
363
                $size,
364
                $class,
365
                $attributes
366
            );
367
        }
368
369
        return $this->addElement(
370
            'button',
371
            $name,
372
            $label,
373
            $icon,
374
            $style,
375
            $size,
376
            $class,
377
            $attributes
378
        );
379
    }
380
381
    /**
382
     * Returns a button with the primary color and a check mark.
383
     *
384
     * @param string $label         Text appearing on the button
385
     * @param string $name          Element name (for form treatment purposes)
386
     * @param bool   $createElement Whether to use the create or add method
387
     *
388
     * @return HTML_QuickForm_button
389
     */
390
    public function addButtonSave($label, $name = 'submit', $createElement = false)
391
    {
392
        return $this->addButton(
393
            $name,
394
            $label,
395
            'check',
396
            'primary',
397
            null,
398
            null,
399
            [],
400
            $createElement
401
        );
402
    }
403
404
    /**
405
     * Returns a cancel button.
406
     *
407
     * @param string $label         Text appearing on the button
408
     * @param string $name          Element name (for form treatment purposes)
409
     * @param bool   $createElement Whether to use the create or add method
410
     *
411
     * @return HTML_QuickForm_button
412
     */
413
    public function addButtonCancel($label, $name = 'submit', $createElement = false)
414
    {
415
        return $this->addButton(
416
            $name,
417
            $label,
418
            'times',
419
            'danger',
420
            null,
421
            null,
422
            [],
423
            $createElement
424
        );
425
    }
426
427
    /**
428
     * Returns a button with the primary color and a "plus" icon.
429
     *
430
     * @param string $label         Text appearing on the button
431
     * @param string $name          Element name (for form treatment purposes)
432
     * @param bool   $createElement Whether to use the create or add method
433
     * @param array  $attributes    Additional attributes
434
     *
435
     * @return HTML_QuickForm_button
436
     */
437
    public function addButtonCreate($label, $name = 'submit', $createElement = false, $attributes = [])
438
    {
439
        return $this->addButton(
440
            $name,
441
            $label,
442
            'plus',
443
            'primary',
444
            null,
445
            null,
446
            $attributes,
447
            $createElement
448
        );
449
    }
450
451
    /**
452
     * Returns a button with the primary color and a pencil icon.
453
     *
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
     *
458
     * @return HTML_QuickForm_button
459
     */
460
    public function addButtonUpdate($label, $name = 'submit', $createElement = false)
461
    {
462
        return $this->addButton(
463
            $name,
464
            $label,
465
            'pencil',
466
            'primary',
467
            null,
468
            null,
469
            [],
470
            $createElement
471
        );
472
    }
473
474
    /**
475
     * Returns a button with the danger color and a trash icon.
476
     *
477
     * @param string $label         Text appearing on the button
478
     * @param string $name          Element name (for form treatment purposes)
479
     * @param bool   $createElement Whether to use the create or add method
480
     *
481
     * @return HTML_QuickForm_button
482
     */
483
    public function addButtonDelete($label, $name = 'submit', $createElement = false)
484
    {
485
        return $this->addButton(
486
            $name,
487
            $label,
488
            'trash',
489
            'danger',
490
            null,
491
            null,
492
            [],
493
            $createElement
494
        );
495
    }
496
497
    /**
498
     * Returns a move style button.
499
     *
500
     * @param string $label         Text appearing on the button
501
     * @param string $name          Element name (for form treatment purposes)
502
     * @param bool   $createElement Whether to use the create or add method
503
     *
504
     * @return HTML_QuickForm_button
505
     */
506
    public function addButtonMove($label, $name = 'submit', $createElement = false)
507
    {
508
        return $this->addButton(
509
            $name,
510
            $label,
511
            'arrow-circle-right',
512
            'primary',
513
            null,
514
            null,
515
            [],
516
            $createElement
517
        );
518
    }
519
520
    /**
521
     * Returns a button with the primary color and a paper-plane icon.
522
     *
523
     * @param string $label         Text appearing on the button
524
     * @param string $name          Element name (for form treatment purposes)
525
     * @param bool   $createElement Whether to use the create or add method
526
     * @param array  $attributes
527
     *
528
     * @return HTML_QuickForm_button
529
     */
530
    public function addButtonSend($label, $name = 'submit', $createElement = false, $attributes = [])
531
    {
532
        return $this->addButton(
533
            $name,
534
            $label,
535
            'paper-plane',
536
            'primary',
537
            null,
538
            null,
539
            $attributes,
540
            $createElement
541
        );
542
    }
543
544
    /**
545
     * Returns a button with the default (grey?) color and a magnifier icon.
546
     *
547
     * @param string $label Text appearing on the button
548
     * @param string $name  Element name (for form treatment purposes)
549
     *
550
     * @return HTML_QuickForm_button
551
     */
552
    public function addButtonSearch($label = null, $name = 'submit')
553
    {
554
        if (empty($label)) {
555
            $label = get_lang('Search');
556
        }
557
558
        return $this->addButton($name, $label, 'search', 'default');
559
    }
560
561
    /**
562
     * Returns a button with the primary color and a right-pointing arrow icon.
563
     *
564
     * @param string $label      Text appearing on the button
565
     * @param string $name       Element name (for form treatment purposes)
566
     * @param array  $attributes Additional attributes
567
     *
568
     * @return HTML_QuickForm_button
569
     */
570
    public function addButtonNext($label, $name = 'submit', $attributes = [])
571
    {
572
        return $this->addButton(
573
            $name,
574
            $label,
575
            'arrow-right',
576
            'primary',
577
            null,
578
            null,
579
            $attributes
580
        );
581
    }
582
583
    /**
584
     * Returns a button with the primary color and a check mark icon.
585
     *
586
     * @param string $label         Text appearing on the button
587
     * @param string $name          Element name (for form treatment purposes)
588
     * @param bool   $createElement Whether to use the create or add method
589
     *
590
     * @return HTML_QuickForm_button
591
     */
592
    public function addButtonImport($label, $name = 'submit', $createElement = false)
593
    {
594
        return $this->addButton(
595
            $name,
596
            $label,
597
            'check',
598
            'primary',
599
            null,
600
            null,
601
            [],
602
            $createElement
603
        );
604
    }
605
606
    /**
607
     * Returns a button with the primary color and a check-mark icon.
608
     *
609
     * @param string $label         Text appearing on the button
610
     * @param string $name          Element name (for form treatment purposes)
611
     * @param bool   $createElement Whether to use the create or add method
612
     *
613
     * @return HTML_QuickForm_button
614
     */
615
    public function addButtonExport($label, $name = 'submit', $createElement = false)
616
    {
617
        return $this->addButton(
618
            $name,
619
            $label,
620
            'check',
621
            'primary',
622
            null,
623
            null,
624
            [],
625
            $createElement
626
        );
627
    }
628
629
    /**
630
     * Shortcut to filter button.
631
     *
632
     * @param string $label         Text appearing on the button
633
     * @param string $name          Element name (for form treatment purposes)
634
     * @param bool   $createElement Whether to use the create or add method
635
     *
636
     * @return HTML_QuickForm_button
637
     */
638
    public function addButtonFilter($label, $name = 'submit', $createElement = false)
639
    {
640
        return $this->addButton(
641
            $name,
642
            $label,
643
            'filter',
644
            'primary',
645
            null,
646
            null,
647
            [],
648
            $createElement
649
        );
650
    }
651
652
    /**
653
     * Shortcut to reset button.
654
     *
655
     * @param string $label         Text appearing on the button
656
     * @param string $name          Element name (for form treatment purposes)
657
     * @param bool   $createElement Whether to use the create or add method
658
     *
659
     * @return HTML_QuickForm_button
660
     */
661
    public function addButtonReset($label, $name = 'reset', $createElement = false)
662
    {
663
        $icon = 'eraser';
664
        $style = 'default';
665
        $size = 'default';
666
        $class = null;
667
        $attributes = [];
668
669
        if ($createElement) {
670
            return $this->createElement(
671
                'reset',
672
                $name,
673
                $label,
674
                $icon,
675
                $style,
676
                $size,
677
                $class,
678
                $attributes
679
            );
680
        }
681
682
        return $this->addElement(
683
            'reset',
684
            $name,
685
            $label,
686
            $icon,
687
            $style,
688
            $size,
689
            $class,
690
            $attributes
691
        );
692
    }
693
694
    /**
695
     * Returns a button with the primary color and an upload icon.
696
     *
697
     * @param string $label         Text appearing on the button
698
     * @param string $name          Element name (for form treatment purposes)
699
     * @param bool   $createElement Whether to use the create or add method
700
     *
701
     * @return HTML_QuickForm_button
702
     */
703
    public function addButtonUpload($label, $name = 'submit', $createElement = false)
704
    {
705
        return $this->addButton(
706
            $name,
707
            $label,
708
            'upload',
709
            'primary',
710
            null,
711
            null,
712
            [],
713
            $createElement
714
        );
715
    }
716
717
    /**
718
     * Returns a button with the primary color and a download icon.
719
     *
720
     * @param string $label         Text appearing on the button
721
     * @param string $name          Element name (for form treatment purposes)
722
     * @param bool   $createElement Whether to use the create or add method
723
     *
724
     * @return HTML_QuickForm_button
725
     */
726
    public function addButtonDownload($label, $name = 'submit', $createElement = false)
727
    {
728
        return $this->addButton(
729
            $name,
730
            $label,
731
            'download',
732
            'primary',
733
            null,
734
            null,
735
            [],
736
            $createElement
737
        );
738
    }
739
740
    /**
741
     * Returns a button with the primary color and a magnifier icon.
742
     *
743
     * @param string $label         Text appearing on the button
744
     * @param string $name          Element name (for form treatment purposes)
745
     * @param bool   $createElement Whether to use the create or add method
746
     *
747
     * @return HTML_QuickForm_button
748
     */
749
    public function addButtonPreview($label, $name = 'submit', $createElement = false)
750
    {
751
        return $this->addButton(
752
            $name,
753
            $label,
754
            'search',
755
            'primary',
756
            null,
757
            null,
758
            [],
759
            $createElement
760
        );
761
    }
762
763
    /**
764
     * Returns a button with the primary color and a copy (double sheet) icon.
765
     *
766
     * @param string $label         Text appearing on the button
767
     * @param string $name          Element name (for form treatment purposes)
768
     * @param bool   $createElement Whether to use the create or add method
769
     *
770
     * @return HTML_QuickForm_button
771
     */
772
    public function addButtonCopy($label, $name = 'submit', $createElement = false)
773
    {
774
        return $this->addButton(
775
            $name,
776
            $label,
777
            'copy',
778
            'primary',
779
            null,
780
            null,
781
            [],
782
            $createElement
783
        );
784
    }
785
786
    /**
787
     * @param string $name
788
     * @param string $label
789
     * @param string $text
790
     * @param array  $attributes
791
     *
792
     * @return HTML_QuickForm_checkbox
793
     */
794
    public function addCheckBox($name, $label, $text = '', $attributes = [])
795
    {
796
        return $this->addElement('checkbox', $name, $label, $text, $attributes);
797
    }
798
799
    /**
800
     * @param string $name
801
     * @param string $label
802
     * @param array  $options
803
     * @param array  $attributes
804
     *
805
     * @return HTML_QuickForm_group
806
     */
807
    public function addCheckBoxGroup($name, $label, $options = [], $attributes = [])
808
    {
809
        $group = [];
810
        foreach ($options as $value => $text) {
811
            $attributes['value'] = $value;
812
            $group[] = $this->createElement(
813
                'checkbox',
814
                $value,
815
                null,
816
                $text,
817
                $attributes
818
            );
819
        }
820
821
        return $this->addGroup($group, $name, $label);
822
    }
823
824
    /**
825
     * @param string $name
826
     * @param string $label
827
     * @param array  $options
828
     * @param array  $attributes
829
     *
830
     * @return HTML_QuickForm_group
831
     */
832
    public function addRadio($name, $label, $options = [], $attributes = [])
833
    {
834
        $group = [];
835
        foreach ($options as $key => $value) {
836
            $group[] = $this->createElement('radio', null, null, $value, $key, $attributes);
837
        }
838
839
        return $this->addGroup($group, $name, $label);
840
    }
841
842
    /**
843
     * @param string $name
844
     * @param string $label
845
     * @param array  $options
846
     * @param array  $attributes
847
     *
848
     * @return HTML_QuickForm_select
849
     */
850
    public function addSelect($name, $label, $options = [], $attributes = [])
851
    {
852
        return $this->addElement('select', $name, $label, $options, $attributes);
853
    }
854
855
    /**
856
     * @param $name
857
     * @param $label
858
     * @param $collection
859
     * @param array  $attributes
860
     * @param bool   $addNoneOption
861
     * @param string $textCallable  set a function getStringValue() by default __toString()
862
     *
863
     * @return HTML_QuickForm_element
864
     */
865
    public function addSelectFromCollection(
866
        $name,
867
        $label,
868
        $collection,
869
        $attributes = [],
870
        $addNoneOption = false,
871
        $textCallable = ''
872
    ) {
873
        $options = [];
874
875
        if ($addNoneOption) {
876
            $options[0] = get_lang('None');
877
        }
878
879
        if (!empty($collection)) {
880
            foreach ($collection as $item) {
881
                $text = $item;
882
                if (!empty($textCallable)) {
883
                    $text = $item->$textCallable();
884
                }
885
                $options[$item->getId()] = $text;
886
            }
887
        }
888
889
        return $this->addElement('select', $name, $label, $options, $attributes);
890
    }
891
892
    /**
893
     * @param string $label
894
     * @param string $text
895
     * @param bool   $createElement
896
     *
897
     * @return HTML_QuickForm_Element
898
     */
899
    public function addLabel($label, $text, $createElement = false)
900
    {
901
        if ($createElement) {
902
            return $this->createElement(
903
                'label',
904
                $label,
905
                $text
906
            );
907
        }
908
909
        return $this->addElement('label', $label, $text);
910
    }
911
912
    /**
913
     * @param string $text
914
     */
915
    public function addHeader($text)
916
    {
917
        if (!empty($text)) {
918
            $this->addElement('header', $text);
919
        }
920
    }
921
922
    /**
923
     * @param string $name
924
     * @param string $label
925
     * @param array  $attributes
926
     *
927
     * @throws Exception if the file doesn't have an id
928
     *
929
     * @return HTML_QuickForm_file
930
     */
931
    public function addFile($name, $label, $attributes = [])
932
    {
933
        $element = $this->addElement('file', $name, $label, $attributes);
934
        if (isset($attributes['crop_image'])) {
935
            $id = $element->getAttribute('id');
936
            if (empty($id)) {
937
                throw new Exception('If you use the crop functionality the element must have an id');
938
            }
939
            $this->addHtml(
940
                '
941
                <div class="form-group" id="'.$id.'-form-group" style="display: none;">
942
                    <div class="col-sm-offset-2 col-sm-8">
943
                        <div id="'.$id.'_crop_image" class="cropCanvas thumbnail">
944
                            <img id="'.$id.'_preview_image">
945
                        </div>
946
                        <button class="btn btn-primary" type="button" name="cropButton" id="'.$id.'_crop_button">
947
                            <em class="fa fa-crop"></em> '.get_lang('CropYourPicture').'
948
                        </button>
949
                    </div>
950
                </div>'
951
            );
952
            $this->addHidden($id.'_crop_result', '');
953
            $this->addHidden($id.'_crop_image_base_64', '');
954
        }
955
956
        return $element;
957
    }
958
959
    /**
960
     * @param string $snippet
961
     */
962
    public function addHtml($snippet)
963
    {
964
        $this->addElement('html', $snippet);
965
    }
966
967
    /**
968
     * Draws a panel of options see the course_info/infocours.php page.
969
     *
970
     * @param string $name      internal name
971
     * @param string $title     visible title
972
     * @param array  $groupList list of group or elements
973
     */
974
    public function addPanelOption($name, $title, $groupList)
975
    {
976
        $this->addHtml('<div class="panel panel-default">');
977
        $this->addHtml(
978
            '
979
            <div class="panel-heading" role="tab" id="heading-'.$name.'-settings">
980
                <h4 class="panel-title">
981
                    <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion"
982
                       href="#collapse-'.$name.'-settings" aria-expanded="false" aria-controls="collapse-'.$name.'-settings">
983
        '
984
        );
985
        $this->addHtml($title);
986
        $this->addHtml('</a></h4></div>');
987
        $this->addHtml('<div id="collapse-'.$name.'-settings" class="panel-collapse collapse" role="tabpanel"
988
             aria-labelledby="heading-'.$name.'-settings">
989
            <div class="panel-body">
990
        ');
991
992
        foreach ($groupList as $groupName => $group) {
993
            // Add group array
994
            if (!empty($groupName) && is_array($group)) {
995
                $this->addGroup($group, '', $groupName);
996
            }
997
            // Add element
998
            if ($group instanceof HTML_QuickForm_element) {
999
                $this->addElement($group);
1000
            }
1001
        }
1002
1003
        $this->addHtml('</div></div>');
1004
        $this->addHtml('</div>');
1005
    }
1006
1007
    /**
1008
     * Adds a HTML-editor to the form.
1009
     *
1010
     * @param string       $name
1011
     * @param string|array $label    The label for the form-element
1012
     * @param bool         $required (optional) Is the form-element required (default=true)
1013
     * @param bool         $fullPage (optional) When it is true, the editor loads completed html code for a full page
1014
     * @param array        $config   (optional) Configuration settings for the online editor
1015
     */
1016
    public function addHtmlEditor(
1017
        $name,
1018
        $label,
1019
        $required = true,
1020
        $fullPage = false,
1021
        $config = []
1022
    ) {
1023
        $attributes = [];
1024
        $attributes['rows'] = isset($config['rows']) ? $config['rows'] : 15;
1025
        $attributes['cols'] = isset($config['cols']) ? $config['cols'] : 80;
1026
        $attributes['cols-size'] = isset($config['cols-size']) ? $config['cols-size'] : [];
1027
        $attributes['class'] = isset($config['class']) ? $config['class'] : [];
1028
1029
        $this->addElement('html_editor', $name, $label, $attributes, $config);
1030
        $this->applyFilter($name, 'trim');
1031
        if ($required) {
1032
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1033
        }
1034
1035
        /** @var HtmlEditor $element */
1036
        $element = $this->getElement($name);
1037
        $config['style'] = isset($config['style']) ? $config['style'] : false;
1038
        if ($fullPage) {
1039
            $config['fullPage'] = true;
1040
            // Adds editor_content.css in ckEditor
1041
            $config['style'] = true;
1042
        }
1043
1044
        if ($element->editor) {
1045
            $element->editor->processConfig($config);
1046
        }
1047
    }
1048
1049
    /**
1050
     * Adds a Google Maps Geolocalization field to the form.
1051
     *
1052
     * @param      $name
1053
     * @param      $label
1054
     * @param bool $hideGeoLocalizationDetails
1055
     */
1056
    public function addGeoLocationMapField($name, $label, $dataValue, $hideGeoLocalizationDetails = false)
1057
    {
1058
        $gMapsPlugin = GoogleMapsPlugin::create();
1059
        $geolocalization = $gMapsPlugin->get('enable_api') === 'true';
1060
1061
        if ($geolocalization && $gMapsPlugin->javascriptIncluded === false) {
1062
            $gmapsApiKey = $gMapsPlugin->get('api_key');
1063
            $url = '//maps.googleapis.com/maps/api/js?key='.$gmapsApiKey;
1064
            $this->addHtml('<script type="text/javascript" src="'.$url.'" ></script>');
1065
            $gMapsPlugin->javascriptIncluded = true;
1066
        }
1067
1068
        $this->addElement(
1069
            'text',
1070
            $name,
1071
            $label,
1072
            ['id' => $name]
1073
        );
1074
1075
        $this->addHidden(
1076
            $name.'_coordinates',
1077
            '',
1078
            ['id' => $name.'_coordinates']
1079
        );
1080
1081
        $this->applyFilter($name, 'stripslashes');
1082
        $this->applyFilter($name, 'trim');
1083
1084
        $this->addHtml(Extrafield::getLocalizationJavascript($name, $dataValue));
1085
1086
        if ($hideGeoLocalizationDetails) {
1087
            $this->addHtml('<div style="display:none">');
1088
        }
1089
1090
        $this->addHtml(
1091
            Extrafield::getLocalizationInput($name, $label)
1092
        );
1093
1094
        if ($hideGeoLocalizationDetails) {
1095
            $this->addHtml('</div>');
1096
        }
1097
    }
1098
1099
    /**
1100
     * @param string $name
1101
     * @param string $label
1102
     *
1103
     * @return mixed
1104
     */
1105
    public function addButtonAdvancedSettings($name, $label = '')
1106
    {
1107
        $label = !empty($label) ? $label : get_lang('AdvancedParameters');
1108
1109
        return $this->addElement('advanced_settings', $name, $label);
1110
    }
1111
1112
    /**
1113
     * Adds a progress loading image to the form.
1114
     */
1115
    public function addProgress($delay = 2, $label = '')
1116
    {
1117
        if (empty($label)) {
1118
            $label = get_lang('PleaseStandBy');
1119
        }
1120
        $this->with_progress_bar = true;
1121
        $id = $this->getAttribute('id');
1122
1123
        $this->updateAttributes("onsubmit=\"javascript: addProgress('".$id."')\"");
1124
        $this->addHtml('<script language="javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/upload.js" type="text/javascript"></script>');
1125
    }
1126
1127
    /**
1128
     * This function has been created for avoiding changes directly within QuickForm class.
1129
     * When we use it, the element is threated as 'required' to be dealt during validation.
1130
     *
1131
     * @param array  $elements The array of elements
1132
     * @param string $message  The message displayed
1133
     */
1134
    public function add_multiple_required_rule($elements, $message)
1135
    {
1136
        $this->_required[] = $elements[0];
1137
        $this->addRule($elements, $message, 'multiple_required');
1138
    }
1139
1140
    /**
1141
     * Displays the form.
1142
     * If an element in the form didn't validate, an error message is showed
1143
     * asking the user to complete the form.
1144
     */
1145
    public function display()
1146
    {
1147
        echo $this->returnForm();
1148
    }
1149
1150
    /**
1151
     * Returns the HTML code of the form.
1152
     *
1153
     * @return string $return_value HTML code of the form
1154
     */
1155
    public function returnForm()
1156
    {
1157
        $returnValue = '';
1158
1159
        /** @var HTML_QuickForm_element $element */
1160
        foreach ($this->_elements as $element) {
1161
            $elementError = parent::getElementError($element->getName());
1162
            if (!is_null($elementError)) {
1163
                $returnValue .= Display::return_message($elementError, 'warning').'<br />';
1164
                break;
1165
            }
1166
        }
1167
1168
        $returnValue .= parent::toHtml();
1169
        // Add div-element which is to hold the progress bar
1170
        $id = $this->getAttribute('id');
1171
        if (isset($this->with_progress_bar) && $this->with_progress_bar) {
1172
            // Deprecated
1173
            // $icon = Display::return_icon('progress_bar.gif');
1174
1175
            // @todo improve UI
1176
            $returnValue .= '<br />
1177
1178
            <div id="loading_div_'.$id.'" class="loading_div" style="display:none;margin-left:40%; margin-top:10px; height:50px;">
1179
                <div class="wobblebar-loader"></div>
1180
            </div>
1181
            ';
1182
        }
1183
1184
        return $returnValue;
1185
    }
1186
1187
    /**
1188
     * Returns the HTML code of the form.
1189
     * If an element in the form didn't validate, an error message is showed
1190
     * asking the user to complete the form.
1191
     *
1192
     * @return string $return_value HTML code of the form
1193
     *
1194
     * @author Patrick Cool <[email protected]>, Ghent University, august 2006
1195
     * @author Julio Montoya
1196
     *
1197
     * @deprecated use returnForm()
1198
     */
1199
    public function return_form()
1200
    {
1201
        return $this->returnForm();
1202
    }
1203
1204
    /**
1205
     * @return HTML_QuickForm_Renderer_Default
1206
     */
1207
    public static function getDefaultRenderer()
1208
    {
1209
        return
1210
            isset($GLOBALS['_HTML_QuickForm_default_renderer']) ?
1211
                $GLOBALS['_HTML_QuickForm_default_renderer'] : null;
1212
    }
1213
1214
    /**
1215
     * Adds a input of type url to the form.
1216
     *
1217
     * @param string $name       The label for the form-element
1218
     * @param string $label      The element name
1219
     * @param bool   $required   Optional. Is the form-element required (default=true)
1220
     * @param array  $attributes Optional. List of attributes for the form-element
1221
     */
1222
    public function addUrl($name, $label, $required = true, $attributes = [])
1223
    {
1224
        $this->addElement('url', $name, $label, $attributes);
1225
        $this->applyFilter($name, 'trim');
1226
        $this->addRule($name, get_lang('InsertAValidUrl'), 'url');
1227
1228
        if ($required) {
1229
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1230
        }
1231
    }
1232
1233
    /**
1234
     * Adds a text field for letters to the form.
1235
     * A trim-filter is attached to the field.
1236
     *
1237
     * @param string $name       The element name
1238
     * @param string $label      The label for the form-element
1239
     * @param bool   $required   Optional. Is the form-element required (default=true)
1240
     * @param array  $attributes Optional. List of attributes for the form-element
1241
     */
1242
    public function addTextLettersOnly(
1243
        $name,
1244
        $label,
1245
        $required = false,
1246
        $attributes = []
1247
    ) {
1248
        $attributes = array_merge(
1249
            $attributes,
1250
            [
1251
                'pattern' => '[a-zA-ZñÑ]+',
1252
                'title' => get_lang('OnlyLetters'),
1253
            ]
1254
        );
1255
1256
        $this->addElement(
1257
            'text',
1258
            $name,
1259
            [
1260
                $label,
1261
                get_lang('OnlyLetters'),
1262
            ],
1263
            $attributes
1264
        );
1265
1266
        $this->applyFilter($name, 'trim');
1267
1268
        if ($required) {
1269
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1270
        }
1271
1272
        $this->addRule(
1273
            $name,
1274
            get_lang('OnlyLetters'),
1275
            'regex',
1276
            '/^[a-zA-ZñÑ]+$/'
1277
        );
1278
    }
1279
1280
    /**
1281
     * @param string      $name
1282
     * @param string      $label
1283
     * @param array $attributes
1284
     * @param bool  $required
1285
     *
1286
     * @return HTML_QuickForm_element
1287
     */
1288
    public function addNumeric($name, $label, $attributes = [], $required = false)
1289
    {
1290
        $element = $this->addElement('Number', $name, $label, $attributes);
1291
1292
        if ($required) {
1293
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1294
        }
1295
1296
        return $element;
1297
    }
1298
1299
    /**
1300
     * Adds a text field for alphanumeric characters to the form.
1301
     * A trim-filter is attached to the field.
1302
     *
1303
     * @param string $name       The element name
1304
     * @param string $label      The label for the form-element
1305
     * @param bool   $required   Optional. Is the form-element required (default=true)
1306
     * @param array  $attributes Optional. List of attributes for the form-element
1307
     */
1308
    public function addTextAlphanumeric(
1309
        $name,
1310
        $label,
1311
        $required = false,
1312
        $attributes = []
1313
    ) {
1314
        $attributes = array_merge(
1315
            $attributes,
1316
            [
1317
                'pattern' => '[a-zA-Z0-9ñÑ]+',
1318
                'title' => get_lang('OnlyLettersAndNumbers'),
1319
            ]
1320
        );
1321
1322
        $this->addElement(
1323
            'text',
1324
            $name,
1325
            [
1326
                $label,
1327
                get_lang('OnlyLettersAndNumbers'),
1328
            ],
1329
            $attributes
1330
        );
1331
1332
        $this->applyFilter($name, 'trim');
1333
1334
        if ($required) {
1335
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1336
        }
1337
1338
        $this->addRule(
1339
            $name,
1340
            get_lang('OnlyLettersAndNumbers'),
1341
            'regex',
1342
            '/^[a-zA-Z0-9ÑÑ]+$/'
1343
        );
1344
    }
1345
1346
    /**
1347
     * @param string $name
1348
     * @param $label
1349
     * @param bool  $required
1350
     * @param array $attributes
1351
     * @param bool  $allowNegative
1352
     * @param int   $minValue
1353
     * @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...
1354
     */
1355
    public function addFloat(
1356
        $name,
1357
        $label,
1358
        $required = false,
1359
        $attributes = [],
1360
        $allowNegative = false,
1361
        $minValue = null,
1362
        $maxValue = null
1363
    ) {
1364
        $this->addElement(
1365
            'FloatNumber',
1366
            $name,
1367
            $label,
1368
            $attributes
1369
        );
1370
1371
        $this->applyFilter($name, 'trim');
1372
1373
        if ($required) {
1374
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1375
        }
1376
1377
        // Rule allows "," and "."
1378
        /*$this->addRule(
1379
            $name,
1380
            get_lang('OnlyNumbers'),
1381
            'regex',
1382
            '/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|(^-?\d\d*\,\d*$)|(^-?\,\d\d*$)/'
1383
        );*/
1384
1385
        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...
1386
            $this->addRule(
1387
                $name,
1388
                get_lang('NegativeValue'),
1389
                'compare',
1390
                '>=',
1391
                'server',
1392
                false,
1393
                false,
1394
                0
1395
            );
1396
        }
1397
1398
        if (!is_null($minValue)) {
1399
            $this->addRule(
1400
                $name,
1401
                get_lang('UnderMin'),
1402
                'compare',
1403
                '>=',
1404
                'server',
1405
                false,
1406
                false,
1407
                $minValue
1408
            );
1409
        }
1410
1411
        if (!is_null($maxValue)) {
1412
            $this->addRule(
1413
                $name,
1414
                get_lang('OverMax'),
1415
                'compare',
1416
                '<=',
1417
                'server',
1418
                false,
1419
                false,
1420
                $maxValue
1421
            );
1422
        }
1423
    }
1424
1425
    /**
1426
     * Adds a text field for letters and spaces to the form.
1427
     * A trim-filter is attached to the field.
1428
     *
1429
     * @param string $name       The element name
1430
     * @param string $label      The label for the form-element
1431
     * @param bool   $required   Optional. Is the form-element required (default=true)
1432
     * @param array  $attributes Optional. List of attributes for the form-element
1433
     */
1434
    public function addTextLettersAndSpaces(
1435
        $name,
1436
        $label,
1437
        $required = false,
1438
        $attributes = []
1439
    ) {
1440
        $attributes = array_merge(
1441
            $attributes,
1442
            [
1443
                'pattern' => '[a-zA-ZñÑ\s]+',
1444
                'title' => get_lang('OnlyLettersAndSpaces'),
1445
            ]
1446
        );
1447
1448
        $this->addElement(
1449
            'text',
1450
            $name,
1451
            [
1452
                $label,
1453
                get_lang('OnlyLettersAndSpaces'),
1454
            ],
1455
            $attributes
1456
        );
1457
1458
        $this->applyFilter($name, 'trim');
1459
1460
        if ($required) {
1461
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1462
        }
1463
1464
        $this->addRule(
1465
            $name,
1466
            get_lang('OnlyLettersAndSpaces'),
1467
            'regex',
1468
            '/^[a-zA-ZñÑ\s]+$/'
1469
        );
1470
    }
1471
1472
    /**
1473
     * Adds a text field for alphanumeric and spaces characters to the form.
1474
     * A trim-filter is attached to the field.
1475
     *
1476
     * @param string $name       The element name
1477
     * @param string $label      The label for the form-element
1478
     * @param bool   $required   Optional. Is the form-element required (default=true)
1479
     * @param array  $attributes Optional. List of attributes for the form-element
1480
     */
1481
    public function addTextAlphanumericAndSpaces(
1482
        $name,
1483
        $label,
1484
        $required = false,
1485
        $attributes = []
1486
    ) {
1487
        $attributes = array_merge(
1488
            $attributes,
1489
            [
1490
                'pattern' => '[a-zA-Z0-9ñÑ\s]+',
1491
                'title' => get_lang('OnlyLettersAndNumbersAndSpaces'),
1492
            ]
1493
        );
1494
1495
        $this->addElement(
1496
            'text',
1497
            $name,
1498
            [
1499
                $label,
1500
                get_lang('OnlyLettersAndNumbersAndSpaces'),
1501
            ],
1502
            $attributes
1503
        );
1504
1505
        $this->applyFilter($name, 'trim');
1506
1507
        if ($required) {
1508
            $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
1509
        }
1510
1511
        $this->addRule(
1512
            $name,
1513
            get_lang('OnlyLettersAndNumbersAndSpaces'),
1514
            'regex',
1515
            '/^[a-zA-Z0-9ñÑ\s]+$/'
1516
        );
1517
    }
1518
1519
    /**
1520
     * @param string $url
1521
     * @param string $urlToRedirect after upload redirect to this page
1522
     */
1523
    public function addMultipleUpload($url, $urlToRedirect = '')
1524
    {
1525
        $inputName = 'input_file_upload';
1526
        $this->addMultipleUploadJavascript($url, $inputName, $urlToRedirect);
1527
1528
        $this->addHtml('
1529
            <div class="description-upload">
1530
            '.get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadField').'
1531
            </div>
1532
            <span class="btn btn-success fileinput-button">
1533
                <i class="glyphicon glyphicon-plus"></i>
1534
                <span>'.get_lang('AddFiles').'</span>
1535
                <!-- The file input field used as target for the file upload widget -->
1536
                <input id="'.$inputName.'" type="file" name="files[]" multiple>
1537
            </span>
1538
            <div id="dropzone">
1539
                <div class="button-load">
1540
                '.get_lang('UploadFiles').'
1541
                </div>
1542
            </div>
1543
            <br />
1544
            <!-- The global progress bar -->
1545
            <div id="progress" class="progress">
1546
                <div class="progress-bar progress-bar-success"></div>
1547
            </div>
1548
            <div id="files" class="files"></div>
1549
        ');
1550
    }
1551
1552
    /**
1553
     * @param string $elementName
1554
     * @param string $groupName   if element is inside a group
1555
     *
1556
     * @throws Exception
1557
     */
1558
    public function addPasswordRule($elementName, $groupName = '')
1559
    {
1560
        // Constant defined in old config/profile.conf.php
1561
        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...
1562
            $message = get_lang('PassTooEasy').': '.api_generate_password();
1563
1564
            if (!empty($groupName)) {
1565
                $groupObj = $this->getElement($groupName);
1566
1567
                if ($groupObj instanceof HTML_QuickForm_group) {
1568
                    $elementName = $groupObj->getElementName($elementName);
1569
1570
                    if ($elementName === false) {
1571
                        throw new Exception("The $groupName doesn't have the element $elementName");
1572
                    }
1573
1574
                    $this->_rules[$elementName][] = [
1575
                        'type' => 'callback',
1576
                        'format' => 'api_check_password',
1577
                        'message' => $message,
1578
                        'validation' => '',
1579
                        'reset' => false,
1580
                        'group' => $groupName,
1581
                    ];
1582
                }
1583
            } else {
1584
                $this->addRule(
1585
                    $elementName,
1586
                    $message,
1587
                    'callback',
1588
                    'api_check_password'
1589
                );
1590
            }
1591
        }
1592
    }
1593
1594
    /**
1595
     * Add an element with user ID and avatar to the form.
1596
     * It needs a Chamilo\UserBundle\Entity\User as value. The exported value is the Chamilo\UserBundle\Entity\User ID.
1597
     *
1598
     * @see \UserAvatar
1599
     *
1600
     * @param string $name
1601
     * @param string $label
1602
     * @param string $imageSize Optional. Small, medium or large image
1603
     * @param string $subtitle  Optional. The subtitle for the field
1604
     *
1605
     * @return \UserAvatar
1606
     */
1607
    public function addUserAvatar($name, $label, $imageSize = 'small', $subtitle = '')
1608
    {
1609
        return $this->addElement('UserAvatar', $name, $label, ['image_size' => $imageSize, 'sub_title' => $subtitle]);
1610
    }
1611
1612
    /**
1613
     * @param array $typeList
1614
     */
1615
    public function addEmailTemplate($typeList)
1616
    {
1617
        $mailManager = new MailTemplateManager();
1618
        foreach ($typeList as $type) {
1619
            $list = $mailManager->get_all(
1620
                ['where' => ['type = ? AND url_id = ?' => [$type, api_get_current_access_url_id()]]]
1621
            );
1622
1623
            $options = [get_lang('Select')];
1624
            $name = $type;
1625
            $defaultId = '';
1626
            foreach ($list as $item) {
1627
                $options[$item['id']] = $item['name'];
1628
                $name = $item['name'];
1629
                if (empty($defaultId)) {
1630
                    $defaultId = $item['default_template'] == 1 ? $item['id'] : '';
1631
                }
1632
            }
1633
1634
            $url = api_get_path(WEB_AJAX_PATH).'mail.ajax.php?a=select_option';
1635
            $typeNoDots = 'email_template_option_'.str_replace('.tpl', '', $type);
1636
            $this->addSelect(
1637
                'email_template_option['.$type.']',
1638
                $name,
1639
                $options,
1640
                ['id' => $typeNoDots]
1641
            );
1642
1643
            $templateNoDots = 'email_template_'.str_replace('.tpl', '', $type);
1644
            $templateNoDotsBlock = 'email_template_block_'.str_replace('.tpl', '', $type);
1645
            $this->addHtml('<div id="'.$templateNoDotsBlock.'" style="display:none">');
1646
            $this->addTextarea(
1647
                $templateNoDots,
1648
                get_lang('Preview'),
1649
                ['disabled' => 'disabled ', 'id' => $templateNoDots, 'rows' => '5']
1650
            );
1651
            $this->addHtml('</div>');
1652
1653
            $this->addHtml("<script>
1654
            $(function() {
1655
                var defaultValue = '$defaultId';
1656
                $('#$typeNoDots').val(defaultValue);
1657
                $('#$typeNoDots').selectpicker('render');
1658
                if (defaultValue != '') {
1659
                    var selected = $('#$typeNoDots option:selected').val();
1660
                    $.ajax({
1661
                        url: '$url' + '&id=' + selected+ '&template_name=$type',
1662
                        success: function (data) {
1663
                            $('#$templateNoDots').html(data);
1664
                            $('#$templateNoDotsBlock').show();
1665
                            return;
1666
                        },
1667
                    });
1668
                }
1669
1670
                $('#$typeNoDots').on('change', function(){
1671
                    var selected = $('#$typeNoDots option:selected').val();
1672
                    $.ajax({
1673
                        url: '$url' + '&id=' + selected,
1674
                        success: function (data) {
1675
                            $('#$templateNoDots').html(data);
1676
                            $('#$templateNoDotsBlock').show();
1677
                            return;
1678
                        },
1679
                    });
1680
                });
1681
            });
1682
            </script>");
1683
        }
1684
    }
1685
1686
    /**
1687
     * @param string $url           page that will handle the upload
1688
     * @param string $inputName
1689
     * @param string $urlToRedirect
1690
     */
1691
    private function addMultipleUploadJavascript($url, $inputName, $urlToRedirect = '')
1692
    {
1693
        $redirectCondition = '';
1694
        if (!empty($urlToRedirect)) {
1695
            $redirectCondition = "window.location.replace('$urlToRedirect'); ";
1696
        }
1697
        $icon = Display::return_icon('file_txt.gif');
1698
        $this->addHtml("
1699
        <script>
1700
        $(function () {
1701
            'use strict';
1702
            $('#".$this->getAttribute('id')."').submit(function() {
1703
                return false;
1704
            });
1705
1706
            $('#dropzone').on('click', function() {
1707
                $('#".$inputName."').click();
1708
            });
1709
1710
            var url = '".$url."';
1711
            var uploadButton = $('<button/>')
1712
                .addClass('btn btn-primary')
1713
                .prop('disabled', true)
1714
                .text('".addslashes(get_lang('Loading'))."')
1715
                .on('click', function () {
1716
                    var \$this = $(this),
1717
                    data = \$this.data();
1718
                    \$this
1719
                        .off('click')
1720
                        .text('".addslashes(get_lang('Cancel'))."')
1721
                        .on('click', function () {
1722
                            \$this.remove();
1723
                            data.abort();
1724
                        });
1725
                    data.submit().always(function () {
1726
                        \$this.remove();
1727
                    });
1728
                });
1729
1730
            $('#".$inputName."').fileupload({
1731
                url: url,
1732
                dataType: 'json',
1733
                // Enable image resizing, except for Android and Opera,
1734
                // which actually support image resizing, but fail to
1735
                // send Blob objects via XHR requests:
1736
                disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
1737
                previewMaxWidth: 300,
1738
                previewMaxHeight: 169,
1739
                previewCrop: true,
1740
                dropzone: $('#dropzone'),
1741
            }).on('fileuploadadd', function (e, data) {
1742
                data.context = $('<div class=\"row\" />').appendTo('#files');
1743
                $.each(data.files, function (index, file) {
1744
                    var node = $('<div class=\"col-sm-5 file_name\">').text(file.name);
1745
                    node.appendTo(data.context);
1746
                });
1747
            }).on('fileuploadprocessalways', function (e, data) {
1748
                var index = data.index,
1749
                    file = data.files[index],
1750
                    node = $(data.context.children()[index]);
1751
                if (file.preview) {
1752
                    data.context.prepend($('<div class=\"col-sm-4\">').html(file.preview));
1753
                } else {
1754
                    data.context.prepend($('<div class=\"col-sm-4\">').html('".$icon."'));
1755
                }
1756
                if (index + 1 === data.files.length) {
1757
                    data.context.find('button')
1758
                        .text('Upload')
1759
                        .prop('disabled', !!data.files.error);
1760
                }
1761
            }).on('fileuploadprogressall', function (e, data) {
1762
                var progress = parseInt(data.loaded / data.total * 100, 10);
1763
                $('#progress .progress-bar').css(
1764
                    'width',
1765
                    progress + '%'
1766
                );
1767
            }).on('fileuploaddone', function (e, data) {
1768
                $.each(data.result.files, function (index, file) {
1769
                    if (file.error) {
1770
                        var link = $('<div>')
1771
                            .attr({class : 'panel-image'})                            ;
1772
                        $(data.context.children()[index]).parent().wrap(link);
1773
                        // Update file name with new one from Chamilo
1774
                        $(data.context.children()[index]).parent().find('.file_name').html(file.name);
1775
                        var message = $('<div class=\"col-sm-3\">').html(
1776
                            $('<span class=\"message-image-danger\"/>').text(file.error)
1777
                        );
1778
                        $(data.context.children()[index]).parent().append(message);
1779
1780
                        return;
1781
                    }
1782
                    if (file.url) {
1783
                        var link = $('<a>')
1784
                            .attr({target: '_blank', class : 'panel-image'})
1785
                            .prop('href', file.url);
1786
                        $(data.context.children()[index]).parent().wrap(link);
1787
                    }
1788
                    // Update file name with new one from Chamilo
1789
                    $(data.context.children()[index]).parent().find('.file_name').html(file.name);
1790
                    var message = $('<div class=\"col-sm-3\">').html(
1791
                        $('<span class=\"message-image-success\"/>').text('".addslashes(get_lang('UplUploadSucceeded'))."')
1792
                    );
1793
                    $(data.context.children()[index]).parent().append(message);
1794
                });
1795
                $('#dropzone').removeClass('hover');
1796
                ".$redirectCondition."
1797
            }).on('fileuploadfail', function (e, data) {
1798
                $.each(data.files, function (index) {
1799
                    var failedMessage = '".addslashes(get_lang('UplUploadFailed'))."';
1800
                    var error = $('<div class=\"col-sm-3\">').html(
1801
                        $('<span class=\"alert alert-danger\"/>').text(failedMessage)
1802
                    );
1803
                    $(data.context.children()[index]).parent().append(error);
1804
                });
1805
                $('#dropzone').removeClass('hover');
1806
            }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
1807
1808
            $('#dropzone').on('dragover', function (e) {
1809
                // dragleave callback implementation
1810
                $('#dropzone').addClass('hover');
1811
            });
1812
1813
            $('#dropzone').on('dragleave', function (e) {
1814
                $('#dropzone').removeClass('hover');
1815
            });
1816
            $('.fileinput-button').hide();
1817
        });
1818
        </script>");
1819
    }
1820
}
1821
1822
/**
1823
 * Cleans HTML text filter.
1824
 *
1825
 * @param string $html HTML to clean
1826
 * @param int    $mode (optional)
1827
 *
1828
 * @return string The cleaned HTML
1829
 */
1830
function html_filter($html, $mode = NO_HTML)
1831
{
1832
    $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode);
1833
    $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

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