Passed
Push — 1.11.x ( 67b61d...698144 )
by Julito
09:47
created

learnpathItem::get_core_exit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class learnpathItem
7
 * lp_item defines items belonging to a learnpath. Each item has a name,
8
 * a score, a use time and additional information that enables tracking a user's
9
 * progress in a learning path.
10
 *
11
 * @author  Yannick Warnier <[email protected]>
12
 */
13
class learnpathItem
14
{
15
    const DEBUG = 0; // Logging parameter.
16
    public $iId;
17
    public $attempt_id; // Also called "objectives" SCORM-wise.
18
    public $audio; // The path to an audio file (stored in document/audio/).
19
    public $children = []; // Contains the ids of children items.
20
    public $condition; // If this item has a special condition embedded.
21
    public $current_score;
22
    public $current_start_time;
23
    public $current_stop_time;
24
    public $current_data = '';
25
    public $db_id;
26
    public $db_item_view_id = '';
27
    public $description = '';
28
    public $file;
29
    /**
30
     * At the moment, interactions are just an array of arrays with a structure
31
     * of 8 text fields: id(0), type(1), time(2), weighting(3),
32
     * correct_responses(4), student_response(5), result(6), latency(7).
33
     */
34
    public $interactions = [];
35
    public $interactions_count = 0;
36
    public $objectives = [];
37
    public $objectives_count = 0;
38
    public $launch_data = '';
39
    public $lesson_location = '';
40
    public $level = 0;
41
    public $core_exit = '';
42
    //var $location; // Only set this for SCORM?
43
    public $lp_id;
44
    public $max_score;
45
    public $mastery_score;
46
    public $min_score;
47
    public $max_time_allowed = '';
48
    public $name;
49
    public $next;
50
    public $parent;
51
    public $path; // In some cases the exo_id = exercise_id in courseDb exercices table.
52
    public $possible_status = [
53
        'not attempted',
54
        'incomplete',
55
        'completed',
56
        'passed',
57
        'failed',
58
        'browsed',
59
    ];
60
    public $prereq_string = '';
61
    public $prereq_alert = '';
62
    public $prereqs = [];
63
    public $previous;
64
    public $prevent_reinit = 1; // 0 =  multiple attempts   1 = one attempt
65
    public $seriousgame_mode;
66
    public $ref;
67
    public $save_on_close = true;
68
    public $search_did = null;
69
    public $status;
70
    public $title;
71
    /**
72
     * Type attribute can contain one of
73
     * link|student_publication|dir|quiz|document|forum|thread.
74
     */
75
    public $type;
76
    public $view_id;
77
    public $oldTotalTime;
78
    //var used if absolute session time mode is used
79
    private $last_scorm_session_time = 0;
80
    private $prerequisiteMaxScore;
81
    private $prerequisiteMinScore;
82
    public $view_max_score;
83
84
    /**
85
     * Prepares the learning path item for later launch.
86
     * Don't forget to use set_lp_view() if applicable after creating the item.
87
     * Setting an lp_view will finalise the item_view data collection.
88
     *
89
     * @param int        $id           Learning path item ID
90
     * @param int        $user_id      User ID
91
     * @param int        $course_id    Course int id
92
     * @param array|null $item_content An array with the contents of the item
93
     */
94
    public function __construct(
95
        $id,
96
        $user_id = 0,
97
        $course_id = 0,
98
        $item_content = null
99
    ) {
100
        $items_table = Database::get_course_table(TABLE_LP_ITEM);
101
102
        // Get items table.
103
        if (!isset($user_id)) {
104
            $user_id = api_get_user_id();
105
        }
106
        if (self::DEBUG > 0) {
107
            error_log("learnpathItem constructor: id: $id user_id: $user_id course_id: $course_id");
108
            error_log("item_content: ".print_r($item_content, 1));
109
        }
110
        $id = (int) $id;
111
        if (empty($item_content)) {
112
            if (empty($course_id)) {
113
                $course_id = api_get_course_int_id();
114
            } else {
115
                $course_id = (int) $course_id;
116
            }
117
            $sql = "SELECT * FROM $items_table
118
                    WHERE iid = $id";
119
            $res = Database::query($sql);
120
            if (Database::num_rows($res) < 1) {
121
                $this->error = 'Could not find given learnpath item in learnpath_item table';
122
            }
123
            $row = Database::fetch_array($res);
124
        } else {
125
            $row = $item_content;
126
        }
127
128
        $this->lp_id = $row['lp_id'];
129
        $this->iId = $row['iid'];
130
        $this->max_score = $row['max_score'];
131
        $this->min_score = $row['min_score'];
132
        $this->name = $row['title'];
133
        $this->type = $row['item_type'];
134
        $this->ref = $row['ref'];
135
        $this->title = $row['title'];
136
        $this->description = $row['description'];
137
        $this->path = $row['path'];
138
        $this->mastery_score = $row['mastery_score'];
139
        $this->parent = $row['parent_item_id'];
140
        $this->next = $row['next_item_id'];
141
        $this->previous = $row['previous_item_id'];
142
        $this->display_order = $row['display_order'];
143
        $this->prereq_string = $row['prerequisite'];
144
        $this->max_time_allowed = $row['max_time_allowed'];
145
        $this->setPrerequisiteMaxScore($row['prerequisite_max_score']);
146
        $this->setPrerequisiteMinScore($row['prerequisite_min_score']);
147
        $this->oldTotalTime = 0;
148
        $this->view_max_score = 0;
149
150
        if (isset($row['launch_data'])) {
151
            $this->launch_data = $row['launch_data'];
152
        }
153
        $this->save_on_close = true;
154
        $this->db_id = $id;
155
156
        // Load children list
157
        if (!empty($this->lp_id)) {
158
            $sql = "SELECT iid FROM $items_table
159
                    WHERE
160
                        c_id = $course_id AND
161
                        lp_id = ".$this->lp_id." AND
162
                        parent_item_id = $id";
163
            $res = Database::query($sql);
164
            if (Database::num_rows($res) > 0) {
165
                while ($row = Database::fetch_assoc($res)) {
166
                    $this->children[] = $row['iid'];
167
                }
168
            }
169
170
            // Get search_did.
171
            if (api_get_setting('search_enabled') == 'true') {
172
                $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
173
                $sql = 'SELECT *
174
                        FROM %s
175
                        WHERE
176
                            course_code=\'%s\' AND
177
                            tool_id=\'%s\' AND
178
                            ref_id_high_level=%s AND
179
                            ref_id_second_level=%d
180
                        LIMIT 1';
181
                // TODO: Verify if it's possible to assume the actual course instead
182
                // of getting it from db.
183
                $sql = sprintf(
184
                    $sql,
185
                    $tbl_se_ref,
186
                    api_get_course_id(),
187
                    TOOL_LEARNPATH,
188
                    $this->lp_id,
189
                    $id
190
                );
191
                $res = Database::query($sql);
192
                if (Database::num_rows($res) > 0) {
193
                    $se_ref = Database::fetch_array($res);
194
                    $this->search_did = (int) $se_ref['search_did'];
195
                }
196
            }
197
        }
198
        $this->seriousgame_mode = 0;
199
        $this->audio = $row['audio'];
200
        if (self::DEBUG > 0) {
201
            error_log(
202
                'New LP - End of learnpathItem constructor for item '.$id,
203
                0
204
            );
205
        }
206
    }
207
208
    /**
209
     * Adds a child to the current item.
210
     *
211
     * @param int $item The child item ID
212
     */
213
    public function add_child($item)
214
    {
215
        if (!empty($item)) {
216
            // Do not check in DB as we expect the call to come from the
217
            // learnpath class which should be aware of any fake.
218
            $this->children[] = $item;
219
        }
220
    }
221
222
    /**
223
     * Adds an interaction to the current item.
224
     *
225
     * @param int   $index  Index (order ID) of the interaction inside this item
226
     * @param array $params Array of parameters:
227
     *                      id(0), type(1), time(2), weighting(3), correct_responses(4),
228
     *                      student_response(5), result(6), latency(7)
229
     */
230
    public function add_interaction($index, $params)
231
    {
232
        $this->interactions[$index] = $params;
233
        // Take the current maximum index to generate the interactions_count.
234
        if (($index + 1) > $this->interactions_count) {
235
            $this->interactions_count = $index + 1;
236
        }
237
    }
238
239
    /**
240
     * Adds an objective to the current item.
241
     *
242
     * @param    array    Array of parameters:
243
     * id(0), status(1), score_raw(2), score_max(3), score_min(4)
244
     */
245
    public function add_objective($index, $params)
246
    {
247
        if (empty($params[0])) {
248
            return null;
249
        }
250
        $this->objectives[$index] = $params;
251
        // Take the current maximum index to generate the objectives_count.
252
        if ((count($this->objectives) + 1) > $this->objectives_count) {
253
            $this->objectives_count = (count($this->objectives) + 1);
254
        }
255
    }
256
257
    /**
258
     * Closes/stops the item viewing. Finalises runtime values.
259
     * If required, save to DB.
260
     *
261
     * @return bool True on success, false otherwise
262
     */
263
    public function close()
264
    {
265
        if (self::DEBUG > 0) {
266
            error_log('learnpathItem::close()', 0);
267
        }
268
        $this->current_stop_time = time();
269
        $type = $this->get_type();
270
        if ($type != 'sco') {
271
            if ($type == TOOL_QUIZ || $type == TOOL_HOTPOTATOES) {
272
                $this->get_status(
273
                    true,
274
                    true
275
                ); // Update status (second option forces the update).
276
            } else {
277
                $this->status = $this->possible_status[2];
278
            }
279
        }
280
        if ($this->save_on_close) {
281
            $this->save();
282
        }
283
284
        return true;
285
    }
286
287
    /**
288
     * Deletes all traces of this item in the database.
289
     *
290
     * @return bool true. Doesn't check for errors yet.
291
     */
292
    public function delete()
293
    {
294
        if (self::DEBUG > 0) {
295
            error_log('learnpath_item::delete() for item '.$this->db_id, 0);
296
        }
297
        $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
298
        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
299
        $course_id = api_get_course_int_id();
300
301
        $sql = "DELETE FROM $lp_item_view
302
                WHERE c_id = $course_id AND lp_item_id = ".$this->db_id;
303
        Database::query($sql);
304
305
        $sql = "SELECT * FROM $lp_item
306
                WHERE iid = ".$this->db_id;
307
        $res_sel = Database::query($sql);
308
        if (Database::num_rows($res_sel) < 1) {
309
            return false;
310
        }
311
312
        $sql = "DELETE FROM $lp_item
313
                WHERE iid = ".$this->db_id;
314
        Database::query($sql);
315
316
        if (api_get_setting('search_enabled') == 'true') {
317
            if (!is_null($this->search_did)) {
318
                $di = new ChamiloIndexer();
319
                $di->remove_document($this->search_did);
320
            }
321
        }
322
323
        return true;
324
    }
325
326
    /**
327
     * Drops a child from the children array.
328
     *
329
     * @param string $item index of child item to drop
330
     */
331
    public function drop_child($item)
332
    {
333
        if (!empty($item)) {
334
            foreach ($this->children as $index => $child) {
335
                if ($child == $item) {
336
                    $this->children[$index] = null;
337
                }
338
            }
339
        }
340
    }
341
342
    /**
343
     * Gets the current attempt_id for this user on this item.
344
     *
345
     * @return int attempt_id for this item view by this user or 1 if none defined
346
     */
347
    public function get_attempt_id()
348
    {
349
        $res = 1;
350
        if (!empty($this->attempt_id)) {
351
            $res = (int) $this->attempt_id;
352
        }
353
354
        return $res;
355
    }
356
357
    /**
358
     * Gets a list of the item's children.
359
     *
360
     * @return array Array of children items IDs
361
     */
362
    public function get_children()
363
    {
364
        $list = [];
365
        foreach ($this->children as $child) {
366
            if (!empty($child)) {
367
                $list[] = $child;
368
            }
369
        }
370
371
        return $list;
372
    }
373
374
    /**
375
     * Gets the core_exit value from the database.
376
     */
377
    public function get_core_exit()
378
    {
379
        return $this->core_exit;
380
    }
381
382
    /**
383
     * Gets the credit information (rather scorm-stuff) based on current status
384
     * and reinit autorization. Credit tells the sco(content) if Chamilo will
385
     * record the data it is sent (credit) or not (no-credit).
386
     *
387
     * @return string 'credit' or 'no-credit'. Defaults to 'credit'
388
     *                Because if we don't know enough about this item, it's probably because
389
     *                it was never used before.
390
     */
391
    public function get_credit()
392
    {
393
        if (self::DEBUG > 1) {
394
            error_log('learnpathItem::get_credit()', 0);
395
        }
396
        $credit = 'credit';
397
        // Now check the value of prevent_reinit (if it's 0, return credit as
398
        // the default was).
399
        // If prevent_reinit == 1 (or more).
400
        if ($this->get_prevent_reinit() != 0) {
401
            // If status is not attempted or incomplete, credit anyway.
402
            // Otherwise:
403
            // Check the status in the database rather than in the object, as
404
            // checking in the object would always return "no-credit" when we
405
            // want to set it to completed.
406
            $status = $this->get_status(true);
407
            if (self::DEBUG > 2) {
408
                error_log(
409
                    'learnpathItem::get_credit() - get_prevent_reinit!=0 and '.
410
                    'status is '.$status,
411
                    0
412
                );
413
            }
414
            //0=not attempted - 1 = incomplete
415
            if ($status != $this->possible_status[0] &&
416
                $status != $this->possible_status[1]
417
            ) {
418
                $credit = 'no-credit';
419
            }
420
        }
421
        if (self::DEBUG > 1) {
422
            error_log("learnpathItem::get_credit() returns: $credit");
423
        }
424
425
        return $credit;
426
    }
427
428
    /**
429
     * Gets the current start time property.
430
     *
431
     * @return int Current start time, or current time if none
432
     */
433
    public function get_current_start_time()
434
    {
435
        if (empty($this->current_start_time)) {
436
            return time();
437
        }
438
439
        return $this->current_start_time;
440
    }
441
442
    /**
443
     * Gets the item's description.
444
     *
445
     * @return string Description
446
     */
447
    public function get_description()
448
    {
449
        if (empty($this->description)) {
450
            return '';
451
        }
452
453
        return $this->description;
454
    }
455
456
    /**
457
     * Gets the file path from the course's root directory, no matter what
458
     * tool it is from.
459
     *
460
     * @param string $path_to_scorm_dir
461
     *
462
     * @return string The file path, or an empty string if there is no file
463
     *                attached, or '-1' if the file must be replaced by an error page
464
     */
465
    public function get_file_path($path_to_scorm_dir = '')
466
    {
467
        $course_id = api_get_course_int_id();
468
        if (self::DEBUG > 0) {
469
            error_log('learnpathItem::get_file_path()', 0);
470
        }
471
        $path = $this->get_path();
472
        $type = $this->get_type();
473
474
        if (empty($path)) {
475
            if ($type == 'dir') {
476
                return '';
477
            } else {
478
                return '-1';
479
            }
480
        } elseif ($path == strval(intval($path))) {
481
            // The path is numeric, so it is a reference to a Chamilo object.
482
            switch ($type) {
483
                case 'dir':
484
                    return '';
485
                case TOOL_DOCUMENT:
486
                    $table_doc = Database::get_course_table(TABLE_DOCUMENT);
487
                    $sql = 'SELECT path
488
                            FROM '.$table_doc.'
489
                            WHERE
490
                                c_id = '.$course_id.' AND
491
                                iid = '.$path;
492
                    $res = Database::query($sql);
493
                    $row = Database::fetch_array($res);
494
                    $real_path = 'document'.$row['path'];
495
496
                    return $real_path;
497
                case TOOL_STUDENTPUBLICATION:
498
                case TOOL_QUIZ:
499
                case TOOL_FORUM:
500
                case TOOL_THREAD:
501
                case TOOL_LINK:
502
                default:
503
                    return '-1';
504
            }
505
        } else {
506
            if (!empty($path_to_scorm_dir)) {
507
                $path = $path_to_scorm_dir.$path;
508
            }
509
510
            return $path;
511
        }
512
    }
513
514
    /**
515
     * Gets the DB ID.
516
     *
517
     * @return int Database ID for the current item
518
     */
519
    public function get_id()
520
    {
521
        if (!empty($this->db_id)) {
522
            return $this->db_id;
523
        }
524
        // TODO: Check this return value is valid for children classes (SCORM?).
525
        return 0;
526
    }
527
528
    /**
529
     * Loads the interactions into the item object, from the database.
530
     * If object interactions exist, they will be overwritten by this function,
531
     * using the database elements only.
532
     */
533
    public function load_interactions()
534
    {
535
        $this->interactions = [];
536
        $course_id = api_get_course_int_id();
537
        $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
538
        $sql = "SELECT id FROM $tbl
539
                WHERE
540
                    c_id = $course_id AND
541
                    lp_item_id = ".$this->db_id." AND
542
                    lp_view_id = ".$this->view_id." AND
543
                    view_count = ".$this->get_view_count();
544
        $res = Database::query($sql);
545
        if (Database::num_rows($res) > 0) {
546
            $row = Database::fetch_array($res);
547
            $lp_iv_id = $row[0];
548
            $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
549
            $sql = "SELECT * FROM $iva_table
550
                    WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
551
            $res_sql = Database::query($sql);
552
            while ($row = Database::fetch_array($res_sql)) {
553
                $this->interactions[$row['interaction_id']] = [
554
                    $row['interaction_id'],
555
                    $row['interaction_type'],
556
                    $row['weighting'],
557
                    $row['completion_time'],
558
                    $row['correct_responses'],
559
                    $row['student_responses'],
560
                    $row['result'],
561
                    $row['latency'],
562
                ];
563
            }
564
        }
565
    }
566
567
    /**
568
     * Gets the current count of interactions recorded in the database.
569
     *
570
     * @param bool $checkdb Whether to count from database or not (defaults to no)
571
     *
572
     * @return int The current number of interactions recorder
573
     */
574
    public function get_interactions_count($checkdb = false)
575
    {
576
        $return = 0;
577
        if (api_is_invitee()) {
578
            // If the user is an invitee, we consider there's no interaction
579
            return 0;
580
        }
581
        $course_id = api_get_course_int_id();
582
583
        if ($checkdb) {
584
            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
585
            $sql = "SELECT iid FROM $tbl
586
                    WHERE
587
                        c_id = $course_id AND
588
                        lp_item_id = ".$this->db_id." AND
589
                        lp_view_id = ".$this->view_id." AND
590
                        view_count = ".$this->get_attempt_id();
591
            $res = Database::query($sql);
592
            if (Database::num_rows($res) > 0) {
593
                $row = Database::fetch_array($res);
594
                $lp_iv_id = $row[0];
595
                $iva_table = Database::get_course_table(
596
                    TABLE_LP_IV_INTERACTION
597
                );
598
                $sql = "SELECT count(id) as mycount
599
                        FROM $iva_table
600
                        WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
601
                $res_sql = Database::query($sql);
602
                if (Database::num_rows($res_sql) > 0) {
603
                    $row = Database::fetch_array($res_sql);
604
                    $return = $row['mycount'];
605
                }
606
            }
607
        } else {
608
            if (!empty($this->interactions_count)) {
609
                $return = $this->interactions_count;
610
            }
611
        }
612
613
        return $return;
614
    }
615
616
    /**
617
     * Gets the JavaScript array content to fill the interactions array.
618
     *
619
     * @param bool $checkdb Whether to check directly into the database (default no)
620
     *
621
     * @return string An empty string if no interaction, a JS array definition otherwise
622
     */
623
    public function get_interactions_js_array($checkdb = false)
624
    {
625
        $return = '';
626
        if ($checkdb) {
627
            $this->load_interactions(true);
628
        }
629
        foreach ($this->interactions as $id => $in) {
630
            $return .= "[
631
                '$id',
632
                '".$in[1]."',
633
                '".$in[2]."',
634
                '".$in[3]."',
635
                '".$in[4]."',
636
                '".$in[5]."',
637
                '".$in[6]."',
638
                '".$in[7]."'],";
639
        }
640
        if (!empty($return)) {
641
            $return = substr($return, 0, -1);
642
        }
643
644
        return $return;
645
    }
