Completed
Push — master ( 88715c...d7c14e )
by Julito
09:34
created

learnpathItem::get_id()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 4
nop 0
dl 0
loc 10
rs 10
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 array|null $item_content An array with the contents of the item
93
     */
94
    public function __construct(
95
        $id,
96
        $user_id = 0,
97
        $course_id = 0,
98
        $item_content = null
99
    ) {
100
        $items_table = Database::get_course_table(TABLE_LP_ITEM);
101
102
        // Get items table.
103
        if (!isset($user_id)) {
104
            $user_id = api_get_user_id();
105
        }
106
        if (self::DEBUG > 0) {
107
            error_log("learnpathItem constructor: id: $id user_id: $user_id course_id: $course_id");
108
            error_log("item_content: ".print_r($item_content, 1));
109
        }
110
        $id = (int) $id;
111
        if (empty($item_content)) {
112
            if (empty($course_id)) {
113
                $course_id = api_get_course_int_id();
114
            } else {
115
                $course_id = (int) $course_id;
116
            }
117
            $sql = "SELECT * FROM $items_table
118
                    WHERE iid = $id";
119
            $res = Database::query($sql);
120
            if (Database::num_rows($res) < 1) {
121
                $this->error = 'Could not find given learnpath item in learnpath_item table';
122
            }
123
            $row = Database::fetch_array($res);
124
        } else {
125
            $row = $item_content;
126
        }
127
128
        $this->lp_id = $row['lp_id'];
129
        $this->iId = $row['iid'];
130
        $this->max_score = $row['max_score'];
131
        $this->min_score = $row['min_score'];
132
        $this->name = $row['title'];
133
        $this->type = $row['item_type'];
134
        $this->ref = $row['ref'];
135
        $this->title = $row['title'];
136
        $this->description = $row['description'];
137
        $this->path = $row['path'];
138
        $this->mastery_score = $row['mastery_score'];
139
        $this->parent = $row['parent_item_id'];
140
        $this->next = $row['next_item_id'];
141
        $this->previous = $row['previous_item_id'];
142
        $this->display_order = $row['display_order'];
143
        $this->prereq_string = $row['prerequisite'];
144
        $this->max_time_allowed = $row['max_time_allowed'];
145
        $this->setPrerequisiteMaxScore($row['prerequisite_max_score']);
146
        $this->setPrerequisiteMinScore($row['prerequisite_min_score']);
147
        $this->oldTotalTime = 0;
148
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
        if (!api_get_configuration_value('lp_minimum_time')) {
1893
            $fixedAddedMinute = 5 * 60; // Add only 5 minutes
1894
            if ($time > $sessionLifetime) {
1895
                error_log("fixAbusiveTime: Total time is too big: $time replaced with: $fixedAddedMinute");
1896
                error_log("item_id : ".$this->db_id." lp_item_view.iid: ".$this->db_item_view_id);
1897
                $time = $fixedAddedMinute;
1898
            }
1899
1900
            return $time;
1901
        } else {
1902
            // Calulate minimum and accumulated time
1903
            $user_id = api_get_user_id();
1904
            $myLP = learnpath::getLpFromSession(api_get_course_id(), $this->lp_id, $user_id);
1905
            $timeLp = $myLP->getAccumulateWorkTime();
1906
            $timeTotalCourse = $myLP->getAccumulateWorkTimeTotalCourse();
1907
            /*
1908
            $timeLp = $_SESSION['oLP']->getAccumulateWorkTime();
1909
            $timeTotalCourse = $_SESSION['oLP']->getAccumulateWorkTimeTotalCourse();
1910
            */
1911
            // Minimum connection percentage
1912
            $perc = 100;
1913
            // Time from the course
1914
            $tc = $timeTotalCourse;
1915
            /*if (!empty($sessionId) && $sessionId != 0) {
1916
                $sql = "SELECT hours, perc FROM plugin_licences_course_session WHERE session_id = $sessionId";
1917
                $res = Database::query($sql);
1918
                if (Database::num_rows($res) > 0) {
1919
                    $aux = Database::fetch_assoc($res);
1920
                    $perc = $aux['perc'];
1921
                    $tc = $aux['hours'] * 60;
1922
                }
1923
            }*/
1924
            // Percentage of the learning paths
1925
            $pl = 0;
1926
            if (!empty($timeTotalCourse)) {
1927
                $pl = $timeLp / $timeTotalCourse;
1928
            }
1929
1930
            // Minimum time for each learning path
1931
            $accumulateWorkTime = ($pl * $tc * $perc / 100);
1932
            $time_seg = intval($accumulateWorkTime * 60);
1933
1934
            if ($time_seg < $sessionLifetime) {
1935
                $sessionLifetime = $time_seg;
1936
            }
1937
1938
            if ($time > $sessionLifetime) {
1939
                $fixedAddedMinute = $time_seg + mt_rand(0, 300);
1940
                if (self::DEBUG > 2) {
1941
                    error_log("Total time is too big: $time replaced with: $fixedAddedMinute");
1942
                }
1943
                $time = $fixedAddedMinute;
1944
            }
1945
1946
            return $time;
1947
        }
1948
    }
1949
1950
    /**
1951
     * Gets the item type.
1952
     *
1953
     * @return string The item type (can be doc, dir, sco, asset)
1954
     */
1955
    public function get_type()
1956
    {
1957
        $res = 'asset';
1958
        if (!empty($this->type)) {
1959
            $res = $this->type;
1960
        }
1961
        if (self::DEBUG > 2) {
1962
            error_log(
1963
                'learnpathItem::get_type() - Returning '.$res.' for item '.$this->db_id,
1964
                0
1965
            );
1966
        }
1967
1968
        return $res;
1969
    }
1970
1971
    /**
1972
     * Gets the view count for this item.
1973
     *
1974
     * @return int Number of attempts or 0
1975
     */
1976
    public function get_view_count()
1977
    {
1978
        if (self::DEBUG > 0) {
1979
            error_log('learnpathItem::get_view_count()', 0);
1980
        }
1981
        if (!empty($this->attempt_id)) {
1982
            return $this->attempt_id;
1983
        } else {
1984
            return 0;
1985
        }
1986
    }
1987
1988
    /**
1989
     * Tells if an item is done ('completed','passed','succeeded') or not.
1990
     *
1991
     * @return bool True if the item is done ('completed','passed','succeeded'),
1992
     *              false otherwise
1993
     */
1994
    public function is_done()
1995
    {
1996
        $completedStatusList = [
1997
            'completed',
1998
            'passed',
1999
            'succeeded',
2000
            'failed',
2001
        ];
2002
2003
        if ($this->status_is($completedStatusList)) {
2004
            if (self::DEBUG > 2) {
2005
                error_log(
2006
                    'learnpath::is_done() - Item '.$this->get_id(
2007
                    ).' is complete',
2008
                    0
2009
                );
2010
            }
2011
2012
            return true;
2013
        } else {
2014
            if (self::DEBUG > 2) {
2015
                error_log(
2016
                    'learnpath::is_done() - Item '.$this->get_id(
2017
                    ).' is not complete',
2018
                    0
2019
                );
2020
            }
2021
2022
            return false;
2023
        }
2024
    }
2025
2026
    /**
2027
     * Tells if a restart is allowed (take it from $this->prevent_reinit and $this->status).
2028
     *
2029
     * @return int -1 if retaking the sco another time for credit is not allowed,
2030
     *             0 if it is not allowed but the item has to be finished
2031
     *             1 if it is allowed. Defaults to 1
2032
     */
2033
    public function isRestartAllowed()
2034
    {
2035
        if (self::DEBUG > 2) {
2036
            error_log('learnpathItem::isRestartAllowed()', 0);
2037
        }
2038
        $restart = 1;
2039
        $mystatus = $this->get_status(true);
2040
        if ($this->get_prevent_reinit() > 0) {
2041
            // If prevent_reinit == 1 (or more)
2042
            // If status is not attempted or incomplete, authorize retaking (of the same) anyway. Otherwise:
2043
            if ($mystatus != $this->possible_status[0] && $mystatus != $this->possible_status[1]) {
2044
                $restart = -1;
2045
            } else { //status incompleted or not attempted
2046
                $restart = 0;
2047
            }
2048
        } else {
2049
            if ($mystatus == $this->possible_status[0] || $mystatus == $this->possible_status[1]) {
2050
                $restart = -1;
2051
            }
2052
        }
2053
        if (self::DEBUG > 2) {
2054
            error_log(
2055
                'New LP - End of learnpathItem::isRestartAllowed() - Returning '.$restart,
2056
                0
2057
            );
2058
        }
2059
2060
        return $restart;
2061
    }
2062
2063
    /**
2064
     * Opens/launches the item. Initialises runtime values.
2065
     *
2066
     * @param bool $allow_new_attempt
2067
     *
2068
     * @return bool true on success, false on failure
2069
     */
2070
    public function open($allow_new_attempt = false)
2071
    {
2072
        if (self::DEBUG > 0) {
2073
            error_log('learnpathItem::open()', 0);
2074
        }
2075
        if ($this->prevent_reinit == 0) {
2076
            $this->current_score = 0;
2077
            $this->current_start_time = time();
2078
            // In this case, as we are opening the item, what is important to us
2079
            // is the database status, in order to know if this item has already
2080
            // been used in the past (rather than just loaded and modified by
2081
            // some javascript but not written in the database).
2082
            // If the database status is different from 'not attempted', we can
2083
            // consider this item has already been used, and as such we can
2084
            // open a new attempt. Otherwise, we'll just reuse the current
2085
            // attempt, which is generally created the first time the item is
2086
            // loaded (for example as part of the table of contents).
2087
            $stat = $this->get_status(true);
2088
            if ($allow_new_attempt && isset($stat) && ($stat != $this->possible_status[0])) {
2089
                $this->attempt_id = $this->attempt_id + 1; // Open a new attempt.
2090
            }
2091
            $this->status = $this->possible_status[1];
2092
        } else {
2093
            /*if ($this->current_start_time == 0) {
2094
                // Small exception for start time, to avoid amazing values.
2095
                $this->current_start_time = time();
2096
            }*/
2097
            // If we don't init start time here, the time is sometimes calculated from the last start time.
2098
            $this->current_start_time = time();
2099
        }
2100
    }
2101
2102
    /**
2103
     * Outputs the item contents.
2104
     *
2105
     * @return string HTML file (displayable in an <iframe>) or empty string if no path defined
2106
     */
2107
    public function output()
2108
    {
2109
        if (self::DEBUG > 0) {
2110
            error_log('learnpathItem::output()', 0);
2111
        }
2112
        if (!empty($this->path) and is_file($this->path)) {
2113
            $output = '';
2114
            $output .= file_get_contents($this->path);
2115
2116
            return $output;
2117
        }
2118
2119
        return '';
2120
    }
2121
2122
    /**
2123
     * Parses the prerequisites string with the AICC logic language.
2124
     *
2125
     * @param string $prereqs_string The prerequisites string as it figures in imsmanifest.xml
2126
     * @param array  $items          Array of items in the current learnpath object.
2127
     *                               Although we're in the learnpathItem object, it's necessary to have
2128
     *                               a list of all items to be able to check the current item's prerequisites
2129
     * @param array  $refs_list      list of references
2130
     *                               (the "ref" column in the lp_item table) that are strings used in the
2131
     *                               expression of prerequisites
2132
     * @param int    $user_id        The user ID. In some cases like Chamilo quizzes,
2133
     *                               it's necessary to have the user ID to query other tables (like the results of quizzes)
2134
     *
2135
     * @return bool True if the list of prerequisites given is entirely satisfied, false otherwise
2136
     */
2137
    public function parse_prereq($prereqs_string, $items, $refs_list, $user_id)
