Passed
Push — master ( 518cb9...ab560b )
by Julito
10:37
created

learnpathItem::add_audio()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 47
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 31
nc 6
nop 0
dl 0
loc 47
rs 9.1128
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class learnpathItem
6
 * lp_item defines items belonging to a learnpath. Each item has a name,
7
 * a score, a use time and additional information that enables tracking a user's
8
 * progress in a learning path.
9
 *
10
 * @package chamilo.learnpath
11
 *
12
 * @author  Yannick Warnier <[email protected]>
13
 */
14
class learnpathItem
15
{
16
    const DEBUG = 0; // Logging parameter.
17
    public $iId;
18
    public $attempt_id; // Also called "objectives" SCORM-wise.
19
    public $audio; // The path to an audio file (stored in document/audio/).
20
    public $children = []; // Contains the ids of children items.
21
    public $condition; // If this item has a special condition embedded.
22
    public $current_score;
23
    public $current_start_time;
24
    public $current_stop_time;
25
    public $current_data = '';
26
    public $db_id;
27
    public $db_item_view_id = '';
28
    public $description = '';
29
    public $file;
30
    /**
31
     * At the moment, interactions are just an array of arrays with a structure
32
     * of 8 text fields: id(0), type(1), time(2), weighting(3),
33
     * correct_responses(4), student_response(5), result(6), latency(7).
34
     */
35
    public $interactions = [];
36
    public $interactions_count = 0;
37
    public $objectives = [];
38
    public $objectives_count = 0;
39
    public $launch_data = '';
40
    public $lesson_location = '';
41
    public $level = 0;
42
    public $core_exit = '';
43
    //var $location; // Only set this for SCORM?
44
    public $lp_id;
45
    public $max_score;
46
    public $mastery_score;
47
    public $min_score;
48
    public $max_time_allowed = '';
49
    public $name;
50
    public $next;
51
    public $parent;
52
    public $path; // In some cases the exo_id = exercise_id in courseDb exercices table.
53
    public $possible_status = [
54
        'not attempted',
55
        'incomplete',
56
        'completed',
57
        'passed',
58
        'failed',
59
        'browsed',
60
    ];
61
    public $prereq_string = '';
62
    public $prereq_alert = '';
63
    public $prereqs = [];
64
    public $previous;
65
    public $prevent_reinit = 1; // 0 =  multiple attempts   1 = one attempt
66
    public $seriousgame_mode;
67
    public $ref;
68
    public $save_on_close = true;
69
    public $search_did = null;
70
    public $status;
71
    public $title;
72
    /**
73
     * Type attribute can contain one of
74
     * link|student_publication|dir|quiz|document|forum|thread.
75
     */
76
    public $type;
77
    public $view_id;
78
    public $oldTotalTime;
79
    //var used if absolute session time mode is used
80
    private $last_scorm_session_time = 0;
81
    private $prerequisiteMaxScore;
82
    private $prerequisiteMinScore;
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 null|array $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
149
        if (isset($row['launch_data'])) {
150
            $this->launch_data = $row['launch_data'];
151
        }
152
        $this->save_on_close = true;
153
        $this->db_id = $id;
154
155
        // Load children list
156
        if (!empty($this->lp_id)) {
157
            $sql = "SELECT iid FROM $items_table
158
                    WHERE
159
                        c_id = $course_id AND
160
                        lp_id = ".$this->lp_id." AND
161
                        parent_item_id = $id";
162
            $res = Database::query($sql);
163
            if (Database::num_rows($res) > 0) {
164
                while ($row = Database::fetch_assoc($res)) {
165
                    $this->children[] = $row['iid'];
166
                }
167
            }
168
169
            // Get search_did.
170
            if (api_get_setting('search_enabled') == 'true') {
171
                $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
172
                $sql = 'SELECT *
173
                        FROM %s
174
                        WHERE 
175
                            course_code=\'%s\' AND 
176
                            tool_id=\'%s\' AND 
177
                            ref_id_high_level=%s AND 
178
                            ref_id_second_level=%d
179
                        LIMIT 1';
180
                // TODO: Verify if it's possible to assume the actual course instead
181
                // of getting it from db.
182
                $sql = sprintf(
183
                    $sql,
184
                    $tbl_se_ref,
185
                    api_get_course_id(),
186
                    TOOL_LEARNPATH,
187
                    $this->lp_id,
188
                    $id
189
                );
190
                $res = Database::query($sql);
191
                if (Database::num_rows($res) > 0) {
192
                    $se_ref = Database::fetch_array($res);
193
                    $this->search_did = (int) $se_ref['search_did'];
194
                }
195
            }
196
        }
197
        $this->seriousgame_mode = 0;
198
        $this->audio = $row['audio'];
199
        if (self::DEBUG > 0) {
200
            error_log(
201
                'New LP - End of learnpathItem constructor for item '.$id,
202
                0
203
            );
204
        }
205
    }
206
207
    /**
208
     * Adds a child to the current item.
209
     *
210
     * @param int $item The child item ID
211
     */
212
    public function add_child($item)
213
    {
214
        if (self::DEBUG > 0) {
215
            error_log('learnpathItem::add_child()', 0);
216
        }
217
        if (!empty($item)) {
218
            // Do not check in DB as we expect the call to come from the
219
            // learnpath class which should be aware of any fake.
220
            $this->children[] = $item;
221
        }
222
    }
223
224
    /**
225
     * Adds an interaction to the current item.
226
     *
227
     * @param int   $index  Index (order ID) of the interaction inside this item
228
     * @param array $params Array of parameters:
229
     *                      id(0), type(1), time(2), weighting(3), correct_responses(4),
230
     *                      student_response(5), result(6), latency(7)
231
     */
232
    public function add_interaction($index, $params)
233
    {
234
        $this->interactions[$index] = $params;
235
        // Take the current maximum index to generate the interactions_count.
236
        if (($index + 1) > $this->interactions_count) {
237
            $this->interactions_count = $index + 1;
238
        }
239
    }
240
241
    /**
242
     * Adds an objective to the current item.
243
     *
244
     * @param    array    Array of parameters:
245
     * id(0), status(1), score_raw(2), score_max(3), score_min(4)
246
     */
247
    public function add_objective($index, $params)
248
    {
249
        if (empty($params[0])) {
250
            return null;
251
        }
252
        $this->objectives[$index] = $params;
253
        // Take the current maximum index to generate the objectives_count.
254
        if ((count($this->objectives) + 1) > $this->objectives_count) {
255
            $this->objectives_count = (count($this->objectives) + 1);
256
        }
257
    }
258
259
    /**
260
     * Closes/stops the item viewing. Finalises runtime values.
261
     * If required, save to DB.
262
     *
263
     * @return bool True on success, false otherwise
264
     */
265
    public function close()
266
    {
267
        if (self::DEBUG > 0) {
268
            error_log('learnpathItem::close()', 0);
269
        }
270
        $this->current_stop_time = time();
271
        $type = $this->get_type();
272
        if ($type != 'sco') {
273
            if ($type == TOOL_QUIZ || $type == TOOL_HOTPOTATOES) {
274
                $this->get_status(
275
                    true,
276
                    true
277
                ); // Update status (second option forces the update).
278
            } else {
279
                $this->status = $this->possible_status[2];
280
            }
281
        }
282
        if ($this->save_on_close) {
283
            $this->save();
284
        }
285
286
        return true;
287
    }
288
289
    /**
290
     * Deletes all traces of this item in the database.
291
     *
292
     * @return bool true. Doesn't check for errors yet.
293
     */
294
    public function delete()
295
    {
296
        if (self::DEBUG > 0) {
297
            error_log('learnpath_item::delete() for item '.$this->db_id, 0);
298
        }
299
        $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
300
        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
301
        $course_id = api_get_course_int_id();
302
303
        $sql = "DELETE FROM $lp_item_view
304
                WHERE c_id = $course_id AND lp_item_id = ".$this->db_id;
305
        if (self::DEBUG > 0) {
306
            error_log('Deleting from lp_item_view: '.$sql, 0);
307
        }
308
        Database::query($sql);
309
310
        $sql = "SELECT * FROM $lp_item
311
                WHERE iid = ".$this->db_id;
312
        $res_sel = Database::query($sql);
313
        if (Database::num_rows($res_sel) < 1) {
314
            return false;
315
        }
316
317
        $sql = "DELETE FROM $lp_item
318
                WHERE iid = ".$this->db_id;
319
        Database::query($sql);
320
        if (self::DEBUG > 0) {
321
            error_log('Deleting from lp_item: '.$sql);
322
        }
323
324
        if (api_get_setting('search_enabled') == 'true') {
325
            if (!is_null($this->search_did)) {
326
                $di = new ChamiloIndexer();
327
                $di->remove_document($this->search_did);
328
            }
329
        }
330
331
        return true;
332
    }
333
334
    /**
335
     * Drops a child from the children array.
336
     *
337
     * @param string $item index of child item to drop
338
     */
339
    public function drop_child($item)
340
    {
341
        if (self::DEBUG > 0) {
342
            error_log('learnpathItem::drop_child()', 0);
343
        }
344
        if (!empty($item)) {
345
            foreach ($this->children as $index => $child) {
346
                if ($child == $item) {
347
                    $this->children[$index] = null;
348
                }
349
            }
350
        }
351
    }
352
353
    /**
354
     * Gets the current attempt_id for this user on this item.
355
     *
356
     * @return int attempt_id for this item view by this user or 1 if none defined
357
     */
358
    public function get_attempt_id()
359
    {
360
        if (self::DEBUG > 0) {
361
            error_log(
362
                'learnpathItem::get_attempt_id() on item '.$this->db_id,
363
                0
364
            );
365
        }
366
        $res = 1;
367
        if (!empty($this->attempt_id)) {
368
            $res = (int) $this->attempt_id;
369
        }
370
        if (self::DEBUG > 0) {
371
            error_log(
372
                'New LP - End of learnpathItem::get_attempt_id() on item '.
373
                $this->db_id.' - Returning '.$res,
374
                0
375
            );
376
        }
377
378
        return $res;
379
    }
380
381
    /**
382
     * Gets a list of the item's children.
383
     *
384
     * @return array Array of children items IDs
385
     */
386
    public function get_children()
387
    {
388
        if (self::DEBUG > 0) {
389
            error_log('learnpathItem::get_children()', 0);
390
        }
391
        $list = [];
392
        foreach ($this->children as $child) {
393
            if (!empty($child)) {
394
                $list[] = $child;
395
            }
396
        }
397
398
        return $list;
399
    }
400
401
    /**
402
     * Gets the core_exit value from the database.
403
     */
404
    public function get_core_exit()
405
    {
406
        return $this->core_exit;
407
    }
408
409
    /**
410
     * Gets the credit information (rather scorm-stuff) based on current status
411
     * and reinit autorization. Credit tells the sco(content) if Chamilo will
412
     * record the data it is sent (credit) or not (no-credit).
413
     *
414
     * @return string 'credit' or 'no-credit'. Defaults to 'credit'
415
     *                Because if we don't know enough about this item, it's probably because
416
     *                it was never used before.
417
     */
418
    public function get_credit()
419
    {
420
        if (self::DEBUG > 1) {
421
            error_log('learnpathItem::get_credit()', 0);
422
        }
423
        $credit = 'credit';
424
        // Now check the value of prevent_reinit (if it's 0, return credit as
425
        // the default was).
426
        // If prevent_reinit == 1 (or more).
427
        if ($this->get_prevent_reinit() != 0) {
428
            // If status is not attempted or incomplete, credit anyway.
429
            // Otherwise:
430
            // Check the status in the database rather than in the object, as
431
            // checking in the object would always return "no-credit" when we
432
            // want to set it to completed.
433
            $status = $this->get_status(true);
434
            if (self::DEBUG > 2) {
435
                error_log(
436
                    'learnpathItem::get_credit() - get_prevent_reinit!=0 and '.
437
                    'status is '.$status,
438
                    0
439
                );
440
            }
441
            //0=not attempted - 1 = incomplete
442
            if ($status != $this->possible_status[0] &&
443
                $status != $this->possible_status[1]
444
            ) {
445
                $credit = 'no-credit';
446
            }
447
        }
448
        if (self::DEBUG > 1) {
449
            error_log("learnpathItem::get_credit() returns: $credit");
450
        }
451
452
        return $credit;
453
    }
454
455
    /**
456
     * Gets the current start time property.
457
     *
458
     * @return int Current start time, or current time if none
459
     */
460
    public function get_current_start_time()
461
    {
462
        if (self::DEBUG > 0) {
463
            error_log('learnpathItem::get_current_start_time()', 0);
464
        }
465
        if (empty($this->current_start_time)) {
466
            return time();
467
        } else {
468
            return $this->current_start_time;
469
        }
470
    }
471
472
    /**
473
     * Gets the item's description.
474
     *
475
     * @return string Description
476
     */
477
    public function get_description()
478
    {
479
        if (self::DEBUG > 0) {
480
            error_log('learnpathItem::get_description()', 0);
481
        }
482
        if (empty($this->description)) {
483
            return '';
484
        }
485
486
        return $this->description;
487
    }
488
489
    /**
490
     * Gets the file path from the course's root directory, no matter what
491
     * tool it is from.
492
     *
493
     * @param string $path_to_scorm_dir
494
     *
495
     * @return string The file path, or an empty string if there is no file
496
     *                attached, or '-1' if the file must be replaced by an error page
497
     */
498
    public function get_file_path($path_to_scorm_dir = '')
499
    {
500
        $course_id = api_get_course_int_id();
501
        if (self::DEBUG > 0) {
502
            error_log('learnpathItem::get_file_path()', 0);
503
        }
504
        $path = $this->get_path();
505
        $type = $this->get_type();
506
507
        if (empty($path)) {
508
            if ($type == 'dir') {
509
                return '';
510
            } else {
511
                return '-1';
512
            }
513
        } elseif ($path == strval(intval($path))) {
514
            // The path is numeric, so it is a reference to a Chamilo object.
515
            switch ($type) {
516
                case 'dir':
517
                    return '';
518
                case TOOL_DOCUMENT:
519
                    $table_doc = Database::get_course_table(TABLE_DOCUMENT);
520
                    $sql = 'SELECT path
521
                            FROM '.$table_doc.'
522
                            WHERE
523
                                c_id = '.$course_id.' AND
524
                                iid = '.$path;
525
                    $res = Database::query($sql);
526
                    $row = Database::fetch_array($res);
527
                    $real_path = 'document'.$row['path'];
528
529
                    return $real_path;
530
                case TOOL_STUDENTPUBLICATION:
531
                case TOOL_QUIZ:
532
                case TOOL_FORUM:
533
                case TOOL_THREAD:
534
                case TOOL_LINK:
535
                default:
536
                    return '-1';
537
            }
538
        } else {
539
            if (!empty($path_to_scorm_dir)) {
540
                $path = $path_to_scorm_dir.$path;
541
            }
542
543
            return $path;
544
        }
545
    }
546
547
    /**
548
     * Gets the DB ID.
549
     *
550
     * @return int Database ID for the current item
551
     */
552
    public function get_id()
553
    {
554
        if (self::DEBUG > 1) {
555
            error_log('learnpathItem::get_id()', 0);
556
        }
557
        if (!empty($this->db_id)) {
558
            return $this->db_id;
559
        }
560
        // TODO: Check this return value is valid for children classes (SCORM?).
561
        return 0;
562
    }
563
564
    /**
565
     * Loads the interactions into the item object, from the database.
566
     * If object interactions exist, they will be overwritten by this function,
567
     * using the database elements only.
568
     */
569
    public function load_interactions()
570
    {
571
        $this->interactions = [];
572
        $course_id = api_get_course_int_id();
573
        $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
574
        $sql = "SELECT id FROM $tbl
575
                WHERE
576
                    c_id = $course_id AND
577
                    lp_item_id = ".$this->db_id." AND
578
                    lp_view_id = ".$this->view_id." AND
579
                    view_count = ".$this->attempt_id;
580
        $res = Database::query($sql);
581
        if (Database::num_rows($res) > 0) {
582
            $row = Database::fetch_array($res);
583
            $lp_iv_id = $row[0];
584
            $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
585
            $sql = "SELECT * FROM $iva_table
586
                    WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
587
            $res_sql = Database::query($sql);
588
            while ($row = Database::fetch_array($res_sql)) {
589
                $this->interactions[$row['interaction_id']] = [
590
                    $row['interaction_id'],
591
                    $row['interaction_type'],
592
                    $row['weighting'],
593
                    $row['completion_time'],
594
                    $row['correct_responses'],
595
                    $row['student_responses'],
596
                    $row['result'],
597
                    $row['latency'],
598
                ];
599
            }
600
        }
601
    }
602
603
    /**
604
     * Gets the current count of interactions recorded in the database.
605
     *
606
     * @param bool $checkdb Whether to count from database or not (defaults to no)
607
     *
608
     * @return int The current number of interactions recorder
609
     */
610
    public function get_interactions_count($checkdb = false)
611
    {
612
        if (self::DEBUG > 1) {
613
            error_log('learnpathItem::get_interactions_count()', 0);
614
        }
615
        $return = 0;
616
        $course_id = api_get_course_int_id();
617
618
        if ($checkdb) {
619
            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
620
            $sql = "SELECT iid FROM $tbl
621
                    WHERE
622
                        c_id = $course_id AND
623
                        lp_item_id = ".$this->db_id." AND
624
                        lp_view_id = ".$this->view_id." AND
625
                        view_count = ".$this->get_attempt_id();
626
            $res = Database::query($sql);
627
            if (Database::num_rows($res) > 0) {
628
                $row = Database::fetch_array($res);
629
                $lp_iv_id = $row[0];
630
                $iva_table = Database::get_course_table(
631
                    TABLE_LP_IV_INTERACTION
632
                );
633
                $sql = "SELECT count(id) as mycount
634
                        FROM $iva_table
635
                        WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
636
                $res_sql = Database::query($sql);
637
                if (Database::num_rows($res_sql) > 0) {
638
                    $row = Database::fetch_array($res_sql);
639
                    $return = $row['mycount'];
640
                }
641
            }
642
        } else {
643
            if (!empty($this->interactions_count)) {
644
                $return = $this->interactions_count;
645
            }
646
        }
647
648
        return $return;
649
    }
650
651
    /**
652
     * Gets the JavaScript array content to fill the interactions array.
653
     *
654
     * @param bool $checkdb Whether to check directly into the database (default no)
655
     *
656
     * @return string An empty string if no interaction, a JS array definition otherwise
657
     */
658
    public function get_interactions_js_array($checkdb = false)
659
    {
660
        $return = '';
661
        if ($checkdb) {
662
            $this->load_interactions(true);
663
        }
664
        foreach ($this->interactions as $id => $in) {
665
            $return .= "[
666
                '$id',
667
                '".$in[1]."',
668
                '".$in[2]."',
669
                '".$in[3]."',
670
                '".$in[4]."',
671
                '".$in[5]."',
672
                '".$in[6]."',
673
                '".$in[7]."'],";
674
        }
675
        if (!empty($return)) {
676
            $return = substr($return, 0, -1);
677
        }
678
679
        return $return;
680
    }
681
682
    /**
683
     * Gets the current count of objectives recorded in the database.
684
     *
685
     * @return int The current number of objectives recorder
686
     */
687
    public function get_objectives_count()