646
647
    /**
648
     * Gets the current count of objectives recorded in the database.
649
     *
650
     * @return int The current number of objectives recorder
651
     */
652
    public function get_objectives_count()
653
    {
654
        $res = 0;
655
        if (!empty($this->objectives_count)) {
656
            $res = $this->objectives_count;
657
        }
658
659
        return $res;
660
    }
661
662
    /**
663
     * Gets the launch_data field found in imsmanifests (this is SCORM- or
664
     * AICC-related, really).
665
     *
666
     * @return string Launch data as found in imsmanifest and stored in
667
     *                Chamilo (read only). Defaults to ''.
668
     */
669
    public function get_launch_data()
670
    {
671
        if (!empty($this->launch_data)) {
672
            return str_replace(
673
                ["\r", "\n", "'"],
674
                ['\r', '\n', "\\'"],
675
                $this->launch_data
676
            );
677
        }
678
679
        return '';
680
    }
681
682
    /**
683
     * Gets the lesson location.
684
     *
685
     * @return string lesson location as recorded by the SCORM and AICC
686
     *                elements. Defaults to ''
687
     */
688
    public function get_lesson_location()
689
    {
690
        if (!empty($this->lesson_location)) {
691
            return str_replace(
692
                ["\r", "\n", "'"],
693
                ['\r', '\n', "\\'"],
694
                $this->lesson_location
695
            );
696
        }
697
698
        return '';
699
    }
700
701
    /**
702
     * Gets the lesson_mode (scorm feature, but might be used by aicc as well
703
     * as chamilo paths).
704
     *
705
     * The "browse" mode is not supported yet (because there is no such way of
706
     * seeing a sco in Chamilo)
707
     *
708
     * @return string 'browse','normal' or 'review'. Defaults to 'normal'
709
     */
710
    public function get_lesson_mode()
711
    {
712
        $mode = 'normal';
713
        if ($this->get_prevent_reinit() != 0) {
714
            // If prevent_reinit == 0
715
            $my_status = $this->get_status();
716
            if ($my_status != $this->possible_status[0] && $my_status != $this->possible_status[1]) {
717
                $mode = 'review';
718
            }
719
        }
720
721
        return $mode;
722
    }
723
724
    /**
725
     * Gets the depth level.
726
     *
727
     * @return int Level. Defaults to 0
728
     */
729
    public function get_level()
730
    {
731
        if (empty($this->level)) {
732
            return 0;
733
        }
734
735
        return $this->level;
736
    }
737
738
    /**
739
     * Gets the mastery score.
740
     */
741
    public function get_mastery_score()
742
    {
743
        if (isset($this->mastery_score)) {
744
            return $this->mastery_score;
745
        }
746
747
        return -1;
748
    }
749
750
    /**
751
     * Gets the maximum (score).
752
     *
753
     * @return int Maximum score. Defaults to 100 if nothing else is defined
754
     */
755
    public function get_max()
756
    {
757
        if ($this->type === 'sco') {
758
            if (!empty($this->view_max_score) && $this->view_max_score > 0) {
759
                return $this->view_max_score;
760
            } else {
761
                if (!empty($this->max_score)) {
762
                    return $this->max_score;
763
                }
764
765
                return 100;
766
            }
767
        } else {
768
            if (!empty($this->max_score)) {
769
                return $this->max_score;
770
            }
771
772
            return 100;
773
        }
774
    }
775
776
    /**
777
     * Gets the maximum time allowed for this user in this attempt on this item.
778
     *
779
     * @return string Time string in SCORM format
780
     *                (HH:MM:SS or HH:MM:SS.SS or HHHH:MM:SS.SS)
781
     */
782
    public function get_max_time_allowed()
783
    {
784
        if (!empty($this->max_time_allowed)) {
785
            return $this->max_time_allowed;
786
        }
787
788
        return '';
789
    }
790
791
    /**
792
     * Gets the minimum (score).
793
     *
794
     * @return int Minimum score. Defaults to 0
795
     */
796
    public function get_min()
797
    {
798
        if (!empty($this->min_score)) {
799
            return $this->min_score;
800
        }
801
802
        return 0;
803
    }
804
805
    /**
806
     * Gets the parent ID.
807
     *
808
     * @return int Parent ID. Defaults to null
809
     */
810
    public function get_parent()
811
    {
812
        if (!empty($this->parent)) {
813
            return $this->parent;
814
        }
815
        // TODO: Check this return value is valid for children classes (SCORM?).
816
        return null;
817
    }
818
819
    /**
820
     * Gets the path attribute.
821
     *
822
     * @return string Path. Defaults to ''
823
     */
824
    public function get_path()
825
    {
826
        if (empty($this->path)) {
827
            return '';
828
        }
829
830
        return $this->path;
831
    }
832
833
    /**
834
     * Gets the prerequisites string.
835
     *
836
     * @return string empty string or prerequisites string if defined
837
     */
838
    public function get_prereq_string()
839
    {
840
        if (!empty($this->prereq_string)) {
841
            return $this->prereq_string;
842
        }
843
844
        return '';
845
    }
846
847
    /**
848
     * Gets the prevent_reinit attribute value (and sets it if not set already).
849
     *
850
     * @return int 1 or 0 (defaults to 1)
851
     */
852
    public function get_prevent_reinit()
853
    {
854
        if (self::DEBUG > 2) {
855
            error_log('learnpathItem::get_prevent_reinit()', 0);
856
        }
857
        if (!isset($this->prevent_reinit)) {
858
            if (!empty($this->lp_id)) {
859
                $table = Database::get_course_table(TABLE_LP_MAIN);
860
                $sql = "SELECT prevent_reinit
861
                        FROM $table
862
                        WHERE iid = ".$this->lp_id;
863
                $res = Database::query($sql);
864
                if (Database::num_rows($res) < 1) {
865
                    $this->error = "Could not find parent learnpath in lp table";
866
                    if (self::DEBUG > 2) {
867
                        error_log(
868
                            'New LP - End of learnpathItem::get_prevent_reinit() - Returning false',
869
                            0
870
                        );
871
                    }
872
873
                    return false;
874
                } else {
875
                    $row = Database::fetch_array($res);
876
                    $this->prevent_reinit = $row['prevent_reinit'];
877
                }
878
            } else {
879
                // Prevent reinit is always 1 by default - see learnpath.class.php
880
                $this->prevent_reinit = 1;
881
            }
882
        }
883
        if (self::DEBUG > 2) {
884
            error_log(
885
                'New LP - End of learnpathItem::get_prevent_reinit() - Returned '.$this->prevent_reinit,
886
                0
887
            );
888
        }
889
890
        return $this->prevent_reinit;
891
    }
892
893
    /**
894
     * Returns 1 if seriousgame_mode is activated, 0 otherwise.
895
     *
896
     * @return int (0 or 1)
897
     *
898
     * @deprecated seriousgame_mode seems not to be used
899
     *
900
     * @author ndiechburg <[email protected]>
901
     */
902
    public function get_seriousgame_mode()
903
    {
904
        if (!isset($this->seriousgame_mode)) {
905
            if (!empty($this->lp_id)) {
906
                $table = Database::get_course_table(TABLE_LP_MAIN);
907
                $sql = "SELECT seriousgame_mode
908
                        FROM $table
909
                        WHERE iid = ".$this->lp_id;
910
                $res = Database::query($sql);
911
                if (Database::num_rows($res) < 1) {
912
                    $this->error = 'Could not find parent learnpath in learnpath table';
913
914
                    return false;
915
                } else {
916
                    $row = Database::fetch_array($res);
917
                    $this->seriousgame_mode = isset($row['seriousgame_mode']) ? $row['seriousgame_mode'] : 0;
918
                }
919
            } else {
920
                $this->seriousgame_mode = 0; //SeriousGame mode is always off by default
921
            }
922
        }
923
924
        return $this->seriousgame_mode;
925
    }
926
927
    /**
928
     * Gets the item's reference column.
929
     *
930
     * @return string The item's reference field (generally used for SCORM identifiers)
931
     */
932
    public function get_ref()
933
    {
934
        return $this->ref;
935
    }
936
937
    /**
938
     * Gets the list of included resources as a list of absolute or relative
939
     * paths of resources included in the current item. This allows for a
940
     * better SCORM export. The list will generally include pictures, flash
941
     * objects, java applets, or any other stuff included in the source of the
942
     * current item. The current item is expected to be an HTML file. If it
943
     * is not, then the function will return and empty list.
944
     *
945
     * @param string $type        (one of the Chamilo tools) - optional (otherwise takes the current item's type)
946
     * @param string $abs_path    absolute file path - optional (otherwise takes the current item's path)
947
     * @param int    $recursivity level of recursivity we're in
948
     *
949
     * @return array List of file paths.
950
     *               An additional field containing 'local' or 'remote' helps determine if
951
     *               the file should be copied into the zip or just linked
952
     */
953
    public function get_resources_from_source(
954
        $type = null,
955
        $abs_path = null,
956
        $recursivity = 1
957
    ) {
958
        $max = 5;
959
        if ($recursivity > $max) {
960
            return [];
961
        }
962
963
        $type = empty($type) ? $this->get_type() : $type;
964
965
        if (!isset($abs_path)) {
966
            $path = $this->get_file_path();
967
            $abs_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$path;
968
        }
969
970
        $files_list = [];
971
        switch ($type) {
972
            case TOOL_DOCUMENT:
973
            case TOOL_QUIZ:
974
            case 'sco':
975
                // Get the document and, if HTML, open it.
976
                if (!is_file($abs_path)) {
977
                    // The file could not be found.
978
                    return false;
979
                }
980
981
                // for now, read the whole file in one go (that's gonna be
982
                // a problem when the file is too big).
983
                $info = pathinfo($abs_path);
984
                $ext = $info['extension'];
985
986
                switch (strtolower($ext)) {
987
                    case 'html':
988
                    case 'htm':
989
                    case 'shtml':
990
                    case 'css':
991
                        $wantedAttributes = [
992
                            'src',
993
                            'url',
994
                            '@import',
995
                            'href',
996
                            'value',
997
                        ];
998
999
                        // Parse it for included resources.
1000
                        $fileContent = file_get_contents($abs_path);
1001
                        // Get an array of attributes from the HTML source.
1002
                        $attributes = DocumentManager::parse_HTML_attributes(
1003
                            $fileContent,
1004
                            $wantedAttributes
1005
                        );
1006
1007
                        // Look at 'src' attributes in this file
1008
                        foreach ($wantedAttributes as $attr) {
1009
                            if (isset($attributes[$attr])) {
1010
                                // Find which kind of path these are (local or remote).
1011
                                $sources = $attributes[$attr];
1012
1013
                                foreach ($sources as $source) {
1014
                                    // Skip what is obviously not a resource.
1015
                                    if (strpos($source, "+this.")) {
1016
                                        continue;
1017
                                    } // javascript code - will still work unaltered.
1018
                                    if (strpos($source, '.') === false) {
1019
                                        continue;
1020
                                    } // No dot, should not be an external file anyway.
1021
                                    if (strpos($source, 'mailto:')) {
1022
                                        continue;
1023
                                    } // mailto link.
1024
                                    if (strpos($source, ';') &&
1025
                                        !strpos($source, '&amp;')
1026
                                    ) {
1027
                                        continue;
1028
                                    } // Avoid code - that should help.
1029
1030
                                    if ($attr == 'value') {
1031
                                        if (strpos($source, 'mp3file')) {
1032
                                            $files_list[] = [
1033
                                                substr(
1034
                                                    $source,
1035
                                                    0,
1036
                                                    strpos(
1037
                                                        $source,
1038
                                                        '.swf'
1039
                                                    ) + 4
1040
                                                ),
1041
                                                'local',
1042
                                                'abs',
1043
                                            ];
1044
                                            $mp3file = substr(
1045
                                                $source,
1046
                                                strpos(
1047
                                                    $source,
1048
                                                    'mp3file='
1049
                                                ) + 8
1050
                                            );
1051
                                            if (substr($mp3file, 0, 1) == '/') {
1052
                                                $files_list[] = [
1053
                                                    $mp3file,
1054
                                                    'local',
1055
                                                    'abs',
1056
                                                ];
1057
                                            } else {
1058
                                                $files_list[] = [
1059
                                                    $mp3file,
1060
                                                    'local',
1061
                                                    'rel',
1062
                                                ];
1063
                                            }
1064
                                        } elseif (strpos($source, 'flv=') === 0) {
1065
                                            $source = substr($source, 4);
1066
                                            if (strpos($source, '&') > 0) {
1067
                                                $source = substr(
1068
                                                    $source,
1069
                                                    0,
1070
                                                    strpos($source, '&')
1071
                                                );
1072
                                            }
1073
                                            if (strpos($source, '://') > 0) {
1074
                                                if (strpos($source, api_get_path(WEB_PATH)) !== false) {
1075
                                                    // We found the current portal url.
1076
                                                    $files_list[] = [
1077
                                                        $source,
1078
                                                        'local',
1079
                                                        'url',
1080
                                                    ];
1081
                                                } else {
1082
                                                    // We didn't find any trace of current portal.
1083
                                                    $files_list[] = [
1084
                                                        $source,
1085
                                                        'remote',
1086
                                                        'url',
1087
                                                    ];
1088
                                                }
1089
                                            } else {
1090
                                                $files_list[] = [
1091
                                                    $source,
1092
                                                    'local',
1093
                                                    'abs',
1094
                                                ];
1095
                                            }
1096
                                            continue; // Skipping anything else to avoid two entries
1097
                                            //(while the others can have sub-files in their url, flv's can't).
1098
                                        }
1099
                                    }
1100
1101
                                    if (strpos($source, '://') > 0) {
1102
                                        // Cut at '?' in a URL with params.
1103
                                        if (strpos($source, '?') > 0) {
1104
                                            $second_part = substr(
1105
                                                $source,
1106
                                                strpos($source, '?')
1107
                                            );
1108
                                            if (strpos($second_part, '://') > 0) {
1109
                                                // If the second part of the url contains a url too,
1110
                                                // treat the second one before cutting.
1111
                                                $pos1 = strpos(
1112
                                                    $second_part,
1113
                                                    '='
1114
                                                );
1115
                                                $pos2 = strpos(
1116
                                                    $second_part,
1117
                                                    '&'
1118
                                                );
1119
                                                $second_part = substr(
1120
                                                    $second_part,
1121
                                                    $pos1 + 1,
1122
                                                    $pos2 - ($pos1 + 1)
1123
                                                );
1124
                                                if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
1125
                                                    // We found the current portal url.
1126
                                                    $files_list[] = [
1127
                                                        $second_part,
1128
                                                        'local',
1129
                                                        'url',
1130
                                                    ];
1131
                                                    $in_files_list[] = self::get_resources_from_source(
1132
                                                        TOOL_DOCUMENT,
1133
                                                        $second_part,
1134
                                                        $recursivity + 1
1135
                                                    );
1136
                                                    if (count($in_files_list) > 0) {
1137
                                                        $files_list = array_merge(
1138
                                                            $files_list,
1139
                                                            $in_files_list
1140
                                                        );
1141
                                                    }
1142
                                                } else {
1143
                                                    // We didn't find any trace of current portal.
1144
                                                    $files_list[] = [
1145
                                                        $second_part,
1146
                                                        'remote',
1147
                                                        'url',
1148
                                                    ];
1149
                                                }
1150
                                            } elseif (strpos($second_part, '=') > 0) {
1151
                                                if (substr($second_part, 0, 1) === '/') {
1152
                                                    // Link starts with a /,
1153
                                                    // making it absolute (relative to DocumentRoot).
1154
                                                    $files_list[] = [
1155
                                                        $second_part,
1156
                                                        'local',
1157
                                                        'abs',
1158
                                                    ];
1159
                                                    $in_files_list[] = self::get_resources_from_source(
1160
                                                        TOOL_DOCUMENT,
1161
                                                        $second_part,
1162
                                                        $recursivity + 1
1163
                                                    );
1164
                                                    if (count($in_files_list) > 0) {
1165
                                                        $files_list = array_merge(
1166
                                                            $files_list,
1167
                                                            $in_files_list
1168
                                                        );
1169
                                                    }
1170
                                                } elseif (strstr($second_part, '..') === 0) {
1171
                                                    // Link is relative but going back in the hierarchy.
1172
                                                    $files_list[] = [
1173
                                                        $second_part,
1174
                                                        'local',
1175
                                                        'rel',
1176
                                                    ];
1177
                                                    $dir = dirname(
1178
                                                        $abs_path
1179
                                                    );
1180
                                                    $new_abs_path = realpath(
1181
                                                        $dir.'/'.$second_part
1182
                                                    );
1183
                                                    $in_files_list[] = self::get_resources_from_source(
1184
                                                        TOOL_DOCUMENT,
1185
                                                        $new_abs_path,
1186
                                                        $recursivity + 1
1187
                                                    );
1188
                                                    if (count($in_files_list) > 0) {
1189
                                                        $files_list = array_merge(
1190
                                                            $files_list,
1191
                                                            $in_files_list
1192
                                                        );
1193
                                                    }
1194
                                                } else {
1195
                                                    // No starting '/', making it relative to current document's path.
1196
                                                    if (substr($second_part, 0, 2) == './') {
1197
                                                        $second_part = substr(
1198
                                                            $second_part,
1199
                                                            2
1200
                                                        );
1201
                                                    }
1202
                                                    $files_list[] = [
1203
                                                        $second_part,
1204
                                                        'local',
1205
                                                        'rel',
1206
                                                    ];
1207
                                                    $dir = dirname(
1208
                                                        $abs_path
1209
                                                    );
1210
                                                    $new_abs_path = realpath(
1211
                                                        $dir.'/'.$second_part
1212
                                                    );
1213
                                                    $in_files_list[] = self::get_resources_from_source(
1214
                                                        TOOL_DOCUMENT,
1215
                                                        $new_abs_path,
1216
                                                        $recursivity + 1
1217
                                                    );
1218
                                                    if (count($in_files_list) > 0) {
1219
                                                        $files_list = array_merge(
1220
                                                            $files_list,
1221
                                                            $in_files_list
1222
                                                        );
1223
                                                    }
1224
                                                }
1225
                                            }
1226
                                            // Leave that second part behind now.
1227
                                            $source = substr(
1228
                                                $source,
1229
                                                0,
1230
                                                strpos($source, '?')
1231
                                            );
1232
                                            if (strpos($source, '://') > 0) {
1233
                                                if (strpos($source, api_get_path(WEB_PATH)) !== false) {
1234
                                                    // We found the current portal url.
1235
                                                    $files_list[] = [
1236
                                                        $source,
1237
                                                        'local',
1238
                                                        'url',
1239
                                                    ];
1240
                                                    $in_files_list[] = self::get_resources_from_source(
1241
                                                        TOOL_DOCUMENT,
1242
                                                        $source,
1243
                                                        $recursivity + 1
1244
                                                    );
1245
                                                    if (count($in_files_list) > 0) {
1246
                                                        $files_list = array_merge(
1247
                                                            $files_list,
1248
                                                            $in_files_list
1249
                                                        );
1250
                                                    }
1251
                                                } else {
1252
                                                    // We didn't find any trace of current portal.
1253
                                                    $files_list[] = [
1254
                                                        $source,
1255
                                                        'remote',
1256
                                                        'url',
1257
                                                    ];
1258
                                                }
1259
                                            } else {
1260
                                                // No protocol found, make link local.
1261
                                                if (substr($source, 0, 1) === '/') {
1262
                                                    // Link starts with a /, making it absolute (relative to DocumentRoot).
1263
                                                    $files_list[] = [
1264
                                                        $source,
1265
                                                        'local',
1266
                                                        'abs',
1267
                                                    ];
1268
                                                    $in_files_list[] = self::get_resources_from_source(
1269
                                                        TOOL_DOCUMENT,
1270
                                                        $source,
1271
                                                        $recursivity + 1
1272
                                                    );
1273
                                                    if (count($in_files_list) > 0) {
1274
                                                        $files_list = array_merge(
1275
                                                            $files_list,
1276
                                                            $in_files_list
1277
                                                        );
1278
                                                    }
1279
                                                } elseif (strstr($source, '..') === 0) {
1280
                                                    // Link is relative but going back in the hierarchy.
1281
                                                    $files_list[] = [
1282
                                                        $source,
1283
                                                        'local',
1284
                                                        'rel',
1285
                                                    ];
1286
                                                    $dir = dirname(
1287
                                                        $abs_path
1288
                                                    );
1289
                                                    $new_abs_path = realpath(
1290
                                                        $dir.'/'.$source
1291
                                                    );
1292
                                                    $in_files_list[] = self::get_resources_from_source(
1293
                                                        TOOL_DOCUMENT,
1294
                                                        $new_abs_path,
1295
                                                        $recursivity + 1
1296
                                                    );
1297
                                                    if (count($in_files_list) > 0) {
1298
                                                        $files_list = array_merge(
1299
                                                            $files_list,
1300
                                                            $in_files_list
1301
                                                        );
1302
                                                    }
1303
                                                } else {
1304
                                                    // No starting '/', making it relative to current document's path.
1305
                                                    if (substr($source, 0, 2) == './') {
1306
                                                        $source = substr(
1307
                                                            $source,
1308
                                                            2
1309
                                                        );
1310
                                                    }
1311
                                                    $files_list[] = [
1312
                                                        $source,
1313
                                                        'local',
1314
                                                        'rel',
1315
                                                    ];
1316
                                                    $dir = dirname(
1317
                                                        $abs_path
1318
                                                    );
1319
                                                    $new_abs_path = realpath(
1320
                                                        $dir.'/'.$source
1321
                                                    );
1322
                                                    $in_files_list[] = self::get_resources_from_source(
1323
                                                        TOOL_DOCUMENT,
1324
                                                        $new_abs_path,
1325
                                                        $recursivity + 1
1326
                                                    );
1327
                                                    if (count($in_files_list) > 0) {
1328
                                                        $files_list = array_merge(
1329
                                                            $files_list,
1330
                                                            $in_files_list
1331
                                                        );
1332
                                                    }
1333
                                                }
1334
                                            }
1335
                                        }
1336
1337
                                        // Found some protocol there.
1338
                                        if (strpos($source, api_get_path(WEB_PATH)) !== false) {
1339
                                            // We found the current portal url.
1340
                                            $files_list[] = [
1341
                                                $source,
1342
                                                'local',
1343
                                                'url',
1344
                                            ];
1345
                                            $in_files_list[] = self::get_resources_from_source(
1346
                                                TOOL_DOCUMENT,
1347
                                                $source,
1348
                                                $recursivity + 1
1349
                                            );
1350
                                            if (count($in_files_list) > 0) {
1351
                                                $files_list = array_merge(
1352
                                                    $files_list,
1353
                                                    $in_files_list
1354
                                                );
1355
                                            }
1356
                                        } else {
1357
                                            // We didn't find any trace of current portal.
1358
                                            $files_list[] = [
1359
                                                $source,
1360
                                                'remote',
1361
                                                'url',
1362
                                            ];
1363
                                        }
1364
                                    } else {
1365
                                        // No protocol found, make link local.
1366
                                        if (substr($source, 0, 1) === '/') {
1367
                                            // Link starts with a /, making it absolute (relative to DocumentRoot).
1368
                                            $files_list[] = [
1369
                                                $source,
1370
                                                'local',
1371
                                                'abs',
1372
                                            ];
1373
                                            $in_files_list[] = self::get_resources_from_source(
1374
                                                TOOL_DOCUMENT,
1375
                                                $source,
1376
                                                $recursivity + 1
1377
                                            );
1378
                                            if (count($in_files_list) > 0) {
1379
                                                $files_list = array_merge(
1380
                                                    $files_list,
1381
                                                    $in_files_list
1382
                                                );
1383
                                            }
1384
                                        } elseif (strstr($source, '..') === 0) {
1385
                                            // Link is relative but going back in the hierarchy.
1386
                                            $files_list[] = [
1387
                                                $source,
1388
                                                'local',
1389
                                                'rel',
1390
                                            ];
1391
                                            $dir = dirname($abs_path);
1392
                                            $new_abs_path = realpath(
1393
                                                $dir.'/'.$source
1394
                                            );
1395
                                            $in_files_list[] = self::get_resources_from_source(
1396
                                                TOOL_DOCUMENT,
1397
                                                $new_abs_path,
1398
                                                $recursivity + 1
1399
                                            );
1400
                                            if (count($in_files_list) > 0) {
1401
                                                $files_list = array_merge(
1402
                                                    $files_list,
1403
                                                    $in_files_list
1404
                                                );
1405
                                            }
1406
                                        } else {
1407
                                            // No starting '/', making it relative to current document's path.
1408
                                            if (strpos($source, 'width=') ||
1409
                                                strpos($source, 'autostart=')
1410
                                            ) {
1411
                                                continue;
1412
                                            }
1413
1414
                                            if (substr($source, 0, 2) == './') {
1415
                                                $source = substr(
1416
                                                    $source,
1417
                                                    2
1418
                                                );
1419
                                            }
1420
                                            $files_list[] = [
1421
                                                $source,
1422
                                                'local',
1423
                                                'rel',
1424
                                            ];
1425
                                            $dir = dirname($abs_path);
1426
                                            $new_abs_path = realpath(
1427
                                                $dir.'/'.$source
1428
                                            );
1429
                                            $in_files_list[] = self::get_resources_from_source(
1430
                                                TOOL_DOCUMENT,
1431
                                                $new_abs_path,
1432
                                                $recursivity + 1
1433
                                            );
1434
                                            if (count($in_files_list) > 0) {
1435
                                                $files_list = array_merge(
1436
                                                    $files_list,
1437
                                                    $in_files_list
1438
                                                );
1439
                                            }
1440
                                        }
1441
                                    }
1442
                                }
1443
                            }
1444
                        }
1445
                        break;
1446
                    default:
1447
                        break;
1448
                }
1449
1450
                break;
1451
            default: // Ignore.
1452
                break;
1453
        }
