Test Setup Failed
Push — master ( 4e700f...c7183e )
by Julito
63:12
created

ExtraField::getExtraFieldRules()   D

Complexity

Conditions 15
Paths 39

Size

Total Lines 81
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 52
nc 39
nop 2
dl 0
loc 81
rs 4.9974
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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_to_self',
19
        'visible_to_others',
20
        'changeable',
21
        'filter',
22
        'extra_field_type',
23
         /* Enable this when field_loggeable is introduced as a table field (2.0)
24
        'field_loggeable',
25
         */
26
        'created_at'
27
    );
28
29
    public $ops = array(
30
        'eq' => '=', //equal
31
        'ne' => '<>', //not equal
32
        'lt' => '<', //less than
33
        'le' => '<=', //less than or equal
34
        'gt' => '>', //greater than
35
        'ge' => '>=', //greater than or equal
36
        'bw' => 'LIKE', //begins with
37
        'bn' => 'NOT LIKE', //doesn't begin with
38
        'in' => 'LIKE', //is in
39
        'ni' => 'NOT LIKE', //is not in
40
        'ew' => 'LIKE', //ends with
41
        'en' => 'NOT LIKE', //doesn't end with
42
        'cn' => 'LIKE', //contains
43
        'nc' => 'NOT LIKE'  //doesn't contain
44
    );
45
46
    const FIELD_TYPE_TEXT = 1;
47
    const FIELD_TYPE_TEXTAREA = 2;
48
    const FIELD_TYPE_RADIO = 3;
49
    const FIELD_TYPE_SELECT = 4;
50
    const FIELD_TYPE_SELECT_MULTIPLE = 5;
51
    const FIELD_TYPE_DATE = 6;
52
    const FIELD_TYPE_DATETIME = 7;
53
    const FIELD_TYPE_DOUBLE_SELECT = 8;
54
    const FIELD_TYPE_DIVIDER = 9;
55
    const FIELD_TYPE_TAG = 10;
56
    const FIELD_TYPE_TIMEZONE = 11;
57
    const FIELD_TYPE_SOCIAL_PROFILE = 12;
58
    const FIELD_TYPE_CHECKBOX = 13;
59
    const FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
60
    const FIELD_TYPE_INTEGER = 15;
61
    const FIELD_TYPE_FILE_IMAGE = 16;
62
    const FIELD_TYPE_FLOAT = 17;
63
    const FIELD_TYPE_FILE = 18;
64
    const FIELD_TYPE_VIDEO_URL = 19;
65
    const FIELD_TYPE_LETTERS_ONLY = 20;
66
    const FIELD_TYPE_ALPHANUMERIC = 21;
67
    const FIELD_TYPE_LETTERS_SPACE = 22;
68
    const FIELD_TYPE_ALPHANUMERIC_SPACE = 23;
69
    const FIELD_TYPE_GEOLOCALIZATION = 24;
70
    const FIELD_TYPE_GEOLOCALIZATION_COORDINATES = 25;
71
72
    public $type = 'user';
73
    public $pageName;
74
    public $pageUrl;
75
    public $extraFieldType = 0;
76
77
    public $table_field_options;
78
    public $table_field_values;
79
    public $table_field_tag;
80
    public $table_field_rel_tag;
81
82
    public $handler_id;
83
    public $primaryKey;
84
85
    /**
86
     * @param string $type
87
     */
88
    public function __construct($type)
89
    {
90
        parent::__construct();
91
92
        $this->type = $type;
93
        $this->table = Database::get_main_table(TABLE_EXTRA_FIELD);
94
        $this->table_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
95
        $this->table_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
96
        $this->table_field_tag = Database::get_main_table(TABLE_MAIN_TAG);
97
        $this->table_field_rel_tag = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
98
99
        $this->handler_id = 'item_id';
100
101
        switch ($this->type) {
102
            case 'calendar_event':
103
                $this->extraFieldType = EntityExtraField::CALENDAR_FIELD_TYPE;
104
                break;
105
            case 'course':
106
                $this->extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
107
                $this->primaryKey = 'id';
108
                break;
109
            case 'user':
110
                $this->extraFieldType = EntityExtraField::USER_FIELD_TYPE;
111
                $this->primaryKey = 'id';
112
                break;
113
            case 'session':
114
                $this->extraFieldType = EntityExtraField::SESSION_FIELD_TYPE;
115
                $this->primaryKey = 'id';
116
                break;
117
            case 'question':
118
                $this->extraFieldType = EntityExtraField::QUESTION_FIELD_TYPE;
119
                break;
120
            case 'lp':
121
                $this->extraFieldType = EntityExtraField::LP_FIELD_TYPE;
122
                break;
123
            case 'lp_item':
124
                $this->extraFieldType = EntityExtraField::LP_ITEM_FIELD_TYPE;
125
                break;
126
            case 'skill':
127
                $this->extraFieldType = EntityExtraField::SKILL_FIELD_TYPE;
128
                break;
129
            case 'work':
130
                $this->extraFieldType = EntityExtraField::WORK_FIELD_TYPE;
131
                break;
132
            case 'career':
133
                $this->extraFieldType = EntityExtraField::CAREER_FIELD_TYPE;
134
                break;
135
            case 'user_certificate':
136
                $this->extraFieldType = EntityExtraField::USER_CERTIFICATE;
137
                break;
138
            case 'survey':
139
                $this->extraFieldType = EntityExtraField::SURVEY_FIELD_TYPE;
140
                break;
141
        }
142
143
        $this->pageUrl = 'extra_fields.php?type='.$this->type;
144
        // Example QuestionFields
145
        $this->pageName = get_lang(ucwords($this->type).'Fields');
146
    }
147
148
    /**
149
     * @return int
150
     */
151
    public function getExtraFieldType()
152
    {
153
        return (int) $this->extraFieldType;
154
    }
155
156
    /**
157
     * @return array
158
     */
159
    public static function getValidExtraFieldTypes()
160
    {
161
        return array(
162
            'user',
163
            'course',
164
            'session',
165
            'question',
166
            'lp',
167
            'calendar_event',
168
            'lp_item',
169
            'skill',
170
            'work',
171
            'career',
172
            'user_certificate',
173
            'survey'
174
        );
175
    }
176
177
    /**
178
     * @return int
179
     */
180 View Code Duplication
    public function get_count()
181
    {
182
        $em = Database::getManager();
183
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
184
        $query->select('count(e.id)');
185
        $query->where('e.extraFieldType = :type');
186
        $query->setParameter('type', $this->getExtraFieldType());
187
188
        return $query->getQuery()->getSingleScalarResult();
189
    }
190
191
    /**
192
     * @param string $sidx
193
     * @param string $sord
194
     * @param int $start
195
     * @param int $limit
196
     *
197
     * @return array
198
     */
199
    public function getAllGrid($sidx, $sord, $start, $limit)
200
    {
201
        switch ($sidx) {
202
            case 'field_order':
203
                $sidx = 'e.fieldOrder';
204
                break;
205
            case 'variable':
206
                $sidx = 'e.variable';
207
                break;
208
            case 'display_text':
209
                $sidx = 'e.displayText';
210
                break;
211
            case 'changeable':
212
                $sidx = 'e.changeable';
213
                break;
214
            case 'visible_to_self':
215
                $sidx = 'e.visibleToSelf';
216
                break;
217
            case 'visible_to_others':
218
                $sidx = 'e.visibleToOthers';
219
                break;
220
            case 'filter':
221
                $sidx = 'e.filter';
222
                break;
223
            case 'display_text':
224
                $sidx = 'e.fieldType';
225
                break;
226
        }
227
        $em = Database::getManager();
228
        $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
229
        $query->select('e')
230
            ->where('e.extraFieldType = :type')
231
            ->setParameter('type', $this->getExtraFieldType())
232
            ->orderBy($sidx, $sord)
233
            ->setFirstResult($start)
234
            ->setMaxResults($limit);
235
        //echo $query->getQuery()->getSQL();
236
        return $query->getQuery()->getArrayResult();
237
    }
238
239
    /**
240
     * @param array $conditions
241
     * @param null $order_field_options_by
242
     *
243
     * @return array
244
     */
245
    public function get_all($conditions = array(), $order_field_options_by = null)
246
    {
247
        $conditions = Database::parse_conditions(array('where' => $conditions));
248
249
        if (empty($conditions)) {
250
            $conditions .= " WHERE extra_field_type = ".$this->extraFieldType;
251
        } else {
252
            $conditions .= " AND extra_field_type = ".$this->extraFieldType;
253
        }
254
255
        $sql = "SELECT * FROM $this->table
256
                $conditions
257
                ORDER BY field_order ASC
258
        ";
259
260
        $result = Database::query($sql);
261
        $extraFields = Database::store_result($result, 'ASSOC');
262
263
        $option = new ExtraFieldOption($this->type);
264
        if (!empty($extraFields)) {
265
            foreach ($extraFields as &$extraField) {
266
                $extraField['display_text'] = self::translateDisplayName(
267
                    $extraField['variable'],
268
                    $extraField['display_text']
269
                );
270
                $extraField['options'] = $option->get_field_options_by_field(
271
                    $extraField['id'],
272
                    false,
273
                    $order_field_options_by
274
                );
275
            }
276
        }
277
278
        return $extraFields;
279
    }
280
281
    /**
282
     * @param string $variable
283
     *
284
     * @return array|bool
285
     */
286 View Code Duplication
    public function get_handler_field_info_by_field_variable($variable)
287
    {
288
        $variable = Database::escape_string($variable);
289
        $sql = "SELECT * FROM {$this->table}
290
                WHERE
291
                    variable = '$variable' AND
292
                    extra_field_type = $this->extraFieldType";
293
        $result = Database::query($sql);
294
        if (Database::num_rows($result)) {
295
            $row = Database::fetch_array($result, 'ASSOC');
296
            $row['display_text'] = self::translateDisplayName($row['variable'], $row['display_text']);
297
298
            // All the options of the field
299
            $sql = "SELECT * FROM $this->table_field_options
300
                    WHERE field_id='".intval($row['id'])."'
301
                    ORDER BY option_order ASC";
302
            $result = Database::query($sql);
303
            while ($option = Database::fetch_array($result)) {
304
                $row['options'][$option['id']] = $option;
305
            }
306
307
            return $row;
308
        } else {
309
            return false;
310
        }
311
    }
312
313
    /**
314
     * Get all the field info for tags
315
     * @param string $variable
316
     *
317
     * @return array|bool
318
     */
319 View Code Duplication
    public function get_handler_field_info_by_tags($variable)
320
    {
321
        $variable = Database::escape_string($variable);
322
        $sql = "SELECT * FROM {$this->table}
323
                WHERE
324
                    variable = '$variable' AND
325
                    extra_field_type = $this->extraFieldType";
326
        $result = Database::query($sql);
327
        if (Database::num_rows($result)) {
328
            $row = Database::fetch_array($result, 'ASSOC');
329
            $row['display_text'] = self::translateDisplayName(
330
                $row['variable'],
331
                $row['display_text']
332
            );
333
334
            // All the tags of the field
335
            $sql = "SELECT * FROM $this->table_field_tag
336
                    WHERE field_id='".intval($row['id'])."'
337
                    ORDER BY id ASC";
338
            $result = Database::query($sql);
339
            while ($option = Database::fetch_array($result, 'ASSOC')) {
340
                $row['options'][$option['id']] = $option;
341
            }
342
343
            return $row;
344
        } else {
345
            return false;
346
        }
347
    }
348
349
    /**
350
     * @param int $fieldId
351
     *
352
     * @return array|bool
353
     */
354
    public function getFieldInfoByFieldId($fieldId)
355
    {
356
        $fieldId = intval($fieldId);
357
        $sql = "SELECT * FROM {$this->table}
358
                WHERE
359
                    id = '$fieldId' AND
360
                    extra_field_type = $this->extraFieldType";
361
        $result = Database::query($sql);
362
        if (Database::num_rows($result)) {
363
            $row = Database::fetch_array($result, 'ASSOC');
364
365
            // All the options of the field
366
            $sql = "SELECT * FROM $this->table_field_options
367
                    WHERE field_id='".$fieldId."'
368
                    ORDER BY option_order ASC";
369
            $result = Database::query($sql);
370
            while ($option = Database::fetch_array($result)) {
371
                $row['options'][$option['id']] = $option;
372
            }
373
374
            return $row;
375
        } else {
376
            return false;
377
        }
378
    }
379
380
    /**
381
     * @return int
382
     */
383
    public function get_max_field_order()
384
    {
385
        $sql = "SELECT MAX(field_order)
386
                FROM {$this->table}
387
                WHERE
388
                    extra_field_type = '.$this->extraFieldType.'";
389
        $res = Database::query($sql);
390
391
        $order = 0;
392
        if (Database::num_rows($res) > 0) {
393
            $row = Database::fetch_row($res);
394
            $order = $row[0] + 1;
395
        }
396
397
        return $order;
398
    }