2138
    {
2139
        if (self::DEBUG > 0) {
2140
            error_log(
2141
                'learnpathItem::parse_prereq() for learnpath '.$this->lp_id.' with string '.$prereqs_string,
2142
                0
2143
            );
2144
        }
2145
2146
        $course_id = api_get_course_int_id();
2147
        $sessionId = api_get_session_id();
2148
2149
        // Deal with &, |, ~, =, <>, {}, ,, X*, () in reverse order.
2150
        $this->prereq_alert = '';
2151
        // First parse all parenthesis by using a sequential loop
2152
        //  (looking for less-inclusives first).
2153
        if ($prereqs_string == '_true_') {
2154
            return true;
2155
        }
2156
2157
        if ($prereqs_string == '_false_') {
2158
            if (empty($this->prereq_alert)) {
2159
                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2160
            }
2161
2162
            return false;
2163
        }
2164
2165
        while (strpos($prereqs_string, '(') !== false) {
2166
            // Remove any () set and replace with its value.
2167
            $matches = [];
2168
            $res = preg_match_all(
2169
                '/(\(([^\(\)]*)\))/',
2170
                $prereqs_string,
2171
                $matches
2172
            );
2173
            if ($res) {
2174
                foreach ($matches[2] as $id => $match) {
2175
                    $str_res = $this->parse_prereq(
2176
                        $match,
2177
                        $items,
2178
                        $refs_list,
2179
                        $user_id
2180
                    );
2181
                    if ($str_res) {
2182
                        $prereqs_string = str_replace(
2183
                            $matches[1][$id],
2184
                            '_true_',
2185
                            $prereqs_string
2186
                        );
2187
                    } else {
2188
                        $prereqs_string = str_replace(
2189
                            $matches[1][$id],
2190
                            '_false_',
2191
                            $prereqs_string
2192
                        );
2193
                    }
2194
                }
2195
            }
2196
        }
2197
2198
        // Parenthesis removed, now look for ORs as it is the lesser-priority
2199
        //  binary operator (= always uses one text operand).
2200
        if (strpos($prereqs_string, '|') === false) {
2201
            if (self::DEBUG > 1) {
2202
                error_log('New LP - Didnt find any OR, looking for AND', 0);
2203
            }
2204
            if (strpos($prereqs_string, '&') !== false) {
2205
                $list = explode('&', $prereqs_string);
2206
                if (count($list) > 1) {
2207
                    $andstatus = true;
2208
                    foreach ($list as $condition) {
2209
                        $andstatus = $andstatus && $this->parse_prereq(
2210
                            $condition,
2211
                            $items,
2212
                            $refs_list,
2213
                            $user_id
2214
                        );
2215
2216
                        if (!$andstatus) {
2217
                            if (self::DEBUG > 1) {
2218
                                error_log(
2219
                                    'New LP - One condition in AND was false, short-circuit',
2220
                                    0
2221
                                );
2222
                            }
2223
                            break;
2224
                        }
2225
                    }
2226
2227
                    if (empty($this->prereq_alert) && !$andstatus) {
2228
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2229
                    }
2230
2231
                    return $andstatus;
2232
                } else {
2233
                    if (isset($items[$refs_list[$list[0]]])) {
2234
                        $status = $items[$refs_list[$list[0]]]->get_status(true);
2235
                        $returnstatus = ($status == $this->possible_status[2]) || ($status == $this->possible_status[3]);
2236
                        if (empty($this->prereq_alert) && !$returnstatus) {
2237
                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2238
                        }
2239
2240
                        return $returnstatus;
2241
                    }
2242
                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2243
2244
                    return false;
2245
                }
2246
            } else {
2247
                // No ORs found, now look for ANDs.
2248
                if (self::DEBUG > 1) {
2249
                    error_log('New LP - Didnt find any AND, looking for =', 0);
2250
                }
2251
2252
                if (strpos($prereqs_string, '=') !== false) {
2253
                    if (self::DEBUG > 1) {
2254
                        error_log('New LP - Found =, looking into it', 0);
2255
                    }
2256
                    // We assume '=' signs only appear when there's nothing else around.
2257
                    $params = explode('=', $prereqs_string);
2258
                    if (count($params) == 2) {
2259
                        // Right number of operands.
2260
                        if (isset($items[$refs_list[$params[0]]])) {
2261
                            $status = $items[$refs_list[$params[0]]]->get_status(true);
2262
                            $returnstatus = $status == $params[1];
2263
                            if (empty($this->prereq_alert) && !$returnstatus) {
2264
                                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2265
                            }
2266
2267
                            return $returnstatus;
2268
                        }
2269
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2270
2271
                        return false;
2272
                    }
2273
                } else {
2274
                    // No ANDs found, look for <>
2275
                    if (self::DEBUG > 1) {
2276
                        error_log(
2277
                            'New LP - Didnt find any =, looking for <>',
2278
                            0
2279
                        );
2280
                    }
2281
2282
                    if (strpos($prereqs_string, '<>') !== false) {
2283
                        if (self::DEBUG > 1) {
2284
                            error_log('New LP - Found <>, looking into it', 0);
2285
                        }
2286
                        // We assume '<>' signs only appear when there's nothing else around.
2287
                        $params = explode('<>', $prereqs_string);
2288
                        if (count($params) == 2) {
2289
                            // Right number of operands.
2290
                            if (isset($items[$refs_list[$params[0]]])) {
2291
                                $status = $items[$refs_list[$params[0]]]->get_status(true);
2292
                                $returnstatus = $status != $params[1];
2293
                                if (empty($this->prereq_alert) && !$returnstatus) {
2294
                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2295
                                }
2296
2297
                                return $returnstatus;
2298
                            }
2299
                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2300
2301
                            return false;
2302
                        }
2303
                    } else {
2304
                        // No <> found, look for ~ (unary)
2305
                        if (self::DEBUG > 1) {
2306
                            error_log(
2307
                                'New LP - Didnt find any =, looking for ~',
2308
                                0
2309
                            );
2310
                        }
2311
                        // Only remains: ~ and X*{}
2312
                        if (strpos($prereqs_string, '~') !== false) {
2313
                            // Found NOT.
2314
                            if (self::DEBUG > 1) {
2315
                                error_log(
2316
                                    'New LP - Found ~, looking into it',
2317
                                    0
2318
                                );
2319
                            }
2320
                            $list = [];
2321
                            $myres = preg_match(
2322
                                '/~([^(\d+\*)\{]*)/',
2323
                                $prereqs_string,
2324
                                $list
2325
                            );
2326
                            if ($myres) {
2327
                                $returnstatus = !$this->parse_prereq(
2328
                                    $list[1],
2329
                                    $items,
2330
                                    $refs_list,
2331
                                    $user_id
2332
                                );
2333
                                if (empty($this->prereq_alert) && !$returnstatus) {
2334
                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2335
                                }
2336
2337
                                return $returnstatus;
2338
                            } else {
2339
                                // Strange...
2340
                                if (self::DEBUG > 1) {
2341
                                    error_log(
2342
                                        'New LP - Found ~ but strange string: '.$prereqs_string,
2343
                                        0
2344
                                    );
2345
                                }
2346
                            }
2347
                        } else {
2348
                            // Finally, look for sets/groups
2349
                            if (self::DEBUG > 1) {
2350
                                error_log(
2351
                                    'New LP - Didnt find any ~, looking for groups',
2352
                                    0
2353
                                );
2354
                            }
2355
                            // Only groups here.
2356
                            $groups = [];
2357
                            $groups_there = preg_match_all(
2358
                                '/((\d+\*)?\{([^\}]+)\}+)/',
2359
                                $prereqs_string,
2360
                                $groups
2361
                            );
2362
2363
                            if ($groups_there) {
2364
                                foreach ($groups[1] as $gr) {
2365
                                    // Only take the results that correspond to
2366
                                    //  the big brackets-enclosed condition.
2367
                                    if (self::DEBUG > 1) {
2368
                                        error_log(
2369
                                            'New LP - Dealing with group '.$gr,
2370
                                            0
2371
                                        );
2372
                                    }
2373
                                    $multi = [];
2374
                                    $mycond = false;
2375
                                    if (preg_match(
2376
                                        '/(\d+)\*\{([^\}]+)\}/',
2377
                                        $gr,
2378
                                        $multi
2379
                                    )
2380
                                    ) {
2381
                                        if (self::DEBUG > 1) {
2382
                                            error_log(
2383
                                                'New LP - Found multiplier '.$multi[0],
2384
                                                0
2385
                                            );
2386
                                        }
2387
                                        $count = $multi[1];
2388
                                        $list = explode(',', $multi[2]);
2389
                                        $mytrue = 0;
2390
                                        foreach ($list as $cond) {
2391
                                            if (isset($items[$refs_list[$cond]])) {
2392
                                                $status = $items[$refs_list[$cond]]->get_status(true);
2393
                                                if ($status == $this->possible_status[2] ||
2394
                                                    $status == $this->possible_status[3]
2395
                                                ) {
2396
                                                    $mytrue++;
2397
                                                    if (self::DEBUG > 1) {
2398
                                                        error_log(
2399
                                                            'New LP - Found true item, counting.. ('.($mytrue).')',
2400
                                                            0
2401
                                                        );
2402
                                                    }
2403
                                                }
2404
                                            } else {
2405
                                                if (self::DEBUG > 1) {
2406
                                                    error_log(
2407
                                                        'New LP - item '.$cond.' does not exist in items list',
2408
                                                        0
2409
                                                    );
2410
                                                }
2411
                                            }
2412
                                        }
2413
                                        if ($mytrue >= $count) {
2414
                                            if (self::DEBUG > 1) {
2415
                                                error_log(
2416
                                                    'New LP - Got enough true results, return true',
2417
                                                    0
2418
                                                );
2419
                                            }
2420
                                            $mycond = true;
2421
                                        } else {
2422
                                            if (self::DEBUG > 1) {
2423
                                                error_log(
2424
                                                    'New LP - Not enough true results',
2425
                                                    0
2426
                                                );
2427
                                            }
2428
                                        }
2429
                                    } else {
2430
                                        if (self::DEBUG > 1) {
2431
                                            error_log(
2432
                                                'New LP - No multiplier',
2433
                                                0
2434
                                            );
2435
                                        }
2436
                                        $list = explode(',', $gr);
2437
                                        $mycond = true;
2438
                                        foreach ($list as $cond) {
2439
                                            if (isset($items[$refs_list[$cond]])) {
2440
                                                $status = $items[$refs_list[$cond]]->get_status(true);
2441
                                                if ($status == $this->possible_status[2] ||
2442
                                                    $status == $this->possible_status[3]
2443
                                                ) {
2444
                                                    $mycond = true;
2445
                                                    if (self::DEBUG > 1) {
2446
                                                        error_log(
2447
                                                            'New LP - Found true item',
2448
                                                            0
2449
                                                        );
2450
                                                    }
2451
                                                } else {
2452
                                                    if (self::DEBUG > 1) {
2453
                                                        error_log(
2454
                                                            'New LP - '.
2455
                                                            ' Found false item, the set is not true, return false',
2456
                                                            0
2457
                                                        );
2458
                                                    }
2459
                                                    $mycond = false;
2460
                                                    break;
2461
                                                }
2462
                                            } else {
2463
                                                if (self::DEBUG > 1) {
2464
                                                    error_log(
2465
                                                        'New LP - item '.$cond.' does not exist in items list',
2466
                                                        0
2467
                                                    );
2468
                                                }
2469
                                                if (self::DEBUG > 1) {
2470
                                                    error_log(
2471
                                                        'New LP - Found false item, the set is not true, return false',
2472
                                                        0
2473
                                                    );
2474
                                                }
2475
                                                $mycond = false;
2476
                                                break;
2477
                                            }
2478
                                        }
2479
                                    }
2480
                                    if (!$mycond && empty($this->prereq_alert)) {
2481
                                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2482
                                    }
2483
2484
                                    return $mycond;
2485
                                }
2486
                            } else {
2487
                                // Nothing found there either. Now return the
2488
                                // value of the corresponding resource completion status.
2489
                                if (self::DEBUG > 1) {
2490
                                    error_log(
2491
                                        'New LP - Didnt find any group, returning value for '.$prereqs_string,
2492
                                        0
2493
                                    );
2494
                                }
2495
2496
                                if (isset($refs_list[$prereqs_string]) &&
2497
                                    isset($items[$refs_list[$prereqs_string]])
2498
                                ) {
2499
                                    /** @var learnpathItem $itemToCheck */
2500
                                    $itemToCheck = $items[$refs_list[$prereqs_string]];
2501
2502
                                    if ($itemToCheck->type === 'quiz') {
2503
                                        // 1. Checking the status in current items.
2504
                                        $status = $itemToCheck->get_status(true);
2505
                                        $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2506
2507
                                        if (!$returnstatus) {
2508
                                            $explanation = sprintf(
2509
                                                get_lang('ItemXBlocksThisElement'),
2510
                                                $itemToCheck->get_title()
2511
                                            );
2512
                                            $this->prereq_alert = $explanation;
2513
                                            if (self::DEBUG > 1) {
2514
                                                error_log(
2515
                                                    'New LP - Prerequisite '.$prereqs_string.' not complete',
2516
                                                    0
2517
                                                );
2518
                                            }
2519
                                        } else {
2520
                                            if (self::DEBUG > 1) {
2521
                                                error_log(
2522
                                                    'New LP - Prerequisite '.$prereqs_string.' complete',
2523
                                                    0
2524
                                                );
2525
                                            }
2526
                                        }
2527
2528
                                        // For one and first attempt.
2529
                                        if ($this->prevent_reinit == 1) {
2530
                                            // 2. If is completed we check the results in the DB of the quiz.
2531
                                            if ($returnstatus) {
2532
                                                //AND origin_lp_item_id = '.$user_id.'
2533
                                                $sql = 'SELECT score, max_score
2534
                                                        FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
2535
                                                        WHERE
2536
                                                            exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
2537
                                                            exe_user_id = '.$user_id.' AND
2538
                                                            orig_lp_id = '.$this->lp_id.' AND
2539
                                                            orig_lp_item_id = '.$prereqs_string.' AND
2540
                                                            status <> "incomplete" AND
2541
                                                            c_id = '.$course_id.'
2542
                                                        ORDER BY exe_date DESC
2543
                                                        LIMIT 0, 1';
2544
                                                $rs_quiz = Database::query($sql);
2545
                                                if ($quiz = Database::fetch_array($rs_quiz)) {
2546
                                                    /** @var learnpathItem $myItemToCheck */
2547
                                                    $myItemToCheck = $items[$refs_list[$this->get_id()]];
2548
                                                    $minScore = $myItemToCheck->getPrerequisiteMinScore();
2549
                                                    $maxScore = $myItemToCheck->getPrerequisiteMaxScore();
2550
2551
                                                    if (empty($minScore)) {
2552
                                                        // Try with mastery_score
2553
                                                        $masteryScoreAsMin = $myItemToCheck->get_mastery_score();
2554
                                                        if (!empty($masteryScoreAsMin)) {
2555
                                                            $minScore = $masteryScoreAsMin;
2556
                                                        }
2557
                                                    }
2558
2559
                                                    if (isset($minScore) && isset($minScore)) {
2560
                                                        // Taking min/max prerequisites values see BT#5776
2561
                                                        if ($quiz['score'] >= $minScore &&
2562
                                                            $quiz['score'] <= $maxScore
2563
                                                        ) {
2564
                                                            $returnstatus = true;
2565
                                                        } else {
2566
                                                            $explanation = sprintf(
2567
                                                                get_lang('YourResultAtXBlocksThisElement'),
2568
                                                                $itemToCheck->get_title()
2569
                                                            );
2570
                                                            $this->prereq_alert = $explanation;
2571
                                                            $returnstatus = false;
2572
                                                        }
2573
                                                    } else {
2574
                                                        // Classic way
2575
                                                        if ($quiz['score'] >=
2576
                                                            $items[$refs_list[$prereqs_string]]->get_mastery_score()
2577
                                                        ) {
2578
                                                            $returnstatus = true;
2579
                                                        } else {
2580
                                                            $explanation = sprintf(
2581
                                                                get_lang('YourResultAtXBlocksThisElement'),
2582
                                                                $itemToCheck->get_title()
2583
                                                            );
2584
                                                            $this->prereq_alert = $explanation;
2585
                                                            $returnstatus = false;
2586
                                                        }
2587
                                                    }
2588
                                                } else {
2589
                                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2590
                                                    $returnstatus = false;
2591
                                                }
2592
                                            }
2593
                                        } else {
2594
                                            // 3. For multiple attempts we check that there are minimum 1 item completed
2595
                                            // Checking in the database.
2596
                                            $sql = 'SELECT score, max_score
2597
                                                    FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
2598
                                                    WHERE
2599
                                                        c_id = '.$course_id.' AND 
2600
                                                        exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
2601
                                                        exe_user_id = '.$user_id.' AND
2602
                                                        orig_lp_id = '.$this->lp_id.' AND
2603
                                                        orig_lp_item_id = '.$prereqs_string.' ';
2604
2605
                                            $rs_quiz = Database::query($sql);
2606
                                            if (Database::num_rows($rs_quiz) > 0) {
2607
                                                while ($quiz = Database::fetch_array($rs_quiz)) {
2608
                                                    /** @var learnpathItem $myItemToCheck */
2609
                                                    $myItemToCheck = $items[$refs_list[$this->get_id()]];
2610
                                                    $minScore = $myItemToCheck->getPrerequisiteMinScore();
2611
                                                    $maxScore = $myItemToCheck->getPrerequisiteMaxScore();
2612
2613
                                                    if (empty($minScore)) {
2614
                                                        // Try with mastery_score
2615
                                                        $masteryScoreAsMin = $myItemToCheck->get_mastery_score();
2616
                                                        if (!empty($masteryScoreAsMin)) {
2617
                                                            $minScore = $masteryScoreAsMin;
2618
                                                        }
2619
                                                    }
2620
2621
                                                    if (isset($minScore) && isset($minScore)) {
2622
                                                        // Taking min/max prerequisites values see BT#5776
2623
                                                        if ($quiz['score'] >= $minScore && $quiz['score'] <= $maxScore) {
2624
                                                            $returnstatus = true;
2625
                                                            break;
2626
                                                        } else {
2627
                                                            $explanation = sprintf(
2628
                                                                get_lang('YourResultAtXBlocksThisElement'),
2629
                                                                $itemToCheck->get_title()
2630
                                                            );
2631
                                                            $this->prereq_alert = $explanation;
2632
                                                            $returnstatus = false;
2633
                                                        }
2634
                                                    } else {
2635
                                                        if ($quiz['score'] >=
2636
                                                            $items[$refs_list[$prereqs_string]]->get_mastery_score()
2637
                                                        ) {
2638
                                                            $returnstatus = true;
2639
                                                            break;
2640
                                                        } else {
2641
                                                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2642
                                                            $returnstatus = false;
2643
                                                        }
2644
                                                    }
2645
                                                }
2646
                                            } else {
2647
                                                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2648
                                                $returnstatus = false;
2649
                                            }
2650
                                        }
2651
2652
                                        return $returnstatus;
2653
                                    } elseif ($itemToCheck->type === 'student_publication') {
2654
                                        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2655
                                        $workId = $items[$refs_list[$prereqs_string]]->path;
2656
                                        $count = get_work_count_by_student($user_id, $workId);
2657
                                        if ($count >= 1) {
2658
                                            $returnstatus = true;
2659
                                        } else {
2660
                                            $returnstatus = false;
2661
                                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2662
                                            if (self::DEBUG > 1) {
2663
                                                error_log(
2664
                                                    'Student pub, prereq'.$prereqs_string.' not completed',
2665
                                                    0
2666
                                                );
2667
                                            }
2668
                                        }
2669
2670
                                        return $returnstatus;
2671
                                    } else {
2672
                                        $status = $itemToCheck->get_status(false);
2673
                                        $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2674
                                        if (!$returnstatus) {
2675
                                            $explanation = sprintf(
2676
                                                get_lang('ItemXBlocksThisElement'),
2677
                                                $itemToCheck->get_title()
2678
                                            );
2679
                                            $this->prereq_alert = $explanation;
2680
                                            if (self::DEBUG > 1) {
2681
                                                error_log(
2682
                                                    'New LP - Prerequisite '.$prereqs_string.' not complete',
2683
                                                    0
2684
                                                );
2685
                                            }
2686
                                        } else {
2687
                                            if (self::DEBUG > 1) {
2688
                                                error_log(
2689
                                                    'New LP - Prerequisite '.$prereqs_string.' complete',
2690
                                                    0
2691
                                                );
2692
                                            }
2693
                                        }
2694
2695
                                        if ($returnstatus && $this->prevent_reinit == 1) {
2696
                                            // I would prefer check in the database.
2697
                                            $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
2698
                                            $lp_view = Database::get_course_table(TABLE_LP_VIEW);
2699
2700
                                            $sql = 'SELECT iid FROM '.$lp_view.'
2701
                                                    WHERE
2702
                                                        c_id = '.$course_id.' AND
2703
                                                        user_id = '.$user_id.'  AND
2704
                                                        lp_id = '.$this->lp_id.' AND
2705
                                                        session_id = '.$sessionId.'
2706
                                                    LIMIT 0, 1';
2707
                                            $rs_lp = Database::query($sql);
2708
                                            if (Database::num_rows($rs_lp)) {
2709
                                                $lp_id = Database::fetch_row($rs_lp);
2710
                                                $my_lp_id = $lp_id[0];
2711
2712
                                                $sql = 'SELECT status FROM '.$lp_item_view.'
2713
                                                        WHERE
2714
                                                            c_id = '.$course_id.' AND
2715
                                                            lp_view_id = '.$my_lp_id.' AND
2716
                                                            lp_item_id = '.$refs_list[$prereqs_string].'
2717
                                                        LIMIT 0, 1';
2718
                                                $rs_lp = Database::query($sql);
2719
                                                $status_array = Database::fetch_row($rs_lp);
2720
                                                $status = $status_array[0];
2721
2722
                                                $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
2723
                                                if (!$returnstatus && empty($this->prereq_alert)) {
2724
                                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2725
                                                }
2726
                                                if (!$returnstatus) {
2727
                                                    if (self::DEBUG > 1) {
2728
                                                        error_log(
2729
                                                            'New LP - Prerequisite '.$prereqs_string.' not complete'
2730
                                                        );
2731
                                                    }
2732
                                                } else {
2733
                                                    if (self::DEBUG > 1) {
2734
                                                        error_log('New LP - Prerequisite '.$prereqs_string.' complete');
2735
                                                    }
2736
                                                }
2737
2738
                                                return $returnstatus;
2739
                                            }
2740
                                        } else {
2741
                                            return $returnstatus;
2742
                                        }
2743
                                    }
2744
                                } else {
2745
                                    if (self::DEBUG > 1) {
2746
                                        error_log(
2747
                                            'New LP - Could not find '.$prereqs_string.' in '.print_r(
2748
                                                $refs_list,
2749
                                                true
2750
                                            ),
2751
                                            0
2752
                                        );
2753
                                    }
2754
                                }
2755
                            }
2756
                        }
2757
                    }
2758
                }
2759
            }
2760
        } else {
2761
            $list = explode("\|", $prereqs_string);
2762
            if (count($list) > 1) {
2763
                if (self::DEBUG > 1) {
2764
                    error_log('New LP - Found OR, looking into it', 0);
2765
                }
2766
                $orstatus = false;
2767
                foreach ($list as $condition) {
2768
                    if (self::DEBUG > 1) {
2769
                        error_log(
2770
                            'New LP - Found OR, adding it ('.$condition.')',
2771
                            0
2772
                        );
2773
                    }
2774
                    $orstatus = $orstatus || $this->parse_prereq(
2775
                        $condition,
2776
                        $items,
2777
                        $refs_list,
2778
                        $user_id
2779
                    );
2780
                    if ($orstatus) {
2781
                        // Shortcircuit OR.
2782
                        if (self::DEBUG > 1) {
2783
                            error_log(
2784
                                'New LP - One condition in OR was true, short-circuit',
2785
                                0
2786
                            );
2787
                        }
2788
                        break;
2789
                    }
2790
                }
2791
                if (!$orstatus && empty($this->prereq_alert)) {
2792
                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2793
                }
2794
2795
                return $orstatus;
2796
            } else {
2797
                if (self::DEBUG > 1) {
2798
                    error_log(
2799
                        'New LP - OR was found but only one elem present !?',
2800
                        0
2801
                    );
2802
                }
2803
                if (isset($items[$refs_list[$list[0]]])) {
2804
                    $status = $items[$refs_list[$list[0]]]->get_status(true);
2805
                    $returnstatus = $status == 'completed' || $status == 'passed';
2806
                    if (!$returnstatus && empty($this->prereq_alert)) {
2807
                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2808
                    }
2809
2810
                    return $returnstatus;
2811
                }
2812
            }
2813
        }
2814
        if (empty($this->prereq_alert)) {
2815
            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
2816
        }
2817
2818
        if (self::DEBUG > 1) {
2819
            error_log(
2820
                'New LP - End of parse_prereq. Error code is now '.$this->prereq_alert,
2821
                0
2822
            );
2823
        }
2824
2825
        return false;
2826
    }
