Passed
Push — master ( 7e1a48...92a822 )
by Yannick
21:31 queued 10:48
created

learnpath::get_student_publications()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 43
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 29
nc 2
nop 0
dl 0
loc 43
rs 9.456
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Course;
6
use Chamilo\CoreBundle\Entity\ResourceLink;
7
use Chamilo\CoreBundle\Entity\ResourceNode;
8
use Chamilo\CoreBundle\Entity\Session as SessionEntity;
9
use Chamilo\CoreBundle\Entity\TrackEExercise;
10
use Chamilo\CoreBundle\Entity\User;
11
use Chamilo\CoreBundle\Enums\ObjectIcon;
12
use Chamilo\CoreBundle\Event\Events;
13
use Chamilo\CoreBundle\Event\LearningPathEndedEvent;
14
use Chamilo\CoreBundle\Framework\Container;
15
use Chamilo\CoreBundle\Repository\TrackEDefaultRepository;
16
use Chamilo\CoreBundle\Helpers\ThemeHelper;
17
use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
18
use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
19
use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
20
use Chamilo\CourseBundle\Entity\CDocument;
21
use Chamilo\CourseBundle\Entity\CForumThread;
22
use Chamilo\CourseBundle\Entity\CLink;
23
use Chamilo\CourseBundle\Entity\CLp;
24
use Chamilo\CourseBundle\Entity\CLpCategory;
25
use Chamilo\CourseBundle\Entity\CLpItem;
26
use Chamilo\CourseBundle\Entity\CLpItemView;
27
use Chamilo\CourseBundle\Entity\CLpRelUser;
28
use Chamilo\CourseBundle\Entity\CQuiz;
29
use Chamilo\CourseBundle\Entity\CStudentPublication;
30
use Chamilo\CourseBundle\Entity\CSurvey;
31
use Chamilo\CourseBundle\Entity\CTool;
32
use Chamilo\CourseBundle\Repository\CLpRelUserRepository;
33
use ChamiloSession as Session;
34
use Doctrine\Common\Collections\Criteria;
35
use PhpZip\ZipFile;
36
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
37
38
/**
39
 * Class learnpath
40
 * This class defines the parent attributes and methods for Chamilo learnpaths
41
 * and SCORM learnpaths. It is used by the scorm class.
42
 *
43
 * @todo decouple class
44
 *
45
 * @author  Yannick Warnier <[email protected]>
46
 * @author  Julio Montoya   <[email protected]> Several improvements and fixes
47
 */
48
class learnpath
49
{
50
    public const MAX_LP_ITEM_TITLE_LENGTH = 36;
51
    public const STATUS_CSS_CLASS_NAME = [
52
        'not attempted' => 'scorm_not_attempted',
53
        'incomplete' => 'scorm_not_attempted',
54
        'failed' => 'scorm_failed',
55
        'completed' => 'scorm_completed',
56
        'passed' => 'scorm_completed',
57
        'succeeded' => 'scorm_completed',
58
        'browsed' => 'scorm_completed',
59
    ];
60
61
    public $attempt = 0; // The number for the current ID view.
62
    public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
63
    public $current; // Id of the current item the user is viewing.
64
    public $current_score; // The score of the current item.
65
    public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
66
    public $current_time_stop; // The time the user closed this resource.
67
    public $default_status = 'not attempted';
68
    public $encoding = 'UTF-8';
69
    public $error = '';
70
    public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
71
    public $index; // The index of the active learnpath_item in $ordered_items array.
72
    /** @var learnpathItem[] */
73
    public $items = [];
74
    public $last; // item_id of last item viewed in the learning path.
75
    public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
76
    public $license; // Which license this course has been given - not used yet on 20060522.
77
    public $lp_id; // DB iid for this learnpath.
78
    public $lp_view_id; // DB ID for lp_view
79
    public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
80
    public $message = '';
81
    public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
82
    public $name; // Learnpath name (they generally have one).
83
    public $ordered_items = []; // List of the learnpath items in the order they are to be read.
84
    public $path = ''; // Path inside the scorm directory (if scorm).
85
    public $theme; // The current theme of the learning path.
86
    public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
87
    public $accumulateWorkTime; // The min time of learnpath
88
89
    // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
90
    public $prevent_reinit = 1;
91
92
    // Describes the mode of progress bar display.
93
    public $seriousgame_mode = 0;
94
    public $progress_bar_mode = '%';
95
96
    // Percentage progress as saved in the db.
97
    public $progress_db = 0;
98
    public $proximity; // Wether the content is distant or local or unknown.
99
    public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
100
    // !!!This array (refs_list) is built differently depending on the nature of the LP.
101
    // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
102
    public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
103
    // TODO: Check if this type variable is useful here (instead of just in the controller script).
104
    public $user_id; //ID of the user that is viewing/using the course
105
    public $update_queue = [];
106
    public $scorm_debug = 0;
107
    public $arrMenu = []; // Array for the menu items.
108
    public $debug = 0; // Logging level.
109
    public $lp_session_id = 0;
110
    public $lp_view_session_id = 0; // The specific view might be bound to a session.
111
    public $prerequisite = 0;
112
    public $use_max_score = 1; // 1 or 0
113
    public $subscribeUsers = 0; // Subscribe users or not
114
    public $created_on = '';
115
    public $modified_on = '';
116
    public $published_on = '';
117
    public $expired_on = '';
118
    public $ref;
119
    public $course_int_id;
120
    public $course_info;
121
    public $categoryId;
122
    public $scormUrl;
123
    public $entity;
124
    public $auto_forward_video = 1;
125
126
    public function __construct(CLp $entity = null, $course_info, $user_id)
127
    {
128
        $debug = $this->debug;
129
        $user_id = (int) $user_id;
130
        $this->encoding = api_get_system_encoding();
131
        $lp_id = 0;
132
        if (null !== $entity) {
133
            $lp_id = $entity->getIid();
134
        }
135
        $course_info = empty($course_info) ? api_get_course_info() : $course_info;
136
        $course_id = (int) $course_info['real_id'];
137
        $this->course_info = $course_info;
138
        $this->set_course_int_id($course_id);
139
        if (empty($lp_id) || empty($course_id)) {
140
            $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
141
        } else {
142
            //$this->entity = $entity;
143
            $this->lp_id = $lp_id;
144
            $this->type = $entity->getLpType();
145
            $this->name = stripslashes($entity->getTitle());
146
            $this->proximity = $entity->getContentLocal();
147
            $this->theme = $entity->getTheme();
148
            $this->maker = $entity->getContentLocal();
149
            $this->prevent_reinit = $entity->getPreventReinit();
150
            $this->seriousgame_mode = $entity->getSeriousgameMode();
151
            $this->license = $entity->getContentLicense();
152
            $this->scorm_debug = $entity->getDebug();
153
            $this->js_lib = $entity->getJsLib();
154
            $this->path = $entity->getPath();
155
            $this->author = $entity->getAuthor();
156
            $this->hide_toc_frame = $entity->getHideTocFrame();
157
            //$this->lp_session_id = $entity->getSessionId();
158
            $this->use_max_score = $entity->getUseMaxScore();
159
            $this->subscribeUsers = $entity->getSubscribeUsers();
160
            $this->created_on = $entity->getCreatedOn()->format('Y-m-d H:i:s');
161
            $this->modified_on = $entity->getModifiedOn()->format('Y-m-d H:i:s');
162
            $this->ref = $entity->getRef();
163
            $this->auto_forward_video = $entity->getAutoForwardVideo();
164
            $this->categoryId = 0;
165
            if ($entity->getCategory()) {
166
                $this->categoryId = $entity->getCategory()->getIid();
167
            }
168
169
            if ($entity->hasAsset()) {
170
                $asset = $entity->getAsset();
171
                $this->scormUrl = Container::getAssetRepository()->getAssetUrl($asset).'/'.$entity->getPath().'/';
172
            }
173
174
            $this->accumulateScormTime = $entity->getAccumulateWorkTime();
175
176
            if (!empty($entity->getPublishedOn())) {
177
                $this->published_on = $entity->getPublishedOn()->format('Y-m-d H:i:s');
178
            }
179
180
            if (!empty($entity->getExpiredOn())) {
181
                $this->expired_on = $entity->getExpiredOn()->format('Y-m-d H:i:s');
182
            }
183
            if (2 == $this->type) {
184
                if (1 == $entity->getForceCommit()) {
185
                    $this->force_commit = true;
186
                }
187
            }
188
            $this->mode = $entity->getDefaultViewMod();
189
190
            // Check user ID.
191
            if (empty($user_id)) {
192
                $this->error = 'User ID is empty';
193
            } else {
194
                $this->user_id = $user_id;
195
            }
196
197
            // End of variables checking.
198
            $session_id = api_get_session_id();
199
            //  Get the session condition for learning paths of the base + session.
200
            $session = api_get_session_condition($session_id);
201
            // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
202
            $lp_table = Database::get_course_table(TABLE_LP_VIEW);
203
204
            // Selecting by view_count descending allows to get the highest view_count first.
205
            $sql = "SELECT * FROM $lp_table
206
                    WHERE
207
                        c_id = $course_id AND
208
                        lp_id = $lp_id AND
209
                        user_id = $user_id
210
                        $session
211
                    ORDER BY view_count DESC";
212
            $res = Database::query($sql);
213
214
            if (Database::num_rows($res) > 0) {
215
                $row = Database::fetch_array($res);
216
                $this->attempt = $row['view_count'];
217
                $this->lp_view_id = $row['iid'];
218
                $this->last_item_seen = $row['last_item'];
219
                $this->progress_db = $row['progress'];
220
                $this->lp_view_session_id = $row['session_id'];
221
            } elseif (!api_is_invitee()) {
222
                $this->attempt = 1;
223
                $params = [
224
                    'c_id' => $course_id,
225
                    'lp_id' => $lp_id,
226
                    'user_id' => $user_id,
227
                    'view_count' => 1,
228
                    //'session_id' => $session_id,
229
                    'last_item' => 0,
230
                ];
231
                if (!empty($session_id)) {
232
                    $params['session_id'] = $session_id;
233
                }
234
                $this->last_item_seen = 0;
235
                $this->lp_view_session_id = $session_id;
236
                $this->lp_view_id = Database::insert($lp_table, $params);
237
            }
238
239
            $criteria = new Criteria();
240
            $criteria
241
                ->where($criteria->expr()->neq('path', 'root'))
242
                ->orderBy(
243
                    [
244
                        'parent' => Criteria::ASC,
245
                        'displayOrder' => Criteria::ASC,
246
                    ]
247
                );
248
            $items = $entity->getItems()->matching($criteria);
249
            $lp_item_id_list = [];
250
            foreach ($items as $item) {
251
                $itemId = $item->getIid();
252
                $lp_item_id_list[] = $itemId;
253
254
                switch ($this->type) {
255
                    case CLp::AICC_TYPE:
256
                        $oItem = new aiccItem('db', $itemId, $course_id);
257
                        if (is_object($oItem)) {
258
                            $oItem->set_lp_view($this->lp_view_id);
259
                            $oItem->set_prevent_reinit($this->prevent_reinit);
260
                            // Don't use reference here as the next loop will make the pointed object change.
261
                            $this->items[$itemId] = $oItem;
262
                            $this->refs_list[$oItem->ref] = $itemId;
263
                        }
264
                        break;
265
                    case CLp::SCORM_TYPE:
266
                        $oItem = new scormItem('db', $itemId);
267
                        if (is_object($oItem)) {
268
                            $oItem->set_lp_view($this->lp_view_id);
269
                            $oItem->set_prevent_reinit($this->prevent_reinit);
270
                            // Don't use reference here as the next loop will make the pointed object change.
271
                            $this->items[$itemId] = $oItem;
272
                            $this->refs_list[$oItem->ref] = $itemId;
273
                        }
274
                        break;
275
                    case CLp::LP_TYPE:
276
                    default:
277
                        $oItem = new learnpathItem(null, $item);
278
                        if (is_object($oItem)) {
279
                            // Moved down to when we are sure the item_view exists.
280
                            //$oItem->set_lp_view($this->lp_view_id);
281
                            $oItem->set_prevent_reinit($this->prevent_reinit);
282
                            // Don't use reference here as the next loop will make the pointed object change.
283
                            $this->items[$itemId] = $oItem;
284
                            $this->refs_list[$itemId] = $itemId;
285
                        }
286
                        break;
287
                }
288
289
                // Setting the object level with variable $this->items[$i][parent]
290
                foreach ($this->items as $itemLPObject) {
291
                    $level = self::get_level_for_item($this->items, $itemLPObject->db_id);
292
                    $itemLPObject->level = $level;
293
                }
294
295
                // Setting the view in the item object.
296
                if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
297
                    $this->items[$itemId]->set_lp_view($this->lp_view_id);
298
                    if (TOOL_HOTPOTATOES == $this->items[$itemId]->get_type()) {
299
                        $this->items[$itemId]->current_start_time = 0;
300
                        $this->items[$itemId]->current_stop_time = 0;
301
                    }
302
                }
303
            }
304
305
            if (!empty($lp_item_id_list)) {
306
                $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
307
                if (!empty($lp_item_id_list_to_string)) {
308
                    // Get last viewing vars.
309
                    $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
310
                    // This query should only return one or zero result.
311
                    $sql = "SELECT lp_item_id, status
312
                            FROM $itemViewTable
313
                            WHERE
314
                                lp_view_id = ".$this->get_view_id()." AND
315
                                lp_item_id IN ('".$lp_item_id_list_to_string."')
316
                            ORDER BY view_count DESC ";
317
                    $status_list = [];
318
                    $res = Database::query($sql);
319
                    while ($row = Database:: fetch_array($res)) {
320
                        $status_list[$row['lp_item_id']] = $row['status'];
321
                    }
322
323
                    foreach ($lp_item_id_list as $item_id) {
324
                        if (isset($status_list[$item_id])) {
325
                            $status = $status_list[$item_id];
326
327
                            if (is_object($this->items[$item_id])) {
328
                                $this->items[$item_id]->set_status($status);
329
                                if (empty($status)) {
330
                                    $this->items[$item_id]->set_status(
331
                                        $this->default_status
332
                                    );
333
                                }
334
                            }
335
                        } else {
336
                            if (!api_is_invitee()) {
337
                                if (isset($this->items[$item_id]) && is_object($this->items[$item_id])) {
338
                                    $this->items[$item_id]->set_status(
339
                                        $this->default_status
340
                                    );
341
                                }
342
343
                                if (!empty($this->lp_view_id)) {
344
                                    // Add that row to the lp_item_view table so that
345
                                    // we have something to show in the stats page.
346
                                    $params = [
347
                                        'lp_item_id' => $item_id,
348
                                        'lp_view_id' => $this->lp_view_id,
349
                                        'view_count' => 1,
350
                                        'status' => 'not attempted',
351
                                        'start_time' => time(),
352
                                        'total_time' => 0,
353
                                        'score' => 0,
354
                                    ];
355
                                    Database::insert($itemViewTable, $params);
356
357
                                    $this->items[$item_id]->set_lp_view(
358
                                        $this->lp_view_id
359
                                    );
360
                                }
361
                            }
362
                        }
363
                    }
364
                }
365
            }
366
367
            $this->ordered_items = self::get_flat_ordered_items_list($entity, null);
368
            $this->max_ordered_items = 0;
369
            foreach ($this->ordered_items as $index => $dummy) {
370
                if ($index > $this->max_ordered_items && !empty($dummy)) {
371
                    $this->max_ordered_items = $index;
372
                }
373
            }
374
            // TODO: Define the current item better.
375
            $this->first();
376
            if ($debug) {
377
                error_log('lp_view_session_id '.$this->lp_view_session_id);
378
                error_log('End of learnpath constructor for learnpath '.$this->get_id());
379
            }
380
        }
381
    }
382
383
    /**
384
     * @return int
385
     */
386
    public function get_course_int_id()
387
    {
388
        return $this->course_int_id ?? api_get_course_int_id();
389
    }
390
391
    /**
392
     * @param $course_id
393
     *
394
     * @return int
395
     */
396
    public function set_course_int_id($course_id)
397
    {
398
        return $this->course_int_id = (int) $course_id;
399
    }
400
401
    /**
402
     * Function rewritten based on old_add_item() from Yannick Warnier.
403
     * Due the fact that users can decide where the item should come, I had to overlook this function and
404
     * I found it better to rewrite it. Old function is still available.
405
     * Added also the possibility to add a description.
406
     *
407
     * @param CLpItem $parent
408
     * @param int     $previousId
409
     * @param string  $type
410
     * @param int     $id resource ID (ref)
411
     * @param string  $title
412
     * @param string  $description
413
     * @param int     $prerequisites
414
     * @param int     $maxTimeAllowed
415
     * @param int     $userId
416
     *
417
     * @return int
418
     */
419
    public function add_item(
420
        ?CLpItem $parent,
421
        $previousId,
422
        $type,
423
        $id,
424
        $title,
425
        $description = '',
426
        $prerequisites = 0,
427
        $maxTimeAllowed = 0
428
    ) {
429
        $type = empty($type) ? 'dir' : $type;
430
        $course_id = $this->course_info['real_id'];
431
        if (empty($course_id)) {
432
            // Sometimes Oogie doesn't catch the course info but sets $this->cc
433
            $this->course_info = api_get_course_info($this->cc);
434
            $course_id = $this->course_info['real_id'];
435
        }
436
        $id = (int) $id;
437
        $maxTimeAllowed = (int) $maxTimeAllowed;
438
        if (empty($maxTimeAllowed)) {
439
            $maxTimeAllowed = 0;
440
        }
441
        $maxScore = 100;
442
        if ('quiz' === $type && $id) {
443
            // Disabling the exercise if we add it inside a LP
444
            $exercise = new Exercise($course_id);
445
            $exercise->read($id);
446
            $maxScore = $exercise->getMaxScore();
447
448
            $exercise->disable();
449
            $exercise->save();
450
            $title = $exercise->get_formated_title();
451
        }
452
453
        $lpItem = (new CLpItem())
454
            ->setTitle($title)
455
            ->setDescription($description)
456
            ->setPath($id)
457
            ->setLp(api_get_lp_entity($this->get_id()))
458
            ->setItemType($type)
459
            ->setMaxScore($maxScore)
460
            ->setMaxTimeAllowed($maxTimeAllowed)
461
            ->setPrerequisite($prerequisites)
462
            //->setDisplayOrder($display_order + 1)
463
            //->setNextItemId((int) $next)
464
            //->setPreviousItemId($previous)
465
        ;
466
467
        if (!empty($parent))  {
468
            $lpItem->setParent($parent);
469
        }
470
        $em = Database::getManager();
471
        $em->persist($lpItem);
472
        $em->flush();
473
474
        $new_item_id = $lpItem->getIid();
475
        if ($new_item_id) {
476
            // @todo fix upload audio.
477
            // Upload audio.
478
            /*if (!empty($_FILES['mp3']['name'])) {
479
                // Create the audio folder if it does not exist yet.
480
                $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
481
                if (!is_dir($filepath.'audio')) {
482
                    mkdir(
483
                        $filepath.'audio',
484
                        api_get_permissions_for_new_directories()
485
                    );
486
                    DocumentManager::addDocument(
487
                        $_course,
488
                        '/audio',
489
                        'folder',
490
                        0,
491
                        'audio',
492
                        '',
493
                        0,
494
                        true,
495
                        null,
496
                        $sessionId,
497
                        $userId
498
                    );
499
                }
500
501
                $file_path = handle_uploaded_document(
502
                    $_course,
503
                    $_FILES['mp3'],
504
                    api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
505
                    '/audio',
506
                    $userId,
507
                    '',
508
                    '',
509
                    '',
510
                    '',
511
                    false
512
                );
513
514
                // Getting the filename only.
515
                $file_components = explode('/', $file_path);
516
                $file = $file_components[count($file_components) - 1];
517
518
                // Store the mp3 file in the lp_item table.
519
                $sql = "UPDATE $tbl_lp_item SET
520
                          audio = '".Database::escape_string($file)."'
521
                        WHERE iid = '".intval($new_item_id)."'";
522
                Database::query($sql);
523
            }*/
524
        }
525
526
        return $new_item_id;
527
    }
528
529
    /**
530
     * Static admin function allowing addition of a learnpath to a course.
531
     *
532
     * @param string $courseCode
533
     * @param string $name
534
     * @param string $description
535
     * @param string $learnpath
536
     * @param string $origin
537
     * @param string $zipname       Zip file containing the learnpath or directory containing the learnpath
538
     * @param string $published_on
539
     * @param string $expired_on
540
     * @param int    $categoryId
541
     * @param int    $userId
542
     *
543
     * @return CLp
544
     */
545
    public static function add_lp(
546
        $courseCode,
547
        $name,
548
        $description = '',
549
        $learnpath = 'guess',
550
        $origin = 'zip',
551
        $zipname = '',
552
        $published_on = '',
553
        $expired_on = '',
554
        $categoryId = 0,
555
        $userId = 0
556
    ) {
557
        global $charset;
558
559
        if (!empty($courseCode)) {
560
            $courseInfo = api_get_course_info($courseCode);
561
            $course_id = $courseInfo['real_id'];
562
        } else {
563
            $course_id = api_get_course_int_id();
564
            $courseInfo = api_get_course_info();
565
        }
566
567
        $categoryId = (int) $categoryId;
568
569
        if (empty($published_on)) {
570
            $published_on = null;
571
        } else {
572
            $published_on = api_get_utc_datetime($published_on, true, true);
573
        }
574
575
        if (empty($expired_on)) {
576
            $expired_on = null;
577
        } else {
578
            $expired_on = api_get_utc_datetime($expired_on, true, true);
579
        }
580
581
        $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES));
582
        $type = 1;
583
        switch ($learnpath) {
584
            case 'guess':
585
            case 'aicc':
586
                break;
587
            case 'dokeos':
588
            case 'chamilo':
589
                $type = 1;
590
                break;
591
        }
592
593
        $sessionEntity = api_get_session_entity();
594
        $courseEntity = api_get_course_entity($courseInfo['real_id']);
595
        $lp = null;
596
        switch ($origin) {
597
            case 'zip':
598
                // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
599
                break;
600
            case 'manual':
601
            default:
602
                /*$get_max = "SELECT MAX(display_order)
603
                            FROM $tbl_lp WHERE c_id = $course_id";
604
                $res_max = Database::query($get_max);
605
                if (Database::num_rows($res_max) < 1) {
606
                    $dsp = 1;
607
                } else {
608
                    $row = Database::fetch_array($res_max);
609
                    $dsp = $row[0] + 1;
610
                }*/
611
612
                $category = null;
613
                if (!empty($categoryId)) {
614
                    $category = Container::getLpCategoryRepository()->find($categoryId);
615
                }
616
617
                $lpRepo = Container::getLpRepository();
618
619
                $lp = (new CLp())
620
                    ->setLpType($type)
621
                    ->setTitle($name)
622
                    ->setDescription($description)
623
                    ->setCategory($category)
624
                    ->setPublishedOn($published_on)
625
                    ->setExpiredOn($expired_on)
626
                    ->setParent($courseEntity)
627
                    ->addCourseLink($courseEntity, $sessionEntity)
628
                ;
629
                $lpRepo->createLp($lp);
630
631
                break;
632
        }
633
634
        return $lp;
635
    }
636
637
    /**
638
     * Auto completes the parents of an item in case it's been completed or passed.
639
     *
640
     * @param int $item Optional ID of the item from which to look for parents
641
     */
642
    public function autocomplete_parents($item)
643
    {
644
        $debug = $this->debug;
645
646
        if (empty($item)) {
647
            $item = $this->current;
648
        }
649
650
        $currentItem = $this->getItem($item);
651
        if ($currentItem) {
652
            $parent_id = $currentItem->get_parent();
653
            $parent = $this->getItem($parent_id);
654
            if ($parent) {
655
                // if $item points to an object and there is a parent.
656
                if ($debug) {
657
                    error_log(
658
                        'Autocompleting parent of item '.$item.' '.
659
                        $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
660
                        0
661
                    );
662
                }
663
664
                // New experiment including failed and browsed in completed status.
665
                //$current_status = $currentItem->get_status();
666
                //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
667
                // Fixes chapter auto complete
668
                if (true) {
669
                    // If the current item is completed or passes or succeeded.
670
                    $updateParentStatus = true;
671
                    if ($debug) {
672
                        error_log('Status of current item is alright');
673
                    }
674
675
                    foreach ($parent->get_children() as $childItemId) {
676
                        $childItem = $this->getItem($childItemId);
677
678
                        // If children was not set try to get the info
679
                        if (empty($childItem->db_item_view_id)) {
680
                            $childItem->set_lp_view($this->lp_view_id);
681
                        }
682
683
                        // Check all his brothers (parent's children) for completion status.
684
                        if ($childItemId != $item) {
685
                            if ($debug) {
686
                                error_log(
687
                                    'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
688
                                    0
689
                                );
690
                            }
691
                            // Trying completing parents of failed and browsed items as well.
692
                            if ($childItem->status_is(
693
                                [
694
                                    'completed',
695
                                    'passed',
696
                                    'succeeded',
697
                                    'browsed',
698
                                    'failed',
699
                                ]
700
                            )
701
                            ) {
702
                                // Keep completion status to true.
703
                                continue;
704
                            } else {
705
                                if ($debug > 2) {
706
                                    error_log(
707
                                        'Found one incomplete child of parent #'.$parent_id.': child #'.$childItemId.' "'.$childItem->get_title().'", is '.$childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
708
                                        0
709
                                    );
710
                                }
711
                                $updateParentStatus = false;
712
                                break;
713
                            }
714
                        }
715
                    }
716
717
                    if ($updateParentStatus) {
718
                        // If all the children were completed:
719
                        $parent->set_status('completed');
720
                        $parent->save(false, $this->prerequisites_match($parent->get_id()));
721
                        // Force the status to "completed"
722
                        //$this->update_queue[$parent->get_id()] = $parent->get_status();
723
                        $this->update_queue[$parent->get_id()] = 'completed';
724
                        if ($debug) {
725
                            error_log(
726
                                'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
727
                                print_r($this->update_queue, 1),
728
                                0
729
                            );
730
                        }
731
                        // Recursive call.
732
                        $this->autocomplete_parents($parent->get_id());
733
                    }
734
                }
735
            } else {
736
                if ($debug) {
737
                    error_log("Parent #$parent_id does not exists");
738
                }
739
            }
740
        } else {
741
            if ($debug) {
742
                error_log("#$item is an item that doesn't have parents");
743
            }
744
        }
745
    }
746
747
    /**
748
     * Closes the current resource.
749
     *
750
     * Stops the timer
751
     * Saves into the database if required
752
     * Clears the current resource data from this object
753
     *
754
     * @return bool True on success, false on failure
755
     */
756
    public function close()
757
    {
758
        if (empty($this->lp_id)) {
759
            $this->error = 'Trying to close this learnpath but no ID is set';
760
761
            return false;
762
        }
763
        $this->current_time_stop = time();
764
        $this->ordered_items = [];
765
        $this->index = 0;
766
        unset($this->lp_id);
767
        //unset other stuff
768
        return true;
769
    }
770
771
    /**
772
     * Static admin function allowing removal of a learnpath.
773
     *
774
     * @param array  $courseInfo
775
     * @param int    $id         Learnpath ID
776
     * @param string $delete     Whether to delete data or keep it (default: 'keep', others: 'remove')
777
     *
778
     * @return bool True on success, false on failure (might change that to return number of elements deleted)
779
     */
780
    public function delete($courseInfo = null, $id = null, $delete = 'keep')
781
    {
782
        $course_id = api_get_course_int_id();
783
        if (!empty($courseInfo)) {
784
            $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
785
        }
786
787
        // TODO: Implement a way of getting this to work when the current object is not set.
788
        // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
789
        // If an ID is specifically given and the current LP is not the same, prevent delete.
790
        if (!empty($id) && ($id != $this->lp_id)) {
791
            return false;
792
        }
793
794
        $course = api_get_course_entity();
795
        $session = api_get_session_entity();
796
        /* @var CLp $lp */
797
        $lp = Container::getLpRepository()->find($this->lp_id);
798
799
        // 1) Detach the asset to avoid FK constraint
800
        $asset = $lp->getAsset();
801
        if ($asset) {
802
            $lp->setAsset(null);
803
            $em = Database::getManager();
804
            $em->persist($lp);
805
            $em->flush();
806
        }
807
808
        // 2) Now delete the asset and its folder
809
        if ($asset) {
810
            Container::getAssetRepository()->delete($asset);
811
        }
812
813
        Database::getManager()
814
            ->getRepository(ResourceLink::class)
815
            ->removeByResourceInContext($lp, $course, $session);
816
817
        $link_info = GradebookUtils::isResourceInCourseGradebook(
818
            api_get_course_int_id(),
819
            4,
820
            $id,
821
            api_get_session_id()
822
        );
823
824
        if (!empty($link_info)) {
825
            GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
826
        }
827
828
        $trackRepo     = Container::$container->get(TrackEDefaultRepository::class);
829
        $resourceNode  = $lp->getResourceNode();
830
        if ($resourceNode) {
831
            $trackRepo->registerResourceEvent(
832
                $resourceNode,
833
                'deletion',
834
                api_get_user_id(),
835
                api_get_course_int_id(),
836
                api_get_session_id()
837
            );
838
        }
839
    }
840
841
    /**
842
     * Removes all the children of one item - dangerous!
843
     *
844
     * @param int $id Element ID of which children have to be removed
845
     *
846
     * @return int Total number of children removed
847
     */
848
    public function delete_children_items($id)
849
    {
850
        $course_id = $this->course_info['real_id'];
851
852
        $num = 0;
853
        $id = (int) $id;
854
        if (empty($id) || empty($course_id)) {
855
            return false;
856
        }
857
        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
858
        $sql = "SELECT * FROM $lp_item
859
                WHERE parent_item_id = $id";
860
        $res = Database::query($sql);
861
        while ($row = Database::fetch_array($res)) {
862
            $num += $this->delete_children_items($row['iid']);
863
            $sql = "DELETE FROM $lp_item
864
                    WHERE iid = ".$row['iid'];
865
            Database::query($sql);
866
            $num++;
867
        }
868
869
        return $num;
870
    }
871
872
    /**
873
     * Removes an item from the current learnpath.
874
     *
875
     * @param int $id Elem ID (0 if first)
876
     *
877
     * @return int Number of elements moved
878
     *
879
     * @todo implement resource removal
880
     */
881
    public function delete_item($id)
882
    {
883
        $course_id = api_get_course_int_id();
884
        $id = (int) $id;
885
        // TODO: Implement the resource removal.
886
        if (empty($id) || empty($course_id)) {
887
            return false;
888
        }
889
890
        $repo = Container::getLpItemRepository();
891
        $item = $repo->find($id);
892
        if (null === $item) {
893
            return false;
894
        }
895
896
        $em = Database::getManager();
897
        $repo->removeFromTree($item);
898
        $em->flush();
899
        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
900
901
        //Removing prerequisites since the item will not longer exist
902
        $sql_all = "UPDATE $lp_item SET prerequisite = ''
903
                    WHERE prerequisite = '$id'";
904
        Database::query($sql_all);
905
906
        $sql = "UPDATE $lp_item
907
                SET previous_item_id = ".$this->getLastInFirstLevel()."
908
                WHERE lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
909
        Database::query($sql);
910
911
        // Remove from search engine if enabled.
912
        if ('true' === api_get_setting('search_enabled')) {
913
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
914
            $sql = 'SELECT * FROM %s
915
                    WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
916
                    LIMIT 1';
917
            $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
918
            $res = Database::query($sql);
919
            if (Database::num_rows($res) > 0) {
920
                $row2 = Database::fetch_array($res);
921
                $di = new ChamiloIndexer();
922
                $di->remove_document($row2['search_did']);
923
            }
924
            $sql = 'DELETE FROM %s
925
                    WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
926
                    LIMIT 1';
927
            $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
928
            Database::query($sql);
929
        }
930
    }
931
932
    /**
933
     * Updates an item's content in place.
934
     *
935
     * @param int    $id               Element ID
936
     * @param int    $parent           Parent item ID
937
     * @param int    $previous         Previous item ID
938
     * @param string $title            Item title
939
     * @param string $description      Item description
940
     * @param string $prerequisites    Prerequisites (optional)
941
     * @param array  $audio            The array resulting of the $_FILES[mp3] element
942
     * @param int    $max_time_allowed
943
     * @param string $url
944
     *
945
     * @return bool True on success, false on error
946
     */
947
    public function edit_item(
948
        $id,
949
        $parent,
950
        $previous,
951
        $title,
952
        $description,
953
        $prerequisites = '0',
954
        $audio = [],
955
        $max_time_allowed = 0,
956
        $url = ''
957
    ) {
958
        $_course = api_get_course_info();
959
        $id = (int) $id;
960
961
        if (empty($id) || empty($_course)) {
962
            return false;
963
        }
964
        $repo = Container::getLpItemRepository();
965
        /** @var CLpItem $item */
966
        $item = $repo->find($id);
967
        if (null === $item) {
968
            return false;
969
        }
970
971
        $item
972
            ->setTitle($title)
973
            ->setDescription($description)
974
            ->setPrerequisite($prerequisites)
975
            ->setMaxTimeAllowed((int) $max_time_allowed)
976
        ;
977
978
        $em = Database::getManager();
979
        if (!empty($parent)) {
980
            $parent = $repo->find($parent);
981
            $item->setParent($parent);
982
        } else {
983
            $item->setParent(null);
984
        }
985
986
        if (!empty($previous)) {
987
            $previous = $repo->find($previous);
988
            $repo->persistAsNextSiblingOf( $item, $previous);
989
        } else {
990
            $em->persist($item);
991
        }
992
993
        $em->flush();
994
995
        if ('link' === $item->getItemType()) {
996
            $link = new Link();
997
            $linkId = $item->getPath();
998
            $link->updateLink($linkId, $url);
999
        }
1000
    }
1001
1002
    /**
1003
     * Updates an item's prereq in place.
1004
     *
1005
     * @param int    $id              Element ID
1006
     * @param string $prerequisite_id Prerequisite Element ID
1007
     * @param int    $minScore        Prerequisite min score
1008
     * @param int    $maxScore        Prerequisite max score
1009
     *
1010
     * @return bool True on success, false on error
1011
     */
1012
    public function edit_item_prereq($id, $prerequisite_id, $minScore = 0, $maxScore = 100)
1013
    {
1014
        $id = (int) $id;
1015
1016
        if (empty($id)) {
1017
            return false;
1018
        }
1019
        $prerequisite_id = (int) $prerequisite_id;
1020
1021
        if (empty($minScore) || $minScore < 0) {
1022
            $minScore = 0;
1023
        }
1024
1025
        if (empty($maxScore) || $maxScore < 0) {
1026
            $maxScore = 100;
1027
        }
1028
1029
        $minScore = (float) $minScore;
1030
        $maxScore = (float) $maxScore;
1031
1032
        if (empty($prerequisite_id)) {
1033
            $prerequisite_id = 'NULL';
1034
            $minScore = 0;
1035
            $maxScore = 100;
1036
        }
1037
1038
        $table = Database::get_course_table(TABLE_LP_ITEM);
1039
        $sql = " UPDATE $table
1040
                 SET
1041
                    prerequisite = $prerequisite_id ,
1042
                    prerequisite_min_score = $minScore ,
1043
                    prerequisite_max_score = $maxScore
1044
                 WHERE iid = $id";
1045
        Database::query($sql);
1046
1047
        return true;
1048
    }
1049
1050
    /**
1051
     * Get the specific prefix index terms of this learning path.
1052
     *
1053
     * @param string $prefix
1054
     *
1055
     * @return array Array of terms
1056
     */
1057
    public function get_common_index_terms_by_prefix($prefix)
1058
    {
1059
        $terms = get_specific_field_values_list_by_prefix(
1060
            $prefix,
1061
            $this->cc,
1062
            TOOL_LEARNPATH,
1063
            $this->lp_id
1064
        );
1065
        $prefix_terms = [];
1066
        if (!empty($terms)) {
1067
            foreach ($terms as $term) {
1068
                $prefix_terms[] = $term['value'];
1069
            }
1070
        }
1071
1072
        return $prefix_terms;
1073
    }
1074
1075
    /**
1076
     * Gets the number of items currently completed.
1077
     *
1078
     * @param bool Flag to determine the failed status is not considered progressed
1079
     *
1080
     * @return int The number of items currently completed
1081
     */
1082
    public function get_complete_items_count(bool $failedStatusException = false): int
1083
    {
1084
        $i = 0;
1085
        $completedStatusList = [
1086
            'completed',
1087
            'passed',
1088
            'succeeded',
1089
            'browsed',
1090
        ];
1091
1092
        if (!$failedStatusException) {
1093
            $completedStatusList[] = 'failed';
1094
        }
1095
1096
        foreach ($this->items as $id => $dummy) {
1097
            // Trying failed and browsed considered "progressed" as well.
1098
            if ($this->items[$id]->status_is($completedStatusList) &&
1099
                'dir' !== $this->items[$id]->get_type()
1100
            ) {
1101
                $i++;
1102
            }
1103
        }
1104
1105
        return $i;
1106
    }
1107
1108
    /**
1109
     * Gets the current item ID.
1110
     *
1111
     * @return int The current learnpath item id
1112
     */
1113
    public function get_current_item_id()
1114
    {
1115
        $current = 0;
1116
        if (!empty($this->current)) {
1117
            $current = (int) $this->current;
1118
        }
1119
1120
        return $current;
1121
    }
1122
1123
    /**
1124
     * Force to get the first learnpath item id.
1125
     *
1126
     * @return int The current learnpath item id
1127
     */
1128
    public function get_first_item_id()
1129
    {
1130
        $current = 0;
1131
        if (is_array($this->ordered_items)) {
1132
            $current = $this->ordered_items[0];
1133
        }
1134
1135
        return $current;
1136
    }
1137
1138
    /**
1139
     * Gets the total number of items available for viewing in this SCORM.
1140
     *
1141
     * @return int The total number of items
1142
     */
1143
    public function get_total_items_count()
1144
    {
1145
        return count($this->items);
1146
    }