1454
1455
        $checked_files_list = [];
1456
        $checked_array_list = [];
1457
        foreach ($files_list as $idx => $file) {
1458
            if (!empty($file[0])) {
1459
                if (!in_array($file[0], $checked_files_list)) {
1460
                    $checked_files_list[] = $files_list[$idx][0];
1461
                    $checked_array_list[] = $files_list[$idx];
1462
                }
1463
            }
1464
        }
1465
1466
        return $checked_array_list;
1467
    }
1468
1469
    /**
1470
     * Gets the score.
1471
     *
1472
     * @return float The current score or 0 if no score set yet
1473
     */
1474
    public function get_score()
1475
    {
1476
        $res = 0;
1477
        if (!empty($this->current_score)) {
1478
            $res = $this->current_score;
1479
        }
1480
1481
        return $res;
1482
    }
1483
1484
    /**
1485
     * Gets the item status.
1486
     *
1487
     * @param bool $check_db     Do or don't check into the database for the
1488
     *                           latest value. Optional. Default is true
1489
     * @param bool $update_local Do or don't update the local attribute
1490
     *                           value with what's been found in DB
1491
     *
1492
     * @return string Current status or 'Not attempted' if no status set yet
1493
     */
1494
    public function get_status($check_db = true, $update_local = false)
1495
    {
1496
        $course_id = api_get_course_int_id();
1497
        $debug = self::DEBUG;
1498
        if ($debug > 0) {
1499
            error_log('learnpathItem::get_status() on item '.$this->db_id, 0);
1500
        }
1501
        if ($check_db) {
1502
            if ($debug > 2) {
1503
                error_log('learnpathItem::get_status(): checking db', 0);
1504
            }
1505
            if (!empty($this->db_item_view_id) && !empty($course_id)) {
1506
                $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
1507
                $sql = "SELECT status FROM $table
1508
                        WHERE
1509
                            c_id = $course_id AND
1510
                            iid = '".$this->db_item_view_id."' AND
1511
                            view_count = '".$this->get_attempt_id()."'";
1512
                $res = Database::query($sql);
1513
                if (Database::num_rows($res) == 1) {
1514
                    $row = Database::fetch_array($res);
1515
                    if ($update_local) {
1516
                        $this->set_status($row['status']);
1517
                    }
1518
1519
                    return $row['status'];
1520
                }
1521
            }
1522
        } else {
1523
            if (!empty($this->status)) {
1524
                return $this->status;
1525
            }
1526
        }
1527
1528
        return $this->possible_status[0];
1529
    }
1530
1531
    /**
1532
     * Gets the suspend data.
1533
     */
1534
    public function get_suspend_data()
1535
    {
1536
        // TODO: Improve cleaning of breaklines ... it works but is it really
1537
        // a beautiful way to do it ?
1538
        if (!empty($this->current_data)) {
1539
            return str_replace(
1540
                ["\r", "\n", "'"],
1541
                ['\r', '\n', "\\'"],
1542
                $this->current_data
1543
            );
1544
        }
1545
1546
        return '';
1547
    }
1548
1549
    /**
1550
     * @param string $origin
1551
     * @param string $time
1552
     *
1553
     * @return string
1554
     */
1555
    public static function getScormTimeFromParameter(
1556
        $origin = 'php',
1557
        $time = null
1558
    ) {
1559
        $h = get_lang('h');
1560
        if (!isset($time)) {
1561
            if ($origin == 'js') {
1562
                return '00 : 00: 00';
1563
            }
1564
1565
            return '00 '.$h.' 00 \' 00"';
1566
        }
1567
1568
        return api_format_time($time, $origin);
1569
    }
1570
1571
    /**
1572
     * Gets the total time spent on this item view so far.
1573
     *
1574
     * @param string   $origin     Origin of the request. If coming from PHP,
1575
     *                             send formatted as xxhxx'xx", otherwise use scorm format 00:00:00
1576
     * @param int|null $given_time Given time is a default time to return formatted
1577
     * @param bool     $query_db   Whether to get the value from db or from memory
1578
     *
1579
     * @return string A string with the time in SCORM format
1580
     */
1581
    public function get_scorm_time(
1582
        $origin = 'php',
1583
        $given_time = null,
1584
        $query_db = false
1585
    ) {
1586
        $time = null;
1587
        $course_id = api_get_course_int_id();
1588
        if (!isset($given_time)) {
1589
            if (self::DEBUG > 2) {
1590
                error_log(
1591
                    'learnpathItem::get_scorm_time(): given time empty, current_start_time = '.$this->current_start_time,
1592
                    0
1593
                );
1594
            }
1595
            if ($query_db === true) {
1596
                $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
1597
                $sql = "SELECT start_time, total_time
1598
                        FROM $table
1599
                        WHERE
1600
                            c_id = $course_id AND
1601
                            iid = '".$this->db_item_view_id."' AND
1602
                            view_count = '".$this->get_attempt_id()."'";
1603
                $res = Database::query($sql);
1604
                $row = Database::fetch_array($res);
1605
                $start = $row['start_time'];
1606
                $stop = $start + $row['total_time'];
1607
            } else {
1608
                $start = $this->current_start_time;
1609
                $stop = $this->current_stop_time;
1610
            }
1611
            if (!empty($start)) {
1612
                if (!empty($stop)) {
1613
                    $time = $stop - $start;
1614
                } else {
1615
                    $time = time() - $start;
1616
                }
1617
            }
1618
        } else {
1619
            $time = $given_time;
1620
        }
1621
        if (self::DEBUG > 2) {
1622
            error_log(
1623
                'learnpathItem::get_scorm_time(): intermediate = '.$time,
1624
                0
1625
            );
1626
        }
1627
        $time = api_format_time($time, $origin);
1628
1629
        return $time;
1630
    }
1631
1632
    /**
1633
     * Get the extra terms (tags) that identify this item.
1634
     *
1635
     * @return mixed
1636
     */
1637
    public function get_terms()
1638
    {
1639
        $table = Database::get_course_table(TABLE_LP_ITEM);
1640
        $sql = "SELECT * FROM $table
1641
                WHERE iid = ".intval($this->db_id);
1642
        $res = Database::query($sql);
1643
        $row = Database::fetch_array($res);
1644
1645
        return $row['terms'];
1646
    }
1647
1648
    /**
1649
     * Returns the item's title.
1650
     *
1651
     * @return string Title
1652
     */
1653
    public function get_title()
1654
    {
1655
        if (empty($this->title)) {
1656
            return '';
1657
        }
1658
1659
        return $this->title;
1660
    }
1661
1662
    /**
1663
     * Returns the total time used to see that item.
1664
     *
1665
     * @return int Total time
1666
     */
1667
    public function get_total_time()
1668
    {
1669
        $debug = self::DEBUG;
1670
        if ($debug) {
1671
            error_log(
1672
                'learnpathItem::get_total_time() for item '.$this->db_id.
1673
                ' - Initially, current_start_time = '.$this->current_start_time.
1674
                ' and current_stop_time = '.$this->current_stop_time,
1675
                0
1676
            );
1677
        }
1678
        if ($this->current_start_time == 0) {
1679
            // Shouldn't be necessary thanks to the open() method.
1680
            if ($debug) {
1681
                error_log(
1682
                    'learnpathItem::get_total_time() - Current start time was empty',
1683
                    0
1684
                );
1685
            }
1686
            $this->current_start_time = time();
1687
        }
1688
1689
        if (time() < $this->current_stop_time ||
1690
            $this->current_stop_time == 0
1691
        ) {
1692
            if ($debug) {
1693
                error_log(
1694
                    'learnpathItem::get_total_time() - Current stop time was '
1695
                    .'greater than the current time or was empty',
1696
                    0
1697
                );
1698
            }
1699
            // If this case occurs, then we risk to write huge time data in db.
1700
            // In theory, stop time should be *always* updated here, but it
1701
            // might be used in some unknown goal.
1702
            $this->current_stop_time = time();
1703
        }
1704
1705
        $time = $this->current_stop_time - $this->current_start_time;
1706
1707
        if ($time < 0) {
1708
            if ($debug) {
1709
                error_log(
1710
                    'learnpathItem::get_total_time() - Time smaller than 0. Returning 0',
1711
                    0
1712
                );
1713
            }
1714
1715
            return 0;
1716
        } else {
1717
            $time = $this->fixAbusiveTime($time);
1718
            if ($debug) {
1719
                error_log(
1720
                    'Current start time = '.$this->current_start_time.', current stop time = '.
1721
                    $this->current_stop_time.' Returning '.$time."-----------\n"
1722
                );
1723
            }
1724
1725
            return $time;
1726
        }
1727
    }
1728
1729
    /**
1730
     * Sometimes time recorded for a learning path item is superior to the maximum allowed duration of the session.
1731
     * In this case, this session resets the time for that particular learning path item to 5 minutes
1732
     * (something more realistic, that is also used when leaving the portal without closing one's session).
1733
     *
1734
     * @param int $time
1735
     *
1736
     * @return int
1737
     */
1738
    public function fixAbusiveTime($time)
1739
    {
1740
        // Code based from Event::courseLogout
1741
        $sessionLifetime = api_get_configuration_value('session_lifetime');
1742
        // If session life time too big use 1 hour
1743
        if (empty($sessionLifetime) || $sessionLifetime > 86400) {
1744
            $sessionLifetime = 3600;
1745
        }
1746
1747
        if (!Tracking::minimumTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
1748
            $fixedAddedMinute = 5 * 60; // Add only 5 minutes
1749
            if ($time > $sessionLifetime) {
1750
                error_log("fixAbusiveTime: Total time is too big: $time replaced with: $fixedAddedMinute");
1751
                error_log("item_id : ".$this->db_id." lp_item_view.iid: ".$this->db_item_view_id);
1752
                $time = $fixedAddedMinute;
1753
            }
1754
1755
            return $time;
1756
        } else {
1757
            // Calulate minimum and accumulated time
1758
            $user_id = api_get_user_id();
1759
            $myLP = learnpath::getLpFromSession(api_get_course_id(), $this->lp_id, $user_id);
1760
            $timeLp = $myLP->getAccumulateWorkTime();
1761
            $timeTotalCourse = $myLP->getAccumulateWorkTimeTotalCourse();
1762
            /*
1763
            $timeLp = $_SESSION['oLP']->getAccumulateWorkTime();
1764
            $timeTotalCourse = $_SESSION['oLP']->getAccumulateWorkTimeTotalCourse();
1765
            */
1766
            // Minimum connection percentage
1767
            $perc = 100;
1768
            // Time from the course
1769
            $tc = $timeTotalCourse;
1770
            /*if (!empty($sessionId) && $sessionId != 0) {
1771
                $sql = "SELECT hours, perc FROM plugin_licences_course_session WHERE session_id = $sessionId";
1772
                $res = Database::query($sql);
1773
                if (Database::num_rows($res) > 0) {
1774
                    $aux = Database::fetch_assoc($res);
1775
                    $perc = $aux['perc'];
1776
                    $tc = $aux['hours'] * 60;
1777
                }
1778
            }*/
1779
            // Percentage of the learning paths
1780
            $pl = 0;
1781
            if (!empty($timeTotalCourse)) {
1782
                $pl = $timeLp / $timeTotalCourse;
1783
            }
1784
1785
            // Minimum time for each learning path
1786
            $accumulateWorkTime = ($pl * $tc * $perc / 100);
1787
            $time_seg = intval($accumulateWorkTime * 60);
1788
1789
            if ($time_seg < $sessionLifetime) {
1790
                $sessionLifetime = $time_seg;
1791
            }
1792
1793
            if ($time > $sessionLifetime) {
1794
                $fixedAddedMinute = $time_seg + mt_rand(0, 300);
1795
                if (self::DEBUG > 2) {
1796
                    error_log("Total time is too big: $time replaced with: $fixedAddedMinute");
1797
                }
1798
                $time = $fixedAddedMinute;
1799
            }
1800
1801
            return $time;
1802
        }
1803
    }