2827
2828
    /**
2829
     * Reinits all local values as the learnpath is restarted.
2830
     *
2831
     * @return bool True on success, false otherwise
2832
     */
2833
    public function restart()
2834
    {
2835
        if (self::DEBUG > 0) {
2836
            error_log('learnpathItem::restart()', 0);
2837
        }
2838
        $seriousGame = $this->get_seriousgame_mode();
2839
        //For serious game  : We reuse same attempt_id
2840
        if ($seriousGame == 1 && $this->type == 'sco') {
2841
            // If this is a sco, Chamilo can't update the time without an
2842
            //  explicit scorm call
2843
            $this->current_start_time = 0;
2844
            $this->current_stop_time = 0; //Those 0 value have this effect
2845
            $this->last_scorm_session_time = 0;
2846
            $this->save();
2847
2848
            return true;
2849
        }
2850
        $this->save();
2851
2852
        $allowed = $this->isRestartAllowed();
2853
        if ($allowed === -1) {
2854
            // Nothing allowed, do nothing.
2855
        } elseif ($allowed === 1) {
2856
            // Restart as new attempt is allowed, record a new attempt.
2857
            $this->attempt_id = $this->attempt_id + 1; // Simply reuse the previous attempt_id.
2858
            $this->current_score = 0;
2859
            $this->current_start_time = 0;
2860
            $this->current_stop_time = 0;
2861
            $this->current_data = '';
2862
            $this->status = $this->possible_status[0];
2863
            $this->interactions_count = 0;
2864
            $this->interactions = [];
2865
            $this->objectives_count = 0;
2866
            $this->objectives = [];
2867
            $this->lesson_location = '';
2868
            if ($this->type != TOOL_QUIZ) {
2869
                $this->write_to_db();
2870
            }
2871
        } else {
2872
            // Restart current element is allowed (because it's not finished yet),
2873
            // reinit current.
2874
            //$this->current_score = 0;
2875
            $this->current_start_time = 0;
2876
            $this->current_stop_time = 0;
2877
            $this->interactions_count = $this->get_interactions_count(true);
2878
        }
2879
2880
        return true;
2881
    }