1147
1148
    /**
1149
     * Gets the total number of items available for viewing in this SCORM but without chapters.
1150
     *
1151
     * @return int The total no-chapters number of items
1152
     */
1153
    public function getTotalItemsCountWithoutDirs()
1154
    {
1155
        $total = 0;
1156
        $typeListNotToCount = self::getChapterTypes();
1157
        foreach ($this->items as $temp2) {
1158
            if (!in_array($temp2->get_type(), $typeListNotToCount)) {
1159
                $total++;
1160
            }
1161
        }
1162
1163
        return $total;
1164
    }
1165
1166
    /**
1167
     *  Sets the first element URL.
1168
     */
1169
    public function first()
1170
    {
1171
        if ($this->debug > 0) {
1172
            error_log('In learnpath::first()', 0);
1173
            error_log('$this->last_item_seen '.$this->last_item_seen);
1174
        }
1175
1176
        // Test if the last_item_seen exists and is not a dir.
1177
        if (0 == count($this->ordered_items)) {
1178
            $this->index = 0;
1179
        }
1180
1181
        if (!empty($this->last_item_seen) &&
1182
            !empty($this->items[$this->last_item_seen]) &&
1183
            'dir' !== $this->items[$this->last_item_seen]->get_type()
1184
            //with this change (below) the LP will NOT go to the next item, it will take lp item we left
1185
            //&& !$this->items[$this->last_item_seen]->is_done()
1186
        ) {
1187
            if ($this->debug > 2) {
1188
                error_log(
1189
                    'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
1190
                    $this->items[$this->last_item_seen]->get_type()
1191
                );
1192
            }
1193
            $index = -1;
1194
            foreach ($this->ordered_items as $myindex => $item_id) {
1195
                if ($item_id == $this->last_item_seen) {
1196
                    $index = $myindex;
1197
                    break;
1198
                }
1199
            }
1200
            if (-1 == $index) {
1201
                // Index hasn't changed, so item not found - panic (this shouldn't happen).
1202
                if ($this->debug > 2) {
1203
                    error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
1204
                }
1205
1206
                return false;
1207
            } else {
1208
                $this->last = $this->last_item_seen;
1209
                $this->current = $this->last_item_seen;
1210
                $this->index = $index;
1211
            }
1212
        } else {
1213
            if ($this->debug > 2) {
1214
                error_log('In learnpath::first() - No last item seen', 0);
1215
            }
1216
            $index = 0;
1217
            // Loop through all ordered items and stop at the first item that is
1218
            // not a directory *and* that has not been completed yet.
1219
            while (!empty($this->ordered_items[$index]) &&
1220
                is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
1221
                (
1222
                    'dir' === $this->items[$this->ordered_items[$index]]->get_type() ||
1223
                    true === $this->items[$this->ordered_items[$index]]->is_done()
1224
                ) && $index < $this->max_ordered_items
1225
            ) {
1226
                $index++;
1227
            }
1228
1229
            $this->last = $this->current;
1230
            // current is
1231
            $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
1232
            $this->index = $index;
1233
            if ($this->debug > 2) {
1234
                error_log('$index '.$index);
1235
                error_log('In learnpath::first() - No last item seen');
1236
                error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
1237
            }
1238
        }
1239
        if ($this->debug > 2) {
1240
            error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
1241
        }
1242
    }
1243
1244
    /**
1245
     * Gets the js library from the database.
1246
     *
1247
     * @return string The name of the javascript library to be used
1248
     */
1249
    public function get_js_lib()
1250
    {
1251
        $lib = '';
1252
        if (!empty($this->js_lib)) {
1253
            $lib = $this->js_lib;
1254
        }
1255
1256
        return $lib;
1257
    }
1258
1259
    /**
1260
     * Gets the learnpath database ID.
1261
     *
1262
     * @return int Learnpath ID in the lp table
1263
     */
1264
    public function get_id()
1265
    {
1266
        if (!empty($this->lp_id)) {
1267
            return (int) $this->lp_id;
1268
        }
1269
1270
        return 0;
1271
    }
1272
1273
    /**
1274
     * Gets the last element URL.
1275
     *
1276
     * @return string URL to load into the viewer
1277
     */
1278
    public function get_last()
1279
    {
1280
        // This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
1281
        if (count($this->ordered_items) > 0) {
1282
            $this->index = count($this->ordered_items) - 1;
1283
1284
            return $this->ordered_items[$this->index];
1285
        }
1286
1287
        return false;
1288
    }
1289
1290
    /**
1291
     * Get the last element in the first level.
1292
     * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
1293
     *
1294
     * @return mixed
1295
     */
1296
    public function getLastInFirstLevel()
1297
    {
1298
        try {
1299
            $lastId = Database::getManager()
1300
                ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
1301
                WHERE i.lp = :lp AND i.parent IS NULL AND i.itemType != :type ORDER BY i.displayOrder DESC')
1302
                ->setMaxResults(1)
1303
                ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
1304
                ->getSingleScalarResult();
1305
1306
            return $lastId;
1307
        } catch (Exception $exception) {
1308
            return 0;
1309
        }
1310
    }
1311
1312
    /**
1313
     * Gets the navigation bar for the learnpath display screen.
1314
     *
1315
     * @param string $barId
1316
     *
1317
     * @return string The HTML string to use as a navigation bar
1318
     */
1319
    public function get_navigation_bar($barId = '')
1320
    {
1321
        if (empty($barId)) {
1322
            $barId = 'control-top';
1323
        }
1324
        $lpId = $this->lp_id;
1325
        $mycurrentitemid = $this->get_current_item_id();
1326
        $reportingText = get_lang('Reporting');
1327
        $previousText = get_lang('Previous');
1328
        $nextText = get_lang('Next');
1329
        $fullScreenText = get_lang('Back to normal screen');
1330
1331
        $settings = api_get_setting('lp.lp_view_settings', true);
1332
        $display = $settings['display'] ?? false;
1333
        $icon = Display::getMdiIcon('information');
1334
1335
        $reportingIcon = '
1336
            <a class="icon-toolbar"
1337
                id="stats_link"
1338
                href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
1339
                onclick="window.parent.API.save_asset(); return true;"
1340
                target="content_name" title="'.$reportingText.'">
1341
                '.$icon.'<span class="sr-only">'.$reportingText.'</span>
1342
            </a>';
1343
1344
        if (!empty($display)) {
1345
            $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
1346
            if (false === $showReporting) {
1347
                $reportingIcon = '';
1348
            }
1349
        }
1350
1351
        $hideArrows = false;
1352
        if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
1353
            $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
1354
        }
1355
1356
        $previousIcon = '';
1357
        $nextIcon = '';
1358
        if (false === $hideArrows) {
1359
            $icon = Display::getMdiIcon('chevron-left');
1360
            $previousIcon = '
1361
                <button class="icon-toolbar" id="scorm-previous" type="button"
1362
                    onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
1363
                    '.$icon.'<span class="sr-only">'.$previousText.'</span>
1364
                </button>';
1365
1366
            $icon = Display::getMdiIcon('chevron-right');
1367
            $nextIcon = '
1368
                <button class="icon-toolbar" id="scorm-next" type="button"
1369
                    onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
1370
                    '.$icon.'<span class="sr-only">'.$nextText.'</span>
1371
                </button>';
1372
        }
1373
1374
        if ('fullscreen' === $this->mode) {
1375
            $icon = Display::getMdiIcon('view-column');
1376
            $navbar = '
1377
                  <span id="'.$barId.'" class="buttons">
1378
                    '.$reportingIcon.'
1379
                    '.$previousIcon.'
1380
                    '.$nextIcon.'
1381
                    <a class="icon-toolbar" id="view-embedded"
1382
                        href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
1383
                        '.$icon.'<span class="sr-only">'.$fullScreenText.'</span>
1384
                    </a>
1385
                  </span>';
1386
        } else {
1387
            $navbar = '
1388
                 <span id="'.$barId.'" class="buttons text-right">
1389
                    '.$reportingIcon.'
1390
                    '.$previousIcon.'
1391
                    '.$nextIcon.'
1392
                </span>';
1393
        }
1394
1395
        return $navbar;
1396
    }
1397
1398
    /**
1399
     * Gets the next resource in queue (url).
1400
     *
1401
     * @return string URL to load into the viewer
1402
     */
1403
    public function get_next_index()
1404
    {
1405
        // TODO
1406
        $index = $this->index;
1407
        $index++;
1408
        while (
1409
            !empty($this->ordered_items[$index]) && ('dir' == $this->items[$this->ordered_items[$index]]->get_type()) &&
1410
            $index < $this->max_ordered_items
1411
        ) {
1412
            $index++;
1413
            if ($index == $this->max_ordered_items) {
1414
                if ('dir' === $this->items[$this->ordered_items[$index]]->get_type()) {
1415
                    return $this->index;
1416
                }
1417
1418
                return $index;
1419
            }
1420
        }
1421
        if (empty($this->ordered_items[$index])) {
1422
            return $this->index;
1423
        }
1424
1425
        return $index;
1426
    }
1427
1428
    /**
1429
     * Gets item_id for the next element.
1430
     *
1431
     * @return int Next item (DB) ID
1432
     */
1433
    public function get_next_item_id()
1434
    {
1435
        $new_index = $this->get_next_index();
1436
        if (!empty($new_index)) {
1437
            if (isset($this->ordered_items[$new_index])) {
1438
                return $this->ordered_items[$new_index];
1439
            }
1440
        }
1441
1442
        return 0;
1443
    }
1444
1445
    /**
1446
     * Returns the package type ('scorm','aicc','scorm2004','ppt'...).
1447
     *
1448
     * Generally, the package provided is in the form of a zip file, so the function
1449
     * has been written to test a zip file. If not a zip, the function will return the
1450
     * default return value: ''
1451
     *
1452
     * @param string $filePath the path to the file
1453
     * @param string $file_name the original name of the file
1454
     *
1455
     * @return string 'scorm','aicc','scorm2004','error-empty-package'
1456
     *                if the package is empty, or '' if the package cannot be recognized
1457
     */
1458
    public static function getPackageType($filePath, $file_name)
1459
    {
1460
        // Get name of the zip file without the extension.
1461
        $file_info = pathinfo($file_name);
1462
        $extension = $file_info['extension']; // Extension only.
1463
        if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
1464
                'dll',
1465
                'exe',
1466
            ])) {
1467
            return 'oogie';
1468
        }
1469
        if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
1470
                'dll',
1471
                'exe',
1472
            ])) {
1473
            return 'woogie';
1474
        }
1475
1476
        $zipFile = new ZipFile();
1477
        $zipFile->openFile($filePath);
1478
        $zipContentArray = $zipFile->getEntries();
1479
        $package_type = '';
1480
        $manifest = '';
1481
        $aicc_match_crs = 0;
1482
        $aicc_match_au = 0;
1483
        $aicc_match_des = 0;
1484
        $aicc_match_cst = 0;
1485
        $countItems = 0;
1486
        // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
1487
        if ($zipContentArray) {
1488
            $countItems = count($zipContentArray);
1489
            if ($countItems > 0) {
1490
                foreach ($zipContentArray as $thisContent) {
1491
                    $fileName = basename($thisContent->getName());
1492
                    if (preg_match('~.(php.*|phtml)$~i', $fileName)) {
1493
                        // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
1494
                    } elseif (false !== stristr($fileName, 'imsmanifest.xml')) {
1495
                        $manifest = $fileName; // Just the relative directory inside scorm/
1496
                        $package_type = 'scorm';
1497
                        break; // Exit the foreach loop.
1498
                    } elseif (
1499
                        preg_match('/aicc\//i', $fileName) ||
1500
                        in_array(
1501
                            strtolower(pathinfo($fileName, PATHINFO_EXTENSION)),
1502
                            ['crs', 'au', 'des', 'cst']
1503
                        )
1504
                    ) {
1505
                        $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
1506
                        switch ($ext) {
1507
                            case 'crs':
1508
                                $aicc_match_crs = 1;
1509
                                break;
1510
                            case 'au':
1511
                                $aicc_match_au = 1;
1512
                                break;
1513
                            case 'des':
1514
                                $aicc_match_des = 1;
1515
                                break;
1516
                            case 'cst':
1517
                                $aicc_match_cst = 1;
1518
                                break;
1519
                            default:
1520
                                break;
1521
                        }
1522
                        //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
1523
                    } else {
1524
                        $package_type = '';
1525
                    }
1526
                }
1527
            }
1528
        }
1529
1530
        if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
1531
            // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
1532
            $package_type = 'aicc';
1533
        }
1534
1535
        // Try with chamilo course builder
1536
        if (empty($package_type)) {
1537
            // Sometimes users will try to upload an empty zip, or a zip with
1538
            // only a folder. Catch that and make the calling function aware.
1539
            // If the single file was the imsmanifest.xml, then $package_type
1540
            // would be 'scorm' and we wouldn't be here.
1541
            if ($countItems < 2) {
1542
                return 'error-empty-package';
1543
            }
1544
            $package_type = 'chamilo';
1545
        }
1546
1547
        return $package_type;
1548
    }
1549
1550
    /**
1551
     * Gets the previous resource in queue (url). Also initialises time values for this viewing.
1552
     *
1553
     * @return string URL to load into the viewer
1554
     */
1555
    public function get_previous_index()
1556
    {
1557
        $index = $this->index;
1558
        if (isset($this->ordered_items[$index - 1])) {
1559
            $index--;
1560
            while (isset($this->ordered_items[$index]) &&
1561
                ('dir' === $this->items[$this->ordered_items[$index]]->get_type())
1562
            ) {
1563
                $index--;
1564
                if ($index < 0) {
1565
                    return $this->index;
1566
                }
1567
            }
1568
        }
1569
1570
        return $index;
1571
    }
1572
1573
    /**
1574
     * Gets item_id for the next element.
1575
     *
1576
     * @return int Previous item (DB) ID
1577
     */
1578
    public function get_previous_item_id()
1579
    {
1580
        $index = $this->get_previous_index();
1581
1582
        return $this->ordered_items[$index];
1583
    }
1584
1585
    /**
1586
     * Returns the HTML necessary to print a mediaplayer block inside a page.
1587
     *
1588
     * @param int    $lpItemId
1589
     * @param string $autostart
1590
     *
1591
     * @return string The mediaplayer HTML
1592
     */
1593
    public function get_mediaplayer($lpItemId, $autostart = 'true')
1594
    {
1595
        $courseInfo = api_get_course_info();
1596
        $lpItemId = (int) $lpItemId;
1597
1598
        if (empty($courseInfo) || empty($lpItemId)) {
1599
            return '';
1600
        }
1601
        $item = $this->items[$lpItemId] ?? null;
1602
1603
        if (empty($item)) {
1604
            return '';
1605
        }
1606
1607
        $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
1608
        $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
1609
        $itemViewId = (int) $item->db_item_view_id;
1610
1611
        // Getting all the information about the item.
1612
        $sql = "SELECT lp_view.status
1613
                FROM $tbl_lp_item as lpi
1614
                INNER JOIN $tbl_lp_item_view as lp_view
1615
                ON (lpi.iid = lp_view.lp_item_id)
1616
                WHERE
1617
                    lp_view.iid = $itemViewId AND
1618
                    lpi.iid = $lpItemId
1619
                ";
1620
        $result = Database::query($sql);
1621
        $row = Database::fetch_assoc($result);
1622
        $output = '';
1623
        $audio = $item->audio;
1624
1625
        if (!empty($audio)) {
1626
            $list = $_SESSION['oLP']->get_toc();
1627
1628
            switch ($item->get_type()) {
1629
                case 'quiz':
1630
                    $type_quiz = false;
1631
                    foreach ($list as $toc) {
1632
                        if ($toc['id'] == $_SESSION['oLP']->current) {
1633
                            $type_quiz = true;
1634
                        }
1635
                    }
1636
1637
                    if ($type_quiz) {
1638
                        if (1 == $_SESSION['oLP']->prevent_reinit) {
1639
                            $autostart_audio = 'completed' === $row['status'] ? 'false' : 'true';
1640
                        } else {
1641
                            $autostart_audio = $autostart;
1642
                        }
1643
                    }
1644
                    break;
1645
                case TOOL_READOUT_TEXT:
1646
                    $autostart_audio = 'false';
1647
                    break;
1648
                default:
1649
                    $autostart_audio = 'true';
1650
            }
1651
1652
            $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document'.$audio;
1653
            $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document'.$audio.'?'.api_get_cidreq();
1654
1655
            $player = Display::getMediaPlayer(
1656
                $file,
1657
                [
1658
                    'id' => 'lp_audio_media_player',
1659
                    'url' => $url,
1660
                    'autoplay' => $autostart_audio,
1661
                    'width' => '100%',
1662
                ]
1663
            );
1664
1665
            // The mp3 player.
1666
            $output = '<div id="container">';
1667
            $output .= $player;
1668
            $output .= '</div>';
1669
        }
1670
1671
        return $output;
1672
    }
1673
1674
    /**
1675
     * @param int    $studentId
1676
     * @param int    $prerequisite
1677
     * @param Course $course
1678
     * @param int    $sessionId
1679
     *
1680
     * @return bool
1681
     */
1682
    public static function isBlockedByPrerequisite(
1683
        $studentId,
1684
        $prerequisite,
1685
        Course $course,
1686
        $sessionId
1687
    ) {
1688
        $courseId = $course->getId();
1689
1690
        $allow = ('true' === api_get_setting('lp.allow_teachers_to_access_blocked_lp_by_prerequisite'));
1691
        if ($allow) {
1692
            if (api_is_allowed_to_edit() ||
1693
                api_is_platform_admin(true) ||
1694
                api_is_drh() ||
1695
                api_is_coach($sessionId, $courseId, false)
1696
            ) {
1697
                return false;
1698
            }
1699
        }
1700
1701
        $isBlocked = false;
1702
        if (!empty($prerequisite)) {
1703
            $progress = self::getProgress(
1704
                $prerequisite,
1705
                $studentId,
1706
                $courseId,
1707
                $sessionId
1708
            );
1709
            if ($progress < 100) {
1710
                $isBlocked = true;
1711
            }
1712
1713
            if (Tracking::minimumTimeAvailable($sessionId, $courseId)) {
1714
                // Block if it does not exceed minimum time
1715
                // Minimum time (in minutes) to pass the learning path
1716
                $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
1717
1718
                if ($accumulateWorkTime > 0) {
1719
                    // Total time in course (sum of times in learning paths from course)
1720
                    $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
1721
1722
                    // Connect with the plugin_licences_course_session table
1723
                    // which indicates what percentage of the time applies
1724
                    // Minimum connection percentage
1725
                    $perc = 100;
1726
                    // Time from the course
1727
                    $tc = $accumulateWorkTimeTotal;
1728
1729
                    // Percentage of the learning paths
1730
                    $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
1731
                    // Minimum time for each learning path
1732
                    $accumulateWorkTime = ($pl * $tc * $perc / 100);
1733
1734
                    // Spent time (in seconds) so far in the learning path
1735
                    $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
1736
                    $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
1737
1738
                    if ($lpTime < ($accumulateWorkTime * 60)) {
1739
                        $isBlocked = true;
1740
                    }
1741
                }
1742
            }
1743
        }
1744
1745
        return $isBlocked;
1746
    }
1747
1748
    /**
1749
     * Checks if the learning path is visible for student after the progress
1750
     * of its prerequisite is completed, considering the time availability and
1751
     * the LP visibility.
1752
     */
1753
    public static function is_lp_visible_for_student(CLp $lp, $student_id, Course $course, SessionEntity $session = null): bool
1754
    {
1755
        $sessionId = $session ? $session->getId() : 0;
1756
        $courseId = $course->getId();
1757
        $visibility = $lp->isVisible($course, $session);
1758
1759
        // If the item was deleted.
1760
        if (false === $visibility) {
1761
            return false;
1762
        }
1763
1764
        $now = time();
1765
        if ($lp->hasCategory()) {
1766
            $category = $lp->getCategory();
1767
1768
            if (false === self::categoryIsVisibleForStudent(
1769
                    $category,
1770
                    api_get_user_entity($student_id),
1771
                    $course,
1772
                    $session
1773
                )) {
1774
                return false;
1775
            }
1776
1777
            $prerequisite = $lp->getPrerequisite();
1778
            $is_visible = true;
1779
1780
            $isBlocked = self::isBlockedByPrerequisite(
1781
                $student_id,
1782
                $prerequisite,
1783
                $course,
1784
                $sessionId
1785
            );
1786
1787
            if ($isBlocked) {
1788
                $is_visible = false;
1789
            }
1790
1791
            // Also check the time availability of the LP
1792
            if ($is_visible) {
1793
                // Adding visibility restrictions
1794
                if (null !== $lp->getPublishedOn()) {
1795
                    if ($now < $lp->getPublishedOn()->getTimestamp()) {
1796
                        $is_visible = false;
1797
                    }
1798
                }
1799
                // Blocking empty start times see BT#2800
1800
                global $_custom;
1801
                if (isset($_custom['lps_hidden_when_no_start_date']) &&
1802
                    $_custom['lps_hidden_when_no_start_date']
1803
                ) {
1804
                    if (null !== $lp->getPublishedOn()) {
1805
                        $is_visible = false;
1806
                    }
1807
                }
1808
1809
                if (null !== $lp->getExpiredOn()) {
1810
                    if ($now > $lp->getExpiredOn()->getTimestamp()) {
1811
                        $is_visible = false;
1812
                    }
1813
                }
1814
            }
1815
1816
            if ($is_visible) {
1817
                $subscriptionSettings = self::getSubscriptionSettings();
1818
1819
                // Check if the subscription users/group to a LP is ON
1820
                if (1 == $lp->getSubscribeUsers() &&
1821
                    true === $subscriptionSettings['allow_add_users_to_lp']
1822
                ) {
1823
                    // Try group
1824
                    $is_visible = false;
1825
                    // Checking only the user visibility
1826
                    $userVisibility = self::isUserSubscribedToLp($lp, $student_id, $course, $session);
1827
1828
                    if (true === $userVisibility) {
1829
                        return true;
1830
                    }
1831
1832
                    // Try with groups
1833
                    $groupVisibility = self::isGroupSubscribedToLp($lp, $student_id, $course, $session);
1834
                    if (true === $groupVisibility) {
1835
                        return true;
1836
                    }
1837
                }
1838
            }
1839
1840
            return $is_visible;
1841
        } else {
1842
1843
            $is_visible = true;
1844
            $subscriptionSettings = self::getSubscriptionSettings();
1845
            // Check if the subscription users/group to a LP is ON
1846
            if (1 == $lp->getSubscribeUsers() &&
1847
                true === $subscriptionSettings['allow_add_users_to_lp']
1848
            ) {
1849
                $is_visible = false;
1850
                $userVisibility = self::isUserSubscribedToLp($lp, $student_id, $course, $session);
1851
1852
                if (true === $userVisibility) {
1853
                    return true;
1854
                }
1855
1856
                // Try with groups
1857
                $groupVisibility = self::isGroupSubscribedToLp($lp, $student_id, $course, $session);
1858
                if (true === $groupVisibility) {
1859
                    return true;
1860
                }
1861
            }
1862
1863
            return $is_visible;
1864
        }
1865
1866
        return true;
0 ignored issues
show
Unused Code introduced by
return true is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1867
    }
1868
1869
    public static function isGroupSubscribedToLp(
1870
        CLp $lp,
1871
        int $studentId,
1872
        Course $course,
1873
        SessionEntity $session = null
1874
    ): bool {
1875
1876
        // Subscribed groups to a LP
1877
        $links = $lp->getResourceNode()->getResourceLinks();
1878
        $selectedChoices = [];
1879
        foreach ($links as $link) {
1880
            if (null !== $link->getGroup()) {
1881
                $selectedChoices[] = $link->getGroup()->getIid();
1882
            }
1883
        }
1884
1885
        $isVisible = false;
1886
        $userGroups = GroupManager::getAllGroupPerUserSubscription($studentId, $course->getId());
1887
        if (!empty($userGroups)) {
1888
            foreach ($userGroups as $groupInfo) {
1889
                $groupId = $groupInfo['iid'];
1890
                if (in_array($groupId, $selectedChoices)) {
1891
                    $isVisible = true;
1892
                    break;
1893
                }
1894
            }
1895
        }
1896
1897
        return $isVisible;
1898
    }
1899
1900
    public static function isUserSubscribedToLp(
1901
        CLp $lp,
1902
        int $studentId,
1903
        Course $course,
1904
        SessionEntity $session = null
1905
    ): bool {
1906
1907
        $isVisible = true;
1908
        $em = Database::getManager();
1909
1910
        /** @var CLpRelUserRepository $cLpRelUserRepo */
1911
        $cLpRelUserRepo = $em->getRepository(CLpRelUser::class);
1912
1913
        // Getting subscribed users to a LP.
1914
        $subscribedUsersInLp = $cLpRelUserRepo->getUsersSubscribedToItem(
1915
            $lp,
1916
            $course,
1917
            $session
1918
        );
1919
1920
        $selectedChoices = [];
1921
        foreach ($subscribedUsersInLp as $users) {
1922
            /** @var \Chamilo\CourseBundle\Entity\CLpRelUser $users */
1923
            $selectedChoices[] = $users->getUser()->getId();
1924
        }
1925
1926
        if (!api_is_allowed_to_edit() && !in_array($studentId, $selectedChoices)) {
1927
            $isVisible = false;
1928
        }
1929
1930
        return $isVisible;
1931
    }
1932
1933
    /**
1934
     * @param int $lpId
1935
     * @param int $userId
1936
     * @param int $courseId
1937
     * @param int $sessionId
1938
     *
1939
     * @return int
1940
     */
1941
    public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
1942
    {
1943
        $lpId = (int) $lpId;
1944
        $userId = (int) $userId;
1945
        $courseId = (int) $courseId;
1946
        $sessionId = (int) $sessionId;
1947
1948
        $sessionCondition = api_get_session_condition($sessionId);
1949
        $table = Database::get_course_table(TABLE_LP_VIEW);
1950
        $sql = "SELECT progress FROM $table
1951
                WHERE
1952
                    c_id = $courseId AND
1953
                    lp_id = $lpId AND
1954
                    user_id = $userId $sessionCondition ";
1955
        $res = Database::query($sql);
1956
1957
        $progress = 0;
1958
        if (Database::num_rows($res) > 0) {
1959
            $row = Database::fetch_array($res);
1960
            $progress = (int) $row['progress'];
1961
        }
1962
1963
        return $progress;
1964
    }
1965
1966
    /**
1967
     * @param array $lpList
1968
     * @param int   $userId
1969
     * @param int   $courseId
1970
     * @param int   $sessionId
1971
     *
1972
     * @return array
1973
     */
1974
    public static function getProgressFromLpList($lpList, $userId, $courseId, $sessionId = 0)
1975
    {
1976
        $lpList = array_map('intval', $lpList);
1977
        if (empty($lpList)) {
1978
            return [];
1979
        }
1980
1981
        $lpList = implode("','", $lpList);
1982
1983
        $userId = (int) $userId;
1984
        $courseId = (int) $courseId;
1985
        $sessionId = (int) $sessionId;
1986
1987
        $sessionCondition = api_get_session_condition($sessionId);
1988
        $table = Database::get_course_table(TABLE_LP_VIEW);
1989
        $sql = "SELECT lp_id, progress FROM $table
1990
                WHERE
1991
                    c_id = $courseId AND
1992
                    lp_id IN ('".$lpList."') AND
1993
                    user_id = $userId $sessionCondition ";
1994
        $res = Database::query($sql);
1995
1996
        if (Database::num_rows($res) > 0) {
1997
            $list = [];
1998
            while ($row = Database::fetch_array($res)) {
1999
                $list[$row['lp_id']] = $row['progress'];
2000
            }
2001
2002
            return $list;
2003
        }
2004
2005
        return [];
2006
    }
2007
2008
    /**
2009
     * Displays a progress bar
2010
     * completed so far.
2011
     *
2012
     * @param int    $percentage Progress value to display
2013
     * @param string $text_add   Text to display near the progress value
2014
     *
2015
     * @return string HTML string containing the progress bar
2016
     */
2017
    public static function get_progress_bar($percentage = -1, $text_add = '')
2018
    {
2019
        $text = $percentage.$text_add;
2020
2021
        return '<div class="p-progressbar p-progressbar-determinate"
2022
            role="progressbar" aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100">
2023
            <div id="progress_bar_value" class="p-progressbar-value" style="width: '.$text.';">
2024
                 <div class="p-progressbar-label">'.$text.'</div>
2025
            </div>
2026
        </div>';
2027
    }
2028
2029
    /**
2030
     * @param string $mode can be '%' or 'abs'
2031
     *                     otherwise this value will be used $this->progress_bar_mode
2032
     *
2033
     * @return string
2034
     */
2035
    public function getProgressBar($mode = null)
2036
    {
2037
        [$percentage, $text_add] = $this->get_progress_bar_text($mode);
2038
2039
        return self::get_progress_bar($percentage, $text_add);
2040
    }
2041
2042
    /**
2043
     * Gets the progress bar info to display inside the progress bar.
2044
     * Also used by scorm_api.php.
2045
     *
2046
     * @param string $mode Mode of display (can be '%' or 'abs').abs means
2047
     *                     we display a number of completed elements per total elements
2048
     * @param int    $add  Additional steps to fake as completed
2049
     *
2050
     * @return array Percentage or number and symbol (% or /xx)
2051
     */
2052
    public function get_progress_bar_text($mode = '', $add = 0)
2053
    {
2054
        if (empty($mode)) {
2055
            $mode = $this->progress_bar_mode;
2056
        }
2057
        $text = '';
2058
        $percentage = 0;
2059
        // If the option to use the score as progress is set for this learning
2060
        // path, then the rules are completely different: we assume only one
2061
        // item exists and the progress of the LP depends on the score
2062
        $scoreAsProgressSetting = ('true' === api_get_setting('lp.lp_score_as_progress_enable'));
2063
        if (true === $scoreAsProgressSetting) {
2064
            $scoreAsProgress = $this->getUseScoreAsProgress();
2065
            if ($scoreAsProgress) {
2066
                // Get single item's score
2067
                $itemId = $this->get_current_item_id();
2068
                $item = $this->getItem($itemId);
2069
                $score = $item->get_score();
2070
                $maxScore = $item->get_max();
2071
                if ($mode = '%') {
2072
                    if (!empty($maxScore)) {
2073
                        $percentage = ((float) $score / (float) $maxScore) * 100;
2074
                    }
2075
                    $percentage = number_format($percentage, 0);
2076
                    $text = '%';
2077
                } else {
2078
                    $percentage = $score;
2079
                    $text = '/'.$maxScore;
2080
                }
2081
2082
                return [$percentage, $text];
2083
            }
2084
        }
2085
        // otherwise just continue the normal processing of progress
2086
        $total_items = $this->getTotalItemsCountWithoutDirs();
2087
        $completeItems = $this->get_complete_items_count();
2088
        if (0 != $add) {
2089
            $completeItems += $add;
2090
        }
2091
        if ($completeItems > $total_items) {
2092
            $completeItems = $total_items;
2093
        }
2094
        if ('%' === $mode) {
2095
            if ($total_items > 0) {
2096
                $percentage = ((float) $completeItems / (float) $total_items) * 100;
2097
            }
2098
            $percentage = number_format($percentage, 0);
2099
            $text = '%';
2100
        } elseif ('abs' === $mode) {
2101
            $percentage = $completeItems;
2102
            $text = '/'.$total_items;
2103
        }
2104
2105
        return [
2106
            $percentage,
2107
            $text,
2108
        ];
2109
    }
2110
2111
    /**
2112
     * Gets the progress bar mode.
2113
     *
2114
     * @return string The progress bar mode attribute
2115
     */
2116
    public function get_progress_bar_mode()
2117
    {
2118
        if (!empty($this->progress_bar_mode)) {
2119
            return $this->progress_bar_mode;
2120
        }
2121
2122
        return '%';
2123
    }
2124
2125
    /**
2126
     * Gets the learnpath theme (remote or local).
2127
     *
2128
     * @return string Learnpath theme
2129
     */
2130
    public function get_theme()
2131
    {
2132
        if (!empty($this->theme)) {
2133
            return $this->theme;
2134
        }
2135
2136
        return '';
2137
    }
2138
2139
    /**
2140
     * Gets the learnpath session id.
2141
     *
2142
     * @return int
2143
     */
2144
    public function get_lp_session_id()
2145
    {
2146
        $lp = Container::getLpRepository()->find($this->lp_id);
2147
        if ($lp) {
2148
            /* @var ResourceNode $resourceNode */
2149
            $resourceNode = $lp->getResourceNode();
2150
            if ($resourceNode) {
0 ignored issues
show
introduced by
$resourceNode is of type Chamilo\CoreBundle\Entity\ResourceNode, thus it always evaluated to true.
Loading history...
2151
                $link = $resourceNode->getResourceLinks()->first();
2152
                if ($link && $link->getSession()) {
2153
2154
                    return (int) $link->getSession()->getId();
2155
                }
2156
            }
2157
        }
2158
2159
        return 0;
2160
    }
2161
2162
    /**
2163
     * Generate a new prerequisites string for a given item. If this item was a sco and
2164
     * its prerequisites were strings (instead of IDs), then transform those strings into
2165
     * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
2166
     * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
2167
     * same rule as the scormExport() method.
2168
     *
2169
     * @param int $item_id Item ID
2170
     *
2171
     * @return string Prerequisites string ready for the export as SCORM
2172
     */
2173
    public function get_scorm_prereq_string($item_id)
2174
    {
2175
        if ($this->debug > 0) {
2176
            error_log('In learnpath::get_scorm_prereq_string()');
2177
        }
2178
        if (!is_object($this->items[$item_id])) {
2179
            return false;
2180
        }
2181
        /** @var learnpathItem $oItem */
2182
        $oItem = $this->items[$item_id];
2183
        $prereq = $oItem->get_prereq_string();
2184
2185
        if (empty($prereq)) {
2186
            return '';
2187
        }
2188
        if (preg_match('/^\d+$/', $prereq) &&
2189
            isset($this->items[$prereq]) &&
2190
            is_object($this->items[$prereq])
2191
        ) {
2192
            // If the prerequisite is a simple integer ID and this ID exists as an item ID,
2193
            // then simply return it (with the ITEM_ prefix).
2194
            //return 'ITEM_' . $prereq;
2195
            return $this->items[$prereq]->ref;
2196
        } else {
2197
            if (isset($this->refs_list[$prereq])) {
2198
                // It's a simple string item from which the ID can be found in the refs list,
2199
                // so we can transform it directly to an ID for export.
2200
                return $this->items[$this->refs_list[$prereq]]->ref;
2201
            } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
2202
                return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
2203
            } else {
2204
                // The last case, if it's a complex form, then find all the IDs (SCORM strings)
2205
                // and replace them, one by one, by the internal IDs (chamilo db)
2206
                // TODO: Modify the '*' replacement to replace the multiplier in front of it
2207
                // by a space as well.
2208
                $find = [
2209
                    '&',
2210
                    '|',
2211
                    '~',
2212
                    '=',
2213
                    '<>',
2214
                    '{',
2215
                    '}',
2216
                    '*',
2217
                    '(',
2218
                    ')',
2219
                ];
2220
                $replace = [
2221
                    ' ',
2222
                    ' ',
2223
                    ' ',
2224
                    ' ',
2225
                    ' ',
2226
                    ' ',
2227
                    ' ',
2228
                    ' ',
2229
                    ' ',
2230
                    ' ',
2231
                ];
2232
                $prereq_mod = str_replace($find, $replace, $prereq);
2233
                $ids = explode(' ', $prereq_mod);
2234
                foreach ($ids as $id) {
2235
                    $id = trim($id);
2236
                    if (isset($this->refs_list[$id])) {
2237
                        $prereq = preg_replace(
2238
                            '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
2239
                            'ITEM_'.$this->refs_list[$id],
2240
                            $prereq
2241
                        );
2242
                    }
2243
                }
2244
2245
                return $prereq;
2246
            }
2247
        }
2248
    }
2249
2250
    /**
2251
     * Returns the XML DOM document's node.
2252
     *
2253
     * @param resource $children Reference to a list of objects to search for the given ITEM_*
2254
     * @param string   $id       The identifier to look for
2255
     *
2256
     * @return mixed The reference to the element found with that identifier. False if not found
2257
     */
2258
    public function get_scorm_xml_node(&$children, $id)
2259
    {
2260
        for ($i = 0; $i < $children->length; $i++) {
2261
            $item_temp = $children->item($i);
2262
            if ('item' === $item_temp->nodeName) {
2263
                if ($item_temp->getAttribute('identifier') == $id) {
2264
                    return $item_temp;
2265
                }
2266
            }
2267
            $subchildren = $item_temp->childNodes;
2268
            if ($subchildren && $subchildren->length > 0) {
2269
                $val = $this->get_scorm_xml_node($subchildren, $id);
2270
                if (is_object($val)) {
2271
                    return $val;
2272
                }
2273
            }
2274
        }
2275
2276
        return false;
2277
    }
2278
2279
    /**
2280
     * Gets the status list for all LP's items.
2281
     *
2282
     * @return array Array of [index] => [item ID => current status]
2283
     */
2284
    public function get_items_status_list()
2285
    {
2286
        $list = [];
2287
        foreach ($this->ordered_items as $item_id) {
2288
            $list[] = [
2289
                $item_id => $this->items[$item_id]->get_status(),
2290
            ];
2291
        }
2292
2293
        return $list;
2294
    }
2295
2296
    /**
2297
     * Return the number of interactions for the given learnpath Item View ID.
2298
     * This method can be used as static.
2299
     *
2300
     * @param int $lp_iv_id  Item View ID
2301
     * @param int $course_id course id
2302
     *
2303
     * @return int
2304
     */
2305
    public static function get_interactions_count_from_db($lp_iv_id, $course_id)
2306
    {
2307
        $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
2308
        $lp_iv_id = (int) $lp_iv_id;
2309
        $course_id = (int) $course_id;
2310
2311
        $sql = "SELECT count(*) FROM $table
2312
                WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
2313
        $res = Database::query($sql);
2314
        $num = 0;
2315
        if (Database::num_rows($res)) {
2316
            $row = Database::fetch_array($res);
2317
            $num = $row[0];
2318
        }
2319
2320
        return $num;
2321
    }