688
    {
689
        if (self::DEBUG > 1) {
690
            error_log('learnpathItem::get_objectives_count()', 0);
691
        }
692
        $res = 0;
693
        if (!empty($this->objectives_count)) {
694
            $res = $this->objectives_count;
695
        }
696
697
        return $res;
698
    }
699
700
    /**
701
     * Gets the launch_data field found in imsmanifests (this is SCORM- or
702
     * AICC-related, really).
703
     *
704
     * @return string Launch data as found in imsmanifest and stored in
705
     *                Chamilo (read only). Defaults to ''.
706
     */
707
    public function get_launch_data()
708
    {
709
        if (self::DEBUG > 0) {
710
            error_log('learnpathItem::get_launch_data()', 0);
711
        }
712
        if (!empty($this->launch_data)) {
713
            return str_replace(
714
                ["\r", "\n", "'"],
715
                ['\r', '\n', "\\'"],
716
                $this->launch_data
717
            );
718
        }
719
720
        return '';
721
    }
722
723
    /**
724
     * Gets the lesson location.
725
     *
726
     * @return string lesson location as recorded by the SCORM and AICC
727
     *                elements. Defaults to ''
728
     */
729
    public function get_lesson_location()
730
    {
731
        if (self::DEBUG > 0) {
732
            error_log('learnpathItem::get_lesson_location()', 0);
733
        }
734
        if (!empty($this->lesson_location)) {
735
            return str_replace(
736
                ["\r", "\n", "'"],
737
                ['\r', '\n', "\\'"],
738
                $this->lesson_location
739
            );
740
        } else {
741
            return '';
742
        }
743
    }
744
745
    /**
746
     * Gets the lesson_mode (scorm feature, but might be used by aicc as well
747
     * as chamilo paths).
748
     *
749
     * The "browse" mode is not supported yet (because there is no such way of
750
     * seeing a sco in Chamilo)
751
     *
752
     * @return string 'browse','normal' or 'review'. Defaults to 'normal'
753
     */
754
    public function get_lesson_mode()
755
    {
756
        $mode = 'normal';
757
        if ($this->get_prevent_reinit() != 0) {
758
            // If prevent_reinit == 0
759
            $my_status = $this->get_status();
760
            if ($my_status != $this->possible_status[0] && $my_status != $this->possible_status[1]) {
761
                $mode = 'review';
762
            }
763
        }
764
765
        return $mode;
766
    }
767
768
    /**
769
     * Gets the depth level.
770
     *
771
     * @return int Level. Defaults to 0
772
     */
773
    public function get_level()
774
    {
775
        if (self::DEBUG > 0) {
776
            error_log('learnpathItem::get_level()', 0);
777
        }
778
        if (empty($this->level)) {
779
            return 0;
780
        }
781
782
        return $this->level;
783
    }
784
785
    /**
786
     * Gets the mastery score.
787
     */
788
    public function get_mastery_score()
789
    {
790
        if (self::DEBUG > 0) {
791
            error_log('learnpathItem::get_mastery_score()', 0);
792
        }
793
        if (isset($this->mastery_score)) {
794
            return $this->mastery_score;
795
        } else {
796
            return -1;
797
        }
798
    }
799
800
    /**
801
     * Gets the maximum (score).
802
     *
803
     * @return int Maximum score. Defaults to 100 if nothing else is defined
804
     */
805
    public function get_max()
806
    {
807
        if (self::DEBUG > 0) {
808
            error_log('learnpathItem::get_max()', 0);
809
        }
810
        if ($this->type == 'sco') {
811
            if (isset($this->view_max_score) &&
812
                !empty($this->view_max_score) &&
813
                $this->view_max_score > 0
814
            ) {
815
                return $this->view_max_score;
816
            } elseif (isset($this->view_max_score) &&
817
                $this->view_max_score === ''
818
            ) {
819
                return $this->view_max_score;
820
            } else {
821
                if (!empty($this->max_score)) {
822
                    return $this->max_score;
823
                } else {
824
                    return 100;
825
                }
826
            }
827
        } else {
828
            if (!empty($this->max_score)) {
829
                return $this->max_score;
830
            } else {
831
                return 100;
832
            }
833
        }
834
    }
835
836
    /**
837
     * Gets the maximum time allowed for this user in this attempt on this item.
838
     *
839
     * @return string Time string in SCORM format
840
     *                (HH:MM:SS or HH:MM:SS.SS or HHHH:MM:SS.SS)
841
     */
842
    public function get_max_time_allowed()
843
    {
844
        if (self::DEBUG > 0) {
845
            error_log('learnpathItem::get_max_time_allowed()', 0);
846
        }
847
        if (!empty($this->max_time_allowed)) {
848
            return $this->max_time_allowed;
849
        } else {
850
            return '';
851
        }
852
    }
853
854
    /**
855
     * Gets the minimum (score).
856
     *
857
     * @return int Minimum score. Defaults to 0
858
     */
859
    public function get_min()
860
    {
861
        if (self::DEBUG > 0) {
862
            error_log('learnpathItem::get_min()', 0);
863
        }
864
        if (!empty($this->min_score)) {
865
            return $this->min_score;
866
        } else {
867
            return 0;
868
        }
869
    }
870
871
    /**
872
     * Gets the parent ID.
873
     *
874
     * @return int Parent ID. Defaults to null
875
     */
876
    public function get_parent()
877
    {
878
        if (self::DEBUG > 0) {
879
            error_log('learnpathItem::get_parent()', 0);
880
        }
881
        if (!empty($this->parent)) {
882
            return $this->parent;
883
        }
884
        // TODO: Check this return value is valid for children classes (SCORM?).
885
        return null;
886
    }
887
888
    /**
889
     * Gets the path attribute.
890
     *
891
     * @return string Path. Defaults to ''
892
     */
893
    public function get_path()
894
    {
895
        if (self::DEBUG > 0) {
896
            error_log('learnpathItem::get_path()', 0);
897
        }
898
        if (empty($this->path)) {
899
            return '';
900
        }
901
902
        return $this->path;
903
    }
904
905
    /**
906
     * Gets the prerequisites string.
907
     *
908
     * @return string empty string or prerequisites string if defined
909
     */
910
    public function get_prereq_string()
911
    {
912
        if (self::DEBUG > 0) {
913
            error_log('learnpathItem::get_prereq_string()', 0);
914
        }
915
        if (!empty($this->prereq_string)) {
916
            return $this->prereq_string;
917
        } else {
918
            return '';
919
        }
920
    }
921
922
    /**
923
     * Gets the prevent_reinit attribute value (and sets it if not set already).
924
     *
925
     * @return int 1 or 0 (defaults to 1)
926
     */
927
    public function get_prevent_reinit()
928
    {
929
        if (self::DEBUG > 2) {
930
            error_log('learnpathItem::get_prevent_reinit()', 0);
931
        }
932
        if (!isset($this->prevent_reinit)) {
933
            if (!empty($this->lp_id)) {
934
                $table = Database::get_course_table(TABLE_LP_MAIN);
935
                $sql = "SELECT prevent_reinit
936
                    FROM $table
937
                    WHERE iid = ".$this->lp_id;
938
                $res = Database::query($sql);
939
                if (Database::num_rows($res) < 1) {
940
                    $this->error = "Could not find parent learnpath in lp table";
941
                    if (self::DEBUG > 2) {
942
                        error_log(
943
                            'New LP - End of learnpathItem::get_prevent_reinit() - Returning false',
944
                            0
945
                        );
946
                    }
947
948
                    return false;
949
                } else {
950
                    $row = Database::fetch_array($res);
951
                    $this->prevent_reinit = $row['prevent_reinit'];
952
                }
953
            } else {
954
                // Prevent reinit is always 1 by default - see learnpath.class.php
955
                $this->prevent_reinit = 1;
956
            }
957
        }
958
        if (self::DEBUG > 2) {
959
            error_log(
960
                'New LP - End of learnpathItem::get_prevent_reinit() - Returned '.$this->prevent_reinit,
961
                0
962
            );
963
        }
964
965
        return $this->prevent_reinit;
966
    }
967
968
    /**
969
     * Returns 1 if seriousgame_mode is activated, 0 otherwise.
970
     *
971
     * @return int (0 or 1)
972
     *
973
     * @deprecated seriousgame_mode seems not to be used
974
     *
975
     * @author ndiechburg <[email protected]>
976
     */
977
    public function get_seriousgame_mode()
978
    {
979
        if (self::DEBUG > 2) {
980
            error_log('learnpathItem::get_seriousgame_mode()', 0);
981
        }
982
        if (!isset($this->seriousgame_mode)) {
983
            if (!empty($this->lp_id)) {
984
                $table = Database::get_course_table(TABLE_LP_MAIN);
985
                $sql = "SELECT seriousgame_mode
986
                        FROM $table
987
                        WHERE iid = ".$this->lp_id;
988
                $res = Database::query($sql);
989
                if (Database::num_rows($res) < 1) {
990
                    $this->error = "Could not find parent learnpath in learnpath table";
991
                    if (self::DEBUG > 2) {
992
                        error_log(
993
                            'New LP - End of learnpathItem::get_seriousgame_mode() - Returning false',
994
                            0
995
                        );
996
                    }
997
998
                    return false;
999
                } else {
1000
                    $row = Database::fetch_array($res);
1001
                    $this->seriousgame_mode = isset($row['seriousgame_mode']) ? $row['seriousgame_mode'] : 0;
1002
                }
1003
            } else {
1004
                $this->seriousgame_mode = 0; //SeriousGame mode is always off by default
1005
            }
1006
        }
1007
        if (self::DEBUG > 2) {
1008
            error_log(
1009
                'New LP - End of learnpathItem::get_seriousgame_mode() - Returned '.$this->seriousgame_mode,
1010
                0
1011
            );
1012
        }
1013
1014
        return $this->seriousgame_mode;
1015
    }
1016
1017
    /**
1018
     * Gets the item's reference column.
1019
     *
1020
     * @return string The item's reference field (generally used for SCORM identifiers)
1021
     */
1022
    public function get_ref()
1023
    {
1024
        return $this->ref;
1025
    }
1026
1027
    /**
1028
     * Gets the list of included resources as a list of absolute or relative
1029
     * paths of resources included in the current item. This allows for a
1030
     * better SCORM export. The list will generally include pictures, flash
1031
     * objects, java applets, or any other stuff included in the source of the
1032
     * current item. The current item is expected to be an HTML file. If it
1033
     * is not, then the function will return and empty list.
1034
     *
1035
     * @param string $type        (one of the Chamilo tools) - optional (otherwise takes the current item's type)
1036
     * @param string $abs_path    absolute file path - optional (otherwise takes the current item's path)
1037
     * @param int    $recursivity level of recursivity we're in
1038
     *
1039
     * @return array List of file paths.
1040
     *               An additional field containing 'local' or 'remote' helps determine if
1041
     *               the file should be copied into the zip or just linked
1042
     */
1043
    public function get_resources_from_source(
1044
        $type = null,
1045
        $abs_path = null,
1046
        $recursivity = 1
1047
    ) {
1048
        $max = 5;
1049
        if ($recursivity > $max) {
1050
            return [];
1051
        }
1052
1053
        $type = empty($type) ? $this->get_type() : $type;
1054
1055
        if (!isset($abs_path)) {
1056
            $path = $this->get_file_path();
1057
            $abs_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$path;
1058
        }
1059
1060
        $files_list = [];
1061
        switch ($type) {
1062
            case TOOL_DOCUMENT:
1063
            case TOOL_QUIZ:
1064
            case 'sco':
1065
                // Get the document and, if HTML, open it.
1066
                if (!is_file($abs_path)) {
1067
                    // The file could not be found.
1068
                    return false;
1069
                }
1070
1071
                // for now, read the whole file in one go (that's gonna be
1072
                // a problem when the file is too big).
1073
                $info = pathinfo($abs_path);
1074
                $ext = $info['extension'];
1075
1076
                switch (strtolower($ext)) {
1077
                    case 'html':
1078
                    case 'htm':
1079
                    case 'shtml':
1080
                    case 'css':
1081
                        $wantedAttributes = [
1082
                            'src',
1083
                            'url',
1084
                            '@import',
1085
                            'href',
1086
                            'value',
1087
                        ];
1088
1089
                        // Parse it for included resources.
1090
                        $fileContent = file_get_contents($abs_path);
1091
                        // Get an array of attributes from the HTML source.
1092
                        $attributes = DocumentManager::parse_HTML_attributes(
1093
                            $fileContent,
1094
                            $wantedAttributes
1095
                        );
1096
1097
                        // Look at 'src' attributes in this file
1098
                        foreach ($wantedAttributes as $attr) {
1099
                            if (isset($attributes[$attr])) {
1100
                                // Find which kind of path these are (local or remote).
1101
                                $sources = $attributes[$attr];
1102
1103
                                foreach ($sources as $source) {
1104
                                    // Skip what is obviously not a resource.
1105
                                    if (strpos($source, "+this.")) {
1106
                                        continue;
1107
                                    } // javascript code - will still work unaltered.
1108
                                    if (strpos($source, '.') === false) {
1109
                                        continue;
1110
                                    } // No dot, should not be an external file anyway.
1111
                                    if (strpos($source, 'mailto:')) {
1112
                                        continue;
1113
                                    } // mailto link.
1114
                                    if (strpos($source, ';') &&
1115
                                        !strpos($source, '&amp;')
1116
                                    ) {
1117
                                        continue;
1118
                                    } // Avoid code - that should help.
1119
1120
                                    if ($attr == 'value') {
1121
                                        if (strpos($source, 'mp3file')) {
1122
                                            $files_list[] = [
1123
                                                substr(
1124
                                                    $source,
1125
                                                    0,
1126
                                                    strpos(
1127
                                                        $source,
1128
                                                        '.swf'
1129
                                                    ) + 4
1130
                                                ),
1131
                                                'local',
1132
                                                'abs',
1133
                                            ];
1134
                                            $mp3file = substr(
1135
                                                $source,
1136
                                                strpos(
1137
                                                    $source,
1138
                                                    'mp3file='
1139
                                                ) + 8
1140
                                            );
1141
                                            if (substr($mp3file, 0, 1) == '/') {
1142
                                                $files_list[] = [
1143
                                                    $mp3file,
1144
                                                    'local',
1145
                                                    'abs',
1146
                                                ];
1147
                                            } else {
1148
                                                $files_list[] = [
1149
                                                    $mp3file,
1150
                                                    'local',
1151
                                                    'rel',
1152
                                                ];
1153
                                            }
1154
                                        } elseif (strpos($source, 'flv=') === 0) {
1155
                                            $source = substr($source, 4);
1156
                                            if (strpos($source, '&') > 0) {
1157
                                                $source = substr(
1158
                                                    $source,
1159
                                                    0,
1160
                                                    strpos($source, '&')
1161
                                                );
1162
                                            }
1163
                                            if (strpos($source, '://') > 0) {
1164
                                                if (strpos($source, api_get_path(WEB_PATH)) !== false) {
1165
                                                    // We found the current portal url.
1166
                                                    $files_list[] = [
1167
                                                        $source,
1168
                                                        'local',
1169
                                                        'url',
1170
                                                    ];
1171
                                                } else {
1172
                                                    // We didn't find any trace of current portal.
1173
                                                    $files_list[] = [
1174
                                                        $source,
1175
                                                        'remote',
1176
                                                        'url',
1177
                                                    ];
1178
                                                }
1179
                                            } else {
1180
                                                $files_list[] = [
1181
                                                    $source,
1182
                                                    'local',
1183
                                                    'abs',
1184
                                                ];
1185
                                            }
1186
                                            continue; // Skipping anything else to avoid two entries
1187
                                            //(while the others can have sub-files in their url, flv's can't).
1188
                                        }
1189
                                    }
1190
1191
                                    if (strpos($source, '://') > 0) {
1192
                                        // Cut at '?' in a URL with params.
1193
                                        if (strpos($source, '?') > 0) {
1194
                                            $second_part = substr(
1195
                                                $source,
1196
                                                strpos($source, '?')
1197
                                            );
1198
                                            if (strpos($second_part, '://') > 0) {
1199
                                                // If the second part of the url contains a url too,
1200
                                                // treat the second one before cutting.
1201
                                                $pos1 = strpos(
1202
                                                    $second_part,
1203
                                                    '='
1204
                                                );
1205
                                                $pos2 = strpos(
1206
                                                    $second_part,
1207
                                                    '&'
1208
                                                );
1209
                                                $second_part = substr(
1210
                                                    $second_part,
1211
                                                    $pos1 + 1,
1212
                                                    $pos2 - ($pos1 + 1)
1213
                                                );
1214
                                                if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
1215
                                                    // We found the current portal url.
1216
                                                    $files_list[] = [
1217
                                                        $second_part,
1218
                                                        'local',
1219
                                                        'url',
1220
                                                    ];
1221
                                                    $in_files_list[] = self::get_resources_from_source(
1222
                                                        TOOL_DOCUMENT,
1223
                                                        $second_part,
1224
                                                        $recursivity + 1
1225
                                                    );
1226
                                                    if (count($in_files_list) > 0) {
1227
                                                        $files_list = array_merge(
1228
                                                            $files_list,
1229
                                                            $in_files_list
1230
                                                        );
1231
                                                    }
1232
                                                } else {
1233
                                                    // We didn't find any trace of current portal.
1234
                                                    $files_list[] = [
1235
                                                        $second_part,
1236
                                                        'remote',
1237
                                                        'url',
1238
                                                    ];
1239
                                                }
1240
                                            } elseif (strpos($second_part, '=') > 0) {
1241
                                                if (substr($second_part, 0, 1) === '/') {
1242
                                                    // Link starts with a /,
1243
                                                    // making it absolute (relative to DocumentRoot).
1244
                                                    $files_list[] = [
1245
                                                        $second_part,
1246
                                                        'local',
1247
                                                        'abs',
1248
                                                    ];
1249
                                                    $in_files_list[] = self::get_resources_from_source(
1250
                                                        TOOL_DOCUMENT,
1251
                                                        $second_part,
1252
                                                        $recursivity + 1
1253
                                                    );
1254
                                                    if (count($in_files_list) > 0) {
1255
                                                        $files_list = array_merge(
1256
                                                            $files_list,
1257
                                                            $in_files_list
1258
                                                        );
1259
                                                    }
1260
                                                } elseif (strstr($second_part, '..') === 0) {
1261
                                                    // Link is relative but going back in the hierarchy.
1262
                                                    $files_list[] = [
1263
                                                        $second_part,
1264
                                                        'local',
1265
                                                        'rel',
1266
                                                    ];
1267
                                                    $dir = dirname(
1268
                                                        $abs_path
1269
                                                    );
1270
                                                    $new_abs_path = realpath(
1271
                                                        $dir.'/'.$second_part
1272
                                                    );
1273
                                                    $in_files_list[] = self::get_resources_from_source(
1274
                                                        TOOL_DOCUMENT,
1275
                                                        $new_abs_path,
1276
                                                        $recursivity + 1
1277
                                                    );
1278
                                                    if (count($in_files_list) > 0) {
1279
                                                        $files_list = array_merge(
1280
                                                            $files_list,
1281
                                                            $in_files_list
1282
                                                        );
1283
                                                    }
1284
                                                } else {
1285
                                                    // No starting '/', making it relative to current document's path.
1286
                                                    if (substr($second_part, 0, 2) == './') {
1287
                                                        $second_part = substr(
1288
                                                            $second_part,
1289
                                                            2
1290
                                                        );
1291
                                                    }
1292
                                                    $files_list[] = [
1293
                                                        $second_part,
1294
                                                        'local',
1295
                                                        'rel',
1296
                                                    ];
1297
                                                    $dir = dirname(
1298
                                                        $abs_path
1299
                                                    );
1300
                                                    $new_abs_path = realpath(
1301
                                                        $dir.'/'.$second_part
1302
                                                    );
1303
                                                    $in_files_list[] = self::get_resources_from_source(
1304
                                                        TOOL_DOCUMENT,
1305
                                                        $new_abs_path,
1306
                                                        $recursivity + 1
1307
                                                    );
1308
                                                    if (count($in_files_list) > 0) {
1309
                                                        $files_list = array_merge(
1310
                                                            $files_list,
1311
                                                            $in_files_list
1312
                                                        );
1313
                                                    }
1314
                                                }
1315
                                            }
1316
                                            // Leave that second part behind now.
1317
                                            $source = substr(
1318
                                                $source,
1319
                                                0,
1320
                                                strpos($source, '?')
1321
                                            );
1322
                                            if (strpos($source, '://') > 0) {
1323
                                                if (strpos($source, api_get_path(WEB_PATH)) !== false) {
1324
                                                    // We found the current portal url.
1325
                                                    $files_list[] = [
1326
                                                        $source,
1327
                                                        'local',
1328
                                                        'url',
1329
                                                    ];
1330
                                                    $in_files_list[] = self::get_resources_from_source(
1331
                                                        TOOL_DOCUMENT,
1332
                                                        $source,
1333
                                                        $recursivity + 1
1334
                                                    );
1335
                                                    if (count($in_files_list) > 0) {
1336
                                                        $files_list = array_merge(
1337
                                                            $files_list,
1338
                                                            $in_files_list
1339
                                                        );
1340
                                                    }
1341
                                                } else {
1342
                                                    // We didn't find any trace of current portal.
1343
                                                    $files_list[] = [
1344
                                                        $source,
1345
                                                        'remote',
1346
                                                        'url',
1347
                                                    ];
1348
                                                }
1349
                                            } else {
1350
                                                // No protocol found, make link local.
1351
                                                if (substr($source, 0, 1) === '/') {
1352
                                                    // Link starts with a /, making it absolute (relative to DocumentRoot).
1353
                                                    $files_list[] = [
1354
                                                        $source,
1355
                                                        'local',
1356
                                                        'abs',
1357
                                                    ];
1358
                                                    $in_files_list[] = self::get_resources_from_source(
1359
                                                        TOOL_DOCUMENT,
1360
                                                        $source,
1361
                                                        $recursivity + 1
1362
                                                    );
1363
                                                    if (count($in_files_list) > 0) {
1364
                                                        $files_list = array_merge(
1365
                                                            $files_list,
1366
                                                            $in_files_list
1367
                                                        );
1368
                                                    }
1369
                                                } elseif (strstr($source, '..') === 0) {
1370
                                                    // Link is relative but going back in the hierarchy.
1371
                                                    $files_list[] = [
1372
                                                        $source,
1373
                                                        'local',
1374
                                                        'rel',
1375
                                                    ];
1376
                                                    $dir = dirname(
1377
                                                        $abs_path
1378
                                                    );
1379
                                                    $new_abs_path = realpath(
1380
                                                        $dir.'/'.$source
1381
                                                    );
1382
                                                    $in_files_list[] = self::get_resources_from_source(
1383
                                                        TOOL_DOCUMENT,
1384
                                                        $new_abs_path,
1385
                                                        $recursivity + 1
1386
                                                    );
1387
                                                    if (count($in_files_list) > 0) {
1388
                                                        $files_list = array_merge(
1389
                                                            $files_list,
1390
                                                            $in_files_list
1391
                                                        );
1392
                                                    }
1393
                                                } else {
1394
                                                    // No starting '/', making it relative to current document's path.
1395
                                                    if (substr($source, 0, 2) == './') {
1396
                                                        $source = substr(
1397
                                                            $source,
1398
                                                            2
1399
                                                        );
1400
                                                    }
1401
                                                    $files_list[] = [
1402
                                                        $source,
1403
                                                        'local',
1404
                                                        'rel',
1405
                                                    ];
1406
                                                    $dir = dirname(
1407
                                                        $abs_path
1408
                                                    );
1409
                                                    $new_abs_path = realpath(
1410
                                                        $dir.'/'.$source
1411
                                                    );
1412
                                                    $in_files_list[] = self::get_resources_from_source(
1413
                                                        TOOL_DOCUMENT,
1414
                                                        $new_abs_path,
1415
                                                        $recursivity + 1
1416
                                                    );
1417
                                                    if (count($in_files_list) > 0) {
1418
                                                        $files_list = array_merge(
1419
                                                            $files_list,
1420
                                                            $in_files_list
1421
                                                        );
1422
                                                    }
1423
                                                }
1424
                                            }
1425
                                        }
1426
1427
                                        // Found some protocol there.
1428
                                        if (strpos($source, api_get_path(WEB_PATH)) !== false) {
1429
                                            // We found the current portal url.
1430
                                            $files_list[] = [
1431
                                                $source,
1432
                                                'local',
1433
                                                'url',
1434
                                            ];
1435
                                            $in_files_list[] = self::get_resources_from_source(
1436
                                                TOOL_DOCUMENT,
1437
                                                $source,
1438
                                                $recursivity + 1
1439
                                            );
1440
                                            if (count($in_files_list) > 0) {
1441
                                                $files_list = array_merge(
1442
                                                    $files_list,
1443
                                                    $in_files_list
1444
                                                );
1445
                                            }
1446
                                        } else {
1447
                                            // We didn't find any trace of current portal.
1448
                                            $files_list[] = [
1449
                                                $source,
1450
                                                'remote',
1451
                                                'url',
1452
                                            ];
1453
                                        }
1454
                                    } else {
1455
                                        // No protocol found, make link local.
1456
                                        if (substr($source, 0, 1) === '/') {
1457
                                            // Link starts with a /, making it absolute (relative to DocumentRoot).
1458
                                            $files_list[] = [
1459
                                                $source,
1460
                                                'local',
1461
                                                'abs',
1462
                                            ];
1463
                                            $in_files_list[] = self::get_resources_from_source(
1464
                                                TOOL_DOCUMENT,
1465
                                                $source,
1466
                                                $recursivity + 1
1467
                                            );
1468
                                            if (count($in_files_list) > 0) {
1469
                                                $files_list = array_merge(
1470
                                                    $files_list,
1471
                                                    $in_files_list
1472
                                                );
1473
                                            }
1474
                                        } elseif (strstr($source, '..') === 0) {
1475
                                            // Link is relative but going back in the hierarchy.
1476
                                            $files_list[] = [
1477
                                                $source,
1478
                                                'local',
1479
                                                'rel',
1480
                                            ];
1481
                                            $dir = dirname($abs_path);
1482
                                            $new_abs_path = realpath(
1483
                                                $dir.'/'.$source
1484
                                            );
1485
                                            $in_files_list[] = self::get_resources_from_source(
1486
                                                TOOL_DOCUMENT,
1487
                                                $new_abs_path,
1488
                                                $recursivity + 1
1489
                                            );
1490
                                            if (count($in_files_list) > 0) {
1491
                                                $files_list = array_merge(
1492
                                                    $files_list,
1493
                                                    $in_files_list
1494
                                                );
1495
                                            }
1496
                                        } else {
1497
                                            // No starting '/', making it relative to current document's path.
1498
                                            if (strpos($source, 'width=') ||
1499
                                                strpos($source, 'autostart=')
1500
                                            ) {
1501
                                                continue;
1502
                                            }
1503
1504
                                            if (substr($source, 0, 2) == './') {
1505
                                                $source = substr(
1506
                                                    $source,
1507
                                                    2
1508
                                                );
1509
                                            }
1510
                                            $files_list[] = [
1511
                                                $source,
1512
                                                'local',
1513
                                                'rel',
1514
                                            ];
1515
                                            $dir = dirname($abs_path);
1516
                                            $new_abs_path = realpath(
1517
                                                $dir.'/'.$source
1518
                                            );
1519
                                            $in_files_list[] = self::get_resources_from_source(
1520
                                                TOOL_DOCUMENT,
1521
                                                $new_abs_path,
1522
                                                $recursivity + 1
1523
                                            );
1524
                                            if (count($in_files_list) > 0) {
1525
                                                $files_list = array_merge(
1526
                                                    $files_list,
1527
                                                    $in_files_list
1528
                                                );
1529
                                            }
1530
                                        }
1531
                                    }
1532
                                }
1533
                            }
1534
                        }
1535
                        break;
1536
                    default:
1537
                        break;
1538
                }
1539
1540
                break;
1541
            default: // Ignore.
1542
                break;
1543
        }