1804
1805
    /**
1806
     * Gets the item type.
1807
     *
1808
     * @return string The item type (can be doc, dir, sco, asset)
1809
     */
1810
    public function get_type()
1811
    {
1812
        $res = 'asset';
1813
        if (!empty($this->type)) {
1814
            $res = $this->type;
1815
        }
1816
1817
        return $res;
1818
    }
1819
1820
    /**
1821
     * Gets the view count for this item.
1822
     *
1823
     * @return int Number of attempts or 0
1824
     */
1825
    public function get_view_count()
1826
    {
1827
        if (!empty($this->attempt_id)) {
1828
            return $this->attempt_id;
1829
        }
1830
1831
        return 0;
1832
    }
1833
1834
    /**
1835
     * Tells if an item is done ('completed','passed','succeeded') or not.
1836
     *
1837
     * @return bool True if the item is done ('completed','passed','succeeded'),
1838
     *              false otherwise
1839
     */
1840
    public function is_done()
1841
    {
1842
        $completedStatusList = [
1843
            'completed',
1844
            'passed',
1845
            'succeeded',
1846
            'failed',
1847
        ];
1848
1849
        if ($this->status_is($completedStatusList)) {
1850
            if (self::DEBUG > 2) {
1851
                error_log(
1852
                    'learnpath::is_done() - Item '.$this->get_id(
1853
                    ).' is complete',
1854
                    0
1855
                );
1856
            }
1857
1858
            return true;
1859
        } else {
1860
            if (self::DEBUG > 2) {
1861
                error_log(
1862
                    'learnpath::is_done() - Item '.$this->get_id(
1863
                    ).' is not complete',
1864
                    0
1865
                );
1866
            }
1867
1868
            return false;
1869
        }
1870
    }
1871
1872
    /**
1873
     * Tells if a restart is allowed (take it from $this->prevent_reinit and $this->status).
1874
     *
1875
     * @return int -1 if retaking the sco another time for credit is not allowed,
1876
     *             0 if it is not allowed but the item has to be finished
1877
     *             1 if it is allowed. Defaults to 1
1878
     */
1879
    public function isRestartAllowed()
1880
    {
1881
        $restart = 1;
1882
        $mystatus = $this->get_status(true);
1883
        if ($this->get_prevent_reinit() > 0) {
1884
            // If prevent_reinit == 1 (or more)
1885
            // If status is not attempted or incomplete, authorize retaking (of the same) anyway. Otherwise:
1886
            if ($mystatus != $this->possible_status[0] && $mystatus != $this->possible_status[1]) {
1887
                $restart = -1;
1888
            } else { //status incompleted or not attempted
1889
                $restart = 0;
1890
            }
1891
        } else {
1892
            if ($mystatus == $this->possible_status[0] || $mystatus == $this->possible_status[1]) {
1893
                $restart = -1;
1894
            }
1895
        }
1896
        if (self::DEBUG > 2) {
1897
            error_log(
1898
                'New LP - End of learnpathItem::isRestartAllowed() - Returning '.$restart,
1899
                0
1900
            );
1901
        }
1902
1903
        return $restart;
1904
    }
1905
1906
    /**
1907
     * Opens/launches the item. Initialises runtime values.
1908
     *
1909
     * @param bool $allow_new_attempt
1910
     *
1911
     * @return bool true on success, false on failure
1912
     */
1913
    public function open($allow_new_attempt = false)
1914
    {
1915
        if (self::DEBUG > 0) {
1916
            error_log('learnpathItem::open()', 0);
1917
        }
1918
        if ($this->prevent_reinit == 0) {
1919
            $this->current_score = 0;
1920
            $this->current_start_time = time();
1921
            // In this case, as we are opening the item, what is important to us
1922
            // is the database status, in order to know if this item has already
1923
            // been used in the past (rather than just loaded and modified by
1924
            // some javascript but not written in the database).
1925
            // If the database status is different from 'not attempted', we can
1926
            // consider this item has already been used, and as such we can
1927
            // open a new attempt. Otherwise, we'll just reuse the current
1928
            // attempt, which is generally created the first time the item is
1929
            // loaded (for example as part of the table of contents).
1930
            $stat = $this->get_status(true);
1931
            if ($allow_new_attempt && isset($stat) && ($stat != $this->possible_status[0])) {
1932
                $this->attempt_id = $this->attempt_id + 1; // Open a new attempt.
1933
            }
1934
            $this->status = $this->possible_status[1];
1935
        } else {
1936
            /*if ($this->current_start_time == 0) {
1937
                // Small exception for start time, to avoid amazing values.
1938
                $this->current_start_time = time();
1939
            }*/
1940
            // If we don't init start time here, the time is sometimes calculated from the last start time.
1941
            $this->current_start_time = time();
1942
        }
1943
    }
1944
1945
    /**
1946
     * Outputs the item contents.
1947
     *
1948
     * @return string HTML file (displayable in an <iframe>) or empty string if no path defined
1949
     */
1950
    public function output()
1951
    {
1952
        if (!empty($this->path) and is_file($this->path)) {
1953
            $output = '';
1954
            $output .= file_get_contents($this->path);
1955
1956
            return $output;
1957
        }
1958
1959
        return '';
1960
    }
1961
1962
    /**
1963
     * Parses the prerequisites string with the AICC logic language.
1964
     *
1965
     * @param string $prereqs_string The prerequisites string as it figures in imsmanifest.xml
1966
     * @param array  $items          Array of items in the current learnpath object.
1967
     *                               Although we're in the learnpathItem object, it's necessary to have
1968
     *                               a list of all items to be able to check the current item's prerequisites
1969
     * @param array  $refs_list      list of references
1970
     *                               (the "ref" column in the lp_item table) that are strings used in the
1971
     *                               expression of prerequisites
1972
     * @param int    $user_id        The user ID. In some cases like Chamilo quizzes,
1973
     *                               it's necessary to have the user ID to query other tables (like the results of quizzes)
1974
     *
1975
     * @return bool True if the list of prerequisites given is entirely satisfied, false otherwise
1976
     */
1977
    public function parse_prereq($prereqs_string, $items, $refs_list, $user_id)
1978
    {
1979
        $debug = self::DEBUG;
1980
        if ($debug > 0) {
1981
            error_log(
1982
                'learnpathItem::parse_prereq() for learnpath '.$this->lp_id.' with string '.$prereqs_string,
1983
                0
1984
            );
1985
        }
1986
1987
        $course_id = api_get_course_int_id();
1988
        $sessionId = api_get_session_id();
1989
1990
        // Deal with &, |, ~, =, <>, {}, ,, X*, () in reverse order.
1991
        $this->prereq_alert = '';
1992
1993
        // First parse all parenthesis by using a sequential loop
1994
        //  (looking for less-inclusives first).
1995
        if ($prereqs_string == '_true_') {
1996
            return true;
1997
        }
1998
1999
        if ($prereqs_string == '_false_') {
2000
            if (empty($this->prereq_alert)) {
2001
                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2002
            }
2003
2004
            return false;
2005
        }
2006
2007
        while (strpos($prereqs_string, '(') !== false) {
2008
            // Remove any () set and replace with its value.
2009
            $matches = [];
2010
            $res = preg_match_all(
2011
                '/(\(([^\(\)]*)\))/',
2012
                $prereqs_string,
2013
                $matches
2014
            );
2015
            if ($res) {
2016
                foreach ($matches[2] as $id => $match) {
2017
                    $str_res = $this->parse_prereq(
2018
                        $match,
2019
                        $items,
2020
                        $refs_list,
2021
                        $user_id
2022
                    );
2023
                    if ($str_res) {
2024
                        $prereqs_string = str_replace(
2025
                            $matches[1][$id],
2026
                            '_true_',
2027
                            $prereqs_string
2028
                        );
2029
                    } else {
2030
                        $prereqs_string = str_replace(
2031
                            $matches[1][$id],
2032
                            '_false_',
2033
                            $prereqs_string
2034
                        );
2035
                    }
2036
                }
2037
            }
2038
        }
2039
2040
        // Parenthesis removed, now look for ORs as it is the lesser-priority
2041
        //  binary operator (= always uses one text operand).
2042
        if (strpos($prereqs_string, '|') === false) {
2043
            if ($debug) {
2044
                error_log('New LP - Didnt find any OR, looking for AND', 0);
2045
            }
2046
            if (strpos($prereqs_string, '&') !== false) {
2047
                $list = explode('&', $prereqs_string);
2048
                if (count($list) > 1) {
2049
                    $andstatus = true;
2050
                    foreach ($list as $condition) {
2051
                        $andstatus = $andstatus && $this->parse_prereq(
2052
                            $condition,
2053
                            $items,
2054
                            $refs_list,
2055
                            $user_id
2056
                        );
2057
2058
                        if (!$andstatus) {
2059
                            if ($debug) {
2060
                                error_log(
2061
                                    'New LP - One condition in AND was false, short-circuit',
2062
                                    0
2063
                                );
2064
                            }
2065
                            break;
2066
                        }
2067
                    }
2068
2069
                    if (empty($this->prereq_alert) && !$andstatus) {
2070
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2071
                    }
2072
2073
                    return $andstatus;
2074
                } else {
2075
                    if (isset($items[$refs_list[$list[0]]])) {
2076
                        $status = $items[$refs_list[$list[0]]]->get_status(true);
2077
                        $returnstatus = ($status == $this->possible_status[2]) || ($status == $this->possible_status[3]);
2078
                        if (empty($this->prereq_alert) && !$returnstatus) {
2079
                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2080
                        }
2081
2082
                        return $returnstatus;
2083
                    }
2084
                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2085
2086
                    return false;
2087
                }
2088
            } else {
2089
                // No ORs found, now look for ANDs.
2090
                if ($debug) {
2091
                    error_log('New LP - Didnt find any AND, looking for =', 0);
2092
                }
2093
2094
                if (strpos($prereqs_string, '=') !== false) {
2095
                    if ($debug) {
2096
                        error_log('New LP - Found =, looking into it', 0);
2097
                    }
2098
                    // We assume '=' signs only appear when there's nothing else around.
2099
                    $params = explode('=', $prereqs_string);
2100
                    if (count($params) == 2) {
2101
                        // Right number of operands.
2102
                        if (isset($items[$refs_list[$params[0]]])) {
2103
                            $status = $items[$refs_list[$params[0]]]->get_status(true);
2104
                            $returnstatus = $status == $params[1];
2105
                            if (empty($this->prereq_alert) && !$returnstatus) {
2106
                                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2107
                            }
2108
2109
                            return $returnstatus;
2110
                        }
2111
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2112
2113
                        return false;
2114
                    }
2115
                } else {
2116
                    // No ANDs found, look for <>
2117
                    if ($debug) {
2118
                        error_log(
2119
                            'New LP - Didnt find any =, looking for <>',
2120
                            0
2121
                        );
2122
                    }
2123
2124
                    if (strpos($prereqs_string, '<>') !== false) {
2125
                        if ($debug) {
2126
                            error_log('New LP - Found <>, looking into it', 0);
2127
                        }
2128
                        // We assume '<>' signs only appear when there's nothing else around.
2129
                        $params = explode('<>', $prereqs_string);
2130
                        if (count($params) == 2) {
2131
                            // Right number of operands.
2132
                            if (isset($items[$refs_list[$params[0]]])) {
2133
                                $status = $items[$refs_list[$params[0]]]->get_status(true);
2134
                                $returnstatus = $status != $params[1];
2135
                                if (empty($this->prereq_alert) && !$returnstatus) {
2136
                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2137
                                }
2138
2139
                                return $returnstatus;
2140
                            }
2141
                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2142
2143
                            return false;
2144
                        }
2145
                    } else {
2146
                        // No <> found, look for ~ (unary)
2147
                        if ($debug) {
2148
                            error_log(
2149
                                'New LP - Didnt find any =, looking for ~',
2150
                                0
2151
                            );
2152
                        }
2153
                        // Only remains: ~ and X*{}
2154
                        if (strpos($prereqs_string, '~') !== false) {
2155
                            // Found NOT.
2156
                            if ($debug) {
2157
                                error_log(
2158
                                    'New LP - Found ~, looking into it',
2159
                                    0
2160
                                );
2161
                            }
2162
                            $list = [];
2163
                            $myres = preg_match(
2164
                                '/~([^(\d+\*)\{]*)/',
2165
                                $prereqs_string,
2166
                                $list
2167
                            );
2168
                            if ($myres) {
2169
                                $returnstatus = !$this->parse_prereq(
2170
                                    $list[1],
2171
                                    $items,
2172
                                    $refs_list,
2173
                                    $user_id
2174
                                );
2175
                                if (empty($this->prereq_alert) && !$returnstatus) {
2176
                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2177
                                }
2178
2179
                                return $returnstatus;
2180
                            } else {
2181
                                // Strange...
2182
                                if ($debug) {
2183
                                    error_log(
2184
                                        'New LP - Found ~ but strange string: '.$prereqs_string,
2185
                                        0
2186
                                    );
2187
                                }
2188
                            }
2189
                        } else {
2190
                            // Finally, look for sets/groups
2191
                            if ($debug) {
2192
                                error_log(
2193
                                    'New LP - Didnt find any ~, looking for groups',
2194
                                    0
2195
                                );
2196
                            }
2197
                            // Only groups here.
2198
                            $groups = [];
2199
                            $groups_there = preg_match_all(
2200
                                '/((\d+\*)?\{([^\}]+)\}+)/',
2201
                                $prereqs_string,
2202
                                $groups
2203
                            );
2204
2205
                            if ($groups_there) {
2206
                                foreach ($groups[1] as $gr) {
2207
                                    // Only take the results that correspond to
2208
                                    //  the big brackets-enclosed condition.
2209
                                    if ($debug) {
2210
                                        error_log(
2211
                                            'New LP - Dealing with group '.$gr,
2212
                                            0
2213
                                        );
2214
                                    }
2215
                                    $multi = [];
2216
                                    $mycond = false;
2217
                                    if (preg_match(
2218
                                        '/(\d+)\*\{([^\}]+)\}/',
2219
                                        $gr,
2220
                                        $multi
2221
                                    )
2222
                                    ) {
2223
                                        if ($debug) {
2224
                                            error_log(
2225
                                                'New LP - Found multiplier '.$multi[0],
2226
                                                0
2227
                                            );
2228
                                        }
2229
                                        $count = $multi[1];
2230
                                        $list = explode(',', $multi[2]);
2231
                                        $mytrue = 0;
2232
                                        foreach ($list as $cond) {
2233
                                            if (isset($items[$refs_list[$cond]])) {
2234
                                                $status = $items[$refs_list[$cond]]->get_status(true);
2235
                                                if ($status == $this->possible_status[2] ||
2236
                                                    $status == $this->possible_status[3]
2237
                                                ) {
2238
                                                    $mytrue++;
2239
                                                    if ($debug) {
2240
                                                        error_log(
2241
                                                            'New LP - Found true item, counting.. ('.($mytrue).')',
2242
                                                            0
2243
                                                        );
2244
                                                    }
2245
                                                }
2246
                                            } else {
2247
                                                if ($debug) {
2248
                                                    error_log(
2249
                                                        'New LP - item '.$cond.' does not exist in items list',
2250
                                                        0
2251
                                                    );
2252
                                                }
2253
                                            }
2254
                                        }
2255
                                        if ($mytrue >= $count) {
2256
                                            if ($debug) {
2257
                                                error_log(
2258
                                                    'New LP - Got enough true results, return true',
2259
                                                    0
2260
                                                );
2261
                                            }
2262
                                            $mycond = true;
2263
                                        } else {
2264
                                            if ($debug) {
2265
                                                error_log(
2266
                                                    'New LP - Not enough true results',
2267
                                                    0
2268
                                                );
2269
                                            }
2270
                                        }
2271
                                    } else {
2272
                                        if ($debug) {
2273
                                            error_log(
2274
                                                'New LP - No multiplier',
2275
                                                0
2276
                                            );
2277
                                        }
2278
                                        $list = explode(',', $gr);
2279
                                        $mycond = true;
2280
                                        foreach ($list as $cond) {
2281
                                            if (isset($items[$refs_list[$cond]])) {
2282
                                                $status = $items[$refs_list[$cond]]->get_status(true);
2283
                                                if ($status == $this->possible_status[2] ||
2284
                                                    $status == $this->possible_status[3]
2285
                                                ) {
2286
                                                    $mycond = true;
2287
                                                    if ($debug) {
2288
                                                        error_log(
2289
                                                            'New LP - Found true item',
2290
                                                            0
2291
                                                        );
2292
                                                    }
2293
                                                } else {
2294
                                                    if ($debug) {
2295
                                                        error_log(
2296
                                                            'New LP - '.
2297
                                                            ' Found false item, the set is not true, return false',
2298
                                                            0
2299
                                                        );
2300
                                                    }
2301
                                                    $mycond = false;
2302
                                                    break;
2303
                                                }
2304
                                            } else {
2305
                                                if ($debug) {
2306
                                                    error_log(
2307
                                                        'New LP - item '.$cond.' does not exist in items list',
2308
                                                        0
2309
                                                    );
2310
                                                }
2311
                                                if ($debug) {
2312
                                                    error_log(
2313
                                                        'New LP - Found false item, the set is not true, return false',
2314
                                                        0
2315
                                                    );
2316
                                                }
2317
                                                $mycond = false;
2318
                                                break;
2319
                                            }
2320
                                        }
2321
                                    }
2322
                                    if (!$mycond && empty($this->prereq_alert)) {
2323
                                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2324
                                    }
2325
2326
                                    return $mycond;
2327
                                }
2328
                            } else {
2329
                                // Nothing found there either. Now return the
2330
                                // value of the corresponding resource completion status.
2331
                                if (isset($refs_list[$prereqs_string]) &&
2332
                                    isset($items[$refs_list[$prereqs_string]])
2333
                                ) {
2334
                                    /** @var learnpathItem $itemToCheck */
2335
                                    $itemToCheck = $items[$refs_list[$prereqs_string]];
2336
2337
                                    if ($itemToCheck->type === 'quiz') {
2338
                                        // 1. Checking the status in current items.
2339
                                        $status = $itemToCheck->get_status(true);
2340
                                        $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2341
2342
                                        if (!$returnstatus) {
2343
                                            $explanation = sprintf(
2344
                                                get_lang('ItemXBlocksThisElement'),
2345
                                                $itemToCheck->get_title()
2346
                                            );
2347
                                            $this->prereq_alert = $explanation;
2348
                                        }
2349
2350
                                        // For one and first attempt.
2351
                                        if ($this->prevent_reinit == 1) {
2352
                                            // 2. If is completed we check the results in the DB of the quiz.
2353
                                            if ($returnstatus) {
2354
                                                $sql = 'SELECT exe_result, exe_weighting
2355
                                                        FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
2356
                                                        WHERE
2357
                                                            exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
2358
                                                            exe_user_id = '.$user_id.' AND
2359
                                                            orig_lp_id = '.$this->lp_id.' AND
2360
                                                            orig_lp_item_id = '.$prereqs_string.' AND
2361
                                                            status <> "incomplete" AND
2362
                                                            c_id = '.$course_id.'
2363
                                                        ORDER BY exe_date DESC
2364
                                                        LIMIT 0, 1';
2365
                                                $rs_quiz = Database::query($sql);
2366
                                                if ($quiz = Database::fetch_array($rs_quiz)) {
2367
                                                    /** @var learnpathItem $myItemToCheck */
2368
                                                    $myItemToCheck = $items[$refs_list[$this->get_id()]];
2369
                                                    $minScore = $myItemToCheck->getPrerequisiteMinScore();
2370
                                                    $maxScore = $myItemToCheck->getPrerequisiteMaxScore();
2371
2372
                                                    if (isset($minScore) && isset($minScore)) {
2373
                                                        // Taking min/max prerequisites values see BT#5776
2374
                                                        if ($quiz['exe_result'] >= $minScore &&
2375
                                                            $quiz['exe_result'] <= $maxScore
2376
                                                        ) {
2377
                                                            $returnstatus = true;
2378
                                                        } else {
2379
                                                            $explanation = sprintf(
2380
                                                                get_lang('YourResultAtXBlocksThisElement'),
2381
                                                                $itemToCheck->get_title()
2382
                                                            );
2383
                                                            $this->prereq_alert = $explanation;
2384
                                                            $returnstatus = false;
2385
                                                        }
2386
                                                    } else {
2387
                                                        // Classic way
2388
                                                        if ($quiz['exe_result'] >=
2389
                                                            $items[$refs_list[$prereqs_string]]->get_mastery_score()
2390
                                                        ) {
2391
                                                            $returnstatus = true;
2392
                                                        } else {
2393
                                                            $explanation = sprintf(
2394
                                                                get_lang('YourResultAtXBlocksThisElement'),
2395
                                                                $itemToCheck->get_title()
2396
                                                            );
2397
                                                            $this->prereq_alert = $explanation;
2398
                                                            $returnstatus = false;
2399
                                                        }
2400
                                                    }
2401
                                                } else {
2402
                                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2403
                                                    $returnstatus = false;
2404
                                                }
2405
                                            }
2406
                                        } else {
2407
                                            // 3. For multiple attempts we check that there are minimum 1 item completed
2408
                                            // Checking in the database.
2409
                                            $sql = 'SELECT exe_result, exe_weighting
2410
                                                    FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
2411
                                                    WHERE
2412
                                                        c_id = '.$course_id.' AND
2413
                                                        exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
2414
                                                        exe_user_id = '.$user_id.' AND
2415
                                                        orig_lp_id = '.$this->lp_id.' AND
2416
                                                        orig_lp_item_id = '.$prereqs_string;
2417
2418
                                            $rs_quiz = Database::query($sql);
2419
                                            if (Database::num_rows($rs_quiz) > 0) {
2420
                                                while ($quiz = Database::fetch_array($rs_quiz)) {
2421
                                                    /** @var learnpathItem $myItemToCheck */
2422
                                                    $myItemToCheck = $items[$refs_list[$this->get_id()]];
2423
                                                    $minScore = $myItemToCheck->getPrerequisiteMinScore();
2424
                                                    $maxScore = $myItemToCheck->getPrerequisiteMaxScore();
2425
2426
                                                    if (empty($minScore)) {
2427
                                                        // Try with mastery_score
2428
                                                        $masteryScoreAsMin = $myItemToCheck->get_mastery_score();
2429
                                                        if (!empty($masteryScoreAsMin)) {
2430
                                                            $minScore = $masteryScoreAsMin;
2431
                                                        }
2432
                                                    }
2433
2434
                                                    if (isset($minScore) && isset($minScore)) {
2435
                                                        // Taking min/max prerequisites values see BT#5776
2436
                                                        if ($quiz['exe_result'] >= $minScore &&
2437
                                                            $quiz['exe_result'] <= $maxScore
2438
                                                        ) {
2439
                                                            $returnstatus = true;
2440
                                                            break;
2441
                                                        } else {
2442
                                                            $explanation = sprintf(
2443
                                                                get_lang('YourResultAtXBlocksThisElement'),
2444
                                                                $itemToCheck->get_title()
2445
                                                            );
2446
                                                            $this->prereq_alert = $explanation;
2447
                                                            $returnstatus = false;
2448
                                                        }
2449
                                                    } else {
2450
                                                        if ($quiz['exe_result'] >=
2451
                                                            $items[$refs_list[$prereqs_string]]->get_mastery_score()
2452
                                                        ) {
2453
                                                            $returnstatus = true;
2454
                                                            break;
2455
                                                        } else {
2456
                                                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2457
                                                            $returnstatus = false;
2458
                                                        }
2459
                                                    }
2460
                                                }
2461
                                            } else {
2462
                                                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2463
                                                $returnstatus = false;
2464
                                            }
2465
                                        }
2466
2467
                                        if ($returnstatus === false) {
2468
                                            // Check results from another sessions.
2469
                                            $checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
2470
                                            if ($checkOtherSessions) {
2471
                                                $returnstatus = $this->getStatusFromOtherSessions(
2472
                                                    $user_id,
2473
                                                    $prereqs_string,
2474
                                                    $refs_list
2475
                                                );
2476
                                            }
2477
                                        }
2478
2479
                                        return $returnstatus;
2480
                                    } elseif ($itemToCheck->type === 'student_publication') {
2481
                                        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2482
                                        $workId = $items[$refs_list[$prereqs_string]]->path;
2483
                                        $count = get_work_count_by_student($user_id, $workId);
2484
                                        if ($count >= 1) {
2485
                                            $returnstatus = true;
2486
                                        } else {
2487
                                            $returnstatus = false;
2488
                                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2489
                                        }
2490
2491
                                        return $returnstatus;
2492
                                    } else {
2493
                                        $status = $itemToCheck->get_status(false);
2494
                                        $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2495
2496
                                        // Check results from another sessions.
2497
                                        $checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
2498
                                        if ($checkOtherSessions && !$returnstatus) {
2499
                                            $returnstatus = $this->getStatusFromOtherSessions(
2500
                                                $user_id,
2501
                                                $prereqs_string,
2502
                                                $refs_list
2503
                                            );
2504
                                        }
2505
2506
                                        if (!$returnstatus) {
2507
                                            $explanation = sprintf(
2508
                                                get_lang('ItemXBlocksThisElement'),
2509
                                                $itemToCheck->get_title()
2510
                                            );
2511
                                            $this->prereq_alert = $explanation;
2512
                                        }
2513
2514
                                        $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
2515
                                        $lp_view = Database::get_course_table(TABLE_LP_VIEW);
2516
2517
                                        if ($returnstatus && $this->prevent_reinit == 1) {
2518
                                            $sql = "SELECT iid FROM $lp_view
2519
                                                    WHERE
2520
                                                        c_id = $course_id AND
2521
                                                        user_id = $user_id  AND
2522
                                                        lp_id = $this->lp_id AND
2523
                                                        session_id = $sessionId
2524
                                                    LIMIT 0, 1";
2525
                                            $rs_lp = Database::query($sql);
2526
                                            if (Database::num_rows($rs_lp)) {
2527
                                                $lp_id = Database::fetch_row($rs_lp);
2528
                                                $my_lp_id = $lp_id[0];
2529
2530
                                                $sql = "SELECT status FROM $lp_item_view
2531
                                                        WHERE
2532
                                                            c_id = $course_id AND
2533
                                                            lp_view_id = $my_lp_id AND
2534
                                                            lp_item_id = $refs_list[$prereqs_string]
2535
                                                        LIMIT 0, 1";
2536
                                                $rs_lp = Database::query($sql);
2537
                                                $status_array = Database::fetch_row($rs_lp);
2538
                                                $status = $status_array[0];
2539
2540
                                                $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2541
                                                if (!$returnstatus && empty($this->prereq_alert)) {
2542
                                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2543
                                                }
2544
                                            }
2545
2546
                                            if ($checkOtherSessions && $returnstatus === false) {
2547
                                                $returnstatus = $returnstatus = $this->getStatusFromOtherSessions(
2548
                                                    $user_id,
2549
                                                    $prereqs_string,
2550
                                                    $refs_list
2551
                                                );
2552
                                            }
2553
                                        }
2554
2555
                                        return $returnstatus;
2556
                                    }
2557
                                }
2558
                            }
2559
                        }
2560
                    }
2561
                }
2562
            }
2563
        } else {
2564
            $list = explode("\|", $prereqs_string);
2565
            if (count($list) > 1) {
2566
                if (self::DEBUG > 1) {
2567
                    error_log('New LP - Found OR, looking into it', 0);
2568
                }
2569
                $orstatus = false;
2570
                foreach ($list as $condition) {
2571
                    if (self::DEBUG > 1) {
2572
                        error_log(
2573
                            'New LP - Found OR, adding it ('.$condition.')',
2574
                            0
2575
                        );
2576
                    }
2577
                    $orstatus = $orstatus || $this->parse_prereq(
2578
                        $condition,
2579
                        $items,
2580
                        $refs_list,
2581
                        $user_id
2582
                    );
2583
                    if ($orstatus) {
2584
                        // Shortcircuit OR.
2585
                        if (self::DEBUG > 1) {
2586
                            error_log(
2587
                                'New LP - One condition in OR was true, short-circuit',
2588
                                0
2589
                            );
2590
                        }
2591
                        break;
2592
                    }
2593
                }
2594
                if (!$orstatus && empty($this->prereq_alert)) {
2595
                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2596
                }
2597
2598
                return $orstatus;
2599
            } else {
2600
                if (self::DEBUG > 1) {
2601
                    error_log(
2602
                        'New LP - OR was found but only one elem present !?',
2603
                        0
2604
                    );
2605
                }
2606
                if (isset($items[$refs_list[$list[0]]])) {
2607
                    $status = $items[$refs_list[$list[0]]]->get_status(true);
2608
                    $returnstatus = $status == 'completed' || $status == 'passed';
2609
                    if (!$returnstatus && empty($this->prereq_alert)) {
2610
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2611
                    }
2612
2613
                    return $returnstatus;
2614
                }
2615
            }
2616
        }
2617
        if (empty($this->prereq_alert)) {
2618
            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2619
        }
2620
2621
        if (self::DEBUG > 1) {
2622
            error_log(
2623
                'New LP - End of parse_prereq. Error code is now '.$this->prereq_alert,
2624
                0
2625
            );
2626
        }
2627
2628
        return false;
2629
    }