2322
2323
    /**
2324
     * Return the interactions as an array for the given lp_iv_id.
2325
     * This method can be used as static.
2326
     *
2327
     * @param int $lp_iv_id Learnpath Item View ID
2328
     *
2329
     * @return array
2330
     *
2331
     * @todo    Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
2332
     */
2333
    public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
2334
    {
2335
        $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
2336
        $list = [];
2337
        $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
2338
        $lp_iv_id = (int) $lp_iv_id;
2339
2340
        if (empty($lp_iv_id) || empty($course_id)) {
2341
            return [];
2342
        }
2343
2344
        $sql = "SELECT * FROM $table
2345
                WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
2346
                ORDER BY order_id ASC";
2347
        $res = Database::query($sql);
2348
        $num = Database::num_rows($res);
2349
        if ($num > 0) {
2350
            $list[] = [
2351
                'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
2352
                'id' => api_htmlentities(get_lang('Interaction ID'), ENT_QUOTES),
2353
                'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
2354
                'time' => api_htmlentities(get_lang('Time (finished at...)'), ENT_QUOTES),
2355
                'correct_responses' => api_htmlentities(get_lang('Correct answers'), ENT_QUOTES),
2356
                'student_response' => api_htmlentities(get_lang('Learner answers'), ENT_QUOTES),
2357
                'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
2358
                'latency' => api_htmlentities(get_lang('Time spent'), ENT_QUOTES),
2359
                'student_response_formatted' => '',
2360
            ];
2361
            while ($row = Database::fetch_array($res)) {
2362
                $studentResponseFormatted = urldecode($row['student_response']);
2363
                $content_student_response = explode('__|', $studentResponseFormatted);
2364
                if (count($content_student_response) > 0) {
2365
                    if (count($content_student_response) >= 3) {
2366
                        // Pop the element off the end of array.
2367
                        array_pop($content_student_response);
2368
                    }
2369
                    $studentResponseFormatted = implode(',', $content_student_response);
2370
                }
2371
2372
                $list[] = [
2373
                    'order_id' => $row['order_id'] + 1,
2374
                    'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
2375
                    'type' => $row['interaction_type'],
2376
                    'time' => $row['completion_time'],
2377
                    'correct_responses' => '', // Hide correct responses from students.
2378
                    'student_response' => $row['student_response'],
2379
                    'result' => $row['result'],
2380
                    'latency' => $row['latency'],
2381
                    'student_response_formatted' => $studentResponseFormatted,
2382
                ];
2383
            }
2384
        }
2385
2386
        return $list;
2387
    }
2388
2389
    /**
2390
     * Return the number of objectives for the given learnpath Item View ID.
2391
     * This method can be used as static.
2392
     *
2393
     * @param int $lp_iv_id  Item View ID
2394
     * @param int $course_id Course ID
2395
     *
2396
     * @return int Number of objectives
2397
     */
2398
    public static function get_objectives_count_from_db($lp_iv_id, $course_id)
2399
    {
2400
        $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
2401
        $course_id = (int) $course_id;
2402
        $lp_iv_id = (int) $lp_iv_id;
2403
        $sql = "SELECT count(*) FROM $table
2404
                WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
2405
        //@todo seems that this always returns 0
2406
        $res = Database::query($sql);
2407
        $num = 0;
2408
        if (Database::num_rows($res)) {
2409
            $row = Database::fetch_array($res);
2410
            $num = $row[0];
2411
        }
2412
2413
        return $num;
2414
    }
2415
2416
    /**
2417
     * Return the objectives as an array for the given lp_iv_id.
2418
     * This method can be used as static.
2419
     *
2420
     * @param int $lpItemViewId Learnpath Item View ID
2421
     * @param int $course_id
2422
     *
2423
     * @return array
2424
     *
2425
     * @todo    Translate labels
2426
     */
2427
    public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
2428
    {
2429
        $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
2430
        $lpItemViewId = (int) $lpItemViewId;
2431
2432
        if (empty($course_id) || empty($lpItemViewId)) {
2433
            return [];
2434
        }
2435
2436
        $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
2437
        $sql = "SELECT * FROM $table
2438
                WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
2439
                ORDER BY order_id ASC";
2440
        $res = Database::query($sql);
2441
        $num = Database::num_rows($res);
2442
        $list = [];
2443
        if ($num > 0) {
2444
            $list[] = [
2445
                'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
2446
                'objective_id' => api_htmlentities(get_lang('Objective ID'), ENT_QUOTES),
2447
                'score_raw' => api_htmlentities(get_lang('Objective raw score'), ENT_QUOTES),
2448
                'score_max' => api_htmlentities(get_lang('Objective max score'), ENT_QUOTES),
2449
                'score_min' => api_htmlentities(get_lang('Objective min score'), ENT_QUOTES),
2450
                'status' => api_htmlentities(get_lang('Objective status'), ENT_QUOTES),
2451
            ];
2452
            while ($row = Database::fetch_array($res)) {
2453
                $list[] = [
2454
                    'order_id' => $row['order_id'] + 1,
2455
                    'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
2456
                    'score_raw' => $row['score_raw'],
2457
                    'score_max' => $row['score_max'],
2458
                    'score_min' => $row['score_min'],
2459
                    'status' => $row['status'],
2460
                ];
2461
            }
2462
        }
2463
2464
        return $list;
2465
    }
2466
2467
    /**
2468
     * Generate and return the table of contents for this learnpath. The (flat) table returned can be
2469
     * used by get_html_toc() to be ready to display.
2470
     */
2471
    public function get_toc(): array
2472
    {
2473
        $toc = [];
2474
        foreach ($this->ordered_items as $item_id) {
2475
            // TODO: Change this link generation and use new function instead.
2476
            $toc[] = [
2477
                'id' => $item_id,
2478
                'title' => $this->items[$item_id]->get_title(),
2479
                'status' => $this->items[$item_id]->get_status(false),
2480
                'status_class' => self::getStatusCSSClassName($this->items[$item_id]->get_status(false)),
2481
                'level' => $this->items[$item_id]->get_level(),
2482
                'type' => $this->items[$item_id]->get_type(),
2483
                'description' => $this->items[$item_id]->get_description(),
2484
                'path' => $this->items[$item_id]->get_path(),
2485
                'parent' => $this->items[$item_id]->get_parent(),
2486
            ];
2487
        }
2488
2489
        return $toc;
2490
    }
2491
2492
    /**
2493
     * Returns the CSS class name associated with a given item status.
2494
     *
2495
     * @param $status string an item status
2496
     *
2497
     * @return string CSS class name
2498
     */
2499
    public static function getStatusCSSClassName($status)
2500
    {
2501
        if (array_key_exists($status, self::STATUS_CSS_CLASS_NAME)) {
2502
            return self::STATUS_CSS_CLASS_NAME[$status];
2503
        }
2504
2505
        return '';
2506
    }
2507
2508
    /**
2509
     * Generate and return the table of contents for this learnpath. The JS
2510
     * table returned is used inside of scorm_api.php.
2511
     *
2512
     * @param string $varname
2513
     *
2514
     * @return string A JS array variable construction
2515
     */
2516
    public function get_items_details_as_js($varname = 'olms.lms_item_types')
2517
    {
2518
        $toc = $varname.' = new Array();';
2519
        foreach ($this->ordered_items as $item_id) {
2520
            $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
2521
        }
2522
2523
        return $toc;
2524
    }
2525
2526
    /**
2527
     * Gets the learning path type.
2528
     *
2529
     * @param bool $get_name Return the name? If false, return the ID. Default is false.
2530
     *
2531
     * @return mixed Type ID or name, depending on the parameter
2532
     */
2533
    public function get_type($get_name = false)
2534
    {
2535
        $res = false;
2536
        if (!empty($this->type) && (!$get_name)) {
2537
            $res = $this->type;
2538
        }
2539
2540
        return $res;
2541
    }
2542
2543
    /**
2544
     * Gets the learning path type as static method.
2545
     *
2546
     * @param int $lp_id
2547
     *
2548
     * @return mixed Type ID or name, depending on the parameter
2549
     */
2550
    public static function get_type_static($lp_id = 0)
2551
    {
2552
        $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
2553
        $lp_id = (int) $lp_id;
2554
        $sql = "SELECT lp_type FROM $tbl_lp
2555
                WHERE iid = $lp_id";
2556
        $res = Database::query($sql);
2557
        if (false === $res) {
2558
            return null;
2559
        }
2560
        if (Database::num_rows($res) <= 0) {
2561
            return null;
2562
        }
2563
        $row = Database::fetch_array($res);
2564
2565
        return $row['lp_type'];
2566
    }
2567
2568
    /**
2569
     * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
2570
     * This method can be used as abstract and is recursive.
2571
     *
2572
     * @param CLp $lp
2573
     * @param int $parent    Parent ID of the items to look for
2574
     *
2575
     * @return array Ordered list of item IDs (empty array on error)
2576
     */
2577
    public static function get_flat_ordered_items_list(CLp $lp, $parent = 0)
2578
    {
2579
        $parent = (int) $parent;
2580
        $lpItemRepo = Container::getLpItemRepository();
2581
        if (empty($parent)) {
2582
            $rootItem = $lpItemRepo->getRootItem($lp->getIid());
2583
            if (null !== $rootItem) {
2584
                $parent = $rootItem->getIid();
2585
            }
2586
        }
2587
2588
        if (empty($parent)) {
2589
            return [];
2590
        }
2591
2592
        $criteria = new Criteria();
2593
        $criteria
2594
            ->where($criteria->expr()->neq('path', 'root'))
2595
            ->orderBy(
2596
                [
2597
                    'displayOrder' => Criteria::ASC,
2598
                ]
2599
            );
2600
        $items = $lp->getItems()->matching($criteria);
2601
        $items = $items->filter(
2602
            function (CLpItem $element) use ($parent) {
2603
                if ('root' === $element->getPath()) {
2604
                    return false;
2605
                }
2606
2607
                if (null !== $element->getParent()) {
2608
                    return $element->getParent()->getIid() === $parent;
2609
                }
2610
                return false;
2611
2612
            }
2613
        );
2614
        $list = [];
2615
        foreach ($items as $item) {
2616
            $itemId = $item->getIid();
2617
            $sublist = self::get_flat_ordered_items_list($lp, $itemId);
2618
            $list[] = $itemId;
2619
            foreach ($sublist as $subItem) {
2620
                $list[] = $subItem;
2621
            }
2622
        }
2623
2624
        return $list;
2625
    }
2626
2627
    public static function getChapterTypes(): array
2628
    {
2629
        return [
2630
            'dir',
2631
        ];
2632
    }
2633
2634
    /**
2635
     * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
2636
     *
2637
     * @return array HTML TOC ready to display
2638
     */
2639
    public function getListArrayToc()
2640
    {
2641
        $lpItemRepo = Container::getLpItemRepository();
2642
        $itemRoot = $lpItemRepo->getRootItem($this->get_id());
2643
        $options = [
2644
            'decorate' => false,
2645
        ];
2646
2647
        return $lpItemRepo->childrenHierarchy($itemRoot, false, $options);
2648
    }
2649
2650
    /**
2651
     * Returns an HTML-formatted string ready to display with teacher buttons
2652
     * in LP view menu.
2653
     *
2654
     * @return string HTML TOC ready to display
2655
     */
2656
    public function get_teacher_toc_buttons()
2657
    {
2658
        $isAllow = api_is_allowed_to_edit(null, true, false, false);
2659
        $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
2660
        $html = '';
2661
        if ($isAllow && false == $hideIcons) {
2662
            if ($this->get_lp_session_id() == api_get_session_id()) {
2663
                $html .= '<div id="actions_lp" class="actions_lp"><hr>';
2664
                $html .= '<div class="flex flex-wrap gap-1 justify-center">';
2665
                $html .= "<a
2666
                    class='btn btn-sm btn--plain'
2667
                    href='lp_controller.php?".api_get_cidreq()."&action=add_item&type=step&lp_id=".$this->lp_id."&isStudentView=false'
2668
                    target='_parent'>".
2669
                    Display::getMdiIcon('pencil').get_lang('Edit')."</a>";
2670
                $html .= '<a
2671
                    class="btn btn-sm btn--plain"
2672
                    href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
2673
                    Display::getMdiIcon('hammer-wrench').get_lang('Settings').'</a>';
2674
                $html .= '</div>';
2675
                $html .= '</div>';
2676
            }
2677
        }
2678
2679
        return $html;
2680
    }
2681
2682
    /**
2683
     * Gets the learnpath name/title.
2684
     *
2685
     * @return string Learnpath name/title
2686
     */
2687
    public function get_name()
2688
    {
2689
        if (!empty($this->name)) {
2690
            return $this->name;
2691
        }
2692
2693
        return 'N/A';
2694
    }
2695
2696
    /**
2697
     * @return string
2698
     */
2699
    public function getNameNoTags()
2700
    {
2701
        return strip_tags($this->get_name());
2702
    }
2703
2704
    /**
2705
     * Gets a link to the resource from the present location, depending on item ID.
2706
     *
2707
     * @param string $type         Type of link expected
2708
     * @param int    $item_id      Learnpath item ID
2709
     * @param bool   $provided_toc
2710
     *
2711
     * @return string $provided_toc Link to the lp_item resource
2712
     */
2713
    public function get_link($type = 'http', $item_id = 0, $provided_toc = false)
2714
    {
2715
        $course_id = $this->get_course_int_id();
2716
        $item_id = (int) $item_id;
2717
2718
        if (empty($item_id)) {
2719
            $item_id = $this->get_current_item_id();
2720
2721
            if (empty($item_id)) {
2722
                //still empty, this means there was no item_id given and we are not in an object context or
2723
                //the object property is empty, return empty link
2724
                $this->first();
2725
2726
                return '';
2727
            }
2728
        }
2729
2730
        $file = '';
2731
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
2732
        $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
2733
        $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
2734
2735
        $sql = "SELECT
2736
                    l.lp_type as ltype,
2737
                    l.path as lpath,
2738
                    li.item_type as litype,
2739
                    li.path as lipath,
2740
                    li.parameters as liparams
2741
        		FROM $lp_table l
2742
                INNER JOIN $lp_item_table li
2743
                ON (li.lp_id = l.iid)
2744
        		WHERE
2745
        		    li.iid = $item_id
2746
        		";
2747
        $res = Database::query($sql);
2748
        if (Database::num_rows($res) > 0) {
2749
            $row = Database::fetch_array($res);
2750
            $lp_type = $row['ltype'];
2751
            $lp_path = $row['lpath'];
2752
            $lp_item_type = $row['litype'];
2753
            $lp_item_path = $row['lipath'];
2754
            $lp_item_params = $row['liparams'];
2755
            if (empty($lp_item_params) && false !== strpos($lp_item_path, '?')) {
2756
                [$lp_item_path, $lp_item_params] = explode('?', $lp_item_path);
2757
            }
2758
            //$sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
2759
            if ('http' === $type) {
2760
                //web path
2761
                //$course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
2762
            } else {
2763
                //$course_path = $sys_course_path; //system path
2764
            }
2765
2766
            // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
2767
            // then change the lp type to thread it as a normal Chamilo LP not a SCO.
2768
            if (in_array(
2769
                $lp_item_type,
2770
                ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication', 'survey']
2771
            )
2772
            ) {
2773
                $lp_type = CLp::LP_TYPE;
2774
            }
2775
2776
            // Now go through the specific cases to get the end of the path
2777
            // @todo Use constants instead of int values.
2778
            switch ($lp_type) {
2779
                case CLp::LP_TYPE:
2780
                    $file = self::rl_get_resource_link_for_learnpath(
2781
                        $course_id,
2782
                        $this->get_id(),
2783
                        $item_id,
2784
                        $this->get_view_id()
2785
                    );
2786
                    switch ($lp_item_type) {
2787
                        case 'document':
2788
                            // Shows a button to download the file instead of just downloading the file directly.
2789
                            $documentPathInfo = pathinfo($file);
2790
                            if (isset($documentPathInfo['extension'])) {
2791
                                $parsed = parse_url($documentPathInfo['extension']);
2792
                                if (isset($parsed['path'])) {
2793
                                    $extension = $parsed['path'];
2794
                                    $extensionsToDownload = [
2795
                                        'zip',
2796
                                        'ppt',
2797
                                        'pptx',
2798
                                        'ods',
2799
                                        'xlsx',
2800
                                        'xls',
2801
                                        'csv',
2802
                                        'doc',
2803
                                        'docx',
2804
                                        'dot',
2805
                                    ];
2806
2807
                                    if (in_array($extension, $extensionsToDownload)) {
2808
                                        $file = api_get_path(WEB_CODE_PATH).
2809
                                            'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
2810
                                    }
2811
                                }
2812
                            }
2813
                            break;
2814
                        case 'dir':
2815
                            $file = 'lp_content.php?type=dir';
2816
                            break;
2817
                        case 'link':
2818
                            if (Link::is_youtube_link($file)) {
2819
                                $src = Link::get_youtube_video_id($file);
2820
                                $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
2821
                            } elseif (Link::isVimeoLink($file)) {
2822
                                $src = Link::getVimeoLinkId($file);
2823
                                $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
2824
                            } else {
2825
                                // If the current site is HTTPS and the link is
2826
                                // HTTP, browsers will refuse opening the link
2827
                                $urlId = api_get_current_access_url_id();
2828
                                $url = api_get_access_url($urlId, false);
2829
                                $protocol = substr($url['url'], 0, 5);
2830
                                if ('https' === $protocol) {
2831
                                    $linkProtocol = substr($file, 0, 5);
2832
                                    if ('http:' === $linkProtocol) {
2833
                                        //this is the special intervention case
2834
                                        $file = api_get_path(WEB_CODE_PATH).
2835
                                            'lp/embed.php?type=nonhttps&source='.urlencode($file);
2836
                                    }
2837
                                }
2838
                            }
2839
                            break;
2840
                        case 'quiz':
2841
                            // Check how much attempts of a exercise exits in lp
2842
                            $lp_item_id = $this->get_current_item_id();
2843
                            $lp_view_id = $this->get_view_id();
2844
2845
                            $prevent_reinit = null;
2846
                            if (isset($this->items[$this->current])) {
2847
                                $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
2848
                            }
2849
2850
                            if (empty($provided_toc)) {
2851
                                $list = $this->get_toc();
2852
                            } else {
2853
                                $list = $provided_toc;
2854
                            }
2855
2856
                            $type_quiz = false;
2857
                            foreach ($list as $toc) {
2858
                                if ($toc['id'] == $lp_item_id && 'quiz' === $toc['type']) {
2859
                                    $type_quiz = true;
2860
                                }
2861
                            }
2862
2863
                            if ($type_quiz) {
2864
                                $lp_item_id = (int) $lp_item_id;
2865
                                $lp_view_id = (int) $lp_view_id;
2866
                                $sql = "SELECT count(*) FROM $lp_item_view_table
2867
                                        WHERE
2868
                                            lp_item_id='".$lp_item_id."' AND
2869
                                            lp_view_id ='".$lp_view_id."' AND
2870
                                            status='completed'";
2871
                                $result = Database::query($sql);
2872
                                $row_count = Database:: fetch_row($result);
2873
                                $count_item_view = (int) $row_count[0];
2874
                                $not_multiple_attempt = 0;
2875
                                if (1 === $prevent_reinit && $count_item_view > 0) {
2876
                                    $not_multiple_attempt = 1;
2877
                                }
2878
                                $file .= '&not_multiple_attempt='.$not_multiple_attempt;
2879
                            }
2880
                            break;
2881
                    }
2882
2883
                    $tmp_array = explode('/', $file);
2884
                    $document_name = $tmp_array[count($tmp_array) - 1];
2885
                    if (strpos($document_name, '_DELETED_')) {
2886
                        $file = 'blank.php?error=document_deleted';
2887
                    }
2888
                    break;
2889
                case CLp::SCORM_TYPE:
2890
                    if ('dir' !== $lp_item_type) {
2891
                        // Quite complex here:
2892
                        // We want to make sure 'http://' (and similar) links can
2893
                        // be loaded as is (withouth the Chamilo path in front) but
2894
                        // some contents use this form: resource.htm?resource=http://blablabla
2895
                        // which means we have to find a protocol at the path's start, otherwise
2896
                        // it should not be considered as an external URL.
2897
                        // if ($this->prerequisites_match($item_id)) {
2898
                        if (0 != preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path)) {
2899
                            if ($this->debug > 2) {
2900
                                error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
2901
                            }
2902
                            // Distant url, return as is.
2903
                            $file = $lp_item_path;
2904
                        } else {
2905
                            if ($this->debug > 2) {
2906
                                error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path);
2907
                            }
2908
                            // Prevent getting untranslatable urls.
2909
                            $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
2910
                            $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
2911
2912
                            /*$asset = $this->getEntity()->getAsset();
2913
                            $folder = Container::getAssetRepository()->getFolder($asset);
2914
                            $hasFile = Container::getAssetRepository()->getFileSystem()->has($folder.$lp_item_path);
2915
                            $file = null;
2916
                            if ($hasFile) {
2917
                                $file = Container::getAssetRepository()->getAssetUrl($asset).'/'.$lp_item_path;
2918
                            }*/
2919
                            $file = $this->scormUrl.$lp_item_path;
2920
2921
                            // Prepare the path.
2922
                            /*$file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
2923
                            // TODO: Fix this for urls with protocol header.
2924
                            $file = str_replace('//', '/', $file);
2925
                            $file = str_replace(':/', '://', $file);
2926
                            if ('/' === substr($lp_path, -1)) {
2927
                                $lp_path = substr($lp_path, 0, -1);
2928
                            }*/
2929
                            /*if (!$hasFile) {
2930
                                // if file not found.
2931
                                $decoded = html_entity_decode($lp_item_path);
2932
                                [$decoded] = explode('?', $decoded);
2933
                                if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
2934
                                    $file = self::rl_get_resource_link_for_learnpath(
2935
                                        $course_id,
2936
                                        $this->get_id(),
2937
                                        $item_id,
2938
                                        $this->get_view_id()
2939
                                    );
2940
                                    if (empty($file)) {
2941
                                        $file = 'blank.php?error=document_not_found';
2942
                                    } else {
2943
                                        $tmp_array = explode('/', $file);
2944
                                        $document_name = $tmp_array[count($tmp_array) - 1];
2945
                                        if (strpos($document_name, '_DELETED_')) {
2946
                                            $file = 'blank.php?error=document_deleted';
2947
                                        } else {
2948
                                            $file = 'blank.php?error=document_not_found';
2949
                                        }
2950
                                    }
2951
                                } else {
2952
                                    $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
2953
                                }
2954
                            }*/
2955
                        }
2956
2957
                        // We want to use parameters if they were defined in the imsmanifest
2958
                        if (false === strpos($file, 'blank.php')) {
2959
                            $lp_item_params = ltrim($lp_item_params, '?');
2960
                            $file .= (false === strstr($file, '?') ? '?' : '').$lp_item_params;
2961
                        }
2962
                    } else {
2963
                        $file = 'lp_content.php?type=dir';
2964
                    }
2965
                    break;
2966
                case CLp::AICC_TYPE:
2967
                    // Formatting AICC HACP append URL.
2968
                    $aicc_append = '?aicc_sid='.
2969
                        urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
2970
                    if (!empty($lp_item_params)) {
2971
                        $aicc_append .= $lp_item_params.'&';
2972
                    }
2973
                    if ('dir' !== $lp_item_type) {
2974
                        // Quite complex here:
2975
                        // We want to make sure 'http://' (and similar) links can
2976
                        // be loaded as is (withouth the Chamilo path in front) but
2977
                        // some contents use this form: resource.htm?resource=http://blablabla
2978
                        // which means we have to find a protocol at the path's start, otherwise
2979
                        // it should not be considered as an external URL.
2980
                        if (0 != preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path)) {
2981
                            if ($this->debug > 2) {
2982
                                error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
2983
                            }
2984
                            // Distant url, return as is.
2985
                            $file = $lp_item_path;
2986
                            // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
2987
                            /*
2988
                            if (stristr($file,'<servername>') !== false) {
2989
                                $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
2990
                            }
2991
                            */
2992
                            if (false !== stripos($file, '<servername>')) {
2993
                                //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
2994
                                $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
2995
                                $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
2996
                            }
2997
2998
                            $file .= $aicc_append;
2999
                        } else {
3000
                            if ($this->debug > 2) {
3001
                                error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
3002
                            }
3003
                            // Prevent getting untranslatable urls.
3004
                            $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
3005
                            $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
3006
                            // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
3007
                            $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
3008
                            // TODO: Fix this for urls with protocol header.
3009
                            $file = str_replace('//', '/', $file);
3010
                            $file = str_replace(':/', '://', $file);
3011
                            $file .= $aicc_append;
3012
                        }
3013
                    } else {
3014
                        $file = 'lp_content.php?type=dir';
3015
                    }
3016
                    break;
3017
                case 4:
3018
                default:
3019
                    break;
3020
            }
3021
            // Replace &amp; by & because &amp; will break URL with params
3022
            $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
3023
        }
3024
        if ($this->debug > 2) {
3025
            error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
3026
        }
3027
3028
        return $file;
3029
    }
3030
3031
    /**
3032
     * Gets the latest usable view or generate a new one.
3033
     *
3034
     * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
3035
     * @param int $userId      The user ID, as $this->get_user_id() is not always available
3036
     *
3037
     * @return int DB lp_view id
3038
     */
3039
    public function get_view($attempt_num = 0, $userId = null)
3040
    {
3041
        $search = '';
3042
        $attempt_num = (int) $attempt_num;
3043
        // Use $attempt_num to enable multi-views management (disabled so far).
3044
        if (!empty($attempt_num)) {
3045
            $search = 'AND view_count = '.$attempt_num;
3046
        }
3047
3048
        $course_id = api_get_course_int_id();
3049
        $sessionId = api_get_session_id();
3050
3051
        // Check user ID.
3052
        if (empty($userId)) {
3053
            if (empty($this->get_user_id())) {
3054
                $this->error = 'User ID is empty in learnpath::get_view()';
3055
3056
                return null;
3057
            } else {
3058
                $userId = $this->get_user_id();
3059
            }
3060
        }
3061
        $sessionCondition = api_get_session_condition($sessionId);
3062
3063
        // When missing $attempt_num, search for a unique lp_view record for this lp and user.
3064
        $table = Database::get_course_table(TABLE_LP_VIEW);
3065
        $sql = "SELECT iid FROM $table
3066
        		WHERE
3067
        		    c_id = $course_id AND
3068
        		    lp_id = ".$this->get_id()." AND
3069
        		    user_id = ".$userId."
3070
        		    $sessionCondition
3071
        		    $search
3072
                ORDER BY view_count DESC";
3073
        $res = Database::query($sql);
3074
        if (Database::num_rows($res) > 0) {
3075
            $row = Database::fetch_array($res);
3076
            $this->lp_view_id = $row['iid'];
3077
        } elseif (!api_is_invitee()) {
3078
            $params = [
3079
                'c_id' => $course_id,
3080
                'lp_id' => $this->get_id(),
3081
                'user_id' => $this->get_user_id(),
3082
                'view_count' => 1,
3083
                'last_item' => 0,
3084
            ];
3085
            if (!empty($sessionId)) {
3086
                $params['session_id']  = $sessionId;
3087
            }
3088
            $this->lp_view_id = Database::insert($table, $params);
3089
        }
3090
3091
        return $this->lp_view_id;
3092
    }
3093
3094
    /**
3095
     * Gets the current view id.
3096
     *
3097
     * @return int View ID (from lp_view)
3098
     */
3099
    public function get_view_id()
3100
    {
3101
        if (!empty($this->lp_view_id)) {
3102
            return (int) $this->lp_view_id;
3103
        }
3104
3105
        return 0;
3106
    }
3107
3108
    /**
3109
     * Gets the update queue.
3110
     *
3111
     * @return array Array containing IDs of items to be updated by JavaScript
3112
     */
3113
    public function get_update_queue()
3114
    {
3115
        return $this->update_queue;
3116
    }
3117
3118
    /**
3119
     * Gets the user ID.
3120
     *
3121
     * @return int User ID
3122
     */
3123
    public function get_user_id()
3124
    {
3125
        if (!empty($this->user_id)) {
3126
            return (int) $this->user_id;
3127
        }
3128
3129
        return false;
3130
    }
3131
3132
    /**
3133
     * Checks if any of the items has an audio element attached.
3134
     *
3135
     * @return bool True or false
3136
     */
3137
    public function has_audio()
3138
    {
3139
        $has = false;
3140
        foreach ($this->items as $i => $item) {
3141
            if (!empty($this->items[$i]->audio)) {
3142
                $has = true;
3143
                break;
3144
            }
3145
        }
3146
3147
        return $has;
3148
    }
3149
3150
    /**
3151
     * Updates learnpath attributes to point to the next element
3152
     * The last part is similar to set_current_item but processing the other way around.
3153
     */
3154
    public function next()
3155
    {
3156
        if ($this->debug > 0) {
3157
            error_log('In learnpath::next()', 0);
3158
        }
3159
        $this->last = $this->get_current_item_id();
3160
        $this->items[$this->last]->save(
3161
            false,
3162
            $this->prerequisites_match($this->last)
3163
        );
3164
        $this->autocomplete_parents($this->last);
3165
        $new_index = $this->get_next_index();
3166
        if ($this->debug > 2) {
3167
            error_log('New index: '.$new_index, 0);
3168
        }
3169
        $this->index = $new_index;
3170
        if ($this->debug > 2) {
3171
            error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
3172
        }
3173
        $this->current = $this->ordered_items[$new_index];
3174
        if ($this->debug > 2) {
3175
            error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
3176
        }
3177
    }
3178
3179
    /**
3180
     * Open a resource = initialise all local variables relative to this resource. Depending on the child
3181
     * class, this might be redefined to allow several behaviours depending on the document type.
3182
     *
3183
     * @param int $id Resource ID
3184
     */
3185
    public function open($id)
3186
    {
3187
        // TODO:
3188
        // set the current resource attribute to this resource
3189
        // switch on element type (redefine in child class?)
3190
        // set status for this item to "opened"
3191
        // start timer
3192
        // initialise score
3193
        $this->index = 0; //or = the last item seen (see $this->last)
3194
    }
3195
3196
    /**
3197
     * Check that all prerequisites are fulfilled. Returns true and an
3198
     * empty string on success, returns false
3199
     * and the prerequisite string on error.
3200
     * This function is based on the rules for aicc_script language as
3201
     * described in the SCORM 1.2 CAM documentation page 108.
3202
     *
3203
     * @param int $itemId Optional item ID. If none given, uses the current open item.
3204
     *
3205
     * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
3206
     *              string otherwise
3207
     */
3208
    public function prerequisites_match($itemId = null)
3209
    {
3210
        $allow = ('true' === api_get_setting('lp.allow_teachers_to_access_blocked_lp_by_prerequisite'));
3211
        if ($allow) {
3212
            if (api_is_allowed_to_edit() ||
3213
                api_is_platform_admin(true) ||
3214
                api_is_drh() ||
3215
                api_is_coach(api_get_session_id(), api_get_course_int_id())
3216
            ) {
3217
                return true;
3218
            }
3219
        }
3220
3221
        $debug = $this->debug;
3222
        if ($debug > 0) {
3223
            error_log('In learnpath::prerequisites_match()');
3224
        }
3225
3226
        if (empty($itemId)) {
3227
            $itemId = $this->current;
3228
        }
3229
3230
        $currentItem = $this->getItem($itemId);
3231
3232
        if ($currentItem) {
3233
            if (2 == $this->type) {
3234
                // Getting prereq from scorm
3235
                $prereq_string = $this->get_scorm_prereq_string($itemId);
3236
            } else {
3237
                $prereq_string = $currentItem->get_prereq_string();
3238
            }
3239
3240
            if (empty($prereq_string)) {
3241
                if ($debug > 0) {
3242
                    error_log('Found prereq_string is empty return true');
3243
                }
3244
3245
                return true;
3246
            }
3247
3248
            // Clean spaces.
3249
            $prereq_string = str_replace(' ', '', $prereq_string);
3250
            if ($debug > 0) {
3251
                error_log('Found prereq_string: '.$prereq_string, 0);
3252
            }
3253
3254
            // Now send to the parse_prereq() function that will check this component's prerequisites.
3255
            $result = $currentItem->parse_prereq(
3256
                $prereq_string,
3257
                $this->items,
3258
                $this->refs_list,
3259
                $this->get_user_id()
3260
            );
3261
3262
            if (false === $result) {
3263
                $this->set_error_msg($currentItem->prereq_alert);
3264
            }
3265
        } else {
3266
            $result = true;
3267
            if ($debug > 1) {
3268
                error_log('$this->items['.$itemId.'] was not an object', 0);
3269
            }
3270
        }
3271
3272
        if ($debug > 1) {
3273
            error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
3274
        }
3275
3276
        return $result;
3277
    }
3278
3279
    /**
3280
     * Updates learnpath attributes to point to the previous element
3281
     * The last part is similar to set_current_item but processing the other way around.
3282
     */
3283
    public function previous()
3284
    {
3285
        $this->last = $this->get_current_item_id();
3286
        $this->items[$this->last]->save(
3287
            false,
3288
            $this->prerequisites_match($this->last)
3289
        );
3290
        $this->autocomplete_parents($this->last);
3291
        $new_index = $this->get_previous_index();
3292
        $this->index = $new_index;
3293
        $this->current = $this->ordered_items[$new_index];
3294
    }
3295
3296
    /**
3297
     * Publishes a learnpath. This basically means show or hide the learnpath
3298
     * to normal users.
3299
     * Can be used as abstract.
3300
     *
3301
     * @param int $id         Learnpath ID
3302
     * @param int $visibility New visibility (1 = visible/published, 0= invisible/draft)
3303
     *
3304
     * @return bool
3305
     */
3306
    public static function toggleVisibility($id, $visibility = 1)
3307
    {
3308
        $repo = Container::getLpRepository();
3309
        $lp = $repo->find($id);
3310
3311
        if (!$lp) {
3312
            return false;
3313
        }
3314
3315
        $visibility = (int) $visibility;
3316
3317
        $course = api_get_course_entity();
3318
        $session = api_get_session_entity();
3319
3320
        if (1 === $visibility) {
3321
            $repo->setVisibilityPublished($lp, $course, $session);
3322
        } else {
3323
            $repo->setVisibilityDraft($lp, $course, $session);
3324
        }
3325
3326
        return true;
3327
    }
3328
3329
    /**
3330
     * Publishes a learnpath category.
3331
     * This basically means show or hide the learnpath category to normal users.
3332
     *
3333
     * @param int $id
3334
     * @param int $visibility
3335
     *
3336
     * @return bool
3337
     */
3338
    public static function toggleCategoryVisibility($id, $visibility = 1)
3339
    {
3340
        $repo = Container::getLpCategoryRepository();
3341
        $resource = $repo->find($id);
3342
3343
        if (!$resource) {
3344
            return false;
3345
        }
3346
3347
        $visibility = (int) $visibility;
3348
3349
        $course = api_get_course_entity();
3350
        $session = api_get_session_entity();
3351
3352
        if (1 === $visibility) {
3353
            $repo->setVisibilityPublished($resource, $course, $session);
3354
        } else {
3355
            $repo->setVisibilityDraft($resource, $course, $session);
3356
            self::toggleCategoryPublish($id, 0);
3357
        }
3358
3359
        return false;
3360
    }
3361
3362
    /**
3363
     * Publishes a learnpath. This basically means show or hide the learnpath
3364
     * on the course homepage.
3365
     *
3366
     * @param int    $id            Learnpath id
3367
     * @param string $setVisibility New visibility (v/i - visible/invisible)
3368
     *
3369
     * @return bool
3370
     */
3371
    public static function togglePublish($id, $setVisibility = 'v')
3372
    {
3373
        $addShortcut = false;
3374
        if ('v' === $setVisibility) {
3375
            $addShortcut = true;
3376
        }
3377
        $repo = Container::getLpRepository();
3378
        /** @var CLp|null $lp */
3379
        $lp = $repo->find($id);
3380
        if (null === $lp) {
3381
            return false;
3382
        }
3383
        $repoShortcut = Container::getShortcutRepository();
3384
        if ($addShortcut) {
3385
            $repoShortcut->addShortCut($lp, api_get_user_entity(), api_get_course_entity(), api_get_session_entity());
3386
        } else {
3387
            $repoShortcut->removeShortCut($lp);
3388
        }
3389
3390
        return true;
3391
    }
3392
3393
    /**
3394
     * Show or hide the learnpath category on the course homepage.
3395
     *
3396
     * @param int $id
3397
     * @param int $setVisibility
3398
     *
3399
     * @return bool
3400
     */
3401
    public static function toggleCategoryPublish($id, $setVisibility = 1)
3402
    {
3403
        $setVisibility = (int) $setVisibility;
3404
        $addShortcut = false;
3405
        if (1 === $setVisibility) {
3406
            $addShortcut = true;
3407
        }
3408
3409
        $repo = Container::getLpCategoryRepository();
3410
        /** @var CLpCategory|null $lp */
3411
        $category = $repo->find($id);
3412
3413
        if (null === $category) {
3414
            return false;
3415
        }
3416
3417
        $repoShortcut = Container::getShortcutRepository();
3418
        if ($addShortcut) {
3419
            $courseEntity = api_get_course_entity(api_get_course_int_id());
3420
            $repoShortcut->addShortCut($category, api_get_user_entity(), $courseEntity, api_get_session_entity());
3421
        } else {
3422
            $repoShortcut->removeShortCut($category);
3423
        }
3424
3425
        return true;
3426
    }
3427
3428
    /**
3429
     * Check if the learnpath category is visible for a user.
3430
     *
3431
     * @return bool
3432
     */