2882
2883
    /**
2884
     * Saves data in the database.
2885
     *
2886
     * @param bool $from_outside     Save from URL params (1) or from object attributes (0)
2887
     * @param bool $prereqs_complete The results of a check on prerequisites for this item.
2888
     *                               True if prerequisites are completed, false otherwise. Defaults to false. Only used if not sco or au
2889
     *
2890
     * @return bool True on success, false on failure
2891
     */
2892
    public function save($from_outside = true, $prereqs_complete = false)
2893
    {
2894
        $debug = self::DEBUG;
2895
        if ($debug) {
2896
            error_log('learnpathItem::save()', 0);
2897
        }
2898
        // First check if parameters passed via GET can be saved here
2899
        // in case it's a SCORM, we should get:
2900
        if ($this->type == 'sco' || $this->type == 'au') {
2901
            $status = $this->get_status(true);
2902
            if ($this->prevent_reinit == 1 &&
2903
                $status != $this->possible_status[0] && // not attempted
2904
                $status != $this->possible_status[1]    //incomplete
2905
            ) {
2906
                if ($debug) {
2907
                    error_log(
2908
                        'learnpathItem::save() - save reinit blocked by setting',
2909
                        0
2910
                    );
2911
                }
2912
                // Do nothing because the status has already been set. Don't allow it to change.
2913
                // TODO: Check there isn't a special circumstance where this should be saved.
2914
            } else {
2915
                if ($debug) {
2916
                    error_log(
2917
                        'learnpathItem::save() - SCORM save request received',
2918
                        0
2919
                    );
2920
                }
2921
2922
                // Get all new settings from the URL
2923
                if ($from_outside) {
2924
                    if ($debug) {
2925
                        error_log(
2926
                            'learnpathItem::save() - Getting item data from outside',
2927
                            0
2928
                        );
2929
                    }
2930
                    foreach ($_GET as $param => $value) {
2931
                        switch ($param) {
2932
                            case 'score':
2933
                                $this->set_score($value);
2934
                                if ($debug) {
2935
                                    error_log(
2936
                                        'learnpathItem::save() - setting score to '.$value,
2937
                                        0
2938
                                    );
2939
                                }
2940
                                break;
2941
                            case 'max':
2942
                                $this->set_max_score($value);
2943
                                if ($debug) {
2944
                                    error_log(
2945
                                        'learnpathItem::save() - setting view_max_score to '.$value,
2946
                                        0
2947
                                    );
2948
                                }
2949
                                break;
2950
                            case 'min':
2951
                                $this->min_score = $value;
2952
                                if ($debug) {
2953
                                    error_log(
2954
                                        'learnpathItem::save() - setting min_score to '.$value,
2955
                                        0
2956
                                    );
2957
                                }
2958
                                break;
2959
                            case 'lesson_status':
2960
                                if (!empty($value)) {
2961
                                    $this->set_status($value);
2962
                                    if ($debug) {
2963
                                        error_log(
2964
                                            'learnpathItem::save() - setting status to '.$value,
2965
                                            0
2966
                                        );
2967
                                    }
2968
                                }
2969
                                break;
2970
                            case 'time':
2971
                                $this->set_time($value);
2972
                                if ($debug) {
2973
                                    error_log(
2974
                                        'learnpathItem::save() - setting time to '.$value,
2975
                                        0
2976
                                    );
2977
                                }
2978
                                break;
2979
                            case 'suspend_data':
2980
                                $this->current_data = $value;
2981
                                if ($debug) {
2982
                                    error_log(
2983
                                        'learnpathItem::save() - setting suspend_data to '.$value,
2984
                                        0
2985
                                    );
2986
                                }
2987
                                break;
2988
                            case 'lesson_location':
2989
                                $this->set_lesson_location($value);
2990
                                if ($debug) {
2991
                                    error_log(
2992
                                        'learnpathItem::save() - setting lesson_location to '.$value,
2993
                                        0
2994
                                    );
2995
                                }
2996
                                break;
2997
                            case 'core_exit':
2998
                                $this->set_core_exit($value);
2999
                                if ($debug) {
3000
                                    error_log(
3001
                                        'learnpathItem::save() - setting core_exit to '.$value,
3002
                                        0
3003
                                    );
3004
                                }
3005
                                break;
3006
                            case 'interactions':
3007
                                break;
3008
                            case 'objectives':
3009
                                break;
3010
                            default:
3011
                                // Ignore.
3012
                                break;
3013
                        }
3014
                    }
3015
                } else {
3016
                    if ($debug) {
3017
                        error_log(
3018
                            'learnpathItem::save() - Using inside item status',
3019
                            0
3020
                        );
3021
                    }
3022
                    // Do nothing, just let the local attributes be used.
3023
                }
3024
            }
3025
        } else {
3026
            // If not SCO, such messages should not be expected.
3027
            $type = strtolower($this->type);
3028
            if ($debug) {
3029
                error_log("type: $type");
3030
            }
3031
            switch ($type) {
3032
                case 'asset':
3033
                    if ($prereqs_complete) {
3034
                        $this->set_status($this->possible_status[2]);
3035
                    }
3036
                    break;
3037
                case TOOL_HOTPOTATOES:
3038
                    break;
3039
                case TOOL_QUIZ:
3040
                    return false;
3041
                    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...
3042
                default:
3043
                    // For now, everything that is not sco and not asset is set to
3044
                    // completed when saved.
3045
                    if ($prereqs_complete) {
3046
                        $this->set_status($this->possible_status[2]);
3047
                    }
3048
                    break;
3049
            }
3050
        }
3051
3052
        if ($debug) {
3053
            error_log(
3054
                'New LP - End of learnpathItem::save() - Calling write_to_db()',
3055
                0
3056
            );
3057
        }
3058
3059
        return $this->write_to_db();
3060
    }
3061
3062
    /**
3063
     * Sets the number of attempt_id to a given value.
3064
     *
3065
     * @param int $num The given value to set attempt_id to
3066
     *
3067
     * @return bool TRUE on success, FALSE otherwise
3068
     */
3069
    public function set_attempt_id($num)
3070
    {
3071
        if (self::DEBUG > 0) {
3072
            error_log('learnpathItem::set_attempt_id()', 0);
3073
        }
3074
        if ($num == strval(intval($num)) && $num >= 0) {
3075
            $this->attempt_id = $num;
3076
3077
            return true;
3078
        }
3079
3080
        return false;
3081
    }
3082
3083
    /**
3084
     * Sets the core_exit value to the one given.
3085
     *
3086
     * @return bool $value  True (always)
3087
     */
3088
    public function set_core_exit($value)
3089
    {
3090
        switch ($value) {
3091
            case '':
3092
                $this->core_exit = '';
3093
                break;
3094
            case 'suspend':
3095
                $this->core_exit = 'suspend';
3096
                break;
3097
            default:
3098
                $this->core_exit = 'none';
3099
                break;
3100
        }
3101
3102
        return true;
3103
    }
3104
3105
    /**
3106
     * Sets the item's description.
3107
     *
3108
     * @param string $string Description
3109
     */
3110
    public function set_description($string = '')
3111
    {
3112
        if (self::DEBUG > 0) {
3113
            error_log('learnpathItem::set_description()', 0);
3114
        }
3115
        if (!empty($string)) {
3116
            $this->description = $string;
3117
        }
3118
    }
3119
3120
    /**
3121
     * Sets the lesson_location value.
3122
     *
3123
     * @param string $location lesson_location as provided by the SCO
3124
     *
3125
     * @return bool True on success, false otherwise
3126
     */
3127
    public function set_lesson_location($location)
3128
    {
3129
        if (self::DEBUG > 0) {
3130
            error_log('learnpathItem::set_lesson_location()', 0);
3131
        }
3132
        if (isset($location)) {
3133
            $this->lesson_location = $location;
3134
3135
            return true;
3136
        }
3137
3138
        return false;
3139
    }
3140
3141
    /**
3142
     * Sets the item's depth level in the LP tree (0 is at root).
3143
     *
3144
     * @param int $int Level
3145
     */
3146
    public function set_level($int = 0)
3147
    {
3148
        if (self::DEBUG > 0) {
3149
            error_log('learnpathItem::set_level('.$int.')', 0);
3150
        }
3151
        if (!empty($int) && $int == strval(intval($int))) {
3152
            $this->level = $int;
3153
        }
3154
    }
3155
3156
    /**
3157
     * Sets the lp_view id this item view is registered to.
3158
     *
3159
     * @param int $lp_view_id lp_view DB ID
3160
     * @param int $course_id
3161
     *
3162
     * @return bool
3163
     *
3164
     * @todo //todo insert into lp_item_view if lp_view not exists
3165
     */
3166
    public function set_lp_view($lp_view_id, $course_id = null)
3167
    {
3168
        $lp_view_id = intval($lp_view_id);
3169
3170
        if (empty($course_id)) {
3171
            $course_id = api_get_course_int_id();
3172
        } else {
3173
            $course_id = intval($course_id);
3174
        }
3175
3176
        $lpItemId = $this->get_id();
3177
3178
        if (empty($lpItemId)) {
3179
            if (self::DEBUG > 0) {
3180
                error_log(
3181
                    'learnpathItem::set_lp_view('.$lp_view_id.') $lpItemId is empty',
3182
                    0
3183
                );
3184
            }
3185
3186
            return false;
3187
        }
3188
3189
        if (empty($lp_view_id)) {
3190
            if (self::DEBUG > 0) {
3191
                error_log(
3192
                    'learnpathItem::set_lp_view('.$lp_view_id.') $lp_view_id is empty',
3193
                    0
3194
                );
3195
            }
3196
3197
            return false;
3198
        }
3199
3200
        if (self::DEBUG > 0) {
3201
            error_log('learnpathItem::set_lp_view('.$lp_view_id.')', 0);
3202
        }
3203
3204
        $this->view_id = $lp_view_id;
3205
3206
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3207
        // Get the lp_item_view with the highest view_count.
3208
        $sql = "SELECT * FROM $item_view_table
3209
                WHERE
3210
                    c_id = $course_id AND
3211
                    lp_item_id = ".$lpItemId." AND
3212
                    lp_view_id = ".$lp_view_id."
3213
                ORDER BY view_count DESC";
3214
3215
        if (self::DEBUG > 2) {
3216
            error_log(
3217
                'learnpathItem::set_lp_view() - Querying lp_item_view: '.$sql,
3218
                0
3219
            );
3220
        }
3221
        $res = Database::query($sql);
3222
        if (Database::num_rows($res) > 0) {
3223
            $row = Database::fetch_array($res);
3224
            $this->db_item_view_id = $row['iid'];
3225
            $this->attempt_id = $row['view_count'];
3226
            $this->current_score = $row['score'];
3227
            $this->current_data = $row['suspend_data'];
3228
            $this->view_max_score = $row['max_score'];
3229
            $this->status = $row['status'];
3230
            $this->current_start_time = $row['start_time'];
3231
            $this->current_stop_time = $this->current_start_time + $row['total_time'];
3232
            $this->lesson_location = $row['lesson_location'];
3233
            $this->core_exit = $row['core_exit'];
3234
3235
            if (self::DEBUG > 2) {
3236
                error_log(
3237
                    'learnpathItem::set_lp_view() - Updated item object with database values',
3238
                    0
3239
                );
3240
            }
3241
3242
            // Now get the number of interactions for this little guy.
3243
            $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
3244
            $sql = "SELECT * FROM $table
3245
                    WHERE
3246
                        c_id = $course_id AND
3247
                        lp_iv_id = '".$this->db_item_view_id."'";
3248
3249
            $res = Database::query($sql);
3250
            if ($res !== false) {
3251
                $this->interactions_count = Database::num_rows($res);
3252
            } else {
3253
                $this->interactions_count = 0;
3254
            }
3255
            // Now get the number of objectives for this little guy.
3256
            $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
3257
            $sql = "SELECT * FROM $table
3258
                    WHERE
3259
                        c_id = $course_id AND
3260
                        lp_iv_id = '".$this->db_item_view_id."'";
3261
3262
            $res = Database::query($sql);
3263
            if ($res !== false) {
3264
                $this->objectives_count = Database::num_rows($res);
3265
            } else {
3266
                $this->objectives_count = 0;
3267
            }
3268
        }
3269
3270
        // End
3271
        if (self::DEBUG > 2) {
3272
            error_log('New LP - End of learnpathItem::set_lp_view()', 0);
3273
        }
3274
3275
        return true;
3276
    }