1544
1545
        $checked_files_list = [];
1546
        $checked_array_list = [];
1547
        foreach ($files_list as $idx => $file) {
1548
            if (!empty($file[0])) {
1549
                if (!in_array($file[0], $checked_files_list)) {
1550
                    $checked_files_list[] = $files_list[$idx][0];
1551
                    $checked_array_list[] = $files_list[$idx];
1552
                }
1553
            }
1554
        }
1555
1556
        return $checked_array_list;
1557
    }
1558
1559
    /**
1560
     * Gets the score.
1561
     *
1562
     * @return float The current score or 0 if no score set yet
1563
     */
1564
    public function get_score()
1565
    {
1566
        if (self::DEBUG > 0) {
1567
            error_log('learnpathItem::get_score()', 0);
1568
        }
1569
        $res = 0;
1570
        if (!empty($this->current_score)) {
1571
            $res = $this->current_score;
1572
        }
1573
        if (self::DEBUG > 1) {
1574
            error_log(
1575
                'New LP - Out of learnpathItem::get_score() - returning '.$res,
1576
                0
1577
            );
1578
        }
1579
1580
        return $res;
1581
    }
1582
1583
    /**
1584
     * Gets the item status.
1585
     *
1586
     * @param bool $check_db     Do or don't check into the database for the
1587
     *                           latest value. Optional. Default is true
1588
     * @param bool $update_local Do or don't update the local attribute
1589
     *                           value with what's been found in DB
1590
     *
1591
     * @return string Current status or 'Not attempted' if no status set yet
1592
     */
1593
    public function get_status($check_db = true, $update_local = false)
1594
    {
1595
        $course_id = api_get_course_int_id();
1596
        $debug = self::DEBUG;
1597
        if ($debug > 0) {
1598
            error_log('learnpathItem::get_status() on item '.$this->db_id, 0);
1599
        }
1600
        if ($check_db) {
1601
            if ($debug > 2) {
1602
                error_log('learnpathItem::get_status(): checking db', 0);
1603
            }
1604
            if (!empty($this->db_item_view_id) && !empty($course_id)) {
1605
                $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
1606
                $sql = "SELECT status FROM $table
1607
                        WHERE
1608
                            c_id = $course_id AND
1609
                            iid = '".$this->db_item_view_id."' AND
1610
                            view_count = '".$this->get_attempt_id()."'";
1611
1612
                if ($debug > 2) {
1613
                    error_log(
1614
                        'learnpathItem::get_status() - Checking DB: '.$sql,
1615
                        0
1616
                    );
1617
                }
1618
1619
                $res = Database::query($sql);
1620
                if (Database::num_rows($res) == 1) {
1621
                    $row = Database::fetch_array($res);
1622
                    if ($update_local) {
1623
                        if ($debug > 2) {
1624
                            error_log(
1625
                                'learnpathItem::set_status() :'.$row['status'],
1626
                                0
1627
                            );
1628
                        }
1629
                        $this->set_status($row['status']);
1630
                    }
1631
                    if ($debug > 2) {
1632
                        error_log(
1633
                            'learnpathItem::get_status() - Returning db value '.$row['status'],
1634
                            0
1635
                        );
1636
                    }
1637
1638
                    return $row['status'];
1639
                }
1640
            }
1641
        } else {
1642
            if ($debug > 2) {
1643
                error_log(
1644
                    'learnpathItem::get_status() - in get_status: using attrib',
1645
                    0
1646
                );
1647
            }
1648
            if (!empty($this->status)) {
1649
                if ($debug > 2) {
1650
                    error_log(
1651
                        'learnpathItem::get_status() - Returning attrib: '.$this->status,
1652
                        0
1653
                    );
1654
                }
1655
1656
                return $this->status;
1657
            }
1658
        }
1659
1660
        if ($debug > 2) {
1661
            error_log(
1662
                'learnpathItem::get_status() - Returning default '.$this->possible_status[0],
1663
                0
1664
            );
1665
        }
1666
1667
        return $this->possible_status[0];
1668
    }
1669
1670
    /**
1671
     * Gets the suspend data.
1672
     */
1673
    public function get_suspend_data()
1674
    {
1675
        if (self::DEBUG > 0) {
1676
            error_log('learnpathItem::get_suspend_data()', 0);
1677
        }
1678
        // TODO: Improve cleaning of breaklines ... it works but is it really
1679
        // a beautiful way to do it ?
1680
        if (!empty($this->current_data)) {
1681
            return str_replace(
1682
                ["\r", "\n", "'"],
1683
                ['\r', '\n', "\\'"],
1684
                $this->current_data
1685
            );
1686
        } else {
1687
            return '';
1688
        }
1689
    }
1690
1691
    /**
1692
     * @param string $origin
1693
     * @param string $time
1694
     *
1695
     * @return string
1696
     */
1697
    public static function getScormTimeFromParameter(
1698
        $origin = 'php',
1699
        $time = null
1700
    ) {
1701
        $h = get_lang('h');
1702
        if (!isset($time)) {
1703
            if ($origin == 'js') {
1704
                return '00 : 00: 00';
1705
            } else {
1706
                return '00 '.$h.' 00 \' 00"';
1707
            }
1708
        } else {
1709
            return api_format_time($time, $origin);
1710
        }
1711
    }
1712
1713
    /**
1714
     * Gets the total time spent on this item view so far.
1715
     *
1716
     * @param string   $origin     Origin of the request. If coming from PHP,
1717
     *                             send formatted as xxhxx'xx", otherwise use scorm format 00:00:00
1718
     * @param int|null $given_time Given time is a default time to return formatted
1719
     * @param bool     $query_db   Whether to get the value from db or from memory
1720
     *
1721
     * @return string A string with the time in SCORM format
1722
     */
1723
    public function get_scorm_time(
1724
        $origin = 'php',
1725
        $given_time = null,
1726
        $query_db = false
1727
    ) {
1728
        $time = null;
1729
        $course_id = api_get_course_int_id();
1730
        if (!isset($given_time)) {
1731
            if (self::DEBUG > 2) {
1732
                error_log(
1733
                    'learnpathItem::get_scorm_time(): given time empty, current_start_time = '.$this->current_start_time,
1734
                    0
1735
                );
1736
            }
1737
            if ($query_db === true) {
1738
                $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
1739
                $sql = "SELECT start_time, total_time
1740
                        FROM $table
1741
                        WHERE
1742
                            c_id = $course_id AND
1743
                            iid = '".$this->db_item_view_id."' AND
1744
                            view_count = '".$this->get_attempt_id()."'";
1745
                $res = Database::query($sql);
1746
                $row = Database::fetch_array($res);
1747
                $start = $row['start_time'];
1748
                $stop = $start + $row['total_time'];
1749
            } else {
1750
                $start = $this->current_start_time;
1751
                $stop = $this->current_stop_time;
1752
            }
1753
            if (!empty($start)) {
1754
                if (!empty($stop)) {
1755
                    $time = $stop - $start;
1756
                } else {
1757
                    $time = time() - $start;
1758
                }
1759
            }
1760
        } else {
1761
            $time = $given_time;
1762
        }
1763
        if (self::DEBUG > 2) {
1764
            error_log(
1765
                'learnpathItem::get_scorm_time(): intermediate = '.$time,
1766
                0
1767
            );
1768
        }
1769
        $time = api_format_time($time, $origin);
1770
1771
        return $time;
1772
    }
1773
1774
    /**
1775
     * Get the extra terms (tags) that identify this item.
1776
     *
1777
     * @return mixed
1778
     */
1779
    public function get_terms()
1780
    {
1781
        $table = Database::get_course_table(TABLE_LP_ITEM);
1782
        $sql = "SELECT * FROM $table
1783
                WHERE iid = ".intval($this->db_id);
1784
        $res = Database::query($sql);
1785
        $row = Database::fetch_array($res);
1786
1787
        return $row['terms'];
1788
    }
1789
1790
    /**
1791
     * Returns the item's title.
1792
     *
1793
     * @return string Title
1794
     */
1795
    public function get_title()
1796
    {
1797
        if (self::DEBUG > 0) {
1798
            error_log('learnpathItem::get_title()', 0);
1799
        }
1800
        if (empty($this->title)) {
1801
            return '';
1802
        }
1803
1804
        return $this->title;
1805
    }
1806
1807
    /**
1808
     * Returns the total time used to see that item.
1809
     *
1810
     * @return int Total time
1811
     */
1812
    public function get_total_time()
1813
    {
1814
        $debug = self::DEBUG;
1815
        if ($debug) {
1816
            error_log(
1817
                'learnpathItem::get_total_time() for item '.$this->db_id.
1818
                ' - Initially, current_start_time = '.$this->current_start_time.
1819
                ' and current_stop_time = '.$this->current_stop_time,
1820
                0
1821
            );
1822
        }
1823
        if ($this->current_start_time == 0) {
1824
            // Shouldn't be necessary thanks to the open() method.
1825
            if ($debug) {
1826
                error_log(
1827
                    'learnpathItem::get_total_time() - Current start time was empty',
1828
                    0
1829
                );
1830
            }
1831
            $this->current_start_time = time();
1832
        }
1833
1834
        if (time() < $this->current_stop_time ||
1835
            $this->current_stop_time == 0
1836
        ) {
1837
            if ($debug) {
1838
                error_log(
1839
                    'learnpathItem::get_total_time() - Current stop time was '
1840
                    .'greater than the current time or was empty',
1841
                    0
1842
                );
1843
            }
1844
            // If this case occurs, then we risk to write huge time data in db.
1845
            // In theory, stop time should be *always* updated here, but it
1846
            // might be used in some unknown goal.
1847
            $this->current_stop_time = time();
1848
        }
1849
1850
        $time = $this->current_stop_time - $this->current_start_time;
1851
1852
        if ($time < 0) {
1853
            if ($debug) {
1854
                error_log(
1855
                    'learnpathItem::get_total_time() - Time smaller than 0. Returning 0',
1856
                    0
1857
                );
1858
            }
1859
1860
            return 0;
1861
        } else {
1862
            $time = $this->fixAbusiveTime($time);
1863
            if ($debug) {
1864
                error_log(
1865
                    'Current start time = '.$this->current_start_time.', current stop time = '.
1866
                    $this->current_stop_time.' Returning '.$time."-----------\n"
1867
                );
1868
            }
1869
1870
            return $time;
1871
        }
1872
    }
1873
1874
    /**
1875
     * Sometimes time recorded for a learning path item is superior to the maximum allowed duration of the session.
1876
     * In this case, this session resets the time for that particular learning path item to 5 minutes
1877
     * (something more realistic, that is also used when leaving the portal without closing one's session).
1878
     *
1879
     * @param int $time
1880
     *
1881
     * @return int
1882
     */
1883
    public function fixAbusiveTime($time)