2630
2631
    /**
2632
     * Reinits all local values as the learnpath is restarted.
2633
     *
2634
     * @return bool True on success, false otherwise
2635
     */
2636
    public function restart()
2637
    {
2638
        if (self::DEBUG > 0) {
2639
            error_log('learnpathItem::restart()', 0);
2640
        }
2641
        $seriousGame = $this->get_seriousgame_mode();
2642
        //For serious game  : We reuse same attempt_id
2643
        if ($seriousGame == 1 && $this->type == 'sco') {
2644
            // If this is a sco, Chamilo can't update the time without an
2645
            //  explicit scorm call
2646
            $this->current_start_time = 0;
2647
            $this->current_stop_time = 0; //Those 0 value have this effect
2648
            $this->last_scorm_session_time = 0;
2649
            $this->save();
2650
2651
            return true;
2652
        }
2653
2654
        $this->save();
2655
2656
        $allowed = $this->isRestartAllowed();
2657
        if ($allowed === -1) {
2658
            // Nothing allowed, do nothing.
2659
        } elseif ($allowed === 1) {
2660
            // Restart as new attempt is allowed, record a new attempt.
2661
            $this->attempt_id = $this->attempt_id + 1; // Simply reuse the previous attempt_id.
2662
            $this->current_score = 0;
2663
            $this->current_start_time = 0;
2664
            $this->current_stop_time = 0;
2665
            $this->current_data = '';
2666
            $this->status = $this->possible_status[0];
2667
            $this->interactions_count = 0;
2668
            $this->interactions = [];
2669
            $this->objectives_count = 0;
2670
            $this->objectives = [];
2671
            $this->lesson_location = '';
2672
            if ($this->type != TOOL_QUIZ) {
2673
                $this->write_to_db();
2674
            }
2675
        } else {
2676
            // Restart current element is allowed (because it's not finished yet),
2677
            // reinit current.
2678
            //$this->current_score = 0;
2679
            $this->current_start_time = 0;
2680
            $this->current_stop_time = 0;
2681
            $this->interactions_count = $this->get_interactions_count(true);
2682
        }
2683
2684
        return true;
2685
    }
2686
2687
    /**
2688
     * Saves data in the database.
2689
     *
2690
     * @param bool $from_outside     Save from URL params (1) or from object attributes (0)
2691
     * @param bool $prereqs_complete The results of a check on prerequisites for this item.
2692
     *                               True if prerequisites are completed, false otherwise. Defaults to false. Only used if not sco or au
2693
     *
2694
     * @return bool True on success, false on failure
2695
     */
2696
    public function save($from_outside = true, $prereqs_complete = false)
2697
    {
2698
        $debug = self::DEBUG;
2699
        if ($debug) {
2700
            error_log('learnpathItem::save()', 0);
2701
        }
2702
        // First check if parameters passed via GET can be saved here
2703
        // in case it's a SCORM, we should get:
2704
        if ($this->type == 'sco' || $this->type == 'au') {
2705
            $status = $this->get_status(true);
2706
            if ($this->prevent_reinit == 1 &&
2707
                $status != $this->possible_status[0] && // not attempted
2708
                $status != $this->possible_status[1]    //incomplete
2709
            ) {
2710
                if ($debug) {
2711
                    error_log(
2712
                        'learnpathItem::save() - save reinit blocked by setting',
2713
                        0
2714
                    );
2715
                }
2716
                // Do nothing because the status has already been set. Don't allow it to change.
2717
                // TODO: Check there isn't a special circumstance where this should be saved.
2718
            } else {
2719
                if ($debug) {
2720
                    error_log(
2721
                        'learnpathItem::save() - SCORM save request received',
2722
                        0
2723
                    );
2724
                }
2725
                // Get all new settings from the URL
2726
                if ($from_outside) {
2727
                    if ($debug) {
2728
                        error_log(
2729
                            'learnpathItem::save() - Getting item data from outside',
2730
                            0
2731
                        );
2732
                    }
2733
                    foreach ($_GET as $param => $value) {
2734
                        switch ($param) {
2735
                            case 'score':
2736
                                $this->set_score($value);
2737
                                if ($debug) {
2738
                                    error_log(
2739
                                        'learnpathItem::save() - setting score to '.$value,
2740
                                        0
2741
                                    );
2742
                                }
2743
                                break;
2744
                            case 'max':
2745
                                $this->set_max_score($value);
2746
                                if ($debug) {
2747
                                    error_log(
2748
                                        'learnpathItem::save() - setting view_max_score to '.$value,
2749
                                        0
2750
                                    );
2751
                                }
2752
                                break;
2753
                            case 'min':
2754
                                $this->min_score = $value;
2755
                                if ($debug) {
2756
                                    error_log(
2757
                                        'learnpathItem::save() - setting min_score to '.$value,
2758
                                        0
2759
                                    );
2760
                                }
2761
                                break;
2762
                            case 'lesson_status':
2763
                                if (!empty($value)) {
2764
                                    $this->set_status($value);
2765
                                    if ($debug) {
2766
                                        error_log(
2767
                                            'learnpathItem::save() - setting status to '.$value,
2768
                                            0
2769
                                        );
2770
                                    }
2771
                                }
2772
                                break;
2773
                            case 'time':
2774
                                $this->set_time($value);
2775
                                if ($debug) {
2776
                                    error_log(
2777
                                        'learnpathItem::save() - setting time to '.$value,
2778
                                        0
2779
                                    );
2780
                                }
2781
                                break;
2782
                            case 'suspend_data':
2783
                                $this->current_data = $value;
2784
                                if ($debug) {
2785
                                    error_log(
2786
                                        'learnpathItem::save() - setting suspend_data to '.$value,
2787
                                        0
2788
                                    );
2789
                                }
2790
                                break;
2791
                            case 'lesson_location':
2792
                                $this->set_lesson_location($value);
2793
                                if ($debug) {
2794
                                    error_log(
2795
                                        'learnpathItem::save() - setting lesson_location to '.$value,
2796
                                        0
2797
                                    );
2798
                                }
2799
                                break;
2800
                            case 'core_exit':
2801
                                $this->set_core_exit($value);
2802
                                if ($debug) {
2803
                                    error_log(
2804
                                        'learnpathItem::save() - setting core_exit to '.$value,
2805
                                        0
2806
                                    );
2807
                                }
2808
                                break;
2809
                            case 'interactions':
2810
                                break;
2811
                            case 'objectives':
2812
                                break;
2813
                            default:
2814
                                // Ignore.
2815
                                break;
2816
                        }
2817
                    }
2818
                } else {
2819
                    if ($debug) {
2820
                        error_log(
2821
                            'learnpathItem::save() - Using inside item status',
2822
                            0
2823
                        );
2824
                    }
2825
                    // Do nothing, just let the local attributes be used.
2826
                }
2827
            }
2828
        } else {
2829
            // If not SCO, such messages should not be expected.
2830
            $type = strtolower($this->type);
2831
            if ($debug) {
2832
                error_log("type: $type");
2833
            }
2834
            switch ($type) {
2835
                case 'asset':
2836
                    if ($prereqs_complete) {
2837
                        $this->set_status($this->possible_status[2]);
2838
                    }
2839
                    break;
2840
                case TOOL_HOTPOTATOES:
2841
                    break;
2842
                case TOOL_QUIZ:
2843
                    return false;
2844
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2845
                default:
2846
                    // For now, everything that is not sco and not asset is set to
2847
                    // completed when saved.
2848
                    if ($prereqs_complete) {
2849
                        $this->set_status($this->possible_status[2]);
2850
                    }
2851
                    break;
2852
            }
2853
        }
2854
2855
        if ($debug) {
2856
            error_log(
2857
                'New LP - End of learnpathItem::save() - Calling write_to_db()',
2858
                0
2859
            );
2860
        }
2861
2862
        return $this->write_to_db();
2863
    }
2864
2865
    /**
2866
     * Sets the number of attempt_id to a given value.
2867
     *
2868
     * @param int $num The given value to set attempt_id to
2869
     *
2870
     * @return bool TRUE on success, FALSE otherwise
2871
     */
2872
    public function set_attempt_id($num)
2873
    {
2874
        if ($num == strval(intval($num)) && $num >= 0) {
2875
            $this->attempt_id = $num;
2876
2877
            return true;
2878
        }
2879
2880
        return false;
2881
    }
2882
2883
    /**
2884
     * Sets the core_exit value to the one given.
2885
     *
2886
     * @return bool $value  True (always)
2887
     */
2888
    public function set_core_exit($value)
2889
    {
2890
        switch ($value) {
2891
            case '':
2892
                $this->core_exit = '';
2893
                break;
2894
            case 'suspend':
2895
                $this->core_exit = 'suspend';
2896
                break;
2897
            default:
2898
                $this->core_exit = 'none';
2899
                break;
2900
        }
2901
2902
        return true;
2903
    }