3433
    public static function categoryIsVisibleForStudent(
3434
        CLpCategory $category,
3435
        User $user,
3436
        Course $course,
3437
        SessionEntity $session = null
3438
    ) {
3439
        $isAllowedToEdit = api_is_allowed_to_edit(null, true);
3440
3441
        if ($isAllowedToEdit) {
3442
            return true;
3443
        }
3444
3445
        $categoryVisibility = $category->isVisible($course, $session);
3446
3447
        if (!$categoryVisibility) {
3448
            return false;
3449
        }
3450
3451
        $subscriptionSettings = self::getSubscriptionSettings();
3452
3453
        if (false === $subscriptionSettings['allow_add_users_to_lp_category']) {
3454
            return true;
3455
        }
3456
3457
        $noUserSubscribed = false;
3458
        $noGroupSubscribed = true;
3459
        $users = $category->getUsers();
3460
        if (empty($users) || !$users->count()) {
3461
            $noUserSubscribed = true;
3462
        } elseif ($category->hasUserAdded($user)) {
3463
            return true;
3464
        }
3465
3466
        //$groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
3467
3468
        return $noGroupSubscribed && $noUserSubscribed;
3469
    }
3470
3471
    /**
3472
     * Check if a learnpath category is published as course tool.
3473
     *
3474
     * @param int $courseId
3475
     *
3476
     * @return bool
3477
     */
3478
    public static function categoryIsPublished(CLpCategory $category, $courseId)
3479
    {
3480
        return false;
3481
        $link = self::getCategoryLinkForTool($category->getId());
0 ignored issues
show
Unused Code introduced by
$link = self::getCategor...ool($category->getId()) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
3482
        $em = Database::getManager();
3483
3484
        $tools = $em
3485
            ->createQuery("
3486
                SELECT t FROM ChamiloCourseBundle:CTool t
3487
                WHERE t.course = :course AND
3488
                    t.name = :name AND
3489
                    t.image LIKE 'lp_category.%' AND
3490
                    t.link LIKE :link
3491
            ")
3492
            ->setParameters([
3493
                'course' => $courseId,
3494
                'name' => strip_tags($category->getTitle()),
3495
                'link' => "$link%",
3496
            ])
3497
            ->getResult();
3498
3499
        /** @var CTool $tool */
3500
        $tool = current($tools);
3501
3502
        return $tool ? $tool->getVisibility() : false;
3503
    }
3504
3505
    /**
3506
     * Restart the whole learnpath. Return the URL of the first element.
3507
     * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
3508
     * To use a similar method  statically, use the create_new_attempt() method.
3509
     *
3510
     * @return bool
3511
     */
3512
    public function restart()
3513
    {
3514
        if ($this->debug > 0) {
3515
            error_log('In learnpath::restart()', 0);
3516
        }
3517
        // TODO
3518
        // Call autosave method to save the current progress.
3519
        //$this->index = 0;
3520
        if (api_is_invitee()) {
3521
            return false;
3522
        }
3523
        $session_id = api_get_session_id();
3524
        $course_id = api_get_course_int_id();
3525
        $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
3526
        $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
3527
                VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
3528
        if ($this->debug > 2) {
3529
            error_log('Inserting new lp_view for restart: '.$sql, 0);
3530
        }
3531
        Database::query($sql);
3532
        $view_id = Database::insert_id();
3533
3534
        if ($view_id) {
3535
            $this->lp_view_id = $view_id;
3536
            $this->attempt = $this->attempt + 1;
3537
        } else {
3538
            $this->error = 'Could not insert into item_view table...';
3539
3540
            return false;
3541
        }
3542
        $this->autocomplete_parents($this->current);
3543
        foreach ($this->items as $index => $dummy) {
3544
            $this->items[$index]->restart();
3545
            $this->items[$index]->set_lp_view($this->lp_view_id);
3546
        }
3547
        $this->first();
3548
3549
        return true;
3550
    }
3551
3552
    /**
3553
     * Saves the current item.
3554
     *
3555
     * @return bool
3556
     */
3557
    public function save_current()
3558
    {
3559
        $debug = $this->debug;
3560
        // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
3561
        // on $ordered_items[] but not sure it's always safe to use with $items[]).
3562
        if ($debug) {
3563
            error_log('save_current() saving item '.$this->current, 0);
3564
            error_log(''.print_r($this->items, true), 0);
3565
        }
3566
        if (isset($this->items[$this->current]) &&
3567
            is_object($this->items[$this->current])
3568
        ) {
3569
            if ($debug) {
3570
                error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
3571
            }
3572
3573
            $res = $this->items[$this->current]->save(
3574
                false,
3575
                $this->prerequisites_match($this->current)
3576
            );
3577
            $this->autocomplete_parents($this->current);
3578
            $status = $this->items[$this->current]->get_status();
3579
            $this->update_queue[$this->current] = $status;
3580
3581
            if ($debug) {
3582
                error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
3583
            }
3584
3585
            return $res;
3586
        }
3587
3588
        return false;
3589
    }
3590
3591
    /**
3592
     * Saves the given item.
3593
     *
3594
     * @param int  $item_id      Optional (will take from $_REQUEST if null)
3595
     * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
3596
     *
3597
     * @return bool
3598
     */
3599
    public function save_item($item_id = null, $from_outside = true)
3600
    {
3601
        $debug = $this->debug;
3602
        if ($debug) {
3603
            error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
3604
        }
3605
        // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
3606
        // on $ordered_items[] but not sure it's always safe to use with $items[]).
3607
        if (empty($item_id)) {
3608
            $item_id = (int) $_REQUEST['id'];
3609
        }
3610
3611
        if (empty($item_id)) {
3612
            $item_id = $this->get_current_item_id();
3613
        }
3614
        if (isset($this->items[$item_id]) &&
3615
            is_object($this->items[$item_id])
3616
        ) {
3617
            if ($debug) {
3618
                error_log('Object exists');
3619
            }
3620
3621
            // Saving the item.
3622
            $res = $this->items[$item_id]->save(
3623
                $from_outside,
3624
                $this->prerequisites_match($item_id)
3625
            );
3626
3627
            if ($debug) {
3628
                error_log('update_queue before:');
3629
                error_log(print_r($this->update_queue, 1));
3630
            }
3631
            $this->autocomplete_parents($item_id);
3632
3633
            $status = $this->items[$item_id]->get_status();
3634
            $this->update_queue[$item_id] = $status;
3635
3636
            if ($debug) {
3637
                error_log('get_status(): '.$status);
3638
                error_log('update_queue after:');
3639
                error_log(print_r($this->update_queue, 1));
3640
            }
3641
3642
            return $res;
3643
        }
3644
3645
        return false;
3646
    }
3647
3648
    /**
3649
     * Saves the last item seen's ID only in case.
3650
     */
3651
    public function save_last()
3652
    {
3653
        $course_id = api_get_course_int_id();
3654
        $debug = $this->debug;
3655
        if ($debug) {
3656
            error_log('In learnpath::save_last()', 0);
3657
        }
3658
        $session_condition = api_get_session_condition(
3659
            api_get_session_id(),
3660
            true,
3661
            false
3662
        );
3663
        $table = Database::get_course_table(TABLE_LP_VIEW);
3664
3665
        $userId = $this->get_user_id();
3666
        if (empty($userId)) {
3667
            $userId = api_get_user_id();
3668
            if ($debug) {
3669
                error_log('$this->get_user_id() was empty, used api_get_user_id() instead in '.__FILE__.' line '.__LINE__);
3670
            }
3671
        }
3672
        if (isset($this->current) && !api_is_invitee()) {
3673
            if ($debug) {
3674
                error_log('Saving current item ('.$this->current.') for later review', 0);
3675
            }
3676
            $sql = "UPDATE $table SET
3677
                        last_item = ".$this->get_current_item_id()."
3678
                    WHERE
3679
                        c_id = $course_id AND
3680
                        lp_id = ".$this->get_id()." AND
3681
                        user_id = ".$userId." ".$session_condition;
3682
3683
            if ($debug) {
3684
                error_log('Saving last item seen : '.$sql, 0);
3685
            }
3686
            Database::query($sql);
3687
        }
3688
3689
        if (!api_is_invitee()) {
3690
            // Save progress.
3691
            [$progress] = $this->get_progress_bar_text('%');
3692
            $scoreAsProgressSetting = ('true' === api_get_setting('lp.lp_score_as_progress_enable'));
3693
            $scoreAsProgress = $this->getUseScoreAsProgress();
3694
            if ($scoreAsProgress && $scoreAsProgressSetting && (null === $score || empty($score) || -1 == $score)) {
3695
                if ($debug) {
3696
                    error_log("Return false: Dont save score: $score");
3697
                    error_log("progress: $progress");
3698
                }
3699
3700
                return false;
3701
            }
3702
3703
            if ($scoreAsProgress && $scoreAsProgressSetting) {
3704
                $storedProgress = self::getProgress(
3705
                    $this->get_id(),
3706
                    $userId,
3707
                    $course_id,
3708
                    $this->get_lp_session_id()
3709
                );
3710
3711
                // Check if the stored progress is higher than the new value
3712
                if ($storedProgress >= $progress) {
3713
                    if ($debug) {
3714
                        error_log("Return false: New progress value is lower than stored value - Current value: $storedProgress - New value: $progress [lp ".$this->get_id()." - user ".$userId."]");
3715
                    }
3716
3717
                    return false;
3718
                }
3719
            }
3720
            if ($progress >= 0 && $progress <= 100) {
3721
                $progress = (int) $progress;
3722
                $sql = "UPDATE $table SET
3723
                            progress = $progress
3724
                        WHERE
3725
                            c_id = $course_id AND
3726
                            lp_id = ".$this->get_id()." AND
3727
                            user_id = ".$userId." ".$session_condition;
3728
                // Ignore errors as some tables might not have the progress field just yet.
3729
                Database::query($sql);
3730
                $this->progress_db = $progress;
3731
3732
                if (100 == $progress) {
3733
                    Container::getEventDispatcher()->dispatch(
3734
                        new LearningPathEndedEvent(['lp_view_id' => $this->lp_view_id]),
3735
                        Events::LP_ENDED
3736
                    );
3737
                }
3738
            }
3739
        }
3740
    }
3741
3742
    /**
3743
     * Sets the current item ID (checks if valid and authorized first).
3744
     *
3745
     * @param int $item_id New item ID. If not given or not authorized, defaults to current
3746
     */
3747
    public function set_current_item($item_id = null)
3748
    {
3749
        $debug = $this->debug;
3750
        if ($debug) {
3751
            error_log('In learnpath::set_current_item('.$item_id.')', 0);
3752
        }
3753
        if (empty($item_id)) {
3754
            if ($debug) {
3755
                error_log('No new current item given, ignore...', 0);
3756
            }
3757
            // Do nothing.
3758
        } else {
3759
            if ($debug) {
3760
                error_log('New current item given is '.$item_id.'...', 0);
3761
            }
3762
            if (is_numeric($item_id)) {
3763
                $item_id = (int) $item_id;
3764
                // TODO: Check in database here.
3765
                $this->last = $this->current;
3766
                $this->current = $item_id;
3767
                // TODO: Update $this->index as well.
3768
                foreach ($this->ordered_items as $index => $item) {
3769
                    if ($item == $this->current) {
3770
                        $this->index = $index;
3771
                        break;
3772
                    }
3773
                }
3774
                if ($debug) {
3775
                    error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
3776
                }
3777
            } else {
3778
                if ($debug) {
3779
                    error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
3780
                }
3781
            }
3782
        }
3783
    }
3784
3785
    /**
3786
     * Set index specified prefix terms for all items in this path.
3787
     *
3788
     * @param string $terms_string Comma-separated list of terms
3789
     * @param string $prefix       Xapian term prefix
3790
     *
3791
     * @return bool False on error, true otherwise
3792
     */
3793
    public function set_terms_by_prefix($terms_string, $prefix)
3794
    {
3795
        $course_id = api_get_course_int_id();
3796
        if ('true' !== api_get_setting('search_enabled')) {
3797
            return false;
3798
        }
3799
3800
        if (!extension_loaded('xapian')) {
3801
            return false;
3802
        }
3803
3804
        $terms_string = trim($terms_string);
3805
        $terms = explode(',', $terms_string);
3806
        array_walk($terms, 'trim_value');
3807
        $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
3808
3809
        // Don't do anything if no change, verify only at DB, not the search engine.
3810
        if ((0 == count(array_diff($terms, $stored_terms))) && (0 == count(array_diff($stored_terms, $terms)))) {
3811
            return false;
3812
        }
3813
3814
        require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
3815
        require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
3816
3817
        $items_table = Database::get_course_table(TABLE_LP_ITEM);
3818
        // TODO: Make query secure agains XSS : use member attr instead of post var.
3819
        $lp_id = (int) $_POST['lp_id'];
3820
        $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
3821
        $result = Database::query($sql);
3822
        $di = new ChamiloIndexer();
3823
3824
        while ($lp_item = Database::fetch_array($result)) {
3825
            // Get search_did.
3826
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
3827
            $sql = 'SELECT * FROM %s
3828
                    WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
3829
                    LIMIT 1';
3830
            $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
3831
3832
            //echo $sql; echo '<br>';
3833
            $res = Database::query($sql);
3834
            if (Database::num_rows($res) > 0) {
3835
                $se_ref = Database::fetch_array($res);
3836
                // Compare terms.
3837
                $doc = $di->get_document($se_ref['search_did']);
3838
                $xapian_terms = xapian_get_doc_terms($doc, $prefix);
3839
                $xterms = [];
3840
                foreach ($xapian_terms as $xapian_term) {
3841
                    $xterms[] = substr($xapian_term['name'], 1);
3842
                }
3843
3844
                $dterms = $terms;
3845
                $missing_terms = array_diff($dterms, $xterms);
3846
                $deprecated_terms = array_diff($xterms, $dterms);
3847
3848
                // Save it to search engine.
3849
                foreach ($missing_terms as $term) {
3850
                    $doc->add_term($prefix.$term, 1);
3851
                }
3852
                foreach ($deprecated_terms as $term) {
3853
                    $doc->remove_term($prefix.$term);
3854
                }
3855
                $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
3856
                $di->getDb()->flush();
3857
            }
3858
        }
3859
3860
        return true;
3861
    }
3862
3863
    /**
3864
     * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
3865
     *
3866
     * @param int $id DB ID of the item
3867
     */
3868
    public function set_previous_item($id)
3869
    {
3870
        if ($this->debug > 0) {
3871
            error_log('In learnpath::set_previous_item()', 0);
3872
        }
3873
        $this->last = $id;
3874
    }
3875
3876
    /**
3877
     * Sets and saves the expired_on date.
3878
     *
3879
     * @return bool Returns true if author's name is not empty
3880
     */
3881
    public function set_modified_on()
3882
    {
3883
        $this->modified_on = api_get_utc_datetime();
3884
        $table = Database::get_course_table(TABLE_LP_MAIN);
3885
        $lp_id = $this->get_id();
3886
        $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
3887
                WHERE iid = $lp_id";
3888
        Database::query($sql);
3889
3890
        return true;
3891
    }
3892
3893
    /**
3894
     * Sets the object's error message.
3895
     *
3896
     * @param string $error Error message. If empty, reinits the error string
3897
     */
3898
    public function set_error_msg($error = '')
3899
    {
3900
        if ($this->debug > 0) {
3901
            error_log('In learnpath::set_error_msg()', 0);
3902
        }
3903
        if (empty($error)) {
3904
            $this->error = '';
3905
        } else {
3906
            $this->error .= $error;
3907
        }
3908
    }
3909
3910
    /**
3911
     * Launches the current item if not 'sco'
3912
     * (starts timer and make sure there is a record ready in the DB).
3913
     *
3914
     * @param bool $allow_new_attempt Whether to allow a new attempt or not
3915
     *
3916
     * @return bool
3917
     */
3918
    public function start_current_item($allow_new_attempt = false)
3919
    {
3920
        $debug = $this->debug;
3921
        if ($debug) {
3922
            error_log('In learnpath::start_current_item()');
3923
            error_log('current: '.$this->current);
3924
        }
3925
        if (0 != $this->current && isset($this->items[$this->current]) &&
3926
            is_object($this->items[$this->current])
3927
        ) {
3928
            $type = $this->get_type();
3929
            $item_type = $this->items[$this->current]->get_type();
3930
            if ($debug) {
3931
                error_log('item type: '.$item_type);
3932
                error_log('lp type: '.$type);
3933
            }
3934
            if ((2 == $type && 'sco' !== $item_type) ||
3935
                (3 == $type && 'au' !== $item_type) ||
3936
                (1 == $type && TOOL_QUIZ != $item_type && TOOL_HOTPOTATOES != $item_type)
3937
            ) {
3938
                $this->items[$this->current]->open($allow_new_attempt);
3939
                $this->autocomplete_parents($this->current);
3940
                $prereq_check = $this->prerequisites_match($this->current);
3941
                if ($debug) {
3942
                    error_log('start_current_item will save item with prereq: '.$prereq_check);
3943
                }
3944
                $this->items[$this->current]->save(false, $prereq_check);
3945
            }
3946
            // If sco, then it is supposed to have been updated by some other call.
3947
            if ('sco' === $item_type) {
3948
                $this->items[$this->current]->restart();
3949
            }
3950
        }
3951
        if ($debug) {
3952
            error_log('lp_view_session_id');
3953
            error_log($this->lp_view_session_id);
3954
            error_log('api session id');
3955
            error_log(api_get_session_id());
3956
            error_log('End of learnpath::start_current_item()');
3957
        }
3958
3959
        return true;
3960
    }
3961
3962
    /**
3963
     * Stops the processing and counters for the old item (as held in $this->last).
3964
     *
3965
     * @return bool True/False
3966
     */
3967
    public function stop_previous_item()
3968
    {
3969
        $debug = $this->debug;
3970
        if ($debug) {
3971
            error_log('In learnpath::stop_previous_item()', 0);
3972
        }
3973
3974
        if (0 != $this->last && $this->last != $this->current &&
3975
            isset($this->items[$this->last]) && is_object($this->items[$this->last])
3976
        ) {
3977
            if ($debug) {
3978
                error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
3979
            }
3980
            switch ($this->get_type()) {
3981
                case '3':
3982
                    if ('au' != $this->items[$this->last]->get_type()) {
3983
                        if ($debug) {
3984
                            error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
3985
                        }
3986
                        $this->items[$this->last]->close();
3987
                    } else {
3988
                        if ($debug) {
3989
                            error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
3990
                        }
3991
                    }
3992
                    break;
3993
                case '2':
3994
                    if ('sco' != $this->items[$this->last]->get_type()) {
3995
                        if ($debug) {
3996
                            error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
3997
                        }
3998
                        $this->items[$this->last]->close();
3999
                    } else {
4000
                        if ($debug) {
4001
                            error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
4002
                        }
4003
                    }
4004
                    break;
4005
                case '1':
4006
                default:
4007
                    if ($debug) {
4008
                        error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
4009
                    }
4010
                    $this->items[$this->last]->close();
4011
                    break;
4012
            }
4013
        } else {
4014
            if ($debug) {
4015
                error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
4016
            }
4017
4018
            return false;
4019
        }
4020
4021
        return true;
4022
    }
4023
4024
    /**
4025
     * Updates the default view mode from fullscreen to embedded and inversely.
4026
     *
4027
     * @return string The current default view mode ('fullscreen' or 'embedded')
4028
     */
4029
    public function update_default_view_mode()
4030
    {
4031
        $table = Database::get_course_table(TABLE_LP_MAIN);
4032
        $sql = "SELECT * FROM $table
4033
                WHERE iid = ".$this->get_id();
4034
        $res = Database::query($sql);
4035
        if (Database::num_rows($res) > 0) {
4036
            $row = Database::fetch_array($res);
4037
            $default_view_mode = $row['default_view_mod'];
4038
            $view_mode = $default_view_mode;
4039
            switch ($default_view_mode) {
4040
                case 'fullscreen': // default with popup
4041
                    $view_mode = 'embedded';
4042
                    break;
4043
                case 'embedded': // default view with left menu
4044
                    $view_mode = 'embedframe';
4045
                    break;
4046
                case 'embedframe': //folded menu
4047
                    $view_mode = 'impress';
4048
                    break;
4049
                case 'impress':
4050
                    $view_mode = 'fullscreen';
4051
                    break;
4052
            }
4053
            $sql = "UPDATE $table SET default_view_mod = '$view_mode'
4054
                    WHERE iid = ".$this->get_id();
4055
            Database::query($sql);
4056
            $this->mode = $view_mode;
4057
4058
            return $view_mode;
4059
        }
4060
4061
        return -1;
4062
    }
4063
4064
    /**
4065
     * Updates the default behaviour about auto-commiting SCORM updates.
4066
     *
4067
     * @return bool True if auto-commit has been set to 'on', false otherwise
4068
     */
4069
    public function update_default_scorm_commit()
4070
    {
4071
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
4072
        $sql = "SELECT * FROM $lp_table
4073
                WHERE iid = ".$this->get_id();
4074
        $res = Database::query($sql);
4075
        if (Database::num_rows($res) > 0) {
4076
            $row = Database::fetch_array($res);
4077
            $force = $row['force_commit'];
4078
            if (1 == $force) {
4079
                $force = 0;
4080
                $force_return = false;
4081
            } elseif (0 == $force) {
4082
                $force = 1;
4083
                $force_return = true;
4084
            }
4085
            $sql = "UPDATE $lp_table SET force_commit = $force
4086
                    WHERE iid = ".$this->get_id();
4087
            Database::query($sql);
4088
            $this->force_commit = $force_return;
4089
4090
            return $force_return;
4091
        }
4092
4093
        return -1;
4094
    }
4095
4096
    /**
4097
     * Updates the order of learning paths (goes through all of them by order and fills the gaps).
4098
     *
4099
     * @return bool True on success, false on failure
4100
     */
4101
    public function update_display_order()
4102
    {
4103
        return;
4104
        $course_id = api_get_course_int_id();
0 ignored issues
show
Unused Code introduced by
$course_id = api_get_course_int_id() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
4105
        $table = Database::get_course_table(TABLE_LP_MAIN);
4106
        $sql = "SELECT * FROM $table
4107
                WHERE c_id = $course_id
4108
                ORDER BY display_order";
4109
        $res = Database::query($sql);
4110
        if (false === $res) {
4111
            return false;
4112
        }
4113
4114
        $num = Database::num_rows($res);
4115
        // First check the order is correct, globally (might be wrong because
4116
        // of versions < 1.8.4).
4117
        if ($num > 0) {
4118
            $i = 1;
4119
            while ($row = Database::fetch_array($res)) {
4120
                if ($row['display_order'] != $i) {
4121
                    // If we find a gap in the order, we need to fix it.
4122
                    $sql = "UPDATE $table SET display_order = $i
4123
                            WHERE iid = ".$row['iid'];
4124
                    Database::query($sql);
4125
                }
4126
                $i++;
4127
            }
4128
        }
4129
4130
        return true;
4131
    }
4132
4133
    /**
4134
     * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
4135
     *
4136
     * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
4137
     */
4138
    public function update_reinit()
4139
    {
4140
        $force = $this->prevent_reinit;
4141
        if (1 == $force) {
4142
            $force = 0;
4143
        } elseif (0 == $force) {
4144
            $force = 1;
4145
        }
4146
4147
        $table = Database::get_course_table(TABLE_LP_MAIN);
4148
        $sql = "UPDATE $table SET prevent_reinit = $force
4149
                WHERE iid = ".$this->get_id();
4150
        Database::query($sql);
4151
        $this->prevent_reinit = $force;
4152
4153
        return $force;
4154
    }
4155
4156
    /**
4157
     * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
4158
     *
4159
     * @return string 'single', 'multi' or 'seriousgame'
4160
     *
4161
     * @author ndiechburg <[email protected]>
4162
     */
4163
    public function get_attempt_mode()
4164
    {
4165
        //Set default value for seriousgame_mode
4166
        if (!isset($this->seriousgame_mode)) {
4167
            $this->seriousgame_mode = 0;
4168
        }
4169
        // Set default value for prevent_reinit
4170
        if (!isset($this->prevent_reinit)) {
4171
            $this->prevent_reinit = 1;
4172
        }
4173
        if (1 == $this->seriousgame_mode && 1 == $this->prevent_reinit) {
4174
            return 'seriousgame';
4175
        }
4176
        if (0 == $this->seriousgame_mode && 1 == $this->prevent_reinit) {
4177
            return 'single';
4178
        }
4179
        if (0 == $this->seriousgame_mode && 0 == $this->prevent_reinit) {
4180
            return 'multiple';
4181
        }
4182
4183
        return 'single';
4184
    }
4185
4186
    /**
4187
     * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
4188
     *
4189
     * @param string 'seriousgame', 'single' or 'multiple'
0 ignored issues
show
Documentation Bug introduced by
The doc comment 'seriousgame', 'single' at position 0 could not be parsed: Unknown type name ''seriousgame'' at position 0 in 'seriousgame', 'single'.
Loading history...
4190
     *
4191
     * @return bool
4192
     *
4193
     * @author ndiechburg <[email protected]>
4194
     */
4195
    public function set_attempt_mode($mode)
4196
    {
4197
        switch ($mode) {
4198
            case 'seriousgame':
4199
                $sg_mode = 1;
4200
                $prevent_reinit = 1;
4201
                break;
4202
            case 'single':
4203
                $sg_mode = 0;
4204
                $prevent_reinit = 1;
4205
                break;
4206
            case 'multiple':
4207
                $sg_mode = 0;
4208
                $prevent_reinit = 0;
4209
                break;
4210
            default:
4211
                $sg_mode = 0;
4212
                $prevent_reinit = 0;
4213
                break;
4214
        }
4215
        $this->prevent_reinit = $prevent_reinit;
4216
        $this->seriousgame_mode = $sg_mode;
4217
        $table = Database::get_course_table(TABLE_LP_MAIN);
4218
        $sql = "UPDATE $table SET
4219
                prevent_reinit = $prevent_reinit ,
4220
                seriousgame_mode = $sg_mode
4221
                WHERE iid = ".$this->get_id();
4222
        $res = Database::query($sql);
4223
        if ($res) {
4224
            return true;
4225
        } else {
4226
            return false;
4227
        }
4228
    }
4229
4230
    /**
4231
     * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
4232
     *
4233
     * @author ndiechburg <[email protected]>
4234
     */
4235
    public function switch_attempt_mode()
4236
    {
4237
        $mode = $this->get_attempt_mode();
4238
        switch ($mode) {
4239
            case 'single':
4240
                $next_mode = 'multiple';
4241
                break;
4242
            case 'multiple':
4243
                $next_mode = 'seriousgame';
4244
                break;
4245
            case 'seriousgame':
4246
            default:
4247
                $next_mode = 'single';
4248
                break;
4249
        }
4250
        $this->set_attempt_mode($next_mode);
4251
    }
4252
4253
    /**
4254
     * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
4255
     * but possibility to do again a completed item.
4256
     *
4257
     * @return bool true if seriousgame_mode has been set to 1, false otherwise
4258
     *
4259
     * @author ndiechburg <[email protected]>
4260
     */
4261
    public function set_seriousgame_mode()
4262
    {
4263
        $table = Database::get_course_table(TABLE_LP_MAIN);
4264
        $force = $this->seriousgame_mode;
4265
        if (1 == $force) {
4266
            $force = 0;
4267
        } elseif (0 == $force) {
4268
            $force = 1;
4269
        }
4270
        $sql = "UPDATE $table SET seriousgame_mode = $force
4271
                WHERE iid = ".$this->get_id();
4272
        Database::query($sql);
4273
        $this->seriousgame_mode = $force;
4274
4275
        return $force;
4276
    }
4277
4278
    /**
4279
     * Updates the "scorm_debug" value that shows or hide the debug window.
4280
     *
4281
     * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
4282
     */
4283
    public function update_scorm_debug()
4284
    {
4285
        $table = Database::get_course_table(TABLE_LP_MAIN);
4286
        $force = $this->scorm_debug;
4287
        if (1 == $force) {
4288
            $force = 0;
4289
        } elseif (0 == $force) {
4290
            $force = 1;
4291
        }
4292
        $sql = "UPDATE $table SET debug = $force
4293
                WHERE iid = ".$this->get_id();
4294
        Database::query($sql);
4295
        $this->scorm_debug = $force;
4296
4297
        return $force;
4298
    }
4299
4300
    /**
4301
     * Function that creates a html list of learning path items so that we can add audio files to them.
4302
     *
4303
     * @author Kevin Van Den Haute
4304
     *
4305
     * @return string
4306
     */
4307
    public function overview()
4308
    {
4309
        $return = '';
4310
        $update_audio = $_GET['updateaudio'] ?? null;
4311
4312
        // we need to start a form when we want to update all the mp3 files
4313
        if ('true' == $update_audio) {
4314
            $return .= '<form action="'.api_get_self().'?'.api_get_cidreq().'&updateaudio='.Security::remove_XSS(
4315
                    $_GET['updateaudio']
4316
                ).'&action='.Security::remove_XSS(
4317
                    $_GET['action']
4318
                ).'&lp_id='.$_SESSION['oLP']->lp_id.'" method="post" enctype="multipart/form-data" name="updatemp3" id="updatemp3">';
4319
        }
4320
        $return .= '<div id="message"></div>';
4321
        if (0 == count($this->items)) {
4322
            $return .= Display::return_message(
4323
                get_lang(
4324
                    'You should add some items to your learning path, otherwise you won\'t be able to attach audio files to them'
4325
                ),
4326
                'normal'
4327
            );
4328
        } else {
4329
            $return_audio = '<table class="table table-hover table-striped data_table">';
4330
            $return_audio .= '<tr>';
4331
            $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
4332
            $return_audio .= '<th>'.get_lang('Audio').'</th>';
4333
            $return_audio .= '</tr>';
4334
4335
            if ('true' != $update_audio) {
4336
                /*$return .= '<div class="col-md-12">';
4337
                $return .= self::return_new_tree($update_audio);
4338
                $return .= '</div>';*/
4339
                $return .= Display::div(
4340
                    Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn--primary']),
4341
                    ['style' => 'float:left; margin-top:15px;width:100%']
4342
                );
4343
            } else {
4344
                //$return_audio .= self::return_new_tree($update_audio);
4345
                $return .= $return_audio.'</table>';
4346
            }
4347
4348
            // We need to close the form when we are updating the mp3 files.
4349
            if ('true' == $update_audio) {
4350
                $return .= '<div class="footer-audio">';
4351
                $return .= Display::button(
4352
                    'save_audio',
4353
                    '<em class="fa fa-file-audio-o"></em> '.get_lang('Save audio and organization'),
4354
                    ['class' => 'btn btn--primary', 'type' => 'submit']
4355
                );
4356
                $return .= '</div>';
4357
            }
4358
        }
4359
4360
        // We need to close the form when we are updating the mp3 files.
4361
        if ('true' === $update_audio && isset($this->arrMenu) && 0 != count($this->arrMenu)) {
4362
            $return .= '</form>';
4363
        }
4364
4365
        return $return;
4366
    }
4367
4368
    public function showBuildSideBar($updateAudio = false, $dropElementHere = false, $type = null)
4369
    {
4370
        $sureToDelete = trim(get_lang('Are you sure to delete'));
4371
        $ajax_url = api_get_path(WEB_AJAX_PATH).'lp.ajax.php?lp_id='.$this->get_id().'&'.api_get_cidreq();
4372
4373
        $content = '
4374
    <script>
4375
    $(function() {
4376
        function enforceFinalAtEndDOM() {
4377
            var $root = $("#lp_item_list");
4378
            $root.find("li.final-item").each(function() {
4379
                $root.append(this);
4380
            });
4381
        }
4382
4383
        function refreshTree() {
4384
            var params = "&a=get_lp_item_tree";
4385
            $.get(
4386
                "'.$ajax_url.'",
4387
                params,
4388
                function(result) {
4389
                    $("#lp_item_list").html(result);
4390
                    enforceFinalAtEndDOM();
4391
                    nestedSortable();
4392
                }
4393
            );
4394
        }
4395
4396
        const nestedQuery = ".nested-sortable";
4397
        const identifier  = "id";
4398
        const root        = document.getElementById("lp_item_list");
4399
4400
        function serialize(sortable) {
4401
            var out    = [];
4402
            var finals = [];
4403
            var children = [].slice.call(sortable.children);
4404
4405
            for (var i = 0; i < children.length; i++) {
4406
                var li = children[i];
4407
                if (!li || !li.dataset) continue;
4408
4409
                var id = li.dataset[identifier];
4410
                if (!id) continue;
4411
4412
                var isFinal =
4413
                    li.classList.contains("final-item") ||
4414
                    li.dataset.type === "final_item" ||
4415
                    li.dataset.fixed === "final";
4416
4417
                var parentLi = $(li).closest("ul.nested-sortable").closest("li")[0];
4418
                var parentId = (parentLi && parentLi.dataset) ? parentLi.dataset[identifier] : null;
4419
                var rec = { id: id, parent_id: isFinal ? null : parentId };
4420
                var nested = li.querySelector(nestedQuery);
4421
                if (nested && !isFinal) {
4422
                    out = out.concat( serialize(nested) );
4423
                }
4424
4425
                (isFinal ? finals : out).push(rec);
4426
            }
4427
4428
            return out.concat(finals);
4429
        }
4430
4431
        function nestedSortable() {
4432
            let lists = document.getElementsByClassName("nested-sortable");
4433
            Array.prototype.forEach.call(lists, function(ul) {
4434
                Sortable.create(ul, {
4435
                    group: "nested",
4436
                    put: ["nested-sortable", ".lp_resource", ".nested-source"],
4437
                    animation: 150,
4438
                    swapThreshold: 0.65,
4439
                    dataIdAttr: "data-id",
4440
                    filter: ".disable_drag",
4441
                    onMove: function (evt) {
4442
                        var t = evt.dragged && evt.dragged.dataset ? evt.dragged.dataset.type : null;
4443
                        if (t === "final_item") return false;
4444
                    },
4445
                    onEnd: function(evt) {
4446
                        if (evt.item && (evt.item.classList.contains("final-item") || evt.item.dataset.type === "final_item")) {
4447
                            enforceFinalAtEndDOM();
4448
                            return;
4449
                        }
4450
                        enforceFinalAtEndDOM();
4451
4452
                        let list  = serialize(root);
4453
                        let order = "&a=update_lp_item_order&new_order=" + JSON.stringify(list);
4454
4455
                        $.get(
4456
                            "'.$ajax_url.'",
4457
                            order,
4458
                            function(reponse) {
4459
                                $("#message").html(reponse);
4460
                                refreshTree();
4461
                            }
4462
                        );
4463
                    },
4464
                });
4465
            });
4466
        }
4467
4468
        nestedSortable();
4469
4470
        let resources = document.getElementsByClassName("lp_resource");
4471
        Array.prototype.forEach.call(resources, function(resource) {
4472
            Sortable.create(resource, {
4473
                group: "nested",
4474
                put: ["nested-sortable"],
4475
                filter: ".disable_drag",
4476
                animation: 150,
4477
                fallbackOnBody: true,
4478
                swapThreshold: 0.65,
4479
                dataIdAttr: "data-id",
4480
                onRemove: function(evt) {
4481
                    var itemEl   = evt.item;
4482
                    var newIndex = evt.newIndex;
4483
                    var id       = $(itemEl).attr("id");
4484
                    var parentId = $(itemEl).parent().parent().attr("id");
4485
                    var type     = $(itemEl).find(".link_with_id").attr("data_type");
4486
                    var title    = $(itemEl).find(".link_with_id").text();
4487
4488
                    let previousId = 0;
4489
                    if (0 !== newIndex) {
4490
                        previousId = $(itemEl).prev().attr("id");
4491
                    }
4492
4493
                    var params = {
4494
                        "a": "add_lp_item",
4495
                        "id": id,
4496
                        "parent_id": parentId,
4497
                        "previous_id": previousId,
4498
                        "type": type,
4499
                        "title" : title
4500
                    };
4501
4502
                    $.ajax({
4503
                        type: "GET",
4504
                        url: "'.$ajax_url.'",
4505
                        data: params,
4506
                        success: function(itemId) {
4507
                            $(itemEl).attr("id", itemId);
4508
                            $(itemEl).attr("data-id", itemId);
4509
4510
                            enforceFinalAtEndDOM();
4511
4512
                            let list = serialize(root);
4513
                            let listInString = JSON.stringify(list) || "[]";
4514
                            let order = "&a=update_lp_item_order&new_order=" + listInString;
4515
4516
                            $.get(
4517
                                "'.$ajax_url.'",
4518
                                order,
4519
                                function(reponse) {
4520
                                    $("#message").html(reponse);
4521
                                    refreshTree();
4522
                                }
4523
                            );
4524
                        }
4525
                    });
4526
                },
4527
            });
4528
        });
4529
    });
4530
    </script>';
4531
4532
        $content .= "
4533
    <script>
4534
        function confirmation(name) {
4535
            return confirm('$sureToDelete ' + name);
4536
        }
4537
        function refreshTree() {
4538
            var params = '&a=get_lp_item_tree';
4539
            $.get(
4540
                '".$ajax_url."',
4541
                params,
4542
                function(result) {
4543
                    $('#lp_item_list').html(result);
4544
                }
4545
            );
4546
        }
4547
4548
        $(function () {
4549
            expandColumnToggle('#hide_bar_template', { selector: '#lp_sidebar' }, { selector: '#doc_form' });
4550
4551
            $('.lp-btn-associate-forum').on('click', function (e) {
4552
                var ok = confirm('".get_lang('This action will associate a forum thread to this learning path item. Do you want to proceed?')."');
4553
                if (!ok) e.preventDefault();
4554
            });
4555
4556
            $('.lp-btn-dissociate-forum').on('click', function (e) {
4557
                var ok = confirm('".get_lang('This action will dissociate the forum thread of this learning path item. Do you want to proceed?')."');
4558
                if (!ok) e.preventDefault();
4559
            });
4560
4561
            $('#frmModel').hide();
4562
        });
4563
4564
        function deleteItem(event) {
4565
            var id = $(event).attr('data-id');
4566
            var title = $(event).attr('data-title');
4567
            var params = '&a=delete_item&id=' + id;
4568
            if (confirmation(title)) {
4569
                $.get(
4570
                    '".$ajax_url."',
4571
                    params,
4572
                    function(result) {
4573
                        refreshTree();
4574
                    }
4575
                );
4576
            }
4577
        }
4578
    </script>";
4579
4580
        $content .= $this->return_new_tree($updateAudio, $dropElementHere);
4581
        $documentId = isset($_GET['path_item']) ? (int) $_GET['path_item'] : 0;
4582
4583
        $repo = Container::getDocumentRepository();
4584
        $document = $repo->find($documentId);
4585
        if ($document) {
4586
            // Show the template list
4587
            $content .= '<div id="frmModel" class="scrollbar-inner lp-add-item"></div>';
4588
        }
4589
4590
        // Show the template list.
4591
        if (('document' === $type || 'step' === $type) && !isset($_GET['file'])) {
4592
            // Show the template list.
4593
            $content .= '<div id="frmModel" class="scrollbar-inner lp-add-item"></div>';
4594
        }
4595
4596
        return $content;
4597
    }
4598
4599
    /**
4600
     * @param bool  $updateAudio
4601
     * @param bool   $dropElement
4602
     *
4603
     * @return string
4604
     */
4605
    public function return_new_tree($updateAudio = false, $dropElement = false)
4606
    {
4607
        $list = $this->getBuildTree(false, $dropElement);
4608
        $return = Display::panelCollapse(
4609
            $this->name,
4610
            $list,
4611
            'scorm-list',
4612
            null,
4613
            'scorm-list-accordion',
4614
            'scorm-list-collapse'
4615
        );
4616
4617
        if ($updateAudio) {
4618
            //$return = $result['return_audio'];
4619
        }
4620
4621
        return $return;
4622
    }
4623
4624
    public function getBuildTree($noWrapper = false, $dropElement = false): string
4625
    {
4626
        $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
4627
        $upIcon = Display::getMdiIcon('arrow-up-bold', 'ch-tool-icon', '', 16, get_lang('Up'));
4628
        $disableUpIcon = Display::getMdiIcon('arrow-up-bold', 'ch-tool-icon-disabled', '', 16, get_lang('Up'));
4629
        $downIcon = Display::getMdiIcon('arrow-down-bold', 'ch-tool-icon', '', 16, get_lang('Down'));
4630
        $previewImage = Display::getMdiIcon('magnify-plus-outline', 'ch-tool-icon', '', 16, get_lang('Preview'));
4631
4632
        $lpItemRepo = Container::getLpItemRepository();
4633
        $itemRoot = $lpItemRepo->getRootItem($this->get_id());
4634
4635
        $options = [
4636
            'decorate' => true,
4637
            'rootOpen' => function($tree) use ($noWrapper) {
4638
                if ($tree[0]['lvl'] === 1) {
4639
                    if ($noWrapper) {
4640
                        return '';
4641
                    }
4642
                    return '<ul id="lp_item_list" class="list-group nested-sortable">';
4643
                }
4644
4645
                return '<ul class="list-group nested-sortable">';
4646
            },
4647
            'rootClose' => function($tree) use ($noWrapper, $dropElement)  {
4648
                if ($tree[0]['lvl'] === 1) {
4649
                    if ($dropElement) {
4650
                        //return Display::return_message(get_lang('Drag and drop an element here'));
4651
                        //return $this->getDropElementHtml();
4652
                    }
4653
                    if ($noWrapper) {
4654
                        return '';
4655
                    }
4656
                }
4657
4658
                return '</ul>';
4659
            },
4660
            'childOpen' => function($child) {
4661
                $id   = $child['iid'];
4662
                $type = $child['itemType'] ?? ($child['item_type'] ?? '');
4663
                $isFinal = (TOOL_LP_FINAL_ITEM === $type);
4664
                $extraClass = $isFinal ? ' final-item disable_drag' : '';
4665
                $extraAttr  = $isFinal ? ' data-fixed="final"' : '';
4666
4667
                return '<li
4668
                    id="'.$id.'"
4669
                    data-id="'.$id.'"
4670
                    data-type="'.$type.'"
4671
                    '.$extraAttr.'
4672
                    class="flex flex-col list-group-item nested-'.$child['lvl'].$extraClass.'">';
4673
            },
4674
            'childClose' => '',
4675
            'nodeDecorator' => function ($node) use ($mainUrl, $previewImage, $upIcon, $downIcon) {
4676
                $fullTitle = $node['title'];
4677
                //$title = cut($fullTitle, self::MAX_LP_ITEM_TITLE_LENGTH);
4678
                $title = $fullTitle;
4679
                $itemId = $node['iid'];
4680
                $type = $node['itemType'];
4681
                $lpId = $this->get_id();
4682
4683
                $moveIcon = '';
4684
                if (TOOL_LP_FINAL_ITEM !== $type) {
4685
                    $moveIcon .= '<a class="moved" href="#">';
4686
                    $moveIcon .= Display::getMdiIcon('cursor-move', 'ch-tool-icon', '', 16, get_lang('Move'));
4687
                    $moveIcon .= '</a>';
4688
                }
4689
4690
                $iconName = str_replace(' ', '', $type);
4691
                $icon = '';
4692
                switch ($iconName) {
4693
                    case 'category':
4694
                    case 'chapter':
4695
                    case 'folder':
4696
                    case 'dir':
4697
                        $icon = Display::getMdiIcon(ObjectIcon::CHAPTER, 'ch-tool-icon', '', ICON_SIZE_TINY);
4698
                        break;
4699
                    default:
4700
                        $icon = Display::getMdiIcon(ObjectIcon::SINGLE_ELEMENT, 'ch-tool-icon', '', ICON_SIZE_TINY);
4701
                        break;
4702
                }
4703
4704
                $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$itemId.'&lp_id='.$lpId;
4705
                $previewIcon = Display::url(
4706
                    $previewImage,
4707
                    $urlPreviewLink,
4708
                    [
4709
                        'target' => '_blank',
4710
                        'class' => 'btn btn--plain',
4711
                        'data-title' => $title,
4712
                        'title' => $title,
4713
                    ]
4714
                );
4715
                $url = $mainUrl.'&view=build&id='.$itemId.'&lp_id='.$lpId;
4716
4717
                $preRequisitesIcon = Display::url(
4718
                    Display::getMdiIcon('graph', 'ch-tool-icon', '', 16, get_lang('Prerequisites')),
4719
                    $url.'&action=edit_item_prereq',
4720
                    ['class' => '']
4721
                );
4722
4723
                $editIcon = '<a
4724
                    href="'.$mainUrl.'&action=edit_item&view=build&id='.$itemId.'&lp_id='.$lpId.'&path_item='.$node['path'].'"
4725
                    class=""
4726
                    >';
4727
                $editIcon .= Display::getMdiIcon('pencil', 'ch-tool-icon', '', 16, get_lang('Edit section description/name'));
4728
                $editIcon .= '</a>';
4729
                $orderIcons = '';
4730
                /*if ('final_item' !== $type) {
4731
                    $orderIcons = Display::url(
4732
                        $upIcon,
4733
                        'javascript:void(0)',
4734
                        ['class' => 'btn btn--plain order_items', 'data-dir' => 'up', 'data-id' => $itemId]
4735
                    );
4736
                    $orderIcons .= Display::url(
4737
                        $downIcon,
4738
                        'javascript:void(0)',
4739
                        ['class' => 'btn btn--plain order_items', 'data-dir' => 'down', 'data-id' => $itemId]
4740
                    );
4741
                }*/
4742
4743
                $deleteIcon = ' <a
4744
                    data-id = '.$itemId.'
4745
                    data-title = \''.addslashes($title).'\'
4746
                    href="javascript:void(0);"
4747
                    onclick="return deleteItem(this);"
4748
                    class="">';
4749
                $deleteIcon .= Display::getMdiIcon('delete', 'ch-tool-icon', '', 16, get_lang('Delete section'));
4750
                $deleteIcon .= '</a>';
4751
                $extra = '';
4752
4753
                if ('dir' === $type && empty($node['__children'])) {
4754
                    $level = $node['lvl'] + 1;
4755
                    $extra = '<ul class="list-group nested-sortable">
4756
                                <li class="list-group-item list-group-item-empty nested-'.$level.'"></li>
4757
                              </ul>';
4758
                }
4759
4760
                $buttons = Display::tag(
4761
                    'div',
4762
                    "<div class=\"btn-group btn-group-sm\">
4763
                                $editIcon
4764
                                $preRequisitesIcon
4765
                                $orderIcons
4766
                                $deleteIcon
4767
                               </div>",
4768
                    ['class' => 'btn-toolbar button_actions']
4769
                );
4770
4771
                return
4772
                    "<div class='flex flex-row'> $moveIcon  $icon <span class='mx-1'>$title </span></div>
4773
                    $extra
4774
                    $buttons
4775
                    "
4776
                    ;
4777
            },
4778
        ];
4779
4780
        $tree = $lpItemRepo->childrenHierarchy($itemRoot, false, $options);
4781
4782
        if (empty($tree) && $dropElement) {
4783
            return $this->getDropElementHtml($noWrapper);
4784
        }
4785
4786
        return $tree;
4787
    }
4788
4789
    public function getDropElementHtml($noWrapper = false)
4790
    {
4791
        $li = '<li class="list-group-item">'.
4792
            Display::return_message(get_lang('Drag and drop an element here')).
4793
            '</li>';
4794
        if ($noWrapper) {
4795
            return $li;
4796
        }
4797
4798
        return
4799
            '<ul id="lp_item_list" class="list-group nested-sortable">
4800
            '.$li.'
4801
            </ul>';
4802
    }
4803
4804
    /**
4805
     * This function builds the action menu.
4806
     *
4807
     * @param bool   $returnString           Optional
4808
     * @param bool   $showRequirementButtons Optional. Allow show the requirements button
4809
     * @param bool   $isConfigPage           Optional. If is the config page, show the edit button
4810
     * @param bool   $allowExpand            Optional. Allow show the expand/contract button
4811
     * @param string $action
4812
     * @param array  $extraField
4813
     *
4814
     * @return string
4815
     */
4816
    public function build_action_menu(
4817
        $returnString = false,
4818
        $showRequirementButtons = true,
4819
        $isConfigPage = false,
4820
        $allowExpand = true,
4821
        $action = '',
4822
        $extraField = []
4823
    ) {
4824
        $actionsRight = '';
4825
        $lpId = $this->lp_id;
4826
        if (!isset($extraField['backTo']) && empty($extraField['backTo'])) {
4827
            $back = Display::url(
4828
                Display::getMdiIcon('arrow-left-bold-box', 'ch-tool-icon', '', 32, get_lang('Back to learning paths')),
4829
                'lp_controller.php?'.api_get_cidreq()
4830
            );
4831
        } else {
4832
            $back = Display::url(
4833
                Display::getMdiIcon('arrow-left-bold-box', 'ch-tool-icon', '', 32, get_lang('Back')),
4834
                $extraField['backTo']
4835
            );
4836
        }
4837
4838
        /*if ($backToBuild) {
4839
            $back = Display::url(
4840
                Display::getMdiIcon('arrow-left-bold-box', 'ch-tool-icon', null, 32, get_lang('Go back')),
4841
                "lp_controller.php?action=add_item&type=step&lp_id=$lpId&".api_get_cidreq()
4842
            );
4843
        }*/
4844
4845
        $actionsLeft = $back;
4846
4847
        $actionsLeft .= Display::url(
4848
            Display::getMdiIcon('magnify-plus-outline', 'ch-tool-icon', '', 32, get_lang('Preview')),
4849
            'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
4850
                'action' => 'view',
4851
                'lp_id' => $lpId,
4852
                'isStudentView' => 'true',
4853
            ])
4854
        );
