Completed
Push — 1.11.x ( 7723ba...4e7830 )
by José
595:51 queued 554:46
created

ExtraField::get_count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
5
6
/**
7
 * Class ExtraField
8
 */
9
class ExtraField extends Model
10
{
11
    public $columns = array(
12
        'id',
13
        'field_type',
14
        'variable',
15
        'display_text',
16
        'default_value',
17
        'field_order',
18
        'visible',
19
        'changeable',
20
        'filter',
21
        'extra_field_type',
22
         /* Enable this when field_loggeable is introduced as a table field (2.0)
23
        'field_loggeable',
24
         */
25
        'created_at'
26
    );
27
28
    public $ops = array(
29
        'eq' => '=',        //equal
30
        'ne' => '<>',       //not equal
31
        'lt' => '<',        //less than
32
        'le' => '<=',       //less than or equal
33
        'gt' => '>',        //greater than
34
        'ge' => '>=',       //greater than or equal
35
        'bw' => 'LIKE',     //begins with
36
        'bn' => 'NOT LIKE', //doesn't begin with
37
        'in' => 'LIKE',     //is in
38
        'ni' => 'NOT LIKE', //is not in
39
        'ew' => 'LIKE',     //ends with
40
        'en' => 'NOT LIKE', //doesn't end with
41
        'cn' => 'LIKE',     //contains
42
        'nc' => 'NOT LIKE'  //doesn't contain
43
    );
44
45
    const FIELD_TYPE_TEXT = 1;
46
    const FIELD_TYPE_TEXTAREA = 2;
47
    const FIELD_TYPE_RADIO = 3;
48
    const FIELD_TYPE_SELECT = 4;
49
    const FIELD_TYPE_SELECT_MULTIPLE = 5;
50
    const FIELD_TYPE_DATE = 6;
51
    const FIELD_TYPE_DATETIME = 7;
52
    const FIELD_TYPE_DOUBLE_SELECT = 8;
53
    const FIELD_TYPE_DIVIDER = 9;
54
    const FIELD_TYPE_TAG = 10;
55
    const FIELD_TYPE_TIMEZONE = 11;
56
    const FIELD_TYPE_SOCIAL_PROFILE = 12;
57
    const FIELD_TYPE_CHECKBOX = 13;
58
    const FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
59
    const FIELD_TYPE_INTEGER = 15;
60
    const FIELD_TYPE_FILE_IMAGE = 16;
61
    const FIELD_TYPE_FLOAT = 17;
62
    const FIELD_TYPE_FILE = 18;
63
    const FIELD_TYPE_VIDEO_URL = 19;
64
    const FIELD_TYPE_LETTERS_ONLY = 20;
65
    const FIELD_TYPE_ALPHANUMERIC = 21;
66
    const FIELD_TYPE_LETTERS_SPACE = 22;
67
    const FIELD_TYPE_ALPHANUMERIC_SPACE = 23;
68
    const FIELD_TYPE_GEOLOCALIZATION = 24;
69
70
    public $type = 'user';
71
    public $pageName;
72
    public $pageUrl;
73
    public $extraFieldType = 0;
74
75
    public $table_field_options;
76
    public $table_field_values;
77
    public $table_field_tag;
78
    public $table_field_rel_tag;
79
80
    public $handler_id;
81
    public $primaryKey;
82
83
    /**
84
     * @param string $type
85
     */
86
    public function __construct($type)
87
    {
88
        parent::__construct();
89
90
        $this->type = $type;
91
92
        $this->table = Database::get_main_table(TABLE_EXTRA_FIELD);
93
        $this->table_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
94
        $this->table_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
95
        $this->table_field_tag = Database::get_main_table(TABLE_MAIN_TAG);
96
        $this->table_field_rel_tag = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
97
98
        $this->handler_id = 'item_id';
99
100
        switch ($this->type) {
101
            case 'calendar_event':
102
                $this->extraFieldType = EntityExtraField::CALENDAR_FIELD_TYPE;
103
                break;
104
            case 'course':
105
                $this->extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
106
                $this->primaryKey = 'id';
107
                break;
108
            case 'user':
109
                $this->extraFieldType = EntityExtraField::USER_FIELD_TYPE;
110
                $this->primaryKey = 'id';
111
                break;
112
            case 'session':
113
                $this->extraFieldType = EntityExtraField::SESSION_FIELD_TYPE;
114
                $this->primaryKey = 'id';
115
                break;
116
            case 'question':
117
                $this->extraFieldType = EntityExtraField::QUESTION_FIELD_TYPE;
118
                break;
119
            case 'lp':
120
                $this->extraFieldType = EntityExtraField::LP_FIELD_TYPE;
121
                break;
122
            case 'lp_item':
123
                $this->extraFieldType = EntityExtraField::LP_ITEM_FIELD_TYPE;
124
                break;
125
            case 'skill':
126
                $this->extraFieldType = EntityExtraField::SKILL_FIELD_TYPE;
127
        }
128
129
        $this->pageUrl  = 'extra_fields.php?type='.$this->type;
130
        // Example QuestionFields
131
        $this->pageName = get_lang(ucwords($this->type).'Fields');
132
    }
133
134
    /**
135
     * @return int
136
     */
137
    public function getExtraFieldType()
138
    {
139
        return $this->extraFieldType;
140
    }
141
142
    /**
143
     * @return array
144
     */
145
    public static function getValidExtraFieldTypes()
146
    {
147
        return array(
148
            'user',
149
            'course',
150
            'session',
151
            'question',
152
            'lp',
153
            'calendar_event',
154
            'lp_item',
155
            'skill'
156
        );
157
    }
158
159
    /**
160
     * @return int
161
     */
162 View Code Duplication
    public function get_count()
163
    {
164
        $em = Database::getManager();
165
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
166
        $query->select('count(e.id)');
167
        $query->where('e.extraFieldType = :type');
168
        $query->setParameter('type', $this->getExtraFieldType());
169
170
        return $query->getQuery()->getScalarResult();
171
    }
172
173
    /**
174
     * @param string $sidx
175
     * @param string $sord
176
     * @param int $start
177
     * @param int $limit
178
     *
179
     * @return array
180
     */
181
    public function getAllGrid($sidx, $sord, $start, $limit)
182
    {
183
        switch ($sidx) {
184
            case 'field_order':
185
                $sidx = 'e.fieldOrder';
186
                break;
187
            case 'variable':
188
                $sidx = 'e.variable';
189
                break;
190
            case 'display_text':
191
                $sidx = 'e.displayText';
192
                break;
193
            case 'changeable':
194
                $sidx = 'e.changeable';
195
                break;
196
            case 'visible':
197
                $sidx = 'e.visible';
198
                break;
199
            case 'filter':
200
                $sidx = 'e.filter';
201
                break;
202
            case 'display_text':
203
                $sidx = 'e.fieldType';
204
                break;
205
        }
206
        $em = Database::getManager();
207
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
208
        $query->select('e')
209
            ->where('e.extraFieldType = :type')
210
            ->setParameter('type', $this->getExtraFieldType())
211
            ->orderBy($sidx, $sord)
212
            ->setFirstResult($start)
213
            ->setMaxResults($limit);
214
        //echo $query->getQuery()->getSQL();
215
        return $query->getQuery()->getArrayResult();
216
    }
217
218
    /**
219
     * @param array $conditions
220
     * @param null  $order_field_options_by
221
     *
222
     * @return array
223
     */
224
    public function get_all($conditions = array(), $order_field_options_by = null)
225
    {
226
        $conditions = Database::parse_conditions(array('where' => $conditions));
227
228
        if (empty($conditions)) {
229
            $conditions .= " WHERE extra_field_type = ".$this->extraFieldType;
230
        } else {
231
            $conditions .= " AND extra_field_type = ".$this->extraFieldType;
232
        }
233
234
        $sql = "SELECT * FROM $this->table
235
                $conditions
236
                ORDER BY field_order ASC
237
        ";
238
        $result = Database::query($sql);
239
        $extraFields = Database::store_result($result, 'ASSOC');
240
241
        $option = new ExtraFieldOption($this->type);
242
        if (!empty($extraFields)) {
243
            foreach ($extraFields as &$extraField) {
244
                $extraField['display_text'] = self::translateDisplayName(
245
                    $extraField['variable'],
246
                    $extraField['display_text']
247
                );
248
                $extraField['options'] = $option->get_field_options_by_field(
249
                    $extraField['id'],
250
                    false,
251
                    $order_field_options_by
252
                );
253
            }
254
        }
255
256
        return $extraFields;
257
    }
258
259
    /**
260
     * @param string $variable
261
     *
262
     * @return array|bool
263
     */
264 View Code Duplication
    public function get_handler_field_info_by_field_variable($variable)
265
    {
266
        $variable = Database::escape_string($variable);
267
        $sql = "SELECT * FROM {$this->table}
268
                WHERE
269
                    variable = '$variable' AND
270
                    extra_field_type = $this->extraFieldType";
271
        $result = Database::query($sql);
272
        if (Database::num_rows($result)) {
273
            $row = Database::fetch_array($result, 'ASSOC');
274
            $row['display_text'] = ExtraField::translateDisplayName($row['variable'], $row['display_text']);
275
276
            // All the options of the field
277
            $sql = "SELECT * FROM $this->table_field_options
278
                    WHERE field_id='".intval($row['id'])."'
279
                    ORDER BY option_order ASC";
280
            $result = Database::query($sql);
281
            while ($option = Database::fetch_array($result)) {
282
                $row['options'][$option['id']] = $option;
283
            }
284
285
            return $row;
286
        } else {
287
            return false;
288
        }
289
    }
290
291
    /**
292
     * Get all the field info for tags
293
     * @param string $variable
294
     *
295
     * @return array|bool
296
     */
297 View Code Duplication
    public function get_handler_field_info_by_tags($variable)
298
    {
299
        $variable = Database::escape_string($variable);
300
        $sql = "SELECT * FROM {$this->table}
301
                WHERE
302
                    variable = '$variable' AND
303
                    extra_field_type = $this->extraFieldType";
304
        $result = Database::query($sql);
305
        if (Database::num_rows($result)) {
306
            $row = Database::fetch_array($result, 'ASSOC');
307
            $row['display_text'] = ExtraField::translateDisplayName($row['variable'], $row['display_text']);
308
309
            // All the tags of the field
310
            $sql = "SELECT * FROM $this->table_field_tag
311
                    WHERE field_id='".intval($row['id'])."'
312
                    ORDER BY id ASC";
313
            $result = Database::query($sql);
314
            while ($option = Database::fetch_array($result, 'ASSOC')) {
315
                $row['options'][$option['id']] = $option;
316
            }
317
318
            return $row;
319
        } else {
320
            return false;
321
        }
322
    }
323
324
    /**
325
     * @param int $fieldId
326
     *
327
     * @return array|bool
328
     */
329
    public function getFieldInfoByFieldId($fieldId)
330
    {
331
        $fieldId = intval($fieldId);
332
        $sql = "SELECT * FROM {$this->table}
333
                WHERE
334
                    field_id = '$fieldId' AND
335
                    extra_field_type = $this->extraFieldType";
336
        $result = Database::query($sql);
337
        if (Database::num_rows($result)) {
338
            $row = Database::fetch_array($result, 'ASSOC');
339
340
            // All the options of the field
341
            $sql = "SELECT * FROM $this->table_field_options
342
                    WHERE field_id='".$fieldId."'
343
                    ORDER BY option_order ASC";
344
            $result = Database::query($sql);
345
            while ($option = Database::fetch_array($result)) {
346
                $row['options'][$option['id']] = $option;
347
            }
348
349
            return $row;
350
        } else {
351
            return false;
352
        }
353
    }
354
355
    /**
356
     * @return int
357
     */
358
    public function get_max_field_order()
359
    {
360
        $sql = "SELECT MAX(field_order)
361
                FROM {$this->table}
362
                WHERE
363
                    extra_field_type = '.$this->extraFieldType.'";
364
        $res = Database::query($sql);
365
366
        $order = 0;
367
        if (Database::num_rows($res) > 0) {
368
            $row = Database::fetch_row($res);
369
            $order = $row[0] + 1;
370
        }
371
372
        return $order;
373
    }
374
375
    /**
376
     * @param string $handler
377
     *
378
     * @return array
379
     */
380
    public static function get_extra_fields_by_handler($handler)
381
    {
382
        $types= array();
383
        $types[self::FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
384
        $types[self::FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
385
        $types[self::FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
386
        $types[self::FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
387
        $types[self::FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
388
        $types[self::FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
389
        $types[self::FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
390
        $types[self::FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
391
        $types[self::FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
392
        $types[self::FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
393
        $types[self::FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
394
        $types[self::FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
395
        $types[self::FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
396
        $types[self::FIELD_TYPE_CHECKBOX] = get_lang('FieldTypeCheckbox');
397
        $types[self::FIELD_TYPE_INTEGER] = get_lang('FieldTypeInteger');
398
        $types[self::FIELD_TYPE_FILE_IMAGE] = get_lang('FieldTypeFileImage');
399
        $types[self::FIELD_TYPE_FLOAT] = get_lang('FieldTypeFloat');
400
        $types[self::FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
401
        $types[self::FIELD_TYPE_VIDEO_URL] = get_lang('FieldTypeVideoUrl');
402
        $types[self::FIELD_TYPE_LETTERS_ONLY] = get_lang('FieldTypeOnlyLetters');
403
        $types[self::FIELD_TYPE_ALPHANUMERIC] = get_lang('FieldTypeAlphanumeric');
404
        $types[self::FIELD_TYPE_LETTERS_SPACE] = get_lang(
405
            'FieldTypeLettersSpaces'
406
        );
407
        $types[self::FIELD_TYPE_ALPHANUMERIC_SPACE] = get_lang(
408
            'FieldTypeAlphanumericSpaces'
409
        );
410
        $types[self::FIELD_TYPE_GEOLOCALIZATION] = get_lang(
411
            'Geolocalization'
412
        );
413
414
        switch ($handler) {
415
            case 'course':
416
                // no break
417
            case 'session':
418
                // no break
419
            case 'user':
420
                // no break
421
            case 'skill':
422
                break;
423
        }
424
425
        return $types;
426
    }
427
428
    /**
429
     * Add elements to a form
430
     *
431
     * @param FormValidator $form
432
     * @param int $itemId
433
     * @param array $exclude variables of extra field to exclude
434
     * @param bool $filter
435
     *
436
     * @return array|bool
437
     */
438
    public function addElements(
439
        $form,
440
        $itemId = 0,
441
        $exclude = [],
442
        $filter = false,
443
        $useTagAsSelect = false,
444
        $showOnlyThisFields = [],
445
        $orderFields = []
446
    ) {
447
        if (empty($form)) {
448
            return false;
449
        }
450
451
        $itemId = intval($itemId);
452
        $form->addHidden('item_id', $itemId);
453
        $extraData = false;
454
        if (!empty($itemId)) {
455
            $extraData = self::get_handler_extra_data($itemId);
456
457
            if ($form) {
458
                $form->setDefaults($extraData);
459
            }
460
        }
461
462
        $conditions = [];
463
        if ($filter) {
464
            $conditions = ['filter = ?' => 1];
465
        }
466
        $extraFields = $this->get_all($conditions, 'option_order');
467
        $extra = $this->set_extra_fields_in_form(
468
            $form,
469
            $extraData,
0 ignored issues
show
Security Bug introduced by
It seems like $extraData defined by false on line 453 can also be of type false; however, ExtraField::set_extra_fields_in_form() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
470
            false,
471
            $extraFields,
472
            $itemId,
473
            $exclude,
474
            $useTagAsSelect,
475
            $showOnlyThisFields,
476
            $orderFields
477
        );
478
479
        return $extra;
480
    }
481
482
    /**
483
     * @param int $itemId (session_id, question_id, course id)
484
     *
485
     * @return array
486
     */
487
    public function get_handler_extra_data($itemId)
488
    {
489
        if (empty($itemId)) {
490
            return array();
491
        }
492
493
        $extra_data = array();
494
        $fields = self::get_all();
495
        $field_values = new ExtraFieldValue($this->type);
496
497
        if (!empty($fields) > 0) {
498
            foreach ($fields as $field) {
499
500
                $field_value = $field_values->get_values_by_handler_and_field_id(
501
                    $itemId, $field['id']
502
                );
503
504
                if ($field['field_type'] == ExtraField::FIELD_TYPE_TAG) {
505
                    $tags = UserManager::get_user_tags_to_string($itemId, $field['id'], false);
506
                    $extra_data['extra_'.$field['variable']] = $tags;
507
508
                    continue;
509
                }
510
511
                if ($field_value) {
512
                    $field_value = $field_value['value'];
513
                    switch ($field['field_type']) {
514
                        case ExtraField::FIELD_TYPE_TAG:
515
                            $tags = UserManager::get_user_tags_to_string($itemId, $field['id'], false);
516
517
                            $extra_data['extra_'.$field['variable']] = $tags;
518
                            break;
519
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
520
                            $selected_options = explode(
521
                                '::',
522
                                $field_value
523
                            );
524
                            $firstOption = isset($selected_options[0]) ? $selected_options[0] : '';
525
                            $secondOption = isset($selected_options[1]) ? $selected_options[1] : '';
526
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $firstOption;
527
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable'].'_second'] = $secondOption;
528
529
                            break;
530
                        case ExtraField::FIELD_TYPE_SELECT_MULTIPLE:
531
                            $field_value = explode(';', $field_value);
532
                            $extra_data['extra_'.$field['variable']] = $field_value;
533
                            break;
534
                        case ExtraField::FIELD_TYPE_RADIO:
535
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $field_value;
536
                            break;
537
                        default:
538
                            $extra_data['extra_'.$field['variable']] = $field_value;
539
                            break;
540
                    }
541
                } else {
542
                    // Set default values
543
                    if (isset($field['field_default_value']) && !empty($field['field_default_value'])) {
544
                        $extra_data['extra_'.$field['variable']] = $field['field_default_value'];
545
                    }
546
                }
547
            }
548
        }
549
550
        return $extra_data;
551
    }
552
553
    /**
554
     * @param string $field_type
555
     *
556
     * @return array
557
     */
558
    public function get_all_extra_field_by_type($field_type)
559
    {
560
        // all the information of the field
561
        $sql = "SELECT * FROM {$this->table}
562
                WHERE
563
                    field_type = '".Database::escape_string($field_type)."' AND
564
                    extra_field_type = $this->extraFieldType
565
                ";
566
        $result = Database::query($sql);
567
568
        $return = array();
569
        while ($row = Database::fetch_array($result)) {
570
            $return[] = $row['id'];
571
        }
572
573
        return $return;
574
    }
575
576
    /**
577
     * @return array
578
     */
579
    public function get_field_types()
580
    {
581
        return self::get_extra_fields_by_handler($this->type);
582
    }
583
584
    /**
585
     * @param int $id
586
     *
587
     * @return null
588
     */
589
    public function get_field_type_by_id($id)
590
    {
591
        $types = self::get_field_types();
592
        if (isset($types[$id])) {
593
            return $types[$id];
594
        }
595
596
        return null;
597
    }
598
599
    /**
600
     * Converts a string like this:
601
     * France:Paris;Bretagne;Marseille;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
602
     * into
603
     * array(
604
     *   'France' =>
605
     *      array('Paris', 'Bregtane', 'Marseille'),
606
     *   'Belgique' =>
607
     *      array('Namur', 'Liège')
608
     * ), etc
609
     * @param string $string
610
     *
611
     * @return array
612
     */
613
    public static function extra_field_double_select_convert_string_to_array($string)
614
    {
615
        $options = explode('|', $string);
616
        $options_parsed = array();
617
        $id = 0;
618
619
        if (!empty($options)) {
620
            foreach ($options as $sub_options) {
621
                $options = explode(':', $sub_options);
622
                $sub_sub_options = explode(';', $options[1]);
623
                $options_parsed[$id] = array(
624
                    'label' => $options[0],
625
                    'options' => $sub_sub_options,
626
                );
627
                $id++;
628
            }
629
        }
630
631
        return $options_parsed;
632
    }
633
634
    /**
635
     * @param array $options
636
     *
637
     * @return array
638
     */
639
    public static function extra_field_double_select_convert_array_to_ordered_array($options)
640
    {
641
        $options_parsed = array();
642
        if (!empty($options)) {
643
            foreach ($options as $option) {
644
                if ($option['option_value'] == 0) {
645
                    $options_parsed[$option['id']][] = $option;
646
                } else {
647
                    $options_parsed[$option['option_value']][] = $option;
648
                }
649
            }
650
        }
651
652
        return $options_parsed;
653
    }
654
655
    /**
656
     * @param array $options the result of the get_field_options_by_field() array
657
     *
658
     * @return string
659
     */
660
    public static function extra_field_double_select_convert_array_to_string($options)
661
    {
662
        $string = null;
663
        $options_parsed = self::extra_field_double_select_convert_array_to_ordered_array($options);
664
665
        if (!empty($options_parsed)) {
666
            foreach ($options_parsed as $option) {
667
                foreach ($option as $key => $item) {
668
                    $string .= $item['display_text'];
669
                    if ($key == 0) {
670
                        $string .= ':';
671
                    } else {
672
                        if (isset($option[$key + 1])) {
673
                            $string .= ';';
674
                        }
675
                    }
676
                }
677
                $string .= '|';
678
            }
679
        }
680
681
        if (!empty($string)) {
682
            $string = substr($string, 0, strlen($string) - 1);
683
        }
684
685
        return $string;
686
    }
687
688
    /**
689
     * @param array $params
690
     *
691
     * @return array
692
     */
693
    public function clean_parameters($params)
694
    {
695
        if (!isset($params['variable']) || empty($params['variable'])) {
696
            $params['variable'] = $params['display_text'];
697
        }
698
699
        $params['variable'] = trim(strtolower(str_replace(" ", "_", $params['variable'])));
700
701
        if (!isset($params['field_order'])) {
702
            $max_order = self::get_max_field_order();
703
            $params['field_order'] = $max_order;
704
        } else {
705
            $params['field_order'] = (int) $params['field_order'];
706
        }
707
708
        return $params;
709
    }
710
711
    /**
712
     * @param array $params
713
     * @param bool  $show_query
714
     *
715
     * @return bool
716
     */
717
    public function save($params, $show_query = false)
718
    {
719
        $fieldInfo = self::get_handler_field_info_by_field_variable($params['variable']);
720
        $params = self::clean_parameters($params);
721
        $params['extra_field_type'] = $this->extraFieldType;
722
723
        if ($fieldInfo) {
724
            return $fieldInfo['id'];
725
        } else {
726
            $id = parent::save($params, $show_query);
727
            if ($id) {
728
                $session_field_option = new ExtraFieldOption($this->type);
729
                $params['field_id'] = $id;
730
                $session_field_option->save($params);
731
            }
732
733
            return $id;
734
        }
735
    }
736
737
    /**
738
     * @param array $params
739
     *
740
     * @return bool|void
741
     */
742
    public function update($params)
743
    {
744
        $params = self::clean_parameters($params);
745
        if (isset($params['id'])) {
746
            $field_option = new ExtraFieldOption($this->type);
747
            $params['field_id'] = $params['id'];
748
            $field_option->save($params);
749
        }
750
751
        parent::update($params);
752
    }
753
754
    /**
755
     * @param $id
756
     *
757
     * @return bool|void
758
     */
759
    public function delete($id)
760
    {
761
        $em = Database::getManager();
762
        $items = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findBy(['field' => $id]);
763
        if ($items) {
764
            foreach ($items as $item) {
765
                $em->remove($item);
766
            }
767
            $em->flush();
768
        }
769
        $field_option = new ExtraFieldOption($this->type);
770
        $field_option->delete_all_options_by_field_id($id);
771
772
        $session_field_values = new ExtraFieldValue($this->type);
773
        $session_field_values->delete_all_values_by_field_id($id);
774
775
        parent::delete($id);
776
    }
777
778
    /**
779
     * Add an element that matches the given extra field to the given $form object
780
     * @param FormValidator $form
781
     * @param array $extraData
782
     * @param bool $admin_permissions
783
     * @param array $extra
784
     * @param int $itemId
785
     * @param array $exclude variables of extra field to exclude
786
     * @param bool $useTagAsSelect
787
     * @param array $showOnlyThisFields
788
     * @param array $orderFields
789
     * @return array If relevant, returns a one-element array with JS code to be added to the page HTML headers
790
     */
791
    public function set_extra_fields_in_form(
792
        $form,
793
        $extraData,
794
        $admin_permissions = false,
795
        $extra = array(),
796
        $itemId = null,
797
        $exclude = [],
798
        $useTagAsSelect = false,
799
        $showOnlyThisFields = [],
800
        $orderFields = []
801
    ) {
802
        $type = $this->type;
803
        $jquery_ready_content = null;
804
        if (!empty($extra)) {
805
806
            $newOrder = [];
807
            if (!empty($orderFields)) {
808
                foreach ($orderFields as $order) {
809
                    foreach ($extra as $field_details) {
810
                        if ($order == $field_details['variable']) {
811
                           $newOrder[] = $field_details;
812
                        }
813
                    }
814
                }
815
                $extra = $newOrder;
816
            }
817
818
            foreach ($extra as $field_details) {
819
                if (!empty($showOnlyThisFields)) {
820
                    if (!in_array($field_details['variable'], $showOnlyThisFields)) {
821
                        continue;
822
                    }
823
                }
824
825
                // Getting default value id if is set
826
                $defaultValueId = null;
827
                if (isset($field_details['options']) && !empty($field_details['options'])) {
828
                    $valueToFind = null;
829
                    if (isset($field_details['field_default_value'])) {
830
                        $valueToFind = $field_details['field_default_value'];
831
                    }
832
                    // If a value is found we override the default value
833
                    if (isset($extraData['extra_'.$field_details['variable']])) {
834
                        $valueToFind = $extraData['extra_'.$field_details['variable']];
835
                    }
836
837
                    foreach ($field_details['options'] as $option) {
838
                        if ($option['option_value'] == $valueToFind) {
839
                            $defaultValueId = $option['id'];
840
                        }
841
                    }
842
                }
843
844
                if (!$admin_permissions) {
845
                    if ($field_details['visible'] == 0) {
846
                        continue;
847
                    }
848
849
                    if (in_array($field_details['variable'], $exclude)) {
850
                        continue;
851
                    }
852
                }
853
854
                switch ($field_details['field_type']) {
855
                    case ExtraField::FIELD_TYPE_TEXT:
856
                        $form->addElement(
857
                            'text',
858
                            'extra_'.$field_details['variable'],
859
                            $field_details['display_text'],
860
                            array()
861
                        );
862
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
863
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
864
                        if (!$admin_permissions) {
865
                            if ($field_details['visible'] == 0) {
866
                                $form->freeze(
867
                                    'extra_'.$field_details['variable']
868
                                );
869
                            }
870
                        }
871
                        break;
872 View Code Duplication
                    case ExtraField::FIELD_TYPE_TEXTAREA:
873
                        $form->addHtmlEditor(
874
                            'extra_'.$field_details['variable'],
875
                            $field_details['display_text'],
876
                            false,
877
                            false,
878
                            array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')
879
                        );
880
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
881
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
882
                        if (!$admin_permissions) {
883
                            if ($field_details['visible'] == 0) {
884
                                $form->freeze(
885
                                    'extra_'.$field_details['variable']
886
                                );
887
                            }
888
                        }
889
                        break;
890
                    case ExtraField::FIELD_TYPE_RADIO:
891
                        $group = array();
892
                        if (isset($field_details['options']) && !empty($field_details['options'])) {
893 View Code Duplication
                            foreach ($field_details['options'] as $option_details) {
894
                                $options[$option_details['option_value']] = $option_details['display_text'];
895
                                $group[] = $form->createElement(
896
                                    'radio',
897
                                    'extra_'.$field_details['variable'],
898
                                    $option_details['option_value'],
899
                                    $option_details['display_text'].'<br />',
900
                                    $option_details['option_value']
901
                                );
902
                            }
903
                        }
904
                        $form->addGroup(
905
                            $group,
906
                            'extra_'.$field_details['variable'],
907
                            $field_details['display_text'],
908
                            ''
909
                        );
910
                        if (!$admin_permissions) {
911
                            if ($field_details['visible'] == 0) {
912
                                $form->freeze(
913
                                    'extra_'.$field_details['variable']
914
                                );
915
                            }
916
                        }
917
                        break;
918
                    case ExtraField::FIELD_TYPE_CHECKBOX:
919
                        $group = array();
920
                        if (isset($field_details['options']) && !empty($field_details['options'])) {
921 View Code Duplication
                            foreach ($field_details['options'] as $option_details) {
922
                                $options[$option_details['option_value']] = $option_details['display_text'];
923
                                $group[] = $form->createElement(
924
                                    'checkbox',
925
                                    'extra_'.$field_details['variable'],
926
                                    $option_details['option_value'],
927
                                    $option_details['display_text'].'<br />',
928
                                    $option_details['option_value']
929
                                );
930
                            }
931
                        } else {
932
                            $fieldVariable = "extra_{$field_details['variable']}";
933
                            $checkboxAttributes = array();
934
                            if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
935
                                if (!empty($extraData[$fieldVariable])) {
936
                                    $checkboxAttributes['checked'] = 1;
937
                                }
938
                            }
939
940
                            // We assume that is a switch on/off with 1 and 0 as values
941
                            $group[] = $form->createElement(
942
                                'checkbox',
943
                                'extra_'.$field_details['variable'],
944
                                null,
945
                                //$field_details['display_text'].'<br />',
946
                                get_lang('Yes'),
947
                                $checkboxAttributes
948
                            );
949
                        }
950
951
                        $form->addGroup(
952
                            $group,
953
                            'extra_'.$field_details['variable'],
954
                            $field_details['display_text'],
955
                            ''
956
                        );
957
                        if (!$admin_permissions) {
958
                            if ($field_details['visible'] == 0) {
959
                                $form->freeze(
960
                                    'extra_'.$field_details['variable']
961
                                );
962
                            }
963
                        }
964
                        break;
965
                    case ExtraField::FIELD_TYPE_SELECT:
966
                        $get_lang_variables = false;
967
                        if (in_array(
968
                            $field_details['variable'],
969
                            array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message')
970
                        )
971
                        ) {
972
                            $get_lang_variables = true;
973
                        }
974
975
                        // Get extra field workflow
976
                        $userInfo = api_get_user_info();
977
                        $addOptions = array();
978
                        $optionsExists = false;
979
                        global $app;
980
                        // Check if exist $app['orm.em'] object
981
                        if (isset($app['orm.em']) && is_object($app['orm.em'])) {
982
                            $optionsExists = $app['orm.em']
983
                                ->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
984
                                ->findOneBy(array('fieldId' => $field_details['id']));
985
                        }
986
987
                        if ($optionsExists) {
988
                            if (isset($userInfo['status']) && !empty($userInfo['status'])) {
989
990
                                $fieldWorkFlow = $app['orm.em']->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
991
                                    ->findBy(
992
                                        array(
993
                                            'fieldId' => $field_details['id'],
994
                                            'relatedFieldOptionId' => $defaultValueId,
995
                                            'roleId' => $userInfo['status']
996
                                        )
997
                                    );
998
                                foreach ($fieldWorkFlow as $item) {
999
                                    $addOptions[] = $item->getFieldOptionId();
1000
                                }
1001
                            }
1002
                        }
1003
1004
                        $options = array();
1005
                        if (empty($defaultValueId)) {
1006
                            $options[''] = get_lang('SelectAnOption');
1007
                        }
1008
1009
                        $optionList = array();
1010
                        if (!empty($field_details['options'])) {
1011
                            foreach ($field_details['options'] as $option_details) {
1012
                                $optionList[$option_details['id']] = $option_details;
1013
                                if ($get_lang_variables) {
1014
                                    $options[$option_details['option_value']] = $option_details['display_text'];
1015
                                } else {
1016
                                    if ($optionsExists) {
1017
                                        // Adding always the default value
1018 View Code Duplication
                                        if ($option_details['id'] == $defaultValueId) {
1019
                                            $options[$option_details['option_value']] = $option_details['display_text'];
1020
                                        } else {
1021
                                            if (isset($addOptions) && !empty($addOptions)) {
1022
                                                // Parsing filters
1023
                                                if (in_array($option_details['id'], $addOptions)) {
1024
                                                    $options[$option_details['option_value']] = $option_details['display_text'];
1025
                                                }
1026
                                            }
1027
                                        }
1028
                                    } else {
1029
                                        // Normal behaviour
1030
                                        $options[$option_details['option_value']] = $option_details['display_text'];
1031
                                    }
1032
                                }
1033
                            }
1034
1035
                            if (isset($optionList[$defaultValueId])) {
1036
                                if (isset($optionList[$defaultValueId]['option_value']) &&
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
1037
                                    $optionList[$defaultValueId]['option_value'] == 'aprobada'
1038
                                ) {
1039
                                    // @todo function don't exists api_is_question_manager
1040
                                    /*if (api_is_question_manager() == false) {
1041
                                        $form->freeze();
1042
                                    }*/
1043
                                }
1044
                            }
1045
1046
                            // Setting priority message
1047
                            if (isset($optionList[$defaultValueId]) &&
1048
                                isset($optionList[$defaultValueId]['priority'])
1049
                            ) {
1050
1051
                                if (!empty($optionList[$defaultValueId]['priority'])) {
1052
                                    $priorityId = $optionList[$defaultValueId]['priority'];
1053
                                    $option = new ExtraFieldOption($this->type);
1054
                                    $messageType = $option->getPriorityMessageType($priorityId);
1055
                                    $form->addElement(
1056
                                        'label',
1057
                                        null,
1058
                                        Display::return_message(
1059
                                            $optionList[$defaultValueId]['priority_message'],
1060
                                            $messageType
1061
                                        )
1062
                                    );
1063
                                }
1064
                            }
1065
                        }
1066
1067
                        // chzn-select doesn't work for sessions??
1068
                        $form->addElement(
1069
                            'select',
1070
                            'extra_' . $field_details['variable'],
1071
                            $field_details['display_text'],
1072
                            $options,
1073
                            array('id' => 'extra_'.$field_details['variable'])
1074
                        );
1075
1076
                        /* Enable this when field_loggeable is introduced as a table field (2.0)
1077
                        if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) {
1078
1079
                            $form->addElement(
1080
                                'textarea',
1081
                                'extra_' . $field_details['variable'] . '_comment',
1082
                                $field_details['display_text'] . ' ' . get_lang('Comment')
1083
                            );
1084
1085
                            $extraFieldValue = new ExtraFieldValue($this->type);
1086
                            $repo = $app['orm.em']->getRepository($extraFieldValue->entityName);
1087
                            $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry');
1088
                            $newEntity = $repo->findOneBy(
1089
                                array(
1090
                                    $this->handlerEntityId => $itemId,
1091
                                    'fieldId' => $field_details['id']
1092
                                )
1093
                            );
1094
                            // @todo move this in a function inside the class
1095
                            if ($newEntity) {
1096
                                $logs = $repoLog->getLogEntries($newEntity);
1097
                                if (!empty($logs)) {
1098
                                    $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />';
1099
1100
                                    $table = new HTML_Table(array('class' => 'data_table'));
1101
                                    $table->setHeaderContents(0, 0, get_lang('Value'));
1102
                                    $table->setHeaderContents(0, 1, get_lang('Comment'));
1103
                                    $table->setHeaderContents(0, 2, get_lang('ModifyDate'));
1104
                                    $table->setHeaderContents(0, 3, get_lang('Username'));
1105
                                    $row = 1;
1106
                                    foreach ($logs as $log) {
1107
                                        $column = 0;
1108
                                        $data = $log->getData();
1109
                                        $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null;
1110
                                        $comment = isset($data['comment']) ? $data['comment'] : null;
1111
1112
                                        $table->setCellContents($row, $column, $fieldValue);
1113
                                        $column++;
1114
                                        $table->setCellContents($row, $column, $comment);
1115
                                        $column++;
1116
                                        $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s')));
1117
                                        $column++;
1118
                                        $table->setCellContents($row, $column, $log->getUsername());
1119
                                        $row++;
1120
                                    }
1121
                                    $form->addElement('label', null, $html.$table->toHtml());
1122
                                }
1123
                            }
1124
                        }
1125
                        */
1126
1127
                        if (!$admin_permissions) {
1128
                            if ($field_details['visible'] == 0) {
1129
                                $form->freeze('extra_' . $field_details['variable']);
1130
                            }
1131
                        }
1132
                        break;
1133
                    case ExtraField::FIELD_TYPE_SELECT_MULTIPLE:
1134
                        $options = array();
1135
                        foreach ($field_details['options'] as $option_id => $option_details) {
1136
                            $options[$option_details['option_value']] = $option_details['display_text'];
1137
                        }
1138
                        $form->addElement(
1139
                            'select',
1140
                            'extra_'.$field_details['variable'],
1141
                            $field_details['display_text'],
1142
                            $options,
1143
                            array('multiple' => 'multiple', 'id' => 'extra_'.$field_details['variable'])
1144
                        );
1145
                        if (!$admin_permissions) {
1146
                            if ($field_details['visible'] == 0) {
1147
                                $form->freeze('extra_'.$field_details['variable']);
1148
                            }
1149
                        }
1150
                        break;
1151 View Code Duplication
                    case ExtraField::FIELD_TYPE_DATE:
1152
                        $form->addDatePicker('extra_'.$field_details['variable'], $field_details['display_text']);
1153
                        if (!$admin_permissions) {
1154
                            if ($field_details['visible'] == 0) {
1155
                                $form->freeze('extra_'.$field_details['variable']);
1156
                            }
1157
                        }
1158
1159
                        $form->applyFilter('theme', 'trim');
1160
                        break;
1161
                    case ExtraField::FIELD_TYPE_DATETIME:
1162
                        $form->addDateTimePicker(
1163
                            'extra_'.$field_details['variable'],
1164
                            $field_details['display_text']
1165
                        );
1166
1167
                        $defaults['extra_'.$field_details['variable']] = api_get_local_time();
1168
                        if (!isset($form->_defaultValues['extra_'.$field_details['variable']])) {
1169
                            $form->setDefaults($defaults);
1170
                        }
1171
                        if (!$admin_permissions) {
1172
                            if ($field_details['visible'] == 0) {
1173
                                $form->freeze('extra_'.$field_details['variable']);
1174
                            }
1175
                        }
1176
                        $form->applyFilter('theme', 'trim');
1177
                        break;
1178
                    case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
1179
                        $first_select_id = 'first_extra_'.$field_details['variable'];
1180
                        $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
1181
1182
                        $jquery_ready_content .= '
1183
                        $("#'.$first_select_id.'").on("change", function() {
1184
                            var id = $(this).val();
1185
                            if (id) {
1186
                                $.ajax({
1187
                                    url: "'.$url.'&a=get_second_select_options",
1188
                                    dataType: "json",
1189
                                    data: "type='.$type.'&field_id='.$field_details['id'].'&option_value_id="+id,
1190
                                    success: function(data) {
1191
                                        $("#second_extra_'.$field_details['variable'].'").empty();
1192
                                        $.each(data, function(index, value) {
1193
                                            $("#second_extra_'.$field_details['variable'].'").append($("<option/>", {
1194
                                                value: index,
1195
                                                text: value
1196
                                            }));
1197
                                        });
1198
                                        $("#second_extra_'.$field_details['variable'].'").selectpicker("refresh");
1199
                                    },
1200
                                });
1201
                            } else {
1202
                                $("#second_extra_'.$field_details['variable'].'").empty();
1203
                            }
1204
                        });';
1205
1206
                        $first_id  = null;
1207
                        if (!empty($extraData)) {
1208
                            if (isset($extraData['extra_'.$field_details['variable']])) {
1209
                                $first_id = $extraData['extra_'.$field_details['variable']]['extra_'.$field_details['variable']];
1210
                            }
1211
                        }
1212
1213
                        $options = ExtraField::extra_field_double_select_convert_array_to_ordered_array(
1214
                            $field_details['options']
1215
                        );
1216
                        $values = array('' => get_lang('Select'));
1217
1218
                        $second_values = array();
1219
                        if (!empty($options)) {
1220
                            foreach ($options as $option) {
1221
                                foreach ($option as $sub_option) {
1222
                                    if ($sub_option['option_value'] == '0') {
1223
                                        $values[$sub_option['id']] = $sub_option['display_text'];
1224
                                    } else {
1225
                                        if ($first_id === $sub_option['option_value']) {
1226
                                            $second_values[$sub_option['id']] = $sub_option['display_text'];
1227
                                        }
1228
                                    }
1229
                                }
1230
                            }
1231
                        }
1232
                        $group = array();
1233
                        $group[] = $form->createElement(
1234
                            'select',
1235
                            'extra_'.$field_details['variable'],
1236
                            null,
1237
                            $values,
1238
                            array('id' => $first_select_id)
1239
                        );
1240
                        $group[] = $form->createElement(
1241
                            'select',
1242
                            'extra_'.$field_details['variable'].'_second',
1243
                            null,
1244
                            $second_values,
1245
                            array('id' => 'second_extra_'.$field_details['variable'])
1246
                        );
1247
                        $form->addGroup(
1248
                            $group,
1249
                            'extra_'.$field_details['variable'],
1250
                            $field_details['display_text'],
1251
                            '&nbsp;'
1252
                        );
1253
1254
                        if (!$admin_permissions) {
1255
                            if ($field_details['visible'] == 0) {
1256
                                $form->freeze('extra_'.$field_details['variable']);
1257
                            }
1258
                        }
1259
                        break;
1260
                    case ExtraField::FIELD_TYPE_DIVIDER:
1261
                        $form->addElement(
1262
                            'static',
1263
                            $field_details['variable'],
1264
                            '<br /><strong>'.$field_details['display_text'].'</strong>'
1265
                        );
1266
                        break;
1267
                    case ExtraField::FIELD_TYPE_TAG:
1268
                        $variable = $field_details['variable'];
1269
                        $field_id = $field_details['id'];
1270
1271
                        $tagsSelect = $form->addSelect(
1272
                            "extra_{$field_details['variable']}",
1273
                            $field_details['display_text']
1274
                        );
1275
1276
                        if ($useTagAsSelect == false) {
1277
                            $tagsSelect->setAttribute('class', null);
1278
                        }
1279
1280
                        $tagsSelect->setAttribute('id', "extra_{$field_details['variable']}");
1281
                        $tagsSelect->setMultiple(true);
1282
1283
                        if ($this->type == 'user') {
1284
                            // The magic should be here
1285
                            $user_tags = UserManager::get_user_tags($itemId, $field_details['id']);
1286
1287
                            if (is_array($user_tags) && count($user_tags) > 0) {
1288
                                foreach ($user_tags as $tag) {
1289
                                    $tagsSelect->addOption(
1290
                                        $tag['tag'],
1291
                                        $tag['tag'],
1292
                                        ['selected' => 'selected', 'class' => 'selected']
1293
                                    );
1294
                                }
1295
                            }
1296
                            $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
1297
                        } else {
1298
                            $em = Database::getManager();
1299
1300
                            $fieldTags = $em
1301
                                ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
1302
                                ->findBy([
1303
                                    'fieldId' => $field_id,
1304
                                    'itemId' => $itemId
1305
                                ]);
1306
                            foreach ($fieldTags as $fieldTag) {
1307
                                $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1308
1309
                                if (empty($tag)) {
1310
                                    continue;
1311
                                }
1312
                                $tagsSelect->addOption(
1313
                                    $tag->getTag(),
1314
                                    $tag->getTag(),
1315
                                    ['selected' => 'selected', 'class' => 'selected']
1316
                                );
1317
                            }
1318
1319
                            if ($useTagAsSelect) {
1320
1321
                                $fieldTags = $em
1322
                                    ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
1323
                                    ->findBy([
1324
                                        'fieldId' => $field_id
1325
                                    ]);
1326
                                $tagsAdded = [];
1327
                                foreach ($fieldTags as $fieldTag) {
1328
                                    $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1329
1330
                                    if (empty($tag)) {
1331
                                        continue;
1332
                                    }
1333
1334
                                    $tagText = $tag->getTag();
1335
1336
                                    if (in_array($tagText, $tagsAdded)) {
1337
                                        continue;
1338
                                    }
1339
1340
                                    $tagsSelect->addOption(
1341
                                        $tag->getTag(),
1342
                                        $tag->getTag(),
1343
                                        []
1344
                                    );
1345
1346
                                    $tagsAdded[] = $tagText;
1347
                                }
1348
1349
                            }
1350
1351
                            $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php';
1352
                        }
1353
1354
                        if ($useTagAsSelect == false) {
1355
                        $complete_text = get_lang('StartToType');
1356
1357
                        //if cache is set to true the jquery will be called 1 time
1358
1359
                        $jquery_ready_content .= <<<EOF
1360
                            $("#extra_$variable").fcbkcomplete({
1361
                                json_url: "$url?a=search_tags&field_id=$field_id&type={$this->type}",
1362
                                cache: false,
1363
                                filter_case: true,
1364
                                filter_hide: true,
1365
                                complete_text:"$complete_text",
1366
                                firstselected: false,
1367
                                filter_selected: true,                        
1368
                                newel: true
1369
                            });
1370
EOF;
1371
                        }
1372
                        break;
1373 View Code Duplication
                    case ExtraField::FIELD_TYPE_TIMEZONE:
1374
                        $form->addElement(
1375
                            'select',
1376
                            'extra_'.$field_details['variable'],
1377
                            $field_details['display_text'],
1378
                            api_get_timezones(),
1379
                            ''
1380
                        );
1381
                        if ($field_details['visible'] == 0) {
1382
                            $form->freeze(
1383
                                'extra_'.$field_details['variable']
1384
                            );
1385
                        }
1386
                        break;
1387
                    case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
1388
                        // get the social network's favicon
1389
                        $extra_data_variable = isset($extraData['extra_'.$field_details['variable']]) ? $extraData['extra_'.$field_details['variable']] : null;
1390
                        $field_default_value = isset($field_details['field_default_value']) ? $field_details['field_default_value'] : null;
1391
                        $icon_path = UserManager::get_favicon_from_url(
1392
                            $extra_data_variable,
1393
                            $field_default_value
1394
                        );
1395
                        // special hack for hi5
1396
                        $leftpad = '1.7';
1397
                        $top     = '0.4';
1398
                        $domain  = parse_url($icon_path, PHP_URL_HOST);
1399
                        if ($domain == 'www.hi5.com' or $domain == 'hi5.com') {
1400
                            $leftpad = '3';
1401
                            $top     = '0';
1402
                        }
1403
                        // print the input field
1404
                        $form->addElement(
1405
                            'text',
1406
                            'extra_'.$field_details['variable'],
1407
                            $field_details['display_text'],
1408
                            array(
1409
                                'size'  => 60,
1410
                                'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '
1411
                            )
1412
                        );
1413
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1414
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1415
                        if ($field_details['visible'] == 0) {
1416
                            $form->freeze('extra_'.$field_details['variable']);
1417
                        }
1418
                        break;
1419 View Code Duplication
                    case ExtraField::FIELD_TYPE_MOBILE_PHONE_NUMBER:
1420
                        $form->addElement(
1421
                            'text',
1422
                            'extra_'.$field_details[1],
1423
                            $field_details[3]." (".get_lang('CountryDialCode').")",
1424
                            array('size' => 40, 'placeholder' => '(xx)xxxxxxxxx')
1425
                        );
1426
                        $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
1427
                        $form->applyFilter('extra_'.$field_details[1], 'trim');
1428
                        $form->applyFilter('extra_'.$field_details[1], 'mobile_phone_number_filter');
1429
                        $form->addRule(
1430
                            'extra_'.$field_details[1],
1431
                            get_lang('MobilePhoneNumberWrong'),
1432
                            'mobile_phone_number'
1433
                        );
1434
                        if ($field_details['visible'] == 0) {
1435
                            $form->freeze('extra_'.$field_details['variable']);
1436
                        }
1437
                        break;
1438 View Code Duplication
                    case ExtraField::FIELD_TYPE_INTEGER:
1439
                        $form->addElement(
1440
                            'number',
1441
                            'extra_'.$field_details['variable'],
1442
                            $field_details['display_text'],
1443
                            array('class' => 'span1', 'step' => 1)
1444
                        );
1445
1446
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1447
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1448
                        $form->applyFilter('extra_'.$field_details['variable'], 'intval');
1449
1450
                        if (!$admin_permissions) {
1451
                            if ($field_details['visible'] == 0) {
1452
                                $form->freeze(
1453
                                    'extra_'.$field_details['variable']
1454
                                );
1455
                            }
1456
                        }
1457
                        break;
1458
                    case ExtraField::FIELD_TYPE_FILE_IMAGE:
1459
                        $fieldVariable = "extra_{$field_details['variable']}";
1460
1461
                        $fieldTexts = [
1462
                            $field_details['display_text']
1463
                        ];
1464
1465 View Code Duplication
                        if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
1466
1467
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) {
1468
                                $fieldTexts[] = Display::img(
1469
                                    api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable],
1470
                                    $field_details['display_text'],
1471
                                    ['width' => '300']
1472
                                );
1473
                            }
1474
                        }
1475
1476
                        if ($fieldTexts[0] === 'Image') {
1477
                            $fieldTexts[0] = get_lang($fieldTexts[0]);
1478
                        }
1479
1480
                        $form->addElement(
1481
                            'file',
1482
                            $fieldVariable,
1483
                            $fieldTexts,
1484
                            ['accept' => 'image/*', 'id' => 'extra_image']
1485
                        );
1486
1487
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1488
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1489
1490
                        $allowed_picture_types = ['jpg', 'jpeg', 'png', 'gif'];
1491
                        $form->addRule(
1492
                            'extra_'.$field_details['variable'],
1493
                            get_lang('OnlyImagesAllowed') . ' ('.implode(',', $allowed_picture_types).')',
1494
                            'filetype',
1495
                            $allowed_picture_types
1496
                        );
1497
1498
                        if (!$admin_permissions) {
1499
                            if ($field_details['visible'] == 0) {
1500
                                $form->freeze(
1501
                                    'extra_'.$field_details['variable']
1502
                                );
1503
                            }
1504
                        }
1505
                        break;
1506 View Code Duplication
                    case ExtraField::FIELD_TYPE_FLOAT:
1507
                        $form->addElement(
1508
                            'number',
1509
                            'extra_'.$field_details['variable'],
1510
                            $field_details['display_text'],
1511
                            array('class' => 'span1', 'step' => '0.01')
1512
                        );
1513
1514
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1515
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1516
                        $form->applyFilter('extra_'.$field_details['variable'], 'floatval');
1517
1518
                        if (!$admin_permissions) {
1519
                            if ($field_details['visible'] == 0) {
1520
                                $form->freeze(
1521
                                    'extra_'.$field_details['variable']
1522
                                );
1523
                            }
1524
                        }
1525
                        break;
1526
                    case ExtraField::FIELD_TYPE_FILE:
1527
                        $fieldVariable = "extra_{$field_details['variable']}";
1528
                        $fieldTexts = array(
1529
                            $field_details['display_text']
1530
                        );
1531
1532
                        if (is_array($extraData) &&
1533
                            array_key_exists($fieldVariable, $extraData)
1534
                        ) {
1535 View Code Duplication
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) {
1536
                                $fieldTexts[] = Display::url(
1537
                                    api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable],
1538
                                    api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable],
1539
                                    array(
1540
                                        'title' => $field_details['display_text'],
1541
                                        'target' => '_blank'
1542
                                    )
1543
                                );
1544
                            }
1545
                        }
1546
1547
                        $form->addElement(
1548
                            'file',
1549
                            $fieldVariable,
1550
                            $fieldTexts,
1551
                            array()
1552
                        );
1553
1554
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1555
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1556
1557
                        if (!$admin_permissions) {
1558
                            if ($field_details['visible'] == 0) {
1559
                                $form->freeze(
1560
                                    'extra_'.$field_details['variable']
1561
                                );
1562
                            }
1563
                        }
1564
                        break;
1565
                    case ExtraField::FIELD_TYPE_VIDEO_URL:
1566
                        $form->addUrl(
1567
                            "extra_{$field_details['variable']}",
1568
                            $field_details['display_text'],
1569
                            false,
1570
                            ['placeholder' => 'https://']
1571
                        );
1572
                        break;
1573 View Code Duplication
                    case ExtraField::FIELD_TYPE_LETTERS_ONLY:
1574
                        $form->addTextLettersOnly(
1575
                            "extra_{$field_details['variable']}",
1576
                            $field_details['display_text']
1577
                        );
1578
                        $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes');
1579
1580
                        if (!$admin_permissions) {
1581
                            if ($field_details['visible'] == 0) {
1582
                                $form->freeze(
1583
                                    'extra_' . $field_details['variable']
1584
                                );
1585
                            }
1586
                        }
1587
                        break;
1588 View Code Duplication
                    case ExtraField::FIELD_TYPE_ALPHANUMERIC:
1589
                        $form->addTextAlphanumeric(
1590
                            "extra_{$field_details['variable']}",
1591
                            $field_details['display_text']
1592
                        );
1593
                        $form->applyFilter(
1594
                            'extra_' . $field_details['variable'],
1595
                            'stripslashes'
1596
                        );
1597
                        if (!$admin_permissions) {
1598
                            if ($field_details['visible'] == 0) {
1599
                                $form->freeze(
1600
                                    'extra_' . $field_details['variable']
1601
                                );
1602
                            }
1603
                        }
1604
                        break;
1605 View Code Duplication
                    case ExtraField::FIELD_TYPE_LETTERS_SPACE:
1606
                        $form->addTextLettersAndSpaces(
1607
                            "extra_{$field_details['variable']}",
1608
                            $field_details['display_text']
1609
                        );
1610
                        $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes');
1611
1612
                        if (!$admin_permissions) {
1613
                            if ($field_details['visible'] == 0) {
1614
                                $form->freeze(
1615
                                    'extra_' . $field_details['variable']
1616
                                );
1617
                            }
1618
                        }
1619
                        break;
1620 View Code Duplication
                    case ExtraField::FIELD_TYPE_ALPHANUMERIC_SPACE:
1621
                        $form->addTextAlphanumericAndSpaces(
1622
                            "extra_{$field_details['variable']}",
1623
                            $field_details['display_text']
1624
                        );
1625
                        $form->applyFilter(
1626
                            'extra_' . $field_details['variable'],
1627
                            'stripslashes'
1628
                        );
1629
                        if (!$admin_permissions) {
1630
                            if ($field_details['visible'] == 0) {
1631
                                $form->freeze(
1632
                                    'extra_' . $field_details['variable']
1633
                                );
1634
                            }
1635
                        }
1636
                        break;
1637
                    case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
1638
                        $dataValue = isset($extraData['extra_'.$field_details['variable']])
1639
                            ? $extraData['extra_'.$field_details['variable']]
1640
                            : '';
1641
                        $form->addElement(
1642
                            'text',
1643
                            'extra_'.$field_details['variable'],
1644
                            $field_details['display_text'],
1645
                            ['id' => 'extra_'.$field_details['variable']]
1646
                        );
1647
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1648
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1649
                        if (!$admin_permissions) {
1650
                            if ($field_details['visible'] == 0) {
1651
                                $form->freeze(
1652
                                    'extra_'.$field_details['variable']
1653
                                );
1654
                            }
1655
                        }
1656
1657
                        $form->addHtml(
1658
                            '<script>
1659
                                $(document).ready(function() {
1660
1661
                                    var address = "' . $dataValue . '";
1662
                                    initializeGeo'.$field_details['variable'].'(address, false);
1663
1664
                                    $("#geolocalization_extra_'.$field_details['variable'].'").on("click", function() {
1665
                                        var address = $("#extra_'.$field_details['variable'].'").val();
1666
                                        initializeGeo'.$field_details['variable'].'(address, false);
1667
                                        return false;
1668
                                    });
1669
1670
                                    $("#myLocation_extra_'.$field_details['variable'].'").on("click", function() {
1671
                                        myLocation'.$field_details['variable'].'();
1672
                                        return false;
1673
                                    });
1674
1675
                                    $("#extra_'.$field_details['variable'].'").keypress(function (event) {
1676
                                        if (event.which == 13) {
1677
                                            $("#geolocalization_extra_'.$field_details['variable'].'").click();
1678
                                            return false;
1679
                                        }
1680
                                    });
1681
                                });
1682
1683
                                function myLocation'.$field_details['variable'].'() {
1684
                                    if (navigator.geolocation) {
1685
                                        var geoPosition = function(position) {
1686
                                            var lat = position.coords.latitude;
1687
                                            var lng = position.coords.longitude;
1688
                                            var latLng = new google.maps.LatLng(lat, lng);
1689
                                            initializeGeo'.$field_details['variable'].'(false, latLng)
1690
                                        };
1691
1692
                                        var geoError = function(error) {
1693
                                            alert("Geocode ' . get_lang('Error') . ': " + error);
1694
                                        };
1695
1696
                                        var geoOptions = {
1697
                                            enableHighAccuracy: true
1698
                                        };
1699
1700
                                        navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
1701
                                    }
1702
                                }
1703
1704
                                function initializeGeo'.$field_details['variable'].'(address, latLng) {
1705
                                    var geocoder = new google.maps.Geocoder();
1706
                                    var latlng = new google.maps.LatLng(-34.397, 150.644);
1707
                                    var myOptions = {
1708
                                        zoom: 15,
1709
                                        center: latlng,
1710
                                        mapTypeControl: true,
1711
                                        mapTypeControlOptions: {
1712
                                            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
1713
                                        },
1714
                                        navigationControl: true,
1715
                                        mapTypeId: google.maps.MapTypeId.ROADMAP
1716
                                    };
1717
1718
                                    map_'.$field_details['variable'].' = new google.maps.Map(document.getElementById("map_extra_'.$field_details['variable'].'"), myOptions);
1719
1720
                                    var parameter = address ? { "address": address } : latLng ? { "latLng": latLng } : false;
1721
1722
                                    if (geocoder && parameter) {
1723
                                        geocoder.geocode(parameter, function(results, status) {
1724
                                            if (status == google.maps.GeocoderStatus.OK) {
1725
                                                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
1726
                                                    map_'.$field_details['variable'].'.setCenter(results[0].geometry.location);
1727
                                                    if (!address) {
1728
                                                        $("#extra_'.$field_details['variable'].'").val(results[0].formatted_address);
1729
                                                    }
1730
                                                    var infowindow = new google.maps.InfoWindow({
1731
                                                        content: "<b>" + $("#extra_'.$field_details['variable'].'").val() + "</b>",
1732
                                                        size: new google.maps.Size(150, 50)
1733
                                                    });
1734
1735
                                                    var marker = new google.maps.Marker({
1736
                                                        position: results[0].geometry.location,
1737
                                                        map: map_'.$field_details['variable'].',
1738
                                                        title: $("#extra_'.$field_details['variable'].'").val()
1739
                                                    });
1740
                                                    google.maps.event.addListener(marker, "click", function() {
1741
                                                        infowindow.open(map_'.$field_details['variable'].', marker);
1742
                                                    });
1743
                                                } else {
1744
                                                    alert("' . get_lang("NotFound") . '");
1745
                                                }
1746
1747
                                            } else {
1748
                                                alert("Geocode ' . get_lang('Error') . ': " + status);
1749
                                            }
1750
                                        });
1751
                                    }
1752
                                }
1753
                            </script>
1754
                        ');
1755
                        $form->addHtml('
1756
                            <div class="form-group">
1757
                                <label for="geolocalization_extra_'.$field_details['variable'].'" class="col-sm-2 control-label"></label>
1758
                                <div class="col-sm-8">
1759
                                    <button class="null btn btn-default " id="geolocalization_extra_'.$field_details['variable'].'" name="geolocalization_extra_'.$field_details['variable'].'" type="submit"><em class="fa fa-map-marker"></em> '.get_lang('Geolocalization').'</button>
1760
                                    <button class="null btn btn-default " id="myLocation_extra_'.$field_details['variable'].'" name="myLocation_extra_'.$field_details['variable'].'" type="submit"><em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'</button>
1761
                                </div>
1762
                            </div>
1763
                        ');
1764
1765
                        $form->addHtml('
1766
                            <div class="form-group">
1767
                                <label for="map_extra_'.$field_details['variable'].'" class="col-sm-2 control-label">
1768
                                    '.$field_details['display_text'].' - '.get_lang('Map').'
1769
                                </label>
1770
                                <div class="col-sm-8">
1771
                                    <div name="map_extra_'.$field_details['variable'].'" id="map_extra_'.$field_details['variable'].'" style="width:100%; height:300px;">
1772
                                    </div>
1773
                                </div>
1774
                            </div>
1775
                        ');
1776
                        break;
1777
                }
1778
            }
1779
        }
1780
1781
        $return = array();
1782
        $return['jquery_ready_content'] = $jquery_ready_content;
1783
1784
        return $return;
1785
    }
1786
1787
    /**
1788
     * @param $breadcrumb
1789
     * @param $action
1790
     */
1791
    public function setupBreadcrumb(&$breadcrumb, $action)
1792
    {
1793
        if ($action == 'add') {
1794
            $breadcrumb[] = array('url' => $this->pageUrl, 'name' => $this->pageName);
1795
            $breadcrumb[] = array('url' => '#', 'name' => get_lang('Add'));
1796
        } elseif ($action == 'edit') {
1797
            $breadcrumb[] = array('url' => $this->pageUrl, 'name' => $this->pageName);
1798
            $breadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
1799
        } else {
1800
            $breadcrumb[] = array('url' => '#', 'name' => $this->pageName);
1801
        }
1802
    }
1803
1804
1805
    /**
1806
     * Displays the title + grid
1807
     */
1808
    public function display()
1809
    {
1810
        // action links
1811
        echo '<div class="actions">';
1812
        echo '<a href="../admin/index.php">'.Display::return_icon(
1813
                'back.png',
1814
                get_lang('BackTo').' '.get_lang('PlatformAdmin'),
1815
                '',
1816
                ICON_SIZE_MEDIUM
1817
            ).'</a>';
1818
        echo '<a href="'.api_get_self().'?action=add&type='.$this->type.'">'.Display::return_icon(
1819
                'add_user_fields.png',
1820
                get_lang('Add'),
1821
                '',
1822
                ICON_SIZE_MEDIUM
1823
            ).'</a>';
1824
        echo '</div>';
1825
        echo Display::grid_html($this->type.'_fields');
1826
    }
1827
1828
    /**
1829
     * @return array
1830
     */
1831
    public function getJqgridColumnNames()
1832
    {
1833
        return array(
1834
            get_lang('Name'),
1835
            get_lang('FieldLabel'),
1836
            get_lang('Type'),
1837
            get_lang('FieldChangeability'),
1838
            get_lang('Visibility'),
1839
            get_lang('Filter'),
1840
            get_lang('FieldOrder'),
1841
            get_lang('Actions')
1842
        );
1843
    }
1844
1845
    /**
1846
     * @return array
1847
     */
1848
    public function getJqgridColumnModel()
1849
    {
1850
        return array(
1851
            array(
1852
                'name' => 'display_text',
1853
                'index' => 'display_text',
1854
                'width' => '180',
1855
                'align' => 'left',
1856
            ),
1857
            array(
1858
                'name' => 'variable',
1859
                'index' => 'variable',
1860
                'width' => '',
1861
                'align' => 'left',
1862
                'sortable' => 'true',
1863
            ),
1864
            array(
1865
                'name' => 'field_type',
1866
                'index' => 'field_type',
1867
                'width' => '',
1868
                'align' => 'left',
1869
                'sortable' => 'true',
1870
            ),
1871
            array(
1872
                'name' => 'changeable',
1873
                'index' => 'changeable',
1874
                'width' => '50',
1875
                'align' => 'left',
1876
                'sortable' => 'true',
1877
            ),
1878
            array(
1879
                'name' => 'visible',
1880
                'index' => 'visible',
1881
                'width' => '40',
1882
                'align' => 'left',
1883
                'sortable' => 'true',
1884
            ),
1885
            array(
1886
                'name' => 'filter',
1887
                'index' => 'filter',
1888
                'width' => '30',
1889
                'align' => 'left',
1890
                'sortable' => 'true',
1891
            ),
1892
            array(
1893
                'name' => 'field_order',
1894
                'index' => 'field_order',
1895
                'width' => '40',
1896
                'align' => 'left',
1897
                'sortable' => 'true',
1898
            ),
1899
            array(
1900
                'name' => 'actions',
1901
                'index' => 'actions',
1902
                'width' => '100',
1903
                'align' => 'left',
1904
                'formatter' => 'action_formatter',
1905
                'sortable' => 'false',
1906
            ),
1907
        );
1908
    }
1909
1910
    /**
1911
     * @param string $url
1912
     * @param string $action
1913
     * @return FormValidator
1914
     */
1915
    public function return_form($url, $action)
1916
    {
1917
        $form = new FormValidator($this->type.'_field', 'post', $url);
1918
1919
        $form->addElement('hidden', 'type', $this->type);
1920
        $id = isset($_GET['id']) ? intval($_GET['id']) : null;
1921
        $form->addElement('hidden', 'id', $id);
1922
1923
        // Setting the form elements
1924
        $header   = get_lang('Add');
1925
        $defaults = array();
1926
1927
        if ($action == 'edit') {
1928
            $header = get_lang('Modify');
1929
            // Setting the defaults
1930
            $defaults = $this->get($id, false);
1931
        }
1932
1933
        $form->addElement('header', $header);
1934
1935 View Code Duplication
        if ($action == 'edit') {
1936
            $translateUrl = api_get_path(WEB_CODE_PATH) . 'extrafield/translate.php?' . http_build_query([
1937
                'extra_field' => $id
1938
            ]);
1939
            $translateButton = Display::toolbarButton(get_lang('TranslateThisTerm'), $translateUrl, 'language', 'link');
1940
1941
            $form->addText(
1942
                'display_text',
1943
                [get_lang('Name'), $translateButton]
1944
            );
1945
        } else {
1946
            $form->addElement('text', 'display_text', get_lang('Name'));
1947
        }
1948
1949
        // Field type
1950
        $types = self::get_field_types();
1951
1952
        $form->addElement(
1953
            'select',
1954
            'field_type',
1955
            get_lang('FieldType'),
1956
            $types,
1957
            array('id' => 'field_type')
1958
        );
1959
        $form->addElement('label', get_lang('Example'), '<div id="example">-</div>');
1960
        $form->addElement('text', 'variable', get_lang('FieldLabel'), array('class' => 'span5'));
1961
        $form->addElement(
1962
            'text',
1963
            'field_options',
1964
            get_lang('FieldPossibleValues'),
1965
            array('id' => 'field_options', 'class' => 'span6')
1966
        );
1967
1968
        $fieldWithOptions = array(
1969
            ExtraField::FIELD_TYPE_RADIO,
1970
            ExtraField::FIELD_TYPE_SELECT_MULTIPLE,
1971
            ExtraField::FIELD_TYPE_SELECT,
1972
            ExtraField::FIELD_TYPE_TAG,
1973
            ExtraField::FIELD_TYPE_DOUBLE_SELECT,
1974
        );
1975
1976
        if ($action == 'edit') {
1977
            if (in_array($defaults['field_type'], $fieldWithOptions)) {
1978
                $url = Display::url(
1979
                    get_lang('EditExtraFieldOptions'),
1980
                    'extra_field_options.php?type='.$this->type.'&field_id='.$id
1981
                );
1982
                $form->addElement('label', null, $url);
1983
1984
                if ($defaults['field_type'] == ExtraField::FIELD_TYPE_SELECT) {
1985
                    $urlWorkFlow = Display::url(
1986
                        get_lang('EditExtraFieldWorkFlow'),
1987
                        'extra_field_workflow.php?type='.$this->type.'&field_id='.$id
1988
                    );
1989
                    $form->addElement('label', null, $urlWorkFlow);
1990
                }
1991
1992
                $form->freeze('field_options');
1993
            }
1994
        }
1995
        $form->addElement(
1996
            'text',
1997
            'default_value',
1998
            get_lang('FieldDefaultValue'),
1999
            array('id' => 'default_value')
2000
        );
2001
2002
        $group   = array();
2003
        $group[] = $form->createElement('radio', 'visible', null, get_lang('Yes'), 1);
2004
        $group[] = $form->createElement('radio', 'visible', null, get_lang('No'), 0);
2005
        $form->addGroup($group, '', get_lang('Visible'), '', false);
2006
2007
        $group   = array();
2008
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('Yes'), 1);
2009
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('No'), 0);
2010
        $form->addGroup($group, '', get_lang('FieldChangeability'), '', false);
2011
2012
        $group   = array();
2013
        $group[] = $form->createElement('radio', 'filter', null, get_lang('Yes'), 1);
2014
        $group[] = $form->createElement('radio', 'filter', null, get_lang('No'), 0);
2015
        $form->addGroup($group, '', get_lang('FieldFilter'), '', false);
2016
2017
        /* Enable this when field_loggeable is introduced as a table field (2.0)
2018
        $group   = array();
2019
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('Yes'), 1);
2020
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('No'), 0);
2021
        $form->addGroup($group, '', get_lang('FieldLoggeable'), '', false);
2022
        */
2023
2024
        $form->addElement('text', 'field_order', get_lang('FieldOrder'));
2025
2026
        if ($action == 'edit') {
2027
            $option = new ExtraFieldOption($this->type);
2028
            if ($defaults['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
2029
                $form->freeze('field_options');
2030
            }
2031
            $defaults['field_options'] = $option->get_field_options_by_field_to_string($id);
2032
            $form->addButtonUpdate(get_lang('Modify'));
2033
        } else {
2034
            $defaults['visible'] = 0;
2035
            $defaults['changeable'] = 0;
2036
            $defaults['filter'] = 0;
2037
            $form->addButtonCreate(get_lang('Add'));
2038
        }
2039
2040
        /*if (!empty($defaults['created_at'])) {
2041
            $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
2042
        }
2043
        if (!empty($defaults['updated_at'])) {
2044
            $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
2045
        }*/
2046
        $form->setDefaults($defaults);
2047
2048
        // Setting the rules
2049
        $form->addRule('display_text', get_lang('ThisFieldIsRequired'), 'required');
2050
        $form->addRule('field_type', get_lang('ThisFieldIsRequired'), 'required');
2051
2052
        return $form;
2053
    }
2054
2055
    /**
2056
     * @param $token
2057
     * @return string
2058
     */
2059
    public function getJqgridActionLinks($token)
2060
    {
2061
        //With this function we can add actions to the jgrid (edit, delete, etc)
2062
        $editIcon = Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL);
2063
        $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
2064
        $confirmMessage = addslashes(
2065
            api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES)
2066
        );
2067
2068
        $editButton = <<<JAVASCRIPT
2069
            <a href="?action=edit&type={$this->type}&id=' + options.rowId + '" class="btn btn-link btn-xs">\
2070
                $editIcon\
2071
            </a>
2072
JAVASCRIPT;
2073
        $deleteButton = <<<JAVASCRIPT
2074
            <a \
2075
                onclick="if (!confirm(\'$confirmMessage\')) {return false;}" \
2076
                href="?sec_token=$token&type={$this->type}&id=' + options.rowId + '&action=delete" \
2077
                class="btn btn-link btn-xs">\
2078
                $deleteIcon\
2079
            </a>
2080
JAVASCRIPT;
2081
2082
        return "function action_formatter(cellvalue, options, rowObject) {
2083
        console.log(options);
2084
            return '$editButton $deleteButton';
2085
        }";
2086
    }
2087
2088
    /**
2089
     * @param array $columns
2090
     * @param array  $column_model
2091
     * @param array  $extraFields
2092
     * @return array
2093
     */
2094
    public function getRules(&$columns, &$column_model, $extraFields = array(), $checkExtraFieldExistence = false)
2095
    {
2096
        $fields = $this->get_all(
2097
            array(
2098
                'visible = ? AND filter = ?' => array(1, 1)
2099
            ),
2100
            'display_text'
2101
        );
2102
        $extraFieldOption = new ExtraFieldOption($this->type);
2103
2104
        $rules = array();
2105
        if (!empty($fields)) {
2106
            foreach ($fields as $field) {
2107
2108
                $search_options = array();
2109
                $type           = 'text';
2110
                if (in_array($field['field_type'], array(self::FIELD_TYPE_SELECT, self::FIELD_TYPE_DOUBLE_SELECT))) {
2111
                    $type                   = 'select';
2112
                    $search_options['sopt'] = array('eq', 'ne'); //equal not equal
2113
                } else {
2114
                    $search_options['sopt'] = array('cn', 'nc'); //contains not contains
2115
                }
2116
2117
                $search_options['searchhidden'] = 'true';
2118
                $search_options['defaultValue'] = isset($search_options['field_default_value']) ? $search_options['field_default_value'] : null;
2119
2120
                if ($field['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
2121
                    //Add 2 selects
2122
                    $options = $extraFieldOption->get_field_options_by_field($field['id']);
2123
                    $options = self::extra_field_double_select_convert_array_to_ordered_array($options);
0 ignored issues
show
Security Bug introduced by
It seems like $options can also be of type false; however, ExtraField::extra_field_...rray_to_ordered_array() does only seem to accept array, did you maybe forget to handle an error condition?
Loading history...
2124
                    $first_options = array();
2125
2126
                    if (!empty($options)) {
2127
                        foreach ($options as $option) {
2128
                            foreach ($option as $sub_option) {
2129
                                if ($sub_option['option_value'] == 0) {
2130
                                    $first_options[] = $sub_option['field_id'].'#'.$sub_option['id'].':'.$sub_option['display_text'];
2131
                                }
2132
                            }
2133
                        }
2134
                    }
2135
2136
                    $search_options['value'] = implode(';', $first_options);
2137
                    $search_options['dataInit'] = 'fill_second_select';
2138
2139
                    // First
2140
                    $column_model[] = array(
2141
                        'name' => 'extra_'.$field['variable'],
2142
                        'index' => 'extra_'.$field['variable'],
2143
                        'width' => '100',
2144
                        'hidden' => 'true',
2145
                        'search' => 'true',
2146
                        'stype' => 'select',
2147
                        'searchoptions' => $search_options,
2148
                    );
2149
                    $columns[] = $field['display_text'].' (1)';
2150
                    $rules[] = array(
2151
                        'field' => 'extra_'.$field['variable'],
2152
                        'op' => 'cn',
2153
                    );
2154
2155
                    //Second
2156
                    $search_options['value']    = $field['id'].':';
2157
                    $search_options['dataInit'] = 'register_second_select';
2158
2159
                    $column_model[] = array(
2160
                        'name' => 'extra_'.$field['variable'].'_second',
2161
                        'index' => 'extra_'.$field['variable'].'_second',
2162
                        'width' => '100',
2163
                        'hidden' => 'true',
2164
                        'search' => 'true',
2165
                        'stype' => 'select',
2166
                        'searchoptions' => $search_options,
2167
                    );
2168
                    $columns[]      = $field['display_text'].' (2)';
2169
                    $rules[]        = array('field' => 'extra_'.$field['variable'].'_second', 'op' => 'cn');
2170
                    continue;
2171
                } else {
2172
                    $search_options['value'] = $extraFieldOption->getFieldOptionsToString(
2173
                        $field['id'],
2174
                        false,
2175
                        'display_text'
2176
                    );
2177
                }
2178
                $column_model[] = array(
2179
                    'name'          => 'extra_'.$field['variable'],
2180
                    'index'         => 'extra_'.$field['variable'],
2181
                    'width'         => '100',
2182
                    'hidden'        => 'true',
2183
                    'search'        => 'true',
2184
                    'stype'         => $type,
2185
                    'searchoptions' => $search_options
2186
                );
2187
                $columns[]      = $field['display_text'];
2188
                $rules[]        = array('field' => 'extra_'.$field['variable'], 'op' => 'cn');
2189
            }
2190
        }
2191
2192
        return $rules;
2193
    }
2194
2195
    /**
2196
     * @param array $options
2197
     * @return array
2198
     */
2199
    public function parseConditions($options)
2200
    {
2201
        $inject_extra_fields = null;
2202
        $extraFieldOption = new ExtraFieldOption($this->type);
2203
        $double_fields = array();
2204
2205
        if (isset($options['extra'])) {
2206
            $extra_fields = $options['extra'];
2207
            if (!empty($extra_fields)) {
2208
                $counter = 1;
2209
                foreach ($extra_fields as &$extra) {
2210
                    $extra_field_obj = new ExtraField($this->type);
2211
                    $extra_field_info = $extra_field_obj->get($extra['id']);
2212
                    $extra['extra_field_info'] = $extra_field_info;
2213
2214
                    if (isset($extra_field_info['field_type']) && in_array(
2215
                            $extra_field_info['field_type'],
2216
                            array(
2217
                                ExtraField::FIELD_TYPE_SELECT,
2218
                                ExtraField::FIELD_TYPE_SELECT,
2219
                                ExtraField::FIELD_TYPE_DOUBLE_SELECT
2220
                            )
2221
                        )
2222
                    ) {
2223
                        $inject_extra_fields .= " fvo$counter.display_text as {$extra['field']}, ";
2224
                    } else {
2225
                        $inject_extra_fields .= " fv$counter.value as {$extra['field']}, ";
2226
                    }
2227
2228 View Code Duplication
                    if (isset($extra_fields_info[$extra['id']])) {
2229
                        $info = $extra_fields_info[$extra['id']];
2230
                    } else {
2231
                        $info = $this->get($extra['id']);
2232
                        $extra_fields_info[$extra['id']] = $info;
2233
                    }
2234
                    if (isset($info['field_type']) && $info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
2235
                        $double_fields[$info['id']] = $info;
2236
                    }
2237
                    $counter++;
2238
                }
2239
            }
2240
        }
2241
2242
        $options_by_double = array();
2243 View Code Duplication
        foreach ($double_fields as $double) {
2244
            $my_options = $extraFieldOption->get_field_options_by_field(
2245
                $double['id'],
2246
                true
2247
            );
2248
            $options_by_double['extra_'.$double['variable']] = $my_options;
2249
        }
2250
2251
        $field_value_to_join = array();
2252
2253
        //filter can be all/any = and/or
2254
        $inject_joins = null;
2255
        $inject_where = null;
2256
        $where = null;
2257
2258
        if (!empty($options['where'])) {
2259
            if (!empty($options['extra'])) {
2260
                // Removing double 1=1
2261
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
2262
                // Always OR
2263
                $counter = 1;
2264
                foreach ($extra_fields as $extra_info) {
2265
                    $extra_field_info = $extra_info['extra_field_info'];
2266
                    $inject_joins .= " INNER JOIN $this->table_field_values fv$counter
2267
                                       ON (s." . $this->primaryKey . " = fv$counter." . $this->handler_id . ") ";
2268
                    // Add options
2269
                    if (isset($extra_field_info['field_type']) && in_array(
2270
                            $extra_field_info['field_type'],
2271
                            array(
2272
                                ExtraField::FIELD_TYPE_SELECT,
2273
                                ExtraField::FIELD_TYPE_SELECT,
2274
                                ExtraField::FIELD_TYPE_DOUBLE_SELECT
2275
                            )
2276
                        )
2277
                    ) {
2278
                        $options['where'] = str_replace(
2279
                            $extra_info['field'],
2280
                            'fv' . $counter . '.field_id = ' . $extra_info['id'] . ' AND fvo' . $counter . '.option_value',
2281
                            $options['where']
2282
                        );
2283
                        $inject_joins .= "
2284
                             INNER JOIN $this->table_field_options fvo$counter
2285
                             ON (
2286
                                fv$counter.field_id = fvo$counter.field_id AND
2287
                                fv$counter.value = fvo$counter.option_value
2288
                             )
2289
                            ";
2290
                    } else if (isset($extra_field_info['field_type']) &&
2291
                        $extra_field_info['field_type'] == ExtraField::FIELD_TYPE_TAG
2292
                    ) {
2293
                        $options['where'] = str_replace(
2294
                            $extra_info['field'],
2295
                            'tag' . $counter . '.tag ',
2296
                            $options['where']
2297
                        );
2298
2299
                        $inject_joins .= "
2300
                            INNER JOIN $this->table_field_rel_tag tag_rel$counter
2301
                            ON (tag_rel$counter.field_id = ".$extra_info['id']." AND tag_rel$counter.item_id = s." . $this->primaryKey.")
2302
                            INNER JOIN $this->table_field_tag tag$counter
2303
                            ON (tag$counter.id =  tag_rel$counter.tag_id)
2304
                        ";
2305
                    } else {
2306
                        //text, textarea, etc
2307
                        $options['where'] = str_replace(
2308
                            $extra_info['field'],
2309
                            'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fv'.$counter.'.value',
2310
                            $options['where']
2311
                        );
2312
                    }
2313
2314
                    $field_value_to_join[] = " fv$counter.$this->handler_id ";
2315
                    $counter++;
2316
                }
2317
                if (!empty($field_value_to_join)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
2318
                    //$inject_where .= " AND s.id = ".implode(' = ', $field_value_to_join);
2319
                }
2320
            }
2321
            $where .= ' AND '.$options['where'];
2322
        }
2323
2324
        $order = null;
2325
        if (!empty($options['order'])) {
2326
            $order = " ORDER BY ".$options['order'];
2327
        }
2328
        $limit = null;
2329
        if (!empty($options['limit'])) {
2330
            $limit = " LIMIT ".$options['limit'];
2331
        }
2332
2333
        return array(
2334
            'order' => $order,
2335
            'limit' => $limit,
2336
            'where' => $where,
2337
            'inject_where' => $inject_where,
2338
            'inject_joins' => $inject_joins,
2339
            'field_value_to_join' => $field_value_to_join,
2340
            'inject_extra_fields' => $inject_extra_fields,
2341
        );
2342
    }
2343
2344
    //@todo move this in the display_class or somewhere else
2345
    /**
2346
     * @param $col
2347
     * @param $oper
2348
     * @param $val
2349
     * @return string
2350
     */
2351
    public function get_where_clause($col, $oper, $val)
2352
    {
2353
        if (empty($col)) {
2354
            return '';
2355
        }
2356
        if ($oper == 'bw' || $oper == 'bn') {
2357
            $val .= '%';
2358
        }
2359
        if ($oper == 'ew' || $oper == 'en') {
2360
            $val = '%'.$val;
2361
        }
2362
        if ($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') {
2363
            if (is_array($val)) {
2364
                $result = '"%'.implode(';', $val).'%"';
2365
                foreach ($val as $item) {
2366
                    $result .= ' OR '.$col.' LIKE "%'.$item.'%"';
2367
                }
2368
                $val = $result;
2369
2370
                return " $col {$this->ops[$oper]} $val ";
2371
            } else {
2372
                $val = '%'.$val.'%';
2373
            }
2374
        }
2375
        $val = \Database::escape_string($val);
2376
2377
        return " $col {$this->ops[$oper]} '$val' ";
2378
    }
2379
2380
    /**
2381
     * @param $filters
2382
     * @param string $stringToSearch
2383
     * @return array
2384
     */
2385
    public function getExtraFieldRules($filters, $stringToSearch = 'extra_')
2386
    {
2387
        $extra_fields = array();
2388
2389
        // Getting double select if exists
2390
        $double_select = array();
2391
        foreach ($filters->rules as $rule) {
2392
            if (strpos($rule->field, '_second') === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
2393
2394
            } else {
2395
                $my_field = str_replace('_second', '', $rule->field);
2396
                $double_select[$my_field] = $rule->data;
2397
            }
2398
        }
2399
2400
        $condition_array = array();
2401
2402
        foreach ($filters->rules as $rule) {
2403
            if (strpos($rule->field, $stringToSearch) === false) {
2404
                // normal fields
2405
                $field = $rule->field;
2406
                if (isset($rule->data) && is_string($rule->data) && $rule->data != -1) {
2407
                    $condition_array[] = $this->get_where_clause($field, $rule->op, $rule->data);
2408
                }
2409
            } else {
2410
                // Extra fields
2411
                if (strpos($rule->field, '_second') === false) {
2412
                    //No _second
2413
                    $original_field = str_replace($stringToSearch, '', $rule->field);
2414
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2415
2416
                    if ($field_option['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
2417
                        if (isset($double_select[$rule->field])) {
2418
                            $data = explode('#', $rule->data);
2419
                            $rule->data = $data[1].'::'.$double_select[$rule->field];
2420
                        } else {
2421
                            // only was sent 1 select
2422
                            if (is_string($rule->data)) {
2423
                                $data = explode('#', $rule->data);
2424
                                $rule->data = $data[1];
2425
                            }
2426
                        }
2427
2428
                        if (!isset($rule->data)) {
2429
                            $condition_array[] = ' ('.$this->get_where_clause($rule->field, $rule->op, $rule->data).') ';
2430
                            $extra_fields[] = array('field' => $rule->field, 'id' => $field_option['id']);
2431
                        }
2432
                    } else {
2433
                        if (isset($rule->data)) {
2434
                            if ($rule->data == -1) {
2435
                                continue;
2436
                            }
2437
                            $condition_array[] = ' ('.$this->get_where_clause($rule->field, $rule->op, $rule->data).') ';
2438
                            $extra_fields[] = array(
2439
                                'field' => $rule->field,
2440
                                'id' => $field_option['id'],
2441
                                'data' => $rule->data
2442
                            );
2443
                        }
2444
                    }
2445
                } else {
2446
                    $my_field = str_replace('_second', '', $rule->field);
2447
                    $original_field = str_replace($stringToSearch, '', $my_field);
2448
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2449
                    $extra_fields[] = array(
2450
                        'field' => $rule->field,
2451
                        'id' => $field_option['id']
2452
                    );
2453
                }
2454
            }
2455
        }
2456
2457
        return array(
2458
            'extra_fields' => $extra_fields,
2459
            'condition_array' => $condition_array
2460
        );
2461
    }
2462
2463
    /**
2464
     * Get the extra fields and their formatted values
2465
     * @param int|string $itemId The item ID (It could be a session_id, course_id or user_id)
2466
     * @return array The extra fields data
2467
     */
2468
    public function getDataAndFormattedValues($itemId)
2469
    {
2470
        $valuesData = array();
2471
2472
        $fields = $this->get_all();
2473
2474
        foreach ($fields as $field) {
2475
            if ($field['visible'] != '1') {
2476
                continue;
2477
            }
2478
2479
            $fieldValue = new ExtraFieldValue($this->type);
2480
            $valueData = $fieldValue->get_values_by_handler_and_field_id($itemId, $field['id'], true);
2481
2482
            if (!$valueData) {
2483
                continue;
2484
            }
2485
2486
            $displayedValue = get_lang('None');
2487
2488
            switch ($field['field_type']) {
2489
                case ExtraField::FIELD_TYPE_CHECKBOX:
2490
                    if ($valueData !== false && $valueData['value'] == '1') {
2491
                        $displayedValue = get_lang('Yes');
2492
                    } else {
2493
                        $displayedValue = get_lang('No');
2494
                    }
2495
                    break;
2496
                case ExtraField::FIELD_TYPE_DATE:
2497
                    if ($valueData !== false && !empty($valueData['value'])) {
2498
                        $displayedValue = api_format_date($valueData['value'], DATE_FORMAT_LONG_NO_DAY);
2499
                    }
2500
                    break;
2501
                case ExtraField::FIELD_TYPE_FILE_IMAGE:
2502
                    if ($valueData === false || empty($valueData['value'])) {
2503
                        break;
2504
                    }
2505
2506
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH) . $valueData['value'])) {
2507
                        break;
2508
                    }
2509
2510
                    $image = Display::img(
2511
                        api_get_path(WEB_UPLOAD_PATH) . $valueData['value'],
2512
                        $field['display_text'],
2513
                        array('width' => '300')
2514
                    );
2515
2516
                    $displayedValue = Display::url(
2517
                        $image,
2518
                        api_get_path(WEB_UPLOAD_PATH) . $valueData['value'],
2519
                        array('target' => '_blank')
2520
                    );
2521
                    break;
2522
                case ExtraField::FIELD_TYPE_FILE:
2523
                    if ($valueData === false || empty($valueData['value'])) {
2524
                        break;
2525
                    }
2526
2527
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH) . $valueData['value'])) {
2528
                        break;
2529
                    }
2530
2531
                    $displayedValue = Display::url(
2532
                        get_lang('Download'),
2533
                        api_get_path(WEB_UPLOAD_PATH) . $valueData['value'],
2534
                        array(
2535
                            'title' => $field['display_text'],
2536
                            'target' => '_blank'
2537
                        )
2538
                    );
2539
                    break;
2540
                default:
2541
                    $displayedValue = $valueData['value'];
2542
                    break;
2543
            }
2544
2545
            $valuesData[] = array(
2546
                'text' => $field['display_text'],
2547
                'value' => $displayedValue
2548
            );
2549
        }
2550
2551
        return $valuesData;
2552
    }
2553
2554
    /**
2555
     * Gets an element
2556
     * @param int $id
2557
     * @param bool $translateDisplayText Optional
2558
     * @return array
2559
     */
2560 View Code Duplication
    public function get($id, $translateDisplayText = true)
2561
    {
2562
        $info = parent::get($id);
2563
2564
        if ($translateDisplayText) {
2565
            $info['display_text'] = self::translateDisplayName($info['variable'], $info['display_text']);
2566
        }
2567
2568
        return $info;
2569
    }
2570
2571
    /**
2572
     * Translate the display text for a extra field
2573
     * @param string $variable
2574
     * @param string $defaultDisplayText
2575
     * @return string
2576
     */
2577
    public static function translateDisplayName($variable, $defaultDisplayText)
2578
    {
2579
        $camelCase = api_underscore_to_camel_case($variable);
2580
2581
        return isset($GLOBALS[$camelCase]) ? $GLOBALS[$camelCase] : $defaultDisplayText;
2582
    }
2583
2584
    /**
2585
     * @param int $fieldId
2586
     * @param string $tag
2587
     *
2588
     * @return array
2589
     */
2590
    public function getAllUserPerTag($fieldId, $tag)
2591
    {
2592
        $tagRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
2593
        $tag = Database::escape_string($tag);
2594
        $fieldId = (int) $fieldId;
2595
2596
        $sql = "SELECT user_id 
2597
                FROM {$this->table_field_tag} f INNER JOIN $tagRelUserTable ft 
2598
                ON tag_id = f.id 
2599
                WHERE tag = '$tag' AND f.field_id = $fieldId;
2600
        ";
2601
2602
        $result = Database::query($sql);
2603
2604
        return Database::store_result($result, 'ASSOC');
2605
    }
2606
2607
    /**
2608
     * @param int $fieldId
2609
     * @param int $tagId
2610
     *
2611
     * @return array
2612
     */
2613 View Code Duplication
    public function getAllSkillPerTag($fieldId, $tagId)
2614
    {
2615
        $skillTable = Database::get_main_table(TABLE_MAIN_SKILL);
2616
        $tagRelXtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
2617
        $fieldId = intval($fieldId);
2618
        $tagId = intval($tagId);
2619
2620
        $sql = "SELECT s.id
2621
                FROM $skillTable s INNER JOIN $tagRelXtraTable t
2622
                ON t.item_id = s.id
2623
                WHERE tag_id = $tagId AND t.field_id = $fieldId;
2624
        ";
2625
2626
        $result = Database::query($sql);
2627
        $result = Database::store_result($result, 'ASSOC');
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, store_result() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2628
2629
        $skillList = [];
2630
2631
        foreach ($result as $index => $value) {
2632
            $skillList[$value['id']] = $value['id'];
2633
        }
2634
2635
        return $skillList;
2636
    }
2637
}
2638