3277
3278
    /**
3279
     * Sets the path.
3280
     *
3281
     * @param string $string Path
3282
     */
3283
    public function set_path($string = '')
3284
    {
3285
        if (self::DEBUG > 0) {
3286
            error_log('learnpathItem::set_path()', 0);
3287
        }
3288
        if (!empty($string)) {
3289
            $this->path = $string;
3290
        }
3291
    }
3292
3293
    /**
3294
     * Sets the prevent_reinit attribute.
3295
     * This is based on the LP value and is set at creation time for
3296
     * each learnpathItem. It is a (bad?) way of avoiding
3297
     * a reference to the LP when saving an item.
3298
     *
3299
     * @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...
3300
     * saving freshened values (new "not attempted" status etc)
3301
     */
3302
    public function set_prevent_reinit($prevent)
3303
    {
3304
        if (self::DEBUG > 0) {
3305
            error_log('learnpathItem::set_prevent_reinit()', 0);
3306
        }
3307
        if ($prevent) {
3308
            $this->prevent_reinit = 1;
3309
        } else {
3310
            $this->prevent_reinit = 0;
3311
        }
3312
    }
3313
3314
    /**
3315
     * Sets the score value. If the mastery_score is set and the score reaches
3316
     * it, then set the status to 'passed'.
3317
     *
3318
     * @param float $score Score
3319
     *
3320
     * @return bool True on success, false otherwise
3321
     */
3322
    public function set_score($score)
3323
    {
3324
        $debug = self::DEBUG;
3325
        if ($debug > 0) {
3326
            error_log('learnpathItem::set_score('.$score.')', 0);
3327
        }
3328
        if (($this->max_score <= 0 || $score <= $this->max_score) && ($score >= $this->min_score)) {
3329
            $this->current_score = $score;
3330
            $masteryScore = $this->get_mastery_score();
3331
            $current_status = $this->get_status(false);
3332
3333
            // Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
3334
            if ($masteryScore == -1) {
3335
                $masteryScore = $this->max_score;
3336
            }
3337
3338
            if ($debug > 0) {
3339
                error_log('get_mastery_score: '.$masteryScore);
3340
                error_log('current_status: '.$current_status);
3341
                error_log('current score : '.$this->current_score);
3342
            }
3343
3344
            // If mastery_score is set AND the current score reaches the mastery
3345
            //  score AND the current status is different from 'completed', then
3346
            //  set it to 'passed'.
3347
            /*
3348
            if ($master != -1 && $this->current_score >= $master && $current_status != $this->possible_status[2]) {
3349
                if ($debug > 0) error_log('Status changed to: '.$this->possible_status[3]);
3350
                $this->set_status($this->possible_status[3]); //passed
3351
            } elseif ($master != -1 && $this->current_score < $master) {
3352
                if ($debug > 0) error_log('Status changed to: '.$this->possible_status[4]);
3353
                $this->set_status($this->possible_status[4]); //failed
3354
            }*/
3355
            return true;
3356
        }
3357
3358
        return false;
3359
    }
3360
3361
    /**
3362
     * Sets the maximum score for this item.
3363
     *
3364
     * @param int $score Maximum score - must be a decimal or an empty string
3365
     *
3366
     * @return bool True on success, false on error
3367
     */
3368
    public function set_max_score($score)
3369
    {
3370
        if (self::DEBUG > 0) {
3371
            error_log('learnpathItem::set_max_score('.$score.')', 0);
3372
        }
3373
        if (is_int($score) || $score == '') {
3374
            $this->view_max_score = $score;
3375
            if (self::DEBUG > 1) {
3376
                error_log(
3377
                    'learnpathItem::set_max_score() - '.
3378
                    'Updated object score of item '.$this->db_id.
3379
                    ' to '.$this->view_max_score,
3380
                    0
3381
                );
3382
            }
3383
3384
            return true;
3385
        }
3386
3387
        return false;
3388
    }
3389
3390
    /**
3391
     * Sets the status for this item.
3392
     *
3393
     * @param string $status Status - must be one of the values defined in $this->possible_status
3394
     *                       (this affects the status setting)
3395
     *
3396
     * @return bool True on success, false on error
3397
     */
3398
    public function set_status($status)
3399
    {
3400
        if (self::DEBUG > 0) {
3401
            error_log('learnpathItem::set_status('.$status.')', 0);
3402
        }
3403
3404
        $found = false;
3405
        foreach ($this->possible_status as $possible) {
3406
            if (preg_match('/^'.$possible.'$/i', $status)) {
3407
                $found = true;
3408
            }
3409
        }
3410
3411
        if ($found) {
3412
            $this->status = $status;
3413
            if (self::DEBUG > 1) {
3414
                error_log(
3415
                    'learnpathItem::set_status() - '.
3416
                        'Updated object status of item '.$this->db_id.
3417
                        ' to '.$this->status,
3418
                    0
3419
                );
3420
            }
3421
3422
            return true;
3423
        }
3424
3425
        $this->status = $this->possible_status[0];
3426
3427
        return false;
3428
    }
3429
3430
    /**
3431
     * Set the (indexing) terms for this learnpath item.
3432
     *
3433
     * @param string $terms Terms, as a comma-split list
3434
     *
3435
     * @return bool Always return true
3436
     */
3437
    public function set_terms($terms)
3438
    {
3439
        global $charset;
3440
        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
3441
        $a_terms = preg_split('/,/', $terms);
3442
        $i_terms = preg_split('/,/', $this->get_terms());
3443
        foreach ($i_terms as $term) {
3444
            if (!in_array($term, $a_terms)) {
3445
                array_push($a_terms, $term);
3446
            }
3447
        }
3448
        $new_terms = $a_terms;
3449
        $new_terms_string = implode(',', $new_terms);
3450
3451
        // TODO: Validate csv string.
3452
        $terms = Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset));
3453
        $sql = "UPDATE $lp_item
3454
                SET terms = '$terms'
3455
                WHERE iid=".$this->get_id();
3456
        Database::query($sql);
3457
        // Save it to search engine.
3458
        if (api_get_setting('search_enabled') == 'true') {
3459
            $di = new ChamiloIndexer();
3460
            $di->update_terms($this->get_search_did(), $new_terms, 'T');
3461
        }
3462
3463
        return true;
3464
    }
3465
3466
    /**
3467
     * Get the document ID from inside the text index database.
3468
     *
3469
     * @return int Search index database document ID
3470
     */
3471
    public function get_search_did()
3472
    {
3473
        return $this->search_did;
3474
    }
3475
3476
    /**
3477
     * Sets the item viewing time in a usable form, given that SCORM packages
3478
     * often give it as 00:00:00.0000.
3479
     *
3480
     * @param    string    Time as given by SCORM
3481
     * @param string $format
3482
     */
3483
    public function set_time($scorm_time, $format = 'scorm')
3484
    {
3485
        $debug = self::DEBUG;
3486
        if ($debug) {
3487
            error_log("learnpathItem::set_time($scorm_time, $format)");
3488
            error_log("this->type: ".$this->type);
3489
            error_log("this->current_start_time: ".$this->current_start_time);
3490
        }
3491
3492
        if ($scorm_time == '0' &&
3493
            $this->type != 'sco' &&
3494
            $this->current_start_time != 0
3495
        ) {
3496
            $myTime = time() - $this->current_start_time;
3497
            if ($myTime > 0) {
3498
                $this->update_time($myTime);
3499
                if ($debug) {
3500
                    error_log('found asset - set time to '.$myTime);
3501
                }
3502
            } else {
3503
                if ($debug) {
3504
                    error_log('Time not set');
3505
                }
3506
            }
3507
        } else {
3508
            switch ($format) {
3509
                case 'scorm':
3510
                    $res = [];
3511
                    if (preg_match(
3512
                        '/^(\d{1,4}):(\d{2}):(\d{2})(\.\d{1,4})?/',
3513
                        $scorm_time,
3514
                        $res
3515
                    )
3516
                    ) {
3517
                        $hour = $res[1];
3518
                        $min = $res[2];
3519
                        $sec = $res[3];
3520
                        // Getting total number of seconds spent.
3521
                        $totalSec = $hour * 3600 + $min * 60 + $sec;
3522
                        if ($debug) {
3523
                            error_log("totalSec : $totalSec");
3524
                            error_log("Now calling to scorm_update_time()");
3525
                        }
3526
                        $this->scorm_update_time($totalSec);
3527
                    }
3528
                    break;
3529
                case 'int':
3530
                    if ($debug) {
3531
                        error_log("scorm_time = $scorm_time");
3532
                        error_log("Now calling to scorm_update_time()");
3533
                    }
3534
                    $this->scorm_update_time($scorm_time);
3535
                    break;
3536
            }
3537
        }
3538
    }
3539
3540
    /**
3541
     * Sets the item's title.
3542
     *
3543
     * @param string $string Title
3544
     */
3545
    public function set_title($string = '')
3546
    {
3547
        if (self::DEBUG > 0) {
3548
            error_log('learnpathItem::set_title()', 0);
3549
        }
3550
        if (!empty($string)) {
3551
            $this->title = $string;
3552
        }
3553
    }
3554
3555
    /**
3556
     * Sets the item's type.
3557
     *
3558
     * @param string $string Type
3559
     */
3560
    public function set_type($string = '')
3561
    {
3562
        if (self::DEBUG > 0) {
3563
            error_log('learnpathItem::set_type()', 0);
3564
        }
3565
        if (!empty($string)) {
3566
            $this->type = $string;
3567
        }
3568
    }
3569
3570
    /**
3571
     * Checks if the current status is part of the list of status given.
3572
     *
3573
     * @param array $list An array of status to check for.
3574
     *                    If the current status is one of the strings, return true
3575
     *
3576
     * @return bool True if the status was one of the given strings,
3577
     *              false otherwise
3578
     */
3579
    public function status_is($list = [])
3580
    {
3581
        if (self::DEBUG > 1) {
3582
            error_log(
3583
                'learnpathItem::status_is('.print_r(
3584
                    $list,
3585
                    true
3586
                ).') on item '.$this->db_id,
3587
                0
3588
            );
3589
        }
3590
        $currentStatus = $this->get_status(true);
3591
        if (empty($currentStatus)) {
3592
            return false;
3593
        }
3594
        $found = false;
3595
        foreach ($list as $status) {
3596
            if (preg_match('/^'.$status.'$/i', $currentStatus)) {
3597
                if (self::DEBUG > 2) {
3598
                    error_log(
3599
                        'New LP - learnpathItem::status_is() - Found status '.
3600
                            $status.' corresponding to current status',
3601
                        0
3602
                    );
3603
                }
3604
                $found = true;
3605
3606
                return $found;
3607
            }
3608
        }
3609
        if (self::DEBUG > 2) {
3610
            error_log(
3611
                'New LP - learnpathItem::status_is() - Status '.
3612
                    $currentStatus.' did not match request',
3613
                0
3614
            );
3615
        }
3616
3617
        return $found;
3618
    }
3619
3620
    /**
3621
     * Updates the time info according to the given session_time.
3622
     *
3623
     * @param int $totalSec Time in seconds
3624
     */
3625
    public function update_time($totalSec = 0)
3626
    {
3627
        if (self::DEBUG > 0) {
3628
            error_log('learnpathItem::update_time('.$totalSec.')');
3629
        }
3630
        if ($totalSec >= 0) {
3631
            // Getting start time from finish time. The only problem in the calculation is it might be
3632
            // modified by the scripts processing time.
3633
            $now = time();
3634
            $start = $now - $totalSec;
3635
            $this->current_start_time = $start;
3636
            $this->current_stop_time = $now;
3637
        }
3638
    }
3639
3640
    /**
3641
     * Special scorm update time function. This function will update time
3642
     * directly into db for scorm objects.
3643
     *
3644
     * @param int $total_sec Total number of seconds
3645
     */
3646
    public function scorm_update_time($total_sec = 0)