2904
2905
    /**
2906
     * Sets the item's description.
2907
     *
2908
     * @param string $string Description
2909
     */
2910
    public function set_description($string = '')
2911
    {
2912
        if (!empty($string)) {
2913
            $this->description = $string;
2914
        }
2915
    }
2916
2917
    /**
2918
     * Sets the lesson_location value.
2919
     *
2920
     * @param string $location lesson_location as provided by the SCO
2921
     *
2922
     * @return bool True on success, false otherwise
2923
     */
2924
    public function set_lesson_location($location)
2925
    {
2926
        if (isset($location)) {
2927
            $this->lesson_location = $location;
2928
2929
            return true;
2930
        }
2931
2932
        return false;
2933
    }
2934
2935
    /**
2936
     * Sets the item's depth level in the LP tree (0 is at root).
2937
     *
2938
     * @param int $int Level
2939
     */
2940
    public function set_level($int = 0)
2941
    {
2942
        $this->level = (int) $int;
2943
    }
2944
2945
    /**
2946
     * Sets the lp_view id this item view is registered to.
2947
     *
2948
     * @param int $lp_view_id lp_view DB ID
2949
     * @param int $course_id
2950
     *
2951
     * @return bool
2952
     *
2953
     * @todo //todo insert into lp_item_view if lp_view not exists
2954
     */
2955
    public function set_lp_view($lp_view_id, $course_id = null)
2956
    {
2957
        $lp_view_id = (int) $lp_view_id;
2958
        $course_id = (int) $course_id;
2959
2960
        if (empty($course_id)) {
2961
            $course_id = api_get_course_int_id();
2962
        }
2963
2964
        $lpItemId = $this->get_id();
2965
2966
        if (empty($lpItemId)) {
2967
            return false;
2968
        }
2969
2970
        if (empty($lp_view_id)) {
2971
            return false;
2972
        }
2973
2974
        if (self::DEBUG > 0) {
2975
            error_log('learnpathItem::set_lp_view('.$lp_view_id.')', 0);
2976
        }
2977
2978
        $this->view_id = $lp_view_id;
2979
2980
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
2981
        // Get the lp_item_view with the highest view_count.
2982
        $sql = "SELECT * FROM $item_view_table
2983
                WHERE
2984
                    c_id = $course_id AND
2985
                    lp_item_id = $lpItemId AND
2986
                    lp_view_id = $lp_view_id
2987
                ORDER BY view_count DESC";
2988
2989
        if (self::DEBUG > 2) {
2990
            error_log(
2991
                'learnpathItem::set_lp_view() - Querying lp_item_view: '.$sql,
2992
                0
2993
            );
2994
        }
2995
        $res = Database::query($sql);
2996
        if (Database::num_rows($res) > 0) {
2997
            $row = Database::fetch_array($res);
2998
            $this->db_item_view_id = $row['iid'];
2999
            $this->attempt_id = $row['view_count'];
3000
            $this->current_score = $row['score'];
3001
            $this->current_data = $row['suspend_data'];
3002
            $this->view_max_score = $row['max_score'];
3003
            $this->status = $row['status'];
3004
            $this->current_start_time = $row['start_time'];
3005
            $this->current_stop_time = $this->current_start_time + $row['total_time'];
3006
            $this->lesson_location = $row['lesson_location'];
3007
            $this->core_exit = $row['core_exit'];
3008
3009
            if (self::DEBUG > 2) {
3010
                error_log(
3011
                    'learnpathItem::set_lp_view() - Updated item object with database values',
3012
                    0
3013
                );
3014
            }
3015
3016
            // Now get the number of interactions for this little guy.
3017
            $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
3018
            $sql = "SELECT * FROM $table
3019
                    WHERE
3020
                        c_id = $course_id AND
3021
                        lp_iv_id = '".$this->db_item_view_id."'";
3022
3023
            $res = Database::query($sql);
3024
            if ($res !== false) {
3025
                $this->interactions_count = Database::num_rows($res);
3026
            } else {
3027
                $this->interactions_count = 0;
3028
            }
3029
            // Now get the number of objectives for this little guy.
3030
            $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
3031
            $sql = "SELECT * FROM $table
3032
                    WHERE
3033
                        c_id = $course_id AND
3034
                        lp_iv_id = '".$this->db_item_view_id."'";
3035
3036
            $this->objectives_count = 0;
3037
            $res = Database::query($sql);
3038
            if ($res !== false) {
3039
                $this->objectives_count = Database::num_rows($res);
3040
            }
3041
        }
3042
3043
        return true;
3044
    }
3045
3046
    /**
3047
     * Sets the path.
3048
     *
3049
     * @param string $string Path
3050
     */
3051
    public function set_path($string = '')
3052
    {
3053
        if (!empty($string)) {
3054
            $this->path = $string;
3055
        }
3056
    }
3057
3058
    /**
3059
     * Sets the prevent_reinit attribute.
3060
     * This is based on the LP value and is set at creation time for
3061
     * each learnpathItem. It is a (bad?) way of avoiding
3062
     * a reference to the LP when saving an item.
3063
     *
3064
     * @param int 1 for "prevent", 0 for "don't prevent"
0 ignored issues
show
Documentation Bug introduced by
The doc comment 1 at position 0 could not be parsed: Unknown type name '1' at position 0 in 1.
Loading history...
3065
     * saving freshened values (new "not attempted" status etc)
3066
     */
3067
    public function set_prevent_reinit($prevent)
3068
    {
3069
        $this->prevent_reinit = 0;
3070
        if ($prevent) {
3071
            $this->prevent_reinit = 1;
3072
        }
3073
    }
3074
3075
    /**
3076
     * Sets the score value. If the mastery_score is set and the score reaches
3077
     * it, then set the status to 'passed'.
3078
     *
3079
     * @param float $score Score
3080
     *
3081
     * @return bool True on success, false otherwise
3082
     */
3083
    public function set_score($score)
3084
    {
3085
        $debug = self::DEBUG;
3086
        if ($debug > 0) {
3087
            error_log('learnpathItem::set_score('.$score.')', 0);
3088
        }
3089
        if (($this->max_score <= 0 || $score <= $this->max_score) && ($score >= $this->min_score)) {
3090
            $this->current_score = $score;
3091
            $masteryScore = $this->get_mastery_score();
3092
            $current_status = $this->get_status(false);
3093
3094
            // Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
3095
            if ($masteryScore == -1) {
3096
                $masteryScore = $this->max_score;
3097
            }
3098
3099
            if ($debug > 0) {
3100
                error_log('get_mastery_score: '.$masteryScore);
3101
                error_log('current_status: '.$current_status);
3102
                error_log('current score : '.$this->current_score);
3103
            }
3104
3105
            // If mastery_score is set AND the current score reaches the mastery
3106
            //  score AND the current status is different from 'completed', then
3107
            //  set it to 'passed'.
3108
            /*
3109
            if ($master != -1 && $this->current_score >= $master && $current_status != $this->possible_status[2]) {
3110
                if ($debug > 0) error_log('Status changed to: '.$this->possible_status[3]);
3111
                $this->set_status($this->possible_status[3]); //passed
3112
            } elseif ($master != -1 && $this->current_score < $master) {
3113
                if ($debug > 0) error_log('Status changed to: '.$this->possible_status[4]);
3114
                $this->set_status($this->possible_status[4]); //failed
3115
            }*/
3116
            return true;
3117
        }
3118
3119
        return false;
3120
    }
3121
3122
    /**
3123
     * Sets the maximum score for this item.
3124
     *
3125
     * @param int $score Maximum score - must be a decimal or an empty string
3126
     *
3127
     * @return bool True on success, false on error
3128
     */
3129
    public function set_max_score($score)
3130
    {
3131
        if (is_int($score) || $score == '') {
3132
            $this->view_max_score = $score;
3133
3134
            return true;
3135
        }
3136
3137
        return false;
3138
    }
3139
3140
    /**
3141
     * Sets the status for this item.
3142
     *
3143
     * @param string $status Status - must be one of the values defined in $this->possible_status
3144
     *                       (this affects the status setting)
3145
     *
3146
     * @return bool True on success, false on error
3147
     */
3148
    public function set_status($status)
3149
    {
3150
        if (self::DEBUG > 0) {
3151
            error_log('learnpathItem::set_status('.$status.')', 0);
3152
        }
3153
3154
        $found = false;
3155
        foreach ($this->possible_status as $possible) {
3156
            if (preg_match('/^'.$possible.'$/i', $status)) {
3157
                $found = true;
3158
            }
3159
        }
3160
3161
        if ($found) {
3162
            $this->status = $status;
3163
            if (self::DEBUG > 1) {
3164
                error_log(
3165
                    'learnpathItem::set_status() - '.
3166
                        'Updated object status of item '.$this->db_id.
3167
                        ' to '.$this->status,
3168
                    0
3169
                );
3170
            }
3171
3172
            return true;
3173
        }
3174
3175
        $this->status = $this->possible_status[0];
3176
3177
        return false;
3178
    }
3179
3180
    /**
3181
     * Set the (indexing) terms for this learnpath item.
3182
     *
3183
     * @param string $terms Terms, as a comma-split list
3184
     *
3185
     * @return bool Always return true
3186
     */
3187
    public function set_terms($terms)
3188
    {
3189
        global $charset;
3190
        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
3191
        $a_terms = preg_split('/,/', $terms);
3192
        $i_terms = preg_split('/,/', $this->get_terms());
3193
        foreach ($i_terms as $term) {
3194
            if (!in_array($term, $a_terms)) {
3195
                array_push($a_terms, $term);
3196
            }
3197
        }
3198
        $new_terms = $a_terms;
3199
        $new_terms_string = implode(',', $new_terms);
3200
3201
        // TODO: Validate csv string.
3202
        $terms = Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset));
3203
        $sql = "UPDATE $lp_item
3204
                SET terms = '$terms'
3205
                WHERE iid=".$this->get_id();
3206
        Database::query($sql);
3207
        // Save it to search engine.
3208
        if (api_get_setting('search_enabled') == 'true') {
3209
            $di = new ChamiloIndexer();
3210
            $di->update_terms($this->get_search_did(), $new_terms, 'T');
3211
        }
3212
3213
        return true;
3214
    }
3215
3216
    /**
3217
     * Get the document ID from inside the text index database.
3218
     *
3219
     * @return int Search index database document ID
3220
     */
3221
    public function get_search_did()
3222
    {
3223
        return $this->search_did;
3224
    }
3225
3226
    /**
3227
     * Sets the item viewing time in a usable form, given that SCORM packages
3228
     * often give it as 00:00:00.0000.
3229
     *
3230
     * @param    string    Time as given by SCORM
3231
     * @param string $format
3232
     */
3233
    public function set_time($scorm_time, $format = 'scorm')
3234
    {
3235
        $debug = self::DEBUG;
3236
        if ($debug) {
3237
            error_log("learnpathItem::set_time($scorm_time, $format)");
3238
            error_log("this->type: ".$this->type);
3239
            error_log("this->current_start_time: ".$this->current_start_time);
3240
        }
3241
3242
        if ($scorm_time == '0' &&
3243
            $this->type != 'sco' &&
3244
            $this->current_start_time != 0
3245
        ) {
3246
            $myTime = time() - $this->current_start_time;
3247
            if ($myTime > 0) {
3248
                $this->update_time($myTime);
3249
                if ($debug) {
3250
                    error_log('found asset - set time to '.$myTime);
3251
                }
3252
            } else {
3253
                if ($debug) {
3254
                    error_log('Time not set');
3255
                }
3256
            }
3257
        } else {
3258
            switch ($format) {
3259
                case 'scorm':
3260
                    $res = [];
3261
                    if (preg_match(
3262
                        '/^(\d{1,4}):(\d{2}):(\d{2})(\.\d{1,4})?/',
3263
                        $scorm_time,
3264
                        $res
3265
                    )
3266
                    ) {
3267
                        $hour = $res[1];
3268
                        $min = $res[2];
3269
                        $sec = $res[3];
3270
                        // Getting total number of seconds spent.
3271
                        $totalSec = $hour * 3600 + $min * 60 + $sec;
3272
                        if ($debug) {
3273
                            error_log("totalSec : $totalSec");
3274
                            error_log("Now calling to scorm_update_time()");
3275
                        }
3276
                        $this->scorm_update_time($totalSec);
3277
                    }
3278
                    break;
3279
                case 'int':
3280
                    if ($debug) {
3281
                        error_log("scorm_time = $scorm_time");
3282
                        error_log("Now calling to scorm_update_time()");
3283
                    }
3284
                    $this->scorm_update_time($scorm_time);
3285
                    break;
3286
            }
3287
        }
3288
    }
3289
3290
    /**
3291
     * Sets the item's title.
3292
     *
3293
     * @param string $string Title
3294
     */
3295
    public function set_title($string = '')
3296
    {
3297
        if (!empty($string)) {
3298
            $this->title = $string;
3299
        }
3300
    }
3301
3302
    /**
3303
     * Sets the item's type.
3304
     *
3305
     * @param string $string Type
3306
     */
3307
    public function set_type($string = '')
3308
    {
3309
        if (!empty($string)) {
3310
            $this->type = $string;
3311
        }
3312
    }
3313
3314
    /**
3315
     * Checks if the current status is part of the list of status given.
3316
     *
3317
     * @param array $list An array of status to check for.
3318
     *                    If the current status is one of the strings, return true
3319
     *
3320
     * @return bool True if the status was one of the given strings,
3321
     *              false otherwise
3322
     */
3323
    public function status_is($list = [])
3324
    {
3325
        if (self::DEBUG > 1) {
3326
            error_log(
3327
                'learnpathItem::status_is('.print_r(
3328
                    $list,
3329
                    true
3330
                ).') on item '.$this->db_id,
3331
                0
3332
            );
3333
        }
3334
        $currentStatus = $this->get_status(true);
3335
        if (empty($currentStatus)) {
3336
            return false;
3337
        }
3338
        $found = false;
3339
        foreach ($list as $status) {
3340
            if (preg_match('/^'.$status.'$/i', $currentStatus)) {
3341
                if (self::DEBUG > 2) {
3342
                    error_log(
3343
                        'New LP - learnpathItem::status_is() - Found status '.
3344
                            $status.' corresponding to current status',
3345
                        0
3346
                    );
3347
                }
3348
                $found = true;
3349
3350
                return $found;
3351
            }
3352
        }
3353
        if (self::DEBUG > 2) {
3354
            error_log(
3355
                'New LP - learnpathItem::status_is() - Status '.
3356
                    $currentStatus.' did not match request',
3357
                0
3358
            );
3359
        }
3360
3361
        return $found;
3362
    }
3363
3364
    /**
3365
     * Updates the time info according to the given session_time.
3366
     *
3367
     * @param int $totalSec Time in seconds
3368
     */
3369
    public function update_time($totalSec = 0)
3370
    {
3371
        if (self::DEBUG > 0) {
3372
            error_log('learnpathItem::update_time('.$totalSec.')');
3373
        }
3374
        if ($totalSec >= 0) {
3375
            // Getting start time from finish time. The only problem in the calculation is it might be
3376
            // modified by the scripts processing time.
3377
            $now = time();
3378
            $start = $now - $totalSec;
3379
            $this->current_start_time = $start;
3380
            $this->current_stop_time = $now;
3381
        }
3382
    }
3383
3384
    /**
3385
     * Special scorm update time function. This function will update time
3386
     * directly into db for scorm objects.
3387
     *
3388
     * @param int $total_sec Total number of seconds
3389
     */
3390
    public function scorm_update_time($total_sec = 0)
3391
    {
3392
        $debug = self::DEBUG;
3393
        if ($debug) {
3394
            error_log('learnpathItem::scorm_update_time()');
3395
            error_log("total_sec: $total_sec");
3396
        }
3397
3398
        // Step 1 : get actual total time stored in db
3399
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3400
        $course_id = api_get_course_int_id();
3401
3402
        $sql = 'SELECT total_time, status
3403
                FROM '.$item_view_table.'
3404
                WHERE
3405
                    c_id = '.$course_id.' AND
3406
                    lp_item_id = "'.$this->db_id.'" AND
3407
                    lp_view_id = "'.$this->view_id.'" AND
3408
                    view_count = "'.$this->get_attempt_id().'"';
3409
        $result = Database::query($sql);
3410
        $row = Database::fetch_array($result);
3411
3412
        if (!isset($row['total_time'])) {
3413
            $total_time = 0;
3414
        } else {
3415
            $total_time = $row['total_time'];
3416
        }
3417
        if ($debug) {
3418
            error_log("Original total_time: $total_time");
3419
        }
3420
3421
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
3422
        $lp_id = (int) $this->lp_id;
3423
        $sql = "SELECT * FROM $lp_table WHERE iid = $lp_id";
3424
        $res = Database::query($sql);
3425
        $accumulateScormTime = 'false';
3426
        if (Database::num_rows($res) > 0) {
3427
            $row = Database::fetch_assoc($res);
3428
            $accumulateScormTime = $row['accumulate_scorm_time'];
3429
        }
3430
3431
        // Step 2.1 : if normal mode total_time = total_time + total_sec
3432
        if ($this->type == 'sco' && $accumulateScormTime != 0) {
3433
            if ($debug) {
3434
                error_log("accumulateScormTime is on. total_time modified: $total_time + $total_sec");
3435
            }
3436
            $total_time += $total_sec;
3437
        } else {
3438
            // Step 2.2 : if not cumulative mode total_time = total_time - last_update + total_sec
3439
            $total_sec = $this->fixAbusiveTime($total_sec);
3440
            if ($debug) {
3441
                error_log("after fix abusive: $total_sec");
3442
                error_log("total_time: $total_time");
3443
                error_log("this->last_scorm_session_time: ".$this->last_scorm_session_time);
3444
            }
3445
3446
            $total_time = $total_time - $this->last_scorm_session_time + $total_sec;
3447
            $this->last_scorm_session_time = $total_sec;
3448
3449
            if ($total_time < 0) {
3450
                $total_time = $total_sec;
3451
            }
3452
        }
3453
3454
        if ($debug) {
3455
            error_log("accumulate_scorm_time: $accumulateScormTime");
3456
            error_log("total_time modified: $total_time");
3457
        }
3458
3459
        // Step 3 update db only if status != completed, passed, browsed or seriousgamemode not activated
3460
        // @todo complete
3461
        $case_completed = [
3462
            'completed',
3463
            'passed',
3464
            'browsed',
3465
            'failed',
3466
        ];
3467
3468
        if ($this->seriousgame_mode != 1 ||
3469
            !in_array($row['status'], $case_completed)
3470
        ) {
3471
            $sql = "UPDATE $item_view_table
3472
                      SET total_time = '$total_time'
3473
                    WHERE
3474
                        c_id = $course_id AND
3475
                        lp_item_id = {$this->db_id} AND
3476
                        lp_view_id = {$this->view_id} AND
3477
                        view_count = {$this->get_attempt_id()}";
3478
            if ($debug) {
3479
                error_log('-------------total_time updated ------------------------');
3480
                error_log($sql);
3481
                error_log('-------------------------------------');
3482
            }
3483
            Database::query($sql);
3484
        }
3485
    }
