Passed
Push — 1.10.x ( de380a...891fd1 )
by Angel Fernando Quiroz
44:35
created

ExtraField::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
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
69
    public $type = 'user';
70
    public $pageName;
71
    public $pageUrl;
72
    public $extraFieldType = 0;
73
74
    /**
75
     * @param string $type
76
     */
77
    public function __construct($type)
78
    {
79
        $this->type = $type;
80
        $this->table = Database::get_main_table(TABLE_EXTRA_FIELD);
81
        $this->table_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
82
        $this->table_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
83
        $this->handler_id = 'item_id';
84
85
        switch ($this->type) {
86
            case 'calendar_event':
87
                $this->extraFieldType = EntityExtraField::CALENDAR_FIELD_TYPE;
88
                break;
89
            case 'course':
90
                $this->extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
91
                $this->primaryKey = 'id';
92
                break;
93
            case 'user':
94
                $this->extraFieldType = EntityExtraField::USER_FIELD_TYPE;
95
                $this->primaryKey = 'id';
96
                break;
97
            case 'session':
98
                $this->extraFieldType = EntityExtraField::SESSION_FIELD_TYPE;
99
                $this->primaryKey = 'id';
100
                break;
101
            case 'question':
102
                $this->extraFieldType = EntityExtraField::QUESTION_FIELD_TYPE;
103
                break;
104
            case 'lp':
105
                $this->extraFieldType = EntityExtraField::LP_FIELD_TYPE;
106
                break;
107
            case 'lp_item':
108
                $this->extraFieldType = EntityExtraField::LP_ITEM_FIELD_TYPE;
109
                break;
110
            case 'skill':
111
                $this->extraFieldType = EntityExtraField::SKILL_FIELD_TYPE;
112
                break;
113
            case 'work':
114
                $this->extraFieldType = EntityExtraField::WORK_FIELD_TYPE;
115
                break;
116
            case 'survey':
117
                $this->extraFieldType = EntityExtraField::SURVEY_FIELD_TYPE;
118
                break;
119
        }
120
121
        $this->pageUrl  = 'extra_fields.php?type='.$this->type;
122
        // Example QuestionFields
123
        $this->pageName = get_lang(ucwords($this->type).'Fields');
124
    }
125
126
    /**
127
     * @return int
128
     */
129
    public function getExtraFieldType()
130
    {
131
        return $this->extraFieldType;
132
    }
133
134
    /**
135
     * @return array
136
     */
137
    public static function getValidExtraFieldTypes()
138
    {
139
        return array(
140
            'user',
141
            'course',
142
            'session',
143
            'question',
144
            'lp',
145
            'calendar_event',
146
            'lp_item',
147
            'skill',
148
            'work',
149
            'survey'
150
        );
151
    }
152
153
    /**
154
     * @return int
155
     */
156 View Code Duplication
    public function get_count()
157
    {
158
        $em = Database::getManager();
159
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
160
        $query->select('count(e.id)');
161
        $query->where('e.extraFieldType = :type');
162
        $query->setParameter('type', $this->getExtraFieldType());
163
164
        return $query->getQuery()->getScalarResult();
165
    }
166
167
    /**
168
     * @param string $sidx
169
     * @param string $sord
170
     * @param int $start
171
     * @param int $limit
172
     *
173
     * @return array
174
     */
175
    public function getAllGrid($sidx, $sord, $start, $limit)
176
    {
177
        switch ($sidx) {
178
            case 'field_order':
179
                $sidx = 'e.fieldOrder';
180
                break;
181
            case 'variable':
182
                $sidx = 'e.variable';
183
                break;
184
            case 'display_text':
185
                $sidx = 'e.displayText';
186
                break;
187
            case 'changeable':
188
                $sidx = 'e.changeable';
189
                break;
190
            case 'visible':
191
                $sidx = 'e.visible';
192
                break;
193
            case 'filter':
194
                $sidx = 'e.filter';
195
                break;
196
            case 'display_text':
197
                $sidx = 'e.fieldType';
198
                break;
199
        }
200
        $em = Database::getManager();
201
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
202
        $query->select('e')
203
            ->where('e.extraFieldType = :type')
204
            ->setParameter('type', $this->getExtraFieldType())
205
            ->orderBy($sidx, $sord)
206
            ->setFirstResult($start)
207
            ->setMaxResults($limit);
208
        //echo $query->getQuery()->getSQL();
209
        return $query->getQuery()->getArrayResult();
210
    }
211
212
    /**
213
     * @param array $conditions
214
     * @param null  $order_field_options_by
215
     *
216
     * @return array
217
     */
218
    public function get_all($conditions = array(), $order_field_options_by = null)
219
    {
220
        $conditions = Database::parse_conditions(array('where' => $conditions));
221
222
        if (empty($conditions)) {
223
            $conditions .= " WHERE extra_field_type = ".$this->extraFieldType;
224
        } else {
225
            $conditions .= " AND extra_field_type = ".$this->extraFieldType;
226
        }
227
228
        $sql = "SELECT * FROM $this->table
229
                $conditions
230
                ORDER BY field_order ASC
231
        ";
232
        $result = Database::query($sql);
233
        $extraFields = Database::store_result($result, 'ASSOC');
234
235
        $option = new ExtraFieldOption($this->type);
236
        if (!empty($extraFields)) {
237
            foreach ($extraFields as &$extraField) {
238
                $extraField['options'] = $option->get_field_options_by_field(
239
                    $extraField['id'],
240
                    false,
241
                    $order_field_options_by
242
                );
243
            }
244
        }
245
246
        return $extraFields;
247
    }
248
249
    /**
250
     * @param string $variable
251
     *
252
     * @return array|bool
253
     */
254 View Code Duplication
    public function get_handler_field_info_by_field_variable($variable)
255
    {
256
        $variable = Database::escape_string($variable);
257
        $sql = "SELECT * FROM {$this->table}
258
                WHERE
259
                    variable = '$variable' AND
260
                    extra_field_type = $this->extraFieldType";
261
        $result = Database::query($sql);
262
        if (Database::num_rows($result)) {
263
            $row = Database::fetch_array($result, 'ASSOC');
264
265
            // All the options of the field
266
            $sql = "SELECT * FROM $this->table_field_options
267
                    WHERE field_id='".intval($row['id'])."'
268
                    ORDER BY option_order ASC";
269
            $result = Database::query($sql);
270
            while ($option = Database::fetch_array($result)) {
271
                $row['options'][$option['id']] = $option;
272
            }
273
274
            return $row;
275
        } else {
276
            return false;
277
        }
278
    }
279
280
    /**
281
     * @param int $fieldId
282
     *
283
     * @return array|bool
284
     */
285 View Code Duplication
    public function getFieldInfoByFieldId($fieldId)
286
    {
287
        $fieldId = intval($fieldId);
288
        $sql = "SELECT * FROM {$this->table}
289
                WHERE
290
                    field_id = '$fieldId' AND
291
                    extra_field_type = $this->extraFieldType";
292
        $result = Database::query($sql);
293
        if (Database::num_rows($result)) {
294
            $row = Database::fetch_array($result, 'ASSOC');
295
296
            // All the options of the field
297
            $sql = "SELECT * FROM $this->table_field_options
298
                    WHERE field_id='".$fieldId."'
299
                    ORDER BY option_order ASC";
300
            $result = Database::query($sql);
301
            while ($option = Database::fetch_array($result)) {
302
                $row['options'][$option['id']] = $option;
303
            }
304
305
            return $row;
306
        } else {
307
            return false;
308
        }
309
    }
310
311
    /**
312
     * @return int
313
     */
314
    public function get_max_field_order()
315
    {
316
        $sql = "SELECT MAX(field_order)
317
                FROM {$this->table}
318
                WHERE
319
                    extra_field_type = '.$this->extraFieldType.'";
320
        $res = Database::query($sql);
321
322
        $order = 0;
323
        if (Database::num_rows($res) > 0) {
324
            $row = Database::fetch_row($res);
325
            $order = $row[0] + 1;
326
        }
327
328
        return $order;
329
    }
330
331
    /**
332
     * @param string $handler
333
     *
334
     * @return array
335
     */
336
    public static function get_extra_fields_by_handler($handler)