1884
    {
1885
        // Code based from Event::courseLogout
1886
        $sessionLifetime = api_get_configuration_value('session_lifetime');
1887
        // If session life time too big use 1 hour
1888
        if (empty($sessionLifetime) || $sessionLifetime > 86400) {
1889
            $sessionLifetime = 3600;
1890
        }
1891
1892
        $fixedAddedMinute = 5 * 60; // Add only 5 minutes
1893
        if ($time > $sessionLifetime) {
1894
            error_log("fixAbusiveTime: Total time is too big: $time replaced with: $fixedAddedMinute");
1895
            error_log("item_id : ".$this->db_id." lp_item_view.iid: ".$this->db_item_view_id);
1896
            $time = $fixedAddedMinute;
1897
        }
1898
1899
        return $time;
1900
    }
1901
1902
    /**
1903
     * Gets the item type.
1904
     *
1905
     * @return string The item type (can be doc, dir, sco, asset)
1906
     */
1907
    public function get_type()
1908
    {
1909
        $res = 'asset';
1910
        if (!empty($this->type)) {
1911
            $res = $this->type;
1912
        }
1913
        if (self::DEBUG > 2) {
1914
            error_log(
1915
                'learnpathItem::get_type() - Returning '.$res.' for item '.$this->db_id,
1916
                0
1917
            );
1918
        }
1919
1920
        return $res;
1921
    }
1922
1923
    /**
1924
     * Gets the view count for this item.
1925
     *
1926
     * @return int Number of attempts or 0
1927
     */
1928
    public function get_view_count()
1929
    {
1930
        if (self::DEBUG > 0) {
1931
            error_log('learnpathItem::get_view_count()', 0);
1932
        }
1933
        if (!empty($this->attempt_id)) {
1934
            return $this->attempt_id;
1935
        } else {
1936
            return 0;
1937
        }
1938
    }
1939
1940
    /**
1941
     * Tells if an item is done ('completed','passed','succeeded') or not.
1942
     *
1943
     * @return bool True if the item is done ('completed','passed','succeeded'),
1944
     *              false otherwise
1945
     */
1946
    public function is_done()
1947
    {
1948
        $completedStatusList = [
1949
            'completed',
1950
            'passed',
1951
            'succeeded',
1952
            'failed',
1953
        ];
1954
1955
        if ($this->status_is($completedStatusList)) {
1956
            if (self::DEBUG > 2) {
1957
                error_log(
1958
                    'learnpath::is_done() - Item '.$this->get_id(
1959
                    ).' is complete',
1960
                    0
1961
                );
1962
            }
1963
1964
            return true;
1965
        } else {
1966
            if (self::DEBUG > 2) {
1967
                error_log(
1968
                    'learnpath::is_done() - Item '.$this->get_id(
1969
                    ).' is not complete',
1970
                    0
1971
                );
1972
            }
1973
1974
            return false;
1975
        }
1976
    }
1977
1978
    /**
1979
     * Tells if a restart is allowed (take it from $this->prevent_reinit and $this->status).
1980
     *
1981
     * @return int -1 if retaking the sco another time for credit is not allowed,
1982
     *             0 if it is not allowed but the item has to be finished
1983
     *             1 if it is allowed. Defaults to 1
1984
     */
1985
    public function isRestartAllowed()
1986
    {
1987
        if (self::DEBUG > 2) {
1988
            error_log('learnpathItem::isRestartAllowed()', 0);
1989
        }
1990
        $restart = 1;
1991
        $mystatus = $this->get_status(true);
1992
        if ($this->get_prevent_reinit() > 0) {
1993
            // If prevent_reinit == 1 (or more)
1994
            // If status is not attempted or incomplete, authorize retaking (of the same) anyway. Otherwise:
1995
            if ($mystatus != $this->possible_status[0] && $mystatus != $this->possible_status[1]) {
1996
                $restart = -1;
1997
            } else { //status incompleted or not attempted
1998
                $restart = 0;
1999
            }
2000
        } else {
2001
            if ($mystatus == $this->possible_status[0] || $mystatus == $this->possible_status[1]) {
2002
                $restart = -1;
2003
            }
2004
        }
2005
        if (self::DEBUG > 2) {
2006
            error_log(
2007
                'New LP - End of learnpathItem::isRestartAllowed() - Returning '.$restart,
2008
                0
2009
            );
2010
        }
2011
2012
        return $restart;
2013
    }
2014
2015
    /**
2016
     * Opens/launches the item. Initialises runtime values.
2017
     *
2018
     * @param bool $allow_new_attempt
2019
     *
2020
     * @return bool true on success, false on failure
2021
     */
2022
    public function open($allow_new_attempt = false)
2023
    {
2024
        if (self::DEBUG > 0) {
2025
            error_log('learnpathItem::open()', 0);
2026
        }
2027
        if ($this->prevent_reinit == 0) {
2028
            $this->current_score = 0;
2029
            $this->current_start_time = time();
2030
            // In this case, as we are opening the item, what is important to us
2031
            // is the database status, in order to know if this item has already
2032
            // been used in the past (rather than just loaded and modified by
2033
            // some javascript but not written in the database).
2034
            // If the database status is different from 'not attempted', we can
2035
            // consider this item has already been used, and as such we can
2036
            // open a new attempt. Otherwise, we'll just reuse the current
2037
            // attempt, which is generally created the first time the item is
2038
            // loaded (for example as part of the table of contents).
2039
            $stat = $this->get_status(true);
2040
            if ($allow_new_attempt && isset($stat) && ($stat != $this->possible_status[0])) {
2041
                $this->attempt_id = $this->attempt_id + 1; // Open a new attempt.
2042
            }
2043
            $this->status = $this->possible_status[1];
2044
        } else {
2045
            /*if ($this->current_start_time == 0) {
2046
                // Small exception for start time, to avoid amazing values.
2047
                $this->current_start_time = time();
2048
            }*/
2049
            // If we don't init start time here, the time is sometimes calculated from the last start time.
2050
            $this->current_start_time = time();
2051
        }
2052
    }
2053
2054
    /**
2055
     * Outputs the item contents.
2056
     *
2057
     * @return string HTML file (displayable in an <iframe>) or empty string if no path defined
2058
     */
2059
    public function output()
2060
    {
2061
        if (self::DEBUG > 0) {
2062
            error_log('learnpathItem::output()', 0);
2063
        }
2064
        if (!empty($this->path) and is_file($this->path)) {
2065
            $output = '';
2066
            $output .= file_get_contents($this->path);
2067
2068
            return $output;
2069
        }
2070
2071
        return '';
2072
    }
2073
2074
    /**
2075
     * Parses the prerequisites string with the AICC logic language.
2076
     *
2077
     * @param string $prereqs_string The prerequisites string as it figures in imsmanifest.xml
2078
     * @param array  $items          Array of items in the current learnpath object.
2079
     *                               Although we're in the learnpathItem object, it's necessary to have
2080
     *                               a list of all items to be able to check the current item's prerequisites
2081
     * @param array  $refs_list      list of references
2082
     *                               (the "ref" column in the lp_item table) that are strings used in the
2083
     *                               expression of prerequisites
2084
     * @param int    $user_id        The user ID. In some cases like Chamilo quizzes,
2085
     *                               it's necessary to have the user ID to query other tables (like the results of quizzes)
2086
     *
2087
     * @return bool True if the list of prerequisites given is entirely satisfied, false otherwise
2088
     */
2089
    public function parse_prereq($prereqs_string, $items, $refs_list, $user_id)