3647
    {
3648
        $debug = self::DEBUG;
3649
        if ($debug) {
3650
            error_log('learnpathItem::scorm_update_time()');
3651
            error_log("total_sec: $total_sec");
3652
        }
3653
3654
        // Step 1 : get actual total time stored in db
3655
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3656
        $course_id = api_get_course_int_id();
3657
3658
        $sql = 'SELECT total_time, status 
3659
                FROM '.$item_view_table.'
3660
                WHERE 
3661
                    c_id = '.$course_id.' AND 
3662
                    lp_item_id = "'.$this->db_id.'" AND 
3663
                    lp_view_id = "'.$this->view_id.'" AND 
3664
                    view_count = "'.$this->get_attempt_id().'"';
3665
        $result = Database::query($sql);
3666
        $row = Database::fetch_array($result);
3667
3668
        if (!isset($row['total_time'])) {
3669
            $total_time = 0;
3670
        } else {
3671
            $total_time = $row['total_time'];
3672
        }
3673
        if ($debug) {
3674
            error_log("Original total_time: $total_time");
3675
        }
3676
3677
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
3678
        $lp_id = (int) $this->lp_id;
3679
        $sql = "SELECT * FROM $lp_table WHERE iid = $lp_id";
3680
        $res = Database::query($sql);
3681
        $accumulateScormTime = 'false';
3682
        if (Database::num_rows($res) > 0) {
3683
            $row = Database::fetch_assoc($res);
3684
            $accumulateScormTime = $row['accumulate_scorm_time'];
3685
        }
3686
3687
        // Step 2.1 : if normal mode total_time = total_time + total_sec
3688
        if ($this->type == 'sco' && $accumulateScormTime != 0) {
3689
            if ($debug) {
3690
                error_log("accumulateScormTime is on. total_time modified: $total_time + $total_sec");
3691
            }
3692
            $total_time += $total_sec;
3693
        } else {
3694
            // Step 2.2 : if not cumulative mode total_time = total_time - last_update + total_sec
3695
            $total_sec = $this->fixAbusiveTime($total_sec);
3696
            if ($debug) {
3697
                error_log("after fix abusive: $total_sec");
3698
                error_log("total_time: $total_time");
3699
                error_log("this->last_scorm_session_time: ".$this->last_scorm_session_time);
3700
            }
3701
3702
            $total_time = $total_time - $this->last_scorm_session_time + $total_sec;
3703
            $this->last_scorm_session_time = $total_sec;
3704
3705
            if ($total_time < 0) {
3706
                $total_time = $total_sec;
3707
            }
3708
        }
3709
3710
        if ($debug) {
3711
            error_log("accumulate_scorm_time: $accumulateScormTime");
3712
            error_log("total_time modified: $total_time");
3713
        }
3714
3715
        // Step 3 update db only if status != completed, passed, browsed or seriousgamemode not activated
3716
        // @todo complete
3717
        $case_completed = [
3718
            'completed',
3719
            'passed',
3720
            'browsed',
3721
            'failed',
3722
        ];
3723
3724
        if ($this->seriousgame_mode != 1 ||
3725
            !in_array($row['status'], $case_completed)
3726
        ) {
3727
            $sql = "UPDATE $item_view_table
3728
                      SET total_time = '$total_time'
3729
                    WHERE 
3730
                        c_id = $course_id AND 
3731
                        lp_item_id = {$this->db_id} AND 
3732
                        lp_view_id = {$this->view_id} AND 
3733
                        view_count = {$this->get_attempt_id()}";
3734
            if ($debug) {
3735
                error_log('-------------total_time updated ------------------------');
3736
                error_log($sql);
3737
                error_log('-------------------------------------');
3738
            }
3739
            Database::query($sql);
3740
        }
3741
    }
3742
3743
    /**
3744
     * Set the total_time to 0 into db.
3745
     */
3746
    public function scorm_init_time()
3747
    {
3748
        $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3749
        $course_id = api_get_course_int_id();
3750
        $sql = 'UPDATE '.$table.'
3751
                SET total_time = 0, 
3752
                    start_time = '.time().'
3753
                WHERE 
3754
                    c_id = '.$course_id.' AND 
3755
                    lp_item_id = "'.$this->db_id.'" AND 
3756
                    lp_view_id = "'.$this->view_id.'" AND 
3757
                    view_count = "'.$this->attempt_id.'"';
3758
        Database::query($sql);
3759
    }
3760
3761
    /**
3762
     * Write objectives to DB. This method is separate from write_to_db() because otherwise
3763
     * objectives are lost as a side effect to AJAX and session concurrent access.
3764
     *
3765
     * @return bool True or false on error
3766
     */
3767
    public function write_objectives_to_db()
3768
    {
3769
        if (self::DEBUG > 0) {
3770
            error_log('learnpathItem::write_objectives_to_db()', 0);
3771
        }
3772
        $course_id = api_get_course_int_id();
3773
        if (is_array($this->objectives) && count($this->objectives) > 0) {
3774
            // Save objectives.
3775
            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3776
            $sql = "SELECT iid
3777
                    FROM $tbl
3778
                    WHERE
3779
                        c_id = $course_id AND
3780
                        lp_item_id = ".$this->db_id." AND
3781
                        lp_view_id = ".$this->view_id." AND
3782
                        view_count = ".$this->attempt_id;
3783
            $res = Database::query($sql);
3784
            if (Database::num_rows($res) > 0) {
3785
                $row = Database::fetch_array($res);
3786
                $lp_iv_id = $row[0];
3787
                if (self::DEBUG > 2) {
3788
                    error_log(
3789
                        'learnpathItem::write_to_db() - Got item_view_id '.
3790
                            $lp_iv_id.', now checking objectives ',
3791
                        0
3792
                    );
3793
                }
3794
                foreach ($this->objectives as $index => $objective) {
3795
                    $iva_table = Database::get_course_table(
3796
                        TABLE_LP_IV_OBJECTIVE
3797
                    );
3798
                    $iva_sql = "SELECT iid FROM $iva_table
3799
                                WHERE
3800
                                    c_id = $course_id AND
3801
                                    lp_iv_id = $lp_iv_id AND
3802
                                    objective_id = '".Database::escape_string($objective[0])."'";
3803
                    $iva_res = Database::query($iva_sql);
3804
                    // id(0), type(1), time(2), weighting(3),
3805
                    // correct_responses(4), student_response(5),
3806
                    // result(6), latency(7)
3807
                    if (Database::num_rows($iva_res) > 0) {
3808
                        // Update (or don't).
3809
                        $iva_row = Database::fetch_array($iva_res);
3810
                        $iva_id = $iva_row[0];
3811
                        $ivau_sql = "UPDATE $iva_table ".
3812
                            "SET objective_id = '".Database::escape_string($objective[0])."',".
3813
                            "status = '".Database::escape_string($objective[1])."',".
3814
                            "score_raw = '".Database::escape_string($objective[2])."',".
3815
                            "score_min = '".Database::escape_string($objective[4])."',".
3816
                            "score_max = '".Database::escape_string($objective[3])."' ".
3817
                            "WHERE c_id = $course_id AND iid = $iva_id";
3818
                        Database::query($ivau_sql);
3819
                    } else {
3820
                        // Insert new one.
3821
                        $params = [
3822
                            'c_id' => $course_id,
3823
                            'lp_iv_id' => $lp_iv_id,
3824
                            'order_id' => $index,
3825
                            'objective_id' => $objective[0],
3826
                            'status' => $objective[1],
3827
                            'score_raw' => $objective[2],
3828
                            'score_min' => $objective[4],
3829
                            'score_max' => $objective[3],
3830
                        ];
3831
3832
                        $insertId = Database::insert($iva_table, $params);
3833
                        if ($insertId) {
3834
                            $sql = "UPDATE $iva_table SET id = iid 
3835
                                    WHERE iid = $insertId";
3836
                            Database::query($sql);
3837
                        }
3838
                    }
3839
                }
3840
            }
3841
        }
3842
    }
3843
3844
    /**
3845
     * Writes the current data to the database.
3846
     *
3847
     * @return bool Query result
3848
     */
3849
    public function write_to_db()