337
    {
338
        $types= array();
339
        $types[self::FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
340
        $types[self::FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
341
        $types[self::FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
342
        $types[self::FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
343
        $types[self::FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
344
        $types[self::FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
345
        $types[self::FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
346
        $types[self::FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
347
        $types[self::FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
348
        $types[self::FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
349
        $types[self::FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
350
        $types[self::FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
351
        $types[self::FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
352
        $types[self::FIELD_TYPE_CHECKBOX] = get_lang('FieldTypeCheckbox');
353
        $types[self::FIELD_TYPE_INTEGER] = get_lang('FieldTypeInteger');
354
        $types[self::FIELD_TYPE_FILE_IMAGE] = get_lang('FieldTypeFileImage');
355
        $types[self::FIELD_TYPE_FLOAT] = get_lang('FieldTypeFloat');
356
        $types[self::FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
357
        $types[self::FIELD_TYPE_VIDEO_URL] = get_lang('FieldTypeVideoUrl');
358
        $types[self::FIELD_TYPE_LETTERS_ONLY] = get_lang('FieldTypeOnlyLetters');
359
        $types[self::FIELD_TYPE_ALPHANUMERIC] = get_lang('FieldTypeAlphanumeric');
360
        $types[self::FIELD_TYPE_LETTERS_SPACE] = get_lang(
361
            'FieldTypeLettersSpaces'
362
        );
363
        $types[self::FIELD_TYPE_ALPHANUMERIC_SPACE] = get_lang(
364
            'FieldTypeAlphanumericSpaces'
365
        );
366
367
        switch ($handler) {
368
            case 'course':
369
            case 'session':
370
            case 'user':
371
                break;
372
        }
373
374
        return $types;
375
    }
376
377
    /**
378
     * Add elements to a form
379
     *
380
     * @param FormValidator $form
381
     * @param int $itemId
382
     * @param array $exclude variables of extra field to exclude
383
     * @return array|bool
384
     */
385
    public function addElements($form, $itemId = 0, $exclude = [])
386
    {
387
        if (empty($form)) {
388
            return false;
389
        }
390
391
        $itemId = intval($itemId);
392
        $form->addHidden('item_id', $itemId);
393
        $extraData = false;
394
        if (!empty($itemId)) {
395
            $extraData = self::get_handler_extra_data($itemId);
396
397
            if ($form) {
398
                $form->setDefaults($extraData);
399
            }
400
        }
401
402
        $extraFields = $this->get_all(null, 'option_order');
403
        $extra = $this->set_extra_fields_in_form(
404
            $form,
405
            $extraData,
0 ignored issues
show
Security Bug introduced by
It seems like $extraData defined by false on line 393 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...
406
            false,
407
            $extraFields,
408
            $itemId,
409
            $exclude
410
        );
411
412
        return $extra;
413
    }
414
415
    /**
416
     * @param int $itemId (session_id, question_id, course id)
417
     *
418
     * @return array
419
     */
420
    public function get_handler_extra_data($itemId)
421
    {
422
        if (empty($itemId)) {
423
            return array();
424
        }
425
426
        $extra_data = array();
427
        $fields = self::get_all();
428
        $field_values = new ExtraFieldValue($this->type);
429
430
        if (!empty($fields) > 0) {
431
            foreach ($fields as $field) {
432
433
                $field_value = $field_values->get_values_by_handler_and_field_id(
434
                    $itemId, $field['id']
435
                );
436
437
                if ($field['field_type'] == ExtraField::FIELD_TYPE_TAG) {
438
                    $tags = UserManager::get_user_tags_to_string($itemId, $field['id'], false);
439
440
441
                    $extra_data['extra_'.$field['variable']] = $tags;
442
                    continue;
443
                }
444
445
                if ($field_value) {
446
                    $field_value = $field_value['value'];
447
                    switch ($field['field_type']) {
448
                        case ExtraField::FIELD_TYPE_TAG:
449
                            $tags = UserManager::get_user_tags_to_string($itemId, $field['id'], false);
450
451
                            $extra_data['extra_'.$field['variable']] = $tags;
452
                            break;
453
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
454
                            $selected_options = explode(
455
                                '::',
456
                                $field_value
457
                            );
458
                            $firstOption = isset($selected_options[0]) ? $selected_options[0] : '';
459
                            $secondOption = isset($selected_options[1]) ? $selected_options[1] : '';
460
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $firstOption;
461
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable'].'_second'] = $secondOption;
462
463
                            break;
464
                        case ExtraField::FIELD_TYPE_SELECT_MULTIPLE:
465
                            $field_value = explode(';', $field_value);
466
                            $extra_data['extra_'.$field['variable']] = $field_value;
467
                            break;
468
                        case ExtraField::FIELD_TYPE_RADIO:
469
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $field_value;
470
                            break;
471
                        default:
472
                            $extra_data['extra_'.$field['variable']] = $field_value;
473
                            break;
474
                    }
475
                } else {
476
                    // Set default values
477
                    if (isset($field['field_default_value']) && !empty($field['field_default_value'])) {
478
                        $extra_data['extra_'.$field['variable']] = $field['field_default_value'];
479
                    }
480
                }
481
            }
482
        }
483
484
        return $extra_data;
485
    }
486
487
    /**
488
     * @param string $field_type
489
     *
490
     * @return array
491
     */
492
    public function get_all_extra_field_by_type($field_type)
493
    {
494
        // all the information of the field
495
        $sql = "SELECT * FROM {$this->table}
496
                WHERE
497
                    field_type = '".Database::escape_string($field_type)."' AND
498
                    extra_field_type = $this->extraFieldType
499
                ";
500
        $result = Database::query($sql);
501
502
        $return = array();
503
        while ($row = Database::fetch_array($result)) {
504
            $return[] = $row['id'];
505
        }
506
507
        return $return;
508
    }
509
510
    /**
511
     * @return array
512
     */
513
    public function get_field_types()
514
    {
515
        return self::get_extra_fields_by_handler($this->type);
516
    }
517
518
    /**
519
     * @param int $id
520
     *
521
     * @return null
522
     */
523
    public function get_field_type_by_id($id)
524
    {
525
        $types = self::get_field_types();
526
        if (isset($types[$id])) {
527
            return $types[$id];
528
        }
529
530
        return null;
531
    }
532
533
    /**
534
     * Converts a string like this:
535
     * France:Paris;Bretagne;Marseilles;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
536
     * into
537
     * array(
538
 *      'France' =>
539
     *      array('Paris', 'Bregtane', 'Marseilles'),
540
     *  'Belgique' =>
541
     *      array('Namur', 'Liège')
542
     * ), etc
543
     * @param string $string
544
     *
545
     * @return array
546
     */
547
    public static function extra_field_double_select_convert_string_to_array($string)
548
    {
549
        $options = explode('|', $string);
550
        $options_parsed = array();
551
        $id = 0;
552
553
        if (!empty($options)) {
554
            foreach ($options as $sub_options) {
555
                $options = explode(':', $sub_options);
556
                $sub_sub_options = explode(';', $options[1]);
557
                $options_parsed[$id] = array(
558
                    'label' => $options[0],
559
                    'options' => $sub_sub_options,
560
                );
561
                $id++;
562
            }
563
        }
564
565
        return $options_parsed;
566
    }
567
568
    /**
569
     * @param array $options
570
     *
571
     * @return array
572
     */
573
    public static function extra_field_double_select_convert_array_to_ordered_array($options)
574
    {
575
        $options_parsed = array();
576
        if (!empty($options)) {
577
            foreach ($options as $option) {
578
                if ($option['option_value'] == 0) {
579
                    $options_parsed[$option['id']][] = $option;
580
                } else {
581
                    $options_parsed[$option['option_value']][] = $option;
582
                }
583
            }
584
        }
585
586
        return $options_parsed;
587
    }
588
589
    /**
590
     * @param array $options the result of the get_field_options_by_field() array
591
     *
592
     * @return string
593
     */
594
    public static function extra_field_double_select_convert_array_to_string($options)
595
    {
596
        $string = null;
597
        $options_parsed = self::extra_field_double_select_convert_array_to_ordered_array($options);
598
599
        if (!empty($options_parsed)) {
600
            foreach ($options_parsed as $option) {
601
                foreach ($option as $key => $item) {
602
                    $string .= $item['display_text'];
603
                    if ($key == 0) {
604
                        $string .= ':';
605
                    } else {
606
                        if (isset($option[$key + 1])) {
607
                            $string .= ';';
608
                        }
609
                    }
610
                }
611
                $string .= '|';
612
            }
613
        }
614
615
        if (!empty($string)) {
616
            $string = substr($string, 0, strlen($string) - 1);
617
        }
618
619
        return $string;
620
    }
621
622
    /**
623
     * @param array $params
624
     *
625
     * @return array
626
     */
627
    public function clean_parameters($params)
628
    {
629
        if (!isset($params['variable']) || empty($params['variable'])) {
630
            $params['variable'] = $params['display_text'];
631
        }
632
633
        $params['variable'] = trim(strtolower(str_replace(" ", "_", $params['variable'])));
634
635
        if (!isset($params['field_order'])) {
636
            $max_order = self::get_max_field_order();
637
            $params['field_order'] = $max_order;
638
        }
639
640
        return $params;
641
    }
642
643
    /**
644
     * @param array $params
645
     * @param bool  $show_query
646
     *
647
     * @return bool
648
     */
649
    public function save($params, $show_query = false)
650
    {
651
        $fieldInfo = self::get_handler_field_info_by_field_variable($params['variable']);
652
        $params = self::clean_parameters($params);
653
        $params['extra_field_type'] = $this->extraFieldType;
654
655
        if ($fieldInfo) {
656
            return $fieldInfo['id'];
657
        } else {
658
            $id = parent::save($params, $show_query);
659
            if ($id) {
660
                $session_field_option = new ExtraFieldOption($this->type);
661
                $params['field_id'] = $id;
662
                $session_field_option->save($params);
663
            }
664
665
            return $id;
666
        }
667
    }
668
669
    /**
670
     * @param array $params
671
     *
672
     * @return bool|void
673
     */
674
    public function update($params)
675
    {
676
        $params = self::clean_parameters($params);
677
        if (isset($params['id'])) {
678
            $field_option = new ExtraFieldOption($this->type);
679
            $params['field_id'] = $params['id'];
680
            $field_option->save($params);
681
        }
682
683
        parent::update($params);
684
    }
685
686
    /**
687
     * @param $id
688
     *
689
     * @return bool|void
690
     */
691
    public function delete($id)
692
    {
693
        $field_option = new ExtraFieldOption($this->type);
694
        $field_option->delete_all_options_by_field_id($id);
695
696
        $session_field_values = new ExtraFieldValue($this->type);
697
        $session_field_values->delete_all_values_by_field_id($id);
698
699
        parent::delete($id);
700
    }
701
702
    /**
703
     * @param FormValidator $form
704
     * @param array $extraData
705
     * @param bool $admin_permissions
706
     * @param int $user_id
0 ignored issues
show
Bug introduced by
There is no parameter named $user_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
707
     * @param array $extra
708
     * @param int $itemId
709
     * @param array $exclude variables of extra field to exclude
710
     * @return array
711
     */
712
    public function set_extra_fields_in_form(
713
        $form,
714
        $extraData,
715
        $admin_permissions = false,
716
        $extra = array(),
717
        $itemId = null,
718
        $exclude = []
719
    ) {
720
        $type = $this->type;
721
722
        $jquery_ready_content = null;
723
724
        if (!empty($extra)) {
725
            foreach ($extra as $field_details) {
726
727
                // Getting default value id if is set
728
                $defaultValueId = null;
729
                if (isset($field_details['options']) && !empty($field_details['options'])) {
730
                    $valueToFind = null;
731
                    if (isset($field_details['field_default_value'])) {
732
                        $valueToFind = $field_details['field_default_value'];
733
                    }
734
                    // If a value is found we override the default value
735
                    if (isset($extraData['extra_'.$field_details['variable']])) {
736
                        $valueToFind = $extraData['extra_'.$field_details['variable']];
737
                    }
738
739
                    foreach ($field_details['options'] as $option) {
740
                        if ($option['option_value'] == $valueToFind) {
741
                            $defaultValueId = $option['id'];
742
                        }
743
                    }
744
                }
745
746
                if (!$admin_permissions) {
747
                    if ($field_details['visible'] == 0) {
748
                        continue;
749
                    }
750
751
                    if (in_array($field_details['variable'], $exclude)) {
752
                        continue;
753
                    }
754
                }
755
756
                switch ($field_details['field_type']) {
757
                    case ExtraField::FIELD_TYPE_TEXT:
758
                        $form->addElement(
759
                            'text',
760
                            'extra_'.$field_details['variable'],
761
                            $field_details['display_text'],
762
                            array()
763
                        );
764
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
765
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
766
                        if (!$admin_permissions) {
767
                            if ($field_details['visible'] == 0) {
768
                                $form->freeze(
769
                                    'extra_'.$field_details['variable']
770
                                );
771
                            }
772
                        }
773
                        break;
774 View Code Duplication
                    case ExtraField::FIELD_TYPE_TEXTAREA:
775
                        $form->addHtmlEditor(
776
                            'extra_'.$field_details['variable'],
777
                            $field_details['display_text'],
778
                            false,
779
                            false,
780
                            array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')
781
                        );
782
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
783
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
784
                        if (!$admin_permissions) {
785
                            if ($field_details['visible'] == 0) {
786
                                $form->freeze(
787
                                    'extra_'.$field_details['variable']
788
                                );
789
                            }
790
                        }
791
                        break;
792
                    case ExtraField::FIELD_TYPE_RADIO:
793
                        $group = array();
794
                        if (isset($field_details['options']) && !empty($field_details['options'])) {
795 View Code Duplication
                            foreach ($field_details['options'] as $option_details) {
796
                                $options[$option_details['option_value']] = $option_details['display_text'];
797
                                $group[]                                  = $form->createElement(
798
                                    'radio',
799
                                    'extra_'.$field_details['variable'],
800
                                    $option_details['option_value'],
801
                                    $option_details['display_text'].'<br />',
802
                                    $option_details['option_value']
803
                                );
804
                            }
805
                        }
806
                        $form->addGroup(
807
                            $group,
808
                            'extra_'.$field_details['variable'],
809
                            $field_details['display_text'],
810
                            ''
811
                        );
812
                        if (!$admin_permissions) {
813
                            if ($field_details['visible'] == 0) {
814
                                $form->freeze(
815
                                    'extra_'.$field_details['variable']
816
                                );
817
                            }
818
                        }
819
                        break;
820
                    case ExtraField::FIELD_TYPE_CHECKBOX:
821
                        $group = array();
822
                        if (isset($field_details['options']) && !empty($field_details['options'])) {
823 View Code Duplication
                            foreach ($field_details['options'] as $option_details) {
824
                                $options[$option_details['option_value']] = $option_details['display_text'];
825
                                $group[] = $form->createElement(
826
                                    'checkbox',
827
                                    'extra_'.$field_details['variable'],
828
                                    $option_details['option_value'],
829
                                    $option_details['display_text'].'<br />',
830
                                    $option_details['option_value']
831
                                );
832
                            }
833
                        } else {
834
                            $fieldVariable = "extra_{$field_details['variable']}";
835
836
                            $checkboxAttributes = array();
837
838
                            if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
839
                                if (!empty($extraData[$fieldVariable])) {
840
                                    $checkboxAttributes['checked'] = 1;
841
                                }
842
                            }
843
844
                            // We assume that is a switch on/off with 1 and 0 as values
845
                            $group[] = $form->createElement(
846
                                'checkbox',
847
                                'extra_'.$field_details['variable'],
848
                                null,
849
                                //$field_details['display_text'].'<br />',
850
                                get_lang('Yes'),
851
                                $checkboxAttributes
852
                            );
853
                        }
854
855
                        $form->addGroup(
856
                            $group,
857
                            'extra_'.$field_details['variable'],
858
                            $field_details['display_text'],
859
                            ''
860
                        );
861
                        if (!$admin_permissions) {
862
                            if ($field_details['visible'] == 0) {
863
                                $form->freeze(
864
                                    'extra_'.$field_details['variable']
865
                                );
866
                            }
867
                        }
868
                        break;
869
                    case ExtraField::FIELD_TYPE_SELECT:
870
                        $get_lang_variables = false;
871
                        if (in_array(
872
                            $field_details['variable'],
873
                            array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message')
874
                        )
875
                        ) {
876
                            $get_lang_variables = true;
877
                        }
878
879
                        // Get extra field workflow
880
                        $userInfo = api_get_user_info();
881
882
                        $addOptions = array();
883
884
                        $optionsExists = false;
885
                        global $app;
886
                        // Check if exist $app['orm.em'] object
887
                        if (isset($app['orm.em']) && is_object($app['orm.em'])) {
888
                            $optionsExists = $app['orm.em']
889
                                ->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
890
                                ->findOneBy(array('fieldId' => $field_details['id']));
891
                        }
892
893
                        if ($optionsExists) {
894
                            if (isset($userInfo['status']) && !empty($userInfo['status'])) {
895
896
                                $fieldWorkFlow = $app['orm.em']->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
897
                                    ->findBy(
898
                                        array(
899
                                            'fieldId' => $field_details['id'],
900
                                            'relatedFieldOptionId' => $defaultValueId,
901
                                            'roleId' => $userInfo['status']
902
                                        )
903
                                    );
904
                                foreach ($fieldWorkFlow as $item) {
905
                                    $addOptions[] = $item->getFieldOptionId();
906
                                }
907
                            }
908
                        }
909
910
                        $options = array();
911
                        if (empty($defaultValueId)) {
912
                            $options[''] = get_lang('SelectAnOption');
913
                        }
914
915
                        $optionList = array();
916
                        if (!empty($field_details['options'])) {
917
                            foreach ($field_details['options'] as $option_details) {
918
                                $optionList[$option_details['id']] = $option_details;
919
                                if ($get_lang_variables) {
920
                                    $options[$option_details['option_value']] = get_lang($option_details['display_text']);
921
                                } else {
922
                                    if ($optionsExists) {
923
                                        // Adding always the default value
924 View Code Duplication
                                        if ($option_details['id'] == $defaultValueId) {
925
                                            $options[$option_details['option_value']] = $option_details['display_text'];
926
                                        } else {
927
                                            if (isset($addOptions) && !empty($addOptions)) {
928
                                                // Parsing filters
929
                                                if (in_array($option_details['id'], $addOptions)) {
930
                                                    $options[$option_details['option_value']] = $option_details['display_text'];
931
                                                }
932
                                            }
933
                                        }
934
                                    } else {
935
                                        // Normal behaviour
936
                                        $options[$option_details['option_value']] = $option_details['display_text'];
937
                                    }
938
                                }
939
                            }
940
941
                            if (isset($optionList[$defaultValueId])) {
942
                                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...
943
                                    $optionList[$defaultValueId]['option_value'] == 'aprobada'
944
                                ) {
945
                                    // @todo function don't exists api_is_question_manager
946
                                    /*if (api_is_question_manager() == false) {
947
                                        $form->freeze();
948
                                    }*/
949
                                }
950
                            }
951
952
                            // Setting priority message
953
                            if (isset($optionList[$defaultValueId]) &&
954
                                isset($optionList[$defaultValueId]['priority'])
955
                            ) {
956
957
                                if (!empty($optionList[$defaultValueId]['priority'])) {
958
                                    $priorityId = $optionList[$defaultValueId]['priority'];
959
                                    $option = new ExtraFieldOption($this->type);
960
                                    $messageType = $option->getPriorityMessageType($priorityId);
961
                                    $form->addElement(
962
                                        'label',
963
                                        null,
964
                                        Display::return_message(
965
                                            $optionList[$defaultValueId]['priority_message'],
966
                                            $messageType
967
                                        )
968
                                    );
969
                                }
970
                            }
971
                        }
972
973
                        if ($get_lang_variables) {
974
                            $field_details['display_text'] = get_lang($field_details['display_text']);
975
                        }
976
977
                        // chzn-select doesn't work for sessions??
978
                        $form->addElement(
979
                            'select',
980
                            'extra_' . $field_details['variable'],
981
                            $field_details['display_text'],
982
                            $options,
983
                            array('id' => 'extra_'.$field_details['variable'])
984
                        );
985
986
                        /* Enable this when field_loggeable is introduced as a table field (2.0)
987
                        if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) {
988
989
                            $form->addElement(
990
                                'textarea',
991
                                'extra_' . $field_details['variable'] . '_comment',
992
                                $field_details['display_text'] . ' ' . get_lang('Comment')
993
                            );
994
995
                            $extraFieldValue = new ExtraFieldValue($this->type);
996
                            $repo = $app['orm.em']->getRepository($extraFieldValue->entityName);
997
                            $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry');
998
                            $newEntity = $repo->findOneBy(
999
                                array(
1000
                                    $this->handlerEntityId => $itemId,
1001
                                    'fieldId' => $field_details['id']
1002
                                )
1003
                            );
1004
                            // @todo move this in a function inside the class
1005
                            if ($newEntity) {
1006
                                $logs = $repoLog->getLogEntries($newEntity);
1007
                                if (!empty($logs)) {
1008
                                    $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />';
1009
1010
                                    $table = new HTML_Table(array('class' => 'data_table'));
1011
                                    $table->setHeaderContents(0, 0, get_lang('Value'));
1012
                                    $table->setHeaderContents(0, 1, get_lang('Comment'));
1013
                                    $table->setHeaderContents(0, 2, get_lang('ModifyDate'));
1014
                                    $table->setHeaderContents(0, 3, get_lang('Username'));
1015
                                    $row = 1;
1016
                                    foreach ($logs as $log) {
1017
                                        $column = 0;
1018
                                        $data = $log->getData();
1019
                                        $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null;
1020
                                        $comment = isset($data['comment']) ? $data['comment'] : null;
1021
1022
                                        $table->setCellContents($row, $column, $fieldValue);
1023
                                        $column++;
1024
                                        $table->setCellContents($row, $column, $comment);
1025
                                        $column++;
1026
                                        $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s')));
1027
                                        $column++;
1028
                                        $table->setCellContents($row, $column, $log->getUsername());
1029
                                        $row++;
1030
                                    }
1031
                                    $form->addElement('label', null, $html.$table->toHtml());
1032
                                }
1033
                            }
1034
                        }
1035
                        */
1036
1037
                        if (!$admin_permissions) {
1038
                            if ($field_details['visible'] == 0) {
1039
                                $form->freeze('extra_' . $field_details['variable']);
1040
                            }
1041
                        }
1042
                        break;
1043 View Code Duplication
                    case ExtraField::FIELD_TYPE_SELECT_MULTIPLE:
1044
                        $options = array();
1045
                        foreach ($field_details['options'] as $option_id => $option_details) {
1046
                            $options[$option_details['option_value']] = $option_details['display_text'];
1047
                        }
1048
                        $form->addElement(
1049
                            'select',
1050
                            'extra_'.$field_details['variable'],
1051
                            $field_details['display_text'],
1052
                            $options,
1053
                            array('multiple' => 'multiple')
1054
                        );
1055
                        if (!$admin_permissions) {
1056
                            if ($field_details['visible'] == 0) {
1057
                                $form->freeze('extra_'.$field_details['variable']);
1058
                            }
1059
                        }
1060
                        break;
1061 View Code Duplication
                    case ExtraField::FIELD_TYPE_DATE:
1062
                        $form->addDatePicker('extra_'.$field_details['variable'], $field_details['display_text']);
1063
                        if (!$admin_permissions) {
1064
                            if ($field_details['visible'] == 0) {
1065
                                $form->freeze('extra_'.$field_details['variable']);
1066
                            }
1067
                        }
1068
1069
                        $form->applyFilter('theme', 'trim');
1070
                        break;
1071
                    case ExtraField::FIELD_TYPE_DATETIME:
1072
                        $form->addDateTimePicker(
1073
                            'extra_'.$field_details['variable'],
1074
                            $field_details['display_text']
1075
                        );
1076
1077
                        $defaults['extra_'.$field_details['variable']] = api_get_local_time();
1078
                        if (!isset($form->_defaultValues['extra_'.$field_details['variable']])) {
1079
                            $form->setDefaults($defaults);
1080
                        }
1081
                        if (!$admin_permissions) {
1082
                            if ($field_details['visible'] == 0) {
1083
                                $form->freeze('extra_'.$field_details['variable']);
1084
                            }
1085
                        }
1086
                        $form->applyFilter('theme', 'trim');
1087
                        break;
1088
                    case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
1089
                        $first_select_id = 'first_extra_'.$field_details['variable'];
1090
                        $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
1091
1092
                        $jquery_ready_content .= '
1093
                        $("#'.$first_select_id.'").on("change", function() {
1094
                            var id = $(this).val();
1095
                            if (id) {
1096
                                $.ajax({
1097
                                    url: "'.$url.'&a=get_second_select_options",
1098
                                    dataType: "json",
1099
                                    data: "type='.$type.'&field_id='.$field_details['id'].'&option_value_id="+id,
1100
                                    success: function(data) {
1101
                                        $("#second_extra_'.$field_details['variable'].'").empty();
1102
                                        $.each(data, function(index, value) {
1103
                                            $("#second_extra_'.$field_details['variable'].'").append($("<option/>", {
1104
                                                value: index,
1105
                                                text: value
1106
                                            }));
1107
                                        });
1108
                                        $("#second_extra_'.$field_details['variable'].'").selectpicker("refresh");
1109
                                    },
1110
                                });
1111
                            } else {
1112
                                $("#second_extra_'.$field_details['variable'].'").empty();
1113
                            }
1114
                        });';
1115
1116
                        $first_id  = null;
1117
                        $second_id = null;
1118
1119
                        if (!empty($extraData)) {
1120
                            $first_id  = $extraData['extra_'.$field_details['variable']]['extra_'.$field_details['variable']];
1121
                            $second_id = $extraData['extra_'.$field_details['variable']]['extra_'.$field_details['variable'].'_second'];
1122
                        }
1123
1124
                        $options = ExtraField::extra_field_double_select_convert_array_to_ordered_array(
1125
                            $field_details['options']
1126
                        );
1127
                        $values  = array('' => get_lang('Select'));
1128
1129
                        $second_values = array();
1130
                        if (!empty($options)) {
1131
                            foreach ($options as $option) {
1132
                                foreach ($option as $sub_option) {
1133
                                    if ($sub_option['option_value'] == '0') {
1134
                                        $values[$sub_option['id']] = $sub_option['display_text'];
1135
                                    } else {
1136
                                        if ($first_id === $sub_option['option_value']) {
1137
                                            $second_values[$sub_option['id']] = $sub_option['display_text'];
1138
                                        }
1139
                                    }
1140
                                }
1141
                            }
1142
                        }
1143
                        $group   = array();
1144
                        $group[] = $form->createElement(
1145
                            'select',
1146
                            'extra_'.$field_details['variable'],
1147
                            null,
1148
                            $values,
1149
                            array('id' => $first_select_id)
1150
                        );
1151
                        $group[] = $form->createElement(
1152
                            'select',
1153
                            'extra_'.$field_details['variable'].'_second',
1154
                            null,
1155
                            $second_values,
1156
                            array('id' => 'second_extra_'.$field_details['variable'])
1157
                        );
1158
                        $form->addGroup(
1159
                            $group,
1160
                            'extra_'.$field_details['variable'],
1161
                            $field_details['display_text'],
1162
                            '&nbsp;'
1163
                        );
1164
1165
                        if (!$admin_permissions) {
1166
                            if ($field_details['visible'] == 0) {
1167
                                $form->freeze('extra_'.$field_details['variable']);
1168
                            }
1169
                        }
1170
                        break;
1171
                    case ExtraField::FIELD_TYPE_DIVIDER:
1172
                        $form->addElement(
1173
                            'static',
1174
                            $field_details['variable'],
1175
                            '<br /><strong>'.$field_details['display_text'].'</strong>'
1176
                        );
1177
                        break;
1178
                    case ExtraField::FIELD_TYPE_TAG:
1179
                        $variable = $field_details['variable'];
1180
                        $field_id = $field_details['id'];
1181
1182
                        //Added for correctly translate the extra_field
1183
                        $get_lang_variables = false;
1184
                        if (in_array($variable, ['tags'])) {
1185
                            $get_lang_variables = true;
1186
                        }
1187
1188
                        if ($get_lang_variables) {
1189
                            $field_details['display_text'] = get_lang($field_details['display_text']);
1190
                        }
1191
1192
                        $tagsSelect = $form->addSelect(
1193
                            "extra_{$field_details['variable']}",
1194
                            $field_details['display_text']
1195
                        );
1196
                        $tagsSelect->setAttribute('class', null);
1197
                        $tagsSelect->setAttribute('id', "extra_{$field_details['variable']}");
1198
                        $tagsSelect->setMultiple(true);
1199
1200
                        if ($this->type == 'user') {
1201
1202
                           /* //the magic should be here
1203
                            $user_tags = UserManager::get_user_tags($user_id, $field_details[0]);
1204
1205
                            $tag_list = '';
1206
                            if (is_array($user_tags) && count($user_tags) > 0) {
1207
                                foreach ($user_tags as $tag) {
1208
                                    $tag_list .= '<option value="'.$tag['tag'].'" class="selected">'.$tag['tag'].'</option>';
1209
                                }
1210
                            }
1211
1212
                            $multi_select = '<select id="extra_'.$field_details[1].'" name="extra_'.$field_details[1].'">
1213
                                    '.$tag_list.'
1214
                                    </select>';
1215
1216
                            $form->addElement('label', $field_details[3], $multi_select);
1217
                            $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
1218
                            $complete_text = get_lang('StartToType');
1219
                            //if cache is set to true the jquery will be called 1 time
1220
                            $jquery_ready_content = <<<EOF
1221
                    $("#extra_$field_details[1]").fcbkcomplete({
1222
                        json_url: "$url?a=search_tags&field_id=$field_details[0]",
1223
                        cache: false,
1224
                        filter_case: true,
1225
                        filter_hide: true,
1226
                        complete_text:"$complete_text",
1227
                        firstselected: true,
1228
                        //onremove: "testme",
1229
                        //onselect: "testme",
1230
                        filter_selected: true,
1231
                        newel: true
1232
                    });
1233
EOF;
1234
                            break;*/
1235
1236
                            // The magic should be here
1237
                            $user_tags = UserManager::get_user_tags($itemId, $field_details['id']);
1238
1239
                            if (is_array($user_tags) && count($user_tags) > 0) {
1240
                                foreach ($user_tags as $tag) {
1241
                                    $tagsSelect->addOption(
1242
                                        $tag['tag'],
1243
                                        $tag['tag'],
1244
                                        ['selected' => 'selected', 'class' => 'selected']
1245
                                    );
1246
                                }
1247
                            }
1248
                            $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
1249
                        } else {
1250
                            $em = Database::getManager();
1251
1252
                            $fieldTags = $em
1253
                                ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
1254
                                ->findBy([
1255
                                    'fieldId' => $field_id,
1256
                                    'itemId' => $itemId
1257
                                ]);
1258
1259
                            foreach ($fieldTags as $fieldTag) {
1260
                                $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1261
1262
                                if (empty($tag)) {
1263
                                    continue;
1264
                                }
1265
1266
                                $tagsSelect->addOption(
1267
                                    $tag->getTag(),
1268
                                    $tag->getTag(),
1269
                                    ['selected' => 'selected', 'class' => 'selected']
1270
                                );
1271
                            }
1272
1273
                            $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php';
1274
                        }
1275
1276
                        $complete_text = get_lang('StartToType');
1277
1278
                        //if cache is set to true the jquery will be called 1 time
1279
1280
                        $jquery_ready_content .= <<<EOF
1281
                    $("#extra_$variable").fcbkcomplete({
1282
                        json_url: "$url?a=search_tags&field_id=$field_id&type={$this->type}",
1283
                        cache: false,
1284
                        filter_case: true,
1285
                        filter_hide: true,
1286
                        complete_text:"$complete_text",
1287
                        firstselected: false,
1288
                        filter_selected: true,
1289
                        newel: true
1290
                    });
1291
EOF;
1292
                        break;
1293 View Code Duplication
                    case ExtraField::FIELD_TYPE_TIMEZONE:
1294
                        $form->addElement(
1295
                            'select',
1296
                            'extra_'.$field_details['variable'],
1297
                            $field_details['display_text'],
1298
                            api_get_timezones(),
1299
                            ''
1300
                        );
1301
                        if ($field_details['visible'] == 0) {
1302
                            $form->freeze(
1303
                                'extra_'.$field_details['variable']
1304
                            );
1305
                        }
1306
                        break;
1307
                    case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
1308
                        // get the social network's favicon
1309
                        $extra_data_variable = isset($extraData['extra_'.$field_details['variable']]) ? $extraData['extra_'.$field_details['variable']] : null;
1310
                        $field_default_value = isset($field_details['field_default_value']) ? $field_details['field_default_value'] : null;
1311
                        $icon_path = UserManager::get_favicon_from_url(
1312
                            $extra_data_variable,
1313
                            $field_default_value
1314
                        );
1315
                        // special hack for hi5
1316
                        $leftpad = '1.7';
1317
                        $top     = '0.4';
1318
                        $domain  = parse_url($icon_path, PHP_URL_HOST);
1319
                        if ($domain == 'www.hi5.com' or $domain == 'hi5.com') {
1320
                            $leftpad = '3';
1321
                            $top     = '0';
1322
                        }
1323
                        // print the input field
1324
                        $form->addElement(
1325
                            'text',
1326
                            'extra_'.$field_details['variable'],
1327
                            $field_details['display_text'],
1328
                            array(
1329
                                'size'  => 60,
1330
                                'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '
1331
                            )
1332
                        );
1333
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1334
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1335
                        if ($field_details['visible'] == 0) {
1336
                            $form->freeze('extra_'.$field_details['variable']);
1337
                        }
1338
                        break;
1339 View Code Duplication
                    case ExtraField::FIELD_TYPE_MOBILE_PHONE_NUMBER:
1340
                        $form->addElement(
1341
                            'text',
1342
                            'extra_'.$field_details[1],
1343
                            $field_details[3]." (".get_lang('CountryDialCode').")",
1344
                            array('size' => 40, 'placeholder' => '(xx)xxxxxxxxx')
1345
                        );
1346
                        $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
1347
                        $form->applyFilter('extra_'.$field_details[1], 'trim');
1348
                        $form->applyFilter('extra_'.$field_details[1], 'mobile_phone_number_filter');
1349
                        $form->addRule(
1350
                            'extra_'.$field_details[1],
1351
                            get_lang('MobilePhoneNumberWrong'),
1352
                            'mobile_phone_number'
1353
                        );
1354
                        if ($field_details['visible'] == 0) {
1355
                            $form->freeze('extra_'.$field_details['variable']);
1356
                        }
1357
                        break;
1358 View Code Duplication
                    case ExtraField::FIELD_TYPE_INTEGER:
1359
                        $form->addElement(
1360
                            'number',
1361
                            'extra_'.$field_details['variable'],
1362
                            $field_details['display_text'],
1363
                            array('class' => 'span1', 'step' => 1)
1364
                        );
1365
1366
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1367
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1368
                        $form->applyFilter('extra_'.$field_details['variable'], 'intval');
1369
1370
                        if (!$admin_permissions) {
1371
                            if ($field_details['visible'] == 0) {
1372
                                $form->freeze(
1373
                                    'extra_'.$field_details['variable']
1374
                                );
1375
                            }
1376
                        }
1377
                        break;
1378
                    case ExtraField::FIELD_TYPE_FILE_IMAGE:
1379
                        $fieldVariable = "extra_{$field_details['variable']}";
1380
1381
                        $fieldTexts = array(
1382
                            $field_details['display_text']
1383
                        );
1384
1385 View Code Duplication
                        if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
1386
1387
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) {
1388
                                $fieldTexts[] = Display::img(
1389
                                    api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable],
1390
                                    $field_details['display_text'],
1391
                                    array('width' => '300')
1392
                                );
1393
                            }
1394
                        }
1395
1396
                        $form->addElement(
1397
                            'file',
1398
                            $fieldVariable,
1399
                            $fieldTexts,
1400
                            array('accept' => 'image/*')
1401
                        );
1402
1403
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1404
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1405
1406
                        $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
1407
                        $form->addRule(
1408
                            'extra_'.$field_details['variable'],
1409
                            get_lang('OnlyImagesAllowed') . ' ('.implode(',', $allowed_picture_types).')',
1410
                            'filetype',
1411
                            $allowed_picture_types
1412
                        );
1413
1414
                        if (!$admin_permissions) {
1415
                            if ($field_details['visible'] == 0) {
1416
                                $form->freeze(
1417
                                    'extra_'.$field_details['variable']
1418
                                );
1419
                            }
1420
                        }
1421
                        break;
1422 View Code Duplication
                    case ExtraField::FIELD_TYPE_FLOAT:
1423
                        $form->addElement(
1424
                            'number',
1425
                            'extra_'.$field_details['variable'],
1426
                            $field_details['display_text'],
1427
                            array('class' => 'span1', 'step' => '0.01')
1428
                        );
1429
1430
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1431
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1432
                        $form->applyFilter('extra_'.$field_details['variable'], 'floatval');
1433
1434
                        if (!$admin_permissions) {
1435
                            if ($field_details['visible'] == 0) {
1436
                                $form->freeze(
1437
                                    'extra_'.$field_details['variable']
1438
                                );
1439
                            }
1440
                        }
1441
                        break;
1442
                    case ExtraField::FIELD_TYPE_FILE:
1443
                        $fieldVariable = "extra_{$field_details['variable']}";
1444
                        $fieldTexts = array(
1445
                            $field_details['display_text']
1446
                        );
1447
1448
                        if (is_array($extraData) &&
1449
                            array_key_exists($fieldVariable, $extraData)
1450
                        ) {
1451 View Code Duplication
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) {
1452
                                $fieldTexts[] = Display::url(
1453
                                    api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable],
1454
                                    api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable],
1455
                                    array(
1456
                                        'title' => $field_details['display_text'],
1457
                                        'target' => '_blank'
1458
                                    )
1459
                                );
1460
                            }
1461
                        }
1462
1463
                        $form->addElement(
1464
                            'file',
1465
                            $fieldVariable,
1466
                            $fieldTexts,
1467
                            array()
1468
                        );
1469
1470
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1471
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1472
1473
                        if (!$admin_permissions) {
1474
                            if ($field_details['visible'] == 0) {
1475
                                $form->freeze(
1476
                                    'extra_'.$field_details['variable']
1477
                                );
1478
                            }
1479
                        }
1480
                        break;
1481
                    case ExtraField::FIELD_TYPE_VIDEO_URL:
1482
                        //Added for correctly translate the extra_field
1483
                        $get_lang_variables = false;
1484
                        if (in_array($field_details['variable'], ['video_url'])) {
1485
                            $get_lang_variables = true;
1486
                        }
1487
1488
                        if ($get_lang_variables) {
1489
                            $field_details['display_text'] = get_lang($field_details['display_text']);
1490
                        }
1491
1492
                        $form->addUrl(
1493
                            "extra_{$field_details['variable']}",
1494
                            $field_details['display_text'],
1495
                            false,
1496
                            ['placeholder' => 'https://']
1497
                        );
1498
                        break;
1499 View Code Duplication
                    case ExtraField::FIELD_TYPE_LETTERS_ONLY:
1500
                        $form->addTextLettersOnly(
1501
                            "extra_{$field_details['variable']}",
1502
                            $field_details['display_text']
1503
                        );
1504
                        $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes');
1505
1506
                        if (!$admin_permissions) {
1507
                            if ($field_details['visible'] == 0) {
1508
                                $form->freeze(
1509
                                    'extra_' . $field_details['variable']
1510
                                );
1511
                            }
1512
                        }
1513
                        break;
1514 View Code Duplication
                    case ExtraField::FIELD_TYPE_ALPHANUMERIC:
1515
                        $form->addTextAlphanumeric(
1516
                            "extra_{$field_details['variable']}",
1517
                            $field_details['display_text']
1518
                        );
1519
                        $form->applyFilter(
1520
                            'extra_' . $field_details['variable'],
1521
                            'stripslashes'
1522
                        );
1523
                        if (!$admin_permissions) {
1524
                            if ($field_details['visible'] == 0) {
1525
                                $form->freeze(
1526
                                    'extra_' . $field_details['variable']
1527
                                );
1528
                            }
1529
                        }
1530
                        break;
1531 View Code Duplication
                    case ExtraField::FIELD_TYPE_LETTERS_SPACE:
1532
                        $form->addTextLettersAndSpaces(
1533
                            "extra_{$field_details['variable']}",
1534
                            $field_details['display_text']
1535
                        );
1536
                        $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes');
1537
1538
                        if (!$admin_permissions) {
1539
                            if ($field_details['visible'] == 0) {
1540
                                $form->freeze(
1541
                                    'extra_' . $field_details['variable']
1542
                                );
1543
                            }
1544
                        }
1545
                        break;
1546 View Code Duplication
                    case ExtraField::FIELD_TYPE_ALPHANUMERIC_SPACE:
1547
                        $form->addTextAlphanumericAndSpaces(
1548
                            "extra_{$field_details['variable']}",
1549
                            $field_details['display_text']
1550
                        );
1551
                        $form->applyFilter(
1552
                            'extra_' . $field_details['variable'],
1553
                            'stripslashes'
1554
                        );
1555
                        if (!$admin_permissions) {
1556
                            if ($field_details['visible'] == 0) {
1557
                                $form->freeze(
1558
                                    'extra_' . $field_details['variable']
1559
                                );
1560
                            }
1561
                        }
1562
                        break;
1563
                }
1564
            }
1565
        }
1566
        $return = array();
1567
        $return['jquery_ready_content'] = $jquery_ready_content;
1568
1569
        return $return;
1570
    }
1571
1572
    function setupBreadcrumb(&$breadcrumb, $action)
1573
    {
1574
        if ($action == 'add') {
1575
            $breadcrumb[] = array('url' => $this->pageUrl, 'name' => $this->pageName);
1576
            $breadcrumb[] = array('url' => '#', 'name' => get_lang('Add'));
1577
        } elseif ($action == 'edit') {
1578
            $breadcrumb[] = array('url' => $this->pageUrl, 'name' => $this->pageName);
1579
            $breadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
1580
        } else {
1581
            $breadcrumb[] = array('url' => '#', 'name' => $this->pageName);
1582
        }
1583
    }
1584
1585
1586
    /**
1587
     * Displays the title + grid
1588
     */
1589
    public function display()
1590
    {
1591
        // action links
1592
        echo '<div class="actions">';
1593
        echo '<a href="../admin/index.php">'.Display::return_icon(
1594
                'back.png',
1595
                get_lang('BackTo').' '.get_lang('PlatformAdmin'),
1596
                '',
1597
                ICON_SIZE_MEDIUM
1598
            ).'</a>';
1599
        echo '<a href="'.api_get_self().'?action=add&type='.$this->type.'">'.Display::return_icon(
1600
                'add_user_fields.png',
1601
                get_lang('Add'),
1602
                '',
1603
                ICON_SIZE_MEDIUM
1604
            ).'</a>';
1605
        echo '</div>';
1606
        echo Display::grid_html($this->type.'_fields');
1607
    }
1608
1609
    /**
1610
     * @return array
1611
     */
1612
    public function getJqgridColumnNames()
1613
    {
1614
        return array(
1615
            get_lang('Name'),
1616
            get_lang('FieldLabel'),
1617
            get_lang('Type'),
1618
            get_lang('FieldChangeability'),
1619
            get_lang('Visibility'),
1620
            get_lang('Filter'),
1621
            get_lang('FieldOrder'),
1622
            get_lang('Actions')
1623
        );
1624
    }
1625
1626
    /**
1627
     * @return array
1628
     */
1629
    public function getJqgridColumnModel()
1630
    {
1631
        return array(
1632
            array(
1633
                'name' => 'display_text',
1634
                'index' => 'display_text',
1635
                'width' => '180',
1636
                'align' => 'left',
1637
            ),
1638
            array(
1639
                'name'     => 'variable',
1640
                'index'    => 'variable',
1641
                'width'    => '',
1642
                'align'    => 'left',
1643
                'sortable' => 'true'
1644
            ),
1645
            array(
1646
                'name'     => 'field_type',
1647
                'index'    => 'field_type',
1648
                'width'    => '',
1649
                'align'    => 'left',
1650
                'sortable' => 'true'
1651
            ),
1652
            array(
1653
                'name'     => 'changeable',
1654
                'index'    => 'changeable',
1655
                'width'    => '50',
1656
                'align'    => 'left',
1657
                'sortable' => 'true'
1658
            ),
1659
            array(
1660
                'name'     => 'visible',
1661
                'index'    => 'visible',
1662
                'width'    => '40',
1663
                'align'    => 'left',
1664
                'sortable' => 'true'
1665
            ),
1666
            array(
1667
                'name'     => 'filter',
1668
                'index'    => 'filter',
1669
                'width'    => '30',
1670
                'align'    => 'left',
1671
                'sortable' => 'true'
1672
            ),
1673
            array(
1674
                'name'     => 'field_order',
1675
                'index'    => 'field_order',
1676
                'width'    => '40',
1677
                'align'    => 'left',
1678
                'sortable' => 'true'
1679
            ),
1680
            array(
1681
                'name'      => 'actions',
1682
                'index'     => 'actions',
1683
                'width'     => '100',
1684
                'align'     => 'left',
1685
                'formatter' => 'action_formatter',
1686
                'sortable'  => 'false'
1687
            )
1688
        );
1689
    }
1690
1691
    /**
1692
     * @param string $url
1693
     * @param string $action
1694
     * @return FormValidator
1695
     */
1696
    public function return_form($url, $action)
1697
    {
1698
        $form = new FormValidator($this->type.'_field', 'post', $url);
1699
1700
        $form->addElement('hidden', 'type', $this->type);
1701
        $id = isset($_GET['id']) ? intval($_GET['id']) : null;
1702
        $form->addElement('hidden', 'id', $id);
1703
1704
        // Setting the form elements
1705
        $header   = get_lang('Add');
1706
        $defaults = array();
1707
1708
        if ($action == 'edit') {
1709
            $header = get_lang('Modify');
1710
            // Setting the defaults
1711
            $defaults = $this->get($id);
1712
        }
1713
1714
        $form->addElement('header', $header);
1715
        $form->addElement('text', 'display_text', get_lang('Name'), array('class' => 'span5'));
1716
1717
        // Field type
1718
        $types = self::get_field_types();
1719
1720
        $form->addElement(
1721
            'select',
1722
            'field_type',
1723
            get_lang('FieldType'),
1724
            $types,
1725
            array('id' => 'field_type')
1726
        );
1727
        $form->addElement('label', get_lang('Example'), '<div id="example">-</div>');
1728
        $form->addElement('text', 'variable', get_lang('FieldLabel'), array('class' => 'span5'));
1729
        $form->addElement(
1730
            'text',
1731
            'field_options',
1732
            get_lang('FieldPossibleValues'),
1733
            array('id' => 'field_options', 'class' => 'span6')
1734
        );
1735
1736
        $fieldWithOptions = array(
1737
            ExtraField::FIELD_TYPE_RADIO,
1738
            ExtraField::FIELD_TYPE_SELECT_MULTIPLE,
1739
            ExtraField::FIELD_TYPE_SELECT,
1740
            ExtraField::FIELD_TYPE_TAG,
1741
            ExtraField::FIELD_TYPE_DOUBLE_SELECT,
1742
        );
1743
1744
        if ($action == 'edit') {
1745
            if (in_array($defaults['field_type'], $fieldWithOptions)) {
1746
                $url = Display::url(
1747
                    get_lang('EditExtraFieldOptions'),
1748
                    'extra_field_options.php?type='.$this->type.'&field_id='.$id
1749
                );
1750
                $form->addElement('label', null, $url);
1751
1752
                if ($defaults['field_type'] == ExtraField::FIELD_TYPE_SELECT) {
1753
                    $urlWorkFlow = Display::url(
1754
                        get_lang('EditExtraFieldWorkFlow'),
1755
                        'extra_field_workflow.php?type='.$this->type.'&field_id='.$id
1756
                    );
1757
                    $form->addElement('label', null, $urlWorkFlow);
1758
                }
1759
1760
                $form->freeze('field_options');
1761
            }
1762
        }
1763
        $form->addElement(
1764
            'text',
1765
            'default_value',
1766
            get_lang('FieldDefaultValue'),
1767
            array('id' => 'default_value')
1768
        );
1769
1770
        $group   = array();
1771
        $group[] = $form->createElement('radio', 'visible', null, get_lang('Yes'), 1);
1772
        $group[] = $form->createElement('radio', 'visible', null, get_lang('No'), 0);
1773
        $form->addGroup($group, '', get_lang('Visible'), '', false);
1774
1775
        $group   = array();
1776
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('Yes'), 1);
1777
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('No'), 0);
1778
        $form->addGroup($group, '', get_lang('FieldChangeability'), '', false);
1779
1780
        $group   = array();
1781
        $group[] = $form->createElement('radio', 'filter', null, get_lang('Yes'), 1);
1782
        $group[] = $form->createElement('radio', 'filter', null, get_lang('No'), 0);
1783
        $form->addGroup($group, '', get_lang('FieldFilter'), '', false);
1784
1785
        /* Enable this when field_loggeable is introduced as a table field (2.0)
1786
        $group   = array();
1787
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('Yes'), 1);
1788
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('No'), 0);
1789
        $form->addGroup($group, '', get_lang('FieldLoggeable'), '', false);
1790
        */
1791
1792
        $form->addElement('text', 'field_order', get_lang('FieldOrder'), array('class' => 'span1'));
1793
1794
        if ($action == 'edit') {
1795
            $option = new ExtraFieldOption($this->type);
1796
            if ($defaults['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
1797
                $form->freeze('field_options');
1798
            }
1799
            $defaults['field_options'] = $option->get_field_options_by_field_to_string($id);
1800
            $form->addButtonUpdate(get_lang('Modify'));
1801
        } else {
1802
            $defaults['visible'] = 0;
1803
            $defaults['changeable'] = 0;
1804
            $defaults['filter'] = 0;
1805
            $form->addButtonCreate(get_lang('Add'));
1806
        }
1807
1808
        /*if (!empty($defaults['created_at'])) {
1809
            $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
1810
        }
1811
        if (!empty($defaults['updated_at'])) {
1812
            $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
1813
        }*/
1814
        $form->setDefaults($defaults);
1815
1816
        // Setting the rules
1817
        $form->addRule('display_text', get_lang('ThisFieldIsRequired'), 'required');
1818
        $form->addRule('field_type', get_lang('ThisFieldIsRequired'), 'required');
1819
1820
        return $form;
1821
    }
1822
1823
    /**
1824
     * @param $token
1825
     * @return string
1826
     */
1827
    public function getJqgridActionLinks($token)
1828
    {
1829
        //With this function we can add actions to the jgrid (edit, delete, etc)
1830
        return 'function action_formatter(cellvalue, options, rowObject) {
1831
         return \'<a href="?action=edit&type='.$this->type.'&id=\'+options.rowId+\'">'.Display::return_icon(
1832
            'edit.png',
1833
            get_lang('Edit'),
1834
            '',
1835
            ICON_SIZE_SMALL
1836
        ).'</a>'.
1837
        '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(
1838
            api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES)
1839
        )."\'".')) return false;"  href="?sec_token='.$token.'&type='.$this->type.'&action=delete&id=\'+options.rowId+\'">'.Display::return_icon(
1840
            'delete.png',
1841
            get_lang('Delete'),
1842
            '',
1843
            ICON_SIZE_SMALL
1844
        ).'</a>'.
1845
        '\';
1846
        }';
1847
    }
1848
1849
    /**
1850
     * @param array $columns
1851
     * @param array  $column_model
1852
     * @param array  $extraFields
1853
     * @return array
1854
     */
1855
    public function getRules(&$columns, &$column_model, $extraFields = array(), $checkExtraFieldExistence = false)
1856
    {
1857
        $fields = $this->get_all(
1858
            array(
1859
                'visible = ? AND filter = ?' => array(1, 1)
1860
            ),
1861
            'display_text'
1862
        );
1863
        $extraFieldOption = new ExtraFieldOption($this->type);
1864
1865
        $rules = array();
1866
        if (!empty($fields)) {
1867
            foreach ($fields as $field) {
1868
1869
                $search_options = array();
1870
                $type           = 'text';
1871
                if (in_array($field['field_type'], array(self::FIELD_TYPE_SELECT, self::FIELD_TYPE_DOUBLE_SELECT))) {
1872
                    $type                   = 'select';
1873
                    $search_options['sopt'] = array('eq', 'ne'); //equal not equal
1874
                } else {
1875
                    $search_options['sopt'] = array('cn', 'nc'); //contains not contains
1876
                }
1877
1878
                $search_options['searchhidden'] = 'true';
1879
                $search_options['defaultValue'] = isset($search_options['field_default_value']) ? $search_options['field_default_value'] : null;
1880
1881
                if ($field['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
1882
                    //Add 2 selects
1883
                    $options = $extraFieldOption->get_field_options_by_field($field['id']);
1884
                    $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...
1885
                    $first_options = array();
1886
1887
                    if (!empty($options)) {
1888
                        foreach ($options as $option) {
1889
                            foreach ($option as $sub_option) {
1890
                                if ($sub_option['option_value'] == 0) {
1891
                                    $first_options[] = $sub_option['field_id'].'#'.$sub_option['id'].':'.$sub_option['display_text'];
1892
                                }
1893
                            }
1894
                        }
1895
                    }
1896
1897
                    $search_options['value'] = implode(';', $first_options);
1898
                    $search_options['dataInit'] = 'fill_second_select';
1899
1900
                    // First
1901
                    $column_model[] = array(
1902
                        'name' => 'extra_'.$field['variable'],
1903
                        'index' => 'extra_'.$field['variable'],
1904
                        'width' => '100',
1905
                        'hidden' => 'true',
1906
                        'search' => 'true',
1907
                        'stype' => 'select',
1908
                        'searchoptions' => $search_options,
1909
                    );
1910
                    $columns[] = $field['display_text'].' (1)';
1911
                    $rules[] = array(
1912
                        'field' => 'extra_'.$field['variable'],
1913
                        'op' => 'cn',
1914
                    );
1915
1916
                    //Second
1917
                    $search_options['value']    = $field['id'].':';
1918
                    $search_options['dataInit'] = 'register_second_select';
1919
1920
                    $column_model[] = array(
1921
                        'name' => 'extra_'.$field['variable'].'_second',
1922
                        'index' => 'extra_'.$field['variable'].'_second',
1923
                        'width' => '100',
1924
                        'hidden' => 'true',
1925
                        'search' => 'true',
1926
                        'stype' => 'select',
1927
                        'searchoptions' => $search_options,
1928
                    );
1929
                    $columns[]      = $field['display_text'].' (2)';
1930
                    $rules[]        = array('field' => 'extra_'.$field['variable'].'_second', 'op' => 'cn');
1931
                    continue;
1932
                } else {
1933
                    $search_options['value'] = $extraFieldOption->getFieldOptionsToString(
1934
                        $field['id'],
1935
                        false,
1936
                        'display_text'
1937
                    );
1938
                }
1939
                $column_model[] = array(
1940
                    'name'          => 'extra_'.$field['variable'],
1941
                    'index'         => 'extra_'.$field['variable'],
1942
                    'width'         => '100',
1943
                    'hidden'        => 'true',
1944
                    'search'        => 'true',
1945
                    'stype'         => $type,
1946
                    'searchoptions' => $search_options
1947
                );
1948
                $columns[]      = $field['display_text'];
1949
                $rules[]        = array('field' => 'extra_'.$field['variable'], 'op' => 'cn');
1950
            }
1951
        }
1952
1953
        return $rules;
1954
    }
1955
1956
    /**
1957
     * @param array $options
1958
     * @return array
1959
     */
1960
    public function parseConditions($options)
1961
    {
1962
        $inject_extra_fields = null;
1963
        $extraFieldOption = new ExtraFieldOption($this->type);
1964
        $double_fields = array();
1965
1966
        if (isset($options['extra'])) {
1967
            $extra_fields = $options['extra'];
1968
            if (!empty($extra_fields)) {
1969
                $counter = 1;
1970
                foreach ($extra_fields as &$extra) {
1971
                    $extra_field_obj = new ExtraField($this->type);
1972
                    $extra_field_info = $extra_field_obj->get($extra['id']);
1973
                    $extra['extra_field_info'] = $extra_field_info;
1974
1975
                    if (isset($extra_field_info['field_type']) && in_array(
1976
                            $extra_field_info['field_type'],
1977
                            array(
1978
                                ExtraField::FIELD_TYPE_SELECT,
1979
                                ExtraField::FIELD_TYPE_SELECT,
1980
                                ExtraField::FIELD_TYPE_DOUBLE_SELECT
1981
                            )
1982
                        )
1983
                    ) {
1984
                        $inject_extra_fields .= " fvo$counter.display_text as {$extra['field']}, ";
1985
                    } else {
1986
                        $inject_extra_fields .= " fv$counter.value as {$extra['field']}, ";
1987
                    }
1988
1989 View Code Duplication
                    if (isset($extra_fields_info[$extra['id']])) {
1990
                        $info = $extra_fields_info[$extra['id']];
1991
                    } else {
1992
                        $info = $this->get($extra['id']);
1993
                        $extra_fields_info[$extra['id']] = $info;
1994
                    }
1995
                    if (isset($info['field_type']) && $info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
1996
                        $double_fields[$info['id']] = $info;
1997
                    }
1998
                    $counter++;
1999
                }
2000
            }
2001
        }
2002
        $options_by_double = array();
2003 View Code Duplication
        foreach ($double_fields as $double) {
2004
            $my_options = $extraFieldOption->get_field_options_by_field(
2005
                $double['id'],
2006
                true
2007
            );
2008
            $options_by_double['extra_'.$double['variable']] = $my_options;
2009
        }
2010
2011
        $field_value_to_join = array();
2012
2013
        //filter can be all/any = and/or
2014
        $inject_joins = null;
2015
        $inject_where = null;
2016
        $where        = null;
2017
2018
        if (!empty($options['where'])) {
2019
            if (!empty($options['extra'])) {
2020
                // Removing double 1=1
2021
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
2022
                // Always OR
2023
                $counter = 1;
2024
                foreach ($extra_fields as $extra_info) {
2025
                    $extra_field_info = $extra_info['extra_field_info'];
2026
                    $inject_joins .= " INNER JOIN $this->table_field_values fv$counter
2027
                                       ON (s.".$this->primaryKey." = fv$counter.".$this->handler_id.") ";
2028
2029
                    // Add options
2030
                    if (isset($extra_field_info['field_type']) && in_array(
2031
                            $extra_field_info['field_type'],
2032
                            array(
2033
                                ExtraField::FIELD_TYPE_SELECT,
2034
                                ExtraField::FIELD_TYPE_SELECT,
2035
                                ExtraField::FIELD_TYPE_DOUBLE_SELECT
2036
                            )
2037
                        )
2038
                    ) {
2039
                        $options['where'] = str_replace(
2040
                            $extra_info['field'],
2041
                            'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fvo'.$counter.'.option_value',
2042
                            $options['where']
2043
                        );
2044
                        $inject_joins .= " INNER JOIN $this->table_field_options fvo$counter ".
2045
                            " ON (fv$counter.field_id = fvo$counter.field_id AND fv$counter.value = fvo$counter.option_value) ";
2046
                    } else {
2047
                        //text, textarea, etc
2048
                        $options['where'] = str_replace(
2049
                            $extra_info['field'],
2050
                            'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fv'.$counter.'.value',
2051
                            $options['where']
2052
                        );
2053
                    }
2054
2055
                    $field_value_to_join[] = " fv$counter.$this->handler_id ";
2056
                    $counter++;
2057
                }
2058
                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...
2059
                    //$inject_where .= " AND s.id = ".implode(' = ', $field_value_to_join);
2060
                }
2061
            }
2062
            $where .= ' AND '.$options['where'];
2063
        }
2064
2065
        $order = null;
2066
        if (!empty($options['order'])) {
2067
            $order = " ORDER BY ".$options['order'];
2068
        }
2069
        $limit = null;
2070
        if (!empty($options['limit'])) {
2071
            $limit = " LIMIT ".$options['limit'];
2072
        }
2073
2074
        return array(
2075
            'order'               => $order,
2076
            'limit'               => $limit,
2077
            'where'               => $where,
2078
            'inject_where'        => $inject_where,
2079
            'inject_joins'        => $inject_joins,
2080
            'field_value_to_join' => $field_value_to_join,
2081
            'inject_extra_fields' => $inject_extra_fields,
2082
        );
2083
    }
2084
2085
    //@todo move this in the display_class or somewhere else
2086
    /**
2087
     * @param $col
2088
     * @param $oper
2089
     * @param $val
2090
     * @return string
2091
     */
2092
    public function get_where_clause($col, $oper, $val)
2093
    {
2094
        if (empty($col)) {
2095
            return '';
2096
        }
2097
        if ($oper == 'bw' || $oper == 'bn') {
2098
            $val .= '%';
2099
        }
2100
        if ($oper == 'ew' || $oper == 'en') {
2101
            $val = '%'.$val;
2102
        }
2103 View Code Duplication
        if ($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') {
2104
            $val = '%'.$val.'%';
2105
        }
2106
        $val = \Database::escape_string($val);
2107
2108
        return " $col {$this->ops[$oper]} '$val' ";
2109
    }
2110
2111
    /**
2112
     * @param $filters
2113
     * @param string $stringToSearch
2114
     * @return array
2115
     */
2116
    public function getExtraFieldRules($filters, $stringToSearch = 'extra_')
2117
    {
2118
        $extra_fields = array();
2119
2120
        // Getting double select if exists
2121
        $double_select = array();
2122
        foreach ($filters->rules as $rule) {
2123
            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...
2124
2125
            } else {
2126
                $my_field = str_replace('_second', '', $rule->field);
2127
                $double_select[$my_field] = $rule->data;
2128
            }
2129
        }
2130
2131
        $condition_array = array();
2132
2133
        foreach ($filters->rules as $rule) {
2134
2135
            if (strpos($rule->field, $stringToSearch) === false) {
2136
                //normal fields
2137
                $field = $rule->field;
2138
2139
                if (isset($rule->data) && $rule->data != -1) {
2140
                    $condition_array[] = $this->get_where_clause($field, $rule->op, $rule->data);
2141
                }
2142
            } else {
2143
                // Extra fields
2144
2145
                if (strpos($rule->field, '_second') === false) {
2146
                    //No _second
2147
                    $original_field = str_replace($stringToSearch, '', $rule->field);
2148
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2149
2150
                    if ($field_option['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
2151
2152
                        if (isset($double_select[$rule->field])) {
2153
                            $data = explode('#', $rule->data);
2154
                            $rule->data = $data[1].'::'.$double_select[$rule->field];
2155
                        } else {
2156
                            // only was sent 1 select
2157
                            $data = explode('#', $rule->data);
2158
                            $rule->data = $data[1];
2159
                        }
2160
2161
                        if (!isset($rule->data)) {
2162
                            $condition_array[] = ' ('.$this->get_where_clause($rule->field, $rule->op, $rule->data).') ';
2163
                            $extra_fields[] = array('field' => $rule->field, 'id' => $field_option['id']);
2164
                        }
2165
                    } else {
2166
                        if (isset($rule->data)) {
2167
                            if ($rule->data == -1) {
2168
                                continue;
2169
                            }
2170
                            $condition_array[] = ' ('.$this->get_where_clause($rule->field, $rule->op, $rule->data).') ';
2171
                            $extra_fields[] = array(
2172
                                'field' => $rule->field,
2173
                                'id' => $field_option['id'],
2174
                                'data' => $rule->data
2175
                            );
2176
                        }
2177
                    }
2178
                } else {
2179
                    $my_field = str_replace('_second', '', $rule->field);
2180
                    $original_field = str_replace($stringToSearch, '', $my_field);
2181
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2182
                    $extra_fields[] = array(
2183
                        'field' => $rule->field,
2184
                        'id' => $field_option['id']
2185
                    );
2186
                }
2187
            }
2188
        }
2189
2190
        return array(
2191
            'extra_fields' => $extra_fields,
2192
            'condition_array' => $condition_array
2193
        );
2194
    }
2195
2196
    /**
2197
     * Get the extra fields and their formatted values
2198
     * @param int|string $itemId The item ID (It could be a session_id, course_id or user_id)
2199
     * @return array The extra fields data
2200
     */
2201
    public function getDataAndFormattedValues($itemId)
2202
    {
2203
        $valuesData = array();
2204
2205
        $fields = $this->get_all();
2206
2207
        foreach ($fields as $field) {
2208
            if ($field['visible'] != '1') {
2209
                continue;
2210
            }
2211
2212
            $fieldValue = new ExtraFieldValue($this->type);
2213
            $valueData = $fieldValue->get_values_by_handler_and_field_id($itemId, $field['id'], true);
2214
2215
            if (!$valueData) {
2216
                continue;
2217
            }
2218
2219
            $displayedValue = get_lang('None');
2220
2221
            switch ($field['field_type']) {
2222
                case ExtraField::FIELD_TYPE_CHECKBOX:
2223
                    if ($valueData !== false && $valueData['value'] == '1') {
2224
                        $displayedValue = get_lang('Yes');
2225
                    } else {
2226
                        $displayedValue = get_lang('No');
2227
                    }
2228
                    break;
2229
                case ExtraField::FIELD_TYPE_DATE:
2230
                    if ($valueData !== false && !empty($valueData['value'])) {
2231
                        $displayedValue = api_format_date($valueData['value'], DATE_FORMAT_LONG_NO_DAY);
2232
                    }
2233
                    break;
2234
                case ExtraField::FIELD_TYPE_FILE_IMAGE:
2235
                    if ($valueData === false || empty($valueData['value'])) {
2236
                        break;
2237
                    }
2238
2239
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH) . $valueData['value'])) {
2240
                        break;
2241
                    }
2242
2243
                    $image = Display::img(
2244
                        api_get_path(WEB_UPLOAD_PATH) . $valueData['value'],
2245
                        $field['display_text'],
2246
                        array('width' => '300')
2247
                    );
2248
2249
                    $displayedValue = Display::url(
2250
                        $image,
2251
                        api_get_path(WEB_UPLOAD_PATH) . $valueData['value'],
2252
                        array('target' => '_blank')
2253
                    );
2254
                    break;
2255
                case ExtraField::FIELD_TYPE_FILE:
2256
                    if ($valueData === false || empty($valueData['value'])) {
2257
                        break;
2258
                    }
2259
2260
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH) . $valueData['value'])) {
2261
                        break;
2262
                    }
2263
2264
                    $displayedValue = Display::url(
2265
                        get_lang('Download'),
2266
                        api_get_path(WEB_UPLOAD_PATH) . $valueData['value'],
2267
                        array(
2268
                            'title' => $field['display_text'],
2269
                            'target' => '_blank'
2270
                        )
2271
                    );
2272
                    break;
2273
                default:
2274
                    $displayedValue = $valueData['value'];
2275
                    break;
2276
            }
2277
2278
            $valuesData[] = array(
2279
                'text' => $field['display_text'],
2280
                'value' => $displayedValue
2281
            );
2282
        }
2283
2284
        return $valuesData;
2285
    }
2286
2287
}
2288