3486
3487
    /**
3488
     * Set the total_time to 0 into db.
3489
     */
3490
    public function scorm_init_time()
3491
    {
3492
        $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3493
        $course_id = api_get_course_int_id();
3494
        $sql = 'UPDATE '.$table.'
3495
                SET total_time = 0,
3496
                    start_time = '.time().'
3497
                WHERE
3498
                    c_id = '.$course_id.' AND
3499
                    lp_item_id = "'.$this->db_id.'" AND
3500
                    lp_view_id = "'.$this->view_id.'" AND
3501
                    view_count = "'.$this->attempt_id.'"';
3502
        Database::query($sql);
3503
    }
3504
3505
    /**
3506
     * Write objectives to DB. This method is separate from write_to_db() because otherwise
3507
     * objectives are lost as a side effect to AJAX and session concurrent access.
3508
     *
3509
     * @return bool True or false on error
3510
     */
3511
    public function write_objectives_to_db()
3512
    {
3513
        if (self::DEBUG > 0) {
3514
            error_log('learnpathItem::write_objectives_to_db()', 0);
3515
        }
3516
        if (api_is_invitee()) {
3517
            // If the user is an invitee, we don't write anything to DB
3518
            return true;
3519
        }
3520
        $course_id = api_get_course_int_id();
3521
        if (is_array($this->objectives) && count($this->objectives) > 0) {
3522
            // Save objectives.
3523
            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3524
            $sql = "SELECT iid
3525
                    FROM $tbl
3526
                    WHERE
3527
                        c_id = $course_id AND
3528
                        lp_item_id = ".$this->db_id." AND
3529
                        lp_view_id = ".$this->view_id." AND
3530
                        view_count = ".$this->attempt_id;
3531
            $res = Database::query($sql);
3532
            if (Database::num_rows($res) > 0) {
3533
                $row = Database::fetch_array($res);
3534
                $lp_iv_id = $row[0];
3535
                if (self::DEBUG > 2) {
3536
                    error_log(
3537
                        'learnpathItem::write_to_db() - Got item_view_id '.
3538
                            $lp_iv_id.', now checking objectives ',
3539
                        0
3540
                    );
3541
                }
3542
                foreach ($this->objectives as $index => $objective) {
3543
                    $iva_table = Database::get_course_table(
3544
                        TABLE_LP_IV_OBJECTIVE
3545
                    );
3546
                    $iva_sql = "SELECT iid FROM $iva_table
3547
                                WHERE
3548
                                    c_id = $course_id AND
3549
                                    lp_iv_id = $lp_iv_id AND
3550
                                    objective_id = '".Database::escape_string($objective[0])."'";
3551
                    $iva_res = Database::query($iva_sql);
3552
                    // id(0), type(1), time(2), weighting(3),
3553
                    // correct_responses(4), student_response(5),
3554
                    // result(6), latency(7)
3555
                    if (Database::num_rows($iva_res) > 0) {
3556
                        // Update (or don't).
3557
                        $iva_row = Database::fetch_array($iva_res);
3558
                        $iva_id = $iva_row[0];
3559
                        $ivau_sql = "UPDATE $iva_table ".
3560
                            "SET objective_id = '".Database::escape_string($objective[0])."',".
3561
                            "status = '".Database::escape_string($objective[1])."',".
3562
                            "score_raw = '".Database::escape_string($objective[2])."',".
3563
                            "score_min = '".Database::escape_string($objective[4])."',".
3564
                            "score_max = '".Database::escape_string($objective[3])."' ".
3565
                            "WHERE c_id = $course_id AND iid = $iva_id";
3566
                        Database::query($ivau_sql);
3567
                    } else {
3568
                        // Insert new one.
3569
                        $params = [
3570
                            'c_id' => $course_id,
3571
                            'lp_iv_id' => $lp_iv_id,
3572
                            'order_id' => $index,
3573
                            'objective_id' => $objective[0],
3574
                            'status' => $objective[1],
3575
                            'score_raw' => $objective[2],
3576
                            'score_min' => $objective[4],
3577
                            'score_max' => $objective[3],
3578
                        ];
3579
3580
                        $insertId = Database::insert($iva_table, $params);
3581
                        if ($insertId) {
3582
                            $sql = "UPDATE $iva_table SET id = iid
3583
                                    WHERE iid = $insertId";
3584
                            Database::query($sql);
3585
                        }
3586
                    }
3587
                }
3588
            }
3589
        }
3590
    }
3591
3592
    /**
3593
     * Writes the current data to the database.
3594
     *
3595
     * @return bool Query result
3596
     */
3597
    public function write_to_db()
3598
    {
3599
        $debug = self::DEBUG;
3600
        if ($debug) {
3601
            error_log('learnpathItem::write_to_db()', 0);
3602
        }
3603
3604
        // Check the session visibility.
3605
        if (!api_is_allowed_to_session_edit()) {
3606
            if ($debug) {
3607
                error_log('return false api_is_allowed_to_session_edit');
3608
            }
3609
3610
            return false;
3611
        }
3612
        if (api_is_invitee()) {
3613
            // If the user is an invitee, we don't write anything to DB
3614
            return true;
3615
        }
3616
3617
        $course_id = api_get_course_int_id();
3618
        $mode = $this->get_lesson_mode();
3619
        $credit = $this->get_credit();
3620
        $total_time = ' ';
3621
        $my_status = ' ';
3622
3623
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3624
        $sql = 'SELECT status, total_time FROM '.$item_view_table.'
3625
                WHERE
3626
                    c_id = '.$course_id.' AND
3627
                    lp_item_id="'.$this->db_id.'" AND
3628
                    lp_view_id="'.$this->view_id.'" AND
3629
                    view_count="'.$this->get_attempt_id().'" ';
3630
        $rs_verified = Database::query($sql);
3631
        $row_verified = Database::fetch_array($rs_verified);
3632
3633
        $my_case_completed = [
3634
            'completed',
3635
            'passed',
3636
            'browsed',
3637
            'failed',
3638
        ];
3639
3640
        $oldTotalTime = $row_verified['total_time'];
3641
        $this->oldTotalTime = $oldTotalTime;
3642
3643
        $save = true;
3644
        if (isset($row_verified) && isset($row_verified['status'])) {
3645
            if (in_array($row_verified['status'], $my_case_completed)) {
3646
                $save = false;
3647
            }
3648
        }
3649
3650
        if ((($save === false && $this->type == 'sco') ||
3651
           ($this->type == 'sco' && ($credit == 'no-credit' || $mode == 'review' || $mode == 'browse'))) &&
3652
           ($this->seriousgame_mode != 1 && $this->type == 'sco')
3653
        ) {
3654
            if ($debug) {
3655
                error_log(
3656
                    "This info shouldn't be saved as the credit or lesson mode info prevent it"
3657
                );
3658
                error_log(
3659
                    'learnpathItem::write_to_db() - credit('.$credit.') or'.
3660
                    ' lesson_mode('.$mode.') prevent recording!',
3661
                    0
3662
                );
3663
            }
3664
        } else {
3665
            // Check the row exists.
3666
            $inserted = false;
3667
            // This a special case for multiple attempts and Chamilo exercises.
3668
            if ($this->type == 'quiz' &&
3669
                $this->get_prevent_reinit() == 0 &&
3670
                $this->get_status() == 'completed'
3671
            ) {
3672
                // We force the item to be restarted.
3673
                $this->restart();
3674
                $params = [
3675
                    "c_id" => $course_id,
3676
                    "total_time" => $this->get_total_time(),
3677
                    "start_time" => $this->current_start_time,
3678
                    "score" => $this->get_score(),
3679
                    "status" => $this->get_status(false),
3680
                    "max_score" => $this->get_max(),
3681
                    "lp_item_id" => $this->db_id,
3682
                    "lp_view_id" => $this->view_id,
3683
                    "view_count" => $this->get_attempt_id(),
3684
                    "suspend_data" => $this->current_data,
3685
                    //"max_time_allowed" => ,
3686
                    "lesson_location" => $this->lesson_location,
3687
                ];
3688
                if ($debug) {
3689
                    error_log(
3690
                        'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
3691
                        0
3692
                    );
3693
                }
3694
                $this->db_item_view_id = Database::insert($item_view_table, $params);
3695
                if ($this->db_item_view_id) {
3696
                    $sql = "UPDATE $item_view_table SET id = iid
3697
                            WHERE iid = ".$this->db_item_view_id;
3698
                    Database::query($sql);
3699
                    $inserted = true;
3700
                }
3701
            }
3702
3703
            $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3704
            $sql = "SELECT * FROM $item_view_table
3705
                    WHERE
3706
                        c_id = $course_id AND
3707
                        lp_item_id = ".$this->db_id." AND
3708
                        lp_view_id = ".$this->view_id." AND
3709
                        view_count = ".$this->get_attempt_id();
3710
            if ($debug) {
3711
                error_log(
3712
                    'learnpathItem::write_to_db() - Querying item_view: '.$sql,
3713
                    0
3714
                );
3715
            }
3716
3717
            $check_res = Database::query($sql);
3718
            // Depending on what we want (really), we'll update or insert a new row
3719
            // now save into DB.
3720
            if (!$inserted && Database::num_rows($check_res) < 1) {
3721
                $params = [
3722
                    "c_id" => $course_id,
3723
                    "total_time" => $this->get_total_time(),
3724
                    "start_time" => $this->current_start_time,
3725
                    "score" => $this->get_score(),
3726
                    "status" => $this->get_status(false),
3727
                    "max_score" => $this->get_max(),
3728
                    "lp_item_id" => $this->db_id,
3729
                    "lp_view_id" => $this->view_id,
3730
                    "view_count" => $this->get_attempt_id(),
3731
                    "suspend_data" => $this->current_data,
3732
                    //"max_time_allowed" => ,$this->get_max_time_allowed()
3733
                    "lesson_location" => $this->lesson_location,
3734
                ];
3735
3736
                if ($debug) {
3737
                    error_log(
3738
                        'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
3739
                        0
3740
                    );
3741
                }
3742
3743
                $this->db_item_view_id = Database::insert($item_view_table, $params);
3744
                if ($this->db_item_view_id) {
3745
                    $sql = "UPDATE $item_view_table SET id = iid
3746
                            WHERE iid = ".$this->db_item_view_id;
3747
                    Database::query($sql);
3748
                }
3749
            } else {
3750
                if ($this->type === 'hotpotatoes') {
3751
                    $params = [
3752
                        'total_time' => $this->get_total_time(),
3753
                        'start_time' => $this->get_current_start_time(),
3754
                        'score' => $this->get_score(),
3755
                        'status' => $this->get_status(false),
3756
                        'max_score' => $this->get_max(),
3757
                        'suspend_data' => $this->current_data,
3758
                        'lesson_location' => $this->lesson_location,
3759
                    ];
3760
                    $where = [
3761
                        'c_id = ? AND lp_item_id = ? AND lp_view_id = ? AND view_count = ?' => [
3762
                            $course_id,
3763
                            $this->db_id,
3764
                            $this->view_id,
3765
                            $this->get_attempt_id(),
3766
                        ],
3767
                    ];
3768
                    Database::update($item_view_table, $params, $where);
3769
                } else {
3770
                    // For all other content types...
3771
                    if ($this->type == 'quiz') {
3772
                        if ($debug) {
3773
                            error_log("item is quiz:");
3774
                        }
3775
                        $my_status = ' ';
3776
                        $total_time = ' ';
3777
                        if (!empty($_REQUEST['exeId'])) {
3778
                            $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
3779
                            $exeId = (int) $_REQUEST['exeId'];
3780
                            $sql = "SELECT exe_duration
3781
                                    FROM $table
3782
                                    WHERE exe_id = $exeId";
3783
                            if ($debug) {
3784
                                error_log($sql);
3785
                            }
3786
                            $res = Database::query($sql);
3787
                            $exeRow = Database::fetch_array($res);
3788
                            $duration = $exeRow['exe_duration'];
3789
                            $total_time = " total_time = ".$duration.", ";
3790
                            if ($debug) {
3791
                                error_log("quiz: $total_time");
3792
                            }
3793
                        }
3794
                    } else {
3795
                        $my_type_lp = learnpath::get_type_static($this->lp_id);
3796
                        // This is a array containing values finished
3797
                        $case_completed = [
3798
                            'completed',
3799
                            'passed',
3800
                            'browsed',
3801
                            'failed',
3802
                        ];
3803
3804
                        // Is not multiple attempts
3805
                        if ($this->seriousgame_mode == 1 && $this->type == 'sco') {
3806
                            $total_time = " total_time = total_time +".$this->get_total_time().", ";
3807
                            $my_status = " status = '".$this->get_status(false)."' ,";
3808
                            if ($debug) {
3809
                                error_log("seriousgame_mode time changed: $total_time");
3810
                            }
3811
                        } elseif ($this->get_prevent_reinit() == 1) {
3812
                            // Process of status verified into data base.
3813
                            $sql = 'SELECT status FROM '.$item_view_table.'
3814
                                    WHERE
3815
                                        c_id = '.$course_id.' AND
3816
                                        lp_item_id="'.$this->db_id.'" AND
3817
                                        lp_view_id="'.$this->view_id.'" AND
3818
                                        view_count="'.$this->get_attempt_id().'"
3819
                                    ';
3820
                            $rs_verified = Database::query($sql);
3821
                            $row_verified = Database::fetch_array($rs_verified);
3822
3823
                            // Get type lp: 1=lp dokeos and  2=scorm.
3824
                            // If not is completed or passed or browsed and learning path is scorm.
3825
                            if (!in_array($this->get_status(false), $case_completed) &&
3826
                                $my_type_lp == 2
3827
                            ) {
3828
                                $total_time = " total_time = total_time +".$this->get_total_time().", ";
3829
                                $my_status = " status = '".$this->get_status(false)."' ,";
3830
                                if ($debug) {
3831
                                    error_log("get_prevent_reinit = 1 time changed: $total_time");
3832
                                }
3833
                            } else {
3834
                                // Verified into database.
3835
                                if (!in_array($row_verified['status'], $case_completed) &&
3836
                                    $my_type_lp == 2
3837
                                ) {
3838
                                    $total_time = " total_time = total_time +".$this->get_total_time().", ";
3839
                                    $my_status = " status = '".$this->get_status(false)."' ,";
3840
                                    if ($debug) {
3841
                                        error_log("total_time time changed case 1: $total_time");
3842
                                    }
3843
                                } elseif (in_array($row_verified['status'], $case_completed) &&
3844
                                    $my_type_lp == 2 && $this->type != 'sco'
3845
                                ) {
3846
                                    $total_time = " total_time = total_time +".$this->get_total_time().", ";
3847
                                    $my_status = " status = '".$this->get_status(false)."' ,";
3848
                                    if ($debug) {
3849
                                        error_log("total_time time changed case 2: $total_time");
3850
                                    }
3851
                                } else {
3852
                                    if (($my_type_lp == 3 && $this->type == 'au') ||
3853
                                        ($my_type_lp == 1 && $this->type != 'dir')) {
3854
                                        // Is AICC or Chamilo LP
3855
                                        $total_time = " total_time = total_time + ".$this->get_total_time().", ";
3856
                                        $my_status = " status = '".$this->get_status(false)."' ,";
3857
                                        if ($debug) {
3858
                                            error_log("total_time time changed case 3: $total_time");
3859
                                        }
3860
                                    }
3861
                                }
3862
                            }
3863
                        } else {
3864
                            // Multiple attempts are allowed.
3865
                            if (in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
3866
                                // Reset zero new attempt ?
3867
                                $my_status = " status = '".$this->get_status(false)."' ,";
3868
                                if ($debug) {
3869
                                    error_log("total_time time changed Multiple attempt case 1: $total_time");
3870
                                }
3871
                            } elseif (!in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
3872
                                $total_time = " total_time = ".$this->get_total_time().", ";
3873
                                $my_status = " status = '".$this->get_status(false)."' ,";
3874
                                if ($debug) {
3875
                                    error_log("total_time time changed Multiple attempt case 2: $total_time");
3876
                                }
3877
                            } else {
3878
                                // It is chamilo LP.
3879
                                $total_time = " total_time = total_time +".$this->get_total_time().", ";
3880
                                $my_status = " status = '".$this->get_status(false)."' ,";
3881
                                if ($debug) {
3882
                                    error_log("total_time time changed Multiple attempt case 3: $total_time");
3883
                                }
3884
                            }
3885
3886
                            // This code line fixes the problem of wrong status.
3887
                            if ($my_type_lp == 2) {
3888
                                // Verify current status in multiples attempts.
3889
                                $sql = 'SELECT status FROM '.$item_view_table.'
3890
                                        WHERE
3891
                                            c_id = '.$course_id.' AND
3892
                                            lp_item_id="'.$this->db_id.'" AND
3893
                                            lp_view_id="'.$this->view_id.'" AND
3894
                                            view_count="'.$this->get_attempt_id().'" ';
3895
                                $rs_status = Database::query($sql);
3896
                                $current_status = Database::result(
3897
                                    $rs_status,
3898
                                    0,
3899
                                    'status'
3900
                                );
3901
                                if (in_array($current_status, $case_completed)) {
3902
                                    $my_status = '';
3903
                                    $total_time = '';
3904
                                } else {
3905
                                    $total_time = " total_time = total_time + ".$this->get_total_time().", ";
3906
                                }
3907
3908
                                if ($debug) {
3909
                                    error_log("total_time time my_type_lp: $total_time");
3910
                                }
3911
                            }
3912
                        }
3913
                    }
3914
3915
                    if ($this->type == 'sco') {
3916
                        //IF scorm scorm_update_time has already updated total_time in db
3917
                        //" . //start_time = ".$this->get_current_start_time().", " . //scorm_init_time does it
3918
                        ////" max_time_allowed = '".$this->get_max_time_allowed()."'," .
3919
                        $sql = "UPDATE $item_view_table SET
3920
                                    score = ".$this->get_score().",
3921
                                    $my_status
3922
                                    max_score = '".$this->get_max()."',
3923
                                    suspend_data = '".Database::escape_string($this->current_data)."',
3924
                                    lesson_location = '".$this->lesson_location."'
3925
                                WHERE
3926
                                    c_id = $course_id AND
3927
                                    lp_item_id = ".$this->db_id." AND
3928
                                    lp_view_id = ".$this->view_id."  AND
3929
                                    view_count = ".$this->get_attempt_id();
3930
                    } else {
3931
                        //" max_time_allowed = '".$this->get_max_time_allowed()."'," .
3932
                        $sql = "UPDATE $item_view_table SET
3933
                                    $total_time
3934
                                    start_time = ".$this->get_current_start_time().",
3935
                                    score = ".$this->get_score().",
3936
                                    $my_status
3937
                                    max_score = '".$this->get_max()."',
3938
                                    suspend_data = '".Database::escape_string($this->current_data)."',
3939
                                    lesson_location = '".$this->lesson_location."'
3940
                                WHERE
3941
                                    c_id = $course_id AND
3942
                                    lp_item_id = ".$this->db_id." AND
3943
                                    lp_view_id = ".$this->view_id." AND
3944
                                    view_count = ".$this->get_attempt_id();
3945
                    }
3946
                    $this->current_start_time = time();
3947
                }
3948
                if ($debug) {
3949
                    error_log('-------------------------------------------');
3950
                    error_log('learnpathItem::write_to_db() - Updating item_view:');
3951
                    error_log($sql);
3952
                    error_log('-------------------------------------------');
3953
                }
3954
                Database::query($sql);
3955
            }
3956
3957
            if (is_array($this->interactions) &&
3958
                count($this->interactions) > 0
3959
            ) {
3960
                // Save interactions.
3961
                $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3962
                $sql = "SELECT iid FROM $tbl
3963
                        WHERE
3964
                            c_id = $course_id AND
3965
                            lp_item_id = ".$this->db_id." AND
3966
                            lp_view_id = ".$this->view_id." AND
3967
                            view_count = ".$this->get_attempt_id();
3968
                $res = Database::query($sql);
3969
                if (Database::num_rows($res) > 0) {
3970
                    $row = Database::fetch_array($res);
3971
                    $lp_iv_id = $row[0];
3972
                    if ($debug) {
3973
                        error_log(
3974
                            'learnpathItem::write_to_db() - Got item_view_id '.
3975
                            $lp_iv_id.', now checking interactions ',
3976
                            0
3977
                        );
3978
                    }
3979
                    foreach ($this->interactions as $index => $interaction) {
3980
                        $correct_resp = '';
3981
                        if (is_array($interaction[4]) && !empty($interaction[4][0])) {
3982
                            foreach ($interaction[4] as $resp) {
3983
                                $correct_resp .= $resp.',';
3984
                            }
3985
                            $correct_resp = substr(
3986
                                $correct_resp,
3987
                                0,
3988
                                strlen($correct_resp) - 1
3989
                            );
3990
                        }
3991
                        $iva_table = Database::get_course_table(
3992
                            TABLE_LP_IV_INTERACTION
3993
                        );
3994
3995
                        //also check for the interaction ID as it must be unique for this SCO view
3996
                        $iva_sql = "SELECT iid FROM $iva_table
3997
                                    WHERE
3998
                                        c_id = $course_id AND
3999
                                        lp_iv_id = $lp_iv_id AND
4000
                                        (
4001
                                            order_id = $index OR
4002
                                            interaction_id = '".Database::escape_string($interaction[0])."'
4003
                                        )
4004
                                    ";
4005
                        $iva_res = Database::query($iva_sql);
4006
4007
                        $interaction[0] = isset($interaction[0]) ? $interaction[0] : '';
4008
                        $interaction[1] = isset($interaction[1]) ? $interaction[1] : '';
4009
                        $interaction[2] = isset($interaction[2]) ? $interaction[2] : '';
4010
                        $interaction[3] = isset($interaction[3]) ? $interaction[3] : '';
4011
                        $interaction[4] = isset($interaction[4]) ? $interaction[4] : '';
4012
                        $interaction[5] = isset($interaction[5]) ? $interaction[5] : '';
4013
                        $interaction[6] = isset($interaction[6]) ? $interaction[6] : '';
4014
                        $interaction[7] = isset($interaction[7]) ? $interaction[7] : '';
4015
4016
                        // id(0), type(1), time(2), weighting(3), correct_responses(4), student_response(5), result(6), latency(7)
4017
                        if (Database::num_rows($iva_res) > 0) {
4018
                            // Update (or don't).
4019
                            $iva_row = Database::fetch_array($iva_res);
4020
                            $iva_id = $iva_row[0];
4021
                            // Insert new one.
4022
                            $params = [
4023
                                'interaction_id' => $interaction[0],
4024
                                'interaction_type' => $interaction[1],
4025
                                'weighting' => $interaction[3],
4026
                                'completion_time' => $interaction[2],
4027
                                'correct_responses' => $correct_resp,
4028
                                'student_response' => $interaction[5],
4029
                                'result' => $interaction[6],
4030
                                'latency' => $interaction[7],
4031
                            ];
4032
                            Database::update(
4033
                                $iva_table,
4034
                                $params,
4035
                                [
4036
                                    'c_id = ? AND iid = ?' => [
4037
                                        $course_id,
4038
                                        $iva_id,
4039
                                    ],
4040
                                ]
4041
                            );
4042
                        } else {
4043
                            // Insert new one.
4044
                            $params = [
4045
                                'c_id' => $course_id,
4046
                                'order_id' => $index,
4047
                                'lp_iv_id' => $lp_iv_id,
4048
                                'interaction_id' => $interaction[0],
4049
                                'interaction_type' => $interaction[1],
4050
                                'weighting' => $interaction[3],
4051
                                'completion_time' => $interaction[2],
4052
                                'correct_responses' => $correct_resp,
4053
                                'student_response' => $interaction[5],
4054
                                'result' => $interaction[6],
4055
                                'latency' => $interaction[7],
4056
                            ];
4057
4058
                            $insertId = Database::insert($iva_table, $params);
4059
                            if ($insertId) {
4060
                                $sql = "UPDATE $iva_table SET id = iid
4061
                                        WHERE iid = $insertId";
4062
                                Database::query($sql);
4063
                            }
4064
                        }
4065
                    }
4066
                }
4067
            }
4068
        }
4069
4070
        if ($debug) {
4071
            error_log('End of learnpathItem::write_to_db()', 0);
4072
        }
4073
4074
        return true;
4075
    }