2090
    {
2091
        if (self::DEBUG > 0) {
2092
            error_log(
2093
                'learnpathItem::parse_prereq() for learnpath '.$this->lp_id.' with string '.$prereqs_string,
2094
                0
2095
            );
2096
        }
2097
2098
        $course_id = api_get_course_int_id();
2099
        $sessionId = api_get_session_id();
2100
2101
        // Deal with &, |, ~, =, <>, {}, ,, X*, () in reverse order.
2102
        $this->prereq_alert = '';
2103
        // First parse all parenthesis by using a sequential loop
2104
        //  (looking for less-inclusives first).
2105
        if ($prereqs_string == '_true_') {
2106
            return true;
2107
        }
2108
2109
        if ($prereqs_string == '_false_') {
2110
            if (empty($this->prereq_alert)) {
2111
                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2112
            }
2113
2114
            return false;
2115
        }
2116
2117
        while (strpos($prereqs_string, '(') !== false) {
2118
            // Remove any () set and replace with its value.
2119
            $matches = [];
2120
            $res = preg_match_all(
2121
                '/(\(([^\(\)]*)\))/',
2122
                $prereqs_string,
2123
                $matches
2124
            );
2125
            if ($res) {
2126
                foreach ($matches[2] as $id => $match) {
2127
                    $str_res = $this->parse_prereq(
2128
                        $match,
2129
                        $items,
2130
                        $refs_list,
2131
                        $user_id
2132
                    );
2133
                    if ($str_res) {
2134
                        $prereqs_string = str_replace(
2135
                            $matches[1][$id],
2136
                            '_true_',
2137
                            $prereqs_string
2138
                        );
2139
                    } else {
2140
                        $prereqs_string = str_replace(
2141
                            $matches[1][$id],
2142
                            '_false_',
2143
                            $prereqs_string
2144
                        );
2145
                    }
2146
                }
2147
            }
2148
        }
2149
2150
        // Parenthesis removed, now look for ORs as it is the lesser-priority
2151
        //  binary operator (= always uses one text operand).
2152
        if (strpos($prereqs_string, '|') === false) {
2153
            if (self::DEBUG > 1) {
2154
                error_log('New LP - Didnt find any OR, looking for AND', 0);
2155
            }
2156
            if (strpos($prereqs_string, '&') !== false) {
2157
                $list = explode('&', $prereqs_string);
2158
                if (count($list) > 1) {
2159
                    $andstatus = true;
2160
                    foreach ($list as $condition) {
2161
                        $andstatus = $andstatus && $this->parse_prereq(
2162
                            $condition,
2163
                            $items,
2164
                            $refs_list,
2165
                            $user_id
2166
                        );
2167
2168
                        if (!$andstatus) {
2169
                            if (self::DEBUG > 1) {
2170
                                error_log(
2171
                                    'New LP - One condition in AND was false, short-circuit',
2172
                                    0
2173
                                );
2174
                            }
2175
                            break;
2176
                        }
2177
                    }
2178
                    if (empty($this->prereq_alert) && !$andstatus) {
2179
                        $this->prereq_alert = get_lang(
2180
                            'LearnpathPrereqNotCompleted'
2181
                        );
2182
                    }
2183
2184
                    return $andstatus;
2185
                } else {
2186
                    if (isset($items[$refs_list[$list[0]]])) {
2187
                        $status = $items[$refs_list[$list[0]]]->get_status(true);
2188
                        $returnstatus = ($status == $this->possible_status[2]) || ($status == $this->possible_status[3]);
2189
                        if (empty($this->prereq_alert) && !$returnstatus) {
2190
                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2191
                        }
2192
2193
                        return $returnstatus;
2194
                    }
2195
                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2196
2197
                    return false;
2198
                }
2199
            } else {
2200
                // No ORs found, now look for ANDs.
2201
                if (self::DEBUG > 1) {
2202
                    error_log('New LP - Didnt find any AND, looking for =', 0);
2203
                }
2204
2205
                if (strpos($prereqs_string, '=') !== false) {
2206
                    if (self::DEBUG > 1) {
2207
                        error_log('New LP - Found =, looking into it', 0);
2208
                    }
2209
                    // We assume '=' signs only appear when there's nothing else around.
2210
                    $params = explode('=', $prereqs_string);
2211
                    if (count($params) == 2) {
2212
                        // Right number of operands.
2213
                        if (isset($items[$refs_list[$params[0]]])) {
2214
                            $status = $items[$refs_list[$params[0]]]->get_status(true);
2215
                            $returnstatus = $status == $params[1];
2216
                            if (empty($this->prereq_alert) && !$returnstatus) {
2217
                                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2218
                            }
2219
2220
                            return $returnstatus;
2221
                        }
2222
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2223
2224
                        return false;
2225
                    }
2226
                } else {
2227
                    // No ANDs found, look for <>
2228
                    if (self::DEBUG > 1) {
2229
                        error_log(
2230
                            'New LP - Didnt find any =, looking for <>',
2231
                            0
2232
                        );
2233
                    }
2234
2235
                    if (strpos($prereqs_string, '<>') !== false) {
2236
                        if (self::DEBUG > 1) {
2237
                            error_log('New LP - Found <>, looking into it', 0);
2238
                        }
2239
                        // We assume '<>' signs only appear when there's nothing else around.
2240
                        $params = explode('<>', $prereqs_string);
2241
                        if (count($params) == 2) {
2242
                            // Right number of operands.
2243
                            if (isset($items[$refs_list[$params[0]]])) {
2244
                                $status = $items[$refs_list[$params[0]]]->get_status(true);
2245
                                $returnstatus = $status != $params[1];
2246
                                if (empty($this->prereq_alert) && !$returnstatus) {
2247
                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2248
                                }
2249
2250
                                return $returnstatus;
2251
                            }
2252
                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2253
2254
                            return false;
2255
                        }
2256
                    } else {
2257
                        // No <> found, look for ~ (unary)
2258
                        if (self::DEBUG > 1) {
2259
                            error_log(
2260
                                'New LP - Didnt find any =, looking for ~',
2261
                                0
2262
                            );
2263
                        }
2264
                        // Only remains: ~ and X*{}
2265
                        if (strpos($prereqs_string, '~') !== false) {
2266
                            // Found NOT.
2267
                            if (self::DEBUG > 1) {
2268
                                error_log(
2269
                                    'New LP - Found ~, looking into it',
2270
                                    0
2271
                                );
2272
                            }
2273
                            $list = [];
2274
                            $myres = preg_match(
2275
                                '/~([^(\d+\*)\{]*)/',
2276
                                $prereqs_string,
2277
                                $list
2278
                            );
2279
                            if ($myres) {
2280
                                $returnstatus = !$this->parse_prereq(
2281
                                    $list[1],
2282
                                    $items,
2283
                                    $refs_list,
2284
                                    $user_id
2285
                                );
2286
                                if (empty($this->prereq_alert) && !$returnstatus) {
2287
                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2288
                                }
2289
2290
                                return $returnstatus;
2291
                            } else {
2292
                                // Strange...
2293
                                if (self::DEBUG > 1) {
2294
                                    error_log(
2295
                                        'New LP - Found ~ but strange string: '.$prereqs_string,
2296
                                        0
2297
                                    );
2298
                                }
2299
                            }
2300
                        } else {
2301
                            // Finally, look for sets/groups
2302
                            if (self::DEBUG > 1) {
2303
                                error_log(
2304
                                    'New LP - Didnt find any ~, looking for groups',
2305
                                    0
2306
                                );
2307
                            }
2308
                            // Only groups here.
2309
                            $groups = [];
2310
                            $groups_there = preg_match_all(
2311
                                '/((\d+\*)?\{([^\}]+)\}+)/',
2312
                                $prereqs_string,
2313
                                $groups
2314
                            );
2315
2316
                            if ($groups_there) {
2317
                                foreach ($groups[1] as $gr) {
2318
                                    // Only take the results that correspond to
2319
                                    //  the big brackets-enclosed condition.
2320
                                    if (self::DEBUG > 1) {
2321
                                        error_log(
2322
                                            'New LP - Dealing with group '.$gr,
2323
                                            0
2324
                                        );
2325
                                    }
2326
                                    $multi = [];
2327
                                    $mycond = false;
2328
                                    if (preg_match(
2329
                                        '/(\d+)\*\{([^\}]+)\}/',
2330
                                        $gr,
2331
                                        $multi
2332
                                    )
2333
                                    ) {
2334
                                        if (self::DEBUG > 1) {
2335
                                            error_log(
2336
                                                'New LP - Found multiplier '.$multi[0],
2337
                                                0
2338
                                            );
2339
                                        }
2340
                                        $count = $multi[1];
2341
                                        $list = explode(',', $multi[2]);
2342
                                        $mytrue = 0;
2343
                                        foreach ($list as $cond) {
2344
                                            if (isset($items[$refs_list[$cond]])) {
2345
                                                $status = $items[$refs_list[$cond]]->get_status(true);
2346
                                                if ($status == $this->possible_status[2] ||
2347
                                                    $status == $this->possible_status[3]
2348
                                                ) {
2349
                                                    $mytrue++;
2350
                                                    if (self::DEBUG > 1) {
2351
                                                        error_log(
2352
                                                            'New LP - Found true item, counting.. ('.($mytrue).')',
2353
                                                            0
2354
                                                        );
2355
                                                    }
2356
                                                }
2357
                                            } else {
2358
                                                if (self::DEBUG > 1) {
2359
                                                    error_log(
2360
                                                        'New LP - item '.$cond.' does not exist in items list',
2361
                                                        0
2362
                                                    );
2363
                                                }
2364
                                            }
2365
                                        }
2366
                                        if ($mytrue >= $count) {
2367
                                            if (self::DEBUG > 1) {
2368
                                                error_log(
2369
                                                    'New LP - Got enough true results, return true',
2370
                                                    0
2371
                                                );
2372
                                            }
2373
                                            $mycond = true;
2374
                                        } else {
2375
                                            if (self::DEBUG > 1) {
2376
                                                error_log(
2377
                                                    'New LP - Not enough true results',
2378
                                                    0
2379
                                                );
2380
                                            }
2381
                                        }
2382
                                    } else {
2383
                                        if (self::DEBUG > 1) {
2384
                                            error_log(
2385
                                                'New LP - No multiplier',
2386
                                                0
2387
                                            );
2388
                                        }
2389
                                        $list = explode(',', $gr);
2390
                                        $mycond = true;
2391
                                        foreach ($list as $cond) {
2392
                                            if (isset($items[$refs_list[$cond]])) {
2393
                                                $status = $items[$refs_list[$cond]]->get_status(true);
2394
                                                if ($status == $this->possible_status[2] ||
2395
                                                    $status == $this->possible_status[3]
2396
                                                ) {
2397
                                                    $mycond = true;
2398
                                                    if (self::DEBUG > 1) {
2399
                                                        error_log(
2400
                                                            'New LP - Found true item',
2401
                                                            0
2402
                                                        );
2403
                                                    }
2404
                                                } else {
2405
                                                    if (self::DEBUG > 1) {
2406
                                                        error_log(
2407
                                                            'New LP - '.
2408
                                                            ' Found false item, the set is not true, return false',
2409
                                                            0
2410
                                                        );
2411
                                                    }
2412
                                                    $mycond = false;
2413
                                                    break;
2414
                                                }
2415
                                            } else {
2416
                                                if (self::DEBUG > 1) {
2417
                                                    error_log(
2418
                                                        'New LP - item '.$cond.' does not exist in items list',
2419
                                                        0
2420
                                                    );
2421
                                                }
2422
                                                if (self::DEBUG > 1) {
2423
                                                    error_log(
2424
                                                        'New LP - Found false item, the set is not true, return false',
2425
                                                        0
2426
                                                    );
2427
                                                }
2428
                                                $mycond = false;
2429
                                                break;
2430
                                            }
2431
                                        }
2432
                                    }
2433
                                    if (!$mycond && empty($this->prereq_alert)) {
2434
                                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2435
                                    }
2436
2437
                                    return $mycond;
2438
                                }
2439
                            } else {
2440
                                // Nothing found there either. Now return the
2441
                                // value of the corresponding resource completion status.
2442
                                if (self::DEBUG > 1) {
2443
                                    error_log(
2444
                                        'New LP - Didnt find any group, returning value for '.$prereqs_string,
2445
                                        0
2446
                                    );
2447
                                }
2448
2449
                                if (isset($refs_list[$prereqs_string]) &&
2450
                                    isset($items[$refs_list[$prereqs_string]])
2451
                                ) {
2452
                                    /** @var learnpathItem $itemToCheck */
2453
                                    $itemToCheck = $items[$refs_list[$prereqs_string]];
2454
2455
                                    if ($itemToCheck->type == 'quiz') {
2456
                                        // 1. Checking the status in current items.
2457
                                        $status = $itemToCheck->get_status(true);
2458
                                        $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2459
2460
                                        if (!$returnstatus) {
2461
                                            $explanation = sprintf(
2462
                                                get_lang('ItemXBlocksThisElement'),
2463
                                                $itemToCheck->get_title()
2464
                                            );
2465
                                            $this->prereq_alert = $explanation;
2466
                                            if (self::DEBUG > 1) {
2467
                                                error_log(
2468
                                                    'New LP - Prerequisite '.$prereqs_string.' not complete',
2469
                                                    0
2470
                                                );
2471
                                            }
2472
                                        } else {
2473
                                            if (self::DEBUG > 1) {
2474
                                                error_log(
2475
                                                    'New LP - Prerequisite '.$prereqs_string.' complete',
2476
                                                    0
2477
                                                );
2478
                                            }
2479
                                        }
2480
2481
                                        // For one and first attempt.
2482
                                        if ($this->prevent_reinit == 1) {
2483
                                            // 2. If is completed we check the results in the DB of the quiz.
2484
                                            if ($returnstatus) {
2485
                                                //AND origin_lp_item_id = '.$user_id.'
2486
                                                $sql = 'SELECT score, max_score
2487
                                                        FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
2488
                                                        WHERE
2489
                                                            exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
2490
                                                            exe_user_id = '.$user_id.' AND
2491
                                                            orig_lp_id = '.$this->lp_id.' AND
2492
                                                            orig_lp_item_id = '.$prereqs_string.' AND
2493
                                                            status <> "incomplete" AND
2494
                                                            c_id = '.$course_id.'
2495
                                                        ORDER BY exe_date DESC
2496
                                                        LIMIT 0, 1';
2497
                                                $rs_quiz = Database::query($sql);
2498
                                                if ($quiz = Database::fetch_array($rs_quiz)) {
2499
                                                    $minScore = $items[$refs_list[$this->get_id()]]->getPrerequisiteMinScore();
2500
                                                    $maxScore = $items[$refs_list[$this->get_id()]]->getPrerequisiteMaxScore();
2501
2502
                                                    if (isset($minScore) && isset($minScore)) {
2503
                                                        // Taking min/max prerequisites values see BT#5776
2504
                                                        if ($quiz['score'] >= $minScore &&
2505
                                                            $quiz['score'] <= $maxScore
2506
                                                        ) {
2507
                                                            $returnstatus = true;
2508
                                                        } else {
2509
                                                            $explanation = sprintf(
2510
                                                                get_lang('YourResultAtXBlocksThisElement'),
2511
                                                                $itemToCheck->get_title()
2512
                                                            );
2513
                                                            $this->prereq_alert = $explanation;
2514
                                                            $returnstatus = false;
2515
                                                        }
2516
                                                    } else {
2517
                                                        // Classic way
2518
                                                        if ($quiz['score'] >=
2519
                                                            $items[$refs_list[$prereqs_string]]->get_mastery_score()
2520
                                                        ) {
2521
                                                            $returnstatus = true;
2522
                                                        } else {
2523
                                                            $explanation = sprintf(
2524
                                                                get_lang('YourResultAtXBlocksThisElement'),
2525
                                                                $itemToCheck->get_title()
2526
                                                            );
2527
                                                            $this->prereq_alert = $explanation;
2528
                                                            $returnstatus = false;
2529
                                                        }
2530
                                                    }
2531
                                                } else {
2532
                                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2533
                                                    $returnstatus = false;
2534
                                                }
2535
                                            }
2536
                                        } else {
2537
                                            // 3. For multiple attempts we check that there are minimum 1 item completed
2538
                                            // Checking in the database.
2539
                                            $sql = 'SELECT score, max_score
2540
                                                    FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
2541
                                                    WHERE
2542
                                                        c_id = '.$course_id.' AND 
2543
                                                        exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
2544
                                                        exe_user_id = '.$user_id.' AND
2545
                                                        orig_lp_id = '.$this->lp_id.' AND
2546
                                                        orig_lp_item_id = '.$prereqs_string.' ';
2547
2548
                                            $rs_quiz = Database::query($sql);
2549
                                            if (Database::num_rows($rs_quiz) > 0) {
2550
                                                while ($quiz = Database::fetch_array($rs_quiz)) {
2551
                                                    $minScore = $items[$refs_list[$this->get_id()]]->getPrerequisiteMinScore();
2552
                                                    $maxScore = $items[$refs_list[$this->get_id()]]->getPrerequisiteMaxScore();
2553
2554
                                                    if (isset($minScore) && isset($minScore)) {
2555
                                                        // Taking min/max prerequisites values see BT#5776
2556
                                                        if ($quiz['score'] >= $minScore && $quiz['score'] <= $maxScore) {
2557
                                                            $returnstatus = true;
2558
                                                            break;
2559
                                                        } else {
2560
                                                            $explanation = sprintf(
2561
                                                                get_lang('YourResultAtXBlocksThisElement'),
2562
                                                                $itemToCheck->get_title()
2563
                                                            );
2564
                                                            $this->prereq_alert = $explanation;
2565
                                                            $returnstatus = false;
2566
                                                        }
2567
                                                    } else {
2568
                                                        if ($quiz['score'] >=
2569
                                                            $items[$refs_list[$prereqs_string]]->get_mastery_score()
2570
                                                        ) {
2571
                                                            $returnstatus = true;
2572
                                                            break;
2573
                                                        } else {
2574
                                                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2575
                                                            $returnstatus = false;
2576
                                                        }
2577
                                                    }
2578
                                                }
2579
                                            } else {
2580
                                                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2581
                                                $returnstatus = false;
2582
                                            }
2583
                                        }
2584
2585
                                        return $returnstatus;
2586
                                    } elseif ($itemToCheck->type === 'student_publication') {
2587
                                        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2588
                                        $workId = $items[$refs_list[$prereqs_string]]->path;
2589
                                        $count = get_work_count_by_student($user_id, $workId);
2590
                                        if ($count >= 1) {
2591
                                            $returnstatus = true;
2592
                                        } else {
2593
                                            $returnstatus = false;
2594
                                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2595
                                            if (self::DEBUG > 1) {
2596
                                                error_log(
2597
                                                    'Student pub, prereq'.$prereqs_string.' not completed',
2598
                                                    0
2599
                                                );
2600
                                            }
2601
                                        }
2602
2603
                                        return $returnstatus;
2604
                                    } else {
2605
                                        $status = $itemToCheck->get_status(false);
2606
                                        $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2607
                                        if (!$returnstatus) {
2608
                                            $explanation = sprintf(
2609
                                                get_lang('ItemXBlocksThisElement'),
2610
                                                $itemToCheck->get_title()
2611
                                            );
2612
                                            $this->prereq_alert = $explanation;
2613
                                            if (self::DEBUG > 1) {
2614
                                                error_log(
2615
                                                    'New LP - Prerequisite '.$prereqs_string.' not complete',
2616
                                                    0
2617
                                                );
2618
                                            }
2619
                                        } else {
2620
                                            if (self::DEBUG > 1) {
2621
                                                error_log(
2622
                                                    'New LP - Prerequisite '.$prereqs_string.' complete',
2623
                                                    0
2624
                                                );
2625
                                            }
2626
                                        }
2627
2628
                                        if ($returnstatus && $this->prevent_reinit == 1) {
2629
                                            // I would prefer check in the database.
2630
                                            $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
2631
                                            $lp_view = Database::get_course_table(TABLE_LP_VIEW);
2632
2633
                                            $sql = 'SELECT iid FROM '.$lp_view.'
2634
                                                    WHERE
2635
                                                        c_id = '.$course_id.' AND
2636
                                                        user_id = '.$user_id.'  AND
2637
                                                        lp_id = '.$this->lp_id.' AND
2638
                                                        session_id = '.$sessionId.'
2639
                                                    LIMIT 0, 1';
2640
                                            $rs_lp = Database::query($sql);
2641
                                            if (Database::num_rows($rs_lp)) {
2642
                                                $lp_id = Database::fetch_row($rs_lp);
2643
                                                $my_lp_id = $lp_id[0];
2644
2645
                                                $sql = 'SELECT status FROM '.$lp_item_view.'
2646
                                                        WHERE
2647
                                                            c_id = '.$course_id.' AND
2648
                                                            lp_view_id = '.$my_lp_id.' AND
2649
                                                            lp_item_id = '.$refs_list[$prereqs_string].'
2650
                                                        LIMIT 0, 1';
2651
                                                $rs_lp = Database::query($sql);
2652
                                                $status_array = Database::fetch_row($rs_lp);
2653
                                                $status = $status_array[0];
2654
2655
                                                $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2656
                                                if (!$returnstatus && empty($this->prereq_alert)) {
2657
                                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2658
                                                }
2659
                                                if (!$returnstatus) {
2660
                                                    if (self::DEBUG > 1) {
2661
                                                        error_log(
2662
                                                            'New LP - Prerequisite '.$prereqs_string.' not complete'
2663
                                                        );
2664
                                                    }
2665
                                                } else {
2666
                                                    if (self::DEBUG > 1) {
2667
                                                        error_log('New LP - Prerequisite '.$prereqs_string.' complete');
2668
                                                    }
2669
                                                }
2670
2671
                                                return $returnstatus;
2672
                                            }
2673
                                        } else {
2674
                                            return $returnstatus;
2675
                                        }
2676
                                    }
2677
                                } else {
2678
                                    if (self::DEBUG > 1) {
2679
                                        error_log(
2680
                                            'New LP - Could not find '.$prereqs_string.' in '.print_r(
2681
                                                $refs_list,
2682
                                                true
2683
                                            ),
2684
                                            0
2685
                                        );
2686
                                    }
2687
                                }
2688
                            }
2689
                        }
2690
                    }
2691
                }
2692
            }
2693
        } else {
2694
            $list = explode("\|", $prereqs_string);
2695
            if (count($list) > 1) {
2696
                if (self::DEBUG > 1) {
2697
                    error_log('New LP - Found OR, looking into it', 0);
2698
                }
2699
                $orstatus = false;
2700
                foreach ($list as $condition) {
2701
                    if (self::DEBUG > 1) {
2702
                        error_log(
2703
                            'New LP - Found OR, adding it ('.$condition.')',
2704
                            0
2705
                        );
2706
                    }
2707
                    $orstatus = $orstatus || $this->parse_prereq(
2708
                        $condition,
2709
                        $items,
2710
                        $refs_list,
2711
                        $user_id
2712
                    );
2713
                    if ($orstatus) {
2714
                        // Shortcircuit OR.
2715
                        if (self::DEBUG > 1) {
2716
                            error_log(
2717
                                'New LP - One condition in OR was true, short-circuit',
2718
                                0
2719
                            );
2720
                        }
2721
                        break;
2722
                    }
2723
                }
2724
                if (!$orstatus && empty($this->prereq_alert)) {
2725
                    $this->prereq_alert = get_lang(
2726
                        'LearnpathPrereqNotCompleted'
2727
                    );
2728
                }
2729
2730
                return $orstatus;
2731
            } else {
2732
                if (self::DEBUG > 1) {
2733
                    error_log(
2734
                        'New LP - OR was found but only one elem present !?',
2735
                        0
2736
                    );
2737
                }
2738
                if (isset($items[$refs_list[$list[0]]])) {
2739
                    $status = $items[$refs_list[$list[0]]]->get_status(true);
2740
                    $returnstatus = $status == 'completed' || $status == 'passed';
2741
                    if (!$returnstatus && empty($this->prereq_alert)) {
2742
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2743
                    }
2744
2745
                    return $returnstatus;
2746
                }
2747
            }
2748
        }
2749
        if (empty($this->prereq_alert)) {
2750
            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2751
        }
2752
2753
        if (self::DEBUG > 1) {
2754
            error_log(
2755
                'New LP - End of parse_prereq. Error code is now '.$this->prereq_alert,
2756
                0
2757
            );
2758
        }
2759
2760
        return false;
2761
    }
2762
2763
    /**
2764
     * Reinits all local values as the learnpath is restarted.
2765
     *
2766
     * @return bool True on success, false otherwise
2767
     */
2768
    public function restart()
2769
    {
2770
        if (self::DEBUG > 0) {
2771
            error_log('learnpathItem::restart()', 0);
2772
        }
2773
        $seriousGame = $this->get_seriousgame_mode();
2774
        //For serious game  : We reuse same attempt_id
2775
        if ($seriousGame == 1 && $this->type == 'sco') {
2776
            // If this is a sco, Chamilo can't update the time without an
2777
            //  explicit scorm call
2778
            $this->current_start_time = 0;
2779
            $this->current_stop_time = 0; //Those 0 value have this effect
2780
            $this->last_scorm_session_time = 0;
2781
            $this->save();
2782
2783
            return true;
2784
        }
2785
        $this->save();
2786
2787
        $allowed = $this->isRestartAllowed();
2788
        if ($allowed === -1) {
2789
            // Nothing allowed, do nothing.
2790
        } elseif ($allowed === 1) {
2791
            // Restart as new attempt is allowed, record a new attempt.
2792
            $this->attempt_id = $this->attempt_id + 1; // Simply reuse the previous attempt_id.
2793
            $this->current_score = 0;
2794
            $this->current_start_time = 0;
2795
            $this->current_stop_time = 0;
2796
            $this->current_data = '';
2797
            $this->status = $this->possible_status[0];
2798
            $this->interactions_count = 0;
2799
            $this->interactions = [];
2800
            $this->objectives_count = 0;
2801
            $this->objectives = [];
2802
            $this->lesson_location = '';
2803
            if ($this->type != TOOL_QUIZ) {
2804
                $this->write_to_db();
2805
            }
2806
        } else {
2807
            // Restart current element is allowed (because it's not finished yet),
2808
            // reinit current.
2809
            //$this->current_score = 0;
2810
            $this->current_start_time = 0;
2811
            $this->current_stop_time = 0;
2812
            $this->interactions_count = $this->get_interactions_count(true);
2813
        }
2814
2815
        return true;
2816
    }
2817
2818
    /**
2819
     * Saves data in the database.
2820
     *
2821
     * @param bool $from_outside     Save from URL params (1) or from object attributes (0)
2822
     * @param bool $prereqs_complete The results of a check on prerequisites for this item.
2823
     *                               True if prerequisites are completed, false otherwise. Defaults to false. Only used if not sco or au
2824
     *
2825
     * @return bool True on success, false on failure
2826
     */
2827
    public function save($from_outside = true, $prereqs_complete = false)
2828
    {
2829
        $debug = self::DEBUG;
2830
        if ($debug) {
2831
            error_log('learnpathItem::save()', 0);
2832
        }
2833
        // First check if parameters passed via GET can be saved here
2834
        // in case it's a SCORM, we should get:
2835
        if ($this->type == 'sco' || $this->type == 'au') {
2836
            $status = $this->get_status(true);
2837
            if ($this->prevent_reinit == 1 &&
2838
                $status != $this->possible_status[0] && // not attempted
2839
                $status != $this->possible_status[1]    //incomplete
2840
            ) {
2841
                if ($debug) {
2842
                    error_log(
2843
                        'learnpathItem::save() - save reinit blocked by setting',
2844
                        0
2845
                    );
2846
                }
2847
                // Do nothing because the status has already been set. Don't allow it to change.
2848
                // TODO: Check there isn't a special circumstance where this should be saved.
2849
            } else {
2850
                if ($debug) {
2851
                    error_log(
2852
                        'learnpathItem::save() - SCORM save request received',
2853
                        0
2854
                    );
2855
                }
2856
2857
                // Get all new settings from the URL
2858
                if ($from_outside) {
2859
                    if ($debug) {
2860
                        error_log(
2861
                            'learnpathItem::save() - Getting item data from outside',
2862
                            0
2863
                        );
2864
                    }
2865
                    foreach ($_GET as $param => $value) {
2866
                        switch ($param) {
2867
                            case 'score':
2868
                                $this->set_score($value);
2869
                                if ($debug) {
2870
                                    error_log(
2871
                                        'learnpathItem::save() - setting score to '.$value,
2872
                                        0
2873
                                    );
2874
                                }
2875
                                break;
2876
                            case 'max':
2877
                                $this->set_max_score($value);
2878
                                if ($debug) {
2879
                                    error_log(
2880
                                        'learnpathItem::save() - setting view_max_score to '.$value,
2881
                                        0
2882
                                    );
2883
                                }
2884
                                break;
2885
                            case 'min':
2886
                                $this->min_score = $value;
2887
                                if ($debug) {
2888
                                    error_log(
2889
                                        'learnpathItem::save() - setting min_score to '.$value,
2890
                                        0
2891
                                    );
2892
                                }
2893
                                break;
2894
                            case 'lesson_status':
2895
                                if (!empty($value)) {
2896
                                    $this->set_status($value);
2897
                                    if ($debug) {
2898
                                        error_log(
2899
                                            'learnpathItem::save() - setting status to '.$value,
2900
                                            0
2901
                                        );
2902
                                    }
2903
                                }
2904
                                break;
2905
                            case 'time':
2906
                                $this->set_time($value);
2907
                                if ($debug) {
2908
                                    error_log(
2909
                                        'learnpathItem::save() - setting time to '.$value,
2910
                                        0
2911
                                    );
2912
                                }
2913
                                break;
2914
                            case 'suspend_data':
2915
                                $this->current_data = $value;
2916
                                if ($debug) {
2917
                                    error_log(
2918
                                        'learnpathItem::save() - setting suspend_data to '.$value,
2919
                                        0
2920
                                    );
2921
                                }
2922
                                break;
2923
                            case 'lesson_location':
2924
                                $this->set_lesson_location($value);
2925
                                if ($debug) {
2926
                                    error_log(
2927
                                        'learnpathItem::save() - setting lesson_location to '.$value,
2928
                                        0
2929
                                    );
2930
                                }
2931
                                break;
2932
                            case 'core_exit':
2933
                                $this->set_core_exit($value);
2934
                                if ($debug) {
2935
                                    error_log(
2936
                                        'learnpathItem::save() - setting core_exit to '.$value,
2937
                                        0
2938
                                    );
2939
                                }
2940
                                break;
2941
                            case 'interactions':
2942
                                break;
2943
                            case 'objectives':
2944
                                break;
2945
                            default:
2946
                                // Ignore.
2947
                                break;
2948
                        }
2949
                    }
2950
                } else {
2951
                    if ($debug) {
2952
                        error_log(
2953
                            'learnpathItem::save() - Using inside item status',
2954
                            0
2955
                        );
2956
                    }
2957
                    // Do nothing, just let the local attributes be used.
2958
                }
2959
            }
2960
        } else {
2961
            // If not SCO, such messages should not be expected.
2962
            $type = strtolower($this->type);
2963
            if ($debug) {
2964
                error_log("type: $type");
2965
            }
2966
            switch ($type) {
2967
                case 'asset':
2968
                    if ($prereqs_complete) {
2969
                        $this->set_status($this->possible_status[2]);
2970
                    }
2971
                    break;
2972
                case TOOL_HOTPOTATOES:
2973
                    break;
2974
                case TOOL_QUIZ:
2975
                    return false;
2976
                    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...
2977
                default:
2978
                    // For now, everything that is not sco and not asset is set to
2979
                    // completed when saved.
2980
                    if ($prereqs_complete) {
2981
                        $this->set_status($this->possible_status[2]);
2982
                    }
2983
                    break;
2984
            }
2985
        }
2986
2987
        if ($debug) {
2988
            error_log(
2989
                'New LP - End of learnpathItem::save() - Calling write_to_db()',
2990
                0
2991
            );
2992
        }
2993
2994
        return $this->write_to_db();
2995
    }