4855
4856
        /*$actionsLeft .= Display::url(
4857
            Display::getMdiIcon('music-note-plus', 'ch-tool-icon', null, 32, get_lang('Add audio')),
4858
            'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
4859
                'action' => 'admin_view',
4860
                'lp_id' => $lpId,
4861
                'updateaudio' => 'true',
4862
            ])
4863
        );*/
4864
4865
        $subscriptionSettings = self::getSubscriptionSettings();
4866
4867
        $request = api_request_uri();
4868
        if (false === strpos($request, 'edit')) {
4869
            $actionsLeft .= Display::url(
4870
                Display::getMdiIcon('hammer-wrench', 'ch-tool-icon', '', 32, get_lang('Course settings')),
4871
                'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
4872
                    'action' => 'edit',
4873
                    'lp_id' => $lpId,
4874
                ])
4875
            );
4876
        }
4877
4878
        if ((false === strpos($request, 'build') &&
4879
            false === strpos($request, 'add_item')) ||
4880
            in_array($action, ['add_audio'], true)
4881
        ) {
4882
            $actionsLeft .= Display::url(
4883
                Display::getMdiIcon('pencil', 'ch-tool-icon', '', 32, get_lang('Edit')),
4884
                'lp_controller.php?'.http_build_query([
4885
                    'action' => 'build',
4886
                    'lp_id' => $lpId,
4887
                ]).'&'.api_get_cidreq()
4888
            );
4889
        }
4890
4891
        if (false === strpos(api_get_self(), 'lp_subscribe_users.php')) {
4892
            if (1 == $this->subscribeUsers &&
4893
                $subscriptionSettings['allow_add_users_to_lp']) {
4894
                $actionsLeft .= Display::url(
4895
                    Display::getMdiIcon('account-multiple-plus', 'ch-tool-icon', '', 32, get_lang('Subscribe users to learning path')),
4896
                    api_get_path(WEB_CODE_PATH)."lp/lp_subscribe_users.php?lp_id=$lpId&".api_get_cidreq()
4897
                );
4898
            }
4899
        }
4900
4901
        if ($allowExpand) {
4902
            /*$actionsLeft .= Display::url(
4903
                Display::getMdiIcon('arrow-expand-all', 'ch-tool-icon', null, 32, get_lang('Expand')).
4904
                Display::getMdiIcon('arrow-collapse-all', 'ch-tool-icon', null, 32, get_lang('Collapse')),
4905
                '#',
4906
                ['role' => 'button', 'id' => 'hide_bar_template']
4907
            );*/
4908
        }
4909
4910
        if ($showRequirementButtons) {
4911
            $buttons = [
4912
                [
4913
                    'title' => get_lang('Set previous step as prerequisite for each step'),
4914
                    'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
4915
                        'action' => 'set_previous_step_as_prerequisite',
4916
                        'lp_id' => $lpId,
4917
                    ]),
4918
                ],
4919
                [
4920
                    'title' => get_lang('Clear all prerequisites'),
4921
                    'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
4922
                        'action' => 'clear_prerequisites',
4923
                        'lp_id' => $lpId,
4924
                    ]),
4925
                ],
4926
            ];
4927
            $actionsRight = Display::groupButtonWithDropDown(
4928
                get_lang('Prerequisites options'),
4929
                $buttons,
4930
                true
4931
            );
4932
        }
4933
4934
        if (api_is_platform_admin() && isset($extraField['authorlp'])) {
4935
            $actionsLeft .= Display::url(
4936
                Display::getMdiIcon('account-multiple-plus', 'ch-tool-icon', '', 32, get_lang('Author')),
4937
                'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
4938
                    'action' => 'author_view',
4939
                    'lp_id' => $lpId,
4940
                ])
4941
            );
4942
        }
4943
4944
        $toolbar = Display::toolbarAction('actions-lp-controller', [$actionsLeft, $actionsRight]);
4945
4946
        if ($returnString) {
4947
            return $toolbar;
4948
        }
4949
4950
        echo $toolbar;
4951
    }
4952
4953
    /**
4954
     * Creates the default learning path folder.
4955
     *
4956
     * @param array $course
4957
     * @param int   $creatorId
4958
     *
4959
     * @return CDocument
4960
     */
4961
    public static function generate_learning_path_folder($course, $creatorId = 0)
4962
    {
4963
        // Creating learning_path folder
4964
        $dir = 'learning_path';
4965
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
4966
4967
        return create_unexisting_directory(
4968
            $course,
4969
            $creatorId,
4970
            0,
4971
            null,
4972
            0,
4973
            '',
4974
            $dir,
4975
            get_lang('Learning paths'),
4976
            0
4977
        );
4978
    }
4979
4980
    /**
4981
     * @param array  $course
4982
     * @param string $lp_name
4983
     * @param int    $creatorId
4984
     *
4985
     * @return CDocument
4986
     */
4987
    public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
4988
    {
4989
        $filepath = '';
4990
        $dir = '/learning_path/';
4991
4992
        if (empty($lp_name)) {
4993
            $lp_name = $this->name;
4994
        }
4995
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
4996
        $parent = self::generate_learning_path_folder($course, $creatorId);
4997
4998
        // Limits title size
4999
        $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
5000
        $dir = $dir.$title;
5001
5002
        // Creating LP folder
5003
        $folder = null;
5004
        if ($parent) {
5005
            $folder = create_unexisting_directory(
5006
                $course,
5007
                $creatorId,
5008
                0,
5009
                0,
5010
                0,
5011
                $filepath,
5012
                $dir,
5013
                $lp_name,
5014
                '',
5015
                false,
5016
                false,
5017
                $parent
5018
            );
5019
        }
5020
5021
        return $folder;
5022
    }
5023
5024
    /**
5025
     * Create a new document //still needs some finetuning.
5026
     *
5027
     * @param array  $courseInfo
5028
     * @param string $content
5029
     * @param string $title
5030
     * @param string $extension
5031
     * @param int    $parentId
5032
     * @param int    $creatorId  creator id
5033
     *
5034
     * @return int
5035
     */
5036
    public function create_document(
5037
        $courseInfo,
5038
        $content = '',
5039
        $title = '',
5040
        $extension = 'html',
5041
        $parentId = 0,
5042
        $creatorId = 0,
5043
        $docFiletype = 'file'
5044
    ) {
5045
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
5046
        $sessionId = api_get_session_id();
5047
5048
        // Generates folder
5049
        $this->generate_lp_folder($courseInfo);
5050
        // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
5051
        // is already escaped twice when it gets here.
5052
        $originalTitle = !empty($title) ? $title : $_POST['title'];
5053
        if (!empty($title)) {
5054
            $title = api_replace_dangerous_char(stripslashes($title));
5055
        } else {
5056
            $title = api_replace_dangerous_char(stripslashes($_POST['title']));
5057
        }
5058
5059
        $title = disable_dangerous_file($title);
5060
        $filename = $title;
5061
        $tmp_filename = "$filename.$extension";
5062
        /*$i = 0;
5063
        while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
5064
            $tmp_filename = $filename.'_'.++$i;
5065
        }*/
5066
        $filename = $tmp_filename.'.'.$extension;
5067
5068
        if ('html' === $extension) {
5069
            $content = stripslashes($content);
5070
            $content = str_replace(
5071
                api_get_path(WEB_COURSE_PATH),
5072
                api_get_path(REL_PATH).'courses/',
5073
                $content
5074
            );
5075
            $content = str_replace(
5076
                '</body>',
5077
                '<style type="text/css">body{}</style></body>',
5078
                $content
5079
            );
5080
        }
5081
5082
        $document = DocumentManager::addDocument(
5083
            $courseInfo,
5084
            null,
5085
            $docFiletype,
5086
            '',
5087
            $tmp_filename,
5088
            '',
5089
            0, //readonly
5090
            true,
5091
            null,
5092
            $sessionId,
5093
            $creatorId,
5094
            false,
5095
            $content,
5096
            $parentId
5097
        );
5098
5099
        $document_id = $document->getIid();
5100
        if ($document_id) {
5101
            $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
5102
            $new_title = $originalTitle;
5103
5104
            if ($new_comment || $new_title) {
5105
                $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
5106
                $ct = '';
5107
                if ($new_comment) {
5108
                    $ct .= ", comment='".Database::escape_string($new_comment)."'";
5109
                }
5110
                if ($new_title) {
5111
                    $ct .= ", title='".Database::escape_string($new_title)."' ";
5112
                }
5113
5114
                $sql = "UPDATE $tbl_doc SET ".substr($ct, 1)."
5115
                        WHERE iid = $document_id ";
5116
                Database::query($sql);
5117
            }
5118
        }
5119
5120
        return $document_id;
5121
    }
5122
5123
    /**
5124
     * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
5125
     */
5126
    public function edit_document()
5127
    {
5128
        $repo = Container::getDocumentRepository();
5129
        if (isset($_REQUEST['document_id']) && !empty($_REQUEST['document_id'])) {
5130
            $id = (int) $_REQUEST['document_id'];
5131
            /** @var CDocument $document */
5132
            $document = $repo->find($id);
5133
            if ($document->getResourceNode()->hasEditableTextContent()) {
5134
                $repo->updateResourceFileContent($document, $_REQUEST['content_lp']);
5135
            }
5136
            $document->setTitle($_REQUEST['title']);
5137
            $repo->update($document);
5138
        }
5139
    }
5140
5141
    /**
5142
     * Displays the selected item, with a panel for manipulating the item.
5143
     *
5144
     * @param CLpItem $lpItem
5145
     * @param string  $msg
5146
     * @param bool    $show_actions
5147
     *
5148
     * @return string
5149
     */
5150
    public function display_item($lpItem, $msg = null, $show_actions = true)
5151
    {
5152
        $course_id = api_get_course_int_id();
5153
        $return = '';
5154
5155
        if (null === $lpItem) {
5156
            return '';
5157
        }
5158
        $item_id = $lpItem->getIid();
5159
        $itemType = $lpItem->getItemType();
5160
        $lpId = $lpItem->getLp()->getIid();
5161
        $path = $lpItem->getPath();
5162
5163
        Session::write('parent_item_id', 'dir' === $itemType ? $item_id : 0);
5164
5165
        // Prevents wrong parent selection for document, see Bug#1251.
5166
        if ('dir' !== $itemType) {
5167
            Session::write('parent_item_id', $lpItem->getParentItemId());
5168
        }
5169
5170
        if ($show_actions) {
5171
            $return .= $this->displayItemMenu($lpItem);
5172
        }
5173
        $return .= '<div style="padding:10px;">';
5174
5175
        if ('' != $msg) {
5176
            $return .= $msg;
5177
        }
5178
5179
        $return .= '<h3>'.$lpItem->getTitle().'</h3>';
5180
5181
        switch ($itemType) {
5182
            case TOOL_THREAD:
5183
                $link = $this->rl_get_resource_link_for_learnpath(
5184
                    $course_id,
5185
                    $lpId,
5186
                    $item_id,
5187
                    0
5188
                );
5189
                $return .= Display::url(
5190
                    get_lang('Go to thread'),
5191
                    $link,
5192
                    ['class' => 'btn btn--primary']
5193
                );
5194
                break;
5195
            case TOOL_FORUM:
5196
                $return .= Display::url(
5197
                    get_lang('Go to the forum'),
5198
                    api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$path,
5199
                    ['class' => 'btn btn--primary']
5200
                );
5201
                break;
5202
            case TOOL_QUIZ:
5203
                if (!empty($path)) {
5204
                    $exercise = new Exercise();
5205
                    $exercise->read($path);
5206
                    $return .= $exercise->description.'<br />';
5207
                    $return .= Display::url(
5208
                        get_lang('Go to exercise'),
5209
                        api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
5210
                        ['class' => 'btn btn--primary']
5211
                    );
5212
                }
5213
                break;
5214
            case TOOL_LP_FINAL_ITEM:
5215
                $return .= $this->getSavedFinalItem();
5216
                break;
5217
            case TOOL_DOCUMENT:
5218
            case 'video':
5219
            case TOOL_READOUT_TEXT:
5220
                $repo = Container::getDocumentRepository();
5221
                /** @var CDocument $document */
5222
                $document = $repo->find($lpItem->getPath());
5223
                $return .= $this->display_document($document, true, true);
5224
                break;
5225
        }
5226
        $return .= '</div>';
5227
5228
        return $return;
5229
    }
5230
5231
    /**
5232
     * Shows the needed forms for editing a specific item.
5233
     *
5234
     * @param CLpItem $lpItem
5235
     *
5236
     * @throws Exception
5237
     *
5238
     *
5239
     * @return string
5240
     */
5241
    public function display_edit_item($lpItem, $excludeExtraFields = [])
5242
    {
5243
        $return = '';
5244
        if (empty($lpItem)) {
5245
            return '';
5246
        }
5247
        $itemType = $lpItem->getItemType();
5248
        $path = $lpItem->getPath();
5249
5250
        switch ($itemType) {
5251
            case 'dir':
5252
            case 'asset':
5253
            case 'sco':
5254
                if (isset($_GET['view']) && 'build' === $_GET['view']) {
5255
                    $return .= $this->displayItemMenu($lpItem);
5256
                    $return .= $this->display_item_form($lpItem, 'edit');
5257
                } else {
5258
                    $return .= $this->display_item_form($lpItem, 'edit_item');
5259
                }
5260
                break;
5261
            case TOOL_LP_FINAL_ITEM:
5262
            case TOOL_DOCUMENT:
5263
            case 'video':
5264
            case TOOL_READOUT_TEXT:
5265
                $return .= $this->displayItemMenu($lpItem);
5266
                $return .= $this->displayDocumentForm('edit', $lpItem);
5267
                break;
5268
            case TOOL_LINK:
5269
                $link = null;
5270
                if (!empty($path)) {
5271
                    $repo = Container::getLinkRepository();
5272
                    $link = $repo->find($path);
5273
                }
5274
                $return .= $this->displayItemMenu($lpItem);
5275
                $return .= $this->display_link_form('edit', $lpItem, $link);
5276
5277
                break;
5278
            case TOOL_QUIZ:
5279
                if (!empty($path)) {
5280
                    $repo = Container::getQuizRepository();
5281
                    $resource = $repo->find($path);
5282
                }
5283
                $return .= $this->displayItemMenu($lpItem);
5284
                $return .= $this->display_quiz_form('edit', $lpItem, $resource);
5285
                break;
5286
            case TOOL_STUDENTPUBLICATION:
5287
                if (!empty($path)) {
5288
                    $repo = Container::getStudentPublicationRepository();
5289
                    $resource = $repo->find($path);
5290
                }
5291
                $return .= $this->displayItemMenu($lpItem);
5292
                $return .= $this->display_student_publication_form('edit', $lpItem, $resource);
5293
                break;
5294
            case TOOL_FORUM:
5295
                if (!empty($path)) {
5296
                    $repo = Container::getForumRepository();
5297
                    $resource = $repo->find($path);
5298
                }
5299
                $return .= $this->displayItemMenu($lpItem);
5300
                $return .= $this->display_forum_form('edit', $lpItem, $resource);
5301
                break;
5302
            case TOOL_THREAD:
5303
                if (!empty($path)) {
5304
                    $repo = Container::getForumPostRepository();
5305
                    $resource = $repo->find($path);
5306
                }
5307
                $return .= $this->displayItemMenu($lpItem);
5308
                $return .= $this->display_thread_form('edit', $lpItem, $resource);
5309
                break;
5310
        }
5311
5312
        return $return;
5313
    }
5314
5315
    /**
5316
     * Function that displays a list with al the resources that
5317
     * could be added to the learning path.
5318
     *
5319
     * @throws Exception
5320
     */
5321
    public function displayResources(): string
5322
    {
5323
        // Get all the docs.
5324
        $documents = $this->get_documents(true);
5325
5326
        // Get all the exercises.
5327
        $exercises = $this->get_exercises();
5328
5329
        // Get all the links.
5330
        $links = $this->get_links();
5331
5332
        // Get all the student publications.
5333
        $works = $this->get_student_publications();
5334
5335
        // Get all the forums.
5336
        $forums = $this->get_forums();
5337
5338
        // Get all surveys
5339
        $surveys = $this->getSurveys();
5340
5341
        // Get the final item form (see BT#11048) .
5342
        $finish = $this->getFinalItemForm();
5343
        $size = ICON_SIZE_MEDIUM; //ICON_SIZE_BIG
5344
        $headers = [
5345
            Display::getMdiIcon('bookshelf', 'ch-tool-icon-gradient', '', 64, get_lang('Documents')),
5346
            Display::getMdiIcon('order-bool-ascending-variant', 'ch-tool-icon-gradient', '', 64, get_lang('Tests')),
5347
            Display::getMdiIcon('file-link', 'ch-tool-icon-gradient', '', 64, get_lang('Links')),
5348
            Display::getMdiIcon('inbox-full', 'ch-tool-icon-gradient', '', 64, get_lang('Assignments')),
5349
            Display::getMdiIcon('comment-quote', 'ch-tool-icon-gradient', '', 64, get_lang('Forums')),
5350
            Display::getMdiIcon('bookmark-multiple', 'ch-tool-icon-gradient', '', 64, get_lang('Add section')),
5351
            Display::getMdiIcon('form-dropdown', 'ch-tool-icon-gradient', '', 64, get_lang('Create survey')),
5352
            Display::getMdiIcon('certificate', 'ch-tool-icon-gradient', '', 64, get_lang('Certificate')),
5353
        ];
5354
        $content = '';
5355
        /*$content = Display::return_message(
5356
            get_lang('Click on the [Learner view] button to see your learning path'),
5357
            'normal'
5358
        );*/
5359
        $section = $this->displayNewSectionForm();
5360
        $selected = isset($_REQUEST['lp_build_selected']) ? (int) $_REQUEST['lp_build_selected'] : 0;
5361
5362
        return Display::tabs(
5363
            $headers,
5364
            [
5365
                $documents,
5366
                $exercises,
5367
                $links,
5368
                $works,
5369
                $forums,
5370
                $section,
5371
                $surveys,
5372
                $finish,
5373
            ],
5374
            'resource_tab',
5375
            [],
5376
            [],
5377
            $selected
5378
        );
5379
    }
5380
5381
    /**
5382
     * Returns the extension of a document.
5383
     *
5384
     * @param string $filename
5385
     *
5386
     * @return string Extension (part after the last dot)
5387
     */
5388
    public function get_extension($filename)
5389
    {
5390
        $explode = explode('.', $filename);
5391
5392
        return $explode[count($explode) - 1];
5393
    }
5394
5395
    /**
5396
     * @return string
5397
     */
5398
    public function getCurrentBuildingModeURL()
5399
    {
5400
        $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
5401
        $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
5402
        $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
5403
        $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
5404
5405
        $currentUrl = api_get_self().'?'.api_get_cidreq().
5406
            '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
5407
5408
        return $currentUrl;
5409
    }
5410
5411
    /**
5412
     * Displays a document by id.
5413
     *
5414
     * @param CDocument $document
5415
     * @param bool      $show_title
5416
     * @param bool      $iframe
5417
     * @param bool      $edit_link
5418
     *
5419
     * @return string
5420
     */
5421
    public function display_document($document, $show_title = false, $iframe = true, $edit_link = false)
5422
    {
5423
        $return = '';
5424
        if (!$document) {
5425
            return '';
5426
        }
5427
5428
        $repo = Container::getDocumentRepository();
5429
5430
        // TODO: Add a path filter.
5431
        if ($iframe) {
5432
            $url = $repo->getResourceFileUrl($document);
5433
5434
            $return .= '<iframe
5435
                id="learnpath_preview_frame"
5436
                frameborder="0"
5437
                height="400"
5438
                width="100%"
5439
                scrolling="auto"
5440
                src="'.$url.'"></iframe>';
5441
        } else {
5442
            $return = $repo->getResourceFileContent($document);
5443
        }
5444
5445
        return $return;
5446
    }
5447
5448
    /**
5449
     * Return HTML form to add/edit a link item.
5450
     *
5451
     * @param string  $action (add/edit)
5452
     * @param CLpItem $lpItem
5453
     * @param CLink   $link
5454
     *
5455
     * @throws Exception
5456
     *
5457
     *
5458
     * @return string HTML form
5459
     */
5460
    public function display_link_form($action, $lpItem, $link)
5461
    {
5462
        $item_url = '';
5463
        if ($link) {
5464
            $item_url = stripslashes($link->getUrl());
5465
        }
5466
        $form = new FormValidator(
5467
            'edit_link',
5468
            'POST',
5469
            $this->getCurrentBuildingModeURL()
5470
        );
5471
5472
        LearnPathItemForm::setForm($form, $action, $this, $lpItem);
5473
5474
        $urlAttributes = ['class' => 'learnpath_item_form'];
5475
        $urlAttributes['disabled'] = 'disabled';
5476
        $form->addElement('url', 'url', get_lang('URL'), $urlAttributes);
5477
        $form->setDefault('url', $item_url);
5478
5479
        $form->addButtonSave(get_lang('Save'), 'submit_button');
5480
5481
        return '<div class="sectioncomment">'.$form->returnForm().'</div>';
5482
    }
5483
5484
    /**
5485
     * Return HTML form to add/edit a quiz.
5486
     *
5487
     * @param string  $action   Action (add/edit)
5488
     * @param CLpItem $lpItem   Item ID if already exists
5489
     * @param CQuiz   $exercise Extra information (quiz ID if integer)
5490
     *
5491
     * @throws Exception
5492
     *
5493
     * @return string HTML form
5494
     */
5495
    public function display_quiz_form($action, $lpItem, $exercise)
5496
    {
5497
        $form = new FormValidator(
5498
            'quiz_form',
5499
            'POST',
5500
            $this->getCurrentBuildingModeURL()
5501
        );
5502
5503
        LearnPathItemForm::setForm($form, $action, $this, $lpItem);
5504
        $form->addButtonSave(get_lang('Save'), 'submit_button');
5505
5506
        return '<div class="sectioncomment">'.$form->returnForm().'</div>';
5507
    }
5508
5509
    /**
5510
     * Return the form to display the forum edit/add option.
5511
     *
5512
     * @param CLpItem $lpItem
5513
     *
5514
     * @throws Exception
5515
     *
5516
     * @return string HTML form
5517
     */
5518
    public function display_forum_form($action, $lpItem, $resource)
5519
    {
5520
        $form = new FormValidator(
5521
            'forum_form',
5522
            'POST',
5523
            $this->getCurrentBuildingModeURL()
5524
        );
5525
        LearnPathItemForm::setForm($form, $action, $this, $lpItem);
5526
5527
        if ('add' === $action) {
5528
            $form->addButtonSave(get_lang('Add forum to course'), 'submit_button');
5529
        } else {
5530
            $form->addButtonSave(get_lang('Edit the current forum'), 'submit_button');
5531
        }
5532
5533
        return '<div class="sectioncomment">'.$form->returnForm().'</div>';
5534
    }
5535
5536
    /**
5537
     * Return HTML form to add/edit forum threads.
5538
     *
5539
     * @param string  $action
5540
     * @param CLpItem $lpItem
5541
     * @param string  $resource
5542
     *
5543
     * @throws Exception
5544
     *
5545
     * @return string HTML form
5546
     */
5547
    public function display_thread_form($action, $lpItem, $resource)
5548
    {
5549
        $form = new FormValidator(
5550
            'thread_form',
5551
            'POST',
5552
            $this->getCurrentBuildingModeURL()
5553
        );
5554
5555
        LearnPathItemForm::setForm($form, 'edit', $this, $lpItem);
5556
5557
        $form->addButtonSave(get_lang('Save'), 'submit_button');
5558
5559
        return $form->returnForm();
5560
    }
5561
5562
    /**
5563
     * Return the HTML form to display an item (generally a dir item).
5564
     *
5565
     * @param CLpItem $lpItem
5566
     * @param string  $action
5567
     *
5568
     * @throws Exception
5569
     *
5570
     *
5571
     * @return string HTML form
5572
     */
5573
    public function display_item_form(
5574
        $lpItem,
5575
        $action = 'add_item'
5576
    ) {
5577
        $item_type = $lpItem->getItemType();
5578
5579
        $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
5580
5581
        $form = new FormValidator('form_'.$item_type, 'POST', $url);
5582
        LearnPathItemForm::setForm($form, 'edit', $this, $lpItem);
5583
5584
        $form->addButtonSave(get_lang('Save section'), 'submit_button');
5585
5586
        return $form->returnForm();
5587
    }
5588
5589
    /**
5590
     * Return HTML form to add/edit a student publication (work).
5591
     *
5592
     * @param string              $action
5593
     * @param CStudentPublication $resource
5594
     *
5595
     * @throws Exception
5596
     *
5597
     * @return string HTML form
5598
     */
5599
    public function display_student_publication_form($action, CLpItem $lpItem, $resource)
5600
    {
5601
        $form = new FormValidator('frm_student_publication', 'post', '#');
5602
        LearnPathItemForm::setForm($form, 'edit', $this, $lpItem);
5603
5604
        $form->addButtonSave(get_lang('Save'), 'submit_button');
5605
5606
        $return = '<div class="sectioncomment">';
5607
        $return .= $form->returnForm();
5608
        $return .= '</div>';
5609
5610
        return $return;
5611
    }
5612
5613
    public function displayNewSectionForm()
5614
    {
5615
        $action = 'add_item';
5616
        $item_type = 'dir';
5617
5618
        $lpItem = (new CLpItem())
5619
            ->setTitle('')
5620
            ->setItemType('dir')
5621
        ;
5622
5623
        $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
5624
5625
        $form = new FormValidator('form_'.$item_type, 'POST', $url);
5626
        LearnPathItemForm::setForm($form, 'add', $this, $lpItem);
5627
5628
        $form->addButtonSave(get_lang('Save section'), 'submit_button');
5629
        $form->addElement('hidden', 'type', 'dir');
5630
5631
        return $form->returnForm();
5632
    }
5633
5634
    /**
5635
     * Returns the form to update or create a document.
5636
     *
5637
     * @param string  $action (add/edit)
5638
     * @param CLpItem $lpItem
5639
     *
5640
     *
5641
     * @throws Exception
5642
     *
5643
     * @return string HTML form
5644
     */
5645
    public function displayDocumentForm($action = 'add', $lpItem = null)
5646
    {
5647
        $courseInfo = api_get_course_info();
5648
5649
        $form = new FormValidator(
5650
            'form',
5651
            'POST',
5652
            $this->getCurrentBuildingModeURL(),
5653
            '',
5654
            ['enctype' => 'multipart/form-data']
5655
        );
5656
5657
        $data = $this->generate_lp_folder($courseInfo);
5658
5659
        if (null !== $lpItem) {
5660
            LearnPathItemForm::setForm($form, $action, $this, $lpItem);
5661
        }
5662
5663
        switch ($action) {
5664
            case 'add':
5665
                $folders = DocumentManager::get_all_document_folders(
5666
                    $courseInfo,
5667
                    0,
5668
                    true
5669
                );
5670
                DocumentManager::build_directory_selector(
5671
                    $folders,
5672
                    '',
5673
                    [],
5674
                    true,
5675
                    $form,
5676
                    'directory_parent_id'
5677
                );
5678
5679
                if ($data) {
5680
                    $defaults['directory_parent_id'] = $data->getIid();
5681
                }
5682
5683
                break;
5684
        }
5685
5686
        $form->addButtonSave(get_lang('Save'), 'submit_button');
5687
5688
        return $form->returnForm();
5689
    }
