Passed
Push — preprodparkur ( 752246...93e702 )
by Julito
23:43 queued 10:25
created

ExtraField::set_extra_fields_in_form()   F

Complexity

Conditions 166
Paths 3

Size

Total Lines 1031
Code Lines 637

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 166
eloc 637
c 3
b 0
f 0
nc 3
nop 16
dl 0
loc 1031
rs 3.3333

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

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

1127
            /** @scrutinizer ignore-call */ 
1128
            $max_order = self::get_max_field_order();
Loading history...
1128
            $params['field_order'] = $max_order;
1129
        } else {
1130
            $params['field_order'] = (int) $params['field_order'];
1131
        }
1132
1133
        return $params;
1134
    }
1135
1136
    /**
1137
     * @param array $params
1138
     * @param bool  $show_query
1139
     *
1140
     * @return int|bool
1141
     */
1142
    public function save($params, $show_query = false)
1143
    {
1144
        $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

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

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