-
Notifications
You must be signed in to change notification settings - Fork 467
/
learnpath.class.php
8729 lines (7808 loc) · 302 KB
/
learnpath.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Entity\ResourceLink;
use Chamilo\CoreBundle\Entity\User;
use Chamilo\CoreBundle\Entity\Session as SessionEntity;
use Chamilo\CourseBundle\Entity\CLpRelUser;
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CoreBundle\Repository\Node\CourseRepository;
use Chamilo\CourseBundle\Repository\CLpRelUserRepository;
use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
use Chamilo\CourseBundle\Entity\CDocument;
use Chamilo\CourseBundle\Entity\CForumCategory;
use Chamilo\CourseBundle\Entity\CForumThread;
use Chamilo\CourseBundle\Entity\CLink;
use Chamilo\CourseBundle\Entity\CLp;
use Chamilo\CourseBundle\Entity\CLpCategory;
use Chamilo\CourseBundle\Entity\CLpItem;
use Chamilo\CourseBundle\Entity\CLpItemView;
use Chamilo\CourseBundle\Entity\CQuiz;
use Chamilo\CourseBundle\Entity\CStudentPublication;
use Chamilo\CourseBundle\Entity\CTool;
use \Chamilo\CoreBundle\Entity\ResourceNode;
use ChamiloSession as Session;
use Doctrine\Common\Collections\Criteria;
use PhpZip\ZipFile;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Chamilo\CoreBundle\Component\Utils\ObjectIcon;
/**
* Class learnpath
* This class defines the parent attributes and methods for Chamilo learnpaths
* and SCORM learnpaths. It is used by the scorm class.
*
* @todo decouple class
*
* @author Yannick Warnier <ywarnier@beeznest.org>
* @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
*/
class learnpath
{
public const MAX_LP_ITEM_TITLE_LENGTH = 36;
public const STATUS_CSS_CLASS_NAME = [
'not attempted' => 'scorm_not_attempted',
'incomplete' => 'scorm_not_attempted',
'failed' => 'scorm_failed',
'completed' => 'scorm_completed',
'passed' => 'scorm_completed',
'succeeded' => 'scorm_completed',
'browsed' => 'scorm_completed',
];
public $attempt = 0; // The number for the current ID view.
public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
public $current; // Id of the current item the user is viewing.
public $current_score; // The score of the current item.
public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
public $current_time_stop; // The time the user closed this resource.
public $default_status = 'not attempted';
public $encoding = 'UTF-8';
public $error = '';
public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
public $index; // The index of the active learnpath_item in $ordered_items array.
/** @var learnpathItem[] */
public $items = [];
public $last; // item_id of last item viewed in the learning path.
public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
public $license; // Which license this course has been given - not used yet on 20060522.
public $lp_id; // DB iid for this learnpath.
public $lp_view_id; // DB ID for lp_view
public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
public $message = '';
public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
public $name; // Learnpath name (they generally have one).
public $ordered_items = []; // List of the learnpath items in the order they are to be read.
public $path = ''; // Path inside the scorm directory (if scorm).
public $theme; // The current theme of the learning path.
public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
public $accumulateWorkTime; // The min time of learnpath
// Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
public $prevent_reinit = 1;
// Describes the mode of progress bar display.
public $seriousgame_mode = 0;
public $progress_bar_mode = '%';
// Percentage progress as saved in the db.
public $progress_db = 0;
public $proximity; // Wether the content is distant or local or unknown.
public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
// !!!This array (refs_list) is built differently depending on the nature of the LP.
// If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
// TODO: Check if this type variable is useful here (instead of just in the controller script).
public $user_id; //ID of the user that is viewing/using the course
public $update_queue = [];
public $scorm_debug = 0;
public $arrMenu = []; // Array for the menu items.
public $debug = 0; // Logging level.
public $lp_session_id = 0;
public $lp_view_session_id = 0; // The specific view might be bound to a session.
public $prerequisite = 0;
public $use_max_score = 1; // 1 or 0
public $subscribeUsers = 0; // Subscribe users or not
public $created_on = '';
public $modified_on = '';
public $published_on = '';
public $expired_on = '';
public $ref;
public $course_int_id;
public $course_info;
public $categoryId;
public $scormUrl;
public $entity;
public function __construct(CLp $entity = null, $course_info, $user_id)
{
$debug = $this->debug;
$user_id = (int) $user_id;
$this->encoding = api_get_system_encoding();
$lp_id = 0;
if (null !== $entity) {
$lp_id = $entity->getIid();
}
$course_info = empty($course_info) ? api_get_course_info() : $course_info;
$course_id = (int) $course_info['real_id'];
$this->course_info = $course_info;
$this->set_course_int_id($course_id);
if (empty($lp_id) || empty($course_id)) {
$this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
} else {
//$this->entity = $entity;
$this->lp_id = $lp_id;
$this->type = $entity->getLpType();
$this->name = stripslashes($entity->getTitle());
$this->proximity = $entity->getContentLocal();
$this->theme = $entity->getTheme();
$this->maker = $entity->getContentLocal();
$this->prevent_reinit = $entity->getPreventReinit();
$this->seriousgame_mode = $entity->getSeriousgameMode();
$this->license = $entity->getContentLicense();
$this->scorm_debug = $entity->getDebug();
$this->js_lib = $entity->getJsLib();
$this->path = $entity->getPath();
$this->author = $entity->getAuthor();
$this->hide_toc_frame = $entity->getHideTocFrame();
//$this->lp_session_id = $entity->getSessionId();
$this->use_max_score = $entity->getUseMaxScore();
$this->subscribeUsers = $entity->getSubscribeUsers();
$this->created_on = $entity->getCreatedOn()->format('Y-m-d H:i:s');
$this->modified_on = $entity->getModifiedOn()->format('Y-m-d H:i:s');
$this->ref = $entity->getRef();
$this->categoryId = 0;
if ($entity->getCategory()) {
$this->categoryId = $entity->getCategory()->getIid();
}
if ($entity->hasAsset()) {
$asset = $entity->getAsset();
$this->scormUrl = Container::getAssetRepository()->getAssetUrl($asset).'/'.$entity->getPath().'/';
}
$this->accumulateScormTime = $entity->getAccumulateWorkTime();
if (!empty($entity->getPublishedOn())) {
$this->published_on = $entity->getPublishedOn()->format('Y-m-d H:i:s');
}
if (!empty($entity->getExpiredOn())) {
$this->expired_on = $entity->getExpiredOn()->format('Y-m-d H:i:s');
}
if (2 == $this->type) {
if (1 == $entity->getForceCommit()) {
$this->force_commit = true;
}
}
$this->mode = $entity->getDefaultViewMod();
// Check user ID.
if (empty($user_id)) {
$this->error = 'User ID is empty';
} else {
$this->user_id = $user_id;
}
// End of variables checking.
$session_id = api_get_session_id();
// Get the session condition for learning paths of the base + session.
$session = api_get_session_condition($session_id);
// Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
$lp_table = Database::get_course_table(TABLE_LP_VIEW);
// Selecting by view_count descending allows to get the highest view_count first.
$sql = "SELECT * FROM $lp_table
WHERE
c_id = $course_id AND
lp_id = $lp_id AND
user_id = $user_id
$session
ORDER BY view_count DESC";
$res = Database::query($sql);
if (Database::num_rows($res) > 0) {
$row = Database::fetch_array($res);
$this->attempt = $row['view_count'];
$this->lp_view_id = $row['iid'];
$this->last_item_seen = $row['last_item'];
$this->progress_db = $row['progress'];
$this->lp_view_session_id = $row['session_id'];
} elseif (!api_is_invitee()) {
$this->attempt = 1;
$params = [
'c_id' => $course_id,
'lp_id' => $lp_id,
'user_id' => $user_id,
'view_count' => 1,
//'session_id' => $session_id,
'last_item' => 0,
];
if (!empty($session_id)) {
$params['session_id'] = $session_id;
}
$this->last_item_seen = 0;
$this->lp_view_session_id = $session_id;
$this->lp_view_id = Database::insert($lp_table, $params);
}
$criteria = new Criteria();
$criteria
->where($criteria->expr()->neq('path', 'root'))
->orderBy(
[
'parent' => Criteria::ASC,
'displayOrder' => Criteria::ASC,
]
);
$items = $entity->getItems()->matching($criteria);
$lp_item_id_list = [];
foreach ($items as $item) {
$itemId = $item->getIid();
$lp_item_id_list[] = $itemId;
switch ($this->type) {
case CLp::AICC_TYPE:
$oItem = new aiccItem('db', $itemId, $course_id);
if (is_object($oItem)) {
$oItem->set_lp_view($this->lp_view_id);
$oItem->set_prevent_reinit($this->prevent_reinit);
// Don't use reference here as the next loop will make the pointed object change.
$this->items[$itemId] = $oItem;
$this->refs_list[$oItem->ref] = $itemId;
}
break;
case CLp::SCORM_TYPE:
$oItem = new scormItem('db', $itemId);
if (is_object($oItem)) {
$oItem->set_lp_view($this->lp_view_id);
$oItem->set_prevent_reinit($this->prevent_reinit);
// Don't use reference here as the next loop will make the pointed object change.
$this->items[$itemId] = $oItem;
$this->refs_list[$oItem->ref] = $itemId;
}
break;
case CLp::LP_TYPE:
default:
$oItem = new learnpathItem(null, $item);
if (is_object($oItem)) {
// Moved down to when we are sure the item_view exists.
//$oItem->set_lp_view($this->lp_view_id);
$oItem->set_prevent_reinit($this->prevent_reinit);
// Don't use reference here as the next loop will make the pointed object change.
$this->items[$itemId] = $oItem;
$this->refs_list[$itemId] = $itemId;
}
break;
}
// Setting the object level with variable $this->items[$i][parent]
foreach ($this->items as $itemLPObject) {
$level = self::get_level_for_item($this->items, $itemLPObject->db_id);
$itemLPObject->level = $level;
}
// Setting the view in the item object.
if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
$this->items[$itemId]->set_lp_view($this->lp_view_id);
if (TOOL_HOTPOTATOES == $this->items[$itemId]->get_type()) {
$this->items[$itemId]->current_start_time = 0;
$this->items[$itemId]->current_stop_time = 0;
}
}
}
if (!empty($lp_item_id_list)) {
$lp_item_id_list_to_string = implode("','", $lp_item_id_list);
if (!empty($lp_item_id_list_to_string)) {
// Get last viewing vars.
$itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
// This query should only return one or zero result.
$sql = "SELECT lp_item_id, status
FROM $itemViewTable
WHERE
lp_view_id = ".$this->get_view_id()." AND
lp_item_id IN ('".$lp_item_id_list_to_string."')
ORDER BY view_count DESC ";
$status_list = [];
$res = Database::query($sql);
while ($row = Database:: fetch_array($res)) {
$status_list[$row['lp_item_id']] = $row['status'];
}
foreach ($lp_item_id_list as $item_id) {
if (isset($status_list[$item_id])) {
$status = $status_list[$item_id];
if (is_object($this->items[$item_id])) {
$this->items[$item_id]->set_status($status);
if (empty($status)) {
$this->items[$item_id]->set_status(
$this->default_status
);
}
}
} else {
if (!api_is_invitee()) {
if (isset($this->items[$item_id]) && is_object($this->items[$item_id])) {
$this->items[$item_id]->set_status(
$this->default_status
);
}
if (!empty($this->lp_view_id)) {
// Add that row to the lp_item_view table so that
// we have something to show in the stats page.
$params = [
'lp_item_id' => $item_id,
'lp_view_id' => $this->lp_view_id,
'view_count' => 1,
'status' => 'not attempted',
'start_time' => time(),
'total_time' => 0,
'score' => 0,
];
Database::insert($itemViewTable, $params);
$this->items[$item_id]->set_lp_view(
$this->lp_view_id
);
}
}
}
}
}
}
$this->ordered_items = self::get_flat_ordered_items_list($entity, null);
$this->max_ordered_items = 0;
foreach ($this->ordered_items as $index => $dummy) {
if ($index > $this->max_ordered_items && !empty($dummy)) {
$this->max_ordered_items = $index;
}
}
// TODO: Define the current item better.
$this->first();
if ($debug) {
error_log('lp_view_session_id '.$this->lp_view_session_id);
error_log('End of learnpath constructor for learnpath '.$this->get_id());
}
}
}
/**
* @return int
*/
public function get_course_int_id()
{
return $this->course_int_id ?? api_get_course_int_id();
}
/**
* @param $course_id
*
* @return int
*/
public function set_course_int_id($course_id)
{
return $this->course_int_id = (int) $course_id;
}
/**
* Function rewritten based on old_add_item() from Yannick Warnier.
* Due the fact that users can decide where the item should come, I had to overlook this function and
* I found it better to rewrite it. Old function is still available.
* Added also the possibility to add a description.
*
* @param CLpItem $parent
* @param int $previousId
* @param string $type
* @param int $id resource ID (ref)
* @param string $title
* @param string $description
* @param int $prerequisites
* @param int $maxTimeAllowed
* @param int $userId
*
* @return int
*/
public function add_item(
?CLpItem $parent,
$previousId,
$type,
$id,
$title,
$description = '',
$prerequisites = 0,
$maxTimeAllowed = 0
) {
$type = empty($type) ? 'dir' : $type;
$course_id = $this->course_info['real_id'];
if (empty($course_id)) {
// Sometimes Oogie doesn't catch the course info but sets $this->cc
$this->course_info = api_get_course_info($this->cc);
$course_id = $this->course_info['real_id'];
}
$id = (int) $id;
$maxTimeAllowed = (int) $maxTimeAllowed;
if (empty($maxTimeAllowed)) {
$maxTimeAllowed = 0;
}
$maxScore = 100;
if ('quiz' === $type && $id) {
// Disabling the exercise if we add it inside a LP
$exercise = new Exercise($course_id);
$exercise->read($id);
$maxScore = $exercise->getMaxScore();
$exercise->disable();
$exercise->save();
$title = $exercise->get_formated_title();
}
$lpItem = (new CLpItem())
->setTitle($title)
->setDescription($description)
->setPath($id)
->setLp(api_get_lp_entity($this->get_id()))
->setItemType($type)
->setMaxScore($maxScore)
->setMaxTimeAllowed($maxTimeAllowed)
->setPrerequisite($prerequisites)
//->setDisplayOrder($display_order + 1)
//->setNextItemId((int) $next)
//->setPreviousItemId($previous)
;
if (!empty($parent)) {
$lpItem->setParent($parent);
}
$em = Database::getManager();
$em->persist($lpItem);
$em->flush();
$new_item_id = $lpItem->getIid();
if ($new_item_id) {
// @todo fix upload audio.
// Upload audio.
/*if (!empty($_FILES['mp3']['name'])) {
// Create the audio folder if it does not exist yet.
$filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
if (!is_dir($filepath.'audio')) {
mkdir(
$filepath.'audio',
api_get_permissions_for_new_directories()
);
DocumentManager::addDocument(
$_course,
'/audio',
'folder',
0,
'audio',
'',
0,
true,
null,
$sessionId,
$userId
);
}
$file_path = handle_uploaded_document(
$_course,
$_FILES['mp3'],
api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
'/audio',
$userId,
'',
'',
'',
'',
false
);
// Getting the filename only.
$file_components = explode('/', $file_path);
$file = $file_components[count($file_components) - 1];
// Store the mp3 file in the lp_item table.
$sql = "UPDATE $tbl_lp_item SET
audio = '".Database::escape_string($file)."'
WHERE iid = '".intval($new_item_id)."'";
Database::query($sql);
}*/
}
return $new_item_id;
}
/**
* Static admin function allowing addition of a learnpath to a course.
*
* @param string $courseCode
* @param string $name
* @param string $description
* @param string $learnpath
* @param string $origin
* @param string $zipname Zip file containing the learnpath or directory containing the learnpath
* @param string $published_on
* @param string $expired_on
* @param int $categoryId
* @param int $userId
*
* @return CLp
*/
public static function add_lp(
$courseCode,
$name,
$description = '',
$learnpath = 'guess',
$origin = 'zip',
$zipname = '',
$published_on = '',
$expired_on = '',
$categoryId = 0,
$userId = 0
) {
global $charset;
if (!empty($courseCode)) {
$courseInfo = api_get_course_info($courseCode);
$course_id = $courseInfo['real_id'];
} else {
$course_id = api_get_course_int_id();
$courseInfo = api_get_course_info();
}
$categoryId = (int) $categoryId;
if (empty($published_on)) {
$published_on = null;
} else {
$published_on = api_get_utc_datetime($published_on, true, true);
}
if (empty($expired_on)) {
$expired_on = null;
} else {
$expired_on = api_get_utc_datetime($expired_on, true, true);
}
$description = Database::escape_string(api_htmlentities($description, ENT_QUOTES));
$type = 1;
switch ($learnpath) {
case 'guess':
case 'aicc':
break;
case 'dokeos':
case 'chamilo':
$type = 1;
break;
}
$sessionEntity = api_get_session_entity();
$courseEntity = api_get_course_entity($courseInfo['real_id']);
$lp = null;
switch ($origin) {
case 'zip':
// Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
break;
case 'manual':
default:
/*$get_max = "SELECT MAX(display_order)
FROM $tbl_lp WHERE c_id = $course_id";
$res_max = Database::query($get_max);
if (Database::num_rows($res_max) < 1) {
$dsp = 1;
} else {
$row = Database::fetch_array($res_max);
$dsp = $row[0] + 1;
}*/
$category = null;
if (!empty($categoryId)) {
$category = Container::getLpCategoryRepository()->find($categoryId);
}
$lpRepo = Container::getLpRepository();
$lp = (new CLp())
->setLpType($type)
->setTitle($name)
->setDescription($description)
->setCategory($category)
->setPublishedOn($published_on)
->setExpiredOn($expired_on)
->setParent($courseEntity)
->addCourseLink($courseEntity, $sessionEntity)
;
$lpRepo->createLp($lp);
break;
}
return $lp;
}
/**
* Auto completes the parents of an item in case it's been completed or passed.
*
* @param int $item Optional ID of the item from which to look for parents
*/
public function autocomplete_parents($item)
{
$debug = $this->debug;
if (empty($item)) {
$item = $this->current;
}
$currentItem = $this->getItem($item);
if ($currentItem) {
$parent_id = $currentItem->get_parent();
$parent = $this->getItem($parent_id);
if ($parent) {
// if $item points to an object and there is a parent.
if ($debug) {
error_log(
'Autocompleting parent of item '.$item.' '.
$currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
0
);
}
// New experiment including failed and browsed in completed status.
//$current_status = $currentItem->get_status();
//if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
// Fixes chapter auto complete
if (true) {
// If the current item is completed or passes or succeeded.
$updateParentStatus = true;
if ($debug) {
error_log('Status of current item is alright');
}
foreach ($parent->get_children() as $childItemId) {
$childItem = $this->getItem($childItemId);
// If children was not set try to get the info
if (empty($childItem->db_item_view_id)) {
$childItem->set_lp_view($this->lp_view_id);
}
// Check all his brothers (parent's children) for completion status.
if ($childItemId != $item) {
if ($debug) {
error_log(
'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
0
);
}
// Trying completing parents of failed and browsed items as well.
if ($childItem->status_is(
[
'completed',
'passed',
'succeeded',
'browsed',
'failed',
]
)
) {
// Keep completion status to true.
continue;
} else {
if ($debug > 2) {
error_log(
'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,
0
);
}
$updateParentStatus = false;
break;
}
}
}
if ($updateParentStatus) {
// If all the children were completed:
$parent->set_status('completed');
$parent->save(false, $this->prerequisites_match($parent->get_id()));
// Force the status to "completed"
//$this->update_queue[$parent->get_id()] = $parent->get_status();
$this->update_queue[$parent->get_id()] = 'completed';
if ($debug) {
error_log(
'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
print_r($this->update_queue, 1),
0
);
}
// Recursive call.
$this->autocomplete_parents($parent->get_id());
}
}
} else {
if ($debug) {
error_log("Parent #$parent_id does not exists");
}
}
} else {
if ($debug) {
error_log("#$item is an item that doesn't have parents");
}
}
}
/**
* Closes the current resource.
*
* Stops the timer
* Saves into the database if required
* Clears the current resource data from this object
*
* @return bool True on success, false on failure
*/
public function close()
{
if (empty($this->lp_id)) {
$this->error = 'Trying to close this learnpath but no ID is set';
return false;
}
$this->current_time_stop = time();
$this->ordered_items = [];
$this->index = 0;
unset($this->lp_id);
//unset other stuff
return true;
}
/**
* Static admin function allowing removal of a learnpath.
*
* @param array $courseInfo
* @param int $id Learnpath ID
* @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
*
* @return bool True on success, false on failure (might change that to return number of elements deleted)
*/
public function delete($courseInfo = null, $id = null, $delete = 'keep')
{
$course_id = api_get_course_int_id();
if (!empty($courseInfo)) {
$course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
}
// TODO: Implement a way of getting this to work when the current object is not set.
// In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
// If an ID is specifically given and the current LP is not the same, prevent delete.
if (!empty($id) && ($id != $this->lp_id)) {
return false;
}
$course = api_get_course_entity();
$session = api_get_session_entity();
//$lp_item = Database::get_course_table(TABLE_LP_ITEM);
//$lp_view = Database::get_course_table(TABLE_LP_VIEW);
//$lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
// Delete lp item id.
//foreach ($this->items as $lpItemId => $dummy) {
// $sql = "DELETE FROM $lp_item_view
// WHERE lp_item_id = '".$lpItemId."'";
// Database::query($sql);
//}
// Proposed by Christophe (nickname: clefevre)
//$sql = "DELETE FROM $lp_item
// WHERE lp_id = ".$this->lp_id;
//Database::query($sql);
//$sql = "DELETE FROM $lp_view
// WHERE lp_id = ".$this->lp_id;
//Database::query($sql);
//$table = Database::get_course_table(TABLE_LP_REL_USERGROUP);
//$sql = "DELETE FROM $table
// WHERE
// lp_id = {$this->lp_id}";
//Database::query($sql);
$lp = Container::getLpRepository()->find($this->lp_id);
Database::getManager()
->getRepository(ResourceLink::class)
->removeByResourceInContext($lp, $course, $session);
$link_info = GradebookUtils::isResourceInCourseGradebook(
api_get_course_int_id(),
4,
$id,
api_get_session_id()
);
if (false !== $link_info) {
GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
}
//if ('true' === api_get_setting('search_enabled')) {
// delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
//}
}
/**
* Removes all the children of one item - dangerous!
*
* @param int $id Element ID of which children have to be removed
*
* @return int Total number of children removed
*/
public function delete_children_items($id)
{
$course_id = $this->course_info['real_id'];
$num = 0;
$id = (int) $id;
if (empty($id) || empty($course_id)) {
return false;
}
$lp_item = Database::get_course_table(TABLE_LP_ITEM);
$sql = "SELECT * FROM $lp_item
WHERE parent_item_id = $id";
$res = Database::query($sql);
while ($row = Database::fetch_array($res)) {
$num += $this->delete_children_items($row['iid']);
$sql = "DELETE FROM $lp_item
WHERE iid = ".$row['iid'];
Database::query($sql);
$num++;
}
return $num;
}
/**
* Removes an item from the current learnpath.
*
* @param int $id Elem ID (0 if first)
*
* @return int Number of elements moved
*
* @todo implement resource removal
*/
public function delete_item($id)
{
$course_id = api_get_course_int_id();
$id = (int) $id;
// TODO: Implement the resource removal.
if (empty($id) || empty($course_id)) {
return false;
}
$repo = Container::getLpItemRepository();
$item = $repo->find($id);
if (null === $item) {
return false;
}
$em = Database::getManager();
$repo->removeFromTree($item);
$em->flush();
$lp_item = Database::get_course_table(TABLE_LP_ITEM);
//Removing prerequisites since the item will not longer exist
$sql_all = "UPDATE $lp_item SET prerequisite = ''
WHERE prerequisite = '$id'";
Database::query($sql_all);
$sql = "UPDATE $lp_item
SET previous_item_id = ".$this->getLastInFirstLevel()."
WHERE lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
Database::query($sql);
// Remove from search engine if enabled.
if ('true' === api_get_setting('search_enabled')) {
$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
$sql = 'SELECT * FROM %s
WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
LIMIT 1';
$sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
$res = Database::query($sql);
if (Database::num_rows($res) > 0) {
$row2 = Database::fetch_array($res);
$di = new ChamiloIndexer();
$di->remove_document($row2['search_did']);
}
$sql = 'DELETE FROM %s
WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
LIMIT 1';
$sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
Database::query($sql);
}
}
/**
* Updates an item's content in place.
*
* @param int $id Element ID
* @param int $parent Parent item ID
* @param int $previous Previous item ID
* @param string $title Item title
* @param string $description Item description
* @param string $prerequisites Prerequisites (optional)
* @param array $audio The array resulting of the $_FILES[mp3] element
* @param int $max_time_allowed
* @param string $url
*
* @return bool True on success, false on error
*/
public function edit_item(
$id,
$parent,
$previous,
$title,
$description,
$prerequisites = '0',
$audio = [],
$max_time_allowed = 0,
$url = ''
) {
$_course = api_get_course_info();
$id = (int) $id;
if (empty($id) || empty($_course)) {
return false;
}
$repo = Container::getLpItemRepository();
/** @var CLpItem $item */
$item = $repo->find($id);
if (null === $item) {
return false;
}
$item
->setTitle($title)
->setDescription($description)
->setPrerequisite($prerequisites)
->setMaxTimeAllowed((int) $max_time_allowed)
;
$em = Database::getManager();
if (!empty($parent)) {
$parent = $repo->find($parent);
$item->setParent($parent);
} else {
$item->setParent(null);
}
if (!empty($previous)) {
$previous = $repo->find($previous);
$repo->persistAsNextSiblingOf( $item, $previous);
} else {
$em->persist($item);
}
$em->flush();
if ('link' === $item->getItemType()) {
$link = new Link();
$linkId = $item->getPath();
$link->updateLink($linkId, $url);
}
}