Passed
Push — preprodparkur ( e496f6...18ca73 )
by Angel Fernando Quiroz
10:47
created

ExtraField::addElements()   C

Complexity

Conditions 12
Paths 21

Size

Total Lines 82
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 44
c 0
b 0
f 0
nc 21
nop 17
dl 0
loc 82
rs 6.9666

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
5
use Chamilo\CoreBundle\Entity\ExtraFieldRelTag;
6
use Chamilo\CoreBundle\Entity\Tag;
7
8
/**
9
 * Class ExtraField.
10
 */
11
class ExtraField extends Model
12
{
13
    const FIELD_TYPE_TEXT = 1;
14
    const FIELD_TYPE_TEXTAREA = 2;
15
    const FIELD_TYPE_RADIO = 3;
16
    const FIELD_TYPE_SELECT = 4;
17
    const FIELD_TYPE_SELECT_MULTIPLE = 5;
18
    const FIELD_TYPE_DATE = 6;
19
    const FIELD_TYPE_DATETIME = 7;
20
    const FIELD_TYPE_DOUBLE_SELECT = 8;
21
    const FIELD_TYPE_DIVIDER = 9;
22
    const FIELD_TYPE_TAG = 10;
23
    const FIELD_TYPE_TIMEZONE = 11;
24
    const FIELD_TYPE_SOCIAL_PROFILE = 12;
25
    const FIELD_TYPE_CHECKBOX = 13;
26
    const FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
27
    const FIELD_TYPE_INTEGER = 15;
28
    const FIELD_TYPE_FILE_IMAGE = 16;
29
    const FIELD_TYPE_FLOAT = 17;
30
    const FIELD_TYPE_FILE = 18;
31
    const FIELD_TYPE_VIDEO_URL = 19;
32
    const FIELD_TYPE_LETTERS_ONLY = 20;
33
    const FIELD_TYPE_ALPHANUMERIC = 21;
34
    const FIELD_TYPE_LETTERS_SPACE = 22;
35
    const FIELD_TYPE_ALPHANUMERIC_SPACE = 23;
36
    const FIELD_TYPE_GEOLOCALIZATION = 24;
37
    const FIELD_TYPE_GEOLOCALIZATION_COORDINATES = 25;
38
    const FIELD_TYPE_SELECT_WITH_TEXT_FIELD = 26;
39
    const FIELD_TYPE_TRIPLE_SELECT = 27;
40
    public $columns = [
41
        'id',
42
        'field_type',
43
        'variable',
44
        'display_text',
45
        'default_value',
46
        'field_order',
47
        'visible_to_self',
48
        'visible_to_others',
49
        'changeable',
50
        'filter',
51
        'extra_field_type',
52
        //Enable this when field_loggeable is introduced as a table field (2.0)
53
        //'field_loggeable',
54
        'created_at',
55
    ];
56
57
    public $ops = [
58
        'eq' => '=', //equal
59
        'ne' => '<>', //not equal
60
        'lt' => '<', //less than
61
        'le' => '<=', //less than or equal
62
        'gt' => '>', //greater than
63
        'ge' => '>=', //greater than or equal
64
        'bw' => 'LIKE', //begins with
65
        'bn' => 'NOT LIKE', //doesn't begin with
66
        'in' => 'LIKE', //is in
67
        'ni' => 'NOT LIKE', //is not in
68
        'ew' => 'LIKE', //ends with
69
        'en' => 'NOT LIKE', //doesn't end with
70
        'cn' => 'LIKE', //contains
71
        'nc' => 'NOT LIKE',  //doesn't contain
72
    ];
73
74
    public $type = 'user';
75
    public $pageName;
76
    public $pageUrl;
77
    public $extraFieldType = 0;
78
79
    public $table_field_options;
80
    public $table_field_values;
81
    public $table_field_tag;
82
    public $table_field_rel_tag;
83
84
    public $handler_id;
85
    public $primaryKey;
86
87
    /**
88
     * @param string $type
89
     */
90
    public function __construct($type)
91
    {
92
        parent::__construct();
93
94
        $this->type = $type;
95
        $this->table = Database::get_main_table(TABLE_EXTRA_FIELD);
96
        $this->table_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
97
        $this->table_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
98
        $this->table_field_tag = Database::get_main_table(TABLE_MAIN_TAG);
99
        $this->table_field_rel_tag = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
100
101
        $this->handler_id = 'item_id';
102
103
        switch ($this->type) {
104
            case 'calendar_event':
105
                $this->extraFieldType = EntityExtraField::CALENDAR_FIELD_TYPE;
106
                break;
107
            case 'course':
108
                $this->extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
109
                $this->primaryKey = 'id';
110
                break;
111
            case 'user':
112
                $this->extraFieldType = EntityExtraField::USER_FIELD_TYPE;
113
                $this->primaryKey = 'id';
114
                break;
115
            case 'session':
116
                $this->extraFieldType = EntityExtraField::SESSION_FIELD_TYPE;
117
                $this->primaryKey = 'id';
118
                break;
119
            case 'exercise':
120
                $this->extraFieldType = EntityExtraField::EXERCISE_FIELD_TYPE;
121
                break;
122
            case 'question':
123
                $this->extraFieldType = EntityExtraField::QUESTION_FIELD_TYPE;
124
                break;
125
            case 'lp':
126
                $this->extraFieldType = EntityExtraField::LP_FIELD_TYPE;
127
                break;
128
            case 'lp_item':
129
                $this->extraFieldType = EntityExtraField::LP_ITEM_FIELD_TYPE;
130
                break;
131
            case 'skill':
132
                $this->extraFieldType = EntityExtraField::SKILL_FIELD_TYPE;
133
                break;
134
            case 'work':
135
                $this->extraFieldType = EntityExtraField::WORK_FIELD_TYPE;
136
                break;
137
            case 'career':
138
                $this->extraFieldType = EntityExtraField::CAREER_FIELD_TYPE;
139
                break;
140
            case 'user_certificate':
141
                $this->extraFieldType = EntityExtraField::USER_CERTIFICATE;
142
                break;
143
            case 'survey':
144
                $this->extraFieldType = EntityExtraField::SURVEY_FIELD_TYPE;
145
                break;
146
            case 'scheduled_announcement':
147
                $this->extraFieldType = EntityExtraField::SCHEDULED_ANNOUNCEMENT;
148
                break;
149
            case 'terms_and_condition':
150
                $this->extraFieldType = EntityExtraField::TERMS_AND_CONDITION_TYPE;
151
                break;
152
            case 'forum_category':
153
                $this->extraFieldType = EntityExtraField::FORUM_CATEGORY_TYPE;
154
                break;
155
            case 'forum_post':
156
                $this->extraFieldType = EntityExtraField::FORUM_POST_TYPE;
157
                break;
158
            case 'track_exercise':
159
                $this->extraFieldType = EntityExtraField::TRACK_EXERCISE_FIELD_TYPE;
160
                break;
161
            case 'portfolio':
162
                $this->extraFieldType = EntityExtraField::PORTFOLIO_TYPE;
163
                break;
164
            case 'lp_view':
165
                $this->extraFieldType = EntityExtraField::LP_VIEW_TYPE;
166
                break;
167
            case 'course_announcement':
168
                $this->extraFieldType = EntityExtraField::COURSE_ANNOUNCEMENT;
169
                break;
170
            case 'message':
171
                $this->extraFieldType = EntityExtraField::MESSAGE_TYPE;
172
                break;
173
        }
174
175
        $this->pageUrl = 'extra_fields.php?type='.$this->type;
176
        // Example QuestionFields
177
        $this->pageName = get_lang(ucwords($this->type).'Fields');
178
    }
179
180
    /**
181
     * @return array
182
     */
183
    public static function getValidExtraFieldTypes()
184
    {
185
        $result = [
186
            'user',
187
            'course',
188
            'session',
189
            'question',
190
            'lp',
191
            'calendar_event',
192
            'lp_item',
193
            'skill',
194
            'work',
195
            'career',
196
            'user_certificate',
197
            'survey',
198
            'terms_and_condition',
199
            'forum_category',
200
            'forum_post',
201
            'exercise',
202
            'track_exercise',
203
            'lp_view',
204
            'course_announcement',
205
            'message',
206
        ];
207
208
        if (api_get_configuration_value('allow_scheduled_announcements')) {
209
            $result[] = 'scheduled_announcement';
210
        }
211
212
        if (api_get_configuration_value('allow_portfolio_tool')) {
213
            $result[] = 'portfolio';
214
        }
215
        sort($result);
216
217
        return $result;
218
    }
219
220
    /**
221
     * Converts a string like this:
222
     * France:Paris;Bretagne;Marseille;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
223
     * into
224
     * array(
225
     *   'France' =>
226
     *      array('Paris', 'Bretagne', 'Marseille'),
227
     *   'Belgique' =>
228
     *      array('Namur', 'Liège')
229
     * ), etc.
230
     *
231
     * @param string $string
232
     *
233
     * @return array
234
     */
235
    public static function extra_field_double_select_convert_string_to_array($string)
236
    {
237
        $options = explode('|', $string);
238
        $options_parsed = [];
239
        $id = 0;
240
241
        if (!empty($options)) {
242
            foreach ($options as $sub_options) {
243
                $options = explode(':', $sub_options);
244
                $sub_sub_options = isset($options[1]) ? explode(';', $options[1]) : [];
245
                $options_parsed[$id] = [
246
                    'label' => $options[0],
247
                    'options' => $sub_sub_options,
248
                ];
249
                $id++;
250
            }
251
        }
252
253
        return $options_parsed;
254
    }
255
256
257
    /**
258
     * @param $string
259
     *
260
     * @return array
261
     */
262
    public static function tripleSelectConvertStringToArray($string)
263
    {
264
        $options = [];
265
        foreach (explode('|', $string) as $i => $item0) {
266
            $level1 = explode('\\', $item0);
267
268
            foreach ($level1 as $j => $item1) {
269
                if (0 === $j) {
270
                    $options[] = ['label' => $item1, 'options' => []];
271
272
                    continue;
273
                }
274
275
                foreach (explode(':', $item1) as $k => $item2) {
276
                    if (0 === $k) {
277
                        $options[$i]['options'][] = ['label' => $item2, 'options' => []];
278
279
                        continue;
280
                    }
281
282
                    $options[$i]['options'][$j - 1]['options'][] = explode(';', $item2);
283
                }
284
            }
285
        }
286
287
        array_walk_recursive(
288
            $options,
289
            function (&$item) {
290
                $item = trim($item);
291
            }
292
        );
293
294
        return $options;
295
    }
296
297
    /**
298
     * @param array $options the result of the get_field_options_by_field() array
299
     *
300
     * @return string
301
     */
302
    public static function extra_field_double_select_convert_array_to_string($options)
303
    {
304
        $string = null;
305
        $optionsParsed = self::extra_field_double_select_convert_array_to_ordered_array($options);
306
307
        if (!empty($optionsParsed)) {
308
            foreach ($optionsParsed as $option) {
309
                foreach ($option as $key => $item) {
310
                    $string .= $item['display_text'];
311
                    if (0 == $key) {
312
                        $string .= ':';
313
                    } else {
314
                        if (isset($option[$key + 1])) {
315
                            $string .= ';';
316
                        }
317
                    }
318
                }
319
                $string .= '|';
320
            }
321
        }
322
323
        if (!empty($string)) {
324
            $string = substr($string, 0, strlen($string) - 1);
325
        }
326
327
        return $string;
328
    }
329
330
    /**
331
     * @param array $options The result of the get_field_options_by_field() array
332
     *
333
     * @return string
334
     */
335
    public static function extraFieldSelectWithTextConvertArrayToString(array $options)
336
    {
337
        $parsedOptions = self::extra_field_double_select_convert_array_to_ordered_array($options);
338
339
        if (empty($parsedOptions)) {
340
            return '';
341
        }
342
343
        $string = '';
344
        foreach ($parsedOptions as $options) {
345
            $option = current($options);
346
            $string .= $option['display_text'];
347
            $string .= '|';
348
        }
349
350
        return rtrim($string, '|');
351
    }
352
353
    /**
354
     * @return string
355
     */
356
    public static function tripleSelectConvertArrayToString(array $options)
357
    {
358
        $parsedOptions = self::tripleSelectConvertArrayToOrderedArray($options);
359
        $string = '';
360
        foreach ($parsedOptions['level1'] as $item1) {
361
            $string .= $item1['display_text'];
362
            $level2 = self::getOptionsFromTripleSelect($parsedOptions['level2'], $item1['id']);
363
364
            foreach ($level2 as $item2) {
365
                $string .= '\\'.$item2['display_text'].':';
366
                $level3 = self::getOptionsFromTripleSelect($parsedOptions['level3'], $item2['id']);
367
368
                $string .= implode(';', array_column($level3, 'display_text'));
369
            }
370
371
            $string .= '|';
372
        }
373
374
        return trim($string, '\\|;');
375
    }
376
377
378
    /**
379
     * @param string $variable
380
     * @param string $dataValue
381
     *
382
     * @return string
383
     */
384
    public static function getLocalizationJavascript($variable, $dataValue)
385
    {
386
        $dataValue = addslashes($dataValue);
387
        $html = "<script>
388
            $(function() {
389
                if (typeof google === 'object') {
390
                    var address = '$dataValue';
391
                    initializeGeo{$variable}(address, false);
392
393
                    $('#geolocalization_extra_{$variable}').on('click', function() {
394
                        var address = $('#{$variable}').val();
395
                        initializeGeo{$variable}(address, false);
396
                        return false;
397
                    });
398
399
                    $('#myLocation_extra_{$variable}').on('click', function() {
400
                        myLocation{$variable}();
401
                        return false;
402
                    });
403
404
                    // When clicking enter
405
                    $('#{$variable}').keypress(function(event) {
406
                        if (event.which == 13) {
407
                            $('#geolocalization_extra_{$variable}').click();
408
                            return false;
409
                        }
410
                    });
411
412
                    // On focus out update city
413
                    $('#{$variable}').focusout(function() {
414
                        $('#geolocalization_extra_{$variable}').click();
415
                        return false;
416
                    });
417
418
                    return;
419
                }
420
421
                $('#map_extra_{$variable}')
422
                    .html('<div class=\"alert alert-info\">"
423
            .addslashes(get_lang('YouNeedToActivateTheGoogleMapsPluginInAdminPlatformToSeeTheMap'))
424
            ."</div>');
425
            });
426
427
            function myLocation{$variable}()
428
            {
429
                if (navigator.geolocation) {
430
                    var geoPosition = function(position) {
431
                        var lat = position.coords.latitude;
432
                        var lng = position.coords.longitude;
433
                        var latLng = new google.maps.LatLng(lat, lng);
434
                        initializeGeo{$variable}(false, latLng);
435
                    };
436
437
                    var geoError = function(error) {
438
                        alert('Geocode ".get_lang('Error').": ' + error);
439
                    };
440
441
                    var geoOptions = {
442
                        enableHighAccuracy: true
443
                    };
444
                    navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
445
                }
446
            }
447
448
            function initializeGeo{$variable}(address, latLng)
449
            {
450
                var geocoder = new google.maps.Geocoder();
451
                var latlng = new google.maps.LatLng(-34.397, 150.644);
452
                var myOptions = {
453
                    zoom: 15,
454
                    center: latlng,
455
                    mapTypeControl: true,
456
                    mapTypeControlOptions: {
457
                        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
458
                    },
459
                    navigationControl: true,
460
                    mapTypeId: google.maps.MapTypeId.ROADMAP
461
                };
462
463
                map_{$variable} = new google.maps.Map(
464
                    document.getElementById('map_extra_{$variable}'),
465
                    myOptions
466
                );
467
468
                var parameter = address ? {'address': address} : latLng ? {'latLng': latLng} : false;
469
470
                if (geocoder && parameter) {
471
                    geocoder.geocode(parameter, function(results, status) {
472
                        if (status == google.maps.GeocoderStatus.OK) {
473
                            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
474
                                map_{$variable}.setCenter(results[0].geometry.location);
475
476
                                // get city and country
477
                                var defaultAddress = results[0].formatted_address;
478
                                var city = '';
479
                                var country = '';
480
481
                                for (var i=0; i<results[0].address_components.length; i++) {
482
                                    if (results[0].address_components[i].types[0] == \"locality\") {
483
                                        //this is the object you are looking for City
484
                                        city = results[0].address_components[i];
485
                                    }
486
                                    /*if (results[j].address_components[i].types[0] == \"administrative_area_level_1\") {
487
                                        //this is the object you are looking for State
488
                                        region = results[0].address_components[i];
489
                                    }*/
490
                                    if (results[0].address_components[i].types[0] == \"country\") {
491
                                        //this is the object you are looking for
492
                                        country = results[0].address_components[i];
493
                                    }
494
                                }
495
496
                                if (city && city.long_name && country && country.long_name) {
497
                                    defaultAddress = city.long_name + ', ' + country.long_name;
498
                                }
499
                                $('#{$variable}').val(defaultAddress);
500
                                $('#{$variable}_coordinates').val(
501
                                    results[0].geometry.location.lat()+','+results[0].geometry.location.lng()
502
                                );
503
504
                                var infowindow = new google.maps.InfoWindow({
505
                                    content: '<b>' + $('#extra_{$variable}').val() + '</b>',
506
                                    size: new google.maps.Size(150, 50)
507
                                });
508
509
                                var marker = new google.maps.Marker({
510
                                    position: results[0].geometry.location,
511
                                    map: map_{$variable},
512
                                    title: $('#extra_{$variable}').val()
513
                                });
514
                                google.maps.event.addListener(marker, 'click', function() {
515
                                    infowindow.open(map_{$variable}, marker);
516
                                });
517
                            } else {
518
                                alert('".get_lang('NotFound')."');
519
                            }
520
                        } else {
521
                            alert('Geocode ".get_lang('Error').': '.get_lang('AddressField').' '.get_lang('NotFound')."');
522
                        }
523
                    });
524
                }
525
            }
526
            </script>";
527
528
        return $html;
529
    }
530
531
    /**
532
     * @param string $variable
533
     * @param string $text
534
     *
535
     * @return string
536
     */
537
    public static function getLocalizationInput($variable, $text)
538
    {
539
        $html = '
540
                <div class="form-group">
541
                    <label for="geolocalization_extra_'.$variable.'"
542
                        class="col-sm-2 control-label"></label>
543
                    <div class="col-sm-8">
544
                        <button class="btn btn-default"
545
                            id="geolocalization_extra_'.$variable.'"
546
                            name="geolocalization_extra_'.$variable.'"
547
                            type="submit">
548
                            <em class="fa fa-map-marker"></em> '.get_lang('SearchGeolocalization').'
549
                        </button>
550
                        <button class="btn btn-default" id="myLocation_extra_'.$variable.'"
551
                            name="myLocation_extra_'.$variable.'"
552
                            type="submit">
553
                            <em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'
554
                        </button>
555
                    </div>
556
                </div>
557
                <div class="form-group">
558
                    <label for="map_extra_'.$variable.'" class="col-sm-2 control-label">
559
                        '.$text.' - '.get_lang('Map').'
560
                    </label>
561
                    <div class="col-sm-8">
562
                        <div name="map_extra_'.$variable.'"
563
                            id="map_extra_'.$variable.'" style="width:100%; height:300px;">
564
                        </div>
565
                    </div>
566
                </div>
567
            ';
568
569
        return $html;
570
    }
571
572
    /**
573
     * @return int
574
     */
575
    public function get_count()
576
    {
577
        $em = Database::getManager();
578
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
579
        $query->select('count(e.id)');
580
        $query->where('e.extraFieldType = :type');
581
        $query->setParameter('type', $this->getExtraFieldType());
582
583
        return $query->getQuery()->getSingleScalarResult();
584
    }
585
586
    /**
587
     * @return int
588
     */
589
    public function getExtraFieldType()
590
    {
591
        return (int) $this->extraFieldType;
592
    }
593
594
    /**
595
     * @param string $sidx
596
     * @param string $sord
597
     * @param int    $start
598
     * @param int    $limit
599
     *
600
     * @return array
601
     */
602
    public function getAllGrid($sidx, $sord, $start, $limit)
603
    {
604
        switch ($sidx) {
605
            case 'field_order':
606
                $sidx = 'e.fieldOrder';
607
                break;
608
            case 'variable':
609
                $sidx = 'e.variable';
610
                break;
611
            case 'display_text':
612
                $sidx = 'e.displayText';
613
                break;
614
            case 'changeable':
615
                $sidx = 'e.changeable';
616
                break;
617
            case 'visible_to_self':
618
                $sidx = 'e.visibleToSelf';
619
                break;
620
            case 'visible_to_others':
621
                $sidx = 'e.visibleToOthers';
622
                break;
623
            case 'filter':
624
                $sidx = 'e.filter';
625
                break;
626
        }
627
        $em = Database::getManager();
628
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
629
        $query->select('e')
630
            ->where('e.extraFieldType = :type')
631
            ->setParameter('type', $this->getExtraFieldType())
632
            ->orderBy($sidx, $sord)
633
            ->setFirstResult($start)
634
            ->setMaxResults($limit);
635
636
        return $query->getQuery()->getArrayResult();
637
    }
638
639
640
    /**
641
     * Get all the field info for tags.
642
     *
643
     * @param string $variable
644
     *
645
     * @return array|bool
646
     */
647
    public function get_handler_field_info_by_tags($variable)
648
    {
649
        $variable = Database::escape_string($variable);
650
        $sql = "SELECT * FROM {$this->table}
651
                WHERE
652
                    variable = '$variable' AND
653
                    extra_field_type = $this->extraFieldType";
654
        $result = Database::query($sql);
655
        if (Database::num_rows($result)) {
656
            $row = Database::fetch_array($result, 'ASSOC');
657
            $row['display_text'] = $this->translateDisplayName(
658
                $row['variable'],
659
                $row['display_text']
660
            );
661
662
            // All the tags of the field
663
            $sql = "SELECT * FROM $this->table_field_tag
664
                    WHERE field_id='".intval($row['id'])."'
665
                    ORDER BY id ASC";
666
            $result = Database::query($sql);
667
            while ($option = Database::fetch_array($result, 'ASSOC')) {
668
                $row['options'][$option['id']] = $option;
669
            }
670
671
            return $row;
672
        } else {
673
            return false;
674
        }
675
    }
676
677
678
    /**
679
     * Translate the display text for a extra field.
680
     *
681
     * @param string $variable
682
     * @param string $defaultDisplayText
683
     *
684
     * @return string
685
     */
686
    public static function translateDisplayName($variable, $defaultDisplayText)
687
    {
688
        $camelCase = api_underscore_to_camel_case($variable);
689
690
        return isset($GLOBALS[$camelCase]) ? $GLOBALS[$camelCase] : $defaultDisplayText;
691
    }
692
693
694
    /**
695
     * Get an array of all the values from the extra_field and extra_field_options tables
696
     * based on the current object's type.
697
     *
698
     * @param array $conditions
699
     * @param null  $order_field_options_by
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $order_field_options_by is correct as it would always require null to be passed?
Loading history...
700
     *
701
     * @return array
702
     */
703
    public function get_all($conditions = [], $order_field_options_by = null)
704
    {
705
        $conditions = Database::parse_conditions(['where' => $conditions]);
706
707
        if (empty($conditions)) {
708
            $conditions .= ' WHERE extra_field_type = '.$this->extraFieldType;
709
        } else {
710
            $conditions .= ' AND extra_field_type = '.$this->extraFieldType;
711
        }
712
713
        $sql = "SELECT * FROM $this->table
714
                $conditions
715
                ORDER BY field_order ASC
716
        ";
717
718
        $result = Database::query($sql);
719
        $extraFields = Database::store_result($result, 'ASSOC');
720
721
        $option = new ExtraFieldOption($this->type);
722
        if (!empty($extraFields)) {
723
            foreach ($extraFields as &$extraField) {
724
                $extraField['display_text'] = $this->translateDisplayName(
725
                    $extraField['variable'],
726
                    $extraField['display_text']
727
                );
728
                $extraField['options'] = $option->get_field_options_by_field(
729
                    $extraField['id'],
730
                    false,
731
                    $order_field_options_by
732
                );
733
            }
734
        }
735
736
        return $extraFields;
737
    }
738
739
    /**
740
     * Gets the set of values of an extra_field searching for the variable name.
741
     *
742
     * Example:
743
     * <code>
744
     * <?php
745
     * $extraField = new ExtraField('lp_item');
746
     * $extraFieldArray =  $extraField->get_handler_field_info_by_field_variable('authorlpitem');
747
     * echo "<pre>".var_export($extraFieldArray,true)."</pre>";
748
     * ?>
749
     * </code>
750
     *
751
     * @param string $variable
752
     *
753
     * @return array|bool
754
     */
755
    public function get_handler_field_info_by_field_variable($variable)
756
    {
757
        $variable = Database::escape_string($variable);
758
        $sql = "SELECT * FROM {$this->table}
759
                WHERE
760
                    variable = '$variable' AND
761
                    extra_field_type = $this->extraFieldType";
762
        $result = Database::query($sql);
763
        if (Database::num_rows($result)) {
764
            $row = Database::fetch_array($result, 'ASSOC');
765
            if ($row) {
766
                $row['display_text'] = self::translateDisplayName($row['variable'], $row['display_text']);
767
768
                // All the options of the field
769
                $sql = "SELECT * FROM $this->table_field_options
770
                    WHERE field_id='".intval($row['id'])."'
771
                    ORDER BY option_order ASC";
772
                $result = Database::query($sql);
773
                while ($option = Database::fetch_array($result)) {
774
                    $row['options'][$option['id']] = $option;
775
                }
776
777
                return $row;
778
            }
779
        }
780
781
        return false;
782
    }
783
784
785
    /**
786
     * @param int $fieldId
787
     *
788
     * @return array|bool
789
     */
790
    public function getFieldInfoByFieldId($fieldId)
791
    {
792
        $fieldId = (int) $fieldId;
793
        $sql = "SELECT * FROM {$this->table}
794
                WHERE
795
                    id = '$fieldId' AND
796
                    extra_field_type = $this->extraFieldType";
797
        $result = Database::query($sql);
798
        if (Database::num_rows($result)) {
799
            $row = Database::fetch_array($result, 'ASSOC');
800
801
            // All the options of the field
802
            $sql = "SELECT * FROM $this->table_field_options
803
                    WHERE field_id='".$fieldId."'
804
                    ORDER BY option_order ASC";
805
            $result = Database::query($sql);
806
            while ($option = Database::fetch_array($result)) {
807
                $row['options'][$option['id']] = $option;
808
            }
809
810
            return $row;
811
        } else {
812
            return false;
813
        }
814
    }
815
816
    /**
817
     * @return int
818
     */
819
    public function get_max_field_order()
820
    {
821
        $sql = "SELECT MAX(field_order)
822
                FROM {$this->table}
823
                WHERE
824
                    extra_field_type = '.$this->extraFieldType.'";
825
        $res = Database::query($sql);
826
827
        $order = 0;
828
        if (Database::num_rows($res) > 0) {
829
            $row = Database::fetch_row($res);
830
            $order = $row[0] + 1;
831
        }
832
833
        return $order;
834
    }
835
836
    /**
837
     * @param string $handler
838
     *
839
     * @return array
840
     */
841
    public static function get_extra_fields_by_handler($handler)
842
    {
843
        $types = [];
844
        $types[self::FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
845
        $types[self::FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
846
        $types[self::FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
847
        $types[self::FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
848
        $types[self::FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
849
        $types[self::FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
850
        $types[self::FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
851
        $types[self::FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
852
        $types[self::FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
853
        $types[self::FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
854
        $types[self::FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
855
        $types[self::FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
856
        $types[self::FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
857
        $types[self::FIELD_TYPE_CHECKBOX] = get_lang('FieldTypeCheckbox');
858
        $types[self::FIELD_TYPE_INTEGER] = get_lang('FieldTypeInteger');
859
        $types[self::FIELD_TYPE_FILE_IMAGE] = get_lang('FieldTypeFileImage');
860
        $types[self::FIELD_TYPE_FLOAT] = get_lang('FieldTypeFloat');
861
        $types[self::FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
862
        $types[self::FIELD_TYPE_VIDEO_URL] = get_lang('FieldTypeVideoUrl');
863
        $types[self::FIELD_TYPE_LETTERS_ONLY] = get_lang('FieldTypeOnlyLetters');
864
        $types[self::FIELD_TYPE_ALPHANUMERIC] = get_lang('FieldTypeAlphanumeric');
865
        $types[self::FIELD_TYPE_LETTERS_SPACE] = get_lang('FieldTypeLettersSpaces');
866
        $types[self::FIELD_TYPE_ALPHANUMERIC_SPACE] = get_lang('FieldTypeAlphanumericSpaces');
867
        $types[self::FIELD_TYPE_GEOLOCALIZATION] = get_lang('Geolocalization');
868
        $types[self::FIELD_TYPE_GEOLOCALIZATION_COORDINATES] = get_lang('GeolocalizationCoordinates');
869
        $types[self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD] = get_lang('FieldTypeSelectWithTextField');
870
        $types[self::FIELD_TYPE_TRIPLE_SELECT] = get_lang('FieldTypeTripleSelect');
871
872
        switch ($handler) {
873
            case 'course':
874
            case 'session':
875
            case 'user':
876
            case 'skill':
877
                break;
878
        }
879
880
        return $types;
881
    }
882
883
    /**
884
     * Add elements to a form.
885
     *
886
     * @param FormValidator $form                            The form object to which to attach this element
887
     * @param int           $itemId                          The item (course, user, session, etc) this extra_field is linked to
888
     * @param array         $exclude                         Variables of extra field to exclude
889
     * @param bool          $filter                          Whether to get only the fields with the "filter" flag set to 1 (true)
890
     *                                                       or not (false)
891
     * @param bool          $useTagAsSelect                  Whether to show tag fields as select drop-down or not
892
     * @param array         $showOnlyTheseFields             Limit the extra fields shown to just the list given here
893
     * @param array         $orderFields                     An array containing the names of the fields shown, in the right order
894
     * @param array         $extraData
895
     * @param bool          $orderDependingDefaults
896
     * @param bool          $adminPermissions
897
     * @param array         $separateExtraMultipleSelect
898
     * @param array         $customLabelsExtraMultipleSelect
899
     * @param bool          $addEmptyOptionSelects
900
     * @param array         $introductionTextList
901
     * @param array         $requiredFields
902
     * @param bool          $hideGeoLocalizationDetails
903
     *
904
     * @throws Exception
905
     *
906
     * @return array|bool If relevant, returns a one-element array with JS code to be added to the page HTML headers.
907
     *                    Returns false if the form object was not given
908
     */
909
    public function addElements(
910
        $form,
911
        $itemId = 0,
912
        $exclude = [],
913
        $filter = false,
914
        $useTagAsSelect = false,
915
        $showOnlyTheseFields = [],
916
        $orderFields = [],
917
        $extraData = [],
918
        $orderDependingDefaults = false,
919
        $adminPermissions = false,
920
        $separateExtraMultipleSelect = [],
921
        $customLabelsExtraMultipleSelect = [],
922
        $addEmptyOptionSelects = false,
923
        $introductionTextList = [],
924
        $requiredFields = [],
925
        $hideGeoLocalizationDetails = false,
926
        $help = false
927
    ) {
928
        if (empty($form)) {
929
            return false;
930
        }
931
932
        $itemId = (int) $itemId;
933
        $form->addHidden('item_id', $itemId);
934
935
        if (empty($extraData)) {
936
            if (!empty($itemId)) {
937
                $extraData = self::get_handler_extra_data($itemId);
0 ignored issues
show
Bug Best Practice introduced by
The method ExtraField::get_handler_extra_data() is not static, but was called statically. ( Ignorable by Annotation )

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

937
                /** @scrutinizer ignore-call */ 
938
                $extraData = self::get_handler_extra_data($itemId);
Loading history...
938
                if ($form) {
0 ignored issues
show
introduced by
$form is of type FormValidator, thus it always evaluated to true.
Loading history...
939
                    if (!empty($showOnlyTheseFields)) {
940
                        $setData = [];
941
                        foreach ($showOnlyTheseFields as $variable) {
942
                            $extraName = 'extra_'.$variable;
943
                            if (in_array($extraName, array_keys($extraData))) {
944
                                $setData[$extraName] = $extraData[$extraName];
945
                            }
946
                        }
947
                        $form->setDefaults($setData);
948
                    } else {
949
                        $form->setDefaults($extraData);
950
                    }
951
                }
952
            }
953
        }
954
955
        $conditions = [];
956
        if ($filter) {
957
            $conditions = ['filter = ?' => 1];
958
        }
959
960
        $extraFields = $this->get_all($conditions, 'option_order');
961
        $extra = $this->set_extra_fields_in_form(
962
            $form,
963
            $extraData,
964
            $adminPermissions,
965
            $extraFields,
966
            $itemId,
967
            $exclude,
968
            $useTagAsSelect,
969
            $showOnlyTheseFields,
970
            $orderFields,
971
            $orderDependingDefaults,
972
            $separateExtraMultipleSelect,
973
            $customLabelsExtraMultipleSelect,
974
            $addEmptyOptionSelects,
975
            $introductionTextList,
976
            $hideGeoLocalizationDetails,
977
            $help
978
        );
979
980
        if (!empty($requiredFields)) {
981
            /** @var HTML_QuickForm_input $element */
982
            foreach ($form->getElements() as $element) {
983
                $name = str_replace('extra_', '', $element->getName());
984
                if (in_array($name, $requiredFields)) {
985
                    $form->setRequired($element);
986
                }
987
            }
988
        }
989
990
        return $extra;
991
    }
992
993
    /**
994
     * Return an array of all the extra fields available for this item.
995
     *
996
     * @param int $itemId (session_id, question_id, course id)
997
     *
998
     * @return array
999
     */
1000
    public function get_handler_extra_data($itemId)
1001
    {
1002
        if (empty($itemId)) {
1003
            return [];
1004
        }
1005
1006
        $extra_data = [];
1007
        $fields = $this->get_all();
1008
        $field_values = new ExtraFieldValue($this->type);
1009
1010
        if (!empty($fields)) {
1011
            foreach ($fields as $field) {
1012
                $field_value = $field_values->get_values_by_handler_and_field_id(
1013
                    $itemId,
1014
                    $field['id']
1015
                );
1016
1017
                if (self::FIELD_TYPE_TAG == $field['field_type']) {
1018
                    $tags = UserManager::get_user_tags_to_string(
1019
                        $itemId,
1020
                        $field['id'],
1021
                        false
1022
                    );
1023
                    $extra_data['extra_'.$field['variable']] = $tags;
1024
1025
                    continue;
1026
                }
1027
1028
                if ($field_value) {
1029
                    $variable = $field['variable'];
1030
                    $field_value = $field_value['value'];
1031
                    switch ($field['field_type']) {
1032
                        case self::FIELD_TYPE_TAG:
1033
                            $tags = UserManager::get_user_tags_to_string(
1034
                                $itemId,
1035
                                $field['id'],
1036
                                false
1037
                            );
1038
1039
                            $extra_data['extra_'.$field['variable']] = $tags;
1040
                            break;
1041
                        case self::FIELD_TYPE_DOUBLE_SELECT:
1042
                        case self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
1043
                            $selected_options = explode('::', $field_value);
1044
                            $firstOption = isset($selected_options[0]) ? $selected_options[0] : '';
1045
                            $secondOption = isset($selected_options[1]) ? $selected_options[1] : '';
1046
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $firstOption;
1047
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable'].'_second'] = $secondOption;
1048
1049
                            break;
1050
                        case self::FIELD_TYPE_SELECT_MULTIPLE:
1051
                            $field_value = explode(';', $field_value);
1052
                            $extra_data['extra_'.$field['variable']] = $field_value;
1053
                            break;
1054
                        case self::FIELD_TYPE_RADIO:
1055
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $field_value;
1056
                            break;
1057
                        case self::FIELD_TYPE_TRIPLE_SELECT:
1058
                            list($level1, $level2, $level3) = explode(';', $field_value);
1059
1060
                            $extra_data["extra_$variable"]["extra_$variable"] = $level1;
1061
                            $extra_data["extra_$variable"]["extra_{$variable}_second"] = $level2;
1062
                            $extra_data["extra_$variable"]["extra_{$variable}_third"] = $level3;
1063
                            break;
1064
                        default:
1065
                            $extra_data['extra_'.$field['variable']] = $field_value;
1066
                            break;
1067
                    }
1068
                } else {
1069
                    // Set default values
1070
                    if (isset($field['field_default_value']) &&
1071
                        !empty($field['field_default_value'])
1072
                    ) {
1073
                        $extra_data['extra_'.$field['variable']] = $field['field_default_value'];
1074
                    }
1075
                }
1076
            }
1077
        }
1078
1079
        return $extra_data;
1080
    }
1081
1082
    /**
1083
     * @param string $type
1084
     *
1085
     * @return array
1086
     */
1087
    public function get_all_extra_field_by_type($type)
1088
    {
1089
        // all the information of the field
1090
        $sql = "SELECT * FROM {$this->table}
1091
                WHERE
1092
                    field_type = '".Database::escape_string($type)."' AND
1093
                    extra_field_type = $this->extraFieldType
1094
                ";
1095
        $result = Database::query($sql);
1096
1097
        $return = [];
1098
        while ($row = Database::fetch_array($result)) {
1099
            $return[] = $row['id'];
1100
        }
1101
1102
        return $return;
1103
    }
1104
1105
    /**
1106
     * @return array
1107
     */
1108
    public function get_field_types()
1109
    {
1110
        return $this->get_extra_fields_by_handler($this->type);
1111
    }
1112
1113
    /**
1114
     * @param int $id
1115
     */
1116
    public function get_field_type_by_id($id)
1117
    {
1118
        $types = $this->get_field_types();
1119
        if (isset($types[$id])) {
1120
            return $types[$id];
1121
        }
1122
1123
        return null;
1124
    }
1125
1126
    /**
1127
     * @param array $params
1128
     *
1129
     * @return array
1130
     */
1131
    public function clean_parameters($params)
1132
    {
1133
        if (!isset($params['variable']) || empty($params['variable'])) {
1134
            $params['variable'] = $params['display_text'];
1135
        }
1136
1137
        $params['variable'] = trim(strtolower(str_replace(' ', '_', $params['variable'])));
1138
1139
        if (!isset($params['field_order'])) {
1140
            $max_order = self::get_max_field_order();
0 ignored issues
show
Bug Best Practice introduced by
The method ExtraField::get_max_field_order() is not static, but was called statically. ( Ignorable by Annotation )

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

1140
            /** @scrutinizer ignore-call */ 
1141
            $max_order = self::get_max_field_order();
Loading history...
1141
            $params['field_order'] = $max_order;
1142
        } else {
1143
            $params['field_order'] = (int) $params['field_order'];
1144
        }
1145
1146
        return $params;
1147
    }
1148
1149
    /**
1150
     * @param array $params
1151
     * @param bool  $show_query
1152
     *
1153
     * @return int|bool
1154
     */
1155
    public function save($params, $show_query = false)
1156
    {
1157
        $fieldInfo = self::get_handler_field_info_by_field_variable($params['variable']);
0 ignored issues
show
Bug Best Practice introduced by
The method ExtraField::get_handler_...nfo_by_field_variable() is not static, but was called statically. ( Ignorable by Annotation )

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

1157
        /** @scrutinizer ignore-call */ 
1158
        $fieldInfo = self::get_handler_field_info_by_field_variable($params['variable']);
Loading history...
1158
        $params = $this->clean_parameters($params);
1159
        $params['extra_field_type'] = $this->extraFieldType;
1160
1161
        if ($fieldInfo) {
1162
            return $fieldInfo['id'];
1163
        } else {
1164
            $id = parent::save($params, $show_query);
1165
            if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1166
                $fieldOption = new ExtraFieldOption($this->type);
1167
                $params['field_id'] = $id;
1168
                $fieldOption->save($params);
1169
            }
1170
1171
            return $id;
1172
        }
1173
    }
1174
1175
    /**
1176
     * {@inheritdoc}
1177
     */
1178
    public function update($params, $showQuery = false)
1179
    {
1180
        $params = $this->clean_parameters($params);
1181
        if (isset($params['id'])) {
1182
            $fieldOption = new ExtraFieldOption($this->type);
1183
            $params['field_id'] = $params['id'];
1184
            if (empty($params['field_type'])) {
1185
                $params['field_type'] = $this->type;
1186
            }
1187
            $fieldOption->save($params, $showQuery);
1188
        }
1189
1190
        return parent::update($params, $showQuery);
1191
    }
1192
1193
    /**
1194
     * @param $id
1195
     *
1196
     * @return bool
1197
     */
1198
    public function delete($id)
1199
    {
1200
        $em = Database::getManager();
1201
        $items = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findBy(['field' => $id]);
1202
        if ($items) {
1203
            foreach ($items as $item) {
1204
                $em->remove($item);
1205
            }
1206
            $em->flush();
1207
        }
1208
        $field_option = new ExtraFieldOption($this->type);
1209
        $field_option->delete_all_options_by_field_id($id);
1210
1211
        $session_field_values = new ExtraFieldValue($this->type);
1212
        $session_field_values->delete_all_values_by_field_id($id);
1213
1214
        return parent::delete($id);
1215
    }
1216
1217
    /**
1218
     * Add an element that matches the given extra field to the given $form object.
1219
     *
1220
     * @param FormValidator $form                The form these fields are to be attached to
1221
     * @param array         $extraData
1222
     * @param bool          $adminPermissions    Whether the display is considered without edition limits (true) or not (false)
1223
     * @param array         $extra
1224
     * @param int           $itemId              The item (course, user, session, etc) this extra_field is attached to
1225
     * @param array         $exclude             Extra fields to be skipped, by textual ID
1226
     * @param bool          $useTagAsSelect      Whether to show tag fields as select drop-down or not
1227
     * @param array         $showOnlyTheseFields Limit the extra fields shown to just the list given here
1228
     * @param array         $orderFields         An array containing the names of the fields shown, in the right order
1229
     *
1230
     * @throws Exception
1231
     *
1232
     * @return array If relevant, returns a one-element array with JS code to be added to the page HTML headers
1233
     */
1234
    public function set_extra_fields_in_form(
1235
        $form,
1236
        $extraData,
1237
        $admin_permissions = false,
1238
        $extra = [],
1239
        $itemId = null,
1240
        $exclude = [],
1241
        $useTagAsSelect = false,
1242
        $showOnlyTheseFields = [],
1243
        $orderFields = [],
1244
        $orderDependingDefaults = false,
1245
        $separateExtraMultipleSelect = [],
1246
        $customLabelsExtraMultipleSelect = [],
1247
        $addEmptyOptionSelects = false,
1248
        $introductionTextList = [],
1249
        $hideGeoLocalizationDetails = false,
1250
        $help = false
1251
    ) {
1252
        $type = $this->type;
1253
        $jquery_ready_content = '';
1254
1255
        if (!empty($extra)) {
1256
            $newOrder = [];
1257
            if (!empty($orderFields)) {
1258
                foreach ($orderFields as $order) {
1259
                    foreach ($extra as $field_details) {
1260
                        if ($order === $field_details['variable']) {
1261
                            $newOrder[] = $field_details;
1262
                        }
1263
                    }
1264
                }
1265
                $extra = $newOrder;
1266
            }
1267
1268
            foreach ($extra as $field_details) {
1269
                if (!empty($showOnlyTheseFields)) {
1270
                    if (!in_array($field_details['variable'], $showOnlyTheseFields)) {
1271
                        continue;
1272
                    }
1273
                }
1274
1275
                // Getting default value id if is set
1276
                $defaultValueId = null;
1277
                if (isset($field_details['options']) && !empty($field_details['options'])) {
1278
                    $valueToFind = null;
1279
                    if (isset($field_details['field_default_value'])) {
1280
                        $valueToFind = $field_details['field_default_value'];
1281
                    }
1282
                    // If a value is found we override the default value
1283
                    if (isset($extraData['extra_'.$field_details['variable']])) {
1284
                        $valueToFind = $extraData['extra_'.$field_details['variable']];
1285
                    }
1286
1287
                    foreach ($field_details['options'] as $option) {
1288
                        if ($option['option_value'] == $valueToFind) {
1289
                            $defaultValueId = $option['id'];
1290
                        }
1291
                    }
1292
                }
1293
1294
                if (!$admin_permissions) {
1295
                    if ($field_details['visible_to_self'] == 0) {
1296
                        continue;
1297
                    }
1298
1299
                    if (in_array($field_details['variable'], $exclude)) {
1300
                        continue;
1301
                    }
1302
                }
1303
1304
                if (!empty($introductionTextList) &&
1305
                    in_array($field_details['variable'], array_keys($introductionTextList))
1306
                ) {
1307
                    $form->addHtml($introductionTextList[$field_details['variable']]);
1308
                }
1309
1310
                $freezeElement = false;
1311
                if (!$admin_permissions) {
1312
                    $freezeElement = $field_details['visible_to_self'] == 0 || $field_details['changeable'] == 0;
1313
                }
1314
1315
                $translatedDisplayText = get_lang($field_details['display_text'], true);
1316
                $translatedDisplayHelpText = '';
1317
                if ($help) {
1318
                    $translatedDisplayHelpText .= get_lang($field_details['display_text'].'Help');
1319
                }
1320
                $label = [$translatedDisplayText, $translatedDisplayHelpText];
1321
                // Ofaj
1322
                if (!empty($translatedDisplayText)) {
1323
                    //$field_details['display_text'] = $label;
1324
                }
1325
1326
                switch ($field_details['field_type']) {
1327
                    case self::FIELD_TYPE_TEXT:
1328
                        $form->addElement(
1329
                            'text',
1330
                            'extra_'.$field_details['variable'],
1331
                            $field_details['display_text'],
1332
                            [
1333
                                'id' => 'extra_'.$field_details['variable'],
1334
                            ]
1335
                        );
1336
                        $form->applyFilter(
1337
                            'extra_'.$field_details['variable'],
1338
                            'stripslashes'
1339
                        );
1340
                        $form->applyFilter(
1341
                            'extra_'.$field_details['variable'],
1342
                            'trim'
1343
                        );
1344
                        if ($freezeElement) {
1345
                            $form->freeze('extra_'.$field_details['variable']);
1346
                        }
1347
                        break;
1348
                    case self::FIELD_TYPE_TEXTAREA:
1349
                        $form->addHtmlEditor(
1350
                            'extra_'.$field_details['variable'],
1351
                            $field_details['display_text'],
1352
                            false,
1353
                            false,
1354
                            [
1355
                                'ToolbarSet' => 'Profile',
1356
                                'Width' => '100%',
1357
                                'Height' => '130',
1358
                                'id' => 'extra_'.$field_details['variable'],
1359
                            ]
1360
                        );
1361
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1362
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1363
                        if ($freezeElement) {
1364
                            $form->freeze('extra_'.$field_details['variable']);
1365
                        }
1366
                        break;
1367
                    case self::FIELD_TYPE_RADIO:
1368
                        $group = [];
1369
                        if (isset($field_details['options']) &&
1370
                            !empty($field_details['options'])
1371
                        ) {
1372
                            foreach ($field_details['options'] as $option_details) {
1373
                                $options[$option_details['option_value']] = $option_details['display_text'];
1374
                                $group[] = $form->createElement(
1375
                                    'radio',
1376
                                    'extra_'.$field_details['variable'],
1377
                                    $option_details['option_value'],
1378
                                    $option_details['display_text'].'<br />',
1379
                                    $option_details['option_value']
1380
                                );
1381
                            }
1382
                        }
1383
                        $form->addGroup(
1384
                            $group,
1385
                            'extra_'.$field_details['variable'],
1386
                            $field_details['display_text']
1387
                        );
1388
                        if ($freezeElement) {
1389
                            $form->freeze('extra_'.$field_details['variable']);
1390
                        }
1391
                        break;
1392
                    case self::FIELD_TYPE_CHECKBOX:
1393
                        $group = [];
1394
                        if (isset($field_details['options']) &&
1395
                            !empty($field_details['options'])
1396
                        ) {
1397
                            foreach ($field_details['options'] as $option_details) {
1398
                                $options[$option_details['option_value']] = $option_details['display_text'];
1399
                                $group[] = $form->createElement(
1400
                                    'checkbox',
1401
                                    'extra_'.$field_details['variable'],
1402
                                    $option_details['option_value'],
1403
                                    $option_details['display_text'].'<br />',
1404
                                    $option_details['option_value']
1405
                                );
1406
                            }
1407
                        } else {
1408
                            $fieldVariable = "extra_{$field_details['variable']}";
1409
                            $checkboxAttributes = [];
1410
                            if (is_array($extraData) &&
1411
                                array_key_exists($fieldVariable, $extraData)
1412
                            ) {
1413
                                if (!empty($extraData[$fieldVariable])) {
1414
                                    $checkboxAttributes['checked'] = 1;
1415
                                }
1416
                            }
1417
1418
                            if (empty($checkboxAttributes) &&
1419
                                isset($field_details['default_value']) && empty($extraData)) {
1420
                                if ($field_details['default_value'] == 1) {
1421
                                    $checkboxAttributes['checked'] = 1;
1422
                                }
1423
                            }
1424
1425
                            // We assume that is a switch on/off with 1 and 0 as values
1426
                            $group[] = $form->createElement(
1427
                                'checkbox',
1428
                                'extra_'.$field_details['variable'],
1429
                                null,
1430
                                get_lang('Yes'),
1431
                                $checkboxAttributes
1432
                            );
1433
                        }
1434
1435
                        $form->addGroup(
1436
                            $group,
1437
                            'extra_'.$field_details['variable'],
1438
                            $field_details['display_text']
1439
                        );
1440
                        if ($freezeElement) {
1441
                            $form->freeze('extra_'.$field_details['variable']);
1442
                        }
1443
                        break;
1444
                    case self::FIELD_TYPE_SELECT:
1445
                        $get_lang_variables = false;
1446
                        if (in_array(
1447
                            $field_details['variable'],
1448
                            ['mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message']
1449
                        )
1450
                        ) {
1451
                            $get_lang_variables = true;
1452
                        }
1453
1454
                        // Get extra field workflow
1455
                        $userInfo = api_get_user_info();
1456
                        $addOptions = [];
1457
                        $optionsExists = false;
1458
                        global $app;
1459
                        // Check if exist $app['orm.em'] object
1460
                        if (isset($app['orm.em']) && is_object($app['orm.em'])) {
1461
                            $optionsExists = $app['orm.em']
1462
                                ->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
1463
                                ->findOneBy(['fieldId' => $field_details['id']]);
1464
                        }
1465
1466
                        if ($optionsExists) {
1467
                            if (isset($userInfo['status']) && !empty($userInfo['status'])) {
1468
                                $fieldWorkFlow = $app['orm.em']->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
1469
                                    ->findBy(
1470
                                        [
1471
                                            'fieldId' => $field_details['id'],
1472
                                            'relatedFieldOptionId' => $defaultValueId,
1473
                                            'roleId' => $userInfo['status'],
1474
                                        ]
1475
                                    );
1476
                                foreach ($fieldWorkFlow as $item) {
1477
                                    $addOptions[] = $item->getFieldOptionId();
1478
                                }
1479
                            }
1480
                        }
1481
1482
                        $options = [];
1483
                        if (empty($defaultValueId)) {
1484
                            $options[''] = get_lang('SelectAnOption');
1485
                        }
1486
1487
                        $optionList = [];
1488
                        if (!empty($field_details['options'])) {
1489
                            foreach ($field_details['options'] as $option_details) {
1490
                                $optionList[$option_details['id']] = $option_details;
1491
                                if ($get_lang_variables) {
1492
                                    $options[$option_details['option_value']] = $option_details['display_text'];
1493
                                } else {
1494
                                    if ($optionsExists) {
1495
                                        // Adding always the default value
1496
                                        if ($option_details['id'] == $defaultValueId) {
1497
                                            $options[$option_details['option_value']] = $option_details['display_text'];
1498
                                        } else {
1499
                                            if (isset($addOptions) && !empty($addOptions)) {
1500
                                                // Parsing filters
1501
                                                if (in_array($option_details['id'], $addOptions)) {
1502
                                                    $options[$option_details['option_value']] = $option_details['display_text'];
1503
                                                }
1504
                                            }
1505
                                        }
1506
                                    } else {
1507
                                        // Normal behaviour
1508
                                        $options[$option_details['option_value']] = $option_details['display_text'];
1509
                                    }
1510
                                }
1511
                            }
1512
1513
                            // Setting priority message
1514
                            if (isset($optionList[$defaultValueId]) &&
1515
                                isset($optionList[$defaultValueId]['priority'])
1516
                            ) {
1517
                                if (!empty($optionList[$defaultValueId]['priority'])) {
1518
                                    $priorityId = $optionList[$defaultValueId]['priority'];
1519
                                    $option = new ExtraFieldOption($this->type);
1520
                                    $messageType = $option->getPriorityMessageType($priorityId);
1521
                                    $form->addElement(
1522
                                        'label',
1523
                                        null,
1524
                                        Display::return_message(
1525
                                            $optionList[$defaultValueId]['priority_message'],
1526
                                            $messageType
1527
                                        )
1528
                                    );
1529
                                }
1530
                            }
1531
                        }
1532
1533
                        // chzn-select doesn't work for sessions??
1534
                        $form->addElement(
1535
                            'select',
1536
                            'extra_'.$field_details['variable'],
1537
                            $field_details['display_text'],
1538
                            $options,
1539
                            ['id' => 'extra_'.$field_details['variable']]
1540
                        );
1541
1542
                        if (!$admin_permissions) {
1543
                            if ($field_details['visible_to_self'] == 0) {
1544
                                $form->freeze('extra_'.$field_details['variable']);
1545
                            }
1546
                        }
1547
                        break;
1548
                    case self::FIELD_TYPE_SELECT_MULTIPLE:
1549
                        $options = [];
1550
1551
                        if (empty($defaultValueId)) {
1552
                            $options[''] = get_lang('SelectAnOption');
1553
                        }
1554
1555
                        foreach ($field_details['options'] as $option_id => $option_details) {
1556
                            $options[$option_details['option_value']] = $option_details['display_text'];
1557
                        }
1558
1559
                        if ($orderDependingDefaults) {
1560
                            $defaultOptions = $extraData['extra_'.$field_details['variable']];
1561
                            if (!empty($defaultOptions)) {
1562
                                $firstList = [];
1563
                                if ($addEmptyOptionSelects) {
1564
                                    $firstList[] = '';
1565
                                }
1566
                                foreach ($defaultOptions as $key) {
1567
                                    if (isset($options[$key])) {
1568
                                        $firstList[$key] = $options[$key];
1569
                                    }
1570
                                }
1571
                                if (!empty($firstList)) {
1572
                                    $options = array_merge($firstList, $options);
1573
                                }
1574
                            } else {
1575
                                $firstList = [];
1576
                                if ($addEmptyOptionSelects) {
1577
                                    $firstList[] = '&nbsp;';
1578
                                    $options = array_merge($firstList, $options);
1579
                                }
1580
                            }
1581
                        }
1582
1583
                        // OFAJ
1584
                        $separateValue = 0;
1585
                        if (isset($separateExtraMultipleSelect[$field_details['variable']])) {
1586
                            $separateValue = $separateExtraMultipleSelect[$field_details['variable']];
1587
                        }
1588
1589
                        if ($separateValue > 0) {
1590
                            for ($i = 0; $i < $separateValue; $i++) {
1591
                                $form->addElement(
1592
                                    'select',
1593
                                    'extra_'.$field_details['variable'].'['.$i.']',
1594
                                    $customLabelsExtraMultipleSelect[$field_details['variable']][$i], //$field_details['display_text'],
1595
                                    $options,
1596
                                    ['id' => 'extra_'.$field_details['variable'].'_'.$i]
1597
                                );
1598
                            }
1599
                        } else {
1600
                            // Ofaj
1601
                            $attributes = ['multiple' => 'multiple', 'id' => 'extra_'.$field_details['variable']];
1602
                            $chosenSelect = [
1603
                                'ecouter',
1604
                                'lire',
1605
                                'participer_a_une_conversation',
1606
                                's_exprimer_oralement_en_continu',
1607
                                'ecrire',
1608
                            ];
1609
1610
                            if (in_array($field_details['variable'], $chosenSelect)) {
1611
                                $attributes['select_chosen'] = true;
1612
                            }
1613
1614
                            // default behaviour
1615
                            $form->addElement(
1616
                                'select',
1617
                                'extra_'.$field_details['variable'],
1618
                                $field_details['display_text'],
1619
                                $options,
1620
                                $attributes
1621
                            );
1622
                        }
1623
1624
                        if (!$admin_permissions) {
1625
                            if ($field_details['visible_to_self'] == 0) {
1626
                                $form->freeze('extra_'.$field_details['variable']);
1627
                            }
1628
                        }
1629
                        break;
1630
                    case self::FIELD_TYPE_DATE:
1631
                        $form->addDatePicker('extra_'.$field_details['variable'], $field_details['display_text']);
1632
                        if ($freezeElement) {
1633
                            $form->freeze('extra_'.$field_details['variable']);
1634
                        }
1635
                        break;
1636
                    case self::FIELD_TYPE_DATETIME:
1637
                        $form->addDateTimePicker(
1638
                            'extra_'.$field_details['variable'],
1639
                            $field_details['display_text']
1640
                        );
1641
1642
                        $defaults['extra_'.$field_details['variable']] = api_get_local_time();
1643
                        if (!isset($form->_defaultValues['extra_'.$field_details['variable']])) {
1644
                            $form->setDefaults($defaults);
1645
                        }
1646
                        if ($freezeElement) {
1647
                            $form->freeze('extra_'.$field_details['variable']);
1648
                        }
1649
                        break;
1650
                    case self::FIELD_TYPE_DOUBLE_SELECT:
1651
                        $first_select_id = 'first_extra_'.$field_details['variable'];
1652
                        $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
1653
1654
                        $jquery_ready_content .= '
1655
                        $("#'.$first_select_id.'").on("change", function() {
1656
                            var id = $(this).val();
1657
                            if (id) {
1658
                                $.ajax({
1659
                                    url: "'.$url.'&a=get_second_select_options",
1660
                                    dataType: "json",
1661
                                    data: "type='.$type.'&field_id='.$field_details['id'].'&option_value_id="+id,
1662
                                    success: function(data) {
1663
                                        $("#second_extra_'.$field_details['variable'].'").empty();
1664
                                        $.each(data, function(index, value) {
1665
                                            $("#second_extra_'.$field_details['variable'].'").append($("<option/>", {
1666
                                                value: index,
1667
                                                text: value
1668
                                            }));
1669
                                        });
1670
                                        $("#second_extra_'.$field_details['variable'].'").selectpicker("refresh");
1671
                                    },
1672
                                });
1673
                            } else {
1674
                                $("#second_extra_'.$field_details['variable'].'").empty();
1675
                            }
1676
                        });';
1677
1678
                        $first_id = null;
1679
                        if (!empty($extraData)) {
1680
                            if (isset($extraData['extra_'.$field_details['variable']])) {
1681
                                $first_id = $extraData['extra_'.$field_details['variable']]['extra_'.$field_details['variable']];
1682
                            }
1683
                        }
1684
1685
                        $options = self::extra_field_double_select_convert_array_to_ordered_array(
1686
                            $field_details['options']
1687
                        );
1688
                        $values = ['' => get_lang('Select')];
1689
1690
                        $second_values = [];
1691
                        if (!empty($options)) {
1692
                            foreach ($options as $option) {
1693
                                foreach ($option as $sub_option) {
1694
                                    if ($sub_option['option_value'] == '0') {
1695
                                        $values[$sub_option['id']] = $sub_option['display_text'];
1696
                                    } else {
1697
                                        if ($first_id === $sub_option['option_value']) {
1698
                                            $second_values[$sub_option['id']] = $sub_option['display_text'];
1699
                                        }
1700
                                    }
1701
                                }
1702
                            }
1703
                        }
1704
                        $group = [];
1705
                        $group[] = $form->createElement(
1706
                            'select',
1707
                            'extra_'.$field_details['variable'],
1708
                            null,
1709
                            $values,
1710
                            ['id' => $first_select_id]
1711
                        );
1712
                        $group[] = $form->createElement(
1713
                            'select',
1714
                            'extra_'.$field_details['variable'].'_second',
1715
                            null,
1716
                            $second_values,
1717
                            ['id' => 'second_extra_'.$field_details['variable']]
1718
                        );
1719
                        $form->addGroup(
1720
                            $group,
1721
                            'extra_'.$field_details['variable'],
1722
                            $field_details['display_text']
1723
                        );
1724
1725
                        if (!$admin_permissions) {
1726
                            if ($field_details['visible_to_self'] == 0) {
1727
                                $form->freeze('extra_'.$field_details['variable']);
1728
                            }
1729
                        }
1730
                        break;
1731
                    case self::FIELD_TYPE_DIVIDER:
1732
                        $form->addHtml('
1733
                            <div class="form-group ">
1734
                                <div class="col-sm-12">
1735
                                    <div class="panel-separator">
1736
                                       <h4 id="'.$field_details['variable'].'" class="form-separator">'
1737
                                            .$field_details['display_text'].'
1738
                                       </h4>
1739
                                    </div>
1740
                                </div>
1741
                            </div>
1742
                        ');
1743
                        break;
1744
                    case self::FIELD_TYPE_TAG:
1745
                        $variable = $field_details['variable'];
1746
                        $field_id = $field_details['id'];
1747
                        $separateValue = 0;
1748
                        if (isset($separateExtraMultipleSelect[$field_details['variable']])) {
1749
                            $separateValue = $separateExtraMultipleSelect[$field_details['variable']];
1750
                        }
1751
1752
                        $selectedOptions = [];
1753
1754
                        if ($separateValue > 0) {
1755
                            $em = Database::getManager();
1756
                            $fieldTags = $em
1757
                                ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
1758
                                ->findBy(
1759
                                    [
1760
                                        'fieldId' => $field_id,
1761
                                        'itemId' => $itemId,
1762
                                    ]
1763
                                );
1764
                            // ofaj
1765
1766
                            for ($i = 0; $i < $separateValue; $i++) {
1767
                                $tagsSelect = $form->addElement(
1768
                                    'select',
1769
                                    'extra_'.$field_details['variable'].'['.$i.']',
1770
                                    $customLabelsExtraMultipleSelect[$field_details['variable']][$i], //$field_details['display_text'],
1771
                                    null,
1772
                                    ['id' => 'extra_'.$field_details['variable'].'_'.$i]
1773
                                );
1774
1775
                                if ($addEmptyOptionSelects) {
1776
                                    $tagsSelect->addOption(
1777
                                        '',
1778
                                        ''
1779
                                    );
1780
                                }
1781
1782
                                foreach ($fieldTags as $fieldTag) {
1783
                                    $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1784
1785
                                    if (empty($tag)) {
1786
                                        continue;
1787
                                    }
1788
1789
                                    $tagsSelect->addOption(
1790
                                        $tag->getTag(),
1791
                                        $tag->getTag()
1792
                                    );
1793
                                }
1794
                            }
1795
                        } else {
1796
                            $tagsSelect = $form->addSelect(
1797
                                "extra_{$field_details['variable']}",
1798
                                $field_details['display_text'],
1799
                                [],
1800
                                ['style' => 'width: 100%;']
1801
                            );
1802
1803
                            if ($useTagAsSelect === false) {
1804
                                $tagsSelect->setAttribute('class', null);
1805
                            }
1806
1807
                            $tagsSelect->setAttribute(
1808
                                'id',
1809
                                "extra_{$field_details['variable']}"
1810
                            );
1811
                            $tagsSelect->setMultiple(true);
1812
1813
                            $selectedOptions = [];
1814
                            if ($this->type === 'user') {
1815
                                // The magic should be here
1816
                                $user_tags = UserManager::get_user_tags(
1817
                                    $itemId,
1818
                                    $field_details['id']
1819
                                );
1820
1821
                                if (is_array($user_tags) && count($user_tags) > 0) {
1822
                                    foreach ($user_tags as $tag) {
1823
                                        if (empty($tag['tag'])) {
1824
                                            continue;
1825
                                        }
1826
                                        $tagsSelect->addOption(
1827
                                            $tag['tag'],
1828
                                            $tag['tag'],
1829
                                            [
1830
                                                'selected' => 'selected',
1831
                                                'class' => 'selected',
1832
                                            ]
1833
                                        );
1834
                                        $selectedOptions[] = $tag['tag'];
1835
                                    }
1836
                                }
1837
                                $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
1838
                            } else {
1839
                                $em = Database::getManager();
1840
                                $fieldTags = $em->getRepository(
1841
                                    'ChamiloCoreBundle:ExtraFieldRelTag'
1842
                                )
1843
                                ->findBy(
1844
                                    [
1845
                                        'fieldId' => $field_id,
1846
                                        'itemId' => $itemId,
1847
                                    ]
1848
                                );
1849
1850
                                /** @var ExtraFieldRelTag $fieldTag */
1851
                                foreach ($fieldTags as $fieldTag) {
1852
                                    /** @var Tag $tag */
1853
                                    $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1854
1855
                                    if (empty($tag)) {
1856
                                        continue;
1857
                                    }
1858
                                    $tagsSelect->addOption(
1859
                                        $tag->getTag(),
1860
                                        $tag->getTag()
1861
                                    );
1862
                                    $selectedOptions[] = $tag->getTag();
1863
                                }
1864
1865
                                if (!empty($extraData) && isset($extraData['extra_'.$field_details['variable']])) {
1866
                                    $data = $extraData['extra_'.$field_details['variable']];
1867
                                    if (!empty($data)) {
1868
                                        foreach ($data as $option) {
1869
                                            $tagsSelect->addOption(
1870
                                                $option,
1871
                                                $option
1872
                                            );
1873
                                        }
1874
                                    }
1875
                                }
1876
1877
                                if ($useTagAsSelect) {
1878
                                    $fieldTags = $em->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
1879
                                        ->findBy(
1880
                                            [
1881
                                                'fieldId' => $field_id,
1882
                                            ]
1883
                                        );
1884
                                    $tagsAdded = [];
1885
                                    foreach ($fieldTags as $fieldTag) {
1886
                                        $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1887
1888
                                        if (empty($tag)) {
1889
                                            continue;
1890
                                        }
1891
1892
                                        $tagText = $tag->getTag();
1893
1894
                                        if (in_array($tagText, $tagsAdded)) {
1895
                                            continue;
1896
                                        }
1897
1898
                                        $tagsSelect->addOption(
1899
                                            $tag->getTag(),
1900
                                            $tag->getTag(),
1901
                                            []
1902
                                        );
1903
1904
                                        $tagsAdded[] = $tagText;
1905
                                    }
1906
                                }
1907
                                $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php';
1908
                            }
1909
1910
                            $form->setDefaults(
1911
                                [
1912
                                    'extra_'.$field_details['variable'] => $selectedOptions,
1913
                                ]
1914
                            );
1915
1916
                            if ($useTagAsSelect == 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...
1917
                                $jquery_ready_content .= "
1918
                                    $('#extra_$variable').select2({
1919
                                        ajax: {
1920
                                            url: '$url?a=search_tags&field_id=$field_id&type={$this->type}',
1921
                                            processResults: function (data) {
1922
                                                return {
1923
                                                    results: data.items
1924
                                                }
1925
                                            }
1926
                                        },
1927
                                        cache: false,
1928
                                        tags: true,
1929
                                        tokenSeparators: [','],
1930
                                        placeholder: '".get_lang('StartToType')."'
1931
                                    });
1932
                                ";
1933
                            }
1934
                        }
1935
1936
                        break;
1937
                    case self::FIELD_TYPE_TIMEZONE:
1938
                        $form->addElement(
1939
                            'select',
1940
                            'extra_'.$field_details['variable'],
1941
                            $field_details['display_text'],
1942
                            api_get_timezones(),
1943
                            ''
1944
                        );
1945
                        if ($freezeElement) {
1946
                            $form->freeze('extra_'.$field_details['variable']);
1947
                        }
1948
                        break;
1949
                    case self::FIELD_TYPE_SOCIAL_PROFILE:
1950
                        // get the social network's favicon
1951
                        $extra_data_variable = isset($extraData['extra_'.$field_details['variable']])
1952
                            ? $extraData['extra_'.$field_details['variable']]
1953
                            : null;
1954
                        $field_default_value = isset($field_details['field_default_value'])
1955
                            ? $field_details['field_default_value']
1956
                            : null;
1957
                        $icon_path = UserManager::get_favicon_from_url(
1958
                            $extra_data_variable,
1959
                            $field_default_value
1960
                        );
1961
                        // special hack for hi5
1962
                        $leftpad = '1.7';
1963
                        $top = '0.4';
1964
                        $domain = parse_url($icon_path, PHP_URL_HOST);
1965
                        if ($domain == 'www.hi5.com' or $domain == 'hi5.com') {
1966
                            $leftpad = '3';
1967
                            $top = '0';
1968
                        }
1969
                        // print the input field
1970
                        $form->addElement(
1971
                            'text',
1972
                            'extra_'.$field_details['variable'],
1973
                            $field_details['display_text'],
1974
                            [
1975
                                'size' => 60,
1976
                                'size' => implode(
1977
                                    '; ',
1978
                                    [
1979
                                        "background-image: url('$icon_path')",
1980
                                        'background-repeat: no-repeat',
1981
                                        "background-position: 0.4em {$top}em",
1982
                                        "padding-left: {$leftpad}em",
1983
                                    ]
1984
                                ),
1985
                            ]
1986
                        );
1987
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1988
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1989
                        if ($freezeElement) {
1990
                            $form->freeze('extra_'.$field_details['variable']);
1991
                        }
1992
                        break;
1993
                    case self::FIELD_TYPE_MOBILE_PHONE_NUMBER:
1994
                        $form->addElement(
1995
                            'text',
1996
                            'extra_'.$field_details['variable'],
1997
                            $field_details['display_text']." (".get_lang('CountryDialCode').")",
1998
                            ['size' => 40, 'placeholder' => '(xx)xxxxxxxxx']
1999
                        );
2000
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2001
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
2002
                        $form->applyFilter('extra_'.$field_details['variable'], 'mobile_phone_number_filter');
2003
                        $form->addRule(
2004
                            'extra_'.$field_details['variable'],
2005
                            get_lang('MobilePhoneNumberWrong'),
2006
                            'mobile_phone_number'
2007
                        );
2008
                        if ($freezeElement) {
2009
                            $form->freeze('extra_'.$field_details['variable']);
2010
                        }
2011
                        break;
2012
                    case self::FIELD_TYPE_INTEGER:
2013
                        $form->addElement(
2014
                            'number',
2015
                            'extra_'.$field_details['variable'],
2016
                            $field_details['display_text'],
2017
                            ['class' => 'span1', 'step' => 1]
2018
                        );
2019
2020
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2021
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
2022
                        $form->applyFilter('extra_'.$field_details['variable'], 'intval');
2023
2024
                        if ($freezeElement) {
2025
                            $form->freeze('extra_'.$field_details['variable']);
2026
                        }
2027
                        break;
2028
                    case self::FIELD_TYPE_FILE_IMAGE:
2029
                        $fieldVariable = "extra_{$field_details['variable']}";
2030
                        $fieldTexts = [
2031
                            $field_details['display_text'],
2032
                        ];
2033
2034
                        if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
2035
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH).$extraData[$fieldVariable])) {
2036
                                $fieldTexts[] = Display::img(
2037
                                    api_get_path(WEB_UPLOAD_PATH).$extraData[$fieldVariable],
2038
                                    $field_details['display_text'],
2039
                                    ['width' => '300']
2040
                                );
2041
                            }
2042
                        }
2043
2044
                        if ($fieldTexts[0] === 'Image') {
2045
                            $fieldTexts[0] = get_lang($fieldTexts[0]);
2046
                        }
2047
2048
                        $form->addFile(
2049
                            $fieldVariable,
2050
                            $fieldTexts,
2051
                            ['accept' => 'image/*', 'id' => 'extra_image', 'crop_image' => 'true']
2052
                        );
2053
2054
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2055
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
2056
2057
                        $allowedPictureTypes = ['jpg', 'jpeg', 'png', 'gif'];
2058
                        $form->addRule(
2059
                            'extra_'.$field_details['variable'],
2060
                            get_lang('OnlyImagesAllowed').' ('.implode(',', $allowedPictureTypes).')',
2061
                            'filetype',
2062
                            $allowedPictureTypes
2063
                        );
2064
2065
                        if ($freezeElement) {
2066
                            $form->freeze('extra_'.$field_details['variable']);
2067
                        }
2068
                        break;
2069
                    case self::FIELD_TYPE_FLOAT:
2070
                        $form->addElement(
2071
                            'number',
2072
                            'extra_'.$field_details['variable'],
2073
                            $field_details['display_text'],
2074
                            ['class' => 'span1', 'step' => '0.01']
2075
                        );
2076
2077
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2078
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
2079
                        $form->applyFilter('extra_'.$field_details['variable'], 'floatval');
2080
2081
                        if ($freezeElement) {
2082
                            $form->freeze('extra_'.$field_details['variable']);
2083
                        }
2084
                        break;
2085
                    case self::FIELD_TYPE_FILE:
2086
                        $fieldVariable = "extra_{$field_details['variable']}";
2087
                        $fieldTexts = [
2088
                            $field_details['display_text'],
2089
                        ];
2090
2091
                        if (is_array($extraData) &&
2092
                            array_key_exists($fieldVariable, $extraData)
2093
                        ) {
2094
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH).$extraData[$fieldVariable])) {
2095
                                $linkToDelete = '';
2096
                                $divItemId = $field_details['variable'];
2097
                                if (api_is_platform_admin()) {
2098
                                    $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?type='.$this->type;
2099
                                    $url .= '&a=delete_file&field_id='.$field_details['id'].'&item_id='.$itemId;
2100
2101
                                    $deleteId = $field_details['variable'].'_delete';
2102
                                    $form->addHtml("
2103
                                        <script>
2104
                                            $(function() {
2105
                                                $('#".$deleteId."').on('click', function() {
2106
                                                    $.ajax({
2107
                                                        type: 'GET',
2108
                                                        url: '".$url."',
2109
                                                        success: function(result) {
2110
                                                            if (result == 1) {
2111
                                                                $('#".$divItemId."').html('".get_lang('Deleted')."');
2112
                                                            }
2113
                                                        }
2114
                                                    });
2115
                                                });
2116
                                            });
2117
                                        </script>
2118
                                    ");
2119
2120
                                    $linkToDelete = '&nbsp;'.Display::url(
2121
                                        Display::return_icon('delete.png', get_lang('Delete')),
2122
                                        'javascript:void(0)',
2123
                                        ['id' => $deleteId]
2124
                                    );
2125
                                }
2126
                                $fieldTexts[] = '<div id="'.$divItemId.'">'.Display::url(
2127
                                    basename($extraData[$fieldVariable]),
2128
                                    api_get_path(WEB_UPLOAD_PATH).$extraData[$fieldVariable],
2129
                                    [
2130
                                        'title' => $field_details['display_text'],
2131
                                        'target' => '_blank',
2132
                                    ]
2133
                                ).$linkToDelete.'</div>';
2134
                            }
2135
                        }
2136
2137
                        $form->addElement(
2138
                            'file',
2139
                            $fieldVariable,
2140
                            $fieldTexts,
2141
                            []
2142
                        );
2143
2144
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2145
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
2146
2147
                        if ($freezeElement) {
2148
                            $form->freeze('extra_'.$field_details['variable']);
2149
                        }
2150
                        break;
2151
                    case self::FIELD_TYPE_VIDEO_URL:
2152
                        $form->addUrl(
2153
                            "extra_{$field_details['variable']}",
2154
                            $field_details['display_text'],
2155
                            false,
2156
                            ['placeholder' => 'https://']
2157
                        );
2158
                        if ($freezeElement) {
2159
                            $form->freeze('extra_'.$field_details['variable']);
2160
                        }
2161
                        break;
2162
                    case self::FIELD_TYPE_LETTERS_ONLY:
2163
                        $form->addTextLettersOnly(
2164
                            "extra_{$field_details['variable']}",
2165
                            $field_details['display_text']
2166
                        );
2167
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2168
2169
                        if ($freezeElement) {
2170
                            $form->freeze('extra_'.$field_details['variable']);
2171
                        }
2172
                        break;
2173
                    case self::FIELD_TYPE_ALPHANUMERIC:
2174
                        $form->addTextAlphanumeric(
2175
                            "extra_{$field_details['variable']}",
2176
                            $field_details['display_text']
2177
                        );
2178
                        $form->applyFilter(
2179
                            'extra_'.$field_details['variable'],
2180
                            'stripslashes'
2181
                        );
2182
                        if ($freezeElement) {
2183
                            $form->freeze('extra_'.$field_details['variable']);
2184
                        }
2185
                        break;
2186
                    case self::FIELD_TYPE_LETTERS_SPACE:
2187
                        $form->addTextLettersAndSpaces(
2188
                            "extra_{$field_details['variable']}",
2189
                            $field_details['display_text']
2190
                        );
2191
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2192
2193
                        if ($freezeElement) {
2194
                            $form->freeze('extra_'.$field_details['variable']);
2195
                        }
2196
                        break;
2197
                    case self::FIELD_TYPE_ALPHANUMERIC_SPACE:
2198
                        $form->addTextAlphanumericAndSpaces(
2199
                            "extra_{$field_details['variable']}",
2200
                            $field_details['display_text']
2201
                        );
2202
                        $form->applyFilter(
2203
                            'extra_'.$field_details['variable'],
2204
                            'stripslashes'
2205
                        );
2206
                        if ($freezeElement) {
2207
                            $form->freeze('extra_'.$field_details['variable']);
2208
                        }
2209
                        break;
2210
                    case self::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
2211
                    case self::FIELD_TYPE_GEOLOCALIZATION:
2212
                        $dataValue = isset($extraData['extra_'.$field_details['variable']])
2213
                            ? $extraData['extra_'.$field_details['variable']]
2214
                            : '';
2215
2216
                        $form->addGeoLocationMapField(
2217
                            'extra_'.$field_details['variable'],
2218
                            $field_details['display_text'],
2219
                            $dataValue,
2220
                            $hideGeoLocalizationDetails
2221
                        );
2222
2223
                        /*$form->addElement(
2224
                            'text',
2225
                            'extra_'.$field_details['variable'],
2226
                            $field_details['display_text'],
2227
                            ['id' => 'extra_'.$field_details['variable']]
2228
                        );
2229
                        $form->addHidden(
2230
                            'extra_'.$field_details['variable'].'_coordinates',
2231
                            '',
2232
                            ['id' => 'extra_'.$field_details['variable'].'_coordinates']
2233
                        );
2234
2235
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
2236
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');*/
2237
2238
                        if ($freezeElement) {
2239
                            $form->freeze('extra_'.$field_details['variable']);
2240
                        }
2241
                        break;
2242
                    case self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
2243
                        $jquery_ready_content .= $this->addSelectWithTextFieldElement(
2244
                            $form,
2245
                            $field_details,
2246
                            $freezeElement
2247
                        );
2248
                        break;
2249
                    case self::FIELD_TYPE_TRIPLE_SELECT:
2250
                        $jquery_ready_content .= $this->addTripleSelectElement(
2251
                            $form,
2252
                            $field_details,
2253
                            is_array($extraData) ? $extraData : [],
2254
                            $freezeElement
2255
                        );
2256
                        break;
2257
                }
2258
            }
2259
        }
2260
2261
        $return = [];
2262
        $return['jquery_ready_content'] = $jquery_ready_content;
2263
2264
        return $return;
2265
    }
2266
2267
    public function getHandlerEntityByFieldVariable(string $variable)
2268
    {
2269
        return Database::getManager()
2270
            ->getRepository('ChamiloCoreBundle:ExtraField')
2271
            ->findOneBy(['variable' => $variable, 'extraFieldType' => $this->extraFieldType]);
2272
    }
2273
2274
    /**
2275
     * @param array $options
2276
     *
2277
     * @return array
2278
     */
2279
    public static function extra_field_double_select_convert_array_to_ordered_array($options)
2280
    {
2281
        $optionsParsed = [];
2282
        if (!empty($options)) {
2283
            foreach ($options as $option) {
2284
                if (0 == $option['option_value']) {
2285
                    $optionsParsed[$option['id']][] = $option;
2286
                } else {
2287
                    $optionsParsed[$option['option_value']][] = $option;
2288
                }
2289
            }
2290
        }
2291
2292
        return $optionsParsed;
2293
    }
2294
2295
    /**
2296
     * @return array
2297
     */
2298
    public static function tripleSelectConvertArrayToOrderedArray(array $options)
2299
    {
2300
        $level1 = self::getOptionsFromTripleSelect($options, 0);
2301
        $level2 = [];
2302
        $level3 = [];
2303
2304
        foreach ($level1 as $item1) {
2305
            $level2 += self::getOptionsFromTripleSelect($options, $item1['id']);
2306
        }
2307
2308
        foreach ($level2 as $item2) {
2309
            $level3 += self::getOptionsFromTripleSelect($options, $item2['id']);
2310
        }
2311
2312
        return ['level1' => $level1, 'level2' => $level2, 'level3' => $level3];
2313
    }
2314
2315
    /**
2316
     * @param $breadcrumb
2317
     * @param $action
2318
     */
2319
    public function setupBreadcrumb(&$breadcrumb, $action)
2320
    {
2321
        if ('add' === $action) {
2322
            $breadcrumb[] = ['url' => $this->pageUrl, 'name' => $this->pageName];
2323
            $breadcrumb[] = ['url' => '#', 'name' => get_lang('Add')];
2324
        } elseif ('edit' === $action) {
2325
            $breadcrumb[] = ['url' => $this->pageUrl, 'name' => $this->pageName];
2326
            $breadcrumb[] = ['url' => '#', 'name' => get_lang('Edit')];
2327
        } else {
2328
            $breadcrumb[] = ['url' => '#', 'name' => $this->pageName];
2329
        }
2330
    }
2331
2332
    /**
2333
     * Displays the title + grid.
2334
     */
2335
    public function display()
2336
    {
2337
        // action links
2338
        echo '<div class="actions">';
2339
        echo '<a href="../admin/index.php">';
2340
        echo Display::return_icon(
2341
            'back.png',
2342
            get_lang('BackTo').' '.get_lang('PlatformAdmin'),
2343
            '',
2344
            ICON_SIZE_MEDIUM
2345
        );
2346
        echo '</a>';
2347
        echo '<a href="'.api_get_self().'?action=add&type='.$this->type.'">';
2348
        echo Display::return_icon(
2349
            'add_user_fields.png',
2350
            get_lang('Add'),
2351
            '',
2352
            ICON_SIZE_MEDIUM
2353
        );
2354
        echo '</a>';
2355
        echo '</div>';
2356
        echo Display::grid_html($this->type.'_fields');
2357
    }
2358
2359
    /**
2360
     * @return array
2361
     */
2362
    public function getJqgridColumnNames()
2363
    {
2364
        return [
2365
            get_lang('Name'),
2366
            get_lang('FieldLabel'),
2367
            get_lang('Type'),
2368
            get_lang('FieldChangeability'),
2369
            get_lang('VisibleToSelf'),
2370
            get_lang('VisibleToOthers'),
2371
            get_lang('Filter'),
2372
            get_lang('FieldOrder'),
2373
            get_lang('Actions'),
2374
        ];
2375
    }
2376
2377
    /**
2378
     * @return array
2379
     */
2380
    public function getJqgridColumnModel()
2381
    {
2382
        return [
2383
            [
2384
                'name' => 'display_text',
2385
                'index' => 'display_text',
2386
                'width' => '140',
2387
                'align' => 'left',
2388
            ],
2389
            [
2390
                'name' => 'variable',
2391
                'index' => 'variable',
2392
                'width' => '90',
2393
                'align' => 'left',
2394
                'sortable' => 'true',
2395
            ],
2396
            [
2397
                'name' => 'field_type',
2398
                'index' => 'field_type',
2399
                'width' => '70',
2400
                'align' => 'left',
2401
                'sortable' => 'true',
2402
            ],
2403
            [
2404
                'name' => 'changeable',
2405
                'index' => 'changeable',
2406
                'width' => '35',
2407
                'align' => 'left',
2408
                'sortable' => 'true',
2409
            ],
2410
            [
2411
                'name' => 'visible_to_self',
2412
                'index' => 'visible_to_self',
2413
                'width' => '45',
2414
                'align' => 'left',
2415
                'sortable' => 'true',
2416
            ],
2417
            [
2418
                'name' => 'visible_to_others',
2419
                'index' => 'visible_to_others',
2420
                'width' => '35',
2421
                'align' => 'left',
2422
                'sortable' => 'true',
2423
            ],
2424
            [
2425
                'name' => 'filter',
2426
                'index' => 'filter',
2427
                'width' => '30',
2428
                'align' => 'left',
2429
                'sortable' => 'true',
2430
            ],
2431
            [
2432
                'name' => 'field_order',
2433
                'index' => 'field_order',
2434
                'width' => '25',
2435
                'align' => 'left',
2436
                'sortable' => 'true',
2437
            ],
2438
            [
2439
                'name' => 'actions',
2440
                'index' => 'actions',
2441
                'width' => '40',
2442
                'align' => 'left',
2443
                'formatter' => 'action_formatter',
2444
                'sortable' => 'false',
2445
            ],
2446
        ];
2447
    }
2448
2449
    /**
2450
     * @param string $url
2451
     * @param string $action
2452
     *
2453
     * @return FormValidator
2454
     */
2455
    public function return_form($url, $action)
2456
    {
2457
        $form = new FormValidator($this->type.'_field', 'post', $url);
2458
2459
        $form->addElement('hidden', 'type', $this->type);
2460
        $id = isset($_GET['id']) ? (int) $_GET['id'] : null;
2461
        $form->addElement('hidden', 'id', $id);
2462
2463
        // Setting the form elements
2464
        $header = get_lang('Add');
2465
        $defaults = [];
2466
2467
        if ('edit' === $action) {
2468
            $header = get_lang('Modify');
2469
            // Setting the defaults
2470
            $defaults = $this->get($id, false);
2471
        }
2472
2473
        $form->addElement('header', $header);
2474
2475
        if ('edit' === $action) {
2476
            $translateUrl = api_get_path(WEB_CODE_PATH).'extrafield/translate.php?'
2477
                .http_build_query(['extra_field' => $id]);
2478
            $translateButton = Display::toolbarButton(get_lang('TranslateThisTerm'), $translateUrl, 'language', 'link');
2479
2480
            $form->addText(
2481
                'display_text',
2482
                [get_lang('Name'), $translateButton]
2483
            );
2484
        } else {
2485
            $form->addElement('text', 'display_text', get_lang('Name'));
2486
        }
2487
2488
        // Field type
2489
        $types = self::get_field_types();
0 ignored issues
show
Bug Best Practice introduced by
The method ExtraField::get_field_types() is not static, but was called statically. ( Ignorable by Annotation )

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

2489
        /** @scrutinizer ignore-call */ 
2490
        $types = self::get_field_types();
Loading history...
2490
2491
        $form->addElement(
2492
            'select',
2493
            'field_type',
2494
            get_lang('FieldType'),
2495
            $types,
2496
            ['id' => 'field_type']
2497
        );
2498
        $form->addElement('label', get_lang('Example'), '<div id="example">-</div>');
2499
        $form->addElement('text', 'variable', get_lang('FieldLabel'), ['class' => 'span5']);
2500
        $form->addElement(
2501
            'text',
2502
            'field_options',
2503
            get_lang('FieldPossibleValues'),
2504
            ['id' => 'field_options', 'class' => 'span6']
2505
        );
2506
2507
        $fieldWithOptions = [
2508
            self::FIELD_TYPE_RADIO,
2509
            self::FIELD_TYPE_SELECT_MULTIPLE,
2510
            self::FIELD_TYPE_SELECT,
2511
            self::FIELD_TYPE_TAG,
2512
            self::FIELD_TYPE_DOUBLE_SELECT,
2513
            self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD,
2514
            self::FIELD_TYPE_TRIPLE_SELECT,
2515
        ];
2516
2517
        if ('edit' == $action) {
2518
            if (in_array($defaults['field_type'], $fieldWithOptions)) {
2519
                $url = Display::url(
2520
                    get_lang('EditExtraFieldOptions'),
2521
                    'extra_field_options.php?type='.$this->type.'&field_id='.$id
2522
                );
2523
                $form->addElement('label', null, $url);
2524
2525
                if (self::FIELD_TYPE_SELECT == $defaults['field_type']) {
2526
                    $urlWorkFlow = Display::url(
2527
                        get_lang('EditExtraFieldWorkFlow'),
2528
                        'extra_field_workflow.php?type='.$this->type.'&field_id='.$id
2529
                    );
2530
                    $form->addElement('label', null, $urlWorkFlow);
2531
                }
2532
2533
                $form->freeze('field_options');
2534
            }
2535
        }
2536
        $form->addElement(
2537
            'text',
2538
            'default_value',
2539
            get_lang('FieldDefaultValue'),
2540
            ['id' => 'default_value']
2541
        );
2542
2543
        $group = [];
2544
        $group[] = $form->createElement('radio', 'visible_to_self', null, get_lang('Yes'), 1);
2545
        $group[] = $form->createElement('radio', 'visible_to_self', null, get_lang('No'), 0);
2546
        $form->addGroup($group, '', get_lang('VisibleToSelf'), null, false);
2547
2548
        $group = [];
2549
        $group[] = $form->createElement('radio', 'visible_to_others', null, get_lang('Yes'), 1);
2550
        $group[] = $form->createElement('radio', 'visible_to_others', null, get_lang('No'), 0);
2551
        $form->addGroup($group, '', get_lang('VisibleToOthers'), null, false);
2552
2553
        $group = [];
2554
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('Yes'), 1);
2555
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('No'), 0);
2556
        $form->addGroup($group, '', get_lang('FieldChangeability'), null, false);
2557
2558
        $group = [];
2559
        $group[] = $form->createElement('radio', 'filter', null, get_lang('Yes'), 1);
2560
        $group[] = $form->createElement('radio', 'filter', null, get_lang('No'), 0);
2561
        $form->addGroup($group, '', get_lang('FieldFilter'), null, false);
2562
2563
        /* Enable this when field_loggeable is introduced as a table field (2.0)
2564
        $group   = array();
2565
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('Yes'), 1);
2566
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('No'), 0);
2567
        $form->addGroup($group, '', get_lang('FieldLoggeable'), '', false);
2568
        */
2569
2570
        $form->addElement('text', 'field_order', get_lang('FieldOrder'));
2571
2572
        if ('edit' == $action) {
2573
            $option = new ExtraFieldOption($this->type);
2574
            $defaults['field_options'] = $option->get_field_options_by_field_to_string($id);
2575
            $form->addButtonUpdate(get_lang('Modify'));
2576
        } else {
2577
            $defaults['visible_to_self'] = 0;
2578
            $defaults['visible_to_others'] = 0;
2579
            $defaults['changeable'] = 0;
2580
            $defaults['filter'] = 0;
2581
            $form->addButtonCreate(get_lang('Add'));
2582
        }
2583
2584
        /*if (!empty($defaults['created_at'])) {
2585
            $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
2586
        }
2587
        if (!empty($defaults['updated_at'])) {
2588
            $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
2589
        }*/
2590
        $form->setDefaults($defaults);
2591
2592
        // Setting the rules
2593
        $form->addRule('display_text', get_lang('ThisFieldIsRequired'), 'required');
2594
        $form->addRule('field_type', get_lang('ThisFieldIsRequired'), 'required');
2595
2596
        return $form;
2597
    }
2598
2599
     /**
2600
     * Gets an element.
2601
     *
2602
     * @param int  $id
2603
     * @param bool $translateDisplayText Optional
2604
     *
2605
     * @return array
2606
     */
2607
    public function get($id, $translateDisplayText = true)
2608
    {
2609
        $info = parent::get($id);
2610
2611
        if ($translateDisplayText) {
2612
            $info['display_text'] = self::translateDisplayName($info['variable'], $info['display_text']);
2613
        }
2614
2615
        return $info;
2616
    }
2617
2618
    /**
2619
     * @param $token
2620
     *
2621
     * @return string
2622
     */
2623
    public function getJqgridActionLinks($token)
2624
    {
2625
        //With this function we can add actions to the jgrid (edit, delete, etc)
2626
        $editIcon = Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL);
2627
        $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
2628
        $confirmMessage = addslashes(
2629
            api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)
2630
        );
2631
2632
        $editButton = <<<JAVASCRIPT
2633
            <a href="?action=edit&type={$this->type}&id=' + options.rowId + '" class="btn btn-link btn-xs">\
2634
                $editIcon\
2635
            </a>
2636
JAVASCRIPT;
2637
        $deleteButton = <<<JAVASCRIPT
2638
            <a \
2639
                onclick="if (!confirm(\'$confirmMessage\')) {return false;}" \
2640
                href="?sec_token=$token&type={$this->type}&id=' + options.rowId + '&action=delete" \
2641
                class="btn btn-link btn-xs">\
2642
                $deleteIcon\
2643
            </a>
2644
JAVASCRIPT;
2645
2646
        return "function action_formatter(cellvalue, options, rowObject) {
2647
            return '$editButton $deleteButton';
2648
        }";
2649
    }
2650
2651
    /**
2652
     * @param array $columns
2653
     * @param array $column_model
2654
     * @param array $extraFields
2655
     *
2656
     * @return array
2657
     */
2658
    public function getRules(&$columns, &$column_model, $extraFields = [], $checkExtraFieldExistence = false)
2659
    {
2660
        $fields = $this->get_all(
2661
            [
2662
                'visible_to_self = ? AND filter = ?' => [1, 1],
2663
            ],
2664
            'display_text'
2665
        );
2666
        $extraFieldOption = new ExtraFieldOption($this->type);
2667
2668
        $rules = [];
2669
        if (!empty($fields)) {
2670
            foreach ($fields as $field) {
2671
                $search_options = [];
2672
                $type = 'text';
2673
                if (in_array($field['field_type'], [self::FIELD_TYPE_SELECT, self::FIELD_TYPE_DOUBLE_SELECT])) {
2674
                    $type = 'select';
2675
                    $search_options['sopt'] = ['eq', 'ne']; //equal not equal
2676
                } else {
2677
                    $search_options['sopt'] = ['cn', 'nc']; //contains not contains
2678
                }
2679
2680
                $search_options['searchhidden'] = 'true';
2681
                $search_options['defaultValue'] = isset($search_options['field_default_value'])
2682
                    ? $search_options['field_default_value']
2683
                    : null;
2684
2685
                if (self::FIELD_TYPE_DOUBLE_SELECT == $field['field_type']) {
2686
                    // Add 2 selects
2687
                    $options = $extraFieldOption->get_field_options_by_field($field['id']);
2688
                    $options = self::extra_field_double_select_convert_array_to_ordered_array($options);
2689
2690
                    $first_options = [];
2691
                    if (!empty($options)) {
2692
                        foreach ($options as $option) {
2693
                            foreach ($option as $sub_option) {
2694
                                if (0 == $sub_option['option_value']) {
2695
                                    $first_options[] = $sub_option['field_id'].'#'.$sub_option['id'].':'
2696
                                        .$sub_option['display_text'];
2697
                                }
2698
                            }
2699
                        }
2700
                    }
2701
2702
                    $search_options['value'] = implode(';', $first_options);
2703
                    $search_options['dataInit'] = 'fill_second_select';
2704
2705
                    // First
2706
                    $column_model[] = [
2707
                        'name' => 'extra_'.$field['variable'],
2708
                        'index' => 'extra_'.$field['variable'],
2709
                        'width' => '100',
2710
                        'hidden' => 'true',
2711
                        'search' => 'true',
2712
                        'stype' => 'select',
2713
                        'searchoptions' => $search_options,
2714
                    ];
2715
                    $columns[] = $field['display_text'].' (1)';
2716
                    $rules[] = [
2717
                        'field' => 'extra_'.$field['variable'],
2718
                        'op' => 'cn',
2719
                    ];
2720
2721
                    // Second
2722
                    $search_options['value'] = $field['id'].':';
2723
                    $search_options['dataInit'] = 'register_second_select';
2724
2725
                    $column_model[] = [
2726
                        'name' => 'extra_'.$field['variable'].'_second',
2727
                        'index' => 'extra_'.$field['variable'].'_second',
2728
                        'width' => '100',
2729
                        'hidden' => 'true',
2730
                        'search' => 'true',
2731
                        'stype' => 'select',
2732
                        'searchoptions' => $search_options,
2733
                    ];
2734
                    $columns[] = $field['display_text'].' (2)';
2735
                    $rules[] = ['field' => 'extra_'.$field['variable'].'_second', 'op' => 'cn'];
2736
                    continue;
2737
                } else {
2738
                    $search_options['value'] = $extraFieldOption->getFieldOptionsToString(
2739
                        $field['id'],
2740
                        false,
2741
                        'display_text'
2742
                    );
2743
                }
2744
                $column_model[] = [
2745
                    'name' => 'extra_'.$field['variable'],
2746
                    'index' => 'extra_'.$field['variable'],
2747
                    'width' => '100',
2748
                    'hidden' => 'true',
2749
                    'search' => 'true',
2750
                    'stype' => $type,
2751
                    'searchoptions' => $search_options,
2752
                ];
2753
                $columns[] = $field['display_text'];
2754
                $rules[] = [
2755
                    'field' => 'extra_'.$field['variable'],
2756
                    'op' => 'cn',
2757
                    'data' => '',
2758
                ];
2759
            }
2760
        }
2761
2762
        return $rules;
2763
    }
2764
2765
    public function processExtraFieldSearch($values, $form, $alias, $condition = 'OR')
2766
    {
2767
        // Parse params.
2768
        $fields = [];
2769
        foreach ($values as $key => $value) {
2770
            if (substr($key, 0, 6) !== 'extra_' &&
2771
                substr($key, 0, 7) !== '_extra_'
2772
            ) {
2773
                continue;
2774
            }
2775
            if (!empty($value)) {
2776
                $fields[$key] = $value;
2777
            }
2778
        }
2779
2780
        $extraFieldsAll = $this->get_all(['visible_to_self = ? AND filter = ?' => [1, 1]], 'option_order');
2781
        $extraFieldsType = array_column($extraFieldsAll, 'field_type', 'variable');
2782
        $extraFields = array_column($extraFieldsAll, 'variable');
2783
        $filter = new stdClass();
2784
        $defaults = [];
2785
        foreach ($fields as $variable => $col) {
2786
            $variableNoExtra = str_replace('extra_', '', $variable);
2787
            if (isset($values[$variable]) && !empty($values[$variable]) &&
2788
                in_array($variableNoExtra, $extraFields)
2789
            ) {
2790
                $rule = new stdClass();
2791
                $rule->field = $variable;
2792
                $rule->op = 'in';
2793
                $data = $col;
2794
                if (is_array($data) && array_key_exists($variable, $data)) {
2795
                    $data = $col;
2796
                }
2797
                $rule->data = $data;
2798
                $filter->rules[] = $rule;
2799
                $filter->groupOp = 'AND';
2800
2801
                if ($extraFieldsType[$variableNoExtra] == ExtraField::FIELD_TYPE_TAG) {
2802
                    $tagElement = $form->getElement($variable);
2803
                    $tags = [];
2804
                    foreach ($values[$variable] as $tag) {
2805
                        $tag = Security::remove_XSS($tag);
2806
                        $tags[] = $tag;
2807
                        $tagElement->addOption(
2808
                            $tag,
2809
                            $tag
2810
                        );
2811
                    }
2812
                    $defaults[$variable] = $tags;
2813
                } else {
2814
                    if (is_array($data)) {
2815
                        $defaults[$variable] = array_map(['Security', 'remove_XSS'], $data);
2816
                    } else {
2817
                        $defaults[$variable] = Security::remove_XSS($data);
2818
                    }
2819
                }
2820
            }
2821
        }
2822
2823
        $result = $this->getExtraFieldRules($filter, 'extra_', $condition);
2824
        $conditionArray = $result['condition_array'];
2825
2826
        $whereCondition = '';
2827
        $extraCondition = '';
2828
        if (!empty($conditionArray)) {
2829
            $extraCondition = ' ( ';
2830
            $extraCondition .= implode(' AND ', $conditionArray);
2831
            $extraCondition .= ' ) ';
2832
        }
2833
        $whereCondition .= $extraCondition;
2834
        $conditions = $this->parseConditions(
2835
            [
2836
                'where' => $whereCondition,
2837
                'extra' => $result['extra_fields'],
2838
            ],
2839
            $alias
2840
        );
2841
2842
        return ['condition' => $conditions, 'fields' => $fields, 'defaults' => $defaults];
2843
    }
2844
2845
    /**
2846
     * @param $filters
2847
     * @param string $stringToSearch
2848
     *
2849
     * @return array
2850
     */
2851
    public function getExtraFieldRules($filters, $stringToSearch = 'extra_')
2852
    {
2853
        $extra_fields = [];
2854
2855
        // Getting double select if exists
2856
        $double_select = [];
2857
        foreach ($filters->rules as $rule) {
2858
            if (empty($rule)) {
2859
                continue;
2860
            }
2861
                if (false === strpos($rule->field, '_second')) {
2862
            } else {
2863
                $my_field = str_replace('_second', '', $rule->field);
2864
                $double_select[$my_field] = $rule->data;
2865
            }
2866
        }
2867
2868
        $condition_array = [];
2869
        foreach ($filters->rules as $rule) {
2870
            if (empty($rule)) {
2871
                continue;
2872
            }
2873
            if (strpos($rule->field, $stringToSearch) === false) {
2874
                // normal fields
2875
                $field = $rule->field;
2876
                if (isset($rule->data) && is_string($rule->data) && $rule->data != -1) {
2877
                    $condition_array[] = $this->get_where_clause($field, $rule->op, $rule->data);
2878
                }
2879
            } else {
2880
                // Extra fields
2881
                $ruleField = Database::escapeField($rule->field);
2882
                if (strpos($rule->field, '_second') === false) {
2883
                    //No _second
2884
                    $original_field = str_replace($stringToSearch, '', $rule->field);
2885
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2886
2887
                    if ($field_option['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
2888
                        if (isset($double_select[$rule->field])) {
2889
                            $data = explode('#', $rule->data);
2890
                            $rule->data = $data[1].'::'.$double_select[$rule->field];
2891
                        } else {
2892
                            // only was sent 1 select
2893
                            if (is_string($rule->data)) {
2894
                                $data = explode('#', $rule->data);
2895
                                $rule->data = $data[1];
2896
                            }
2897
                        }
2898
2899
                        if (!isset($rule->data)) {
2900
                            $condition_array[] = ' ('
2901
                                .$this->get_where_clause($rule->field, $rule->op, $rule->data)
2902
                                .') ';
2903
                            $extra_fields[] = ['field' => $ruleField, 'id' => $field_option['id']];
2904
                        }
2905
                    } else {
2906
                        if (isset($rule->data)) {
2907
                            if (isset($rule->data) && is_int($rule->data) && $rule->data == -1) {
2908
                                continue;
2909
                            }
2910
                            $condition_array[] = ' ('
2911
                                .$this->get_where_clause($rule->field, $rule->op, $rule->data)
2912
                                .') ';
2913
                            $extra_fields[] = [
2914
                                'field' => $ruleField,
2915
                                'id' => $field_option['id'],
2916
                                'data' => $rule->data,
2917
                            ];
2918
                        }
2919
                    }
2920
                } else {
2921
                    $my_field = str_replace('_second', '', $rule->field);
2922
                    $original_field = str_replace($stringToSearch, '', $my_field);
2923
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2924
                    $extra_fields[] = [
2925
                        'field' => $ruleField,
2926
                        'id' => $field_option['id'],
2927
                    ];
2928
                }
2929
            }
2930
        }
2931
2932
        return [
2933
            'extra_fields' => $extra_fields,
2934
            'condition_array' => $condition_array,
2935
        ];
2936
    }
2937
2938
2939
    /**
2940
     * @param array $options
2941
     *
2942
     * @return array
2943
     */
2944
    public function parseConditions($options)
2945
    {
2946
        $inject_extra_fields = null;
2947
        $extraFieldOption = new ExtraFieldOption($this->type);
2948
        $double_fields = [];
2949
2950
        if (isset($options['extra'])) {
2951
            $extra_fields = $options['extra'];
2952
            if (!empty($extra_fields)) {
2953
                $counter = 1;
2954
                foreach ($extra_fields as &$extra) {
2955
                    $extra_field_obj = new ExtraField($this->type);
2956
                    $extra_field_info = $extra_field_obj->get($extra['id']);
2957
                    $extra['extra_field_info'] = $extra_field_info;
2958
2959
                    if (isset($extra_field_info['field_type']) &&
2960
                        in_array(
2961
                            $extra_field_info['field_type'],
2962
                            [
2963
                                self::FIELD_TYPE_SELECT,
2964
                                self::FIELD_TYPE_SELECT,
2965
                                self::FIELD_TYPE_DOUBLE_SELECT,
2966
                            ]
2967
                        )
2968
                    ) {
2969
                        $inject_extra_fields .= " fvo$counter.display_text as {$extra['field']}, ";
2970
                    } else {
2971
                        $inject_extra_fields .= " fv$counter.value as {$extra['field']}, ";
2972
                    }
2973
2974
                    if (isset($extra_fields_info[$extra['id']])) {
2975
                        $info = $extra_fields_info[$extra['id']];
2976
                    } else {
2977
                        $info = $this->get($extra['id']);
2978
                        $extra_fields_info[$extra['id']] = $info;
2979
                    }
2980
                    if (isset($info['field_type']) && $info['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
2981
                        $double_fields[$info['id']] = $info;
2982
                    }
2983
                    $counter++;
2984
                }
2985
            }
2986
        }
2987
2988
        $options_by_double = [];
2989
        foreach ($double_fields as $double) {
2990
            $my_options = $extraFieldOption->get_field_options_by_field(
2991
                $double['id'],
2992
                true
2993
            );
2994
            $options_by_double['extra_'.$double['variable']] = $my_options;
2995
        }
2996
2997
        $field_value_to_join = [];
2998
        //filter can be all/any = and/or
2999
        $inject_joins = null;
3000
        $inject_where = null;
3001
        $where = null;
3002
3003
        if (!empty($options['where'])) {
3004
            if (!empty($options['extra'])) {
3005
                // Removing double 1=1
3006
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
3007
                // Always OR
3008
                $counter = 1;
3009
                foreach ($extra_fields as $extra_info) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extra_fields does not seem to be defined for all execution paths leading up to this point.
Loading history...
3010
                    $extra_field_info = $extra_info['extra_field_info'];
3011
                    $inject_joins .= " INNER JOIN $this->table_field_values fv$counter
3012
                                       ON (s.".$this->primaryKey." = fv$counter.".$this->handler_id.") ";
3013
                    // Add options
3014
                    if (isset($extra_field_info['field_type']) &&
3015
                        in_array(
3016
                            $extra_field_info['field_type'],
3017
                            [
3018
                                self::FIELD_TYPE_SELECT,
3019
                                self::FIELD_TYPE_SELECT,
3020
                                self::FIELD_TYPE_DOUBLE_SELECT,
3021
                            ]
3022
                        )
3023
                    ) {
3024
                        $options['where'] = str_replace(
3025
                            $extra_info['field'],
3026
                            'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fvo'.$counter.'.option_value',
3027
                            $options['where']
3028
                        );
3029
                        $inject_joins .= "
3030
                             INNER JOIN $this->table_field_options fvo$counter
3031
                             ON (
3032
                                fv$counter.field_id = fvo$counter.field_id AND
3033
                                fv$counter.value = fvo$counter.option_value
3034
                             )
3035
                            ";
3036
                    } else {
3037
                        if (isset($extra_field_info['field_type']) &&
3038
                            $extra_field_info['field_type'] == self::FIELD_TYPE_TAG
3039
                        ) {
3040
                            $options['where'] = str_replace(
3041
                                $extra_info['field'],
3042
                                'tag'.$counter.'.tag ',
3043
                                $options['where']
3044
                            );
3045
3046
                            $inject_joins .= "
3047
                                INNER JOIN $this->table_field_rel_tag tag_rel$counter
3048
                                ON (
3049
                                    tag_rel$counter.field_id = ".$extra_info['id']." AND
3050
                                    tag_rel$counter.item_id = s.".$this->primaryKey."
3051
                                )
3052
                                INNER JOIN $this->table_field_tag tag$counter
3053
                                ON (tag$counter.id = tag_rel$counter.tag_id)
3054
                            ";
3055
                        } else {
3056
                            //text, textarea, etc
3057
                            $options['where'] = str_replace(
3058
                                $extra_info['field'],
3059
                                'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fv'.$counter.'.value',
3060
                                $options['where']
3061
                            );
3062
                        }
3063
                    }
3064
3065
                    $field_value_to_join[] = " fv$counter.$this->handler_id ";
3066
                    $counter++;
3067
                }
3068
                if (!empty($field_value_to_join)) {
3069
                    //$inject_where .= " AND s.id = ".implode(' = ', $field_value_to_join);
3070
                }
3071
            }
3072
            $where .= ' AND '.$options['where'];
3073
        }
3074
3075
        $order = null;
3076
        if (!empty($options['order'])) {
3077
            $order = " ORDER BY ".$options['order'];
3078
        }
3079
        $limit = null;
3080
        if (!empty($options['limit'])) {
3081
            $limit = " LIMIT ".$options['limit'];
3082
        }
3083
3084
        return [
3085
            'order' => $order,
3086
            'limit' => $limit,
3087
            'where' => $where,
3088
            'inject_where' => $inject_where,
3089
            'inject_joins' => $inject_joins,
3090
            'field_value_to_join' => $field_value_to_join,
3091
            'inject_extra_fields' => $inject_extra_fields,
3092
        ];
3093
    }
3094
3095
    //@todo move this in the display_class or somewhere else
3096
3097
    /**
3098
     * @param $col
3099
     * @param $oper
3100
     * @param $val
3101
     *
3102
     * @return string
3103
     */
3104
    public function get_where_clause($col, $oper, $val)
3105
    {
3106
        if (empty($col)) {
3107
            return '';
3108
        }
3109
        if ($oper == 'bw' || $oper == 'bn') {
3110
            $val .= '%';
3111
        }
3112
        if ($oper == 'ew' || $oper == 'en') {
3113
            $val = '%'.$val;
3114
        }
3115
        if ($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') {
3116
            if (is_array($val)) {
3117
                $result = '"%'.implode(';', $val).'%"';
3118
                foreach ($val as $item) {
3119
                    $item = trim($item);
3120
                    $result .= ' OR '.$col.' LIKE "%'.$item.'%"';
3121
                }
3122
                $val = $result;
3123
3124
                return " $col {$this->ops[$oper]} $val ";
3125
            } else {
3126
                if (is_string($val)) {
3127
                    $val = '%'.$val.'%';
3128
                } else {
3129
                    $val = '';
3130
                }
3131
            }
3132
        }
3133
        $val = \Database::escape_string($val);
3134
3135
        return " $col {$this->ops[$oper]} '$val' ";
3136
    }
3137
3138
3139
    /**
3140
     * Get the extra fields and their formatted values.
3141
     *
3142
     * @param int|string $itemId The item ID (It could be a session_id, course_id or user_id)
3143
     *
3144
     * @return array The extra fields data
3145
     */
3146
    public function getDataAndFormattedValues($itemId)
3147
    {
3148
        $valuesData = [];
3149
        $fields = $this->get_all();
3150
        $em = Database::getManager();
3151
3152
        foreach ($fields as $field) {
3153
            if ($field['visible_to_self'] != '1') {
3154
                continue;
3155
            }
3156
3157
            $valueAsArray = [];
3158
            $fieldValue = new ExtraFieldValue($this->type);
3159
            $valueData = $fieldValue->get_values_by_handler_and_field_id(
3160
                $itemId,
3161
                $field['id'],
3162
                true
3163
            );
3164
3165
            if ($field['field_type'] == ExtraField::FIELD_TYPE_TAG) {
3166
                $tags = $em
3167
                    ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
3168
                    ->findBy(
3169
                        [
3170
                            'fieldId' => $field['id'],
3171
                            'itemId' => $itemId,
3172
                        ]
3173
                    );
3174
                if ($tags) {
3175
                    /** @var \Chamilo\CoreBundle\Entity\ExtraFieldRelTag $tag */
3176
                    $data = [];
3177
                    foreach ($tags as $extraFieldTag) {
3178
                        /** @var \Chamilo\CoreBundle\Entity\Tag $tag */
3179
                        $tag = $em->find('ChamiloCoreBundle:Tag', $extraFieldTag->getTagId());
3180
                        /*$data[] = [
3181
                            'id' => $extraFieldTag->getTagId(),
3182
                            'value' => $tag->getTag()
3183
                        ];*/
3184
                        $data[] = $tag->getTag();
3185
                    }
3186
                    $valueData = implode(',', $data);
3187
                    $valueAsArray = $data;
3188
                }
3189
            }
3190
3191
            if (!$valueData) {
3192
                continue;
3193
            }
3194
3195
            $displayedValue = get_lang('None');
3196
3197
            switch ($field['field_type']) {
3198
                case self::FIELD_TYPE_CHECKBOX:
3199
                    if ($valueData !== false && $valueData['value'] == '1') {
3200
                        $displayedValue = get_lang('Yes');
3201
                    } else {
3202
                        $displayedValue = get_lang('No');
3203
                    }
3204
                    break;
3205
                case self::FIELD_TYPE_DATE:
3206
                    if ($valueData !== false && !empty($valueData['value'])) {
3207
                        $displayedValue = api_format_date($valueData['value'], DATE_FORMAT_LONG_NO_DAY);
3208
                    }
3209
                    break;
3210
                case self::FIELD_TYPE_TAG:
3211
                    if (!empty($valueData)) {
3212
                        $displayedValue = $valueData;
3213
                    }
3214
                    break;
3215
                case self::FIELD_TYPE_FILE_IMAGE:
3216
                    if ($valueData === false || empty($valueData['value'])) {
3217
                        break;
3218
                    }
3219
3220
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
3221
                        break;
3222
                    }
3223
3224
                    $image = Display::img(
3225
                        api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
3226
                        $field['display_text'],
3227
                        ['width' => '300']
3228
                    );
3229
3230
                    $displayedValue = Display::url(
3231
                        $image,
3232
                        api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
3233
                        ['target' => '_blank']
3234
                    );
3235
                    break;
3236
                case self::FIELD_TYPE_FILE:
3237
                    if ($valueData === false || empty($valueData['value'])) {
3238
                        break;
3239
                    }
3240
3241
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
3242
                        break;
3243
                    }
3244
3245
                    $displayedValue = Display::url(
3246
                        get_lang('Download'),
3247
                        api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
3248
                        [
3249
                            'title' => $field['display_text'],
3250
                            'target' => '_blank',
3251
                            'class' => 'download_extra_field',
3252
                        ]
3253
                    );
3254
                    break;
3255
                default:
3256
                    $displayedValue = $valueData['value'];
3257
                    break;
3258
            }
3259
3260
            $valuesData[] = [
3261
                'variable' => $field['variable'],
3262
                'text' => $field['display_text'],
3263
                'value' => $displayedValue,
3264
                'value_as_array' => $valueAsArray,
3265
            ];
3266
        }
3267
3268
        return $valuesData;
3269
    }
3270
3271
3272
3273
    /**
3274
     * @param int    $fieldId
3275
     * @param string $tag
3276
     *
3277
     * @return array
3278
     */
3279
    public function getAllUserPerTag($fieldId, $tag)
3280
    {
3281
        $tagRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
3282
        $tag = Database::escape_string($tag);
3283
        $fieldId = (int) $fieldId;
3284
3285
        $sql = "SELECT user_id
3286
                FROM {$this->table_field_tag} f INNER JOIN $tagRelUserTable ft
3287
                ON tag_id = f.id
3288
                WHERE tag = '$tag' AND f.field_id = $fieldId;
3289
        ";
3290
3291
        $result = Database::query($sql);
3292
3293
        return Database::store_result($result, 'ASSOC');
3294
    }
3295
3296
    /**
3297
     * @param int $fieldId
3298
     * @param int $tagId
3299
     *
3300
     * @return array
3301
     */
3302
    public function getAllSkillPerTag($fieldId, $tagId)
3303
    {
3304
        $skillTable = Database::get_main_table(TABLE_MAIN_SKILL);
3305
        $tagRelExtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
3306
        $fieldId = (int) $fieldId;
3307
        $tagId = (int) $tagId;
3308
3309
        $sql = "SELECT s.id
3310
                FROM $skillTable s INNER JOIN $tagRelExtraTable t
3311
                ON t.item_id = s.id
3312
                WHERE tag_id = $tagId AND t.field_id = $fieldId;
3313
        ";
3314
3315
        $result = Database::query($sql);
3316
        $result = Database::store_result($result, 'ASSOC');
3317
3318
        $skillList = [];
3319
        foreach ($result as $index => $value) {
3320
            $skillList[$value['id']] = $value['id'];
3321
        }
3322
3323
        return $skillList;
3324
    }
3325
3326
    /**
3327
     * @param string $from
3328
     * @param string $search
3329
     * @param array  $options
3330
     *
3331
     * @return array
3332
     */
3333
    public function searchOptionsFromTags($from, $search, $options)
3334
    {
3335
        $extraFieldInfo = $this->get_handler_field_info_by_field_variable(
3336
            str_replace('extra_', '', $from)
3337
        );
3338
        $extraFieldInfoTag = $this->get_handler_field_info_by_field_variable(
3339
            str_replace('extra_', '', $search)
3340
        );
3341
3342
        if (empty($extraFieldInfo) || empty($extraFieldInfoTag)) {
3343
            return [];
3344
        }
3345
3346
        $id = $extraFieldInfo['id'];
3347
        $tagId = $extraFieldInfoTag['id'];
3348
3349
        $table = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
3350
        $tagRelExtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
3351
        $tagTable = Database::get_main_table(TABLE_MAIN_TAG);
3352
        $optionsTable = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
3353
3354
        $cleanOptions = [];
3355
        foreach ($options as $option) {
3356
            $cleanOptions[] = Database::escape_string($option);
3357
        }
3358
        $cleanOptions = array_filter($cleanOptions);
3359
3360
        if (empty($cleanOptions)) {
3361
            return [];
3362
        }
3363
3364
        $value = implode("','", $cleanOptions);
3365
3366
        $sql = "SELECT DISTINCT t.*, v.value, o.display_text
3367
                FROM $tagRelExtraTable te
3368
                INNER JOIN $tagTable t
3369
                ON (t.id = te.tag_id AND te.field_id = t.field_id AND te.field_id = $tagId)
3370
                INNER JOIN $table v
3371
                ON (te.item_id = v.item_id AND v.field_id = $id)
3372
                INNER JOIN $optionsTable o
3373
                ON (o.option_value = v.value)
3374
                WHERE v.value IN ('".$value."')
3375
                ORDER BY o.option_order, t.tag
3376
               ";
3377
3378
        $result = Database::query($sql);
3379
        $result = Database::store_result($result);
3380
3381
        return $result;
3382
    }
3383
3384
    /**
3385
     * @param \FormValidator $form
3386
     * @param array          $fieldDetails
3387
     * @param int            $defaultValueId
3388
     * @param bool           $freezeElement
3389
     */
3390
    private function addSelectElement(FormValidator $form, array $fieldDetails, $defaultValueId, $freezeElement = false)
3391
    {
3392
        $get_lang_variables = false;
3393
        if (in_array(
3394
            $fieldDetails['variable'],
3395
            ['mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message']
3396
        )) {
3397
            $get_lang_variables = true;
3398
        }
3399
3400
        // Get extra field workflow
3401
        $userInfo = api_get_user_info();
3402
        $addOptions = [];
3403
        $optionsExists = false;
3404
        global $app;
3405
3406
        $options = [];
3407
        if (empty($defaultValueId)) {
3408
            $options[''] = get_lang('SelectAnOption');
3409
        }
3410
3411
        $optionList = [];
3412
        if (!empty($fieldDetails['options'])) {
3413
            foreach ($fieldDetails['options'] as $option_details) {
3414
                $optionList[$option_details['id']] = $option_details;
3415
                if ($get_lang_variables) {
3416
                    $options[$option_details['option_value']] = $option_details['display_text'];
3417
                } else {
3418
                    if ($optionsExists) {
3419
                        // Adding always the default value
3420
                        if ($option_details['id'] == $defaultValueId) {
3421
                            $options[$option_details['option_value']] = $option_details['display_text'];
3422
                        } else {
3423
                            if (isset($addOptions) && !empty($addOptions)) {
3424
                                // Parsing filters
3425
                                if (in_array($option_details['id'], $addOptions)) {
3426
                                    $options[$option_details['option_value']] = $option_details['display_text'];
3427
                                }
3428
                            }
3429
                        }
3430
                    } else {
3431
                        // Normal behaviour
3432
                        $options[$option_details['option_value']] = $option_details['display_text'];
3433
                    }
3434
                }
3435
            }
3436
3437
            // Setting priority message
3438
            if (isset($optionList[$defaultValueId])
3439
                && isset($optionList[$defaultValueId]['priority'])
3440
            ) {
3441
                if (!empty($optionList[$defaultValueId]['priority'])) {
3442
                    $priorityId = $optionList[$defaultValueId]['priority'];
3443
                    $option = new ExtraFieldOption($this->type);
3444
                    $messageType = $option->getPriorityMessageType($priorityId);
3445
                    $form->addElement(
3446
                        'label',
3447
                        null,
3448
                        Display::return_message(
3449
                            $optionList[$defaultValueId]['priority_message'],
3450
                            $messageType
3451
                        )
3452
                    );
3453
                }
3454
            }
3455
        }
3456
3457
        /** @var \HTML_QuickForm_select $slct */
3458
        $slct = $form->addElement(
3459
            'select',
3460
            'extra_'.$fieldDetails['variable'],
3461
            $fieldDetails['display_text'],
3462
            $options,
3463
            ['id' => 'extra_'.$fieldDetails['variable']]
3464
        );
3465
3466
        foreach ($options as $value => $text) {
3467
            if (empty($value)) {
3468
                $slct->addOption($text, $value);
3469
                continue;
3470
            }
3471
3472
            $valueParts = explode('#', $text);
3473
            $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
3474
3475
            $slct->addOption(implode('', $valueParts), $value, ['data-value' => $dataValue]);
3476
        }
3477
3478
        if ($freezeElement) {
3479
            $form->freeze('extra_'.$fieldDetails['variable']);
3480
        }
3481
    }
3482
3483
    /**
3484
     * @param \FormValidator $form
3485
     * @param array          $fieldDetails
3486
     * @param array          $extraData
3487
     * @param bool           $freezeElement
3488
     *
3489
     * @return string JavaScript code
3490
     */
3491
    private function addDoubleSelectElement(FormValidator $form, $fieldDetails, $extraData, $freezeElement = false)
3492
    {
3493
        $firstSelectId = 'first_extra_'.$fieldDetails['variable'];
3494
        $secondSelectId = 'second_extra_'.$fieldDetails['variable'];
3495
3496
        $jqueryReadyContent = "
3497
            $('#$firstSelectId').on('change', function() {
3498
                var id = $(this).val();
3499
3500
                if (!id) {
3501
                    $('#$secondSelectId').empty().selectpicker('refresh');
3502
3503
                    return;
3504
                }
3505
3506
                $.getJSON(_p.web_ajax + 'extra_field.ajax.php?1=1&a=get_second_select_options', {
3507
                    'type': '{$this->type}',
3508
                    'field_id': {$fieldDetails['id']},
3509
                    'option_value_id': id
3510
                })
3511
                    .done(function(data) {
3512
                        $('#$secondSelectId').empty();
3513
                        $.each(data, function(index, value) {
3514
                            $('#second_extra_{$fieldDetails['variable']}').append(
3515
                                $('<option>', {value: index, text: value})
3516
                            );
3517
                        });
3518
                        $('#$secondSelectId').selectpicker('refresh');
3519
                    });
3520
            });
3521
        ";
3522
3523
        $firstId = null;
3524
        if (!empty($extraData)) {
3525
            if (isset($extraData['extra_'.$fieldDetails['variable']])) {
3526
                $firstId = $extraData['extra_'.$fieldDetails['variable']]['extra_'.$fieldDetails['variable']];
3527
            }
3528
        }
3529
3530
        $options = $this->extra_field_double_select_convert_array_to_ordered_array($fieldDetails['options']);
3531
        $values = ['' => get_lang('Select')];
3532
3533
        $second_values = [];
3534
        if (!empty($options)) {
3535
            foreach ($options as $option) {
3536
                foreach ($option as $sub_option) {
3537
                    if ('0' == $sub_option['option_value']) {
3538
                        $values[$sub_option['id']] = $sub_option['display_text'];
3539
3540
                        continue;
3541
                    }
3542
3543
                    if ($firstId === $sub_option['option_value']) {
3544
                        $second_values[$sub_option['id']] = $sub_option['display_text'];
3545
                    }
3546
                }
3547
            }
3548
        }
3549
        $form
3550
            ->defaultRenderer()
3551
            ->setGroupElementTemplate('<p>{element}</p>', 'extra_'.$fieldDetails['variable']);
3552
        $group = [];
3553
        $group[] = $form->createElement(
3554
            'select',
3555
            'extra_'.$fieldDetails['variable'],
3556
            null,
3557
            $values,
3558
            ['id' => $firstSelectId]
3559
        );
3560
        $group[] = $form->createElement(
3561
            'select',
3562
            'extra_'.$fieldDetails['variable'].'_second',
3563
            null,
3564
            $second_values,
3565
            ['id' => $secondSelectId]
3566
        );
3567
        $form->addGroup(
3568
            $group,
3569
            'extra_'.$fieldDetails['variable'],
3570
            $fieldDetails['display_text']
3571
        );
3572
3573
        if ($freezeElement) {
3574
            $form->freeze('extra_'.$fieldDetails['variable']);
3575
        }
3576
3577
        return $jqueryReadyContent;
3578
    }
3579
3580
    /**
3581
     * @param \FormValidator $form
3582
     * @param bool           $freezeElement Optional
3583
     *
3584
     * @return string JavaScript code
3585
     */
3586
    private function addSelectWithTextFieldElement(
3587
        FormValidator $form,
3588
        array $fieldDetails,
3589
        $freezeElement = false
3590
    ) {
3591
        $firstSelectId = 'slct_extra_'.$fieldDetails['variable'];
3592
        $txtSelectId = 'txt_extra_'.$fieldDetails['variable'];
3593
3594
        $jqueryReadyContent = "
3595
            $('#$firstSelectId').on('change', function() {
3596
                var id = $(this).val();
3597
3598
                if (!id) {
3599
                    $('#$txtSelectId').val('');
3600
                }
3601
            });
3602
        ";
3603
3604
        $options = $this->extra_field_double_select_convert_array_to_ordered_array($fieldDetails['options']);
3605
        $values = ['' => get_lang('Select')];
3606
3607
        if (!empty($options)) {
3608
            foreach ($options as $option) {
3609
                foreach ($option as $sub_option) {
3610
                    if ('0' == $sub_option['option_value']) {
3611
                        continue;
3612
                    }
3613
3614
                    $values[$sub_option['id']] = $sub_option['display_text'];
3615
                }
3616
            }
3617
        }
3618
3619
        $form
3620
            ->defaultRenderer()
3621
            ->setGroupElementTemplate('<p>{element}</p>', 'extra_'.$fieldDetails['variable']);
3622
        $group = [];
3623
        $group[] = $form->createElement(
3624
            'select',
3625
            'extra_'.$fieldDetails['variable'],
3626
            null,
3627
            $values,
3628
            ['id' => $firstSelectId]
3629
        );
3630
        $group[] = $form->createElement(
3631
            'text',
3632
            'extra_'.$fieldDetails['variable'].'_second',
3633
            null,
3634
            ['id' => $txtSelectId]
3635
        );
3636
        $form->addGroup(
3637
            $group,
3638
            'extra_'.$fieldDetails['variable'],
3639
            $fieldDetails['display_text']
3640
        );
3641
3642
        if ($freezeElement) {
3643
            $form->freeze('extra_'.$fieldDetails['variable']);
3644
        }
3645
3646
        return $jqueryReadyContent;
3647
    }
3648
3649
    /**
3650
     * @param \FormValidator $form
3651
     * @param bool           $freezeElement
3652
     *
3653
     * @return string
3654
     */
3655
    private function addTripleSelectElement(
3656
        FormValidator $form,
3657
        array $fieldDetails,
3658
        array $extraData,
3659
        $freezeElement
3660
    ) {
3661
        $variable = $fieldDetails['variable'];
3662
        $id = $fieldDetails['id'];
3663
        $slctFirstId = "first_extra$variable";
3664
        $slctSecondId = "second_extra$variable";
3665
        $slctThirdId = "third_extra$variable";
3666
        $langSelect = get_lang('Select');
3667
3668
        $js = "
3669
            (function () {
3670
                var slctFirst = $('#$slctFirstId'),
3671
                    slctSecond = $('#$slctSecondId'),
3672
                    slctThird = $('#$slctThirdId');
3673
3674
                slctFirst.on('change', function () {
3675
                    slctSecond.empty().selectpicker('refresh');
3676
                    slctThird.empty().selectpicker('refresh');
3677
3678
                    var level = $(this).val();
3679
3680
                    if (!level) {
3681
                        return;
3682
                    }
3683
3684
                    $.getJSON(_p.web_ajax + 'extra_field.ajax.php', {
3685
                        'a': 'get_second_select_options',
3686
                        'type': '$this->type',
3687
                        'field_id': $id,
3688
                        'option_value_id': level
3689
                    })
3690
                        .done(function (data) {
3691
                            slctSecond.append(
3692
                                $('<option>', {value: '', text: '$langSelect'})
3693
                            );
3694
3695
                            $.each(data, function (index, value) {
3696
                                var valueParts = value.split('#'),
3697
                                    dataValue = valueParts.length > 1 ? valueParts.shift() : '';
3698
3699
                                slctSecond.append(
3700
                                    $('<option>', {value: index, text: valueParts.join(''), 'data-value': dataValue})
3701
                                );
3702
                            });
3703
3704
                            slctSecond.selectpicker('refresh');
3705
                        });
3706
                });
3707
                slctSecond.on('change', function () {
3708
                    slctThird.empty().selectpicker('refresh');
3709
3710
                    var level = $(this).val();
3711
3712
                    if (!level) {
3713
                        return;
3714
                    }
3715
3716
                    $.getJSON(_p.web_ajax + 'extra_field.ajax.php', {
3717
                        'a': 'get_second_select_options',
3718
                        'type': '$this->type',
3719
                        'field_id': $id,
3720
                        'option_value_id': level
3721
                    })
3722
                        .done(function (data) {
3723
                            slctThird.append(
3724
                                $('<option>', {value: '', text: '$langSelect'})
3725
                            );
3726
3727
                            $.each(data, function (index, value) {
3728
                                var valueParts = value.split('#'),
3729
                                    dataValue = valueParts.length > 1 ? valueParts.shift() : '';
3730
3731
                                slctThird.append(
3732
                                    $('<option>', {value: index, text: valueParts.join(''), 'data-value': dataValue})
3733
                                );
3734
                            });
3735
3736
                            slctThird.selectpicker('refresh');
3737
                        });
3738
                });
3739
            })();
3740
        ";
3741
3742
        $firstId = isset($extraData["extra_$variable"]["extra_$variable"])
3743
            ? $extraData["extra_$variable"]["extra_$variable"]
3744
            : '';
3745
        $secondId = isset($extraData["extra_$variable"]["extra_{$variable}_second"])
3746
            ? $extraData["extra_$variable"]["extra_{$variable}_second"]
3747
            : '';
3748
3749
        $options = $this->tripleSelectConvertArrayToOrderedArray($fieldDetails['options']);
3750
        $values1 = ['' => $langSelect];
3751
        $values2 = ['' => $langSelect];
3752
        $values3 = ['' => $langSelect];
3753
        $level1 = $this->getOptionsFromTripleSelect($options['level1'], 0);
3754
        $level2 = $this->getOptionsFromTripleSelect($options['level2'], $firstId);
3755
        $level3 = $this->getOptionsFromTripleSelect($options['level3'], $secondId);
3756
        /** @var \HTML_QuickForm_select $slctFirst */
3757
        $slctFirst = $form->createElement('select', "extra_$variable", null, $values1, ['id' => $slctFirstId]);
3758
        /** @var \HTML_QuickForm_select $slctFirst */
3759
        $slctSecond = $form->createElement(
3760
            'select',
3761
            "extra_{$variable}_second",
3762
            null,
3763
            $values2,
3764
            ['id' => $slctSecondId]
3765
        );
3766
        /** @var \HTML_QuickForm_select $slctFirst */
3767
        $slctThird = $form->createElement('select', "extra_{$variable}_third", null, $values3, ['id' => $slctThirdId]);
3768
3769
        foreach ($level1 as $item1) {
3770
            $valueParts = explode('#', $item1['display_text']);
3771
            $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
3772
            $slctFirst->addOption(implode('', $valueParts), $item1['id'], ['data-value' => $dataValue]);
3773
        }
3774
3775
        foreach ($level2 as $item2) {
3776
            $valueParts = explode('#', $item2['display_text']);
3777
            $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
3778
            $slctSecond->addOption(implode('', $valueParts), $item2['id'], ['data-value' => $dataValue]);
3779
        }
3780
3781
        foreach ($level3 as $item3) {
3782
            $valueParts = explode('#', $item3['display_text']);
3783
            $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
3784
            $slctThird->addOption(implode('', $valueParts), $item3['id'], ['data-value' => $dataValue]);
3785
        }
3786
3787
        $form
3788
            ->defaultRenderer()
3789
            ->setGroupElementTemplate('<p>{element}</p>', "extra_$variable");
3790
        $form->addGroup([$slctFirst, $slctSecond, $slctThird], "extra_$variable", $fieldDetails['display_text']);
3791
3792
        if ($freezeElement) {
3793
            $form->freeze('extra_'.$fieldDetails['variable']);
3794
        }
3795
3796
        return $js;
3797
    }
3798
3799
3800
    /**
3801
     * @param int   $parentId
3802
     *
3803
     * @return array
3804
     */
3805
    private static function getOptionsFromTripleSelect(array $options, $parentId)
3806
    {
3807
        return array_filter(
3808
            $options,
3809
            function ($option) use ($parentId) {
3810
            return $option['option_value'] == $parentId;
3811
            }
3812
        );
3813
    }
3814
}
3815