4076
4077
    /**
4078
     * Adds an audio file attached to the current item (store on disk and in db).
4079
     *
4080
     * @return bool|string|null
4081
     */
4082
    public function add_audio()
4083
    {
4084
        $course_info = api_get_course_info();
4085
        $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/';
4086
4087
        if (!is_dir($filepath.'audio')) {
4088
            mkdir(
4089
                $filepath.'audio',
4090
                api_get_permissions_for_new_directories()
4091
            );
4092
            $audio_id = add_document(
4093
                $course_info,
4094
                '/audio',
4095
                'folder',
4096
                0,
4097
                'audio'
4098
            );
4099
            api_item_property_update(
4100
                $course_info,
4101
                TOOL_DOCUMENT,
4102
                $audio_id,
4103
                'FolderCreated',
4104
                api_get_user_id(),
4105
                null,
4106
                null,
4107
                null,
4108
                null,
4109
                api_get_session_id()
4110
            );
4111
            api_item_property_update(
4112
                $course_info,
4113
                TOOL_DOCUMENT,
4114
                $audio_id,
4115
                'invisible',
4116
                api_get_user_id(),
4117
                null,
4118
                null,
4119
                null,
4120
                null,
4121
                api_get_session_id()
4122
            );
4123
        }
4124
4125
        $key = 'file';
4126
        if (!isset($_FILES[$key]['name']) || !isset($_FILES[$key]['tmp_name'])) {
4127
            return false;
4128
        }
4129
        $result = DocumentManager::upload_document(
4130
            $_FILES,
4131
            '/audio',
4132
            null,
4133
            null,
4134
            0,
4135
            'rename',
4136
            false,
4137
            false
4138
        );
4139
        $file_path = null;
4140
4141
        if ($result) {
4142
            $file_path = basename($result['path']);
4143
4144
            // Store the mp3 file in the lp_item table.
4145
            $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
4146
            $sql = "UPDATE $tbl_lp_item SET
4147
                        audio = '".Database::escape_string($file_path)."'
4148
                    WHERE iid = ".intval($this->db_id);
4149
            Database::query($sql);
4150
        }
4151
4152
        return $file_path;
4153
    }
4154
4155
    /**
4156
     * Adds an audio file to the current item, using a file already in documents.
4157
     *
4158
     * @param int $doc_id
4159
     *
4160
     * @return string
4161
     */
4162
    public function add_audio_from_documents($doc_id)
4163
    {
4164
        $course_info = api_get_course_info();
4165
        $document_data = DocumentManager::get_document_data_by_id(
4166
            $doc_id,
4167
            $course_info['code']
4168
        );
4169
4170
        $file_path = '';
4171
        if (!empty($document_data)) {
4172
            $file_path = substr($document_data['path'], 6);
4173
            $file_path = ltrim($file_path, "/");
4174
            // Store the mp3 file in the lp_item table.
4175
            $table = Database::get_course_table(TABLE_LP_ITEM);
4176
            $sql = "UPDATE $table SET
4177
                        audio = '".Database::escape_string($file_path)."'
4178
                    WHERE iid = ".intval($this->db_id);
4179
            Database::query($sql);
4180
        }
4181
4182
        return $file_path;
4183
    }
4184
4185
    /**
4186
     * Removes the relation between the current item and an audio file. The file
4187
     * is only removed from the lp_item table, but remains in the document table
4188
     * and directory.
4189
     *
4190
     * @return bool
4191
     */
4192
    public function remove_audio()
4193
    {
4194
        if (empty($this->db_id)) {
4195
            return false;
4196
        }
4197
        $table = Database::get_course_table(TABLE_LP_ITEM);
4198
        $sql = "UPDATE $table SET
4199
                audio = ''
4200
                WHERE iid IN (".$this->db_id.")";
4201
        Database::query($sql);
4202
    }
4203
4204
    /**
4205
     * Transform the SCORM status to a string that can be translated by Chamilo
4206
     * in different user languages.
4207
     *
4208
     * @param $status
4209
     * @param bool   $decorate
4210
     * @param string $type     classic|simple
4211
     *
4212
     * @return array|string
4213
     */
4214
    public static function humanize_status($status, $decorate = true, $type = 'classic')
4215
    {
4216
        $statusList = [
4217
            'completed' => 'ScormCompstatus',
4218
            'incomplete' => 'ScormIncomplete',
4219
            'failed' => 'ScormFailed',
4220
            'passed' => 'ScormPassed',
4221
            'browsed' => 'ScormBrowsed',
4222
            'not attempted' => 'ScormNotAttempted',
4223
        ];
4224
4225
        $myLessonStatus = get_lang($statusList[$status]);
4226
4227
        switch ($status) {
4228
            case 'completed':
4229
            case 'browsed':
4230
                $classStatus = 'info';
4231
                break;
4232
            case 'incomplete':
4233
                $classStatus = 'warning';
4234
                break;
4235
            case 'passed':
4236
                $classStatus = 'success';
4237
                break;
4238
            case 'failed':
4239
                $classStatus = 'important';
4240
                break;
4241
            default:
4242
                $classStatus = 'default';
4243
                break;
4244
        }
4245
4246
        if ($type == 'simple') {
4247
            if (in_array($status, ['failed', 'passed', 'browsed'])) {
4248
                $myLessonStatus = get_lang('ScormIncomplete');
4249
4250
                $classStatus = 'warning';
4251
            }
4252
        }
4253
4254
        if ($decorate) {
4255
            return Display::label($myLessonStatus, $classStatus);
4256
        } else {
4257
            return $myLessonStatus;
4258
        }
4259
    }
4260
4261
    /**
4262
     * @return float
4263
     */
4264
    public function getPrerequisiteMaxScore()
4265
    {
4266
        return $this->prerequisiteMaxScore;
4267
    }
4268
4269
    /**
4270
     * @param float $prerequisiteMaxScore
4271
     */
4272
    public function setPrerequisiteMaxScore($prerequisiteMaxScore)
4273
    {
4274
        $this->prerequisiteMaxScore = $prerequisiteMaxScore;
4275
    }
4276
4277
    /**
4278
     * @return float
4279
     */
4280
    public function getPrerequisiteMinScore()
4281
    {
4282
        return $this->prerequisiteMinScore;
4283
    }
4284
4285
    /**
4286
     * @param float $prerequisiteMinScore
4287
     */
4288
    public function setPrerequisiteMinScore($prerequisiteMinScore)
4289
    {
4290
        $this->prerequisiteMinScore = $prerequisiteMinScore;
4291
    }
4292
4293
    /**
4294
     * Check if this LP item has a created thread in the basis course from the forum of its LP.
4295
     *
4296
     * @param int $lpCourseId The course ID
4297
     *
4298
     * @return bool
4299
     */
4300
    public function lpItemHasThread($lpCourseId)
4301
    {
4302
        $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
4303
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4304
4305
        $fakeFrom = "
4306
            $forumThreadTable ft
4307
            INNER JOIN $itemProperty ip
4308
            ON (ft.thread_id = ip.ref AND ft.c_id = ip.c_id)
4309
        ";
4310
4311
        $resultData = Database::select(
4312
            'COUNT(ft.iid) AS qty',
4313
            $fakeFrom,
4314
            [
4315
                'where' => [
4316
                    'ip.visibility != ? AND ' => 2,
4317
                    'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
4318
                    'ft.c_id = ? AND ' => intval($lpCourseId),
4319
                    '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
4320
                        intval($this->db_id),
4321
                        "{$this->title} - {$this->db_id}",
4322
                        intval($this->db_id),
4323
                    ],
4324
                ],
4325
            ],
4326
            'first'
4327
        );
4328
4329
        if ($resultData['qty'] > 0) {
4330
            return true;
4331
        }
4332
4333
        return false;
4334
    }
4335
4336
    /**
4337
     * Get the forum thread info.
4338
     *
4339
     * @param int $lpCourseId  The course ID from the learning path
4340
     * @param int $lpSessionId Optional. The session ID from the learning path
4341
     *
4342
     * @return bool
4343
     */
4344
    public function getForumThread($lpCourseId, $lpSessionId = 0)
4345
    {
4346
        $lpSessionId = (int) $lpSessionId;
4347
        $lpCourseId = (int) $lpCourseId;
4348
4349
        $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
4350
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4351
4352
        $fakeFrom = "$forumThreadTable ft INNER JOIN $itemProperty ip ";
4353
4354
        if ($lpSessionId == 0) {
4355
            $fakeFrom .= "
4356
                ON (
4357
                    ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND (
4358
                        ft.session_id = ip.session_id OR ip.session_id IS NULL
4359
                    )
4360
                )
4361
            ";
4362
        } else {
4363
            $fakeFrom .= "
4364
                ON (
4365
                    ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND ft.session_id = ip.session_id
4366
                )
4367
            ";
4368
        }
4369
4370
        $resultData = Database::select(
4371
            'ft.*',
4372
            $fakeFrom,
4373
            [
4374
                'where' => [
4375
                    'ip.visibility != ? AND ' => 2,
4376
                    'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
4377
                    'ft.session_id = ? AND ' => $lpSessionId,
4378
                    'ft.c_id = ? AND ' => $lpCourseId,
4379
                    '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
4380
                        intval($this->db_id),
4381
                        "{$this->title} - {$this->db_id}",
4382
                        intval($this->db_id),
4383
                    ],
4384
                ],
4385
            ],
4386
            'first'
4387
        );
4388
4389
        if (empty($resultData)) {
4390
            return false;
4391
        }
4392
4393
        return $resultData;
4394
    }
4395
4396
    /**
4397
     * Create a forum thread for this learning path item.
4398
     *
4399
     * @param int $currentForumId The forum ID to add the new thread
4400
     *
4401
     * @return int The forum thread if was created. Otherwise return false
4402
     */
4403
    public function createForumThread($currentForumId)
4404
    {
4405
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
4406
4407
        $currentForumId = (int) $currentForumId;
4408
4409
        $em = Database::getManager();
4410
        $threadRepo = $em->getRepository('ChamiloCourseBundle:CForumThread');
4411
        $forumThread = $threadRepo->findOneBy([
4412
            'threadTitle' => "{$this->title} - {$this->db_id}",
4413
            'forumId' => $currentForumId,
4414
        ]);
4415
4416
        if (!$forumThread) {
4417
            $forumInfo = get_forum_information($currentForumId);
4418
4419
            store_thread(
4420
                $forumInfo,
4421
                [
4422
                    'forum_id' => $currentForumId,
4423
                    'thread_id' => 0,
4424
                    'gradebook' => 0,
4425
                    'post_title' => "{$this->name} - {$this->db_id}",
4426
                    'post_text' => $this->description,
4427
                    'category_id' => 1,
4428
                    'numeric_calification' => 0,
4429
                    'calification_notebook_title' => 0,
4430
                    'weight_calification' => 0.00,
4431
                    'thread_peer_qualify' => 0,
4432
                    'lp_item_id' => $this->db_id,
4433
                ],
4434
                [],
4435
                false
4436
            );
4437
4438
            return;
4439
        }
4440
4441
        $forumThread->setLpItemId($this->db_id);
4442
4443
        $em->persist($forumThread);
4444
        $em->flush();
4445
    }
4446
4447
    /**
4448
     * Allow dissociate a forum to this LP item.
4449
     *
4450
     * @param int $threadIid The thread id
4451
     *
4452
     * @return bool
4453
     */
4454
    public function dissociateForumThread($threadIid)
4455
    {
4456
        $threadIid = (int) $threadIid;
4457
        $em = Database::getManager();
4458
4459
        $forumThread = $em->find('ChamiloCourseBundle:CForumThread', $threadIid);
4460
4461
        if (!$forumThread) {
4462
            return false;
4463
        }
4464
4465
        $forumThread->setThreadTitle("{$this->get_title()} - {$this->db_id}");
4466
        $forumThread->setLpItemId(0);
4467
4468
        $em->persist($forumThread);
4469
        $em->flush();
4470
4471
        return true;
4472
    }
4473
4474
    /**
4475
     * @return int
4476
     */
4477
    public function getLastScormSessionTime()
4478
    {
4479
        return $this->last_scorm_session_time;
4480
    }
4481
4482
    /**
4483
     * @return int
4484
     */
4485
    public function getIid()
4486
    {
4487
        return $this->iId;
4488
    }
4489
4490
    /**
4491
     * @param int    $user_id
4492
     * @param string $prereqs_string
4493
     * @param array  $refs_list
4494
     *
4495
     * @return bool
4496
     */
4497
    public function getStatusFromOtherSessions($user_id, $prereqs_string, $refs_list)
4498
    {
4499
        $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
4500
        $lp_view = Database::get_course_table(TABLE_LP_VIEW);
4501
        $course_id = api_get_course_int_id();
4502
        $user_id = (int) $user_id;
4503
4504
        // Check results from another sessions:
4505
        $checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
4506
        if ($checkOtherSessions) {
4507
            // Check items
4508
            $sql = "SELECT iid FROM $lp_view
4509
                    WHERE
4510
                        c_id = $course_id AND
4511
                        user_id = $user_id  AND
4512
                        lp_id = $this->lp_id AND
4513
                        session_id <> 0
4514
                    ";
4515
            $result = Database::query($sql);
4516
            $resultFromOtherSessions = false;
4517
            while ($row = Database::fetch_array($result)) {
4518
                $lpIid = $row['iid'];
4519
                $sql = "SELECT status FROM $lp_item_view
4520
                        WHERE
4521
                            c_id = $course_id AND
4522
                            lp_view_id = $lpIid AND
4523
                            lp_item_id = $refs_list[$prereqs_string]
4524
                        LIMIT 1";
4525
                $resultRow = Database::query($sql);
4526
                if (Database::num_rows($resultRow)) {
4527
                    $statusResult = Database::fetch_array($resultRow);
4528
                    $status = $statusResult['status'];
4529
                    $checked = $status == $this->possible_status[2] || $status == $this->possible_status[3];
4530
                    if ($checked) {
4531
                        $resultFromOtherSessions = true;
4532
                        break;
4533
                    }
4534
                }
4535
            }
4536
4537
            return $resultFromOtherSessions;
4538
        }
4539
    }
4540
}
4541