399
400
    /**
401
     * @param string $handler
402
     *
403
     * @return array
404
     */
405
    public static function get_extra_fields_by_handler($handler)
406
    {
407
        $types = array();
408
        $types[self::FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
409
        $types[self::FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
410
        $types[self::FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
411
        $types[self::FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
412
        $types[self::FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
413
        $types[self::FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
414
        $types[self::FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
415
        $types[self::FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
416
        $types[self::FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
417
        $types[self::FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
418
        $types[self::FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
419
        $types[self::FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
420
        $types[self::FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
421
        $types[self::FIELD_TYPE_CHECKBOX] = get_lang('FieldTypeCheckbox');
422
        $types[self::FIELD_TYPE_INTEGER] = get_lang('FieldTypeInteger');
423
        $types[self::FIELD_TYPE_FILE_IMAGE] = get_lang('FieldTypeFileImage');
424
        $types[self::FIELD_TYPE_FLOAT] = get_lang('FieldTypeFloat');
425
        $types[self::FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
426
        $types[self::FIELD_TYPE_VIDEO_URL] = get_lang('FieldTypeVideoUrl');
427
        $types[self::FIELD_TYPE_LETTERS_ONLY] = get_lang('FieldTypeOnlyLetters');
428
        $types[self::FIELD_TYPE_ALPHANUMERIC] = get_lang('FieldTypeAlphanumeric');
429
        $types[self::FIELD_TYPE_LETTERS_SPACE] = get_lang(
430
            'FieldTypeLettersSpaces'
431
        );
432
        $types[self::FIELD_TYPE_ALPHANUMERIC_SPACE] = get_lang(
433
            'FieldTypeAlphanumericSpaces'
434
        );
435
        $types[self::FIELD_TYPE_GEOLOCALIZATION] = get_lang(
436
            'Geolocalization'
437
        );
438
        $types[self::FIELD_TYPE_GEOLOCALIZATION_COORDINATES] = get_lang(
439
            'GeolocalizationCoordinates'
440
        );
441
442
        switch ($handler) {
443
            case 'course':
444
                // no break
445
            case 'session':
446
                // no break
447
            case 'user':
448
                // no break
449
            case 'skill':
450
                break;
451
        }
452
453
        return $types;
454
    }
455
456
    /**
457
     * Add elements to a form
458
     *
459
     * @param FormValidator $form
460
     * @param int $itemId
461
     * @param array $exclude variables of extra field to exclude
462
     * @param bool $filter
463
     * @param bool $useTagAsSelect
464
     * @param array $showOnlyTheseFields
465
     * @param array $orderFields
466
     * @param bool $adminPermissions
467
     *
468
     * @return array|bool
469
     */
470
    public function addElements(
471
        $form,
472
        $itemId = 0,
473
        $exclude = [],
474
        $filter = false,
475
        $useTagAsSelect = false,
476
        $showOnlyTheseFields = [],
477
        $orderFields = [],
478
        $adminPermissions = false
479
    ) {
480
        if (empty($form)) {
481
            return false;
482
        }
483
484
        $itemId = (int) $itemId;
485
        $form->addHidden('item_id', $itemId);
486
        $extraData = false;
487
        if (!empty($itemId)) {
488
            $extraData = self::get_handler_extra_data($itemId);
489
490
            if ($form) {
491
                if (!empty($showOnlyTheseFields)) {
492
                    $setData = [];
493
                    foreach ($showOnlyTheseFields as $variable) {
494
                        $extraName = 'extra_'.$variable;
495
                        if (in_array($extraName, array_keys($extraData))) {
496
                            $setData[$extraName] = $extraData[$extraName];
497
                        }
498
                    }
499
                    $form->setDefaults($setData);
500
                } else {
501
                    $form->setDefaults($extraData);
502
                }
503
            }
504
        }
505
506
        $conditions = [];
507
        if ($filter) {
508
            $conditions = ['filter = ?' => 1];
509
        }
510
511
        $extraFields = $this->get_all($conditions, 'option_order');
512
        $extra = $this->set_extra_fields_in_form(
513
            $form,
514
            $extraData,
0 ignored issues
show
Security Bug introduced by
It seems like $extraData defined by false on line 486 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...
515
            $adminPermissions,
516
            $extraFields,
517
            $itemId,
518
            $exclude,
519
            $useTagAsSelect,
520
            $showOnlyTheseFields,
521
            $orderFields
522
        );
523
524
        return $extra;
525
    }
526
527
    /**
528
     * @param int $itemId (session_id, question_id, course id)
529
     *
530
     * @return array
531
     */
532
    public function get_handler_extra_data($itemId)
533
    {
534
        if (empty($itemId)) {
535
            return array();
536
        }
537
538
        $extra_data = array();
539
        $fields = self::get_all();
540
        $field_values = new ExtraFieldValue($this->type);
541
542
        if (!empty($fields) > 0) {
543
            foreach ($fields as $field) {
544
                $field_value = $field_values->get_values_by_handler_and_field_id(
545
                    $itemId,
546
                    $field['id']
547
                );
548
549
                if ($field['field_type'] == self::FIELD_TYPE_TAG) {
550
                    $tags = UserManager::get_user_tags_to_string(
551
                        $itemId,
552
                        $field['id'],
553
                        false
554
                    );
555
                    $extra_data['extra_'.$field['variable']] = $tags;
556
557
                    continue;
558
                }
559
560
                if ($field_value) {
561
                    $field_value = $field_value['value'];
562
                    switch ($field['field_type']) {
563
                        case self::FIELD_TYPE_TAG:
564
                            $tags = UserManager::get_user_tags_to_string(
565
                                $itemId,
566
                                $field['id'],
567
                                false
568
                            );
569
570
                            $extra_data['extra_'.$field['variable']] = $tags;
571
                            break;
572
                        case self::FIELD_TYPE_DOUBLE_SELECT:
573
                            $selected_options = explode(
574
                                '::',
575
                                $field_value
576
                            );
577
                            $firstOption = isset($selected_options[0]) ? $selected_options[0] : '';
578
                            $secondOption = isset($selected_options[1]) ? $selected_options[1] : '';
579
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $firstOption;
580
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable'].'_second'] = $secondOption;
581
582
                            break;
583
                        case self::FIELD_TYPE_SELECT_MULTIPLE:
584
                            $field_value = explode(';', $field_value);
585
                            $extra_data['extra_'.$field['variable']] = $field_value;
586
                            break;
587
                        case self::FIELD_TYPE_RADIO:
588
                            $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $field_value;
589
                            break;
590
                        default:
591
                            $extra_data['extra_'.$field['variable']] = $field_value;
592
                            break;
593
                    }
594
                } else {
595
                    // Set default values
596
                    if (isset($field['field_default_value']) && !empty($field['field_default_value'])) {
597
                        $extra_data['extra_'.$field['variable']] = $field['field_default_value'];
598
                    }
599
                }
600
            }
601
        }
602
603
        return $extra_data;
604
    }
605
606
    /**
607
     * @param string $field_type
608
     *
609
     * @return array
610
     */
611
    public function get_all_extra_field_by_type($field_type)
612
    {
613
        // all the information of the field
614
        $sql = "SELECT * FROM {$this->table}
615
                WHERE
616
                    field_type = '".Database::escape_string($field_type)."' AND
617
                    extra_field_type = $this->extraFieldType
618
                ";
619
        $result = Database::query($sql);
620
621
        $return = array();
622
        while ($row = Database::fetch_array($result)) {
623
            $return[] = $row['id'];
624
        }
625
626
        return $return;
627
    }
628
629
    /**
630
     * @return array
631
     */
632
    public function get_field_types()
633
    {
634
        return self::get_extra_fields_by_handler($this->type);
635
    }
636
637
    /**
638
     * @param int $id
639
     *
640
     * @return null
641
     */
642
    public function get_field_type_by_id($id)
643
    {
644
        $types = self::get_field_types();
645
        if (isset($types[$id])) {
646
            return $types[$id];
647
        }
648
649
        return null;
650
    }
651
652
    /**
653
     * Converts a string like this:
654
     * France:Paris;Bretagne;Marseille;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
655
     * into
656
     * array(
657
     *   'France' =>
658
     *      array('Paris', 'Bretagne', 'Marseille'),
659
     *   'Belgique' =>
660
     *      array('Namur', 'Liège')
661
     * ), etc
662
     * @param string $string
663
     *
664
     * @return array
665
     */
666
    public static function extra_field_double_select_convert_string_to_array($string)
667
    {
668
        $options = explode('|', $string);
669
        $options_parsed = array();
670
        $id = 0;
671
672
        if (!empty($options)) {
673
            foreach ($options as $sub_options) {
674
                $options = explode(':', $sub_options);
675
                $sub_sub_options = explode(';', $options[1]);
676
                $options_parsed[$id] = array(
677
                    'label' => $options[0],
678
                    'options' => $sub_sub_options,
679
                );
680
                $id++;
681
            }
682
        }
683
684
        return $options_parsed;
685
    }
686
687
    /**
688
     * @param array $options
689
     *
690
     * @return array
691
     */
692
    public static function extra_field_double_select_convert_array_to_ordered_array($options)
693
    {
694
        $options_parsed = array();
695
        if (!empty($options)) {
696
            foreach ($options as $option) {
697
                if ($option['option_value'] == 0) {
698
                    $options_parsed[$option['id']][] = $option;
699
                } else {
700
                    $options_parsed[$option['option_value']][] = $option;
701
                }
702
            }
703
        }
704
705
        return $options_parsed;
706
    }
707
708
    /**
709
     * @param array $options the result of the get_field_options_by_field() array
710
     *
711
     * @return string
712
     */
713
    public static function extra_field_double_select_convert_array_to_string($options)
714
    {
715
        $string = null;
716
        $options_parsed = self::extra_field_double_select_convert_array_to_ordered_array($options);
717
718
        if (!empty($options_parsed)) {
719
            foreach ($options_parsed as $option) {
720
                foreach ($option as $key => $item) {
721
                    $string .= $item['display_text'];
722
                    if ($key == 0) {
723
                        $string .= ':';
724
                    } else {
725
                        if (isset($option[$key + 1])) {
726
                            $string .= ';';
727
                        }
728
                    }
729
                }
730
                $string .= '|';
731
            }
732
        }
733
734
        if (!empty($string)) {
735
            $string = substr($string, 0, strlen($string) - 1);
736
        }
737
738
        return $string;
739
    }
740
741
    /**
742
     * @param array $params
743
     *
744
     * @return array
745
     */
746
    public function clean_parameters($params)
747
    {
748
        if (!isset($params['variable']) || empty($params['variable'])) {
749
            $params['variable'] = $params['display_text'];
750
        }
751
752
        $params['variable'] = trim(strtolower(str_replace(" ", "_", $params['variable'])));
753
754
        if (!isset($params['field_order'])) {
755
            $max_order = self::get_max_field_order();
756
            $params['field_order'] = $max_order;
757
        } else {
758
            $params['field_order'] = (int) $params['field_order'];
759
        }
760
761
        return $params;
762
    }
763
764
    /**
765
     * @param array $params
766
     * @param bool $show_query
767
     *
768
     * @return bool
769
     */
770
    public function save($params, $show_query = false)
771
    {
772
        $fieldInfo = self::get_handler_field_info_by_field_variable($params['variable']);
773
        $params = self::clean_parameters($params);
774
        $params['extra_field_type'] = $this->extraFieldType;
775
776
        if ($fieldInfo) {
777
            return $fieldInfo['id'];
778
        } else {
779
            $id = parent::save($params, $show_query);
780
            if ($id) {
781
                $session_field_option = new ExtraFieldOption($this->type);
782
                $params['field_id'] = $id;
783
                $session_field_option->save($params);
784
            }
785
786
            return $id;
787
        }
788
    }
789
790
    /**
791
     * @param array $params
792
     *
793
     * @return bool|void
794
     */
795
    public function update($params)
796
    {
797
        $params = self::clean_parameters($params);
798
        if (isset($params['id'])) {
799
            $field_option = new ExtraFieldOption($this->type);
800
            $params['field_id'] = $params['id'];
801
            $field_option->save($params);
802
        }
803
804
        parent::update($params);
805
    }
806
807
    /**
808
     * @param $id
809
     *
810
     * @return bool|void
811
     */
812
    public function delete($id)
813
    {
814
        $em = Database::getManager();
815
        $items = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findBy(['field' => $id]);
816
        if ($items) {
817
            foreach ($items as $item) {
818
                $em->remove($item);
819
            }
820
            $em->flush();
821
        }
822
        $field_option = new ExtraFieldOption($this->type);
823
        $field_option->delete_all_options_by_field_id($id);
824
825
        $session_field_values = new ExtraFieldValue($this->type);
826
        $session_field_values->delete_all_values_by_field_id($id);
827
828
        parent::delete($id);
829
    }
830
831
    /**
832
     * Add an element that matches the given extra field to the given $form object
833
     * @param FormValidator $form
834
     * @param array $extraData
835
     * @param bool $adminPermissions
836
     * @param array $extra
837
     * @param int $itemId
838
     * @param array $exclude variables of extra field to exclude
839
     * @param bool $useTagAsSelect
840
     * @param array $showOnlyTheseFields
841
     * @param array $orderFields
842
     *
843
     * @return array If relevant, returns a one-element array with JS code to be added to the page HTML headers
844
     */
845
    public function set_extra_fields_in_form(
846
        $form,
847
        $extraData,
848
        $adminPermissions = false,
849
        $extra = array(),
850
        $itemId = null,
851
        $exclude = [],
852
        $useTagAsSelect = false,
853
        $showOnlyTheseFields = [],
854
        $orderFields = []
855
    ) {
856
        $type = $this->type;
857
        $jquery_ready_content = null;
858
        if (!empty($extra)) {
859
            $newOrder = [];
860
            if (!empty($orderFields)) {
861
                foreach ($orderFields as $order) {
862
                    foreach ($extra as $field_details) {
863
                        if ($order == $field_details['variable']) {
864
                            $newOrder[] = $field_details;
865
                        }
866
                    }
867
                }
868
                $extra = $newOrder;
869
            }
870
871
            foreach ($extra as $field_details) {
872
                if (!empty($showOnlyTheseFields)) {
873
                    if (!in_array($field_details['variable'], $showOnlyTheseFields)) {
874
                        continue;
875
                    }
876
                }
877
878
                // Getting default value id if is set
879
                $defaultValueId = null;
880
                if (isset($field_details['options']) && !empty($field_details['options'])) {
881
                    $valueToFind = null;
882
                    if (isset($field_details['field_default_value'])) {
883
                        $valueToFind = $field_details['field_default_value'];
884
                    }
885
                    // If a value is found we override the default value
886
                    if (isset($extraData['extra_'.$field_details['variable']])) {
887
                        $valueToFind = $extraData['extra_'.$field_details['variable']];
888
                    }
889
890
                    foreach ($field_details['options'] as $option) {
891
                        if ($option['option_value'] == $valueToFind) {
892
                            $defaultValueId = $option['id'];
893
                        }
894
                    }
895
                }
896
897
                if (!$adminPermissions) {
898
                    if ($field_details['visible_to_self'] == 0) {
899
                        continue;
900
                    }
901
902
                    if (in_array($field_details['variable'], $exclude)) {
903
                        continue;
904
                    }
905
                }
906
907
                $freezeElement = false;
908
                if (!$adminPermissions) {
909
                    $freezeElement = $field_details['visible_to_self'] == 0 || $field_details['changeable'] == 0;
910
                }
911
912
                switch ($field_details['field_type']) {
913
                    case self::FIELD_TYPE_TEXT:
914
                        $form->addElement(
915
                            'text',
916
                            'extra_'.$field_details['variable'],
917
                            $field_details['display_text'],
918
                            array(
919
                                'id' => 'extra_'.$field_details['variable']
920
                            )
921
                        );
922
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
923
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
924
                        if ($freezeElement) {
925
                            $form->freeze('extra_'.$field_details['variable']);
926
                        }
927
                        break;
928
                    case self::FIELD_TYPE_TEXTAREA:
929
                        $form->addHtmlEditor(
930
                            'extra_'.$field_details['variable'],
931
                            $field_details['display_text'],
932
                            false,
933
                            false,
934
                            array(
935
                                'ToolbarSet' => 'Profile',
936
                                'Width' => '100%',
937
                                'Height' => '130',
938
                                'id' => 'extra_'.$field_details['variable']
939
                            )
940
                        );
941
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
942
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
943
                        if ($freezeElement) {
944
                            $form->freeze('extra_'.$field_details['variable']);
945
                        }
946
                        break;
947
                    case self::FIELD_TYPE_RADIO:
948
                        $group = array();
949
                        if (isset($field_details['options']) && !empty($field_details['options'])) {
950
                            foreach ($field_details['options'] as $option_details) {
951
                                $options[$option_details['option_value']] = $option_details['display_text'];
952
                                $group[] = $form->createElement(
953
                                    'radio',
954
                                    'extra_'.$field_details['variable'],
955
                                    $option_details['option_value'],
956
                                    $option_details['display_text'].'<br />',
957
                                    $option_details['option_value']
958
                                );
959
                            }
960
                        }
961
                        $form->addGroup(
962
                            $group,
963
                            'extra_'.$field_details['variable'],
964
                            $field_details['display_text']
965
                        );
966
                        if ($freezeElement) {
967
                            $form->freeze('extra_'.$field_details['variable']);
968
                        }
969
                        break;
970
                    case self::FIELD_TYPE_CHECKBOX:
971
                        $group = array();
972
                        if (isset($field_details['options']) && !empty($field_details['options'])) {
973
                            foreach ($field_details['options'] as $option_details) {
974
                                $options[$option_details['option_value']] = $option_details['display_text'];
975
                                $group[] = $form->createElement(
976
                                    'checkbox',
977
                                    'extra_'.$field_details['variable'],
978
                                    $option_details['option_value'],
979
                                    $option_details['display_text'].'<br />',
980
                                    $option_details['option_value']
981
                                );
982
                            }
983
                        } else {
984
                            $fieldVariable = "extra_{$field_details['variable']}";
985
                            $checkboxAttributes = array();
986
                            if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
987
                                if (!empty($extraData[$fieldVariable])) {
988
                                    $checkboxAttributes['checked'] = 1;
989
                                }
990
                            }
991
992
                            // We assume that is a switch on/off with 1 and 0 as values
993
                            $group[] = $form->createElement(
994
                                'checkbox',
995
                                'extra_'.$field_details['variable'],
996
                                null,
997
                                //$field_details['display_text'].'<br />',
998
                                get_lang('Yes'),
999
                                $checkboxAttributes
1000
                            );
1001
                        }
1002
1003
                        $form->addGroup(
1004
                            $group,
1005
                            'extra_'.$field_details['variable'],
1006
                            $field_details['display_text']
1007
                        );
1008
                        if ($freezeElement) {
1009
                            $form->freeze('extra_'.$field_details['variable']);
1010
                        }
1011
                        break;
1012
                    case self::FIELD_TYPE_SELECT:
1013
                        $get_lang_variables = false;
1014
                        if (in_array(
1015
                            $field_details['variable'],
1016
                            array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message')
1017
                        )
1018
                        ) {
1019
                            $get_lang_variables = true;
1020
                        }
1021
1022
                        // Get extra field workflow
1023
                        $userInfo = api_get_user_info();
1024
                        $addOptions = array();
1025
                        $optionsExists = false;
1026
                        global $app;
1027
                        // Check if exist $app['orm.em'] object
1028
                        if (isset($app['orm.em']) && is_object($app['orm.em'])) {
1029
                            $optionsExists = $app['orm.em']
1030
                                ->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
1031
                                ->findOneBy(array('fieldId' => $field_details['id']));
1032
                        }
1033
1034
                        if ($optionsExists) {
1035
                            if (isset($userInfo['status']) && !empty($userInfo['status'])) {
1036
                                $fieldWorkFlow = $app['orm.em']
1037
                                    ->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
1038
                                    ->findBy(
1039
                                        array(
1040
                                            'fieldId' => $field_details['id'],
1041
                                            'relatedFieldOptionId' => $defaultValueId,
1042
                                            'roleId' => $userInfo['status']
1043
                                        )
1044
                                    );
1045
                                foreach ($fieldWorkFlow as $item) {
1046
                                    $addOptions[] = $item->getFieldOptionId();
1047
                                }
1048
                            }
1049
                        }
1050
1051
                        $options = array();
1052
                        if (empty($defaultValueId)) {
1053
                            $options[''] = get_lang('SelectAnOption');
1054
                        }
1055
1056
                        $optionList = array();
1057
                        if (!empty($field_details['options'])) {
1058
                            foreach ($field_details['options'] as $option_details) {
1059
                                $optionList[$option_details['id']] = $option_details;
1060
                                if ($get_lang_variables) {
1061
                                    $options[$option_details['option_value']] = $option_details['display_text'];
1062
                                } else {
1063
                                    if ($optionsExists) {
1064
                                        // Adding always the default value
1065 View Code Duplication
                                        if ($option_details['id'] == $defaultValueId) {
1066
                                            $options[$option_details['option_value']] = $option_details['display_text'];
1067
                                        } else {
1068
                                            if (isset($addOptions) && !empty($addOptions)) {
1069
                                                // Parsing filters
1070
                                                if (in_array($option_details['id'], $addOptions)) {
1071
                                                    $options[$option_details['option_value']] = $option_details['display_text'];
1072
                                                }
1073
                                            }
1074
                                        }
1075
                                    } else {
1076
                                        // Normal behaviour
1077
                                        $options[$option_details['option_value']] = $option_details['display_text'];
1078
                                    }
1079
                                }
1080
                            }
1081
1082
                            if (isset($optionList[$defaultValueId])) {
1083
                                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...
1084
                                    $optionList[$defaultValueId]['option_value'] == 'aprobada'
1085
                                ) {
1086
                                    // @todo function don't exists api_is_question_manager
1087
                                    /*if (api_is_question_manager() == false) {
1088
                                        $form->freeze();
1089
                                    }*/
1090
                                }
1091
                            }
1092
1093
                            // Setting priority message
1094
                            if (isset($optionList[$defaultValueId]) &&
1095
                                isset($optionList[$defaultValueId]['priority'])
1096
                            ) {
1097
                                if (!empty($optionList[$defaultValueId]['priority'])) {
1098
                                    $priorityId = $optionList[$defaultValueId]['priority'];
1099
                                    $option = new ExtraFieldOption($this->type);
1100
                                    $messageType = $option->getPriorityMessageType($priorityId);
1101
                                    $form->addElement(
1102
                                        'label',
1103
                                        null,
1104
                                        Display::return_message(
1105
                                            $optionList[$defaultValueId]['priority_message'],
1106
                                            $messageType
1107
                                        )
1108
                                    );
1109
                                }
1110
                            }
1111
                        }
1112
1113
                        // chzn-select doesn't work for sessions??
1114
                        $form->addElement(
1115
                            'select',
1116
                            'extra_'.$field_details['variable'],
1117
                            $field_details['display_text'],
1118
                            $options,
1119
                            array('id' => 'extra_'.$field_details['variable'])
1120
                        );
1121
1122
                        /* Enable this when field_loggeable is introduced as a table field (2.0)
1123
                        if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) {
1124
1125
                            $form->addElement(
1126
                                'textarea',
1127
                                'extra_' . $field_details['variable'] . '_comment',
1128
                                $field_details['display_text'] . ' ' . get_lang('Comment')
1129
                            );
1130
1131
                            $extraFieldValue = new ExtraFieldValue($this->type);
1132
                            $repo = $app['orm.em']->getRepository($extraFieldValue->entityName);
1133
                            $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry');
1134
                            $newEntity = $repo->findOneBy(
1135
                                array(
1136
                                    $this->handlerEntityId => $itemId,
1137
                                    'fieldId' => $field_details['id']
1138
                                )
1139
                            );
1140
                            // @todo move this in a function inside the class
1141
                            if ($newEntity) {
1142
                                $logs = $repoLog->getLogEntries($newEntity);
1143
                                if (!empty($logs)) {
1144
                                    $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />';
1145
1146
                                    $table = new HTML_Table(array('class' => 'data_table'));
1147
                                    $table->setHeaderContents(0, 0, get_lang('Value'));
1148
                                    $table->setHeaderContents(0, 1, get_lang('Comment'));
1149
                                    $table->setHeaderContents(0, 2, get_lang('ModifyDate'));
1150
                                    $table->setHeaderContents(0, 3, get_lang('Username'));
1151
                                    $row = 1;
1152
                                    foreach ($logs as $log) {
1153
                                        $column = 0;
1154
                                        $data = $log->getData();
1155
                                        $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null;
1156
                                        $comment = isset($data['comment']) ? $data['comment'] : null;
1157
1158
                                        $table->setCellContents($row, $column, $fieldValue);
1159
                                        $column++;
1160
                                        $table->setCellContents($row, $column, $comment);
1161
                                        $column++;
1162
                                        $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s')));
1163
                                        $column++;
1164
                                        $table->setCellContents($row, $column, $log->getUsername());
1165
                                        $row++;
1166
                                    }
1167
                                    $form->addElement('label', null, $html.$table->toHtml());
1168
                                }
1169
                            }
1170
                        }
1171
                        */
1172
1173
                        if ($freezeElement) {
1174
                            $form->freeze('extra_'.$field_details['variable']);
1175
                        }
1176
                        break;
1177
                    case self::FIELD_TYPE_SELECT_MULTIPLE:
1178
                        $options = array();
1179
                        foreach ($field_details['options'] as $option_id => $option_details) {
1180
                            $options[$option_details['option_value']] = $option_details['display_text'];
1181
                        }
1182
                        $form->addElement(
1183
                            'select',
1184
                            'extra_'.$field_details['variable'],
1185
                            $field_details['display_text'],
1186
                            $options,
1187
                            array('multiple' => 'multiple', 'id' => 'extra_'.$field_details['variable'])
1188
                        );
1189
                        if ($freezeElement) {
1190
                            $form->freeze('extra_'.$field_details['variable']);
1191
                        }
1192
                        break;
1193
                    case self::FIELD_TYPE_DATE:
1194
                        $form->addDatePicker('extra_'.$field_details['variable'], $field_details['display_text']);
1195
                        if ($freezeElement) {
1196
                            $form->freeze('extra_'.$field_details['variable']);
1197
                        }
1198
                        break;
1199
                    case self::FIELD_TYPE_DATETIME:
1200
                        $form->addDateTimePicker(
1201
                            'extra_'.$field_details['variable'],
1202
                            $field_details['display_text']
1203
                        );
1204
1205
                        $defaults['extra_'.$field_details['variable']] = api_get_local_time();
1206
                        if (!isset($form->_defaultValues['extra_'.$field_details['variable']])) {
1207
                            $form->setDefaults($defaults);
1208
                        }
1209
                        if ($freezeElement) {
1210
                            $form->freeze('extra_'.$field_details['variable']);
1211
                        }
1212
                        break;
1213
                    case self::FIELD_TYPE_DOUBLE_SELECT:
1214
                        $first_select_id = 'first_extra_'.$field_details['variable'];
1215
                        $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
1216
1217
                        $jquery_ready_content .= '
1218
                        $("#'.$first_select_id.'").on("change", function() {
1219
                            var id = $(this).val();
1220
                            if (id) {
1221
                                $.ajax({
1222
                                    url: "'.$url.'&a=get_second_select_options",
1223
                                    dataType: "json",
1224
                                    data: "type='.$type.'&field_id='.$field_details['id'].'&option_value_id="+id,
1225
                                    success: function(data) {
1226
                                        $("#second_extra_'.$field_details['variable'].'").empty();
1227
                                        $.each(data, function(index, value) {
1228
                                            $("#second_extra_'.$field_details['variable'].'").append($("<option/>", {
1229
                                                value: index,
1230
                                                text: value
1231
                                            }));
1232
                                        });
1233
                                        $("#second_extra_'.$field_details['variable'].'").selectpicker("refresh");
1234
                                    },
1235
                                });
1236
                            } else {
1237
                                $("#second_extra_'.$field_details['variable'].'").empty();
1238
                            }
1239
                        });';
1240
1241
                        $first_id = null;
1242
                        if (!empty($extraData)) {
1243
                            if (isset($extraData['extra_'.$field_details['variable']])) {
1244
                                $first_id = $extraData['extra_'.$field_details['variable']]['extra_'.$field_details['variable']];
1245
                            }
1246
                        }
1247
1248
                        $options = self::extra_field_double_select_convert_array_to_ordered_array(
1249
                            $field_details['options']
1250
                        );
1251
                        $values = array('' => get_lang('Select'));
1252
1253
                        $second_values = array();
1254
                        if (!empty($options)) {
1255
                            foreach ($options as $option) {
1256
                                foreach ($option as $sub_option) {
1257
                                    if ($sub_option['option_value'] == '0') {
1258
                                        $values[$sub_option['id']] = $sub_option['display_text'];
1259
                                    } else {
1260
                                        if ($first_id === $sub_option['option_value']) {
1261
                                            $second_values[$sub_option['id']] = $sub_option['display_text'];
1262
                                        }
1263
                                    }
1264
                                }
1265
                            }
1266
                        }
1267
                        $group = array();
1268
                        $group[] = $form->createElement(
1269
                            'select',
1270
                            'extra_'.$field_details['variable'],
1271
                            null,
1272
                            $values,
1273
                            array('id' => $first_select_id)
1274
                        );
1275
                        $group[] = $form->createElement(
1276
                            'select',
1277
                            'extra_'.$field_details['variable'].'_second',
1278
                            null,
1279
                            $second_values,
1280
                            array('id' => 'second_extra_'.$field_details['variable'])
1281
                        );
1282
                        $form->addGroup(
1283
                            $group,
1284
                            'extra_'.$field_details['variable'],
1285
                            $field_details['display_text']
1286
                        );
1287
1288
                        if ($freezeElement) {
1289
                            $form->freeze('extra_'.$field_details['variable']);
1290
                        }
1291
                        break;
1292
                    case self::FIELD_TYPE_DIVIDER:
1293
                        $form->addHtml('
1294
                            <div class="form-group ">
1295
                                <div class="col-sm-12">
1296
                                    <div class="panel-separator">
1297
                                       <h4 id="' . $field_details['variable'].'" class="form-separator">'.$field_details['display_text'].'</h4>
1298
                                    </div>
1299
                                </div>
1300
                            </div>    
1301
                        ');
1302
                        break;
1303
                    case self::FIELD_TYPE_TAG:
1304
                        $variable = $field_details['variable'];
1305
                        $field_id = $field_details['id'];
1306
1307
                        $tagsSelect = $form->addSelect(
1308
                            "extra_{$field_details['variable']}",
1309
                            $field_details['display_text'],
1310
                            [],
1311
                            ['style' => 'width: 100%;']
1312
                        );
1313
1314
                        if ($useTagAsSelect == false) {
1315
                            $tagsSelect->setAttribute('class', null);
1316
                        }
1317
1318
                        $tagsSelect->setAttribute('id', "extra_{$field_details['variable']}");
1319
                        $tagsSelect->setMultiple(true);
1320
1321
                        $selectedOptions = [];
1322
                        if ($this->type === 'user') {
1323
                            // The magic should be here
1324
                            $user_tags = UserManager::get_user_tags($itemId, $field_details['id']);
1325
1326
                            if (is_array($user_tags) && count($user_tags) > 0) {
1327
                                foreach ($user_tags as $tag) {
1328
                                    $tagsSelect->addOption(
1329
                                        $tag['tag'],
1330
                                        $tag['tag']
1331
                                    );
1332
                                    $selectedOptions[] = $tag['tag'];
1333
                                }
1334
                            }
1335
                            $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
1336
                        } else {
1337
                            $em = Database::getManager();
1338
1339
                            $fieldTags = $em
1340
                                ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
1341
                                ->findBy([
1342
                                    'fieldId' => $field_id,
1343
                                    'itemId' => $itemId
1344
                                ]);
1345
                            /** @var \Chamilo\CoreBundle\Entity\ExtraFieldRelTag $fieldTag */
1346
                            foreach ($fieldTags as $fieldTag) {
1347
                                /** @var \Chamilo\CoreBundle\Entity\Tag $tag */
1348
                                $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1349
1350
                                if (empty($tag)) {
1351
                                    continue;
1352
                                }
1353
                                $tagsSelect->addOption(
1354
                                    $tag->getTag(),
1355
                                    $tag->getTag()
1356
                                );
1357
                                $selectedOptions[] = $tag->getTag();
1358
                            }
1359
1360
                            if ($useTagAsSelect) {
1361
                                $fieldTags = $em
1362
                                    ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
1363
                                    ->findBy([
1364
                                        'fieldId' => $field_id
1365
                                    ]);
1366
                                $tagsAdded = [];
1367
                                foreach ($fieldTags as $fieldTag) {
1368
                                    $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
1369
1370
                                    if (empty($tag)) {
1371
                                        continue;
1372
                                    }
1373
1374
                                    $tagText = $tag->getTag();
1375
1376
                                    if (in_array($tagText, $tagsAdded)) {
1377
                                        continue;
1378
                                    }
1379
1380
                                    $tagsSelect->addOption(
1381
                                        $tag->getTag(),
1382
                                        $tag->getTag(),
1383
                                        []
1384
                                    );
1385
1386
                                    $tagsAdded[] = $tagText;
1387
                                }
1388
1389
                            }
1390
1391
                            $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php';
1392
                        }
1393
1394
                        $form->setDefaults([
1395
                            'extra_'.$field_details['variable'] => $selectedOptions
1396
                        ]);
1397
1398
                        if ($useTagAsSelect == false) {
1399
                            $jquery_ready_content .= "
1400
                                $('#extra_$variable').select2({
1401
                                    ajax: {
1402
                                        url: '$url?a=search_tags&field_id=$field_id&type={$this->type}',
1403
                                        processResults: function (data) {
1404
                                            return {
1405
                                                results: data.items
1406
                                            }
1407
                                        }
1408
                                    },
1409
                                    cache: false,
1410
                                    tags: true,
1411
                                    tokenSeparators: [','],
1412
                                    placeholder: '".get_lang('StartToType')."'
1413
                                });
1414
                            ";
1415
                        }
1416
                        break;
1417 View Code Duplication
                    case self::FIELD_TYPE_TIMEZONE:
1418
                        $form->addElement(
1419
                            'select',
1420
                            'extra_'.$field_details['variable'],
1421
                            $field_details['display_text'],
1422
                            api_get_timezones(),
1423
                            ''
1424
                        );
1425
                        if ($freezeElement) {
1426
                            $form->freeze('extra_'.$field_details['variable']);
1427
                        }
1428
                        break;
1429
                    case self::FIELD_TYPE_SOCIAL_PROFILE:
1430
                        // get the social network's favicon
1431
                        $extra_data_variable = isset($extraData['extra_'.$field_details['variable']]) ? $extraData['extra_'.$field_details['variable']] : null;
1432
                        $field_default_value = isset($field_details['field_default_value']) ? $field_details['field_default_value'] : null;
1433
                        $icon_path = UserManager::get_favicon_from_url(
1434
                            $extra_data_variable,
1435
                            $field_default_value
1436
                        );
1437
                        // special hack for hi5
1438
                        $leftpad = '1.7';
1439
                        $top = '0.4';
1440
                        $domain = parse_url($icon_path, PHP_URL_HOST);
1441
                        if ($domain == 'www.hi5.com' or $domain == 'hi5.com') {
1442
                            $leftpad = '3';
1443
                            $top = '0';
1444
                        }
1445
                        // print the input field
1446
                        $form->addElement(
1447
                            'text',
1448
                            'extra_'.$field_details['variable'],
1449
                            $field_details['display_text'],
1450
                            array(
1451
                                'size' => 60,
1452
                                'size' => implode(
1453
                                    '; ',
1454
                                    [
1455
                                        "background-image: url('$icon_path')",
1456
                                        'background-repeat: no-repeat',
1457
                                        "background-position: 0.4em {$top}em",
1458
                                        "padding-left: {$leftpad}em"
1459
                                    ]
1460
                                )
1461
                            )
1462
                        );
1463
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1464
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1465
                        if ($freezeElement) {
1466
                            $form->freeze('extra_'.$field_details['variable']);
1467
                        }
1468
                        break;
1469
                    case self::FIELD_TYPE_MOBILE_PHONE_NUMBER:
1470
                        $form->addElement(
1471
                            'text',
1472
                            'extra_'.$field_details[1],
1473
                            $field_details[3]." (".get_lang('CountryDialCode').")",
1474
                            array('size' => 40, 'placeholder' => '(xx)xxxxxxxxx')
1475
                        );
1476
                        $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
1477
                        $form->applyFilter('extra_'.$field_details[1], 'trim');
1478
                        $form->applyFilter('extra_'.$field_details[1], 'mobile_phone_number_filter');
1479
                        $form->addRule(
1480
                            'extra_'.$field_details[1],
1481
                            get_lang('MobilePhoneNumberWrong'),
1482
                            'mobile_phone_number'
1483
                        );
1484
                        if ($freezeElement) {
1485
                            $form->freeze('extra_'.$field_details['variable']);
1486
                        }
1487
                        break;
1488 View Code Duplication
                    case self::FIELD_TYPE_INTEGER:
1489
                        $form->addElement(
1490
                            'number',
1491
                            'extra_'.$field_details['variable'],
1492
                            $field_details['display_text'],
1493
                            array('class' => 'span1', 'step' => 1)
1494
                        );
1495
1496
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1497
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1498
                        $form->applyFilter('extra_'.$field_details['variable'], 'intval');
1499
1500
                        if ($freezeElement) {
1501
                            $form->freeze('extra_'.$field_details['variable']);
1502
                        }
1503
                        break;
1504
                    case self::FIELD_TYPE_FILE_IMAGE:
1505
                        $fieldVariable = "extra_{$field_details['variable']}";
1506
                        $fieldTexts = [
1507
                            $field_details['display_text']
1508
                        ];
1509
1510 View Code Duplication
                        if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
1511
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH).$extraData[$fieldVariable])) {
1512
                                $fieldTexts[] = Display::img(
1513
                                    api_get_path(WEB_UPLOAD_PATH).$extraData[$fieldVariable],
1514
                                    $field_details['display_text'],
1515
                                    ['width' => '300']
1516
                                );
1517
                            }
1518
                        }
1519
1520
                        if ($fieldTexts[0] === 'Image') {
1521
                            $fieldTexts[0] = get_lang($fieldTexts[0]);
1522
                        }
1523
1524
                        $form->addFile(
1525
                            $fieldVariable,
1526
                            $fieldTexts,
1527
                            ['accept' => 'image/*', 'id' => 'extra_image', 'crop_image' => 'true']
1528
                        );
1529
1530
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1531
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1532
1533
                        $allowed_picture_types = ['jpg', 'jpeg', 'png', 'gif'];
1534
                        $form->addRule(
1535
                            'extra_'.$field_details['variable'],
1536
                            get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
1537
                            'filetype',
1538
                            $allowed_picture_types
1539
                        );
1540
1541
                        if ($freezeElement) {
1542
                            $form->freeze('extra_'.$field_details['variable']);
1543
                        }
1544
                        break;
1545 View Code Duplication
                    case self::FIELD_TYPE_FLOAT:
1546
                        $form->addElement(
1547
                            'number',
1548
                            'extra_'.$field_details['variable'],
1549
                            $field_details['display_text'],
1550
                            array('class' => 'span1', 'step' => '0.01')
1551
                        );
1552
1553
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1554
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1555
                        $form->applyFilter('extra_'.$field_details['variable'], 'floatval');
1556
1557
                        if ($freezeElement) {
1558
                            $form->freeze('extra_'.$field_details['variable']);
1559
                        }
1560
                        break;
1561
                    case self::FIELD_TYPE_FILE:
1562
                        $fieldVariable = "extra_{$field_details['variable']}";
1563
                        $fieldTexts = array(
1564
                            $field_details['display_text']
1565
                        );
1566
1567
                        if (is_array($extraData) &&
1568
                            array_key_exists($fieldVariable, $extraData)
1569
                        ) {
1570 View Code Duplication
                            if (file_exists(api_get_path(SYS_UPLOAD_PATH).$extraData[$fieldVariable])) {
1571
                                $fieldTexts[] = Display::url(
1572
                                    api_get_path(WEB_UPLOAD_PATH).$extraData[$fieldVariable],
1573
                                    api_get_path(WEB_UPLOAD_PATH).$extraData[$fieldVariable],
1574
                                    array(
1575
                                        'title' => $field_details['display_text'],
1576
                                        'target' => '_blank'
1577
                                    )
1578
                                );
1579
                            }
1580
                        }
1581
1582
                        $form->addElement(
1583
                            'file',
1584
                            $fieldVariable,
1585
                            $fieldTexts,
1586
                            array()
1587
                        );
1588
1589
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1590
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1591
1592
                        if ($freezeElement) {
1593
                            $form->freeze('extra_'.$field_details['variable']);
1594
                        }
1595
                        break;
1596
                    case self::FIELD_TYPE_VIDEO_URL:
1597
                        $form->addUrl(
1598
                            "extra_{$field_details['variable']}",
1599
                            $field_details['display_text'],
1600
                            false,
1601
                            ['placeholder' => 'https://']
1602
                        );
1603
                        if ($freezeElement) {
1604
                            $form->freeze('extra_'.$field_details['variable']);
1605
                        }
1606
                        break;
1607 View Code Duplication
                    case self::FIELD_TYPE_LETTERS_ONLY:
1608
                        $form->addTextLettersOnly(
1609
                            "extra_{$field_details['variable']}",
1610
                            $field_details['display_text']
1611
                        );
1612
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1613
1614
                        if ($freezeElement) {
1615
                            $form->freeze('extra_'.$field_details['variable']);
1616
                        }
1617
                        break;
1618 View Code Duplication
                    case self::FIELD_TYPE_ALPHANUMERIC:
1619
                        $form->addTextAlphanumeric(
1620
                            "extra_{$field_details['variable']}",
1621
                            $field_details['display_text']
1622
                        );
1623
                        $form->applyFilter(
1624
                            'extra_'.$field_details['variable'],
1625
                            'stripslashes'
1626
                        );
1627
                        if ($freezeElement) {
1628
                            $form->freeze('extra_'.$field_details['variable']);
1629
                        }
1630
                        break;
1631 View Code Duplication
                    case self::FIELD_TYPE_LETTERS_SPACE:
1632
                        $form->addTextLettersAndSpaces(
1633
                            "extra_{$field_details['variable']}",
1634
                            $field_details['display_text']
1635
                        );
1636
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1637
1638
                        if ($freezeElement) {
1639
                            $form->freeze('extra_'.$field_details['variable']);
1640
                        }
1641
                        break;
1642 View Code Duplication
                    case self::FIELD_TYPE_ALPHANUMERIC_SPACE:
1643
                        $form->addTextAlphanumericAndSpaces(
1644
                            "extra_{$field_details['variable']}",
1645
                            $field_details['display_text']
1646
                        );
1647
                        $form->applyFilter(
1648
                            'extra_'.$field_details['variable'],
1649
                            'stripslashes'
1650
                        );
1651
                        if ($freezeElement) {
1652
                            $form->freeze('extra_'.$field_details['variable']);
1653
                        }
1654
                        break;
1655
                    case self::FIELD_TYPE_GEOLOCALIZATION:
1656
                        $dataValue = isset($extraData['extra_'.$field_details['variable']])
1657
                            ? $extraData['extra_'.$field_details['variable']]
1658
                            : '';
1659
                        $form->addElement(
1660
                            'text',
1661
                            'extra_'.$field_details['variable'],
1662
                            $field_details['display_text'],
1663
                            ['id' => 'extra_'.$field_details['variable']]
1664
                        );
1665
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1666
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1667
                        if ($freezeElement) {
1668
                            $form->freeze('extra_'.$field_details['variable']);
1669
                        }
1670
1671
                        $form->addHtml("
1672
                            <script>
1673
                                $(document).ready(function() {
1674
                                    if (typeof google === 'object') {
1675
                                        var address = '$dataValue';
1676
                                        initializeGeo{$field_details['variable']}(address, false);
1677
    
1678
                                        $('#geolocalization_extra_{$field_details['variable']}').on('click', function() {
1679
                                            var address = $('#extra_{$field_details['variable']}').val();
1680
                                            initializeGeo{$field_details['variable']}(address, false);
1681
                                            return false;
1682
                                        });
1683
    
1684
                                        $('#myLocation_extra_{$field_details['variable']}').on('click', function() {
1685
                                            myLocation{$field_details['variable']}();
1686
                                            return false;
1687
                                        });
1688
    
1689
                                        $('#extra_{$field_details['variable']}').keypress(function(event) {
1690
                                            if (event.which == 13) {
1691
                                                $('#geolocalization_extra_{$field_details['variable']}').click();
1692
                                                return false;
1693
                                            }
1694
                                        });
1695
                                        
1696
                                        return;
1697
                                    }
1698
1699
                                    $('#map_extra_{$field_details['variable']}')
1700
                                        .html('<div class=\"alert alert-info\">"
1701
                                            .get_lang('YouNeedToActivateTheGoogleMapsPluginInAdminPlatformToSeeTheMap')
1702
                                            ."</div>');
1703
                                });
1704
1705
                                function myLocation{$field_details['variable']}() {
1706
                                    if (navigator.geolocation) {
1707
                                        var geoPosition = function(position) {
1708
                                            var lat = position.coords.latitude;
1709
                                            var lng = position.coords.longitude;
1710
                                            var latLng = new google.maps.LatLng(lat, lng);
1711
                                            initializeGeo{$field_details['variable']}(false, latLng)
1712
                                        };
1713
1714
                                        var geoError = function(error) {
1715
                                            console.log(error);
1716
                                            alert('Geocode ".get_lang('Error').": ' + error);
1717
                                        };
1718
1719
                                        var geoOptions = {
1720
                                            enableHighAccuracy: true
1721
                                        };
1722
1723
                                        navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
1724
                                    }
1725
                                }
1726
1727
                                function initializeGeo{$field_details['variable']}(address, latLng) {
1728
                                    var geocoder = new google.maps.Geocoder();
1729
                                    var latlng = new google.maps.LatLng(-34.397, 150.644);
1730
                                    var myOptions = {
1731
                                        zoom: 15,
1732
                                        center: latlng,
1733
                                        mapTypeControl: true,
1734
                                        mapTypeControlOptions: {
1735
                                            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
1736
                                        },
1737
                                        navigationControl: true,
1738
                                        mapTypeId: google.maps.MapTypeId.ROADMAP
1739
                                    };
1740
1741
                                    map_{$field_details['variable']} = new google.maps.Map(
1742
                                        document.getElementById('map_extra_{$field_details['variable']}'),
1743
                                        myOptions
1744
                                    );
1745
1746
                                    var parameter = address ? {'address': address} : latLng ? {'latLng': latLng} : false;
1747
1748
                                    if (geocoder && parameter) {
1749
                                        geocoder.geocode(parameter, function(results, status) {
1750
                                            if (status == google.maps.GeocoderStatus.OK) {
1751
                                                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
1752
                                                    map_{$field_details['variable']}.setCenter(results[0].geometry.location);
1753
                                                    if (!address) {
1754
                                                        $('#extra_{$field_details['variable']}').val(results[0].formatted_address);
1755
                                                    }
1756
                                                    var infowindow = new google.maps.InfoWindow({
1757
                                                        content: '<b>' + $('#extra_{$field_details['variable']}').val() + '</b>',
1758
                                                        size: new google.maps.Size(150, 50)
1759
                                                    });
1760
1761
                                                    var marker = new google.maps.Marker({
1762
                                                        position: results[0].geometry.location,
1763
                                                        map: map_{$field_details['variable']},
1764
                                                        title: $('#extra_{$field_details['variable']}').val()
1765
                                                    });
1766
                                                    google.maps.event.addListener(marker, 'click', function() {
1767
                                                        infowindow.open(map_{$field_details['variable']}, marker);
1768
                                                    });
1769
                                                } else {
1770
                                                    alert('".get_lang('NotFound')."');
1771
                                                }
1772
                                            } else {
1773
                                                alert('Geocode ".get_lang('Error').": ".get_lang("AddressField")
1774
                                                    ." ".get_lang('NotFound')."');
1775
                                            }
1776
                                        });
1777
                                    }
1778
                                }
1779
                            </script>
1780
                        ");
1781
                        $form->addHtml('
1782
                            <div class="form-group">
1783
                                <label for="geolocalization_extra_'.$field_details['variable'].'"
1784
                                    class="col-sm-2 control-label"></label>
1785
                                <div class="col-sm-8">
1786
                                    <button class="null btn btn-default "
1787
                                        id="geolocalization_extra_'.$field_details['variable'].'"
1788
                                        name="geolocalization_extra_'.$field_details['variable'].'"
1789
                                        type="submit">
1790
                                        <em class="fa fa-map-marker"></em> '.get_lang('Geolocalization').'
1791
                                    </button>
1792
                                    <button class="null btn btn-default " id="myLocation_extra_'.$field_details['variable'].'"
1793
                                        name="myLocation_extra_'.$field_details['variable'].'"
1794
                                        type="submit">
1795
                                        <em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'
1796
                                    </button>
1797
                                </div>
1798
                            </div>
1799
                        ');
1800
1801
                        $form->addHtml('
1802
                            <div class="form-group">
1803
                                <label for="map_extra_'.$field_details['variable'].'" class="col-sm-2 control-label">
1804
                                    '.$field_details['display_text'].' - '.get_lang('Map').'
1805
                                </label>
1806
                                <div class="col-sm-8">
1807
                                    <div name="map_extra_'.$field_details['variable'].'"
1808
                                        id="map_extra_'.$field_details['variable'].'" style="width:100%; height:300px;">
1809
                                    </div>
1810
                                </div>
1811
                            </div>
1812
                        ');
1813
                        break;
1814
                    case self::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
1815
                        $dataValue = isset($extraData['extra_'.$field_details['variable']])
1816
                            ? $extraData['extra_'.$field_details['variable']]
1817
                            : '';
1818
                        $form->addElement(
1819
                            'text',
1820
                            'extra_'.$field_details['variable'],
1821
                            $field_details['display_text'],
1822
                            ['id' => 'extra_'.$field_details['variable']]
1823
                        );
1824
                        $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
1825
                        $form->applyFilter('extra_'.$field_details['variable'], 'trim');
1826
                        if ($freezeElement) {
1827
                            $form->freeze('extra_'.$field_details['variable']);
1828
                        }
1829
                        $latLag = explode(",", $dataValue);
1830
1831
                        // if no value, set default coordinates value
1832
                        if (empty($dataValue)) {
1833
                            $lat = '-34.397';
1834
                            $lng = '150.644';
1835
                        } else {
1836
                            $lat = $latLag[0];
1837
                            $lng = $latLag[1];
1838
                        }
1839
1840
                        $form->addHtml("
1841
                            <script>
1842
                                $(document).ready(function() {
1843
                                    if (typeof google === 'object') {
1844
                                        var lat = '$lat';
1845
                                        var lng = '$lng';
1846
                                        var latLng = new google.maps.LatLng(lat, lng);
1847
                                        initializeGeo{$field_details['variable']}(false, latLng);
1848
1849
                                        $('#geolocalization_extra_{$field_details['variable']}').on('click', function() {
1850
                                            var latLng = $('#extra_{$field_details['variable']}').val().split(',');
1851
                                            var lat = latLng[0];
1852
                                            var lng = latLng[1];
1853
                                            var latLng = new google.maps.LatLng(lat, lng);
1854
                                            initializeGeo{$field_details['variable']}(false, latLng);
1855
                                            return false;
1856
                                        });
1857
1858
                                        $('#myLocation_extra_{$field_details['variable']}').on('click', function() {
1859
                                            myLocation{$field_details['variable']}();
1860
                                            return false;
1861
                                        });
1862
1863
                                        $('#extra_{$field_details['variable']}').keypress(function (event) {
1864
                                            if (event.which == 13) {
1865
                                                $('#geolocalization_extra_{$field_details['variable']}').click();
1866
                                                return false;
1867
                                            }
1868
                                        });
1869
1870
                                        return;
1871
                                    }
1872
1873
1874
                                    $('#map_extra_{$field_details['variable']}')
1875
                                        .html('<div class=\"alert alert-info\">"
1876
                                            .get_lang('YouNeedToActivateTheGoogleMapsPluginInAdminPlatformToSeeTheMap')
1877
                                            ."</div>');
1878
                                });
1879
1880
                                function myLocation{$field_details['variable']}() {
1881
                                    if (navigator.geolocation) {
1882
                                        var geoPosition = function(position) {
1883
                                            var lat = position.coords.latitude;
1884
                                            var lng = position.coords.longitude;
1885
                                            var latLng = new google.maps.LatLng(lat, lng);
1886
                                            initializeGeo{$field_details['variable']}(false, latLng)
1887
                                        };
1888
1889
                                        var geoError = function(error) {
1890
                                            alert('Geocode ".get_lang('Error').": ' + error);
1891
                                        };
1892
1893
                                        var geoOptions = {
1894
                                            enableHighAccuracy: true
1895
                                        };
1896
1897
                                        navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
1898
                                    }
1899
                                }
1900
1901
                                function initializeGeo{$field_details['variable']}(address, latLng) {
1902
                                    var geocoder = new google.maps.Geocoder();
1903
                                    var latlng = new google.maps.LatLng(-34.397, 150.644);
1904
                                    var myOptions = {
1905
                                        zoom: 15,
1906
                                        center: latlng,
1907
                                        mapTypeControl: true,
1908
                                        mapTypeControlOptions: {
1909
                                            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
1910
                                        },
1911
                                        navigationControl: true,
1912
                                        mapTypeId: google.maps.MapTypeId.ROADMAP
1913
                                    };
1914
1915
                                    map_{$field_details['variable']} = new google.maps.Map(
1916
                                        document.getElementById('map_extra_{$field_details['variable']}'),
1917
                                        myOptions
1918
                                    );
1919
1920
                                    var parameter = address ? {'address': address} : latLng ? {'latLng': latLng} : false;
1921
1922
                                    if (geocoder && parameter) {
1923
                                        geocoder.geocode(parameter, function(results, status) {
1924
                                            if (status == google.maps.GeocoderStatus.OK) {
1925
                                                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
1926
                                                    map_{$field_details['variable']}.setCenter(results[0].geometry.location);
1927
1928
                                                    $('#extra_{$field_details['variable']}')
1929
                                                        .val(results[0].geometry.location.lat() + ',' + results[0].geometry.location.lng());
1930
1931
                                                    var infowindow = new google.maps.InfoWindow({
1932
                                                        content: '<b>' + $('#extra_{$field_details['variable']}').val() + '</b>',
1933
                                                        size: new google.maps.Size(150, 50)
1934
                                                    });
1935
1936
                                                    var marker = new google.maps.Marker({
1937
                                                        position: results[0].geometry.location,
1938
                                                        map: map_{$field_details['variable']},
1939
                                                        title: $('#extra_{$field_details['variable']}').val()
1940
                                                    });
1941
                                                    google.maps.event.addListener(marker, 'click', function() {
1942
                                                        infowindow.open(map_{$field_details['variable']}, marker);
1943
                                                    });
1944
                                                } else {
1945
                                                    alert('".get_lang("NotFound")."');
1946
                                                }
1947
1948
                                            } else {
1949
                                                alert('Geocode ".get_lang('Error').": ' + status);
1950
                                            }
1951
                                        });
1952
                                    }
1953
                                }
1954
                            </script>
1955
                        ");
1956
                        $form->addHtml('
1957
                            <div class="form-group">
1958
                                <label for="geolocalization_extra_'.$field_details['variable'].'"
1959
                                    class="col-sm-2 control-label"></label>
1960
                                <div class="col-sm-8">
1961
                                    <button class="null btn btn-default "
1962
                                        id="geolocalization_extra_'.$field_details['variable'].'"
1963
                                        name="geolocalization_extra_'.$field_details['variable'].'"
1964
                                        type="submit">
1965
                                        <em class="fa fa-map-marker"></em> '.get_lang('Geolocalization').'
1966
                                    </button>
1967
                                    <button class="null btn btn-default"
1968
                                        id="myLocation_extra_'.$field_details['variable'].'"
1969
                                        name="myLocation_extra_'.$field_details['variable'].'" type="submit">
1970
                                        <em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'
1971
                                    </button>
1972
                                </div>
1973
                            </div>
1974
                        ');
1975
1976
                        $form->addHtml('
1977
                            <div class="form-group">
1978
                                <label for="map_extra_'.$field_details['variable'].'" class="col-sm-2 control-label">
1979
                                    '.$field_details['display_text'].' - '.get_lang('Map').'
1980
                                </label>
1981
                                <div class="col-sm-8">
1982
                                    <div name="map_extra_'.$field_details['variable'].'"
1983
                                        id="map_extra_'.$field_details['variable'].'"
1984
                                        style="width:100%; height:300px;">
1985
                                    </div>
1986
                                </div>
1987
                            </div>
1988
                        ');
1989
                        break;
1990
                }
1991
            }
1992
        }
1993
1994
        $return = array();
1995
        $return['jquery_ready_content'] = $jquery_ready_content;
1996
1997
        return $return;
1998
    }
1999
2000
    /**
2001
     * @param $breadcrumb
2002
     * @param $action
2003
     */
2004
    public function setupBreadcrumb(&$breadcrumb, $action)
2005
    {
2006
        if ($action == 'add') {
2007
            $breadcrumb[] = array('url' => $this->pageUrl, 'name' => $this->pageName);
2008
            $breadcrumb[] = array('url' => '#', 'name' => get_lang('Add'));
2009
        } elseif ($action == 'edit') {
2010
            $breadcrumb[] = array('url' => $this->pageUrl, 'name' => $this->pageName);
2011
            $breadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
2012
        } else {
2013
            $breadcrumb[] = array('url' => '#', 'name' => $this->pageName);
2014
        }
2015
    }
2016
2017
    /**
2018
     * Displays the title + grid
2019
     */
2020
    public function display()
2021
    {
2022
        // action links
2023
        echo '<div class="actions">';
2024
        echo '<a href="../admin/index.php">'.Display::return_icon(
2025
                'back.png',
2026
                get_lang('BackTo').' '.get_lang('PlatformAdmin'),
2027
                '',
2028
                ICON_SIZE_MEDIUM
2029
            ).'</a>';
2030
        echo '<a href="'.api_get_self().'?action=add&type='.$this->type.'">'.Display::return_icon(
2031
                'add_user_fields.png',
2032
                get_lang('Add'),
2033
                '',
2034
                ICON_SIZE_MEDIUM
2035
            ).'</a>';
2036
        echo '</div>';
2037
        echo Display::grid_html($this->type.'_fields');
2038
    }
2039
2040
    /**
2041
     * @return array
2042
     */
2043
    public function getJqgridColumnNames()
2044
    {
2045
        return array(
2046
            get_lang('Name'),
2047
            get_lang('FieldLabel'),
2048
            get_lang('Type'),
2049
            get_lang('FieldChangeability'),
2050
            get_lang('VisibleToSelf'),
2051
            get_lang('VisibleToOthers'),
2052
            get_lang('Filter'),
2053
            get_lang('FieldOrder'),
2054
            get_lang('Actions')
2055
        );
2056
    }
2057
2058
    /**
2059
     * @return array
2060
     */
2061
    public function getJqgridColumnModel()
2062
    {
2063
        return array(
2064
            array(
2065
                'name' => 'display_text',
2066
                'index' => 'display_text',
2067
                'width' => '140',
2068
                'align' => 'left',
2069
            ),
2070
            array(
2071
                'name' => 'variable',
2072
                'index' => 'variable',
2073
                'width' => '90',
2074
                'align' => 'left',
2075
                'sortable' => 'true',
2076
            ),
2077
            array(
2078
                'name' => 'field_type',
2079
                'index' => 'field_type',
2080
                'width' => '70',
2081
                'align' => 'left',
2082
                'sortable' => 'true',
2083
            ),
2084
            array(
2085
                'name' => 'changeable',
2086
                'index' => 'changeable',
2087
                'width' => '35',
2088
                'align' => 'left',
2089
                'sortable' => 'true',
2090
            ),
2091
            array(
2092
                'name' => 'visible_to_self',
2093
                'index' => 'visible_to_self',
2094
                'width' => '45',
2095
                'align' => 'left',
2096
                'sortable' => 'true',
2097
            ),
2098
            array(
2099
                'name' => 'visible_to_others',
2100
                'index' => 'visible_to_others',
2101
                'width' => '35',
2102
                'align' => 'left',
2103
                'sortable' => 'true',
2104
            ),
2105
            array(
2106
                'name' => 'filter',
2107
                'index' => 'filter',
2108
                'width' => '30',
2109
                'align' => 'left',
2110
                'sortable' => 'true',
2111
            ),
2112
            array(
2113
                'name' => 'field_order',
2114
                'index' => 'field_order',
2115
                'width' => '25',
2116
                'align' => 'left',
2117
                'sortable' => 'true',
2118
            ),
2119
            array(
2120
                'name' => 'actions',
2121
                'index' => 'actions',
2122
                'width' => '40',
2123
                'align' => 'left',
2124
                'formatter' => 'action_formatter',
2125
                'sortable' => 'false',
2126
            ),
2127
        );
2128
    }
2129
2130
    /**
2131
     * @param string $url
2132
     * @param string $action
2133
     * @return FormValidator
2134
     */
2135
    public function return_form($url, $action)
2136
    {
2137
        $form = new FormValidator($this->type.'_field', 'post', $url);
2138
2139
        $form->addElement('hidden', 'type', $this->type);
2140
        $id = isset($_GET['id']) ? intval($_GET['id']) : null;
2141
        $form->addElement('hidden', 'id', $id);
2142
2143
        // Setting the form elements
2144
        $header = get_lang('Add');
2145
        $defaults = array();
2146
2147
        if ($action == 'edit') {
2148
            $header = get_lang('Modify');
2149
            // Setting the defaults
2150
            $defaults = $this->get($id, false);
2151
        }
2152
2153
        $form->addElement('header', $header);
2154
2155 View Code Duplication
        if ($action == 'edit') {
2156
            $translateUrl = api_get_path(WEB_CODE_PATH).'extrafield/translate.php?'
2157
                .http_build_query(['extra_field' => $id]);
2158
            $translateButton = Display::toolbarButton(get_lang('TranslateThisTerm'), $translateUrl, 'language', 'link');
2159
2160
            $form->addText(
2161
                'display_text',
2162
                [get_lang('Name'), $translateButton]
2163
            );
2164
        } else {
2165
            $form->addElement('text', 'display_text', get_lang('Name'));
2166
        }
2167
2168
        // Field type
2169
        $types = self::get_field_types();
2170
2171
        $form->addElement(
2172
            'select',
2173
            'field_type',
2174
            get_lang('FieldType'),
2175
            $types,
2176
            array('id' => 'field_type')
2177
        );
2178
        $form->addElement('label', get_lang('Example'), '<div id="example">-</div>');
2179
        $form->addElement('text', 'variable', get_lang('FieldLabel'), array('class' => 'span5'));
2180
        $form->addElement(
2181
            'text',
2182
            'field_options',
2183
            get_lang('FieldPossibleValues'),
2184
            array('id' => 'field_options', 'class' => 'span6')
2185
        );
2186
2187
        $fieldWithOptions = array(
2188
            self::FIELD_TYPE_RADIO,
2189
            self::FIELD_TYPE_SELECT_MULTIPLE,
2190
            self::FIELD_TYPE_SELECT,
2191
            self::FIELD_TYPE_TAG,
2192
            self::FIELD_TYPE_DOUBLE_SELECT,
2193
        );
2194
2195
        if ($action == 'edit') {
2196
            if (in_array($defaults['field_type'], $fieldWithOptions)) {
2197
                $url = Display::url(
2198
                    get_lang('EditExtraFieldOptions'),
2199
                    'extra_field_options.php?type='.$this->type.'&field_id='.$id
2200
                );
2201
                $form->addElement('label', null, $url);
2202
2203
                if ($defaults['field_type'] == self::FIELD_TYPE_SELECT) {
2204
                    $urlWorkFlow = Display::url(
2205
                        get_lang('EditExtraFieldWorkFlow'),
2206
                        'extra_field_workflow.php?type='.$this->type.'&field_id='.$id
2207
                    );
2208
                    $form->addElement('label', null, $urlWorkFlow);
2209
                }
2210
2211
                $form->freeze('field_options');
2212
            }
2213
        }
2214
        $form->addElement(
2215
            'text',
2216
            'default_value',
2217
            get_lang('FieldDefaultValue'),
2218
            array('id' => 'default_value')
2219
        );
2220
2221
        $group = array();
2222
        $group[] = $form->createElement('radio', 'visible_to_self', null, get_lang('Yes'), 1);
2223
        $group[] = $form->createElement('radio', 'visible_to_self', null, get_lang('No'), 0);
2224
        $form->addGroup($group, '', get_lang('VisibleToSelf'), null, false);
2225
2226
        $group = array();
2227
        $group[] = $form->createElement('radio', 'visible_to_others', null, get_lang('Yes'), 1);
2228
        $group[] = $form->createElement('radio', 'visible_to_others', null, get_lang('No'), 0);
2229
        $form->addGroup($group, '', get_lang('VisibleToOthers'), null, false);
2230
2231
        $group = array();
2232
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('Yes'), 1);
2233
        $group[] = $form->createElement('radio', 'changeable', null, get_lang('No'), 0);
2234
        $form->addGroup($group, '', get_lang('FieldChangeability'), null, false);
2235
2236
        $group = array();
2237
        $group[] = $form->createElement('radio', 'filter', null, get_lang('Yes'), 1);
2238
        $group[] = $form->createElement('radio', 'filter', null, get_lang('No'), 0);
2239
        $form->addGroup($group, '', get_lang('FieldFilter'), null, false);
2240
2241
        /* Enable this when field_loggeable is introduced as a table field (2.0)
2242
        $group   = array();
2243
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('Yes'), 1);
2244
        $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('No'), 0);
2245
        $form->addGroup($group, '', get_lang('FieldLoggeable'), '', false);
2246
        */
2247
2248
        $form->addElement('text', 'field_order', get_lang('FieldOrder'));
2249
2250
        if ($action == 'edit') {
2251
            $option = new ExtraFieldOption($this->type);
2252
            if ($defaults['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
2253
                $form->freeze('field_options');
2254
            }
2255
            $defaults['field_options'] = $option->get_field_options_by_field_to_string($id);
2256
            $form->addButtonUpdate(get_lang('Modify'));
2257
        } else {
2258
            $defaults['visible_to_self'] = 0;
2259
            $defaults['visible_to_others'] = 0;
2260
            $defaults['changeable'] = 0;
2261
            $defaults['filter'] = 0;
2262
            $form->addButtonCreate(get_lang('Add'));
2263
        }
2264
2265
        /*if (!empty($defaults['created_at'])) {
2266
            $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
2267
        }
2268
        if (!empty($defaults['updated_at'])) {
2269
            $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
2270
        }*/
2271
        $form->setDefaults($defaults);
2272
2273
        // Setting the rules
2274
        $form->addRule('display_text', get_lang('ThisFieldIsRequired'), 'required');
2275
        $form->addRule('field_type', get_lang('ThisFieldIsRequired'), 'required');
2276
2277
        return $form;
2278
    }
2279
2280
    /**
2281
     * @param $token
2282
     * @return string
2283
     */
2284
    public function getJqgridActionLinks($token)
2285
    {
2286
        //With this function we can add actions to the jgrid (edit, delete, etc)
2287
        $editIcon = Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL);
2288
        $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
2289
        $confirmMessage = addslashes(
2290
            api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES)
2291
        );
2292
2293
        $editButton = <<<JAVASCRIPT
2294
            <a href="?action=edit&type={$this->type}&id=' + options.rowId + '" class="btn btn-link btn-xs">\
2295
                $editIcon\
2296
            </a>
2297
JAVASCRIPT;
2298
        $deleteButton = <<<JAVASCRIPT
2299
            <a \
2300
                onclick="if (!confirm(\'$confirmMessage\')) {return false;}" \
2301
                href="?sec_token=$token&type={$this->type}&id=' + options.rowId + '&action=delete" \
2302
                class="btn btn-link btn-xs">\
2303
                $deleteIcon\
2304
            </a>
2305
JAVASCRIPT;
2306
2307
        return "function action_formatter(cellvalue, options, rowObject) {        
2308
            return '$editButton $deleteButton';
2309
        }";
2310
    }
2311
2312
    /**
2313
     * @param array $columns
2314
     * @param array $column_model
2315
     * @param array $extraFields
2316
     * @return array
2317
     */
2318
    public function getRules(&$columns, &$column_model, $extraFields = array(), $checkExtraFieldExistence = false)
2319
    {
2320
        $fields = $this->get_all(
2321
            array(
2322
                'visible_to_self = ? AND filter = ?' => array(1, 1)
2323
            ),
2324
            'display_text'
2325
        );
2326
        $extraFieldOption = new ExtraFieldOption($this->type);
2327
2328
        $rules = array();
2329
        if (!empty($fields)) {
2330
            foreach ($fields as $field) {
2331
                $search_options = array();
2332
                $type = 'text';
2333
                if (in_array($field['field_type'], array(self::FIELD_TYPE_SELECT, self::FIELD_TYPE_DOUBLE_SELECT))) {
2334
                    $type = 'select';
2335
                    $search_options['sopt'] = array('eq', 'ne'); //equal not equal
2336
                } else {
2337
                    $search_options['sopt'] = array('cn', 'nc'); //contains not contains
2338
                }
2339
2340
                $search_options['searchhidden'] = 'true';
2341
                $search_options['defaultValue'] = isset($search_options['field_default_value'])
2342
                    ? $search_options['field_default_value']
2343
                    : null;
2344
2345
                if ($field['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
2346
                    //Add 2 selects
2347
                    $options = $extraFieldOption->get_field_options_by_field($field['id']);
2348
                    $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...
2349
                    $first_options = array();
2350
2351
                    if (!empty($options)) {
2352
                        foreach ($options as $option) {
2353
                            foreach ($option as $sub_option) {
2354
                                if ($sub_option['option_value'] == 0) {
2355
                                    $first_options[] = $sub_option['field_id'].'#'.$sub_option['id'].':'
2356
                                        .$sub_option['display_text'];
2357
                                }
2358
                            }
2359
                        }
2360
                    }
2361
2362
                    $search_options['value'] = implode(';', $first_options);
2363
                    $search_options['dataInit'] = 'fill_second_select';
2364
2365
                    // First
2366
                    $column_model[] = array(
2367
                        'name' => 'extra_'.$field['variable'],
2368
                        'index' => 'extra_'.$field['variable'],
2369
                        'width' => '100',
2370
                        'hidden' => 'true',
2371
                        'search' => 'true',
2372
                        'stype' => 'select',
2373
                        'searchoptions' => $search_options,
2374
                    );
2375
                    $columns[] = $field['display_text'].' (1)';
2376
                    $rules[] = array(
2377
                        'field' => 'extra_'.$field['variable'],
2378
                        'op' => 'cn',
2379
                    );
2380
2381
                    // Second
2382
                    $search_options['value'] = $field['id'].':';
2383
                    $search_options['dataInit'] = 'register_second_select';
2384
2385
                    $column_model[] = array(
2386
                        'name' => 'extra_'.$field['variable'].'_second',
2387
                        'index' => 'extra_'.$field['variable'].'_second',
2388
                        'width' => '100',
2389
                        'hidden' => 'true',
2390
                        'search' => 'true',
2391
                        'stype' => 'select',
2392
                        'searchoptions' => $search_options,
2393
                    );
2394
                    $columns[] = $field['display_text'].' (2)';
2395
                    $rules[] = array('field' => 'extra_'.$field['variable'].'_second', 'op' => 'cn');
2396
                    continue;
2397
                } else {
2398
                    $search_options['value'] = $extraFieldOption->getFieldOptionsToString(
2399
                        $field['id'],
2400
                        false,
2401
                        'display_text'
2402
                    );
2403
                }
2404
                $column_model[] = array(
2405
                    'name' => 'extra_'.$field['variable'],
2406
                    'index' => 'extra_'.$field['variable'],
2407
                    'width' => '100',
2408
                    'hidden' => 'true',
2409
                    'search' => 'true',
2410
                    'stype' => $type,
2411
                    'searchoptions' => $search_options,
2412
                );
2413
                $columns[] = $field['display_text'];
2414
                $rules[] = array(
2415
                    'field' => 'extra_'.$field['variable'],
2416
                    'op' => 'cn'
2417
                );
2418
            }
2419
        }
2420
2421
        return $rules;
2422
    }
2423
2424
    /**
2425
     * @param array $options
2426
     * @return array
2427
     */
2428
    public function parseConditions($options)
2429
    {
2430
        $inject_extra_fields = null;
2431
        $extraFieldOption = new ExtraFieldOption($this->type);
2432
        $double_fields = array();
2433
2434
        if (isset($options['extra'])) {
2435
            $extra_fields = $options['extra'];
2436
            if (!empty($extra_fields)) {
2437
                $counter = 1;
2438
                foreach ($extra_fields as &$extra) {
2439
                    $extra_field_obj = new ExtraField($this->type);
2440
                    $extra_field_info = $extra_field_obj->get($extra['id']);
2441
                    $extra['extra_field_info'] = $extra_field_info;
2442
2443
                    if (isset($extra_field_info['field_type']) && in_array(
2444
                            $extra_field_info['field_type'],
2445
                            array(
2446
                                self::FIELD_TYPE_SELECT,
2447
                                self::FIELD_TYPE_SELECT,
2448
                                self::FIELD_TYPE_DOUBLE_SELECT
2449
                            )
2450
                        )
2451
                    ) {
2452
                        $inject_extra_fields .= " fvo$counter.display_text as {$extra['field']}, ";
2453
                    } else {
2454
                        $inject_extra_fields .= " fv$counter.value as {$extra['field']}, ";
2455
                    }
2456
2457 View Code Duplication
                    if (isset($extra_fields_info[$extra['id']])) {
2458
                        $info = $extra_fields_info[$extra['id']];
2459
                    } else {
2460
                        $info = $this->get($extra['id']);
2461
                        $extra_fields_info[$extra['id']] = $info;
2462
                    }
2463
                    if (isset($info['field_type']) && $info['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
2464
                        $double_fields[$info['id']] = $info;
2465
                    }
2466
                    $counter++;
2467
                }
2468
            }
2469
        }
2470
2471
        $options_by_double = array();
2472 View Code Duplication
        foreach ($double_fields as $double) {
2473
            $my_options = $extraFieldOption->get_field_options_by_field(
2474
                $double['id'],
2475
                true
2476
            );
2477
            $options_by_double['extra_'.$double['variable']] = $my_options;
2478
        }
2479
2480
        $field_value_to_join = array();
2481
2482
        //filter can be all/any = and/or
2483
        $inject_joins = null;
2484
        $inject_where = null;
2485
        $where = null;
2486
2487
        if (!empty($options['where'])) {
2488
            if (!empty($options['extra'])) {
2489
                // Removing double 1=1
2490
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
2491
                // Always OR
2492
                $counter = 1;
2493
                foreach ($extra_fields as $extra_info) {
2494
                    $extra_field_info = $extra_info['extra_field_info'];
2495
                    $inject_joins .= " INNER JOIN $this->table_field_values fv$counter
2496
                                       ON (s.".$this->primaryKey." = fv$counter.".$this->handler_id.") ";
2497
                    // Add options
2498
                    if (isset($extra_field_info['field_type']) && in_array(
2499
                            $extra_field_info['field_type'],
2500
                            array(
2501
                                self::FIELD_TYPE_SELECT,
2502
                                self::FIELD_TYPE_SELECT,
2503
                                self::FIELD_TYPE_DOUBLE_SELECT
2504
                            )
2505
                        )
2506
                    ) {
2507
                        $options['where'] = str_replace(
2508
                            $extra_info['field'],
2509
                            'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fvo'.$counter.'.option_value',
2510
                            $options['where']
2511
                        );
2512
                        $inject_joins .= "
2513
                             INNER JOIN $this->table_field_options fvo$counter
2514
                             ON (
2515
                                fv$counter.field_id = fvo$counter.field_id AND
2516
                                fv$counter.value = fvo$counter.option_value
2517
                             )
2518
                            ";
2519
                    } else if (isset($extra_field_info['field_type']) &&
2520
                        $extra_field_info['field_type'] == self::FIELD_TYPE_TAG
2521
                    ) {
2522
                        $options['where'] = str_replace(
2523
                            $extra_info['field'],
2524
                            'tag'.$counter.'.tag ',
2525
                            $options['where']
2526
                        );
2527
2528
                        $inject_joins .= "
2529
                            INNER JOIN $this->table_field_rel_tag tag_rel$counter
2530
                            ON (tag_rel$counter.field_id = ".$extra_info['id']." AND tag_rel$counter.item_id = s.".$this->primaryKey.")
2531
                            INNER JOIN $this->table_field_tag tag$counter
2532
                            ON (tag$counter.id =  tag_rel$counter.tag_id)
2533
                        ";
2534
                    } else {
2535
                        //text, textarea, etc
2536
                        $options['where'] = str_replace(
2537
                            $extra_info['field'],
2538
                            'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fv'.$counter.'.value',
2539
                            $options['where']
2540
                        );
2541
                    }
2542
2543
                    $field_value_to_join[] = " fv$counter.$this->handler_id ";
2544
                    $counter++;
2545
                }
2546
                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...
2547
                    //$inject_where .= " AND s.id = ".implode(' = ', $field_value_to_join);
2548
                }
2549
            }
2550
            $where .= ' AND '.$options['where'];
2551
        }
2552
2553
        $order = null;
2554
        if (!empty($options['order'])) {
2555
            $order = " ORDER BY ".$options['order'];
2556
        }
2557
        $limit = null;
2558
        if (!empty($options['limit'])) {
2559
            $limit = " LIMIT ".$options['limit'];
2560
        }
2561
2562
        return array(
2563
            'order' => $order,
2564
            'limit' => $limit,
2565
            'where' => $where,
2566
            'inject_where' => $inject_where,
2567
            'inject_joins' => $inject_joins,
2568
            'field_value_to_join' => $field_value_to_join,
2569
            'inject_extra_fields' => $inject_extra_fields,
2570
        );
2571
    }
2572
2573
    //@todo move this in the display_class or somewhere else
2574
    /**
2575
     * @param $col
2576
     * @param $oper
2577
     * @param $val
2578
     * @return string
2579
     */
2580
    public function get_where_clause($col, $oper, $val)
2581
    {
2582
        if (empty($col)) {
2583
            return '';
2584
        }
2585
        if ($oper == 'bw' || $oper == 'bn') {
2586
            $val .= '%';
2587
        }
2588
        if ($oper == 'ew' || $oper == 'en') {
2589
            $val = '%'.$val;
2590
        }
2591
        if ($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') {
2592
            if (is_array($val)) {
2593
                $result = '"%'.implode(';', $val).'%"';
2594
                foreach ($val as $item) {
2595
                    $item = trim($item);
2596
                    $result .= ' OR '.$col.' LIKE "%'.$item.'%"';
2597
                }
2598
                $val = $result;
2599
2600
                return " $col {$this->ops[$oper]} $val ";
2601
            } else {
2602
                $val = '%'.$val.'%';
2603
            }
2604
        }
2605
        $val = \Database::escape_string($val);
2606
2607
        return " $col {$this->ops[$oper]} '$val' ";
2608
    }
2609
2610
    /**
2611
     * @param $filters
2612
     * @param string $stringToSearch
2613
     * @return array
2614
     */
2615
    public function getExtraFieldRules($filters, $stringToSearch = 'extra_')
2616
    {
2617
        $extra_fields = array();
2618
2619
        // Getting double select if exists
2620
        $double_select = array();
2621
        foreach ($filters->rules as $rule) {
2622
            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...
2623
2624
            } else {
2625
                $my_field = str_replace('_second', '', $rule->field);
2626
                $double_select[$my_field] = $rule->data;
2627
            }
2628
        }
2629
2630
        $condition_array = array();
2631
2632
        foreach ($filters->rules as $rule) {
2633
            if (strpos($rule->field, $stringToSearch) === false) {
2634
                // normal fields
2635
                $field = $rule->field;
2636
                if (isset($rule->data) && is_string($rule->data) && $rule->data != -1) {
2637
                    $condition_array[] = $this->get_where_clause($field, $rule->op, $rule->data);
2638
                }
2639
            } else {
2640
                // Extra fields
2641
                if (strpos($rule->field, '_second') === false) {
2642
                    //No _second
2643
                    $original_field = str_replace($stringToSearch, '', $rule->field);
2644
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2645
2646
                    if ($field_option['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
2647
                        if (isset($double_select[$rule->field])) {
2648
                            $data = explode('#', $rule->data);
2649
                            $rule->data = $data[1].'::'.$double_select[$rule->field];
2650
                        } else {
2651
                            // only was sent 1 select
2652
                            if (is_string($rule->data)) {
2653
                                $data = explode('#', $rule->data);
2654
                                $rule->data = $data[1];
2655
                            }
2656
                        }
2657
2658
                        if (!isset($rule->data)) {
2659
                            $condition_array[] = ' ('
2660
                                .$this->get_where_clause($rule->field, $rule->op, $rule->data)
2661
                                .') ';
2662
                            $extra_fields[] = array('field' => $rule->field, 'id' => $field_option['id']);
2663
                        }
2664
                    } else {
2665
                        if (isset($rule->data)) {
2666
                            if ($rule->data == -1) {
2667
                                continue;
2668
                            }
2669
                            $condition_array[] = ' ('
2670
                                .$this->get_where_clause($rule->field, $rule->op, $rule->data)
2671
                                .') ';
2672
                            $extra_fields[] = array(
2673
                                'field' => $rule->field,
2674
                                'id' => $field_option['id'],
2675
                                'data' => $rule->data
2676
                            );
2677
                        }
2678
                    }
2679
                } else {
2680
                    $my_field = str_replace('_second', '', $rule->field);
2681
                    $original_field = str_replace($stringToSearch, '', $my_field);
2682
                    $field_option = $this->get_handler_field_info_by_field_variable($original_field);
2683
                    $extra_fields[] = array(
2684
                        'field' => $rule->field,
2685
                        'id' => $field_option['id']
2686
                    );
2687
                }
2688
            }
2689
        }
2690
2691
        return array(
2692
            'extra_fields' => $extra_fields,
2693
            'condition_array' => $condition_array
2694
        );
2695
    }
2696
2697
    /**
2698
     * Get the extra fields and their formatted values
2699
     * @param int|string $itemId The item ID (It could be a session_id, course_id or user_id)
2700
     * @return array The extra fields data
2701
     */
2702
    public function getDataAndFormattedValues($itemId)
2703
    {
2704
        $valuesData = array();
2705
2706
        $fields = $this->get_all();
2707
2708
        foreach ($fields as $field) {
2709
            if ($field['visible_to_self'] != '1') {
2710
                continue;
2711
            }
2712
2713
            $fieldValue = new ExtraFieldValue($this->type);
2714
            $valueData = $fieldValue->get_values_by_handler_and_field_id($itemId, $field['id'], true);
2715
2716
            if (!$valueData) {
2717
                continue;
2718
            }
2719
2720
            $displayedValue = get_lang('None');
2721
2722
            switch ($field['field_type']) {
2723
                case self::FIELD_TYPE_CHECKBOX:
2724
                    if ($valueData !== false && $valueData['value'] == '1') {
2725
                        $displayedValue = get_lang('Yes');
2726
                    } else {
2727
                        $displayedValue = get_lang('No');
2728
                    }
2729
                    break;
2730
                case self::FIELD_TYPE_DATE:
2731
                    if ($valueData !== false && !empty($valueData['value'])) {
2732
                        $displayedValue = api_format_date($valueData['value'], DATE_FORMAT_LONG_NO_DAY);
2733
                    }
2734
                    break;
2735
                case self::FIELD_TYPE_FILE_IMAGE:
2736
                    if ($valueData === false || empty($valueData['value'])) {
2737
                        break;
2738
                    }
2739
2740
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
2741
                        break;
2742
                    }
2743
2744
                    $image = Display::img(
2745
                        api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
2746
                        $field['display_text'],
2747
                        array('width' => '300')
2748
                    );
2749
2750
                    $displayedValue = Display::url(
2751
                        $image,
2752
                        api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
2753
                        array('target' => '_blank')
2754
                    );
2755
                    break;
2756
                case self::FIELD_TYPE_FILE:
2757
                    if ($valueData === false || empty($valueData['value'])) {
2758
                        break;
2759
                    }
2760
2761
                    if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
2762
                        break;
2763
                    }
2764
2765
                    $displayedValue = Display::url(
2766
                        get_lang('Download'),
2767
                        api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
2768
                        array(
2769
                            'title' => $field['display_text'],
2770
                            'target' => '_blank'
2771
                        )
2772
                    );
2773
                    break;
2774
                default:
2775
                    $displayedValue = $valueData['value'];
2776
                    break;
2777
            }
2778
2779
            $valuesData[] = array(
2780
                'text' => $field['display_text'],
2781
                'value' => $displayedValue
2782
            );
2783
        }
2784
2785
        return $valuesData;
2786
    }
2787
2788
    /**
2789
     * Gets an element
2790
     * @param int $id
2791
     * @param bool $translateDisplayText Optional
2792
     * @return array
2793
     */
2794 View Code Duplication
    public function get($id, $translateDisplayText = true)
2795
    {
2796
        $info = parent::get($id);
2797
2798
        if ($translateDisplayText) {
2799
            $info['display_text'] = self::translateDisplayName($info['variable'], $info['display_text']);
2800
        }
2801
2802
        return $info;
2803
    }
2804
2805
    /**
2806
     * Translate the display text for a extra field
2807
     * @param string $variable
2808
     * @param string $defaultDisplayText
2809
     * @return string
2810
     */
2811
    public static function translateDisplayName($variable, $defaultDisplayText)
2812
    {
2813
        $camelCase = api_underscore_to_camel_case($variable);
2814
2815
        return isset($GLOBALS[$camelCase]) ? $GLOBALS[$camelCase] : $defaultDisplayText;
2816
    }
2817
2818
    /**
2819
     * @param int $fieldId
2820
     * @param string $tag
2821
     *
2822
     * @return array
2823
     */
2824 View Code Duplication
    public function getAllUserPerTag($fieldId, $tag)
2825
    {
2826
        $tagRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
2827
        $tag = Database::escape_string($tag);
2828
        $fieldId = (int) $fieldId;
2829
2830
        $sql = "SELECT user_id 
2831
                FROM {$this->table_field_tag} f INNER JOIN $tagRelUserTable ft 
2832
                ON tag_id = f.id 
2833
                WHERE tag = '$tag' AND f.field_id = $fieldId;
2834
        ";
2835
2836
        $result = Database::query($sql);
2837
2838
        return Database::store_result($result, 'ASSOC');
2839
    }
2840
2841
    /**
2842
     * @param int $fieldId
2843
     * @param int $tagId
2844
     *
2845
     * @return array
2846
     */
2847 View Code Duplication
    public function getAllSkillPerTag($fieldId, $tagId)
2848
    {
2849
        $skillTable = Database::get_main_table(TABLE_MAIN_SKILL);
2850
        $tagRelExtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
2851
        $fieldId = intval($fieldId);
2852
        $tagId = intval($tagId);
2853
2854
        $sql = "SELECT s.id
2855
                FROM $skillTable s INNER JOIN $tagRelExtraTable t
2856
                ON t.item_id = s.id
2857
                WHERE tag_id = $tagId AND t.field_id = $fieldId;
2858
        ";
2859
2860
        $result = Database::query($sql);
2861
        $result = Database::store_result($result, 'ASSOC');
2862
2863
        $skillList = [];
2864
        foreach ($result as $index => $value) {
2865
            $skillList[$value['id']] = $value['id'];
2866
        }
2867
2868
        return $skillList;
2869
    }
2870
}
2871