2996
2997
    /**
2998
     * Sets the number of attempt_id to a given value.
2999
     *
3000
     * @param int $num The given value to set attempt_id to
3001
     *
3002
     * @return bool TRUE on success, FALSE otherwise
3003
     */
3004
    public function set_attempt_id($num)
3005
    {
3006
        if (self::DEBUG > 0) {
3007
            error_log('learnpathItem::set_attempt_id()', 0);
3008
        }
3009
        if ($num == strval(intval($num)) && $num >= 0) {
3010
            $this->attempt_id = $num;
3011
3012
            return true;
3013
        }
3014
3015
        return false;
3016
    }
3017
3018
    /**
3019
     * Sets the core_exit value to the one given.
3020
     *
3021
     * @return bool $value  True (always)
3022
     */
3023
    public function set_core_exit($value)
3024
    {
3025
        switch ($value) {
3026
            case '':
3027
                $this->core_exit = '';
3028
                break;
3029
            case 'suspend':
3030
                $this->core_exit = 'suspend';
3031
                break;
3032
            default:
3033
                $this->core_exit = 'none';
3034
                break;
3035
        }
3036
3037
        return true;
3038
    }
3039
3040
    /**
3041
     * Sets the item's description.
3042
     *
3043
     * @param string $string Description
3044
     */
3045
    public function set_description($string = '')
3046
    {
3047
        if (self::DEBUG > 0) {
3048
            error_log('learnpathItem::set_description()', 0);
3049
        }
3050
        if (!empty($string)) {
3051
            $this->description = $string;
3052
        }
3053
    }
3054
3055
    /**
3056
     * Sets the lesson_location value.
3057
     *
3058
     * @param string $location lesson_location as provided by the SCO
3059
     *
3060
     * @return bool True on success, false otherwise
3061
     */
3062
    public function set_lesson_location($location)
3063
    {
3064
        if (self::DEBUG > 0) {
3065
            error_log('learnpathItem::set_lesson_location()', 0);
3066
        }
3067
        if (isset($location)) {
3068
            $this->lesson_location = $location;
3069
3070
            return true;
3071
        }
3072
3073
        return false;
3074
    }
3075
3076
    /**
3077
     * Sets the item's depth level in the LP tree (0 is at root).
3078
     *
3079
     * @param int $int Level
3080
     */
3081
    public function set_level($int = 0)
3082
    {
3083
        if (self::DEBUG > 0) {
3084
            error_log('learnpathItem::set_level('.$int.')', 0);
3085
        }
3086
        if (!empty($int) && $int == strval(intval($int))) {
3087
            $this->level = $int;
3088
        }
3089
    }
3090
3091
    /**
3092
     * Sets the lp_view id this item view is registered to.
3093
     *
3094
     * @param int $lp_view_id lp_view DB ID
3095
     * @param int $course_id
3096
     *
3097
     * @return bool
3098
     *
3099
     * @todo //todo insert into lp_item_view if lp_view not exists
3100
     */
3101
    public function set_lp_view($lp_view_id, $course_id = null)
3102
    {
3103
        $lp_view_id = intval($lp_view_id);
3104
3105
        if (empty($course_id)) {
3106
            $course_id = api_get_course_int_id();
3107
        } else {
3108
            $course_id = intval($course_id);
3109
        }
3110
3111
        $lpItemId = $this->get_id();
3112
3113
        if (empty($lpItemId)) {
3114
            if (self::DEBUG > 0) {
3115
                error_log(
3116
                    'learnpathItem::set_lp_view('.$lp_view_id.') $lpItemId is empty',
3117
                    0
3118
                );
3119
            }
3120
3121
            return false;
3122
        }
3123
3124
        if (empty($lp_view_id)) {
3125
            if (self::DEBUG > 0) {
3126
                error_log(
3127
                    'learnpathItem::set_lp_view('.$lp_view_id.') $lp_view_id is empty',
3128
                    0
3129
                );
3130
            }
3131
3132
            return false;
3133
        }
3134
3135
        if (self::DEBUG > 0) {
3136
            error_log('learnpathItem::set_lp_view('.$lp_view_id.')', 0);
3137
        }
3138
3139
        $this->view_id = $lp_view_id;
3140
3141
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3142
        // Get the lp_item_view with the highest view_count.
3143
        $sql = "SELECT * FROM $item_view_table
3144
                WHERE
3145
                    c_id = $course_id AND
3146
                    lp_item_id = ".$lpItemId." AND
3147
                    lp_view_id = ".$lp_view_id."
3148
                ORDER BY view_count DESC";
3149
3150
        if (self::DEBUG > 2) {
3151
            error_log(
3152
                'learnpathItem::set_lp_view() - Querying lp_item_view: '.$sql,
3153
                0
3154
            );
3155
        }
3156
        $res = Database::query($sql);
3157
        if (Database::num_rows($res) > 0) {
3158
            $row = Database::fetch_array($res);
3159
            $this->db_item_view_id = $row['iid'];
3160
            $this->attempt_id = $row['view_count'];
3161
            $this->current_score = $row['score'];
3162
            $this->current_data = $row['suspend_data'];
3163
            $this->view_max_score = $row['max_score'];
3164
            $this->status = $row['status'];
3165
            $this->current_start_time = $row['start_time'];
3166
            $this->current_stop_time = $this->current_start_time + $row['total_time'];
3167
            $this->lesson_location = $row['lesson_location'];
3168
            $this->core_exit = $row['core_exit'];
3169
3170
            if (self::DEBUG > 2) {
3171
                error_log(
3172
                    'learnpathItem::set_lp_view() - Updated item object with database values',
3173
                    0
3174
                );
3175
            }
3176
3177
            // Now get the number of interactions for this little guy.
3178
            $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
3179
            $sql = "SELECT * FROM $table
3180
                    WHERE
3181
                        c_id = $course_id AND
3182
                        lp_iv_id = '".$this->db_item_view_id."'";
3183
3184
            $res = Database::query($sql);
3185
            if ($res !== false) {
3186
                $this->interactions_count = Database::num_rows($res);
3187
            } else {
3188
                $this->interactions_count = 0;
3189
            }
3190
            // Now get the number of objectives for this little guy.
3191
            $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
3192
            $sql = "SELECT * FROM $table
3193
                    WHERE
3194
                        c_id = $course_id AND
3195
                        lp_iv_id = '".$this->db_item_view_id."'";
3196
3197
            $res = Database::query($sql);
3198
            if ($res !== false) {
3199
                $this->objectives_count = Database::num_rows($res);
3200
            } else {
3201
                $this->objectives_count = 0;
3202
            }
3203
        }
3204
3205
        // End
3206
        if (self::DEBUG > 2) {
3207
            error_log('New LP - End of learnpathItem::set_lp_view()', 0);
3208
        }
3209
3210
        return true;
3211
    }
3212
3213
    /**
3214
     * Sets the path.
3215
     *
3216
     * @param string $string Path
3217
     */
3218
    public function set_path($string = '')
3219
    {
3220
        if (self::DEBUG > 0) {
3221
            error_log('learnpathItem::set_path()', 0);
3222
        }
3223
        if (!empty($string)) {
3224
            $this->path = $string;
3225
        }
3226
    }
3227
3228
    /**
3229
     * Sets the prevent_reinit attribute.
3230
     * This is based on the LP value and is set at creation time for
3231
     * each learnpathItem. It is a (bad?) way of avoiding
3232
     * a reference to the LP when saving an item.
3233
     *
3234
     * @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...
3235
     * saving freshened values (new "not attempted" status etc)
3236
     */
3237
    public function set_prevent_reinit($prevent)
3238
    {
3239
        if (self::DEBUG > 0) {
3240
            error_log('learnpathItem::set_prevent_reinit()', 0);
3241
        }
3242
        if ($prevent) {
3243
            $this->prevent_reinit = 1;
3244
        } else {
3245
            $this->prevent_reinit = 0;
3246
        }
3247
    }
3248
3249
    /**
3250
     * Sets the score value. If the mastery_score is set and the score reaches
3251
     * it, then set the status to 'passed'.
3252
     *
3253
     * @param float $score Score
3254
     *
3255
     * @return bool True on success, false otherwise
3256
     */
3257
    public function set_score($score)
3258
    {
3259
        $debug = self::DEBUG;
3260
        if ($debug > 0) {
3261
            error_log('learnpathItem::set_score('.$score.')', 0);
3262
        }
3263
        if (($this->max_score <= 0 || $score <= $this->max_score) && ($score >= $this->min_score)) {
3264
            $this->current_score = $score;
3265
            $masteryScore = $this->get_mastery_score();
3266
            $current_status = $this->get_status(false);
3267
3268
            // Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
3269
            if ($masteryScore == -1) {
3270
                $masteryScore = $this->max_score;
3271
            }
3272
3273
            if ($debug > 0) {
3274
                error_log('get_mastery_score: '.$masteryScore);
3275
                error_log('current_status: '.$current_status);
3276
                error_log('current score : '.$this->current_score);
3277
            }
3278
3279
            // If mastery_score is set AND the current score reaches the mastery
3280
            //  score AND the current status is different from 'completed', then
3281
            //  set it to 'passed'.
3282
            /*
3283
            if ($master != -1 && $this->current_score >= $master && $current_status != $this->possible_status[2]) {
3284
                if ($debug > 0) error_log('Status changed to: '.$this->possible_status[3]);
3285
                $this->set_status($this->possible_status[3]); //passed
3286
            } elseif ($master != -1 && $this->current_score < $master) {
3287
                if ($debug > 0) error_log('Status changed to: '.$this->possible_status[4]);
3288
                $this->set_status($this->possible_status[4]); //failed
3289
            }*/
3290
            return true;
3291
        }
3292
3293
        return false;
3294
    }
3295
3296
    /**
3297
     * Sets the maximum score for this item.
3298
     *
3299
     * @param int $score Maximum score - must be a decimal or an empty string
3300
     *
3301
     * @return bool True on success, false on error
3302
     */
3303
    public function set_max_score($score)
3304
    {
3305
        if (self::DEBUG > 0) {
3306
            error_log('learnpathItem::set_max_score('.$score.')', 0);
3307
        }
3308
        if (is_int($score) || $score == '') {
3309
            $this->view_max_score = $score;
3310
            if (self::DEBUG > 1) {
3311
                error_log(
3312
                    'learnpathItem::set_max_score() - '.
3313
                    'Updated object score of item '.$this->db_id.
3314
                    ' to '.$this->view_max_score,
3315
                    0
3316
                );
3317
            }
3318
3319
            return true;
3320
        }
3321
3322
        return false;
3323
    }
3324
3325
    /**
3326
     * Sets the status for this item.
3327
     *
3328
     * @param string $status Status - must be one of the values defined in $this->possible_status
3329
     *                       (this affects the status setting)
3330
     *
3331
     * @return bool True on success, false on error
3332
     */
3333
    public function set_status($status)
3334
    {
3335
        if (self::DEBUG > 0) {
3336
            error_log('learnpathItem::set_status('.$status.')', 0);
3337
        }
3338
3339
        $found = false;
3340
        foreach ($this->possible_status as $possible) {
3341
            if (preg_match('/^'.$possible.'$/i', $status)) {
3342
                $found = true;
3343
            }
3344
        }
3345
3346
        if ($found) {
3347
            $this->status = $status;
3348
            if (self::DEBUG > 1) {
3349
                error_log(
3350
                    'learnpathItem::set_status() - '.
3351
                        'Updated object status of item '.$this->db_id.
3352
                        ' to '.$this->status,
3353
                    0
3354
                );
3355
            }
3356
3357
            return true;
3358
        }
3359
3360
        $this->status = $this->possible_status[0];
3361
3362
        return false;
3363
    }
3364
3365
    /**
3366
     * Set the (indexing) terms for this learnpath item.
3367
     *
3368
     * @param string $terms Terms, as a comma-split list
3369
     *
3370
     * @return bool Always return true
3371
     */
3372
    public function set_terms($terms)
3373
    {
3374
        global $charset;
3375
        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
3376
        $a_terms = preg_split('/,/', $terms);
3377
        $i_terms = preg_split('/,/', $this->get_terms());
3378
        foreach ($i_terms as $term) {
3379
            if (!in_array($term, $a_terms)) {
3380
                array_push($a_terms, $term);
3381
            }
3382
        }
3383
        $new_terms = $a_terms;
3384
        $new_terms_string = implode(',', $new_terms);
3385
3386
        // TODO: Validate csv string.
3387
        $terms = Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset));
3388
        $sql = "UPDATE $lp_item
3389
                SET terms = '$terms'
3390
                WHERE iid=".$this->get_id();
3391
        Database::query($sql);
3392
        // Save it to search engine.
3393
        if (api_get_setting('search_enabled') == 'true') {
3394
            $di = new ChamiloIndexer();
3395
            $di->update_terms($this->get_search_did(), $new_terms, 'T');
3396
        }
3397
3398
        return true;
3399
    }
3400
3401
    /**
3402
     * Get the document ID from inside the text index database.
3403
     *
3404
     * @return int Search index database document ID
3405
     */
3406
    public function get_search_did()
3407
    {
3408
        return $this->search_did;
3409
    }
3410
3411
    /**
3412
     * Sets the item viewing time in a usable form, given that SCORM packages
3413
     * often give it as 00:00:00.0000.
3414
     *
3415
     * @param    string    Time as given by SCORM
3416
     * @param string $format
3417
     */
3418
    public function set_time($scorm_time, $format = 'scorm')
3419
    {
3420
        $debug = self::DEBUG;
3421
        if ($debug) {
3422
            error_log("learnpathItem::set_time($scorm_time, $format)");
3423
            error_log("this->type: ".$this->type);
3424
            error_log("this->current_start_time: ".$this->current_start_time);
3425
        }
3426
3427
        if ($scorm_time == '0' &&
3428
            $this->type != 'sco' &&
3429
            $this->current_start_time != 0
3430
        ) {
3431
            $myTime = time() - $this->current_start_time;
3432
            if ($myTime > 0) {
3433
                $this->update_time($myTime);
3434
                if ($debug) {
3435
                    error_log('found asset - set time to '.$myTime);
3436
                }
3437
            } else {
3438
                if ($debug) {
3439
                    error_log('Time not set');
3440
                }
3441
            }
3442
        } else {
3443
            switch ($format) {
3444
                case 'scorm':
3445
                    $res = [];
3446
                    if (preg_match(
3447
                        '/^(\d{1,4}):(\d{2}):(\d{2})(\.\d{1,4})?/',
3448
                        $scorm_time,
3449
                        $res
3450
                    )
3451
                    ) {
3452
                        $hour = $res[1];
3453
                        $min = $res[2];
3454
                        $sec = $res[3];
3455
                        // Getting total number of seconds spent.
3456
                        $totalSec = $hour * 3600 + $min * 60 + $sec;
3457
                        if ($debug) {
3458
                            error_log("totalSec : $totalSec");
3459
                            error_log("Now calling to scorm_update_time()");
3460
                        }
3461
                        $this->scorm_update_time($totalSec);
3462
                    }
3463
                    break;
3464
                case 'int':
3465
                    if ($debug) {
3466
                        error_log("scorm_time = $scorm_time");
3467
                        error_log("Now calling to scorm_update_time()");
3468
                    }
3469
                    $this->scorm_update_time($scorm_time);
3470
                    break;
3471
            }
3472
        }
3473
    }
3474
3475
    /**
3476
     * Sets the item's title.
3477
     *
3478
     * @param string $string Title
3479
     */
3480
    public function set_title($string = '')
3481
    {
3482
        if (self::DEBUG > 0) {
3483
            error_log('learnpathItem::set_title()', 0);
3484
        }
3485
        if (!empty($string)) {
3486
            $this->title = $string;
3487
        }
3488
    }
3489
3490
    /**
3491
     * Sets the item's type.
3492
     *
3493
     * @param string $string Type
3494
     */
3495
    public function set_type($string = '')
3496
    {
3497
        if (self::DEBUG > 0) {
3498
            error_log('learnpathItem::set_type()', 0);
3499
        }
3500
        if (!empty($string)) {
3501
            $this->type = $string;
3502
        }
3503
    }
3504
3505
    /**
3506
     * Checks if the current status is part of the list of status given.
3507
     *
3508
     * @param array $list An array of status to check for.
3509
     *                    If the current status is one of the strings, return true
3510
     *
3511
     * @return bool True if the status was one of the given strings,
3512
     *              false otherwise
3513
     */
3514
    public function status_is($list = [])
3515
    {
3516
        if (self::DEBUG > 1) {
3517
            error_log(
3518
                'learnpathItem::status_is('.print_r(
3519
                    $list,
3520
                    true
3521
                ).') on item '.$this->db_id,
3522
                0
3523
            );
3524
        }
3525
        $currentStatus = $this->get_status(true);
3526
        if (empty($currentStatus)) {
3527
            return false;
3528
        }
3529
        $found = false;
3530
        foreach ($list as $status) {
3531
            if (preg_match('/^'.$status.'$/i', $currentStatus)) {
3532
                if (self::DEBUG > 2) {
3533
                    error_log(
3534
                        'New LP - learnpathItem::status_is() - Found status '.
3535
                            $status.' corresponding to current status',
3536
                        0
3537
                    );
3538
                }
3539
                $found = true;
3540
3541
                return $found;
3542
            }
3543
        }
3544
        if (self::DEBUG > 2) {
3545
            error_log(
3546
                'New LP - learnpathItem::status_is() - Status '.
3547
                    $currentStatus.' did not match request',
3548
                0
3549
            );
3550
        }
3551
3552
        return $found;
3553
    }
3554
3555
    /**
3556
     * Updates the time info according to the given session_time.
3557
     *
3558
     * @param int $totalSec Time in seconds
3559
     */
3560
    public function update_time($totalSec = 0)
3561
    {
3562
        if (self::DEBUG > 0) {
3563
            error_log('learnpathItem::update_time('.$totalSec.')');
3564
        }
3565
        if ($totalSec >= 0) {
3566
            // Getting start time from finish time. The only problem in the calculation is it might be
3567
            // modified by the scripts processing time.
3568
            $now = time();
3569
            $start = $now - $totalSec;
3570
            $this->current_start_time = $start;
3571
            $this->current_stop_time = $now;
3572
        }
3573
    }
3574
3575
    /**
3576
     * Special scorm update time function. This function will update time
3577
     * directly into db for scorm objects.
3578
     *
3579
     * @param int $total_sec Total number of seconds
3580
     */
3581
    public function scorm_update_time($total_sec = 0)