3850
    {
3851
        $debug = self::DEBUG;
3852
        if ($debug) {
3853
            error_log('learnpathItem::write_to_db()', 0);
3854
        }
3855
3856
        // Check the session visibility.
3857
        if (!api_is_allowed_to_session_edit()) {
3858
            if ($debug) {
3859
                error_log('return false api_is_allowed_to_session_edit');
3860
            }
3861
3862
            return false;
3863
        }
3864
3865
        $course_id = api_get_course_int_id();
3866
        $mode = $this->get_lesson_mode();
3867
        $credit = $this->get_credit();
3868
        $total_time = ' ';
3869
        $my_status = ' ';
3870
3871
        $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3872
        $sql = 'SELECT status, total_time FROM '.$item_view_table.'
3873
                WHERE
3874
                    c_id = '.$course_id.' AND
3875
                    lp_item_id="'.$this->db_id.'" AND
3876
                    lp_view_id="'.$this->view_id.'" AND
3877
                    view_count="'.$this->get_attempt_id().'" ';
3878
        $rs_verified = Database::query($sql);
3879
        $row_verified = Database::fetch_array($rs_verified);
3880
3881
        $my_case_completed = [
3882
            'completed',
3883
            'passed',
3884
            'browsed',
3885
            'failed',
3886
        ];
3887
3888
        $oldTotalTime = $row_verified['total_time'];
3889
        $this->oldTotalTime = $oldTotalTime;
3890
3891
        $save = true;
3892
        if (isset($row_verified) && isset($row_verified['status'])) {
3893
            if (in_array($row_verified['status'], $my_case_completed)) {
3894
                $save = false;
3895
            }
3896
        }
3897
3898
        if ((($save === false && $this->type == 'sco') ||
3899
           ($this->type == 'sco' && ($credit == 'no-credit' || $mode == 'review' || $mode == 'browse'))) &&
3900
           ($this->seriousgame_mode != 1 && $this->type == 'sco')
3901
        ) {
3902
            if ($debug) {
3903
                error_log(
3904
                    "This info shouldn't be saved as the credit or lesson mode info prevent it"
3905
                );
3906
                error_log(
3907
                    'learnpathItem::write_to_db() - credit('.$credit.') or'.
3908
                    ' lesson_mode('.$mode.') prevent recording!',
3909
                    0
3910
                );
3911
            }
3912
        } else {
3913
            // Check the row exists.
3914
            $inserted = false;
3915
            // This a special case for multiple attempts and Chamilo exercises.
3916
            if ($this->type == 'quiz' &&
3917
                $this->get_prevent_reinit() == 0 &&
3918
                $this->get_status() == 'completed'
3919
            ) {
3920
                // We force the item to be restarted.
3921
                $this->restart();
3922
                $params = [
3923
                    "c_id" => $course_id,
3924
                    "total_time" => $this->get_total_time(),
3925
                    "start_time" => $this->current_start_time,
3926
                    "score" => $this->get_score(),
3927
                    "status" => $this->get_status(false),
3928
                    "max_score" => $this->get_max(),
3929
                    "lp_item_id" => $this->db_id,
3930
                    "lp_view_id" => $this->view_id,
3931
                    "view_count" => $this->get_attempt_id(),
3932
                    "suspend_data" => $this->current_data,
3933
                    //"max_time_allowed" => ,
3934
                    "lesson_location" => $this->lesson_location,
3935
                ];
3936
                if ($debug) {
3937
                    error_log(
3938
                        'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
3939
                        0
3940
                    );
3941
                }
3942
                $this->db_item_view_id = Database::insert($item_view_table, $params);
3943
                if ($this->db_item_view_id) {
3944
                    $sql = "UPDATE $item_view_table SET id = iid
3945
                            WHERE iid = ".$this->db_item_view_id;
3946
                    Database::query($sql);
3947
                    $inserted = true;
3948
                }
3949
            }
3950
3951
            $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3952
            $sql = "SELECT * FROM $item_view_table
3953
                    WHERE
3954
                        c_id = $course_id AND
3955
                        lp_item_id = ".$this->db_id." AND
3956
                        lp_view_id = ".$this->view_id." AND
3957
                        view_count = ".intval($this->get_attempt_id());
3958
            if ($debug) {
3959
                error_log(
3960
                    'learnpathItem::write_to_db() - Querying item_view: '.$sql,
3961
                    0
3962
                );
3963
            }
3964
            $check_res = Database::query($sql);
3965
            // Depending on what we want (really), we'll update or insert a new row
3966
            // now save into DB.
3967
            if (!$inserted && Database::num_rows($check_res) < 1) {
3968
                $params = [
3969
                    "c_id" => $course_id,
3970
                    "total_time" => $this->get_total_time(),
3971
                    "start_time" => $this->current_start_time,
3972
                    "score" => $this->get_score(),
3973
                    "status" => $this->get_status(false),
3974
                    "max_score" => $this->get_max(),
3975
                    "lp_item_id" => $this->db_id,
3976
                    "lp_view_id" => $this->view_id,
3977
                    "view_count" => $this->get_attempt_id(),
3978
                    "suspend_data" => $this->current_data,
3979
                    //"max_time_allowed" => ,$this->get_max_time_allowed()
3980
                    "lesson_location" => $this->lesson_location,
3981
                ];
3982
3983
                if ($debug) {
3984
                    error_log(
3985
                        'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
3986
                        0
3987
                    );
3988
                }
3989
3990
                $this->db_item_view_id = Database::insert($item_view_table, $params);
3991
                if ($this->db_item_view_id) {
3992
                    $sql = "UPDATE $item_view_table SET id = iid
3993
                            WHERE iid = ".$this->db_item_view_id;
3994
                    Database::query($sql);
3995
                }
3996
            } else {
3997
                if ($this->type == 'hotpotatoes') {
3998
                    $params = [
3999
                        'total_time' => $this->get_total_time(),
4000
                        'start_time' => $this->get_current_start_time(),
4001
                        'score' => $this->get_score(),
4002
                        'status' => $this->get_status(false),
4003
                        'max_score' => $this->get_max(),
4004
                        'suspend_data' => $this->current_data,
4005
                        'lesson_location' => $this->lesson_location,
4006
                    ];
4007
                    $where = [
4008
                        'c_id = ? AND lp_item_id = ? AND lp_view_id = ? AND view_count = ?' => [
4009
                            $course_id,
4010
                            $this->db_id,
4011
                            $this->view_id,
4012
                            $this->get_attempt_id(),
4013
                        ],
4014
                    ];
4015
                    Database::update($item_view_table, $params, $where);
4016
                } else {
4017
                    // For all other content types...
4018
                    if ($this->type == 'quiz') {
4019
                        if ($debug) {
4020
                            error_log("item is quiz:");
4021
                        }
4022
                        $my_status = ' ';
4023
                        $total_time = ' ';
4024
                        if (!empty($_REQUEST['exeId'])) {
4025
                            $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
4026
                            $exeId = (int) $_REQUEST['exeId'];
4027
                            $sql = "SELECT exe_duration
4028
                                    FROM $table
4029
                                    WHERE exe_id = $exeId";
4030
                            if ($debug) {
4031
                                error_log($sql);
4032
                            }
4033
                            $res = Database::query($sql);
4034
                            $exeRow = Database::fetch_array($res);
4035
                            $duration = $exeRow['exe_duration'];
4036
                            $total_time = " total_time = ".$duration.", ";
4037
                            if ($debug) {
4038
                                error_log("quiz: $total_time");
4039
                            }
4040
                        }
4041
                    } else {
4042
                        $my_type_lp = learnpath::get_type_static($this->lp_id);
4043
                        // This is a array containing values finished
4044
                        $case_completed = [
4045
                            'completed',
4046
                            'passed',
4047
                            'browsed',
4048
                            'failed',
4049
                        ];
4050
4051
                        // Is not multiple attempts
4052
                        if ($this->seriousgame_mode == 1 && $this->type == 'sco') {
4053
                            $total_time = " total_time = total_time +".$this->get_total_time().", ";
4054
                            $my_status = " status = '".$this->get_status(false)."' ,";
4055
                            if ($debug) {
4056
                                error_log("seriousgame_mode time changed: $total_time");
4057
                            }
4058
                        } elseif ($this->get_prevent_reinit() == 1) {
4059
                            // Process of status verified into data base.
4060
                            $sql = 'SELECT status FROM '.$item_view_table.'
4061
                                    WHERE
4062
                                        c_id = '.$course_id.' AND
4063
                                        lp_item_id="'.$this->db_id.'" AND
4064
                                        lp_view_id="'.$this->view_id.'" AND
4065
                                        view_count="'.$this->get_attempt_id().'"
4066
                                    ';
4067
                            $rs_verified = Database::query($sql);
4068
                            $row_verified = Database::fetch_array($rs_verified);
4069
4070
                            // Get type lp: 1=lp dokeos and  2=scorm.
4071
                            // If not is completed or passed or browsed and learning path is scorm.
4072
                            if (!in_array($this->get_status(false), $case_completed) &&
4073
                                $my_type_lp == 2
4074
                            ) {
4075
                                $total_time = " total_time = total_time +".$this->get_total_time().", ";
4076
                                $my_status = " status = '".$this->get_status(false)."' ,";
4077
                                if ($debug) {
4078
                                    error_log("get_prevent_reinit = 1 time changed: $total_time");
4079
                                }
4080
                            } else {
4081
                                // Verified into database.
4082
                                if (!in_array($row_verified['status'], $case_completed) &&
4083
                                    $my_type_lp == 2
4084
                                ) {
4085
                                    $total_time = " total_time = total_time +".$this->get_total_time().", ";
4086
                                    $my_status = " status = '".$this->get_status(false)."' ,";
4087
                                    if ($debug) {
4088
                                        error_log("total_time time changed case 1: $total_time");
4089
                                    }
4090
                                } elseif (in_array($row_verified['status'], $case_completed) &&
4091
                                    $my_type_lp == 2 && $this->type != 'sco'
4092
                                ) {
4093
                                    $total_time = " total_time = total_time +".$this->get_total_time().", ";
4094
                                    $my_status = " status = '".$this->get_status(false)."' ,";
4095
                                    if ($debug) {
4096
                                        error_log("total_time time changed case 2: $total_time");
4097
                                    }
4098
                                } else {
4099
                                    if (($my_type_lp == 3 && $this->type == 'au') ||
4100
                                        ($my_type_lp == 1 && $this->type != 'dir')) {
4101
                                        // Is AICC or Chamilo LP
4102
                                        $total_time = " total_time = total_time + ".$this->get_total_time().", ";
4103
                                        $my_status = " status = '".$this->get_status(false)."' ,";
4104
                                        if ($debug) {
4105
                                            error_log("total_time time changed case 3: $total_time");
4106
                                        }
4107
                                    }
4108
                                }
4109
                            }
4110
                        } else {
4111
                            // Multiple attempts are allowed.
4112
                            if (in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
4113
                                // Reset zero new attempt ?
4114
                                $my_status = " status = '".$this->get_status(false)."' ,";
4115
                                if ($debug) {
4116
                                    error_log("total_time time changed Multiple attempt case 1: $total_time");
4117
                                }
4118
                            } elseif (!in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
4119
                                $total_time = " total_time = ".$this->get_total_time().", ";
4120
                                $my_status = " status = '".$this->get_status(false)."' ,";
4121
                                if ($debug) {
4122
                                    error_log("total_time time changed Multiple attempt case 2: $total_time");
4123
                                }
4124
                            } else {
4125
                                // It is chamilo LP.
4126
                                $total_time = " total_time = total_time +".$this->get_total_time().", ";
4127
                                $my_status = " status = '".$this->get_status(false)."' ,";
4128
                                if ($debug) {
4129
                                    error_log("total_time time changed Multiple attempt case 3: $total_time");
4130
                                }
4131
                            }
4132
4133
                            // This code line fixes the problem of wrong status.
4134
                            if ($my_type_lp == 2) {
4135
                                // Verify current status in multiples attempts.
4136
                                $sql = 'SELECT status FROM '.$item_view_table.'
4137
                                        WHERE
4138
                                            c_id = '.$course_id.' AND
4139
                                            lp_item_id="'.$this->db_id.'" AND
4140
                                            lp_view_id="'.$this->view_id.'" AND
4141
                                            view_count="'.$this->get_attempt_id().'" ';
4142
                                $rs_status = Database::query($sql);
4143
                                $current_status = Database::result(
4144
                                    $rs_status,
4145
                                    0,
4146
                                    'status'
4147
                                );
4148
                                if (in_array($current_status, $case_completed)) {
4149
                                    $my_status = '';
4150
                                    $total_time = '';
4151
                                } else {
4152
                                    $total_time = " total_time = total_time + ".$this->get_total_time().", ";
4153
                                }
4154
4155
                                if ($debug) {
4156
                                    error_log("total_time time my_type_lp: $total_time");
4157
                                }
4158
                            }
4159
                        }
4160
                    }
4161
4162
                    if ($this->type == 'sco') {
4163
                        //IF scorm scorm_update_time has already updated total_time in db
4164
                        //" . //start_time = ".$this->get_current_start_time().", " . //scorm_init_time does it
4165
                        ////" max_time_allowed = '".$this->get_max_time_allowed()."'," .
4166
                        $sql = "UPDATE $item_view_table SET
4167
                                    score = ".$this->get_score().",
4168
                                    $my_status
4169
                                    max_score = '".$this->get_max()."',
4170
                                    suspend_data = '".Database::escape_string($this->current_data)."',
4171
                                    lesson_location = '".$this->lesson_location."'
4172
                                WHERE
4173
                                    c_id = $course_id AND
4174
                                    lp_item_id = ".$this->db_id." AND
4175
                                    lp_view_id = ".$this->view_id."  AND
4176
                                    view_count = ".$this->get_attempt_id();
4177
                    } else {
4178
                        //" max_time_allowed = '".$this->get_max_time_allowed()."'," .
4179
                        $sql = "UPDATE $item_view_table SET
4180
                                    $total_time
4181
                                    start_time = ".$this->get_current_start_time().",
4182
                                    score = ".$this->get_score().",
4183
                                    $my_status
4184
                                    max_score = '".$this->get_max()."',
4185
                                    suspend_data = '".Database::escape_string($this->current_data)."',
4186
                                    lesson_location = '".$this->lesson_location."'
4187
                                WHERE
4188
                                    c_id = $course_id AND
4189
                                    lp_item_id = ".$this->db_id." AND
4190
                                    lp_view_id = ".$this->view_id." AND
4191
                                    view_count = ".$this->get_attempt_id();
4192
                    }
4193
                    $this->current_start_time = time();
4194
                }
4195
                if ($debug) {
4196
                    error_log('-------------------------------------------');
4197
                    error_log('learnpathItem::write_to_db() - Updating item_view:');
4198
                    error_log($sql);
4199
                    error_log('-------------------------------------------');
4200
                }
4201
                Database::query($sql);
4202
            }
4203
4204
            if (is_array($this->interactions) &&
4205
                count($this->interactions) > 0
4206
            ) {
4207
                // Save interactions.
4208
                $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
4209
                $sql = "SELECT iid FROM $tbl
4210
                        WHERE
4211
                            c_id = $course_id AND
4212
                            lp_item_id = ".$this->db_id." AND
4213
                            lp_view_id = ".$this->view_id." AND
4214
                            view_count = ".$this->get_attempt_id();
4215
                $res = Database::query($sql);
4216
                if (Database::num_rows($res) > 0) {
4217
                    $row = Database::fetch_array($res);
4218
                    $lp_iv_id = $row[0];
4219
                    if ($debug) {
4220
                        error_log(
4221
                            'learnpathItem::write_to_db() - Got item_view_id '.
4222
                            $lp_iv_id.', now checking interactions ',
4223
                            0
4224
                        );
4225
                    }
4226
                    foreach ($this->interactions as $index => $interaction) {
4227
                        $correct_resp = '';
4228
                        if (is_array($interaction[4]) && !empty($interaction[4][0])) {
4229
                            foreach ($interaction[4] as $resp) {
4230
                                $correct_resp .= $resp.',';
4231
                            }
4232
                            $correct_resp = substr(
4233
                                $correct_resp,
4234
                                0,
4235
                                strlen($correct_resp) - 1
4236
                            );
4237
                        }
4238
                        $iva_table = Database::get_course_table(
4239
                            TABLE_LP_IV_INTERACTION
4240
                        );
4241
4242
                        //also check for the interaction ID as it must be unique for this SCO view
4243
                        $iva_sql = "SELECT iid FROM $iva_table
4244
                                    WHERE
4245
                                        c_id = $course_id AND
4246
                                        lp_iv_id = $lp_iv_id AND
4247
                                        (
4248
                                            order_id = $index OR
4249
                                            interaction_id = '".Database::escape_string($interaction[0])."'
4250
                                        )
4251
                                    ";
4252
                        $iva_res = Database::query($iva_sql);
4253
4254
                        $interaction[0] = isset($interaction[0]) ? $interaction[0] : '';
4255
                        $interaction[1] = isset($interaction[1]) ? $interaction[1] : '';
4256
                        $interaction[2] = isset($interaction[2]) ? $interaction[2] : '';
4257
                        $interaction[3] = isset($interaction[3]) ? $interaction[3] : '';
4258
                        $interaction[4] = isset($interaction[4]) ? $interaction[4] : '';
4259
                        $interaction[5] = isset($interaction[5]) ? $interaction[5] : '';
4260
                        $interaction[6] = isset($interaction[6]) ? $interaction[6] : '';
4261
                        $interaction[7] = isset($interaction[7]) ? $interaction[7] : '';
4262
4263
                        // id(0), type(1), time(2), weighting(3), correct_responses(4), student_response(5), result(6), latency(7)
4264
                        if (Database::num_rows($iva_res) > 0) {
4265
                            // Update (or don't).
4266
                            $iva_row = Database::fetch_array($iva_res);
4267
                            $iva_id = $iva_row[0];
4268
                            // Insert new one.
4269
                            $params = [
4270
                                'interaction_id' => $interaction[0],
4271
                                'interaction_type' => $interaction[1],
4272
                                'weighting' => $interaction[3],
4273
                                'completion_time' => $interaction[2],
4274
                                'correct_responses' => $correct_resp,
4275
                                'student_response' => $interaction[5],
4276
                                'result' => $interaction[6],
4277
                                'latency' => $interaction[7],
4278
                            ];
4279
                            Database::update(
4280
                                $iva_table,
4281
                                $params,
4282
                                [
4283
                                    'c_id = ? AND iid = ?' => [
4284
                                        $course_id,
4285
                                        $iva_id,
4286
                                    ],
4287
                                ]
4288
                            );
4289
                        } else {
4290
                            // Insert new one.
4291
                            $params = [
4292
                                'c_id' => $course_id,
4293
                                'order_id' => $index,
4294
                                'lp_iv_id' => $lp_iv_id,
4295
                                'interaction_id' => $interaction[0],
4296
                                'interaction_type' => $interaction[1],
4297
                                'weighting' => $interaction[3],
4298
                                'completion_time' => $interaction[2],
4299
                                'correct_responses' => $correct_resp,
4300
                                'student_response' => $interaction[5],
4301
                                'result' => $interaction[6],
4302
                                'latency' => $interaction[7],
4303
                            ];
4304
4305
                            $insertId = Database::insert($iva_table, $params);
4306
                            if ($insertId) {
4307
                                $sql = "UPDATE $iva_table SET id = iid
4308
                                        WHERE iid = $insertId";
4309
                                Database::query($sql);
4310
                            }
4311
                        }
4312
                    }
4313
                }
4314
            }
4315
        }
4316
4317
        if ($debug) {
4318
            error_log('End of learnpathItem::write_to_db()', 0);
4319
        }
4320
4321
        return true;
4322
    }