5690
5691
    /**
5692
     * @param array  $courseInfo
5693
     * @param string $content
5694
     * @param string $title
5695
     * @param int    $parentId
5696
     *
5697
     * @return int
5698
     */
5699
    public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
5700
    {
5701
        $creatorId = api_get_user_id();
5702
        $sessionId = api_get_session_id();
5703
5704
        // Generates folder
5705
        $result = $this->generate_lp_folder($courseInfo);
5706
        $dir = $result['dir'];
5707
5708
        if (empty($parentId) || '/' === $parentId) {
5709
            $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
5710
            $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
5711
5712
            if ('/' === $parentId) {
5713
                $dir = '/';
5714
            }
5715
5716
            // Please, do not modify this dirname formatting.
5717
            if (strstr($dir, '..')) {
5718
                $dir = '/';
5719
            }
5720
5721
            if (!empty($dir[0]) && '.' == $dir[0]) {
5722
                $dir = substr($dir, 1);
5723
            }
5724
            if (!empty($dir[0]) && '/' != $dir[0]) {
5725
                $dir = '/'.$dir;
5726
            }
5727
            if (isset($dir[strlen($dir) - 1]) && '/' != $dir[strlen($dir) - 1]) {
5728
                $dir .= '/';
5729
            }
5730
        } else {
5731
            $parentInfo = DocumentManager::get_document_data_by_id(
5732
                $parentId,
5733
                $courseInfo['code']
5734
            );
5735
            if (!empty($parentInfo)) {
5736
                $dir = $parentInfo['path'].'/';
5737
            }
5738
        }
5739
5740
        $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
5741
5742
        if (!is_dir($filepath)) {
5743
            $dir = '/';
5744
            $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
5745
        }
5746
5747
        $originalTitle = !empty($title) ? $title : $_POST['title'];
5748
5749
        if (!empty($title)) {
5750
            $title = api_replace_dangerous_char(stripslashes($title));
5751
        } else {
5752
            $title = api_replace_dangerous_char(stripslashes($_POST['title']));
5753
        }
5754
5755
        $title = disable_dangerous_file($title);
5756
        $filename = $title;
5757
        $content = !empty($content) ? $content : $_POST['content_lp'];
5758
        $tmpFileName = $filename;
5759
5760
        $i = 0;
5761
        while (file_exists($filepath.$tmpFileName.'.html')) {
5762
            $tmpFileName = $filename.'_'.++$i;
5763
        }
5764
5765
        $filename = $tmpFileName.'.html';
5766
        $content = stripslashes($content);
5767
5768
        if (file_exists($filepath.$filename)) {
5769
            return 0;
5770
        }
5771
5772
        $putContent = file_put_contents($filepath.$filename, $content);
5773
5774
        if (false === $putContent) {
5775
            return 0;
5776
        }
5777
5778
        $fileSize = filesize($filepath.$filename);
5779
        $saveFilePath = $dir.$filename;
5780
5781
        $document = DocumentManager::addDocument(
5782
            $courseInfo,
5783
            $saveFilePath,
5784
            'file',
5785
            $fileSize,
5786
            $tmpFileName,
5787
            '',
5788
            0, //readonly
5789
            true,
5790
            null,
5791
            $sessionId,
5792
            $creatorId
5793
        );
5794
5795
        $documentId = $document->getIid();
5796
5797
        if (!$document) {
5798
            return 0;
5799
        }
5800
5801
        $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
5802
        $newTitle = $originalTitle;
5803
5804
        if ($newComment || $newTitle) {
5805
            $em = Database::getManager();
5806
5807
            if ($newComment) {
5808
                $document->setComment($newComment);
5809
            }
5810
5811
            if ($newTitle) {
5812
                $document->setTitle($newTitle);
5813
            }
5814
5815
            $em->persist($document);
5816
            $em->flush();
5817
        }
5818
5819
        return $documentId;
5820
    }
5821
5822
    /**
5823
     * Displays the menu for manipulating a step.
5824
     *
5825
     * @return string
5826
     */
5827
    public function displayItemMenu(CLpItem $lpItem)
5828
    {
5829
        $item_id = $lpItem->getIid();
5830
        $audio = $lpItem->getAudio();
5831
        $itemType = $lpItem->getItemType();
5832
        $path = $lpItem->getPath();
5833
5834
        $return = '';
5835
        $audio_player = null;
5836
        // We display an audio player if needed.
5837
        if (!empty($audio)) {
5838
            /*$webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
5839
            $audio_player .= '<div class="lp_mediaplayer" id="container">'
5840
                .'<audio src="'.$webAudioPath.'" controls>'
5841
                .'</div><br>';*/
5842
        }
5843
5844
        $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
5845
5846
        if (TOOL_LP_FINAL_ITEM !== $itemType) {
5847
            $return .= Display::url(
5848
                Display::getMdiIcon('pencil', 'ch-tool-icon', null, 22, get_lang('Edit')),
5849
                $url.'&action=edit_item&path_item='.$path
5850
            );
5851
5852
            /*$return .= Display::url(
5853
                Display::getMdiIcon('arrow-right-bold', 'ch-tool-icon', null, 22, get_lang('Move')),
5854
                $url.'&action=move_item'
5855
            );*/
5856
        }
5857
5858
        // Commented for now as prerequisites cannot be added to chapters.
5859
        if ('dir' !== $itemType) {
5860
            $return .= Display::url(
5861
                Display::getMdiIcon('graph', 'ch-tool-icon', null, 22, get_lang('Prerequisites')),
5862
                $url.'&action=edit_item_prereq'
5863
            );
5864
        }
5865
        $return .= Display::url(
5866
            Display::getMdiIcon('delete', 'ch-tool-icon', null, 22, get_lang('Delete')),
5867
            $url.'&action=delete_item'
5868
        );
5869
5870
        /*if (in_array($itemType, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
5871
            $documentData = DocumentManager::get_document_data_by_id($path, $course_code);
5872
            if (empty($documentData)) {
5873
                // Try with iid
5874
                $table = Database::get_course_table(TABLE_DOCUMENT);
5875
                $sql = "SELECT path FROM $table
5876
                        WHERE
5877
                              c_id = ".api_get_course_int_id()." AND
5878
                              iid = ".$path." AND
5879
                              path NOT LIKE '%_DELETED_%'";
5880
                $result = Database::query($sql);
5881
                $documentData = Database::fetch_array($result);
5882
                if ($documentData) {
5883
                    $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
5884
                }
5885
            }
5886
            if (isset($documentData['absolute_path_from_document'])) {
5887
                $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
5888
            }
5889
        }*/
5890
5891
        if (!empty($audio_player)) {
5892
            $return .= $audio_player;
5893
        }
5894
5895
        return Display::toolbarAction('lp_item', [$return]);
5896
    }
5897
5898
    /**
5899
     * Creates the javascript needed for filling up the checkboxes without page reload.
5900
     *
5901
     * @return string
5902
     */
5903
    public function get_js_dropdown_array()
5904
    {
5905
        $return = 'var child_name = new Array();'."\n";
5906
        $return .= 'var child_value = new Array();'."\n\n";
5907
        $return .= 'child_name[0] = new Array();'."\n";
5908
        $return .= 'child_value[0] = new Array();'."\n\n";
5909
5910
        $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
5911
        $sql = "SELECT * FROM ".$tbl_lp_item."
5912
                WHERE
5913
                    lp_id = ".$this->lp_id." AND
5914
                    parent_item_id = 0
5915
                ORDER BY display_order ASC";
5916
        Database::query($sql);
5917
        $i = 0;
5918
5919
        $list = $this->getItemsForForm(true);
5920
5921
        foreach ($list as $row_zero) {
5922
            if (TOOL_LP_FINAL_ITEM !== $row_zero['item_type']) {
5923
                if (TOOL_QUIZ == $row_zero['item_type']) {
5924
                    $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
5925
                }
5926
                $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
5927
                $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
5928
                $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
5929
            }
5930
        }
5931
5932
        $return .= "\n";
5933
        $sql = "SELECT * FROM $tbl_lp_item
5934
                WHERE lp_id = ".$this->lp_id;
5935
        $res = Database::query($sql);
5936
        while ($row = Database::fetch_array($res)) {
5937
            $sql_parent = "SELECT * FROM ".$tbl_lp_item."
5938
                           WHERE
5939
                                parent_item_id = ".$row['iid']."
5940
                           ORDER BY display_order ASC";
5941
            $res_parent = Database::query($sql_parent);
5942
            $i = 0;
5943
            $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
5944
            $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
5945
5946
            while ($row_parent = Database::fetch_array($res_parent)) {
5947
                $js_var = json_encode(get_lang('After').' '.$this->cleanItemTitle($row_parent['title']));
5948
                $return .= 'child_name['.$row['iid'].']['.$i.'] =   '.$js_var.' ;'."\n";
5949
                $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
5950
            }
5951
            $return .= "\n";
5952
        }
5953
5954
        $return .= "
5955
            function load_cbo(id) {
5956
                if (!id) {
5957
                    return false;
5958
                }
5959
5960
                var cbo = document.getElementById('previous');
5961
                if (cbo) {
5962
                    for(var i = cbo.length - 1; i > 0; i--) {
5963
                        cbo.options[i] = null;
5964
                    }
5965
                    var k=0;
5966
                    for (var i = 1; i <= child_name[id].length; i++){
5967
                        var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
5968
                        option.style.paddingLeft = '40px';
5969
                        cbo.options[i] = option;
5970
                        k = i;
5971
                    }
5972
                    cbo.options[k].selected = true;
5973
                }
5974
5975
                //$('#previous').selectpicker('refresh');
5976
            }";
5977
5978
        return $return;
5979
    }
5980
5981
    /**
5982
     * Display the form to allow moving an item.
5983
     *
5984
     * @param CLpItem $lpItem
5985
     *
5986
     * @throws Exception
5987
     *
5988
     *
5989
     * @return string HTML form
5990
     */
5991
    public function display_move_item($lpItem)
5992
    {
5993
        $return = '';
5994
        $path = $lpItem->getPath();
5995
5996
        if ($lpItem) {
5997
            $itemType = $lpItem->getItemType();
5998
            switch ($itemType) {
5999
                case 'dir':
6000
                case 'asset':
6001
                    $return .= $this->displayItemMenu($lpItem);
6002
                    $return .= $this->display_item_form(
6003
                        $lpItem,
6004
                        get_lang('Move the current section'),
6005
                        'move',
6006
                        $row
6007
                    );
6008
                    break;
6009
                case TOOL_DOCUMENT:
6010
                case 'video':
6011
                    $return .= $this->displayItemMenu($lpItem);
6012
                    $return .= $this->displayDocumentForm('move', $lpItem);
6013
                    break;
6014
                case TOOL_LINK:
6015
                    $link = null;
6016
                    if (!empty($path)) {
6017
                        $repo = Container::getLinkRepository();
6018
                        $link = $repo->find($path);
6019
                    }
6020
                    $return .= $this->displayItemMenu($lpItem);
6021
                    $return .= $this->display_link_form('move', $lpItem, $link);
6022
                    break;
6023
                case TOOL_HOTPOTATOES:
6024
                    $return .= $this->displayItemMenu($lpItem);
6025
                    $return .= $this->display_link_form('move', $lpItem, $row);
6026
                    break;
6027
                case TOOL_QUIZ:
6028
                    $return .= $this->displayItemMenu($lpItem);
6029
                    $return .= $this->display_quiz_form('move', $lpItem, $row);
6030
                    break;
6031
                case TOOL_STUDENTPUBLICATION:
6032
                    $return .= $this->displayItemMenu($lpItem);
6033
                    $return .= $this->display_student_publication_form('move', $lpItem, $row);
6034
                    break;
6035
                case TOOL_FORUM:
6036
                    $return .= $this->displayItemMenu($lpItem);
6037
                    $return .= $this->display_forum_form('move', $lpItem, $row);
6038
                    break;
6039
                case TOOL_THREAD:
6040
                    $return .= $this->displayItemMenu($lpItem);
6041
                    $return .= $this->display_forum_form('move', $lpItem, $row);
6042
                    break;
6043
            }
6044
        }
6045
6046
        return $return;
6047
    }
6048
6049
    /**
6050
     * Return HTML form to allow prerequisites selection.
6051
     *
6052
     * @todo use FormValidator
6053
     *
6054
     * @return string HTML form
6055
     */
6056
    public function displayItemPrerequisitesForm(CLpItem $lpItem)
6057
    {
6058
        $courseId = api_get_course_int_id();
6059
        $preRequisiteId = $lpItem->getPrerequisite();
6060
        $itemId = $lpItem->getIid();
6061
6062
        $return = Display::page_header(get_lang('Add/edit prerequisites').' '.$lpItem->getTitle());
6063
6064
        $return .= '<form method="POST">';
6065
        $return .= '<div class="table-responsive">';
6066
        $return .= '<table class="table table-hover">';
6067
        $return .= '<thead>';
6068
        $return .= '<tr>';
6069
        $return .= '<th>'.get_lang('Prerequisites').'</th>';
6070
        $return .= '<th width="140">'.get_lang('minimum').'</th>';
6071
        $return .= '<th width="140">'.get_lang('maximum').'</th>';
6072
        $return .= '</tr>';
6073
        $return .= '</thead>';
6074
6075
        // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
6076
        $return .= '<tbody>';
6077
        $return .= '<tr>';
6078
        $return .= '<td colspan="3">';
6079
        $return .= '<div class="radio learnpath"><label for="idnone">';
6080
        $return .= '<input checked="checked" id="idnone" name="prerequisites" type="radio" />';
6081
        $return .= get_lang('none').'</label>';
6082
        $return .= '</div>';
6083
        $return .= '</tr>';
6084
6085
        // @todo use entitites
6086
        $tblLpItem = Database::get_course_table(TABLE_LP_ITEM);
6087
        $sql = "SELECT * FROM $tblLpItem
6088
                WHERE lp_id = ".$this->lp_id;
6089
        $result = Database::query($sql);
6090
6091
        $selectedMinScore = [];
6092
        $selectedMaxScore = [];
6093
        $masteryScore = [];
6094
        while ($row = Database::fetch_array($result)) {
6095
            if ($row['iid'] == $itemId) {
6096
                $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
6097
                $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
6098
            }
6099
            $masteryScore[$row['iid']] = $row['mastery_score'];
6100
        }
6101
6102
        $displayOrder = $lpItem->getDisplayOrder();
6103
        $lpItemRepo = Container::getLpItemRepository();
6104
        $itemRoot = $lpItemRepo->getRootItem($this->get_id());
6105
        $em = Database::getManager();
6106
6107
        $currentItemId = $itemId;
6108
        $options = [
6109
            'decorate' => true,
6110
            'rootOpen' => function () {
6111
                return '';
6112
            },
6113
            'rootClose' => function () {
6114
                return '';
6115
            },
6116
            'childOpen' => function () {
6117
                return '';
6118
            },
6119
            'childClose' => '',
6120
            'nodeDecorator' => function ($item) use (
6121
                $currentItemId,
6122
                $preRequisiteId,
6123
                $courseId,
6124
                $selectedMaxScore,
6125
                $selectedMinScore,
6126
                $displayOrder,
6127
                $lpItemRepo,
6128
                $em
6129
            ) {
6130
                $itemId = $item['iid'];
6131
                $type = $item['itemType'];
6132
                $iconName = str_replace(' ', '', $type);
6133
                switch ($iconName) {
6134
                    case 'category':
6135
                    case 'chapter':
6136
                    case 'folder':
6137
                    case 'dir':
6138
                        $icon = Display::getMdiIcon(ObjectIcon::CHAPTER, 'ch-tool-icon', '', ICON_SIZE_TINY);
6139
                        break;
6140
                    default:
6141
                        $icon = Display::getMdiIcon(ObjectIcon::SINGLE_ELEMENT, 'ch-tool-icon', '', ICON_SIZE_TINY);
6142
                        break;
6143
                }
6144
6145
                if ($itemId == $currentItemId) {
6146
                    return '';
6147
                }
6148
6149
                if ($displayOrder < $item['displayOrder']) {
6150
                    return '';
6151
                }
6152
6153
                $selectedMaxScoreValue = isset($selectedMaxScore[$itemId]) ? $selectedMaxScore[$itemId] : $item['maxScore'];
6154
                $selectedMinScoreValue = $selectedMinScore[$itemId] ?? 0;
6155
                $masteryScoreAsMinValue = $masteryScore[$itemId] ?? 0;
6156
6157
                $return = '<tr>';
6158
                $return .= '<td '.((TOOL_QUIZ != $type && TOOL_HOTPOTATOES != $type) ? ' colspan="3"' : '').'>';
6159
                $return .= '<div style="margin-left:'.($item['lvl'] * 20).'px;" class="radio learnpath">';
6160
                $return .= '<label for="id'.$itemId.'">';
6161
6162
                $checked = '';
6163
                if (null !== $preRequisiteId) {
6164
                    $checked = in_array($preRequisiteId, [$itemId, $item['ref']]) ? ' checked="checked" ' : '';
6165
                }
6166
6167
                $disabled = 'dir' === $type ? ' disabled="disabled" ' : '';
6168
6169
                $return .= '<input
6170
                    '.$checked.' '.$disabled.'
6171
                    id="id'.$itemId.'"
6172
                    name="prerequisites"
6173
                    type="radio"
6174
                    value="'.$itemId.'" />';
6175
6176
                $return .= $icon.'&nbsp;&nbsp;'.$item['title'].'</label>';
6177
                $return .= '</div>';
6178
                $return .= '</td>';
6179
6180
                if (TOOL_QUIZ == $type) {
6181
                    // let's update max_score Tests information depending of the Tests Advanced properties
6182
                    $exercise = new Exercise($courseId);
6183
                    /** @var CLpItem $itemEntity */
6184
                    $itemEntity = $lpItemRepo->find($itemId);
6185
                    $exercise->read($item['path']);
6186
                    $itemEntity->setMaxScore($exercise->getMaxScore());
6187
                    $em->persist($itemEntity);
6188
                    $em->flush($itemEntity);
6189
6190
                    $item['maxScore'] = $exercise->getMaxScore();
6191
6192
                    if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
6193
                        // Backwards compatibility with 1.9.x use mastery_score as min value
6194
                        $selectedMinScoreValue = $masteryScoreAsMinValue;
6195
                    }
6196
                    $return .= '<td>';
6197
                    $return .= '<input
6198
                        class="form-control"
6199
                        size="4" maxlength="3"
6200
                        name="min_'.$itemId.'"
6201
                        type="number"
6202
                        min="0"
6203
                        step="any"
6204
                        max="'.$item['maxScore'].'"
6205
                        value="'.$selectedMinScoreValue.'"
6206
                    />';
6207
                    $return .= '</td>';
6208
                    $return .= '<td>';
6209
                    $return .= '<input
6210
                        class="form-control"
6211
                        size="4"
6212
                        maxlength="3"
6213
                        name="max_'.$itemId.'"
6214
                        type="number"
6215
                        min="0"
6216
                        step="any"
6217
                        max="'.$item['maxScore'].'"
6218
                        value="'.$selectedMaxScoreValue.'"
6219
                    />';
6220
                        $return .= '</td>';
6221
                    }
6222
6223
                if (TOOL_HOTPOTATOES == $type) {
6224
                    $return .= '<td>';
6225
                    $return .= '<input
6226
                        size="4"
6227
                        maxlength="3"
6228
                        name="min_'.$itemId.'"
6229
                        type="number"
6230
                        min="0"
6231
                        step="any"
6232
                        max="'.$item['maxScore'].'"
6233
                        value="'.$selectedMinScoreValue.'"
6234
                    />';
6235
                        $return .= '</td>';
6236
                        $return .= '<td>';
6237
                        $return .= '<input
6238
                        size="4"
6239
                        maxlength="3"
6240
                        name="max_'.$itemId.'"
6241
                        type="number"
6242
                        min="0"
6243
                        step="any"
6244
                        max="'.$item['maxScore'].'"
6245
                        value="'.$selectedMaxScoreValue.'"
6246
                    />';
6247
                    $return .= '</td>';
6248
                }
6249
                $return .= '</tr>';
6250
6251
                return $return;
6252
            },
6253
        ];
6254
6255
        $tree = $lpItemRepo->childrenHierarchy($itemRoot, false, $options);
6256
        $return .= $tree;
6257
        $return .= '</tbody>';
6258
        $return .= '</table>';
6259
        $return .= '</div>';
6260
        $return .= '<div class="form-group">';
6261
        $return .= '<button class="btn btn--primary" name="submit_button" type="submit">'.
6262
            get_lang('Save prerequisites settings').'</button>';
6263
        $return .= '</form>';
6264
6265
        return $return;
6266
    }
6267
6268
    /**
6269
     * Return HTML list to allow prerequisites selection for lp.
6270
     */
6271
    public function display_lp_prerequisites_list(FormValidator $form)
6272
    {
6273
        $lp_id = $this->lp_id;
6274
        $lp = api_get_lp_entity($lp_id);
6275
        $prerequisiteId = $lp->getPrerequisite();
6276
6277
        $repo = Container::getLpRepository();
6278
        $qb = $repo->findAllByCourse(api_get_course_entity(), api_get_session_entity());
6279
        /** @var CLp[] $lps */
6280
        $lps = $qb->getQuery()->getResult();
6281
6282
        //$session_id = api_get_session_id();
6283
        /*$session_condition = api_get_session_condition($session_id, true, true);
6284
        $sql = "SELECT * FROM $tbl_lp
6285
                WHERE c_id = $course_id $session_condition
6286
                ORDER BY display_order ";
6287
        $rs = Database::query($sql);*/
6288
6289
        $items = [get_lang('none')];
6290
        foreach ($lps as $lp) {
6291
            $myLpId = $lp->getIid();
6292
            if ($myLpId == $lp_id) {
6293
                continue;
6294
            }
6295
            $items[$myLpId] = $lp->getTitle();
6296
            /*$return .= '<option
6297
                value="'.$myLpId.'" '.(($myLpId == $prerequisiteId) ? ' selected ' : '').'>'.
6298
                $lp->getName().
6299
                '</option>';*/
6300
        }
6301
6302
        $select = $form->addSelect('prerequisites', get_lang('Prerequisites'), $items);
6303
        $select->setSelected($prerequisiteId);
6304
    }
6305
6306
    /**
6307
     * Creates a list with all the documents in it.
6308
     *
6309
     * @param bool $showInvisibleFiles
6310
     *
6311
     * @throws Exception
6312
     *
6313
     *
6314
     * @return string
6315
     */
6316
    public function get_documents($showInvisibleFiles = false)
6317
    {
6318
        $sessionId = api_get_session_id();
6319
        $documentTree = DocumentManager::get_document_preview(
6320
            api_get_course_entity(),
6321
            $this->lp_id,
6322
            null,
6323
            $sessionId,
6324
            true,
6325
            null,
6326
            null,
6327
            $showInvisibleFiles,
6328
            false,
6329
            false,
6330
            true,
6331
            false,
6332
            [],
6333
            [],
6334
            ['file', 'folder'],
6335
            true
6336
        );
6337
6338
        $form = new FormValidator(
6339
            'form_upload',
6340
            'POST',
6341
            $this->getCurrentBuildingModeURL(),
6342
            '',
6343
            ['enctype' => 'multipart/form-data']
6344
        );
6345
6346
        $folders = DocumentManager::get_all_document_folders(
6347
            api_get_course_info(),
6348
            0,
6349
            true
6350
        );
6351
6352
        $folder = $this->generate_lp_folder(api_get_course_info());
6353
6354
        DocumentManager::build_directory_selector(
6355
            $folders,
6356
            $folder->getIid(),
6357
            [],
6358
            true,
6359
            $form,
6360
            'directory_parent_id'
6361
        );
6362
6363
        $group = [
6364
            $form->createElement(
6365
                'radio',
6366
                'if_exists',
6367
                get_lang('If file exists:'),
6368
                get_lang('Do nothing'),
6369
                'nothing'
6370
            ),
6371
            $form->createElement(
6372
                'radio',
6373
                'if_exists',
6374
                null,
6375
                get_lang('Overwrite the existing file'),
6376
                'overwrite'
6377
            ),
6378
            $form->createElement(
6379
                'radio',
6380
                'if_exists',
6381
                null,
6382
                get_lang('Rename the uploaded file if it exists'),
6383
                'rename'
6384
            ),
6385
        ];
6386
        $form->addGroup($group, null, get_lang('If file exists:'));
6387
6388
        $fileExistsOption = api_get_setting('document.document_if_file_exists_option');
6389
        $defaultFileExistsOption = 'rename';
6390
        if (!empty($fileExistsOption)) {
6391
            $defaultFileExistsOption = $fileExistsOption;
6392
        }
6393
        $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
6394
6395
        // Check box options
6396
        $form->addCheckBox(
6397
            'unzip',
6398
            get_lang('Options'),
6399
            get_lang('Uncompress zip')
6400
        );
6401
6402
        $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
6403
        $form->addMultipleUpload($url);
6404
6405
        $lpItem = (new CLpItem())
6406
            ->setTitle('')
6407
            ->setItemType(TOOL_DOCUMENT)
6408
        ;
6409
        $new = $this->displayDocumentForm('add', $lpItem);
6410
6411
        $videosTree = $this->get_videos();
6412
        $headers = [
6413
            get_lang('Files'),
6414
            get_lang('Videos'),
6415
            get_lang('Create a new document'),
6416
            get_lang('Upload'),
6417
        ];
6418
6419
        return Display::tabs(
6420
            $headers,
6421
            [$documentTree, $videosTree, $new, $form->returnForm()],
6422
            'subtab',
6423
            ['class' => 'mt-2']
6424
        );
6425
    }
6426
6427
    public function get_videos()
6428
    {
6429
        $sessionId = api_get_session_id();
6430
6431
        $documentTree = DocumentManager::get_document_preview(
6432
            api_get_course_entity(),
6433
            $this->lp_id,
6434
            null,
6435
            $sessionId,
6436
            true,
6437
            null,
6438
            null,
6439
            false,
6440
            false,
6441
            false,
6442
            true,
6443
            false,
6444
            [],
6445
            [],
6446
            'video',
6447
            true
6448
        );
6449
6450
        return $documentTree ?: get_lang('No video found');
6451
    }
6452
6453
    /**
6454
     * Creates a list with all the exercises (quiz) in it.
6455
     *
6456
     * @return string
6457
     */
6458
    public function get_exercises()
6459
    {
6460
        $course_id = api_get_course_int_id();
6461
        $session_id = api_get_session_id();
6462
        $setting = 'true' === api_get_setting('lp.show_invisible_exercise_in_lp_toc');
6463
6464
        //$activeCondition = ' active <> -1 ';
6465
        $active = 2;
6466
        if ($setting) {
6467
            $active = 1;
6468
            //$activeCondition = ' active = 1 ';
6469
        }
6470
6471
        $categoryCondition = '';
6472
6473
        $keyword = $_REQUEST['keyword'] ?? null;
6474
        $categoryId = $_REQUEST['category_id'] ?? null;
6475
        /*if (api_get_configuration_value('allow_exercise_categories') && !empty($categoryId)) {
6476
            $categoryCondition = " AND exercise_category_id = $categoryId ";
6477
        }
6478
6479
        $keywordCondition = '';
6480
6481
        if (!empty($keyword)) {
6482
            $keyword = Database::escape_string($keyword);
6483
            $keywordCondition = " AND title LIKE '%$keyword%' ";
6484
        }
6485
        */
6486
        $course = api_get_course_entity($course_id);
6487
        $session = api_get_session_entity($session_id);
6488
6489
        $qb = Container::getQuizRepository()->findAllByCourse($course, $session, $keyword, $active, false, $categoryId);
6490
        /** @var CQuiz[] $exercises */
6491
        $exercises = $qb->getQuery()->getResult();
6492
6493
        /*$sql_quiz = "SELECT * FROM $tbl_quiz
6494
                     WHERE
6495
                            c_id = $course_id AND
6496
                            $activeCondition
6497
                            $condition_session
6498
                            $categoryCondition
6499
                            $keywordCondition
6500
                     ORDER BY title ASC";
6501
        $res_quiz = Database::query($sql_quiz);*/
6502
6503
        $currentUrl = api_get_self().'?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.$this->lp_id.'#resource_tab-2';
6504
6505
        // Create a search-box
6506
        /*$form = new FormValidator('search_simple', 'get', $currentUrl);
6507
        $form->addHidden('action', 'add_item');
6508
        $form->addHidden('type', 'step');
6509
        $form->addHidden('lp_id', $this->lp_id);
6510
        $form->addHidden('lp_build_selected', '2');
6511
6512
        $form->addCourseHiddenParams();
6513
        $form->addText(
6514
            'keyword',
6515
            get_lang('Search'),
6516
            false,
6517
            [
6518
                'aria-label' => get_lang('Search'),
6519
            ]
6520
        );
6521
6522
        if (api_get_configuration_value('allow_exercise_categories')) {
6523
            $manager = new ExerciseCategoryManager();
6524
            $options = $manager->getCategoriesForSelect(api_get_course_int_id());
6525
            if (!empty($options)) {
6526
                $form->addSelect(
6527
                    'category_id',
6528
                    get_lang('Category'),
6529
                    $options,
6530
                    ['placeholder' => get_lang('Please select an option')]
6531
                );
6532
            }
6533
        }
6534
6535
        $form->addButtonSearch(get_lang('Search'));
6536
        $return = $form->returnForm();*/
6537
6538
        $return = '<ul class="mt-2 bg-white list-group lp_resource">';
6539
        $return .= '<li class="list-group-item lp_resource_element disable_drag">';
6540
        $return .= Display::getMdiIcon('order-bool-ascending-variant', 'ch-tool-icon', null, 32, get_lang('New test'));
6541
        $return .= '<a
6542
            href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
6543
            get_lang('New test').'</a>';
6544
        $return .= '</li>';
6545
6546
        $previewIcon = Display::getMdiIcon('magnify-plus-outline', 'ch-tool-icon', null, 22, get_lang('Preview'));
6547
        $quizIcon = Display::getMdiIcon('order-bool-ascending-variant', 'ch-tool-icon', null, 16, get_lang('Test'));
6548
        $moveIcon = Display::getMdiIcon('cursor-move', 'ch-tool-icon', '', 16, get_lang('Move'));
6549
        $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
6550
        foreach ($exercises as $exercise) {
6551
            $exerciseId = $exercise->getIid();
6552
            $title = strip_tags(api_html_entity_decode($exercise->getTitle()));
6553
            $visibility = $exercise->isVisible($course, $session);
6554
6555
            $link = Display::url(
6556
                $previewIcon,
6557
                $exerciseUrl.'&exerciseId='.$exerciseId,
6558
                ['target' => '_blank']
6559
            );
6560
            $return .= '<li
6561
                class="list-group-item lp_resource_element"
6562
                id="'.$exerciseId.'"
6563
                data-id="'.$exerciseId.'"
6564
                title="'.$title.'">';
6565
            $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
6566
            $return .= $quizIcon;
6567
            $sessionStar = '';
6568
            /*$sessionStar = api_get_session_image(
6569
                $row_quiz['session_id'],
6570
                $userInfo['status']
6571
            );*/
6572
            $return .= Display::url(
6573
                Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
6574
                api_get_self().'?'.
6575
                    api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$exerciseId.'&lp_id='.$this->lp_id,
6576
                [
6577
                    'class' => false === $visibility ? 'moved text-muted ' : 'moved link_with_id',
6578
                    'data_type' => 'quiz',
6579
                    'data-id' => $exerciseId,
6580
                ]
6581
            );
6582
            $return .= '</li>';
6583
        }
6584
6585
        $return .= '</ul>';
6586
6587
        return $return;
6588
    }
6589
6590
    /**
6591
     * Creates a list with all the links in it.
6592
     *
6593
     * @return string
6594
     */
6595
    public function get_links()
6596
    {
6597
        $sessionId = api_get_session_id();
6598
        $repo = Container::getLinkRepository();
6599
6600
        $course = api_get_course_entity();
6601
        $session = api_get_session_entity($sessionId);
6602
        $qb = $repo->getResourcesByCourse($course, $session);
6603
        /** @var CLink[] $links */
6604
        $links = $qb->getQuery()->getResult();
6605
6606
        $selfUrl = api_get_self();
6607
        $courseIdReq = api_get_cidreq();
6608
        $userInfo = api_get_user_info();
6609
6610
        $moveEverywhereIcon = Display::getMdiIcon('cursor-move', 'ch-tool-icon', '', 16, get_lang('Move'));
6611
6612
        $categorizedLinks = [];
6613
        $categories = [];
6614
6615
        foreach ($links as $link) {
6616
            $categoryId = null !== $link->getCategory() ? $link->getCategory()->getIid() : 0;
6617
            if (empty($categoryId)) {
6618
                $categories[0] = get_lang('Uncategorized');
6619
            } else {
6620
                $category = $link->getCategory();
6621
                $categories[$categoryId] = $category->getTitle();
6622
            }
6623
            $categorizedLinks[$categoryId][$link->getIid()] = $link;
6624
        }
6625
6626
        $linksHtmlCode =
6627
            '<script>
6628
            function toggle_tool(tool, id) {
6629
                if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
6630
                    document.getElementById(tool+"_"+id+"_content").style.display = "block";
6631
                    document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
6632
                } else {
6633
                    document.getElementById(tool+"_"+id+"_content").style.display = "none";
6634
                    document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.png').'";
6635
                }
6636
            }
6637
        </script>
6638
6639
        <ul class="mt-2 bg-white list-group lp_resource">
6640
            <li class="list-group-item lp_resource_element disable_drag ">
6641
                '.Display::getMdiIcon(ObjectIcon::LINK, 'ch-tool-icon', null, ICON_SIZE_SMALL).'
6642
                <a
6643
                href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'"
6644
                title="'.get_lang('Add a link').'">'.
6645
                get_lang('Add a link').'
6646
                </a>
6647
            </li>';
6648
        $linkIcon = Display::getMdiIcon('file-link', 'ch-tool-icon', null, 16, get_lang('Link'));
6649
        foreach ($categorizedLinks as $categoryId => $links) {
6650
            $linkNodes = null;
6651
            /** @var CLink $link */
6652
            foreach ($links as $key => $link) {
6653
                $title = $link->getTitle();
6654
                $id = $link->getIid();
6655
                $linkUrl = Display::url(
6656
                    Display::getMdiIcon('magnify-plus-outline', 'ch-tool-icon', null, 22, get_lang('Preview')),
6657
                    api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
6658
                    ['target' => '_blank']
6659
                );
6660
6661
                if ($link->isVisible($course, $session)) {
6662
                    //$sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
6663
                    $sessionStar = '';
6664
                    $url = $selfUrl.'?'.$courseIdReq.'&action=add_item&type='.TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id;
6665
                    $link = Display::url(
6666
                        Security::remove_XSS($title).$sessionStar.$linkUrl,
6667
                        $url,
6668
                        [
6669
                            'class' => 'moved link_with_id',
6670
                            'data-id' => $key,
6671
                            'data_type' => TOOL_LINK,
6672
                            'title' => $title,
6673
                        ]
6674
                    );
6675
                    $linkNodes .=
6676
                        "<li
6677
                            class='list-group-item lp_resource_element'
6678
                            id= $id
6679
                            data-id= $id
6680
                            >
6681
                         <a class='moved' href='#'>
6682
                            $moveEverywhereIcon
6683
                        </a>
6684
                        $linkIcon $link
6685
                        </li>";
6686
                }
6687
            }
6688
            $linksHtmlCode .=
6689
                '<li class="list-group-item disable_drag">
6690
                    <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" >
6691
                        <img src="'.Display::returnIconPath('add.png').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
6692
                        align="absbottom" />
6693
                    </a>
6694
                    <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
6695
                </li>
6696
            '.
6697
                $linkNodes.
6698
            '';
6699
            //<div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.
6700
        }
6701
        $linksHtmlCode .= '</ul>';
6702
6703
        return $linksHtmlCode;
6704
    }
6705
6706
    /**
6707
     * Creates a list with all the student publications in it.
6708
     *
6709
     * @return string
6710
     */
6711
    public function get_student_publications()
6712
    {
6713
        $return = '<ul class="mt-2 bg-white list-group lp_resource">';
6714
        $return .= '<li class="list-group-item lp_resource_element">';
6715
        $works = getWorkListTeacher(0, 100, null, null, null);
6716
        if (!empty($works)) {
6717
            $icon = Display::getMdiIcon('inbox-full', 'ch-tool-icon',null, 16, get_lang('Assignments'));
6718
            foreach ($works as $work) {
6719
                $workId = $work['iid'];
6720
                $link = Display::url(
6721
                    Display::getMdiIcon('magnify-plus-outline', 'ch-tool-icon', null, 22, get_lang('Preview')),
6722
                    api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$workId,
6723
                    ['target' => '_blank']
6724
                );
6725
6726
                $return .= '<li
6727
                    class="list-group-item lp_resource_element"
6728
                    id="'.$workId.'"
6729
                    data-id="'.$workId.'"
6730
                    >';
6731
                $return .= '<a class="moved" href="#">';
6732
                $return .= Display::getMdiIcon('cursor-move', 'ch-tool-icon', '', 16, get_lang('Move'));
6733
                $return .= '</a> ';
6734
6735
                $return .= $icon;
6736
                $return .= Display::url(
6737
                    Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link,
6738
                    api_get_self().'?'.
6739
                    api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&file='.$work['iid'].'&lp_id='.$this->lp_id,
6740
                    [
6741
                        'class' => 'moved link_with_id',
6742
                        'data-id' => $work['iid'],
6743
                        'data_type' => TOOL_STUDENTPUBLICATION,
6744
                        'title' => Security::remove_XSS(cut(strip_tags($work['title']), 80)),
6745
                    ]
6746
                );
6747
                $return .= '</li>';
6748
            }
6749
        }
6750
6751
        $return .= '</ul>';
6752
6753
        return $return;
6754
    }