3582
    {
3583
        $debug = self::DEBUG;
3584
        if ($debug) {
3585
            error_log('learnpathItem::scorm_update_time()');
3586
            error_log("total_sec: $total_sec");
3587
        }
3588
3589
        // Step 1 : get actual total time stored in db
3590
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3591
        $course_id = api_get_course_int_id();
3592
3593
        $sql = 'SELECT total_time, status 
3594
                FROM '.$item_view_table.'
3595
                WHERE 
3596
                    c_id = '.$course_id.' AND 
3597
                    lp_item_id = "'.$this->db_id.'" AND 
3598
                    lp_view_id = "'.$this->view_id.'" AND 
3599
                    view_count = "'.$this->get_attempt_id().'"';
3600
        $result = Database::query($sql);
3601
        $row = Database::fetch_array($result);
3602
3603
        if (!isset($row['total_time'])) {
3604
            $total_time = 0;
3605
        } else {
3606
            $total_time = $row['total_time'];
3607
        }
3608
        if ($debug) {
3609
            error_log("Original total_time: $total_time");
3610
        }
3611
3612
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
3613
        $lp_id = (int) $this->lp_id;
3614
        $sql = "SELECT * FROM $lp_table WHERE iid = $lp_id";
3615
        $res = Database::query($sql);
3616
        $accumulateScormTime = 'false';
3617
        if (Database::num_rows($res) > 0) {
3618
            $row = Database::fetch_assoc($res);
3619
            $accumulateScormTime = $row['accumulate_scorm_time'];
3620
        }
3621
3622
        // Step 2.1 : if normal mode total_time = total_time + total_sec
3623
        if ($this->type == 'sco' && $accumulateScormTime != 0) {
3624
            if ($debug) {
3625
                error_log("accumulateScormTime is on. total_time modified: $total_time + $total_sec");
3626
            }
3627
            $total_time += $total_sec;
3628
        } else {
3629
            // Step 2.2 : if not cumulative mode total_time = total_time - last_update + total_sec
3630
            $total_sec = $this->fixAbusiveTime($total_sec);
3631
            if ($debug) {
3632
                error_log("after fix abusive: $total_sec");
3633
                error_log("total_time: $total_time");
3634
                error_log("this->last_scorm_session_time: ".$this->last_scorm_session_time);
3635
            }
3636
3637
            $total_time = $total_time - $this->last_scorm_session_time + $total_sec;
3638
            $this->last_scorm_session_time = $total_sec;
3639
3640
            if ($total_time < 0) {
3641
                $total_time = $total_sec;
3642
            }
3643
        }
3644
3645
        if ($debug) {
3646
            error_log("accumulate_scorm_time: $accumulateScormTime");
3647
            error_log("total_time modified: $total_time");
3648
        }
3649
3650
        // Step 3 update db only if status != completed, passed, browsed or seriousgamemode not activated
3651
        // @todo complete
3652
        $case_completed = [
3653
            'completed',
3654
            'passed',
3655
            'browsed',
3656
            'failed',
3657
        ];
3658
3659
        if ($this->seriousgame_mode != 1 ||
3660
            !in_array($row['status'], $case_completed)
3661
        ) {
3662
            $sql = "UPDATE $item_view_table
3663
                      SET total_time = '$total_time'
3664
                    WHERE 
3665
                        c_id = $course_id AND 
3666
                        lp_item_id = {$this->db_id} AND 
3667
                        lp_view_id = {$this->view_id} AND 
3668
                        view_count = {$this->get_attempt_id()}";
3669
            if ($debug) {
3670
                error_log('-------------total_time updated ------------------------');
3671
                error_log($sql);
3672
                error_log('-------------------------------------');
3673
            }
3674
            Database::query($sql);
3675
        }
3676
    }
3677
3678
    /**
3679
     * Set the total_time to 0 into db.
3680
     */
3681
    public function scorm_init_time()
3682
    {
3683
        $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3684
        $course_id = api_get_course_int_id();
3685
        $sql = 'UPDATE '.$table.'
3686
                SET total_time = 0, 
3687
                    start_time = '.time().'
3688
                WHERE 
3689
                    c_id = '.$course_id.' AND 
3690
                    lp_item_id = "'.$this->db_id.'" AND 
3691
                    lp_view_id = "'.$this->view_id.'" AND 
3692
                    view_count = "'.$this->attempt_id.'"';
3693
        Database::query($sql);
3694
    }
3695
3696
    /**
3697
     * Write objectives to DB. This method is separate from write_to_db() because otherwise
3698
     * objectives are lost as a side effect to AJAX and session concurrent access.
3699
     *
3700
     * @return bool True or false on error
3701
     */
3702
    public function write_objectives_to_db()
3703
    {
3704
        if (self::DEBUG > 0) {
3705
            error_log('learnpathItem::write_objectives_to_db()', 0);
3706
        }
3707
        $course_id = api_get_course_int_id();
3708
        if (is_array($this->objectives) && count($this->objectives) > 0) {
3709
            // Save objectives.
3710
            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3711
            $sql = "SELECT iid
3712
                    FROM $tbl
3713
                    WHERE
3714
                        c_id = $course_id AND
3715
                        lp_item_id = ".$this->db_id." AND
3716
                        lp_view_id = ".$this->view_id." AND
3717
                        view_count = ".$this->attempt_id;
3718
            $res = Database::query($sql);
3719
            if (Database::num_rows($res) > 0) {
3720
                $row = Database::fetch_array($res);
3721
                $lp_iv_id = $row[0];
3722
                if (self::DEBUG > 2) {
3723
                    error_log(
3724
                        'learnpathItem::write_to_db() - Got item_view_id '.
3725
                            $lp_iv_id.', now checking objectives ',
3726
                        0
3727
                    );
3728
                }
3729
                foreach ($this->objectives as $index => $objective) {
3730
                    $iva_table = Database::get_course_table(
3731
                        TABLE_LP_IV_OBJECTIVE
3732
                    );
3733
                    $iva_sql = "SELECT iid FROM $iva_table
3734
                                WHERE
3735
                                    c_id = $course_id AND
3736
                                    lp_iv_id = $lp_iv_id AND
3737
                                    objective_id = '".Database::escape_string($objective[0])."'";
3738
                    $iva_res = Database::query($iva_sql);
3739
                    // id(0), type(1), time(2), weighting(3),
3740
                    // correct_responses(4), student_response(5),
3741
                    // result(6), latency(7)
3742
                    if (Database::num_rows($iva_res) > 0) {
3743
                        // Update (or don't).
3744
                        $iva_row = Database::fetch_array($iva_res);
3745
                        $iva_id = $iva_row[0];
3746
                        $ivau_sql = "UPDATE $iva_table ".
3747
                            "SET objective_id = '".Database::escape_string($objective[0])."',".
3748
                            "status = '".Database::escape_string($objective[1])."',".
3749
                            "score_raw = '".Database::escape_string($objective[2])."',".
3750
                            "score_min = '".Database::escape_string($objective[4])."',".
3751
                            "score_max = '".Database::escape_string($objective[3])."' ".
3752
                            "WHERE c_id = $course_id AND iid = $iva_id";
3753
                        Database::query($ivau_sql);
3754
                    } else {
3755
                        // Insert new one.
3756
                        $params = [
3757
                            'c_id' => $course_id,
3758
                            'lp_iv_id' => $lp_iv_id,
3759
                            'order_id' => $index,
3760
                            'objective_id' => $objective[0],
3761
                            'status' => $objective[1],
3762
                            'score_raw' => $objective[2],
3763
                            'score_min' => $objective[4],
3764
                            'score_max' => $objective[3],
3765
                        ];
3766
3767
                        $insertId = Database::insert($iva_table, $params);
3768
                        if ($insertId) {
3769
                            $sql = "UPDATE $iva_table SET id = iid 
3770
                                    WHERE iid = $insertId";
3771
                            Database::query($sql);
3772
                        }
3773
                    }
3774
                }
3775
            }
3776
        }
3777
    }
3778
3779
    /**
3780
     * Writes the current data to the database.
3781
     *
3782
     * @return bool Query result
3783
     */
3784
    public function write_to_db()
3785
    {
3786
        $debug = self::DEBUG;
3787
        if ($debug) {
3788
            error_log('learnpathItem::write_to_db()', 0);
3789
        }
3790
3791
        // Check the session visibility.
3792
        if (!api_is_allowed_to_session_edit()) {
3793
            if ($debug) {
3794
                error_log('return false api_is_allowed_to_session_edit');
3795
            }
3796
3797
            return false;
3798
        }
3799
3800
        $course_id = api_get_course_int_id();
3801
        $mode = $this->get_lesson_mode();
3802
        $credit = $this->get_credit();
3803
        $total_time = ' ';
3804
        $my_status = ' ';
3805
3806
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3807
        $sql = 'SELECT status, total_time FROM '.$item_view_table.'
3808
                WHERE
3809
                    c_id = '.$course_id.' AND
3810
                    lp_item_id="'.$this->db_id.'" AND
3811
                    lp_view_id="'.$this->view_id.'" AND
3812
                    view_count="'.$this->get_attempt_id().'" ';
3813
        $rs_verified = Database::query($sql);
3814
        $row_verified = Database::fetch_array($rs_verified);
3815
3816
        $my_case_completed = [
3817
            'completed',
3818
            'passed',
3819
            'browsed',
3820
            'failed',
3821
        ];
3822
3823
        $oldTotalTime = $row_verified['total_time'];
3824
        $this->oldTotalTime = $oldTotalTime;
3825
3826
        $save = true;
3827
        if (isset($row_verified) && isset($row_verified['status'])) {
3828
            if (in_array($row_verified['status'], $my_case_completed)) {
3829
                $save = false;
3830
            }
3831
        }
3832
3833
        if ((($save === false && $this->type == 'sco') ||
3834
           ($this->type == 'sco' && ($credit == 'no-credit' || $mode == 'review' || $mode == 'browse'))) &&
3835
           ($this->seriousgame_mode != 1 && $this->type == 'sco')
3836
        ) {
3837
            if ($debug) {
3838
                error_log(
3839
                    "This info shouldn't be saved as the credit or lesson mode info prevent it"
3840
                );
3841
                error_log(
3842
                    'learnpathItem::write_to_db() - credit('.$credit.') or'.
3843
                    ' lesson_mode('.$mode.') prevent recording!',
3844
                    0
3845
                );
3846
            }
3847
        } else {
3848
            // Check the row exists.
3849
            $inserted = false;
3850
            // This a special case for multiple attempts and Chamilo exercises.
3851
            if ($this->type == 'quiz' &&
3852
                $this->get_prevent_reinit() == 0 &&
3853
                $this->get_status() == 'completed'
3854
            ) {
3855
                // We force the item to be restarted.
3856
                $this->restart();
3857
                $params = [
3858
                    "c_id" => $course_id,
3859
                    "total_time" => $this->get_total_time(),
3860
                    "start_time" => $this->current_start_time,
3861
                    "score" => $this->get_score(),
3862
                    "status" => $this->get_status(false),
3863
                    "max_score" => $this->get_max(),
3864
                    "lp_item_id" => $this->db_id,
3865
                    "lp_view_id" => $this->view_id,
3866
                    "view_count" => $this->get_attempt_id(),
3867
                    "suspend_data" => $this->current_data,
3868
                    //"max_time_allowed" => ,
3869
                    "lesson_location" => $this->lesson_location,
3870
                ];
3871
                if ($debug) {
3872
                    error_log(
3873
                        'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
3874
                        0
3875
                    );
3876
                }
3877
                $this->db_item_view_id = Database::insert($item_view_table, $params);
3878
                if ($this->db_item_view_id) {
3879
                    $sql = "UPDATE $item_view_table SET id = iid
3880
                            WHERE iid = ".$this->db_item_view_id;
3881
                    Database::query($sql);
3882
                    $inserted = true;
3883
                }
3884
            }
3885
3886
            $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3887
            $sql = "SELECT * FROM $item_view_table
3888
                    WHERE
3889
                        c_id = $course_id AND
3890
                        lp_item_id = ".$this->db_id." AND
3891
                        lp_view_id = ".$this->view_id." AND
3892
                        view_count = ".intval($this->get_attempt_id());
3893
            if ($debug) {
3894
                error_log(
3895
                    'learnpathItem::write_to_db() - Querying item_view: '.$sql,
3896
                    0
3897
                );
3898
            }
3899
            $check_res = Database::query($sql);
3900
            // Depending on what we want (really), we'll update or insert a new row
3901
            // now save into DB.
3902
            if (!$inserted && Database::num_rows($check_res) < 1) {
3903
                $params = [
3904
                    "c_id" => $course_id,
3905
                    "total_time" => $this->get_total_time(),
3906
                    "start_time" => $this->current_start_time,
3907
                    "score" => $this->get_score(),
3908
                    "status" => $this->get_status(false),
3909
                    "max_score" => $this->get_max(),
3910
                    "lp_item_id" => $this->db_id,
3911
                    "lp_view_id" => $this->view_id,
3912
                    "view_count" => $this->get_attempt_id(),
3913
                    "suspend_data" => $this->current_data,
3914
                    //"max_time_allowed" => ,$this->get_max_time_allowed()
3915
                    "lesson_location" => $this->lesson_location,
3916
                ];
3917
3918
                if ($debug) {
3919
                    error_log(
3920
                        'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
3921
                        0
3922
                    );
3923
                }
3924
3925
                $this->db_item_view_id = Database::insert($item_view_table, $params);
3926
                if ($this->db_item_view_id) {
3927
                    $sql = "UPDATE $item_view_table SET id = iid
3928
                            WHERE iid = ".$this->db_item_view_id;
3929
                    Database::query($sql);
3930
                }
3931
            } else {
3932
                if ($this->type == 'hotpotatoes') {
3933
                    $params = [
3934
                        'total_time' => $this->get_total_time(),
3935
                        'start_time' => $this->get_current_start_time(),
3936
                        'score' => $this->get_score(),
3937
                        'status' => $this->get_status(false),
3938
                        'max_score' => $this->get_max(),
3939
                        'suspend_data' => $this->current_data,
3940
                        'lesson_location' => $this->lesson_location,
3941
                    ];
3942
                    $where = [
3943
                        'c_id = ? AND lp_item_id = ? AND lp_view_id = ? AND view_count = ?' => [
3944
                            $course_id,
3945
                            $this->db_id,
3946
                            $this->view_id,
3947
                            $this->get_attempt_id(),
3948
                        ],
3949
                    ];
3950
                    Database::update($item_view_table, $params, $where);
3951
                } else {
3952
                    // For all other content types...
3953
                    if ($this->type == 'quiz') {
3954
                        if ($debug) {
3955
                            error_log("item is quiz:");
3956
                        }
3957
                        $my_status = ' ';
3958
                        $total_time = ' ';
3959
                        if (!empty($_REQUEST['exeId'])) {
3960
                            $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
3961
                            $exeId = (int) $_REQUEST['exeId'];
3962
                            $sql = "SELECT exe_duration
3963
                                    FROM $table
3964
                                    WHERE exe_id = $exeId";
3965
                            if ($debug) {
3966
                                error_log($sql);
3967
                            }
3968
                            $res = Database::query($sql);
3969
                            $exeRow = Database::fetch_array($res);
3970
                            $duration = $exeRow['exe_duration'];
3971
                            $total_time = " total_time = ".$duration.", ";
3972
                            if ($debug) {
3973
                                error_log("quiz: $total_time");
3974
                            }
3975
                        }
3976
                    } else {
3977
                        $my_type_lp = learnpath::get_type_static($this->lp_id);
3978
                        // This is a array containing values finished
3979
                        $case_completed = [
3980
                            'completed',
3981
                            'passed',
3982
                            'browsed',
3983
                            'failed',
3984
                        ];
3985
3986
                        // Is not multiple attempts
3987
                        if ($this->seriousgame_mode == 1 && $this->type == 'sco') {
3988
                            $total_time = " total_time = total_time +".$this->get_total_time().", ";
3989
                            $my_status = " status = '".$this->get_status(false)."' ,";
3990
                            if ($debug) {
3991
                                error_log("seriousgame_mode time changed: $total_time");
3992
                            }
3993
                        } elseif ($this->get_prevent_reinit() == 1) {
3994
                            // Process of status verified into data base.
3995
                            $sql = 'SELECT status FROM '.$item_view_table.'
3996
                                    WHERE
3997
                                        c_id = '.$course_id.' AND
3998
                                        lp_item_id="'.$this->db_id.'" AND
3999
                                        lp_view_id="'.$this->view_id.'" AND
4000
                                        view_count="'.$this->get_attempt_id().'"
4001
                                    ';
4002
                            $rs_verified = Database::query($sql);
4003
                            $row_verified = Database::fetch_array($rs_verified);
4004
4005
                            // Get type lp: 1=lp dokeos and  2=scorm.
4006
                            // If not is completed or passed or browsed and learning path is scorm.
4007
                            if (!in_array($this->get_status(false), $case_completed) &&
4008
                                $my_type_lp == 2
4009
                            ) {
4010
                                $total_time = " total_time = total_time +".$this->get_total_time().", ";
4011
                                $my_status = " status = '".$this->get_status(false)."' ,";
4012
                                if ($debug) {
4013
                                    error_log("get_prevent_reinit = 1 time changed: $total_time");
4014
                                }
4015
                            } else {
4016
                                // Verified into database.
4017
                                if (!in_array($row_verified['status'], $case_completed) &&
4018
                                    $my_type_lp == 2
4019
                                ) {
4020
                                    $total_time = " total_time = total_time +".$this->get_total_time().", ";
4021
                                    $my_status = " status = '".$this->get_status(false)."' ,";
4022
                                    if ($debug) {
4023
                                        error_log("total_time time changed case 1: $total_time");
4024
                                    }
4025
                                } elseif (in_array($row_verified['status'], $case_completed) &&
4026
                                    $my_type_lp == 2 && $this->type != 'sco'
4027
                                ) {
4028
                                    $total_time = " total_time = total_time +".$this->get_total_time().", ";
4029
                                    $my_status = " status = '".$this->get_status(false)."' ,";
4030
                                    if ($debug) {
4031
                                        error_log("total_time time changed case 2: $total_time");
4032
                                    }
4033
                                } else {
4034
                                    if (($my_type_lp == 3 && $this->type == 'au') ||
4035
                                        ($my_type_lp == 1 && $this->type != 'dir')) {
4036
                                        // Is AICC or Chamilo LP
4037
                                        $total_time = " total_time = total_time + ".$this->get_total_time().", ";
4038
                                        $my_status = " status = '".$this->get_status(false)."' ,";
4039
                                        if ($debug) {
4040
                                            error_log("total_time time changed case 3: $total_time");
4041
                                        }
4042
                                    }
4043
                                }
4044
                            }
4045
                        } else {
4046
                            // Multiple attempts are allowed.
4047
                            if (in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
4048
                                // Reset zero new attempt ?
4049
                                $my_status = " status = '".$this->get_status(false)."' ,";
4050
                                if ($debug) {
4051
                                    error_log("total_time time changed Multiple attempt case 1: $total_time");
4052
                                }
4053
                            } elseif (!in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
4054
                                $total_time = " total_time = ".$this->get_total_time().", ";
4055
                                $my_status = " status = '".$this->get_status(false)."' ,";
4056
                                if ($debug) {
4057
                                    error_log("total_time time changed Multiple attempt case 2: $total_time");
4058
                                }
4059
                            } else {
4060
                                // It is chamilo LP.
4061
                                $total_time = " total_time = total_time +".$this->get_total_time().", ";
4062
                                $my_status = " status = '".$this->get_status(false)."' ,";
4063
                                if ($debug) {
4064
                                    error_log("total_time time changed Multiple attempt case 3: $total_time");
4065
                                }
4066
                            }
4067
4068
                            // This code line fixes the problem of wrong status.
4069
                            if ($my_type_lp == 2) {
4070
                                // Verify current status in multiples attempts.
4071
                                $sql = 'SELECT status FROM '.$item_view_table.'
4072
                                        WHERE
4073
                                            c_id = '.$course_id.' AND
4074
                                            lp_item_id="'.$this->db_id.'" AND
4075
                                            lp_view_id="'.$this->view_id.'" AND
4076
                                            view_count="'.$this->get_attempt_id().'" ';
4077
                                $rs_status = Database::query($sql);
4078
                                $current_status = Database::result(
4079
                                    $rs_status,
4080
                                    0,
4081
                                    'status'
4082
                                );
4083
                                if (in_array($current_status, $case_completed)) {
4084
                                    $my_status = '';
4085
                                    $total_time = '';
4086
                                } else {
4087
                                    $total_time = " total_time = total_time + ".$this->get_total_time().", ";
4088
                                }
4089
4090
                                if ($debug) {
4091
                                    error_log("total_time time my_type_lp: $total_time");
4092
                                }
4093
                            }
4094
                        }
4095
                    }
4096
4097
                    if ($this->type == 'sco') {
4098
                        //IF scorm scorm_update_time has already updated total_time in db
4099
                        //" . //start_time = ".$this->get_current_start_time().", " . //scorm_init_time does it
4100
                        ////" max_time_allowed = '".$this->get_max_time_allowed()."'," .
4101
                        $sql = "UPDATE $item_view_table SET
4102
                                    score = ".$this->get_score().",
4103
                                    $my_status
4104
                                    max_score = '".$this->get_max()."',
4105
                                    suspend_data = '".Database::escape_string($this->current_data)."',
4106
                                    lesson_location = '".$this->lesson_location."'
4107
                                WHERE
4108
                                    c_id = $course_id AND
4109
                                    lp_item_id = ".$this->db_id." AND
4110
                                    lp_view_id = ".$this->view_id."  AND
4111
                                    view_count = ".$this->get_attempt_id();
4112
                    } else {
4113
                        //" max_time_allowed = '".$this->get_max_time_allowed()."'," .
4114
                        $sql = "UPDATE $item_view_table SET
4115
                                    $total_time
4116
                                    start_time = ".$this->get_current_start_time().",
4117
                                    score = ".$this->get_score().",
4118
                                    $my_status
4119
                                    max_score = '".$this->get_max()."',
4120
                                    suspend_data = '".Database::escape_string($this->current_data)."',
4121
                                    lesson_location = '".$this->lesson_location."'
4122
                                WHERE
4123
                                    c_id = $course_id AND
4124
                                    lp_item_id = ".$this->db_id." AND
4125
                                    lp_view_id = ".$this->view_id." AND
4126
                                    view_count = ".$this->get_attempt_id();
4127
                    }
4128
                    $this->current_start_time = time();
4129
                }
4130
                if ($debug) {
4131
                    error_log('-------------------------------------------');
4132
                    error_log('learnpathItem::write_to_db() - Updating item_view:');
4133
                    error_log($sql);
4134
                    error_log('-------------------------------------------');
4135
                }
4136
                Database::query($sql);
4137
            }
4138
4139
            if (is_array($this->interactions) &&
4140
                count($this->interactions) > 0
4141
            ) {
4142
                // Save interactions.
4143
                $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
4144
                $sql = "SELECT iid FROM $tbl
4145
                        WHERE
4146
                            c_id = $course_id AND
4147
                            lp_item_id = ".$this->db_id." AND
4148
                            lp_view_id = ".$this->view_id." AND
4149
                            view_count = ".$this->get_attempt_id();
4150
                $res = Database::query($sql);
4151
                if (Database::num_rows($res) > 0) {
4152
                    $row = Database::fetch_array($res);
4153
                    $lp_iv_id = $row[0];
4154
                    if ($debug) {
4155
                        error_log(
4156
                            'learnpathItem::write_to_db() - Got item_view_id '.
4157
                            $lp_iv_id.', now checking interactions ',
4158
                            0
4159
                        );
4160
                    }
4161
                    foreach ($this->interactions as $index => $interaction) {
4162
                        $correct_resp = '';
4163
                        if (is_array($interaction[4]) && !empty($interaction[4][0])) {
4164
                            foreach ($interaction[4] as $resp) {
4165
                                $correct_resp .= $resp.',';
4166
                            }
4167
                            $correct_resp = substr(
4168
                                $correct_resp,
4169
                                0,
4170
                                strlen($correct_resp) - 1
4171
                            );
4172
                        }
4173
                        $iva_table = Database::get_course_table(
4174
                            TABLE_LP_IV_INTERACTION
4175
                        );
4176
4177
                        //also check for the interaction ID as it must be unique for this SCO view
4178
                        $iva_sql = "SELECT iid FROM $iva_table
4179
                                    WHERE
4180
                                        c_id = $course_id AND
4181
                                        lp_iv_id = $lp_iv_id AND
4182
                                        (
4183
                                            order_id = $index OR
4184
                                            interaction_id = '".Database::escape_string($interaction[0])."'
4185
                                        )
4186
                                    ";
4187
                        $iva_res = Database::query($iva_sql);
4188
4189
                        $interaction[0] = isset($interaction[0]) ? $interaction[0] : '';
4190
                        $interaction[1] = isset($interaction[1]) ? $interaction[1] : '';
4191
                        $interaction[2] = isset($interaction[2]) ? $interaction[2] : '';
4192
                        $interaction[3] = isset($interaction[3]) ? $interaction[3] : '';
4193
                        $interaction[4] = isset($interaction[4]) ? $interaction[4] : '';
4194
                        $interaction[5] = isset($interaction[5]) ? $interaction[5] : '';
4195
                        $interaction[6] = isset($interaction[6]) ? $interaction[6] : '';
4196
                        $interaction[7] = isset($interaction[7]) ? $interaction[7] : '';
4197
4198
                        // id(0), type(1), time(2), weighting(3), correct_responses(4), student_response(5), result(6), latency(7)
4199
                        if (Database::num_rows($iva_res) > 0) {
4200
                            // Update (or don't).
4201
                            $iva_row = Database::fetch_array($iva_res);
4202
                            $iva_id = $iva_row[0];
4203
                            // Insert new one.
4204
                            $params = [
4205
                                'interaction_id' => $interaction[0],
4206
                                'interaction_type' => $interaction[1],
4207
                                'weighting' => $interaction[3],
4208
                                'completion_time' => $interaction[2],
4209
                                'correct_responses' => $correct_resp,
4210
                                'student_response' => $interaction[5],
4211
                                'result' => $interaction[6],
4212
                                'latency' => $interaction[7],
4213
                            ];
4214
                            Database::update(
4215
                                $iva_table,
4216
                                $params,
4217
                                [
4218
                                    'c_id = ? AND iid = ?' => [
4219
                                        $course_id,
4220
                                        $iva_id,
4221
                                    ],
4222
                                ]
4223
                            );
4224
                        } else {
4225
                            // Insert new one.
4226
                            $params = [
4227
                                'c_id' => $course_id,
4228
                                'order_id' => $index,
4229
                                'lp_iv_id' => $lp_iv_id,
4230
                                'interaction_id' => $interaction[0],
4231
                                'interaction_type' => $interaction[1],
4232
                                'weighting' => $interaction[3],
4233
                                'completion_time' => $interaction[2],
4234
                                'correct_responses' => $correct_resp,
4235
                                'student_response' => $interaction[5],
4236
                                'result' => $interaction[6],
4237
                                'latency' => $interaction[7],
4238
                            ];
4239
4240
                            $insertId = Database::insert($iva_table, $params);
4241
                            if ($insertId) {
4242
                                $sql = "UPDATE $iva_table SET id = iid
4243
                                        WHERE iid = $insertId";
4244
                                Database::query($sql);
4245
                            }
4246
                        }
4247
                    }
4248
                }
4249
            }
4250
        }
4251
4252
        if ($debug) {
4253
            error_log('End of learnpathItem::write_to_db()', 0);
4254
        }
4255
4256
        return true;
4257
    }