4323
4324
    /**
4325
     * Adds an audio file attached to the current item (store on disk and in db).
4326
     *
4327
     * @return bool|string|null
4328
     */
4329
    public function add_audio()
4330
    {
4331
        $course_info = api_get_course_info();
4332
        $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/';
4333
4334
        if (!is_dir($filepath.'audio')) {
4335
            mkdir(
4336
                $filepath.'audio',
4337
                api_get_permissions_for_new_directories()
4338
            );
4339
            DocumentManager::addDocument(
4340
                $course_info,
4341
                '/audio',
4342
                'folder',
4343
                0,
4344
                'audio'
4345
            );
4346
        }
4347
4348
        $key = 'file';
4349
        if (!isset($_FILES[$key]['name']) || !isset($_FILES[$key]['tmp_name'])) {
4350
            return false;
4351
        }
4352
        $result = DocumentManager::upload_document(
4353
            $_FILES,
4354
            '/audio',
4355
            null,
4356
            null,
4357
            0,
4358
            'rename',
4359
            false,
4360
            false
4361
        );
4362
        $file_path = null;
4363
4364
        if ($result) {
4365
            $file_path = basename($result['path']);
4366
4367
            // Store the mp3 file in the lp_item table.
4368
            $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
4369
            $sql = "UPDATE $tbl_lp_item SET
4370
                        audio = '".Database::escape_string($file_path)."'
4371
                    WHERE iid = ".intval($this->db_id);
4372
            Database::query($sql);
4373
        }
4374
4375
        return $file_path;
4376
    }
4377
4378
    /**
4379
     * Adds an audio file to the current item, using a file already in documents.
4380
     *
4381
     * @param int $doc_id
4382
     *
4383
     * @return string
4384
     */
4385
    public function add_audio_from_documents($doc_id)
4386
    {
4387
        $course_info = api_get_course_info();
4388
        $document_data = DocumentManager::get_document_data_by_id(
4389
            $doc_id,
4390
            $course_info['code']
4391
        );
4392
4393
        $file_path = '';
4394
        if (!empty($document_data)) {
4395
            $file_path = basename($document_data['path']);
4396
            // Store the mp3 file in the lp_item table.
4397
            $table = Database::get_course_table(TABLE_LP_ITEM);
4398
            $sql = "UPDATE $table SET
4399
                        audio = '".Database::escape_string($file_path)."'
4400
                    WHERE iid = ".intval($this->db_id);
4401
            Database::query($sql);
4402
        }
4403
4404
        return $file_path;
4405
    }
4406
4407
    /**
4408
     * Removes the relation between the current item and an audio file. The file
4409
     * is only removed from the lp_item table, but remains in the document table
4410
     * and directory.
4411
     *
4412
     * @return bool
4413
     */
4414
    public function remove_audio()
4415
    {
4416
        if (empty($this->db_id)) {
4417
            return false;
4418
        }
4419
        $table = Database::get_course_table(TABLE_LP_ITEM);
4420
        $sql = "UPDATE $table SET
4421
                audio = ''
4422
                WHERE iid IN (".$this->db_id.")";
4423
        Database::query($sql);
4424
    }
4425
4426
    /**
4427
     * Transform the SCORM status to a string that can be translated by Chamilo
4428
     * in different user languages.
4429
     *
4430
     * @param $status
4431
     * @param bool   $decorate
4432
     * @param string $type     classic|simple
4433
     *
4434
     * @return array|string
4435
     */
4436
    public static function humanize_status($status, $decorate = true, $type = 'classic')
4437
    {
4438
        $statusList = [
4439
            'completed' => 'ScormCompstatus',
4440
            'incomplete' => 'ScormIncomplete',
4441
            'failed' => 'ScormFailed',
4442
            'passed' => 'ScormPassed',
4443
            'browsed' => 'ScormBrowsed',
4444
            'not attempted' => 'ScormNotAttempted',
4445
        ];
4446
4447
        $myLessonStatus = get_lang($statusList[$status]);
4448
4449
        switch ($status) {
4450
            case 'completed':
4451
            case 'browsed':
4452
                $classStatus = 'info';
4453
                break;
4454
            case 'incomplete':
4455
                $classStatus = 'warning';
4456
                break;
4457
            case 'passed':
4458
                $classStatus = 'success';
4459
                break;
4460
            case 'failed':
4461
                $classStatus = 'important';
4462
                break;
4463
            default:
4464
                $classStatus = 'default';
4465
                break;
4466
        }
4467
4468
        if ($type == 'simple') {
4469
            if (in_array($status, ['failed', 'passed', 'browsed'])) {
4470
                $myLessonStatus = get_lang('ScormIncomplete');
4471
4472
                $classStatus = 'warning';
4473
            }
4474
        }
4475
4476
        if ($decorate) {
4477
            return Display::label($myLessonStatus, $classStatus);
4478
        } else {
4479
            return $myLessonStatus;
4480
        }
4481
    }
4482
4483
    /**
4484
     * @return float
4485
     */
4486
    public function getPrerequisiteMaxScore()
4487
    {
4488
        return $this->prerequisiteMaxScore;
4489
    }
4490
4491
    /**
4492
     * @param float $prerequisiteMaxScore
4493
     */
4494
    public function setPrerequisiteMaxScore($prerequisiteMaxScore)
4495
    {
4496
        $this->prerequisiteMaxScore = $prerequisiteMaxScore;
4497
    }
4498
4499
    /**
4500
     * @return float
4501
     */
4502
    public function getPrerequisiteMinScore()
4503
    {
4504
        return $this->prerequisiteMinScore;
4505
    }
4506
4507
    /**
4508
     * @param float $prerequisiteMinScore
4509
     */
4510
    public function setPrerequisiteMinScore($prerequisiteMinScore)
4511
    {
4512
        $this->prerequisiteMinScore = $prerequisiteMinScore;
4513
    }
4514
4515
    /**
4516
     * Check if this LP item has a created thread in the basis course from the forum of its LP.
4517
     *
4518
     * @param int $lpCourseId The course ID
4519
     *
4520
     * @return bool
4521
     */
4522
    public function lpItemHasThread($lpCourseId)
4523
    {
4524
        $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
4525
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4526
4527
        $fakeFrom = "
4528
            $forumThreadTable ft
4529
            INNER JOIN $itemProperty ip
4530
            ON (ft.thread_id = ip.ref AND ft.c_id = ip.c_id)
4531
        ";
4532
4533
        $resultData = Database::select(
4534
            'COUNT(ft.iid) AS qty',
4535
            $fakeFrom,
4536
            [
4537
                'where' => [
4538
                    'ip.visibility != ? AND ' => 2,
4539
                    'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
4540
                    'ft.c_id = ? AND ' => intval($lpCourseId),
4541
                    '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
4542
                        intval($this->db_id),
4543
                        "{$this->title} - {$this->db_id}",
4544
                        intval($this->db_id),
4545
                    ],
4546
                ],
4547
            ],
4548
            'first'
4549
        );
4550
4551
        if ($resultData['qty'] > 0) {
4552
            return true;
4553
        }
4554
4555
        return false;
4556
    }
4557
4558
    /**
4559
     * Get the forum thread info.
4560
     *
4561
     * @param int $lpCourseId  The course ID from the learning path
4562
     * @param int $lpSessionId Optional. The session ID from the learning path
4563
     *
4564
     * @return bool
4565
     */
4566
    public function getForumThread($lpCourseId, $lpSessionId = 0)
4567
    {
4568
        $lpSessionId = (int) $lpSessionId;
4569
        $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
4570
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4571
4572
        $fakeFrom = "$forumThreadTable ft
4573
            INNER JOIN $itemProperty ip ";
4574
4575
        if ($lpSessionId == 0) {
4576
            $fakeFrom .= "
4577
                ON (
4578
                    ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND (
4579
                        ft.session_id = ip.session_id OR ip.session_id IS NULL
4580
                    )
4581
                )
4582
            ";
4583
        } else {
4584
            $fakeFrom .= "
4585
                ON (
4586
                    ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND ft.session_id = ip.session_id
4587
                )
4588
            ";
4589
        }
4590
4591
        $resultData = Database::select(
4592
            'ft.*',
4593
            $fakeFrom,
4594
            [
4595
                'where' => [
4596
                    'ip.visibility != ? AND ' => 2,
4597
                    'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
4598
                    'ft.session_id = ? AND ' => $lpSessionId,
4599
                    'ft.c_id = ? AND ' => intval($lpCourseId),
4600
                    '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
4601
                        intval($this->db_id),
4602
                        "{$this->title} - {$this->db_id}",
4603
                        intval($this->db_id),
4604
                    ],
4605
                ],
4606
            ],
4607
            'first'
4608
        );
4609
4610
        if (empty($resultData)) {
4611
            return false;
4612
        }
4613
4614
        return $resultData;
4615
    }
4616
4617
    /**
4618
     * Create a forum thread for this learning path item.
4619
     *
4620
     * @param int $currentForumId The forum ID to add the new thread
4621
     *
4622
     * @return int The forum thread if was created. Otherwise return false
4623
     */
4624
    public function createForumThread($currentForumId)
4625
    {
4626
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
4627
4628
        $em = Database::getManager();
4629
        $threadRepo = $em->getRepository('ChamiloCourseBundle:CForumThread');
4630
        $forumThread = $threadRepo->findOneBy([
4631
            'threadTitle' => "{$this->title} - {$this->db_id}",
4632
            'forumId' => (int) $currentForumId,
4633
        ]);
4634
4635
        if (!$forumThread) {
4636
            $forumInfo = get_forum_information($currentForumId);
4637
4638
            store_thread(
4639
                $forumInfo,
4640
                [
4641
                    'forum_id' => intval($currentForumId),
4642
                    'thread_id' => 0,
4643
                    'gradebook' => 0,
4644
                    'post_title' => "{$this->name} - {$this->db_id}",
4645
                    'post_text' => $this->description,
4646
                    'category_id' => 1,
4647
                    'numeric_calification' => 0,
4648
                    'calification_notebook_title' => 0,
4649
                    'weight_calification' => 0.00,
4650
                    'thread_peer_qualify' => 0,
4651
                    'lp_item_id' => $this->db_id,
4652
                ],
4653
                [],
4654
                false
4655
            );
4656
4657
            return;
4658
        }
4659
4660
        $forumThread->setLpItemId($this->db_id);
4661
4662
        $em->persist($forumThread);
4663
        $em->flush();
4664
    }
4665
4666
    /**
4667
     * Allow dissociate a forum to this LP item.
4668
     *
4669
     * @param int $threadIid The thread id
4670
     *
4671
     * @return bool
4672
     */
4673
    public function dissociateForumThread($threadIid)
4674
    {
4675
        $threadIid = (int) $threadIid;
4676
        $em = Database::getManager();
4677
4678
        $forumThread = $em->find('ChamiloCourseBundle:CForumThread', $threadIid);
4679
4680
        if (!$forumThread) {
4681
            return false;
4682
        }
4683
4684
        $forumThread->setThreadTitle("{$this->get_title()} - {$this->db_id}");
4685
        $forumThread->setLpItemId(0);
4686
4687
        $em->persist($forumThread);
4688
        $em->flush();
4689
4690
        return true;
4691
    }
4692
4693
    /**
4694
     * @return int
4695
     */
4696
    public function getLastScormSessionTime()
4697
    {
4698
        return $this->last_scorm_session_time;
4699
    }
4700
4701
    /**
4702
     * @return int
4703
     */
4704
    public function getIid()
4705
    {
4706
        return $this->iId;
4707
    }
4708
}
4709