6755
6756
    /**
6757
     * Creates a list with all the forums in it.
6758
     *
6759
     * @return string
6760
     */
6761
    public function get_forums()
6762
    {
6763
        $forumCategories = get_forum_categories();
6764
        $forumsInNoCategory = get_forums_in_category(0);
6765
        if (!empty($forumsInNoCategory)) {
6766
            $forumCategories = array_merge(
6767
                $forumCategories,
6768
                [
6769
                    [
6770
                        'cat_id' => 0,
6771
                        'session_id' => 0,
6772
                        'visibility' => 1,
6773
                        'cat_comment' => null,
6774
                    ],
6775
                ]
6776
            );
6777
        }
6778
6779
        $a_forums = [];
6780
        $courseEntity = api_get_course_entity(api_get_course_int_id());
6781
        $sessionEntity = api_get_session_entity(api_get_session_id());
6782
6783
        foreach ($forumCategories as $forumCategory) {
6784
            // The forums in this category.
6785
            $forumsInCategory = get_forums_in_category($forumCategory->getIid());
6786
            if (!empty($forumsInCategory)) {
6787
                foreach ($forumsInCategory as $forum) {
6788
                    if ($forum->isVisible($courseEntity, $sessionEntity)) {
6789
                        $a_forums[] = $forum;
6790
                    }
6791
                }
6792
            }
6793
        }
6794
6795
        $return = '<ul class="mt-2 bg-white list-group lp_resource">';
6796
6797
        // First add link
6798
        $return .= '<li class="list-group-item lp_resource_element disable_drag">';
6799
        $return .= Display::getMdiIcon('comment-quote	', 'ch-tool-icon', null, 32, get_lang('Create a new forum'));
6800
        $return .= Display::url(
6801
            get_lang('Create a new forum'),
6802
            api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
6803
                'action' => 'add',
6804
                'content' => 'forum',
6805
                'lp_id' => $this->lp_id,
6806
            ]),
6807
            ['title' => get_lang('Create a new forum')]
6808
        );
6809
        $return .= '</li>';
6810
6811
        $return .= '<script>
6812
            function toggle_forum(forum_id) {
6813
                if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
6814
                    document.getElementById("forum_"+forum_id+"_content").style.display = "block";
6815
                    document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
6816
                } else {
6817
                    document.getElementById("forum_"+forum_id+"_content").style.display = "none";
6818
                    document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.png').'";
6819
                }
6820
            }
6821
        </script>';
6822
        $moveIcon = Display::getMdiIcon('cursor-move', 'ch-tool-icon', '', 16, get_lang('Move'));
6823
        $userRights = api_is_allowed_to_edit(false, true);
6824
        foreach ($a_forums as $forum) {
6825
            $forumSession = $forum->getFirstResourceLink()->getSession();
6826
            $isForumSession = (null !== $forumSession);
6827
            $forumId = $forum->getIid();
6828
            $title = Security::remove_XSS($forum->getTitle());
6829
            $link = Display::url(
6830
                Display::getMdiIcon('magnify-plus-outline', 'ch-tool-icon', null, 22, get_lang('Preview')),
6831
                api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forumId,
6832
                ['target' => '_blank']
6833
            );
6834
6835
            $return .= '<li
6836
                    class="list-group-item lp_resource_element"
6837
                    id="'.$forumId.'"
6838
                    data-id="'.$forumId.'"
6839
                    >';
6840
            $return .= '<a class="moved" href="#">';
6841
            $return .= $moveIcon;
6842
            $return .= ' </a>';
6843
            $return .= Display::getMdiIcon('comment-quote', 'ch-tool-icon', null, 16, get_lang('Forum'));
6844
6845
            $moveLink = Display::url(
6846
                $title,
6847
                api_get_self().'?'.
6848
                api_get_cidreq().'&action=add_item&type='.TOOL_FORUM.'&forum_id='.$forumId.'&lp_id='.$this->lp_id,
6849
                [
6850
                    'class' => 'moved link_with_id',
6851
                    'data-id' => $forumId,
6852
                    'data_type' => TOOL_FORUM,
6853
                    'title' => $title,
6854
                    'style' => 'vertical-align:middle',
6855
                ]
6856
            );
6857
            $return .= '<a onclick="javascript:toggle_forum('.$forumId.');" style="cursor:hand; vertical-align:middle">
6858
                    <img
6859
                        src="'.Display::returnIconPath('add.png').'"
6860
                        id="forum_'.$forumId.'_opener" align="absbottom"
6861
                     />
6862
                </a>
6863
                '.$moveLink;
6864
            $return .= '</li>';
6865
6866
            $return .= '<div style="display:none" id="forum_'.$forumId.'_content">';
6867
            $threads = get_threads($forumId);
6868
            if (is_array($threads)) {
6869
                foreach ($threads as $thread) {
6870
                    $threadId = $thread->getIid();
6871
                    $link = Display::url(
6872
                        Display::getMdiIcon('magnify-plus-outline', 'ch-tool-icon', null, 22, get_lang('Preview')),
6873
                        api_get_path(WEB_CODE_PATH).
6874
                        'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forumId.'&thread='.$threadId,
6875
                        ['target' => '_blank']
6876
                    );
6877
6878
                    $return .= '<li
6879
                        class="list-group-item lp_resource_element"
6880
                      id="'.$threadId.'"
6881
                        data-id="'.$threadId.'"
6882
                    >';
6883
                    $return .= '&nbsp;<a class="moved" href="#">';
6884
                    $return .= $moveIcon;
6885
                    $return .= ' </a>';
6886
                    $return .= Display::getMdiIcon('format-quote-open', 'ch-tool-icon', null, 16, get_lang('Thread'));
6887
                    $return .= '<a
6888
                        class="moved link_with_id"
6889
                        data-id="'.$threadId.'"
6890
                        data_type="'.TOOL_THREAD.'"
6891
                        title="'.$thread->getTitle().'"
6892
                        href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_THREAD.'&thread_id='.$threadId.'&lp_id='.$this->lp_id.'"
6893
                        >'.
6894
                        Security::remove_XSS($thread->getTitle()).' '.$link.'</a>';
6895
                    $return .= '</li>';
6896
                }
6897
            }
6898
            $return .= '</div>';
6899
        }
6900
        $return .= '</ul>';
6901
6902
        return $return;
6903
    }
6904
6905
    /**
6906
     * Creates a list with all the surveys in it.
6907
     *
6908
     * @return string
6909
     */
6910
    public function getSurveys()
6911
    {
6912
        $return = '<ul class="mt-2 bg-white list-group lp_resource">';
6913
6914
        // First add link
6915
        $return .= '<li class="list-group-item lp_resource_element disable_drag">';
6916
        $return .= Display::getMdiIcon('clipboard-question-outline', 'ch-tool-icon', null, 32, get_lang('Create survey'));
6917
        $return .= Display::url(
6918
            get_lang('Create survey'),
6919
            api_get_path(WEB_CODE_PATH).'survey/create_new_survey.php?'.api_get_cidreq().'&'.http_build_query([
6920
                'action' => 'add',
6921
                'lp_id' => $this->lp_id,
6922
            ]),
6923
            ['title' => get_lang('Create survey')]
6924
        );
6925
        $return .= '</li>';
6926
6927
        $surveys = SurveyManager::get_surveys(api_get_course_id(), api_get_session_id());
6928
        $moveIcon = Display::getMdiIcon('cursor-move', 'ch-tool-icon', '', 16, get_lang('Move'));
6929
6930
        foreach ($surveys as $survey) {
6931
            if (!empty($survey['iid'])) {
6932
                $surveyTitle = strip_tags($survey['title']);
6933
                $return .= '<li class="list-group-item lp_resource_element" id="'.$survey['iid'].'" data-id="'.$survey['iid'].'">';
6934
                $return .= '<a class="moved" href="#">';
6935
                $return .= $moveIcon;
6936
                $return .= ' </a>';
6937
                $return .= Display::getMdiIcon('poll', 'ch-tool-icon', null, 16, get_lang('Survey'));
6938
                $return .= '<a class="moved link_with_id" data-id="'.$survey['iid'].'" data_type="'.TOOL_SURVEY.'" title="'.$surveyTitle.'" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_SURVEY.'&survey_id='.$survey['iid'].'&lp_id='.$this->lp_id.'" style="vertical-align:middle">'.$surveyTitle.'</a>';
6939
                $return .= '</li>';
6940
            }
6941
        }
6942
6943
        $return .= '</ul>';
6944
6945
        return $return;
6946
    }
6947
6948
    /**
6949
     * Temp function to be moved in main_api or the best place around for this.
6950
     * Creates a file path if it doesn't exist.
6951
     *
6952
     * @param string $path
6953
     */
6954
    public function create_path($path)
6955
    {
6956
        $path_bits = explode('/', dirname($path));
6957
6958
        // IS_WINDOWS_OS has been defined in main_api.lib.php
6959
        $path_built = IS_WINDOWS_OS ? '' : '/';
6960
        foreach ($path_bits as $bit) {
6961
            if (!empty($bit)) {
6962
                $new_path = $path_built.$bit;
6963
                if (is_dir($new_path)) {
6964
                    $path_built = $new_path.'/';
6965
                } else {
6966
                    mkdir($new_path, api_get_permissions_for_new_directories());
6967
                    $path_built = $new_path.'/';
6968
                }
6969
            }
6970
        }
6971
    }
6972
6973
    /**
6974
     * @param int    $lp_id
6975
     * @param string $status
6976
     */
6977
    public function set_autolaunch($lp_id, $status)
6978
    {
6979
        $status = (int) $status;
6980
        $em = Database::getManager();
6981
        $repo = Container::getLpRepository();
6982
6983
        $session = api_get_session_entity();
6984
        $course = api_get_course_entity();
6985
6986
        $qb = $repo->getResourcesByCourse($course, $session);
6987
        $lps = $qb->getQuery()->getResult();
6988
6989
        foreach ($lps as $lp) {
6990
            $lp->setAutoLaunch(0);
6991
            $em->persist($lp);
6992
        }
6993
6994
        $em->flush();
6995
6996
        if ($status === 1) {
6997
            $lp = $repo->find($lp_id);
6998
            if ($lp) {
6999
                $lp->setAutolaunch(1);
7000
                $em->persist($lp);
7001
            }
7002
            $em->flush();
7003
        }
7004
    }
7005
7006
    /**
7007
     * Gets previous_item_id for the next element of the lp_item table.
7008
     *
7009
     * @author Isaac flores paz
7010
     *
7011
     * @return int Previous item ID
7012
     */
7013
    public function select_previous_item_id()
7014
    {
7015
        $course_id = api_get_course_int_id();
7016
        $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
7017
7018
        // Get the max order of the items
7019
        $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
7020
                WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
7021
        $rs_max_order = Database::query($sql);
7022
        $row_max_order = Database::fetch_object($rs_max_order);
7023
        $max_order = $row_max_order->display_order;
7024
        // Get the previous item ID
7025
        $sql = "SELECT iid as previous FROM $table_lp_item
7026
                WHERE
7027
                    c_id = $course_id AND
7028
                    lp_id = ".$this->lp_id." AND
7029
                    display_order = '$max_order' ";
7030
        $rs_max = Database::query($sql);
7031
        $row_max = Database::fetch_object($rs_max);
7032
7033
        // Return the previous item ID
7034
        return $row_max->previous;
7035
    }
7036
7037
    /**
7038
     * Copies an LP.
7039
     */
7040
    public function copy()
7041
    {
7042
        // Course builder
7043
        $cb = new CourseBuilder();
7044
7045
        //Setting tools that will be copied
7046
        $cb->set_tools_to_build(['learnpaths']);
7047
7048
        //Setting elements that will be copied
7049
        $cb->set_tools_specific_id_list(
7050
            ['learnpaths' => [$this->lp_id]]
7051
        );
7052
7053
        $course = $cb->build();
7054
7055
        //Course restorer
7056
        $course_restorer = new CourseRestorer($course);
7057
        $course_restorer->set_add_text_in_items(true);
7058
        $course_restorer->set_tool_copy_settings(
7059
            ['learnpaths' => ['reset_dates' => true]]
7060
        );
7061
        $course_restorer->restore(
7062
            api_get_course_id(),
7063
            api_get_session_id(),
7064
            false,
7065
            false
7066
        );
7067
    }
7068
7069
    public static function getQuotaInfo(string $localFilePath): array
7070
    {
7071
        $post_max_raw   = ini_get('post_max_size');
7072
        $post_max_bytes = (int) rtrim($post_max_raw, 'MG') * (str_ends_with($post_max_raw,'G') ? 1024**3 : 1024**2);
7073
        $upload_max_raw = ini_get('upload_max_filesize');
7074
        $upload_max_bytes = (int) rtrim($upload_max_raw, 'MG') * (str_ends_with($upload_max_raw,'G') ? 1024**3 : 1024**2);
7075
7076
        $em     = Database::getManager();
7077
        $course = api_get_course_entity(api_get_course_int_id());
7078
7079
        $nodes  = Container::getResourceNodeRepository()->findByResourceTypeAndCourse('file', $course);
7080
        $root   = null;
7081
        foreach ($nodes as $n) {
7082
            if ($n->getParent() === null) {
7083
                $root = $n; break;
7084
            }
7085
        }
7086
        $docsSize = $root
7087
            ? Container::getDocumentRepository()->getFolderSize($root, $course)
7088
            : 0;
7089
7090
        $assetRepo = Container::getAssetRepository();
7091
        $fs        = $assetRepo->getFileSystem();
7092
        $scormSize = 0;
7093
        foreach (Container::getLpRepository()->findScormByCourse($course) as $lp) {
7094
            if ($asset = $lp->getAsset()) {
7095
                $folder = $assetRepo->getFolder($asset);
7096
                if ($folder && $fs->directoryExists($folder)) {
7097
                    $scormSize += self::getFolderSize($folder);
7098
                }
7099
            }
7100
        }
7101
7102
        $uploadedSize = filesize($localFilePath);
7103
        $existingTotal = $docsSize + $scormSize;
7104
        $combined = $existingTotal + $uploadedSize;
7105
7106
        $quotaMb = DocumentManager::get_course_quota();
7107
        $quotaBytes = $quotaMb * 1024 * 1024;
7108
7109
        return [
7110
            'post_max'      => $post_max_bytes,
7111
            'upload_max'    => $upload_max_bytes,
7112
            'docs_size'     => $docsSize,
7113
            'scorm_size'    => $scormSize,
7114
            'existing_total'=> $existingTotal,
7115
            'uploaded_size' => $uploadedSize,
7116
            'combined'      => $combined,
7117
            'quota_bytes'   => $quotaBytes,
7118
        ];
7119
    }
7120
7121
    /**
7122
     * Verify document size.
7123
     */
7124
    public static function verify_document_size(string $localFilePath): bool
7125
    {
7126
        $info = self::getQuotaInfo($localFilePath);
7127
        if ($info['uploaded_size'] > $info['post_max']
7128
            || $info['uploaded_size'] > $info['upload_max']
7129
            || $info['combined']    > $info['quota_bytes']
7130
        ) {
7131
            Container::getSession()->set('quota_info', $info);
7132
            return true;
7133
        }
7134
7135
        return false;
7136
    }
7137
7138
    private static function getFolderSize(string $path): int
7139
    {
7140
        $size     = 0;
7141
        $iterator = new \RecursiveIteratorIterator(
7142
            new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS)
7143
        );
7144
        foreach ($iterator as $file) {
7145
            if ($file->isFile()) {
7146
                $size += $file->getSize();
7147
            }
7148
        }
7149
        return $size;
7150
    }
7151
7152
    /**
7153
     * Clear LP prerequisites.
7154
     */
7155
    public function clearPrerequisites()
7156
    {
7157
        $course_id = $this->get_course_int_id();
7158
        $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
7159
        $lp_id = $this->get_id();
7160
        // Cleaning prerequisites
7161
        $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
7162
                WHERE lp_id = $lp_id";
7163
        Database::query($sql);
7164
7165
        // Cleaning mastery score for exercises
7166
        $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
7167
                WHERE lp_id = $lp_id AND item_type = 'quiz'";
7168
        Database::query($sql);
7169
    }
7170
7171
    public function set_previous_step_as_prerequisite_for_all_items()
7172
    {
7173
        $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
7174
        $course_id = $this->get_course_int_id();
7175
        $lp_id = $this->get_id();
7176
7177
        if (!empty($this->items)) {
7178
            $previous_item_id = null;
7179
            $previous_item_max = 0;
7180
            $previous_item_type = null;
7181
            $last_item_not_dir = null;
7182
            $last_item_not_dir_type = null;
7183
            $last_item_not_dir_max = null;
7184
7185
            foreach ($this->ordered_items as $itemId) {
7186
                $item = $this->getItem($itemId);
7187
                // if there was a previous item... (otherwise jump to set it)
7188
                if (!empty($previous_item_id)) {
7189
                    $current_item_id = $item->get_id(); //save current id
7190
                    if ('dir' != $item->get_type()) {
7191
                        // Current item is not a folder, so it qualifies to get a prerequisites
7192
                        if ('quiz' == $last_item_not_dir_type) {
7193
                            // if previous is quiz, mark its max score as default score to be achieved
7194
                            $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
7195
                                    WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
7196
                            Database::query($sql);
7197
                        }
7198
                        // now simply update the prerequisite to set it to the last non-chapter item
7199
                        $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
7200
                                WHERE lp_id = $lp_id AND iid = $current_item_id";
7201
                        Database::query($sql);
7202
                        // record item as 'non-chapter' reference
7203
                        $last_item_not_dir = $item->get_id();
7204
                        $last_item_not_dir_type = $item->get_type();
7205
                        $last_item_not_dir_max = $item->get_max();
7206
                    }
7207
                } else {
7208
                    if ('dir' != $item->get_type()) {
7209
                        // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
7210
                        $last_item_not_dir = $item->get_id();
7211
                        $last_item_not_dir_type = $item->get_type();
7212
                        $last_item_not_dir_max = $item->get_max();
7213
                    }
7214
                }
7215
                // Saving the item as "previous item" for the next loop
7216
                $previous_item_id = $item->get_id();
7217
                $previous_item_max = $item->get_max();
7218
                $previous_item_type = $item->get_type();
7219
            }
7220
        }
7221
    }
7222
7223
    /**
7224
     * @param array $params
7225
     *
7226
     * @return int
7227
     */
7228
    public static function createCategory($params)
7229
    {
7230
        $courseEntity = api_get_course_entity(api_get_course_int_id());
7231
7232
        $item = new CLpCategory();
7233
        $item
7234
            ->setTitle($params['name'])
7235
            ->setParent($courseEntity)
7236
            ->addCourseLink($courseEntity, api_get_session_entity())
7237
        ;
7238
7239
        $repo = Container::getLpCategoryRepository();
7240
        $repo->create($item);
7241
7242
        return $item->getIid();
7243
    }
7244
7245
    /**
7246
     * @param array $params
7247
     */
7248
    public static function updateCategory($params)
7249
    {
7250
        $em = Database::getManager();
7251
        /** @var CLpCategory $item */
7252
        $item = $em->find(CLpCategory::class, $params['id']);
7253
        if ($item) {
7254
            $item->setTitle($params['name']);
7255
            $em->persist($item);
7256
            $em->flush();
7257
        }
7258
    }
7259
7260
    public static function moveUpCategory(int $id): void
7261
    {
7262
        $em = Database::getManager();
7263
        /** @var CLpCategory $item */
7264
        $item = $em->find(CLpCategory::class, $id);
7265
        if ($item) {
7266
            $course = api_get_course_entity();
7267
            $session = api_get_session_entity();
7268
7269
            $link = $item->resourceNode->getResourceLinkByContext($course, $session);
7270
7271
            if ($link) {
7272
                $link->moveUpPosition();
7273
7274
                $em->flush();
7275
            }
7276
        }
7277
    }
7278
7279
    public static function moveDownCategory(int $id): void
7280
    {
7281
        $em = Database::getManager();
7282
        /** @var CLpCategory $item */
7283
        $item = $em->find(CLpCategory::class, $id);
7284
        if ($item) {
7285
            $course = api_get_course_entity();
7286
            $session = api_get_session_entity();
7287
7288
            $link = $item->resourceNode->getResourceLinkByContext($course, $session);
7289
7290
            if ($link) {
7291
                $link->moveDownPosition();
7292
7293
                $em->flush();
7294
            }
7295
        }
7296
    }
7297
7298
    /**
7299
     * @param int $courseId
7300
     *
7301
     * @return int
7302
     */
7303
    public static function getCountCategories($courseId)
7304
    {
7305
        if (empty($courseId)) {
7306
            return 0;
7307
        }
7308
        $repo = Container::getLpCategoryRepository();
7309
        $qb = $repo->getResourcesByCourse(api_get_course_entity($courseId));
7310
        $qb->addSelect('count(resource)');
7311
7312
        return (int) $qb->getQuery()->getSingleScalarResult();
7313
    }
7314
7315
    /**
7316
     * @param int $courseId
7317
     *
7318
     * @return CLpCategory[]
7319
     */
7320
    public static function getCategories($courseId)
7321
    {
7322
        // Using doctrine extensions
7323
        $repo = Container::getLpCategoryRepository();
7324
        $qb = $repo->getResourcesByCourse(api_get_course_entity($courseId), api_get_session_entity(), null, null, true, true);
7325
7326
        return $qb->getQuery()->getResult();
7327
    }
7328
7329
    public static function getCategorySessionId($id)
7330
    {
7331
        if ('true' !== api_get_setting('lp.allow_session_lp_category')) {
7332
            return 0;
7333
        }
7334
7335
        $repo = Container::getLpCategoryRepository();
7336
        /** @var CLpCategory $category */
7337
        $category = $repo->find($id);
7338
7339
        $sessionId = 0;
7340
        $link = $category->getFirstResourceLink();
7341
        if ($link && $link->getSession()) {
7342
            $sessionId = (int) $link->getSession()->getId();
7343
        }
7344
7345
        return $sessionId;
7346
    }
7347
7348
    public static function deleteCategory(int $id): bool
7349
    {
7350
        $repo = Container::getLpCategoryRepository();
7351
        /** @var CLpCategory $category */
7352
        $category = $repo->find($id);
7353
        if ($category) {
7354
            $em = Database::getManager();
7355
            $lps = $category->getLps();
7356
7357
            foreach ($lps as $lp) {
7358
                $lp->setCategory(null);
7359
                $em->persist($lp);
7360
            }
7361
7362
            $course = api_get_course_entity();
7363
            $session = api_get_session_entity();
7364
7365
            $em->getRepository(ResourceLink::class)->removeByResourceInContext($category, $course, $session);
7366
7367
            return true;
7368
        }
7369
7370
        return false;
7371
    }
7372
7373
    /**
7374
     * @param int  $courseId
7375
     * @param bool $addSelectOption
7376
     *
7377
     * @return array
7378
     */
7379
    public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
7380
    {
7381
        $repo = Container::getLpCategoryRepository();
7382
        $qb = $repo->getResourcesByCourse(api_get_course_entity($courseId), api_get_session_entity());
7383
        $items = $qb->getQuery()->getResult();
7384
7385
        $cats = [];
7386
        if ($addSelectOption) {
7387
            $cats = [get_lang('Select a category')];
7388
        }
7389
7390
        if (!empty($items)) {
7391
            foreach ($items as $cat) {
7392
                $cats[$cat->getIid()] = $cat->getTitle();
7393
            }
7394
        }
7395
7396
        return $cats;
7397
    }
7398
7399
    /**
7400
     * @param int   $courseId
7401
     * @param int   $lpId
7402
     * @param int   $user_id
7403
     *
7404
     * @return learnpath
7405
     */
7406
    public static function getLpFromSession(int $courseId, int $lpId, int $user_id)
7407
    {
7408
        $debug = 0;
7409
        $learnPath = null;
7410
        $lpObject = Session::read('lpobject');
7411
7412
        $repo = Container::getLpRepository();
7413
        $lp = $repo->find($lpId);
7414
        if (null !== $lpObject) {
7415
            /** @var learnpath $learnPath */
7416
            $learnPath = UnserializeApi::unserialize('lp', $lpObject);
7417
            $learnPath->entity = $lp;
7418
            if ($debug) {
7419
                error_log('getLpFromSession: unserialize');
7420
                error_log('------getLpFromSession------');
7421
                error_log('------unserialize------');
7422
                error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
7423
                error_log("api_get_sessionid: ".api_get_session_id());
7424
            }
7425
        }
7426
7427
        if (!is_object($learnPath)) {
7428
            $learnPath = new learnpath($lp, api_get_course_info_by_id($courseId), $user_id);
7429
            if ($debug) {
7430
                error_log('------getLpFromSession------');
7431
                error_log('getLpFromSession: create new learnpath');
7432
                error_log("create new LP with $courseId - $lpId - $user_id");
7433
                error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
7434
                error_log("api_get_sessionid: ".api_get_session_id());
7435
            }
7436
        }
7437
7438
        return $learnPath;
7439
    }
7440
7441
    /**
7442
     * @param int $itemId
7443
     *
7444
     * @return learnpathItem|false
7445
     */
7446
    public function getItem($itemId)
7447
    {
7448
        if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
7449
            return $this->items[$itemId];
7450
        }
7451
7452
        return false;
7453
    }
7454
7455
    /**
7456
     * @return int
7457
     */
7458
    public function getCurrentAttempt()
7459
    {
7460
        $attempt = $this->getItem($this->get_current_item_id());
7461
        if ($attempt) {
7462
            return $attempt->get_attempt_id();
7463
        }
7464
7465
        return 0;
7466
    }
7467
7468
    /**
7469
     * @return int
7470
     */
7471
    public function getCategoryId()
7472
    {
7473
        return (int) $this->categoryId;
7474
    }
7475
7476
    /**
7477
     * Get whether this is a learning path with the possibility to subscribe
7478
     * users or not.
7479
     *
7480
     * @return int
7481
     */
7482
    public function getSubscribeUsers()
7483
    {
7484
        return $this->subscribeUsers;
7485
    }
7486
7487
    /**
7488
     * Calculate the count of stars for a user in this LP
7489
     * This calculation is based on the following rules:
7490
     * - the student gets one star when he gets to 50% of the learning path
7491
     * - the student gets a second star when the average score of all tests inside the learning path >= 50%
7492
     * - the student gets a third star when the average score of all tests inside the learning path >= 80%
7493
     * - the student gets the final star when the score for the *last* test is >= 80%.
7494
     *
7495
     * @param int $sessionId Optional. The session ID
7496
     *
7497
     * @return int The count of stars
7498
     */
7499
    public function getCalculateStars($sessionId = 0)
7500
    {
7501
        $stars = 0;
7502
        $progress = self::getProgress(
7503
            $this->lp_id,
7504
            $this->user_id,
7505
            $this->course_int_id,
7506
            $sessionId
7507
        );
7508
7509
        if ($progress >= 50) {
7510
            $stars++;
7511
        }
7512
7513
        // Calculate stars chapters evaluation
7514
        $exercisesItems = $this->getExercisesItems();
7515
7516
        if (!empty($exercisesItems)) {
7517
            $totalResult = 0;
7518
7519
            foreach ($exercisesItems as $exerciseItem) {
7520
                $exerciseResultInfo = Event::getExerciseResultsByUser(
7521
                    $this->user_id,
7522
                    $exerciseItem->path,
7523
                    $this->course_int_id,
7524
                    $sessionId,
7525
                    $this->lp_id,
7526
                    $exerciseItem->db_id
7527
                );
7528
7529
                $exerciseResultInfo = end($exerciseResultInfo);
7530
7531
                if (!$exerciseResultInfo) {
7532
                    continue;
7533
                }
7534
7535
                if (!empty($exerciseResultInfo['max_score'])) {
7536
                    $exerciseResult = $exerciseResultInfo['score'] * 100 / $exerciseResultInfo['max_score'];
7537
                } else {
7538
                    $exerciseResult = 0;
7539
                }
7540
                $totalResult += $exerciseResult;
7541
            }
7542
7543
            $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
7544
7545
            if ($totalExerciseAverage >= 50) {
7546
                $stars++;
7547
            }
7548
7549
            if ($totalExerciseAverage >= 80) {
7550
                $stars++;
7551
            }
7552
        }
7553
7554
        // Calculate star for final evaluation
7555
        $finalEvaluationItem = $this->getFinalEvaluationItem();
7556
7557
        if (!empty($finalEvaluationItem)) {
7558
            $evaluationResultInfo = Event::getExerciseResultsByUser(
7559
                $this->user_id,
7560
                $finalEvaluationItem->path,
7561
                $this->course_int_id,
7562
                $sessionId,
7563
                $this->lp_id,
7564
                $finalEvaluationItem->db_id
7565
            );
7566
7567
            $evaluationResultInfo = end($evaluationResultInfo);
7568
7569
            if ($evaluationResultInfo) {
7570
                $evaluationResult = $evaluationResultInfo['score'] * 100 / $evaluationResultInfo['max_score'];
7571
                if ($evaluationResult >= 80) {
7572
                    $stars++;
7573
                }
7574
            }
7575
        }
7576
7577
        return $stars;
7578
    }
7579
7580
    /**
7581
     * Get the items of exercise type.
7582
     *
7583
     * @return array The items. Otherwise return false
7584
     */
7585
    public function getExercisesItems()
7586
    {
7587
        $exercises = [];
7588
        foreach ($this->items as $item) {
7589
            if ('quiz' !== $item->type) {
7590
                continue;
7591
            }
7592
            $exercises[] = $item;
7593
        }
7594
7595
        array_pop($exercises);
7596
7597
        return $exercises;
7598
    }
7599
7600
    /**
7601
     * Get the item of exercise type (evaluation type).
7602
     *
7603
     * @return array The final evaluation. Otherwise return false
7604
     */
7605
    public function getFinalEvaluationItem()
7606
    {
7607
        $exercises = [];
7608
        foreach ($this->items as $item) {
7609
            if (TOOL_QUIZ !== $item->type) {
7610
                continue;
7611
            }
7612
7613
            $exercises[] = $item;
7614
        }
7615
7616
        return array_pop($exercises);
7617
    }
7618
7619
    /**
7620
     * Calculate the total points achieved for the current user in this learning path.
7621
     *
7622
     * @param int $sessionId Optional. The session Id
7623
     *
7624
     * @return int
7625
     */
7626
    public function getCalculateScore($sessionId = 0)
7627
    {
7628
        // Calculate stars chapters evaluation
7629
        $exercisesItems = $this->getExercisesItems();
7630
        $finalEvaluationItem = $this->getFinalEvaluationItem();
7631
        $totalExercisesResult = 0;
7632
        $totalEvaluationResult = 0;
7633
7634
        if (false !== $exercisesItems) {
7635
            foreach ($exercisesItems as $exerciseItem) {
7636
                $exerciseResultInfo = Event::getExerciseResultsByUser(
7637
                    $this->user_id,
7638
                    $exerciseItem->path,
7639
                    $this->course_int_id,
7640
                    $sessionId,
7641
                    $this->lp_id,
7642
                    $exerciseItem->db_id
7643
                );
7644
7645
                $exerciseResultInfo = end($exerciseResultInfo);
7646
7647
                if (!$exerciseResultInfo) {
7648
                    continue;
7649
                }
7650
7651
                $totalExercisesResult += $exerciseResultInfo['score'];
7652
            }
7653
        }
7654
7655
        if (!empty($finalEvaluationItem)) {
7656
            $evaluationResultInfo = Event::getExerciseResultsByUser(
7657
                $this->user_id,
7658
                $finalEvaluationItem->path,
7659
                $this->course_int_id,
7660
                $sessionId,
7661
                $this->lp_id,
7662
                $finalEvaluationItem->db_id
7663
            );
7664
7665
            $evaluationResultInfo = end($evaluationResultInfo);
7666
7667
            if ($evaluationResultInfo) {
7668
                $totalEvaluationResult += $evaluationResultInfo['score'];
7669
            }
7670
        }
7671
7672
        return $totalExercisesResult + $totalEvaluationResult;
7673
    }
7674
7675
    /**
7676
     * Check if URL is not allowed to be show in a iframe.
7677
     *
7678
     * @param string $src
7679
     *
7680
     * @return string
7681
     */
7682
    public function fixBlockedLinks($src)
7683
    {
7684
        $urlInfo = parse_url($src);
7685
7686
        $platformProtocol = 'https';
7687
        if (false === strpos(api_get_path(WEB_CODE_PATH), 'https')) {
7688
            $platformProtocol = 'http';
7689
        }
7690
7691
        $protocolFixApplied = false;
7692
        //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
7693
        $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
7694
        $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
7695
7696
        if ($platformProtocol != $scheme) {
7697
            Session::write('x_frame_source', $src);
7698
            $src = 'blank.php?error=x_frames_options';
7699
            $protocolFixApplied = true;
7700
        }
7701
7702
        if (false == $protocolFixApplied) {
7703
            if (false === strpos(api_get_path(WEB_PATH), $host)) {
7704
                // Check X-Frame-Options
7705
                $ch = curl_init();
7706
                $options = [
7707
                    CURLOPT_URL => $src,
7708
                    CURLOPT_RETURNTRANSFER => true,
7709
                    CURLOPT_HEADER => true,
7710
                    CURLOPT_FOLLOWLOCATION => true,
7711
                    CURLOPT_ENCODING => "",
7712
                    CURLOPT_AUTOREFERER => true,
7713
                    CURLOPT_CONNECTTIMEOUT => 120,
7714
                    CURLOPT_TIMEOUT => 120,
7715
                    CURLOPT_MAXREDIRS => 10,
7716
                ];
7717
7718
                $proxySettings = api_get_setting('platform.proxy_settings', true);
7719
                if (!empty($proxySettings) &&
7720
                    isset($proxySettings['curl_setopt_array'])
7721
                ) {
7722
                    $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
7723
                    $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
7724
                }
7725
7726
                curl_setopt_array($ch, $options);
7727
                $response = curl_exec($ch);
7728
                $httpCode = curl_getinfo($ch);
7729
                $headers = substr($response, 0, $httpCode['header_size']);
7730
7731
                $error = false;
7732
                if (stripos($headers, 'X-Frame-Options: DENY') > -1
7733
                    //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
7734
                ) {
7735
                    $error = true;
7736
                }
7737
7738
                if ($error) {
7739
                    Session::write('x_frame_source', $src);
7740
                    $src = 'blank.php?error=x_frames_options';
7741
                }
7742
            }
7743
        }
7744
7745
        return $src;
7746
    }
7747
7748
    /**
7749
     * Check if this LP has a created forum in the basis course.
7750
     *
7751
     * @deprecated
7752
     *
7753
     * @return bool
7754
     */
7755
    public function lpHasForum()
7756
    {
7757
        $forumTable = Database::get_course_table(TABLE_FORUM);
7758
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
7759
7760
        $fakeFrom = "
7761
            $forumTable f
7762
            INNER JOIN $itemProperty ip
7763
            ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
7764
        ";
7765
7766
        $resultData = Database::select(
7767
            'COUNT(f.iid) AS qty',
7768
            $fakeFrom,
7769
            [
7770
                'where' => [
7771
                    'ip.visibility != ? AND ' => 2,
7772
                    'ip.tool = ? AND ' => TOOL_FORUM,
7773
                    'f.c_id = ? AND ' => intval($this->course_int_id),
7774
                    'f.lp_id = ?' => intval($this->lp_id),
7775
                ],
7776
            ],
7777
            'first'
7778
        );
7779
7780
        return $resultData['qty'] > 0;
7781
    }
7782
7783
    /**
7784
     * Get the forum for this learning path.
7785
     *
7786
     * @param int $sessionId
7787
     *
7788
     * @return array
7789
     */
7790
    public function getForum($sessionId = 0)
7791
    {
7792
        $repo = Container::getForumRepository();
7793
7794
        $course = api_get_course_entity();
7795
        $session = api_get_session_entity($sessionId);
7796
        $qb = $repo->getResourcesByCourse($course, $session);
7797
7798
        return $qb->getQuery()->getResult();
7799
    }
7800
7801
    /**
7802
     * Get the LP Final Item form.
7803
     *
7804
     * @throws Exception
7805
     *
7806
     *
7807
     * @return string
7808
     */
7809
    public function getFinalItemForm()
7810
    {
7811
        $finalItem = $this->getFinalItem();
7812
        $title = '';
7813
7814
        if ($finalItem) {
7815
            $title = $finalItem->get_title();
7816
            $buttonText = get_lang('Save');
7817
            $content = $this->getSavedFinalItem();
7818
        } else {
7819
            $buttonText = get_lang('Add this document to the course');
7820
            $content = $this->getFinalItemTemplate();
7821
        }
7822
7823
        $editorConfig = [
7824
            'ToolbarSet' => 'LearningPathDocuments',
7825
            'Width' => '100%',
7826
            'Height' => '500',
7827
            'FullPage' => true,
7828
        ];
7829
7830
        $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
7831
            'type' => 'document',
7832
            'lp_id' => $this->lp_id,
7833
        ]);
7834
7835
        $form = new FormValidator('final_item', 'POST', $url);
7836
        $form->addText('title', get_lang('Title'));
7837
        $form->addButtonSave($buttonText);
7838
        $form->addHtml(
7839
            Display::return_message(
7840
                'Variables :<br><br> <b>((certificate))</b> <br> <b>((skill))</b>',
7841
                'normal',
7842
                false
7843
            )
7844
        );
7845
7846
        $renderer = $form->defaultRenderer();
7847
        $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
7848
7849
        $form->addHtmlEditor(
7850
            'content_lp_certificate',
7851
            null,
7852
            true,
7853
            false,
7854
            $editorConfig
7855
        );
7856
        $form->addHidden('action', 'add_final_item');
7857
        $form->addHidden('path', Session::read('pathItem'));
7858
        $form->addHidden('previous', $this->get_last());
7859
        $form->setDefaults(
7860
            ['title' => $title, 'content_lp_certificate' => $content]
7861
        );