4258
4259
    /**
4260
     * Adds an audio file attached to the current item (store on disk and in db).
4261
     *
4262
     * @return bool|null|string
4263
     */
4264
    public function add_audio()
4265
    {
4266
        $course_info = api_get_course_info();
4267
        $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/';
4268
4269
        if (!is_dir($filepath.'audio')) {
4270
            mkdir(
4271
                $filepath.'audio',
4272
                api_get_permissions_for_new_directories()
4273
            );
4274
            DocumentManager::addDocument(
4275
                $course_info,
4276
                '/audio',
4277
                'folder',
4278
                0,
4279
                'audio'
4280
            );
4281
        }
4282
4283
        $key = 'file';
4284
        if (!isset($_FILES[$key]['name']) || !isset($_FILES[$key]['tmp_name'])) {
4285
            return false;
4286
        }
4287
        $result = DocumentManager::upload_document(
4288
            $_FILES,
4289
            '/audio',
4290
            null,
4291
            null,
4292
            0,
4293
            'rename',
4294
            false,
4295
            false
4296
        );
4297
        $file_path = null;
4298
4299
        if ($result) {
4300
            $file_path = basename($result['path']);
4301
4302
            // Store the mp3 file in the lp_item table.
4303
            $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
4304
            $sql = "UPDATE $tbl_lp_item SET
4305
                        audio = '".Database::escape_string($file_path)."'
4306
                    WHERE iid = ".intval($this->db_id);
4307
            Database::query($sql);
4308
        }
4309
4310
        return $file_path;
4311
    }
4312
4313
    /**
4314
     * Adds an audio file to the current item, using a file already in documents.
4315
     *
4316
     * @param int $doc_id
4317
     *
4318
     * @return string
4319
     */
4320
    public function add_audio_from_documents($doc_id)
4321
    {
4322
        $course_info = api_get_course_info();
4323
        $document_data = DocumentManager::get_document_data_by_id(
4324
            $doc_id,
4325
            $course_info['code']
4326
        );
4327
4328
        $file_path = '';
4329
        if (!empty($document_data)) {
4330
            $file_path = basename($document_data['path']);
4331
            // Store the mp3 file in the lp_item table.
4332
            $table = Database::get_course_table(TABLE_LP_ITEM);
4333
            $sql = "UPDATE $table SET
4334
                        audio = '".Database::escape_string($file_path)."'
4335
                    WHERE iid = ".intval($this->db_id);
4336
            Database::query($sql);
4337
        }
4338
4339
        return $file_path;
4340
    }
4341
4342
    /**
4343
     * Removes the relation between the current item and an audio file. The file
4344
     * is only removed from the lp_item table, but remains in the document table
4345
     * and directory.
4346
     *
4347
     * @return bool
4348
     */
4349
    public function remove_audio()
4350
    {
4351
        if (empty($this->db_id)) {
4352
            return false;
4353
        }
4354
        $table = Database::get_course_table(TABLE_LP_ITEM);
4355
        $sql = "UPDATE $table SET
4356
                audio = ''
4357
                WHERE iid IN (".$this->db_id.")";
4358
        Database::query($sql);
4359
    }
4360
4361
    /**
4362
     * Transform the SCORM status to a string that can be translated by Chamilo
4363
     * in different user languages.
4364
     *
4365
     * @param $status
4366
     * @param bool   $decorate
4367
     * @param string $type     classic|simple
4368
     *
4369
     * @return array|string
4370
     */
4371
    public static function humanize_status($status, $decorate = true, $type = 'classic')
4372
    {
4373
        $statusList = [
4374
            'completed' => 'ScormCompstatus',
4375
            'incomplete' => 'ScormIncomplete',
4376
            'failed' => 'ScormFailed',
4377
            'passed' => 'ScormPassed',
4378
            'browsed' => 'ScormBrowsed',
4379
            'not attempted' => 'ScormNotAttempted',
4380
        ];
4381
4382
        $myLessonStatus = get_lang($statusList[$status]);
4383
4384
        switch ($status) {
4385
            case 'completed':
4386
            case 'browsed':
4387
                $classStatus = 'info';
4388
                break;
4389
            case 'incomplete':
4390
                $classStatus = 'warning';
4391
                break;
4392
            case 'passed':
4393
                $classStatus = 'success';
4394
                break;
4395
            case 'failed':
4396
                $classStatus = 'important';
4397
                break;
4398
            default:
4399
                $classStatus = 'default';
4400
                break;
4401
        }
4402
4403
        if ($type == 'simple') {
4404
            if (in_array($status, ['failed', 'passed', 'browsed'])) {
4405
                $myLessonStatus = get_lang('ScormIncomplete');
4406
4407
                $classStatus = 'warning';
4408
            }
4409
        }
4410
4411
        if ($decorate) {
4412
            return Display::label($myLessonStatus, $classStatus);
4413
        } else {
4414
            return $myLessonStatus;
4415
        }
4416
    }
4417
4418
    /**
4419
     * @return float
4420
     */
4421
    public function getPrerequisiteMaxScore()
4422
    {
4423
        return $this->prerequisiteMaxScore;
4424
    }
4425
4426
    /**
4427
     * @param float $prerequisiteMaxScore
4428
     */
4429
    public function setPrerequisiteMaxScore($prerequisiteMaxScore)
4430
    {
4431
        $this->prerequisiteMaxScore = $prerequisiteMaxScore;
4432
    }
4433
4434
    /**
4435
     * @return float
4436
     */
4437
    public function getPrerequisiteMinScore()
4438
    {
4439
        return $this->prerequisiteMinScore;
4440
    }
4441
4442
    /**
4443
     * @param float $prerequisiteMinScore
4444
     */
4445
    public function setPrerequisiteMinScore($prerequisiteMinScore)
4446
    {
4447
        $this->prerequisiteMinScore = $prerequisiteMinScore;
4448
    }
4449
4450
    /**
4451
     * Check if this LP item has a created thread in the basis course from the forum of its LP.
4452
     *
4453
     * @param int $lpCourseId The course ID
4454
     *
4455
     * @return bool
4456
     */
4457
    public function lpItemHasThread($lpCourseId)
4458
    {
4459
        $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
4460
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4461
4462
        $fakeFrom = "
4463
            $forumThreadTable ft
4464
            INNER JOIN $itemProperty ip
4465
            ON (ft.thread_id = ip.ref AND ft.c_id = ip.c_id)
4466
        ";
4467
4468
        $resultData = Database::select(
4469
            'COUNT(ft.iid) AS qty',
4470
            $fakeFrom,
4471
            [
4472
                'where' => [
4473
                    'ip.visibility != ? AND ' => 2,
4474
                    'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
4475
                    'ft.c_id = ? AND ' => intval($lpCourseId),
4476
                    '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
4477
                        intval($this->db_id),
4478
                        "{$this->title} - {$this->db_id}",
4479
                        intval($this->db_id),
4480
                    ],
4481
                ],
4482
            ],
4483
            'first'
4484
        );
4485
4486
        if ($resultData['qty'] > 0) {
4487
            return true;
4488
        }
4489
4490
        return false;
4491
    }
4492
4493
    /**
4494
     * Get the forum thread info.
4495
     *
4496
     * @param int $lpCourseId  The course ID from the learning path
4497
     * @param int $lpSessionId Optional. The session ID from the learning path
4498
     *
4499
     * @return bool
4500
     */
4501
    public function getForumThread($lpCourseId, $lpSessionId = 0)
4502
    {
4503
        $lpSessionId = (int) $lpSessionId;
4504
        $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
4505
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4506
4507
        $fakeFrom = "$forumThreadTable ft
4508
            INNER JOIN $itemProperty ip ";
4509
4510
        if ($lpSessionId == 0) {
4511
            $fakeFrom .= "
4512
                ON (
4513
                    ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND (
4514
                        ft.session_id = ip.session_id OR ip.session_id IS NULL
4515
                    )
4516
                )
4517
            ";
4518
        } else {
4519
            $fakeFrom .= "
4520
                ON (
4521
                    ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND ft.session_id = ip.session_id
4522
                )
4523
            ";
4524
        }
4525
4526
        $resultData = Database::select(
4527
            'ft.*',
4528
            $fakeFrom,
4529
            [
4530
                'where' => [
4531
                    'ip.visibility != ? AND ' => 2,
4532
                    'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
4533
                    'ft.session_id = ? AND ' => $lpSessionId,
4534
                    'ft.c_id = ? AND ' => intval($lpCourseId),
4535
                    '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
4536
                        intval($this->db_id),
4537
                        "{$this->title} - {$this->db_id}",
4538
                        intval($this->db_id),
4539
                    ],
4540
                ],
4541
            ],
4542
            'first'
4543
        );
4544
4545
        if (empty($resultData)) {
4546
            return false;
4547
        }
4548
4549
        return $resultData;
4550
    }
4551
4552
    /**
4553
     * Create a forum thread for this learning path item.
4554
     *
4555
     * @param int $currentForumId The forum ID to add the new thread
4556
     *
4557
     * @return int The forum thread if was created. Otherwise return false
4558
     */
4559
    public function createForumThread($currentForumId)
4560
    {
4561
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
4562
4563
        $em = Database::getManager();
4564
        $threadRepo = $em->getRepository('ChamiloCourseBundle:CForumThread');
4565
        $forumThread = $threadRepo->findOneBy([
4566
            'threadTitle' => "{$this->title} - {$this->db_id}",
4567
            'forumId' => (int) $currentForumId,
4568
        ]);
4569
4570
        if (!$forumThread) {
4571
            $forumInfo = get_forum_information($currentForumId);
4572
4573
            store_thread(
4574
                $forumInfo,
4575
                [
4576
                    'forum_id' => intval($currentForumId),
4577
                    'thread_id' => 0,
4578
                    'gradebook' => 0,
4579
                    'post_title' => "{$this->name} - {$this->db_id}",
4580
                    'post_text' => $this->description,
4581
                    'category_id' => 1,
4582
                    'numeric_calification' => 0,
4583
                    'calification_notebook_title' => 0,
4584
                    'weight_calification' => 0.00,
4585
                    'thread_peer_qualify' => 0,
4586
                    'lp_item_id' => $this->db_id,
4587
                ],
4588
                [],
4589
                false
4590
            );
4591
4592
            return;
4593
        }
4594
4595
        $forumThread->setLpItemId($this->db_id);
4596
4597
        $em->persist($forumThread);
4598
        $em->flush();
4599
    }
4600
4601
    /**
4602
     * Allow dissociate a forum to this LP item.
4603
     *
4604
     * @param int $threadIid The thread id
4605
     *
4606
     * @return bool
4607
     */
4608
    public function dissociateForumThread($threadIid)
4609
    {
4610
        $threadIid = (int) $threadIid;
4611
        $em = Database::getManager();
4612
4613
        $forumThread = $em->find('ChamiloCourseBundle:CForumThread', $threadIid);
4614
4615
        if (!$forumThread) {
4616
            return false;
4617
        }
4618
4619
        $forumThread->setThreadTitle("{$this->get_title()} - {$this->db_id}");
4620
        $forumThread->setLpItemId(0);
4621
4622
        $em->persist($forumThread);
4623
        $em->flush();
4624
4625
        return true;
4626
    }
4627
4628
    /**
4629
     * @return int
4630
     */
4631
    public function getLastScormSessionTime()
4632
    {
4633
        return $this->last_scorm_session_time;
4634
    }
4635
4636
    /**
4637
     * @return int
4638
     */
4639
    public function getIid()
4640
    {
4641
        return $this->iId;
4642
    }
4643
}
4644