7862
7863
        if ($form->validate()) {
7864
            $values = $form->exportValues();
7865
            $lastItemId = $this->getLastInFirstLevel();
7866
7867
            if (!$finalItem) {
7868
                $documentId = $this->create_document(
7869
                    $this->course_info,
7870
                    $values['content_lp_certificate'],
7871
                    $values['title'],
7872
                    'html',
7873
                    0,
7874
                    0,
7875
                    'certificate'
7876
                );
7877
7878
                $lpItemRepo = Container::getLpItemRepository();
7879
                $root       = $lpItemRepo->getRootItem($this->get_id());
7880
7881
                $this->add_item(
7882
                    $root,
7883
                    $lastItemId,
7884
                    TOOL_LP_FINAL_ITEM,
7885
                    $documentId,
7886
                    $values['title']
7887
                );
7888
7889
                Display::addFlash(
7890
                    Display::return_message(get_lang('Added'))
7891
                );
7892
            } else {
7893
                $this->edit_document();
7894
            }
7895
        }
7896
7897
        return $form->returnForm();
7898
    }
7899
7900
    /**
7901
     * Check if the current lp item is first, both, last or none from lp list.
7902
     *
7903
     * @param int $currentItemId
7904
     *
7905
     * @return string
7906
     */
7907
    public function isFirstOrLastItem($currentItemId)
7908
    {
7909
        $lpItemId = [];
7910
        $typeListNotToVerify = self::getChapterTypes();
7911
7912
        // Using get_toc() function instead $this->items because returns the correct order of the items
7913
        foreach ($this->get_toc() as $item) {
7914
            if (!in_array($item['type'], $typeListNotToVerify)) {
7915
                $lpItemId[] = $item['id'];
7916
            }
7917
        }
7918
7919
        $lastLpItemIndex = count($lpItemId) - 1;
7920
        $position = array_search($currentItemId, $lpItemId);
7921
7922
        switch ($position) {
7923
            case 0:
7924
                if (!$lastLpItemIndex) {
7925
                    $answer = 'both';
7926
                    break;
7927
                }
7928
7929
                $answer = 'first';
7930
                break;
7931
            case $lastLpItemIndex:
7932
                $answer = 'last';
7933
                break;
7934
            default:
7935
                $answer = 'none';
7936
        }
7937
7938
        return $answer;
7939
    }
7940
7941
    /**
7942
     * Get whether this is a learning path with the accumulated SCORM time or not.
7943
     *
7944
     * @return int
7945
     */
7946
    public function getAccumulateScormTime()
7947
    {
7948
        return $this->accumulateScormTime;
7949
    }
7950
7951
    /**
7952
     * Returns an HTML-formatted link to a resource, to incorporate directly into
7953
     * the new learning path tool.
7954
     *
7955
     * The function is a big switch on tool type.
7956
     * In each case, we query the corresponding table for information and build the link
7957
     * with that information.
7958
     *
7959
     * @author Yannick Warnier <[email protected]> - rebranding based on
7960
     * previous work (display_addedresource_link_in_learnpath())
7961
     *
7962
     * @param int $course_id      Course code
7963
     * @param int $learningPathId The learning path ID (in lp table)
7964
     * @param int $id_in_path     the unique index in the items table
7965
     * @param int $lpViewId
7966
     *
7967
     * @return string
7968
     */
7969
    public static function rl_get_resource_link_for_learnpath(
7970
        $course_id,
7971
        $learningPathId,
7972
        $id_in_path,
7973
        $lpViewId
7974
    ) {
7975
        $session_id = api_get_session_id();
7976
7977
        $learningPathId = (int) $learningPathId;
7978
        $id_in_path = (int) $id_in_path;
7979
        $lpViewId = (int) $lpViewId;
7980
7981
        $em = Database::getManager();
7982
        $lpItemRepo = $em->getRepository(CLpItem::class);
7983
7984
        /** @var CLpItem $rowItem */
7985
        $rowItem = $lpItemRepo->findOneBy([
7986
            'lp' => $learningPathId,
7987
            'iid' => $id_in_path,
7988
        ]);
7989
        $type = $rowItem->getItemType();
7990
        $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
7991
        $main_dir_path = api_get_path(WEB_CODE_PATH);
7992
        $link = '';
7993
        $extraParams = api_get_cidreq(true, true, 'learnpath').'&sid='.$session_id;
7994
7995
        switch ($type) {
7996
            case 'dir':
7997
                return $main_dir_path.'lp/blank.php';
7998
            case TOOL_CALENDAR_EVENT:
7999
                return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
8000
            case TOOL_ANNOUNCEMENT:
8001
                return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
8002
            case TOOL_LINK:
8003
                $linkInfo = Link::getLinkInfo($id);
8004
                if (isset($linkInfo['url'])) {
8005
                    return $linkInfo['url'];
8006
                }
8007
8008
                return '';
8009
            case TOOL_QUIZ:
8010
                if (empty($id)) {
8011
                    return '';
8012
                }
8013
8014
                // Get the lp_item_view with the highest view_count.
8015
                $learnpathItemViewResult = $em
8016
                    ->getRepository(CLpItemView::class)
8017
                    ->findBy(
8018
                        ['item' => $rowItem->getIid(), 'view' => $lpViewId],
8019
                        ['viewCount' => 'DESC'],
8020
                        1
8021
                    );
8022
                /** @var CLpItemView $learnpathItemViewData */
8023
                $learnpathItemViewData = current($learnpathItemViewResult);
8024
                $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getIid() : 0;
8025
8026
                return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
8027
                    .http_build_query([
8028
                        'lp_init' => 1,
8029
                        'learnpath_item_view_id' => $learnpathItemViewId,
8030
                        'learnpath_id' => $learningPathId,
8031
                        'learnpath_item_id' => $id_in_path,
8032
                        'exerciseId' => $id,
8033
                    ]);
8034
            case TOOL_HOTPOTATOES:
8035
                return '';
8036
            case TOOL_FORUM:
8037
                return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
8038
            case TOOL_THREAD:
8039
                // forum post
8040
                $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
8041
                if (empty($id)) {
8042
                    return '';
8043
                }
8044
                $sql = "SELECT * FROM $tbl_topics WHERE iid=$id";
8045
                $result = Database::query($sql);
8046
                $row = Database::fetch_array($result);
8047
8048
                return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$row['forum_id'].'&lp=true&'
8049
                    .$extraParams;
8050
            case TOOL_POST:
8051
                $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
8052
                $result = Database::query("SELECT * FROM $tbl_post WHERE post_id=$id");
8053
                $row = Database::fetch_array($result);
8054
8055
                return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$row['thread_id'].'&forum='
8056
                    .$row['forum_id'].'&lp=true&'.$extraParams;
8057
            case TOOL_READOUT_TEXT:
8058
                return api_get_path(WEB_CODE_PATH).
8059
                    'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
8060
            case TOOL_DOCUMENT:
8061
            case 'video':
8062
                $repo = Container::getDocumentRepository();
8063
                $document = $repo->find($rowItem->getPath());
8064
                if ($document) {
8065
                    $params = [
8066
                        'cid' => $course_id,
8067
                        'sid' => $session_id,
8068
                    ];
8069
8070
                    return $repo->getResourceFileUrl($document, $params, UrlGeneratorInterface::ABSOLUTE_URL);
8071
                }
8072
8073
                return null;
8074
            case TOOL_LP_FINAL_ITEM:
8075
                return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
8076
                    .$extraParams;
8077
            case 'assignments':
8078
                return $main_dir_path.'work/work.php?'.$extraParams;
8079
            case TOOL_DROPBOX:
8080
                return $main_dir_path.'dropbox/index.php?'.$extraParams;
8081
            case 'introduction_text': //DEPRECATED
8082
                return '';
8083
            case TOOL_COURSE_DESCRIPTION:
8084
                return $main_dir_path.'course_description?'.$extraParams;
8085
            case TOOL_GROUP:
8086
                return $main_dir_path.'group/group.php?'.$extraParams;
8087
            case TOOL_USER:
8088
                return $main_dir_path.'user/user.php?'.$extraParams;
8089
            case TOOL_STUDENTPUBLICATION:
8090
                $repo = Container::getStudentPublicationRepository();
8091
                $publication = $repo->find($rowItem->getPath());
8092
                if ($publication && $publication->hasResourceNode()) {
8093
                    $nodeId = $publication->getResourceNode()->getId();
8094
                    $assignmentId = $publication->getIid();
8095
8096
                    return api_get_path(WEB_PATH) .
8097
                        "resources/assignment/$nodeId/submission/$assignmentId?" .
8098
                        http_build_query([
8099
                            'cid' => $course_id,
8100
                            'sid' => $session_id,
8101
                            'gid' => 0,
8102
                            'origin' => 'learnpath',
8103
                            'isStudentView' => 'true',
8104
                        ]);
8105
                }
8106
                return '';
8107
            case TOOL_SURVEY:
8108
8109
                $surveyId = (int) $id;
8110
                $repo = Container::getSurveyRepository();
8111
                if (!empty($surveyId)) {
8112
                    /** @var CSurvey $survey */
8113
                    $survey = $repo->find($surveyId);
8114
                    $autoSurveyLink = SurveyUtil::generateFillSurveyLink(
8115
                        $survey,
8116
                        'auto',
8117
                        api_get_course_entity($course_id),
8118
                        $session_id
8119
                    );
8120
                    $lpParams = [
8121
                        'lp_id' => $learningPathId,
8122
                        'lp_item_id' => $id_in_path,
8123
                        'origin' => 'learnpath',
8124
                    ];
8125
8126
                    return $autoSurveyLink.'&'.http_build_query($lpParams).'&'.$extraParams;
8127
                }
8128
        }
8129
8130
        return $link;
8131
    }
8132
8133
    /**
8134
     * Checks if any forum items in a given learning path are from the base course.
8135
     */
8136
    public static function isForumFromBaseCourse(int $learningPathId): bool
8137
    {
8138
        $itemRepository = Container::getLpItemRepository();
8139
        $forumRepository = Container::getForumRepository();
8140
        $forums = $itemRepository->findItemsByLearningPathAndType($learningPathId, 'forum');
8141
8142
        /* @var CLpItem $forumItem */
8143
        foreach ($forums as $forumItem) {
8144
            $forumId = (int) $forumItem->getPath();
8145
            $forum = $forumRepository->find($forumId);
8146
8147
            if ($forum !== null) {
8148
                $forumSession = $forum->getFirstResourceLink()->getSession();
8149
                if ($forumSession === null) {
8150
                    return true;
8151
                }
8152
            }
8153
        }
8154
8155
        return false;
8156
    }
8157
8158
    /**
8159
     * Gets the name of a resource (generally used in learnpath when no name is provided).
8160
     *
8161
     * @author Yannick Warnier <[email protected]>
8162
     *
8163
     * @param string $course_code    Course code
8164
     * @param int    $learningPathId
8165
     * @param int    $id_in_path     The resource ID
8166
     *
8167
     * @return string
8168
     */
8169
    public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
8170
    {
8171
        $_course = api_get_course_info($course_code);
8172
        if (empty($_course)) {
8173
            return '';
8174
        }
8175
        $course_id = $_course['real_id'];
8176
        $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
8177
        $learningPathId = (int) $learningPathId;
8178
        $id_in_path = (int) $id_in_path;
8179
8180
        $sql = "SELECT item_type, title, ref
8181
                FROM $tbl_lp_item
8182
                WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
8183
        $res_item = Database::query($sql);
8184
8185
        if (Database::num_rows($res_item) < 1) {
8186
            return '';
8187
        }
8188
        $row_item = Database::fetch_array($res_item);
8189
        $type = strtolower($row_item['item_type']);
8190
        $id = $row_item['ref'];
8191
        $output = '';
8192
8193
        switch ($type) {
8194
            case TOOL_CALENDAR_EVENT:
8195
                $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
8196
                $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
8197
                $myrow = Database::fetch_array($result);
8198
                $output = $myrow['title'];
8199
                break;
8200
            case TOOL_ANNOUNCEMENT:
8201
                $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
8202
                $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
8203
                $myrow = Database::fetch_array($result);
8204
                $output = $myrow['title'];
8205
                break;
8206
            case TOOL_LINK:
8207
                // Doesn't take $target into account.
8208
                $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
8209
                $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
8210
                $myrow = Database::fetch_array($result);
8211
                $output = $myrow['title'];
8212
                break;
8213
            case TOOL_QUIZ:
8214
                $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
8215
                $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
8216
                $myrow = Database::fetch_array($result);
8217
                $output = $myrow['title'];
8218
                break;
8219
            case TOOL_FORUM:
8220
                $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
8221
                $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
8222
                $myrow = Database::fetch_array($result);
8223
                $output = $myrow['title'];
8224
                break;
8225
            case TOOL_THREAD:
8226
                $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
8227
                // Grabbing the title of the post.
8228
                $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
8229
                $result_title = Database::query($sql_title);
8230
                $myrow_title = Database::fetch_array($result_title);
8231
                $output = $myrow_title['title'];
8232
                break;
8233
            case TOOL_POST:
8234
                $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
8235
                $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
8236
                $result = Database::query($sql);
8237
                $post = Database::fetch_array($result);
8238
                $output = $post['title'];
8239
                break;
8240
            case 'dir':
8241
            case TOOL_DOCUMENT:
8242
            case 'video':
8243
                $title = $row_item['title'];
8244
                $output = '-';
8245
                if (!empty($title)) {
8246
                    $output = $title;
8247
                }
8248
                break;
8249
            case 'hotpotatoes':
8250
                $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
8251
                $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
8252
                $myrow = Database::fetch_array($result);
8253
                $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
8254
                $last = count($pathname) - 1; // Making a correct name for the link.
8255
                $filename = $pathname[$last]; // Making a correct name for the link.
8256
                $myrow['path'] = rawurlencode($myrow['path']);
8257
                $output = $filename;
8258
                break;
8259
        }
8260
8261
        return stripslashes($output);
8262
    }
8263
8264
    /**
8265
     * Get the parent names for the current item.
8266
     *
8267
     * @param int $newItemId Optional. The item ID
8268
     */
8269
    public function getCurrentItemParentNames($newItemId = 0): array
8270
    {
8271
        $newItemId = $newItemId ?: $this->get_current_item_id();
8272
        $return = [];
8273
        $item = $this->getItem($newItemId);
8274
8275
        $parent = null;
8276
        if ($item) {
8277
            $parent = $this->getItem($item->get_parent());
8278
        }
8279
8280
        while ($parent) {
8281
            $return[] = $parent->get_title();
8282
            $parent = $this->getItem($parent->get_parent());
8283
        }
8284
8285
        return array_reverse($return);
8286
    }
8287
8288
    /**
8289
     * Reads and process "lp_subscription_settings" setting.
8290
     *
8291
     * @return array
8292
     */
8293
    public static function getSubscriptionSettings()
8294
    {
8295
        $subscriptionSettings = api_get_setting('lp.lp_subscription_settings', true);
8296
        if (!is_array($subscriptionSettings)) {
8297
            // By default, allow both settings
8298
            $subscriptionSettings = [
8299
                'allow_add_users_to_lp' => true,
8300
                'allow_add_users_to_lp_category' => true,
8301
            ];
8302
        } else {
8303
            $subscriptionSettings = $subscriptionSettings['options'];
8304
        }
8305
8306
        return $subscriptionSettings;
8307
    }
8308
8309
    /**
8310
     * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
8311
     */
8312
    public function exportToCourseBuildFormat()
8313
    {
8314
        if (!api_is_allowed_to_edit()) {
8315
            return false;
8316
        }
8317
8318
        $courseBuilder = new CourseBuilder();
8319
        $itemList = [];
8320
        /** @var learnpathItem $item */
8321
        foreach ($this->items as $item) {
8322
            $itemList[$item->get_type()][] = $item->get_path();
8323
        }
8324
8325
        if (empty($itemList)) {
8326
            return false;
8327
        }
8328
8329
        if (isset($itemList['document'])) {
8330
            // Get parents
8331
            foreach ($itemList['document'] as $documentId) {
8332
                $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
8333
                if (!empty($documentInfo['parents'])) {
8334
                    foreach ($documentInfo['parents'] as $parentInfo) {
8335
                        if (in_array($parentInfo['iid'], $itemList['document'])) {
8336
                            continue;
8337
                        }
8338
                        $itemList['document'][] = $parentInfo['iid'];
8339
                    }
8340
                }
8341
            }
8342
8343
            $courseInfo = api_get_course_info();
8344
            foreach ($itemList['document'] as $documentId) {
8345
                $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
8346
                $items = DocumentManager::get_resources_from_source_html(
8347
                    $documentInfo['absolute_path'],
8348
                    true,
8349
                    TOOL_DOCUMENT
8350
                );
8351
8352
                if (!empty($items)) {
8353
                    foreach ($items as $item) {
8354
                        // Get information about source url
8355
                        $url = $item[0]; // url
8356
                        $scope = $item[1]; // scope (local, remote)
8357
                        $type = $item[2]; // type (rel, abs, url)
8358
8359
                        $origParseUrl = parse_url($url);
8360
                        $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
8361
8362
                        if ('local' === $scope) {
8363
                            if ('abs' === $type || 'rel' === $type) {
8364
                                $documentFile = strstr($realOrigPath, 'document');
8365
                                if (false !== strpos($realOrigPath, $documentFile)) {
8366
                                    $documentFile = str_replace('document', '', $documentFile);
8367
                                    $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
8368
                                    // Document found! Add it to the list
8369
                                    if ($itemDocumentId) {
8370
                                        $itemList['document'][] = $itemDocumentId;
8371
                                    }
8372
                                }
8373
                            }
8374
                        }
8375
                    }
8376
                }
8377
            }
8378
8379
            $courseBuilder->build_documents(
8380
                api_get_session_id(),
8381
                $this->get_course_int_id(),
8382
                true,
8383
                $itemList['document']
8384
            );
8385
        }
8386
8387
        if (isset($itemList['quiz'])) {
8388
            $courseBuilder->build_quizzes(
8389
                api_get_session_id(),
8390
                $this->get_course_int_id(),
8391
                true,
8392
                $itemList['quiz']
8393
            );
8394
        }
8395
8396
        if (!empty($itemList['thread'])) {
8397
            $threadList = [];
8398
            $repo = Container::getForumThreadRepository();
8399
            foreach ($itemList['thread'] as $threadId) {
8400
                /** @var CForumThread $thread */
8401
                $thread = $repo->find($threadId);
8402
                if ($thread) {
8403
                    $itemList['forum'][] = $thread->getForum() ? $thread->getForum()->getIid() : 0;
8404
                    $threadList[] = $thread->getIid();
8405
                }
8406
            }
8407
8408
            if (!empty($threadList)) {
8409
                $courseBuilder->build_forum_topics(
8410
                    api_get_session_id(),
8411
                    $this->get_course_int_id(),
8412
                    null,
8413
                    $threadList
8414
                );
8415
            }
8416
        }
8417
8418
        $forumCategoryList = [];
8419
        if (isset($itemList['forum'])) {
8420
            foreach ($itemList['forum'] as $forumId) {
8421
                $forumInfo = get_forums($forumId);
8422
                $forumCategoryList[] = $forumInfo['forum_category'];
8423
            }
8424
        }
8425
8426
        if (!empty($forumCategoryList)) {
8427
            $courseBuilder->build_forum_category(
8428
                api_get_session_id(),
8429
                $this->get_course_int_id(),
8430
                true,
8431
                $forumCategoryList
8432
            );
8433
        }
8434
8435
        if (!empty($itemList['forum'])) {
8436
            $courseBuilder->build_forums(
8437
                api_get_session_id(),
8438
                $this->get_course_int_id(),
8439
                true,
8440
                $itemList['forum']
8441
            );
8442
        }
8443
8444
        if (isset($itemList['link'])) {
8445
            $courseBuilder->build_links(
8446
                api_get_session_id(),
8447
                $this->get_course_int_id(),
8448
                true,
8449
                $itemList['link']
8450
            );
8451
        }
8452
8453
        if (!empty($itemList['student_publication'])) {
8454
            $courseBuilder->build_works(
8455
                api_get_session_id(),
8456
                $this->get_course_int_id(),
8457
                true,
8458
                $itemList['student_publication']
8459
            );
8460
        }
8461
8462
        $courseBuilder->build_learnpaths(
8463
            api_get_session_id(),
8464
            $this->get_course_int_id(),
8465
            true,
8466
            [$this->get_id()],
8467
            false
8468
        );
8469
8470
        $courseBuilder->restoreDocumentsFromList();
8471
8472
        $zipFile = CourseArchiver::createBackup($courseBuilder->course);
8473
        $zipPath = CourseArchiver::getBackupDir().$zipFile;
8474
        $result = DocumentManager::file_send_for_download(
8475
            $zipPath,
8476
            true,
8477
            $this->get_name().'.zip'
8478
        );
8479
8480
        if ($result) {
8481
            api_not_allowed();
8482
        }
8483
8484
        return true;
8485
    }
8486
8487
    /**
8488
     * Get whether this is a learning path with the accumulated work time or not.
8489
     *
8490
     * @return int
8491
     */
8492
    public function getAccumulateWorkTime()
8493
    {
8494
        return (int) $this->accumulateWorkTime;
8495
    }
8496
8497
    /**
8498
     * Get whether this is a learning path with the accumulated work time or not.
8499
     *
8500
     * @return int
8501
     */
8502
    public function getAccumulateWorkTimeTotalCourse()
8503
    {
8504
        $table = Database::get_course_table(TABLE_LP_MAIN);
8505
        $sql = "SELECT SUM(accumulate_work_time) AS total
8506
                FROM $table
8507
                WHERE c_id = ".$this->course_int_id;
8508
        $result = Database::query($sql);
8509
        $row = Database::fetch_array($result);
8510
8511
        return (int) $row['total'];
8512
    }
8513
8514
    /**
8515
     * @param int $lpId
8516
     * @param int $courseId
8517
     *
8518
     * @return mixed
8519
     */
8520
    public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
8521
    {
8522
        $lpId = (int) $lpId;
8523
        $table = Database::get_course_table(TABLE_LP_MAIN);
8524
        $sql = "SELECT accumulate_work_time
8525
                FROM $table
8526
                WHERE iid = $lpId";
8527
        $result = Database::query($sql);
8528
        $row = Database::fetch_array($result);
8529
8530
        return $row['accumulate_work_time'];
8531
    }
8532
8533
    /**
8534
     * @param int $courseId
8535
     *
8536
     * @return int
8537
     */
8538
    public static function getAccumulateWorkTimeTotal($courseId)
8539
    {
8540
        $table = Database::get_course_table(TABLE_LP_MAIN);
8541
        $courseId = (int) $courseId;
8542
        $sql = "SELECT SUM(accumulate_work_time) AS total
8543
                FROM $table
8544
                WHERE c_id = $courseId";
8545
        $result = Database::query($sql);
8546
        $row = Database::fetch_array($result);
8547
8548
        return (int) $row['total'];
8549
    }
8550
8551
    /**
8552
     * In order to use the lp icon option you need to create the "lp_icon" LP extra field
8553
     * and put the images in.
8554
     */
8555
    public static function getIconSelect(): array
8556
    {
8557
        $theme = Container::$container->get(ThemeHelper::class)->getVisualTheme();
8558
        $filesystem = Container::$container->get('oneup_flysystem.themes_filesystem');
8559
8560
        if (!$filesystem->directoryExists("$theme/lp_icons")) {
8561
            return [];
8562
        }
8563
8564
        $icons = ['' => get_lang('Please select an option')];
8565
8566
        $iconFiles = $filesystem->listContents("$theme/lp_icons");
8567
        $allowedExtensions = ['image/jpeg', 'image/jpg', 'image/png'];
8568
8569
        foreach ($iconFiles as $iconFile) {
8570
            $mimeType = $filesystem->mimeType($iconFile->path());
8571
8572
            if (in_array($mimeType, $allowedExtensions)) {
8573
                $basename = basename($iconFile->path());
8574
                $icons[$basename] = $basename;
8575
            }
8576
        }
8577
8578
        return $icons;
8579
    }
8580
8581
    /**
8582
     * @param int $lpId
8583
     *
8584
     * @return string
8585
     */
8586
    public static function getSelectedIcon($lpId)
8587
    {
8588
        $extraFieldValue = new ExtraFieldValue('lp');
8589
        $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
8590
        $icon = '';
8591
        if (!empty($lpIcon) && isset($lpIcon['value'])) {
8592
            $icon = $lpIcon['value'];
8593
        }
8594
8595
        return $icon;
8596
    }
8597
8598
    public static function getSelectedIconHtml(int $lpId): string
8599
    {
8600
        $icon = self::getSelectedIcon($lpId);
8601
8602
        if (empty($icon)) {
8603
            return '';
8604
        }
8605
8606
        $path = Container::getThemeHelper()->getThemeAssetUrl("lp_icons/$icon");
8607
8608
        return Display::img($path);
8609
    }
8610
8611
    /**
8612
     * @param string $value
8613
     *
8614
     * @return string
8615
     */
8616
    public function cleanItemTitle($value)
8617
    {
8618
        $value = Security::remove_XSS(strip_tags($value));
8619
8620
        return $value;
8621
    }
8622
8623
    public function setItemTitle(FormValidator $form)
8624
    {
8625
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
8626
            $form->addHtmlEditor(
8627
                'title',
8628
                get_lang('Title'),
8629
                true,
8630
                false,
8631
                ['ToolbarSet' => 'TitleAsHtml', 'id' => uniqid('editor')]
8632
            );
8633
        } else {
8634
            $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle', 'class' => 'learnpath_item_form']);
8635
            $form->applyFilter('title', 'trim');
8636
            $form->applyFilter('title', 'html_filter');
8637
        }
8638
    }
8639
8640
    /**
8641
     * @return array
8642
     */
8643
    public function getItemsForForm($addParentCondition = false)
8644
    {
8645
        $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
8646
8647
        $sql = "SELECT * FROM $tbl_lp_item
8648
                WHERE path <> 'root' AND lp_id = ".$this->lp_id;
8649
8650
        if ($addParentCondition) {
8651
            $sql .= ' AND parent_item_id IS NULL ';
8652
        }
8653
        $sql .= ' ORDER BY display_order ASC';
8654
8655
        $result = Database::query($sql);
8656
        $arrLP = [];
8657
        while ($row = Database::fetch_array($result)) {
8658
            $arrLP[] = [
8659
                'iid' => $row['iid'],
8660
                'id' => $row['iid'],
8661
                'item_type' => $row['item_type'],
8662
                'title' => $this->cleanItemTitle($row['title']),
8663
                'title_raw' => $row['title'],
8664
                'path' => $row['path'],
8665
                'description' => Security::remove_XSS($row['description']),
8666
                'parent_item_id' => $row['parent_item_id'],
8667
                'previous_item_id' => $row['previous_item_id'],
8668
                'next_item_id' => $row['next_item_id'],
8669
                'display_order' => $row['display_order'],
8670
                'max_score' => $row['max_score'],
8671
                'min_score' => $row['min_score'],
8672
                'mastery_score' => $row['mastery_score'],
8673
                'prerequisite' => $row['prerequisite'],
8674
                'max_time_allowed' => $row['max_time_allowed'],
8675
                'prerequisite_min_score' => $row['prerequisite_min_score'],
8676
                'prerequisite_max_score' => $row['prerequisite_max_score'],
8677
            ];
8678
        }
8679
8680
        return $arrLP;
8681
    }
8682
8683
    /**
8684
     * Gets whether this SCORM learning path has been marked to use the score
8685
     * as progress. Takes into account whether the learnpath matches (SCORM
8686
     * content + less than 2 items).
8687
     *
8688
     * @return bool True if the score should be used as progress, false otherwise
8689
     */
8690
    public function getUseScoreAsProgress()
8691
    {
8692
        // If not a SCORM, we don't care about the setting
8693
        if (2 != $this->get_type()) {
8694
            return false;
8695
        }
8696
        // If more than one step in the SCORM, we don't care about the setting
8697
        if ($this->get_total_items_count() > 1) {
8698
            return false;
8699
        }
8700
        $extraFieldValue = new ExtraFieldValue('lp');
8701
        $doUseScore = false;
8702
        $useScore = $extraFieldValue->get_values_by_handler_and_field_variable(
8703
            $this->get_id(),
8704
            'use_score_as_progress'
8705
        );
8706
        if (!empty($useScore) && isset($useScore['value'])) {
8707
            $doUseScore = $useScore['value'];
8708
        }
8709
8710
        return $doUseScore;
8711
    }
8712
8713
    /**
8714
     * Get the user identifier (user_id or username
8715
     * Depends on scorm_api_username_as_student_id in app/config/configuration.php.
8716
     *
8717
     * @return string User ID or username, depending on configuration setting
8718
     */
8719
    public static function getUserIdentifierForExternalServices()
8720
    {
8721
        $scormApiExtraFieldUseStudentId = api_get_setting('lp.scorm_api_extrafield_to_use_as_student_id');
8722
        $extraFieldValue = new ExtraFieldValue('user');
8723
        $extrafield = $extraFieldValue->get_values_by_handler_and_field_variable(
8724
            api_get_user_id(),
8725
            $scormApiExtraFieldUseStudentId
8726
        );
8727
        if (is_array($extrafield) && isset($extrafield['value'])) {
8728
            return $extrafield['value'];
8729
        } else {
8730
            if ('true' === $scormApiExtraFieldUseStudentId) {
8731
                return api_get_user_info(api_get_user_id())['username'];
8732
            } else {
8733
                return api_get_user_id();
8734
            }
8735
        }
8736
    }
8737
8738
    /**
8739
     * Save the new order for learning path items.
8740
     *
8741
     * @param array $orderList A associative array with id and parent_id keys.
8742
     */
8743
    public static function sortItemByOrderList(CLpItem $rootItem, array $orderList = [], $flush = true, $lpItemRepo = null, $em = null)
8744
    {
8745
        if (empty($orderList)) {
8746
            return true;
8747
        }
8748
        if (!isset($lpItemRepo)) {
8749
            $lpItemRepo = Container::getLpItemRepository();
8750
        }
8751
        if (!isset($em)) {
8752
            $em = Database::getManager();
8753
        }
8754
        $counter = 2;
8755
        $rootItem->setDisplayOrder(1);
8756
        $rootItem->setPreviousItemId(null);
8757
        $em->persist($rootItem);
8758
        if ($flush) {
8759
            $em->flush();
8760
        }
8761
8762
        foreach ($orderList as $item) {
8763
            $itemId = $item->id ?? 0;
8764
            if (empty($itemId)) {
8765
                continue;
8766
            }
8767
            $parentId = $item->parent_id ?? 0;
8768
            $parent = $rootItem;
8769
            if (!empty($parentId)) {
8770
                $parentExists = $lpItemRepo->find($parentId);
8771
                if (null !== $parentExists) {
8772
                    $parent = $parentExists;
8773
                }
8774
            }
8775
8776
            /** @var CLpItem $itemEntity */
8777
            $itemEntity = $lpItemRepo->find($itemId);
8778
            $itemEntity->setParent($parent);
8779
            $itemEntity->setPreviousItemId(null);
8780
            $itemEntity->setNextItemId(null);
8781
            $itemEntity->setDisplayOrder($counter);
8782
8783
            $em->persist($itemEntity);
8784
            if ($flush) {
8785
                $em->flush();
8786
            }
8787
            $counter++;
8788
        }
8789
8790
        $lpItemRepo->recoverNode($rootItem, 'displayOrder');
8791
        $em->persist($rootItem);
8792
        if ($flush) {
8793
            $em->flush();
8794
        }
8795
8796
        return true;
8797
    }
8798
8799
    public static function move(int $lpId, string $direction)
8800
    {
8801
        $em = Database::getManager();
8802
        /** @var CLp $lp */
8803
        $lp = Container::getLpRepository()->find($lpId);
8804
        if ($lp) {
8805
            $course = api_get_course_entity();
8806
            $session = api_get_session_entity();
8807
            $group = api_get_group_entity();
8808
8809
            $link = $lp->getResourceNode()->getResourceLinkByContext($course, $session, $group);
8810
8811
            if ($link) {
8812
                if ('down' === $direction) {
8813
                    $link->moveDownPosition();
8814
                }
8815
                if ('up' === $direction) {
8816
                    $link->moveUpPosition();
8817
                }
8818
8819
                $em->flush();
8820
            }
8821
        }
8822
    }
8823
8824
    /**
8825
     * Get the depth level of LP item.
8826
     *
8827
     * @param array $items
8828
     * @param int   $currentItemId
8829
     *
8830
     * @return int
8831
     */
8832
    private static function get_level_for_item($items, $currentItemId)
8833
    {
8834
        $parentItemId = 0;
8835
        if (isset($items[$currentItemId])) {
8836
            $parentItemId = $items[$currentItemId]->parent;
8837
        }
8838
8839
        if (0 == $parentItemId) {
8840
            return 0;
8841
        }
8842
8843
        return self::get_level_for_item($items, $parentItemId) + 1;
8844
    }
8845
8846
    /**
8847
     * Generate the link for a learnpath category as course tool.
8848
     *
8849
     * @param int $categoryId
8850
     *
8851
     * @return string
8852
     */
8853
    private static function getCategoryLinkForTool($categoryId)
8854
    {
8855
        $categoryId = (int) $categoryId;
8856
        return 'lp/lp_controller.php?'.api_get_cidreq().'&'
8857
            .http_build_query(
8858
                [
8859
                    'action' => 'view_category',
8860
                    'id' => $categoryId,
8861
                ]
8862
            );
8863
    }
8864
8865
    /**
8866
     * Check and obtain the lp final item if exist.
8867
     *
8868
     * @return learnpathItem
8869
     */
8870
    private function getFinalItem()
8871
    {
8872
        if (empty($this->items)) {
8873
            return null;
8874
        }
8875
8876
        foreach ($this->items as $item) {
8877
            if ('final_item' !== $item->type) {
8878
                continue;
8879
            }
8880
8881
            return $item;
8882
        }
8883
    }
8884
8885
    /**
8886
     * Get the LP Final Item Template.
8887
     *
8888
     * @return string
8889
     */
8890
    private function getFinalItemTemplate()
8891
    {
8892
        return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
8893
    }
8894
8895
    /**
8896
     * Get the LP Final Item Url.
8897
     *
8898
     * @return string
8899
     */
8900
    private function getSavedFinalItem()
8901
    {
8902
        $finalItem = $this->getFinalItem();
8903
8904
        $repo = Container::getDocumentRepository();
8905
        /** @var CDocument $document */
8906
        $document = $repo->find($finalItem->path);
8907
8908
        return $document ? $repo->getResourceFileContent($document) : '';
8909
    }
8910
8911
    /**
8912
     * Recalculates the results for all exercises associated with the learning path (LP) for the given user.
8913
     */
8914
    public function recalculateResultsForLp(int $userId): void
8915
    {
8916
        $em = Database::getManager();
8917
        $lpItemRepo = $em->getRepository(CLpItem::class);
8918
        $lpItems = $lpItemRepo->findBy(['lp' => $this->lp_id]);
8919
8920
        if (empty($lpItems)) {
8921
            Display::addFlash(Display::return_message(get_lang('No item found'), 'error'));
8922
            return;
8923
        }
8924
8925
        $lpItemsById = [];
8926
        foreach ($lpItems as $item) {
8927
            $lpItemsById[$item->getIid()] = $item;
8928
        }
8929
8930
        $trackEExerciseRepo = $em->getRepository(TrackEExercise::class);
8931
        $trackExercises = $trackEExerciseRepo->createQueryBuilder('te')
8932
            ->where('te.origLpId = :lpId')
8933
            ->andWhere('te.user = :userId')
8934
            ->andWhere('te.origLpItemId IN (:lpItemIds)')
8935
            ->setParameter('lpId', $this->lp_id)
8936
            ->setParameter('userId', $userId)
8937
            ->setParameter('lpItemIds', array_keys($lpItemsById))
8938
            ->getQuery()
8939
            ->getResult();
8940
8941
        if (empty($trackExercises)) {
8942
            Display::addFlash(Display::return_message(get_lang('No test attempt found'), 'error'));
8943
            return;
8944
        }
8945
8946
        foreach ($trackExercises as $trackExercise) {
8947
            $exeId = $trackExercise->getExeId();
8948
            $lpItemId = $trackExercise->getOrigLpItemId();
8949
8950
            if (!isset($lpItemsById[$lpItemId])) {
8951
                continue;
8952
            }
8953
8954
            $lpItem = $lpItemsById[$lpItemId];
8955
            if ('quiz' !== $lpItem->getItemType()) {
8956
                continue;
8957
            }
8958
8959
            $quizId = (int) $lpItem->getPath();
8960
            $courseId = (int) $trackExercise->getCourse()->getId();
8961
            $updatedExercise = ExerciseLib::recalculateResult($exeId, $userId, $quizId, $courseId);
8962
            if ($updatedExercise instanceof TrackEExercise) {
8963
                Display::addFlash(Display::return_message(get_lang('Results recalculated'), 'success'));
8964
            } else {
8965
                Display::addFlash(Display::return_message(get_lang('Error recalculating results'), 'error'));
8966
            }
8967
        }
8968
    }
8969
8970
    /**
8971
     * Returns the video player HTML for a video-type document LP item.
8972
     *
8973
     * @param int $lpItemId
8974
     * @param string $autostart
8975
     *
8976
     * @return string
8977
     */
8978
    public function getVideoPlayer(CDocument $document, string $autostart = 'true'): string
8979
    {
8980
        $resourceNode = $document->getResourceNode();
8981
        $resourceFile = $resourceNode?->getFirstResourceFile();
8982
8983
        if (!$resourceNode || !$resourceFile) {
8984
            return '';
8985
        }
8986
8987
        $resourceNodeRepository = Container::getResourceNodeRepository();
8988
        $videoUrl = $resourceNodeRepository->getResourceFileUrl($resourceNode);
8989
8990
        if (empty($videoUrl)) {
8991
            return '';
8992
        }
8993
8994
        $fileName = $resourceFile->getTitle();
8995
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
8996
        $mimeType = $resourceFile->getMimeType() ?: 'video/mp4';
8997
        $autoplayAttr = ($autostart === 'true') ? 'autoplay muted playsinline' : '';
8998
8999
        $html = '';
9000
        $html .= '
9001
        <video id="lp-video" width="100%" height="auto" controls '.$autoplayAttr.'>
9002
            <source src="'.$videoUrl.'" type="$mimeType">
9003
        </video>';
9004
9005
        return $html;
9006
    }
9007
}
9008