forked from chamilo/chamilo-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourseBuilder.php
More file actions
3302 lines (2825 loc) · 119 KB
/
Copy pathCourseBuilder.php
File metadata and controls
3302 lines (2825 loc) · 119 KB
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 */
declare(strict_types=1);
namespace Chamilo\CourseBundle\Component\CourseCopy;
use Chamilo\CoreBundle\Entity\Course as CourseEntity;
use Chamilo\CoreBundle\Entity\GradebookCategory;
use Chamilo\CoreBundle\Entity\GradebookEvaluation;
use Chamilo\CoreBundle\Entity\GradebookLink;
use Chamilo\CoreBundle\Entity\ResourceFile;
use Chamilo\CoreBundle\Entity\ResourceLink;
use Chamilo\CoreBundle\Entity\ResourceNode;
use Chamilo\CoreBundle\Entity\Session as SessionEntity;
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CoreBundle\Repository\ResourceNodeRepository;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Attendance;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\CalendarEvent;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\CourseDescription;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Document;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Glossary;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\GradeBookBackup;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Thematic;
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Work;
use Chamilo\CourseBundle\Entity\CAnnouncement;
use Chamilo\CourseBundle\Entity\CAnnouncementAttachment;
use Chamilo\CourseBundle\Entity\CAttendance;
use Chamilo\CourseBundle\Entity\CAttendanceCalendar;
use Chamilo\CourseBundle\Entity\CCalendarEvent;
use Chamilo\CourseBundle\Entity\CCalendarEventAttachment;
use Chamilo\CourseBundle\Entity\CCourseDescription;
use Chamilo\CourseBundle\Entity\CDocument;
use Chamilo\CourseBundle\Entity\CForum;
use Chamilo\CourseBundle\Entity\CForumCategory;
use Chamilo\CourseBundle\Entity\CForumPost;
use Chamilo\CourseBundle\Entity\CForumThread;
use Chamilo\CourseBundle\Entity\CGlossary;
use Chamilo\CourseBundle\Entity\CLink;
use Chamilo\CourseBundle\Entity\CLinkCategory;
use Chamilo\CourseBundle\Entity\CLp;
use Chamilo\CourseBundle\Entity\CLpCategory;
use Chamilo\CourseBundle\Entity\CLpItem;
use Chamilo\CourseBundle\Entity\CQuiz;
use Chamilo\CourseBundle\Entity\CQuizAnswer;
use Chamilo\CourseBundle\Entity\CQuizQuestion;
use Chamilo\CourseBundle\Entity\CQuizQuestionOption;
use Chamilo\CourseBundle\Entity\CQuizRelQuestion;
use Chamilo\CourseBundle\Entity\CStudentPublication;
use Chamilo\CourseBundle\Entity\CStudentPublicationAssignment;
use Chamilo\CourseBundle\Entity\CSurvey;
use Chamilo\CourseBundle\Entity\CSurveyQuestion;
use Chamilo\CourseBundle\Entity\CSurveyQuestionOption;
use Chamilo\CourseBundle\Entity\CThematic;
use Chamilo\CourseBundle\Entity\CThematicAdvance;
use Chamilo\CourseBundle\Entity\CThematicPlan;
use Chamilo\CourseBundle\Entity\CToolIntro;
use Chamilo\CourseBundle\Entity\CWiki;
use Chamilo\CourseBundle\Repository\CDocumentRepository;
use Closure;
use Countable;
use Database;
use DateTimeInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use DocumentManager;
use ReflectionProperty;
use stdClass;
use Symfony\Component\HttpKernel\KernelInterface;
use Throwable;
use const PHP_URL_PATH;
/**
* CourseBuilder focused on Doctrine/ResourceNode export (keeps legacy orchestration).
*/
class CourseBuilder
{
/**
* @var Course Legacy course container used by the exporter
*/
public $course;
/**
* @var array<string> Only the tools to build (defaults kept)
*/
public array $tools_to_build = [
'documents', 'forums', 'tool_intro', 'links', 'quizzes', 'quiz_questions',
'assets', 'surveys', 'survey_questions', 'announcements', 'events',
'course_descriptions', 'glossary', 'wiki', 'thematic', 'attendance', 'works',
'gradebook', 'learnpath_category', 'learnpaths',
];
/**
* @var array<string, int|string> Legacy constant map (extend as you add tools)
*/
public array $toolToName = [
'documents' => RESOURCE_DOCUMENT,
'forums' => RESOURCE_FORUM,
'tool_intro' => RESOURCE_TOOL_INTRO,
'links' => RESOURCE_LINK,
'quizzes' => RESOURCE_QUIZ,
'quiz_questions' => RESOURCE_QUIZQUESTION,
'assets' => 'asset',
'surveys' => RESOURCE_SURVEY,
'survey_questions' => RESOURCE_SURVEYQUESTION,
'announcements' => RESOURCE_ANNOUNCEMENT,
'events' => RESOURCE_EVENT,
'course_descriptions' => RESOURCE_COURSEDESCRIPTION,
'glossary' => RESOURCE_GLOSSARY,
'wiki' => RESOURCE_WIKI,
'thematic' => RESOURCE_THEMATIC,
'attendance' => RESOURCE_ATTENDANCE,
'works' => RESOURCE_WORK,
'gradebook' => RESOURCE_GRADEBOOK,
'learnpaths' => RESOURCE_LEARNPATH,
'learnpath_category' => RESOURCE_LEARNPATH_CATEGORY,
];
/**
* @var array<string, array<int>> Optional whitelist of IDs per tool
*/
public array $specific_id_list = [];
/**
* Documents referenced inside HTML.
*
* Stored as an associative array keyed by the URL to avoid duplicates:
* - key: url
* - value: [url, scope, type]
*
* @var array<string, array{0:string,1:string,2:string}>
*/
public array $documentsAddedInText = [];
/**
* Doctrine services.
*/
private EntityManagerInterface $em;
private CDocumentRepository $docRepo;
/**
* When exporting with a session context:
* - true => include both base course content + session content
* - false => include only session-specific content
*
* This must be used consistently by all resource builders.
*/
private bool $withBaseContent = false;
/**
* Cached course info array used during build().
*
* @var array<string,mixed>
*/
private array $courseInfo = [];
/**
* Internal trace toggle for this class.
* Set to false to disable logs.
*/
private const TRACE_ENABLED = false;
/**
* Constructor (keeps legacy init; wires Doctrine repositories).
*
* @param string $type 'partial'|'complete'
* @param array|null $course Optional course info array
*/
public function __construct(string $type = '', ?array $course = null)
{
// Legacy behavior preserved
$_course = api_get_course_info();
if (!empty($course['official_code'])) {
$_course = $course;
}
$this->course = new Course();
$this->course->code = $_course['code'];
$this->course->type = $type;
$this->course->encoding = api_get_system_encoding();
$this->course->info = $_course;
/** @var EntityManagerInterface $em */
$em = Database::getManager();
$this->em = $em;
/** @var CDocumentRepository $docRepo */
$docRepo = Container::getDocumentRepository();
$this->docRepo = $docRepo;
$this->courseInfo = is_array($this->course->info ?? null) ? $this->course->info : [];
}
/**
* Merge a parsed list of document refs into memory.
*
* @param array<int, array{0:string,1:string,2:string}> $list
*/
public function addDocumentList(array $list): void
{
foreach ($list as $item) {
$url = (string) ($item[0] ?? '');
if ('' === $url) {
continue;
}
// Keep the first occurrence for a given URL (dedupe by URL key).
if (!isset($this->documentsAddedInText[$url])) {
$this->documentsAddedInText[$url] = $item;
}
}
}
/**
* Parse HTML and collect referenced course documents.
*/
public function findAndSetDocumentsInText(string $html = ''): void
{
if ('' === $html) {
return;
}
$documentList = DocumentManager::get_resources_from_source_html($html);
$this->addDocumentList($documentList);
}
/**
* Resolve collected HTML links to CDocument iids and build them.
*/
public function restoreDocumentsFromList(?CourseEntity $course = null, ?SessionEntity $session = null): void
{
if (empty($this->documentsAddedInText)) {
return;
}
// Resolve current course entity if not provided.
if (!$course instanceof CourseEntity) {
$courseInfo = api_get_course_info();
$courseCode = (string) ($courseInfo['code'] ?? '');
if ('' === $courseCode) {
return;
}
/** @var CourseEntity|null $resolved */
$resolved = $this->em->getRepository(CourseEntity::class)->findOneBy(['code' => $courseCode]);
if (!$resolved instanceof CourseEntity) {
return;
}
$course = $resolved;
}
$need = [];
foreach ($this->documentsAddedInText as $item) {
[$url, $scope, $type] = $item; // url, scope(local/remote), type(rel/abs/url)
// Only process local document-style URLs.
if ('local' !== $scope || !\in_array($type, ['rel', 'abs'], true)) {
continue;
}
$rel = $this->extractRelativeDocumentPathFromUrl((string) $url);
$rel = $this->normalizeDocumentRelPath($rel);
if ('' === $rel) {
continue;
}
// Include the file path itself.
$need[$rel] = true;
// Also include parent folders to preserve hierarchy on restore.
$parts = array_values(array_filter(explode('/', $rel), static fn ($s) => '' !== $s));
if (\count($parts) > 1) {
$prefix = '';
for ($i = 0; $i < \count($parts) - 1; $i++) {
$prefix = '' === $prefix ? $parts[$i] : $prefix.'/'.$parts[$i];
$need[$prefix] = true;
}
}
}
if (empty($need)) {
return;
}
$paths = array_keys($need);
$iids = $this->resolveDocumentIidsByRelativePaths($course, $session, $paths);
if (empty($iids)) {
$this->trace('COURSE_BUILD: no referenced documents matched in repository (paths_count='.\count($paths).')');
return;
}
$sid = (int) ($session?->getId() ?? api_get_session_id());
$cid = (int) $course->getId();
$this->build_documents($sid, $cid, $this->withBaseContent, $iids);
}
/**
* Extract path part after ".../document/" from a URL.
* Returns an empty string when not a document-like URL.
*/
private function extractRelativeDocumentPathFromUrl(string $url): string
{
if ('' === $url) {
return '';
}
// Remove fragment/query early, keep only path.
$decoded = urldecode($url);
$path = (string) (parse_url($decoded, PHP_URL_PATH) ?? '');
if ('' === $path) {
$path = $decoded;
}
// Most common patterns:
// - /courses/COURSECODE/document/Folder/file.png
// - /document/Folder/file.png
// - document/Folder/file.png
$pos = stripos($path, '/document/');
if (false !== $pos) {
return substr($path, $pos + \strlen('/document/')) ?: '';
}
if (str_starts_with($path, 'document/')) {
return substr($path, \strlen('document/')) ?: '';
}
if (str_starts_with($path, '/document/')) {
return substr($path, \strlen('/document/')) ?: '';
}
// Fallback: "/document" without trailing slash.
$pos2 = stripos($path, '/document');
if (false !== $pos2) {
$tail = substr($path, $pos2 + \strlen('/document')) ?: '';
return ltrim($tail, '/');
}
return '';
}
/**
* Normalize a relative document path for matching.
*/
private function normalizeDocumentRelPath(string $path): string
{
if ('' === $path) {
return '';
}
$path = urldecode($path);
$path = str_replace('\\', '/', $path);
// Remove "Documents" prefix if present (defensive).
$path = preg_replace('~^/?Documents/?~i', '', $path) ?? $path;
// Trim slashes and collapse duplicated slashes.
$path = trim($path, '/');
$path = preg_replace('~/{2,}~', '/', $path) ?? $path;
return (string) $path;
}
/**
* Resolve document IIDs by comparing computed "relative display paths" with the given list.
*
* @param array<int,string> $relativePaths
*
* @return array<int>
*/
private function resolveDocumentIidsByRelativePaths(
CourseEntity $course,
?SessionEntity $session,
array $relativePaths
): array {
if (empty($relativePaths)) {
return [];
}
$need = [];
foreach ($relativePaths as $p) {
$p = $this->normalizeDocumentRelPath((string) $p);
if ('' !== $p) {
$need[$p] = true;
}
}
if (empty($need)) {
return [];
}
// IMPORTANT: always pass withBaseContent to the repository when supported.
$qb = $this->getResourcesByCourseQbFromRepo($this->docRepo, $course, $session, $this->withBaseContent);
/** @var CDocument[] $docs */
$docs = $qb->getQuery()->getResult();
$documentsRoot = $this->docRepo->getCourseDocumentsRootNode($course);
$iids = [];
foreach ($docs as $doc) {
$node = $doc->getResourceNode();
if (!$node instanceof ResourceNode) {
continue;
}
$rel = '';
if ($documentsRoot instanceof ResourceNode) {
$rel = (string) $node->getPathForDisplayRemoveBase((string) $documentsRoot->getPath());
} else {
$rel = (string) $node->convertPathForDisplay((string) $node->getPath());
$rel = preg_replace('~^/?Documents/?~i', '', (string) $rel) ?? $rel;
}
$rel = $this->normalizeDocumentRelPath($rel);
if ('' === $rel) {
continue;
}
if (isset($need[$rel])) {
$iid = (int) $doc->getIid();
if ($iid > 0) {
$iids[] = $iid;
}
}
}
return array_values(array_unique($iids));
}
/**
* Set tools to build.
*
* @param array<string> $array
*/
public function set_tools_to_build(array $array): void
{
$this->tools_to_build = $array;
}
/**
* Set specific id list per tool.
*
* @param array<string, array<int>> $array
*/
public function set_tools_specific_id_list(array $array): void
{
$this->specific_id_list = $array;
}
/**
* Build the course (documents already repo-based; other tools preserved).
*
* @param array<int|string> $parseOnlyToolList
* @param array<string,mixed> $toolsFromPost
*/
public function build(
int $session_id = 0,
string $courseCode = '',
bool $withBaseContent = false,
array $parseOnlyToolList = [],
array $toolsFromPost = []
): Course {
$this->withBaseContent = $withBaseContent;
// Resolve effective course code:
// - If caller did not pass a code, reuse the code already loaded in the constructor.
$effectiveCourseCode = '' !== trim($courseCode)
? trim($courseCode)
: (string) ($this->course->code ?? '');
if ('' === $effectiveCourseCode) {
throw new \RuntimeException('CourseBuilder cannot determine a course code (empty effective code).');
}
// Prefer constructor-provided course info to avoid api_get_course_info() side effects.
if (empty($this->courseInfo) || !is_array($this->courseInfo)) {
$this->courseInfo = is_array($this->course->info ?? null) ? $this->course->info : [];
}
// Only fetch via api_get_course_info() if we still don't have matching info.
if (
empty($this->courseInfo)
|| !is_array($this->courseInfo)
|| (string) ($this->courseInfo['code'] ?? '') !== $effectiveCourseCode
) {
$this->courseInfo = api_get_course_info($effectiveCourseCode);
}
if (empty($this->courseInfo) || !is_array($this->courseInfo) || '' === (string) ($this->courseInfo['code'] ?? '')) {
throw new \RuntimeException(sprintf(
'CourseBuilder cannot load course info for course code "%s".',
$effectiveCourseCode
));
}
/** @var CourseEntity|null $courseEntity */
$courseEntity = $this->em->getRepository(CourseEntity::class)->findOneBy(['code' => $effectiveCourseCode]);
if (!$courseEntity instanceof CourseEntity) {
throw new \RuntimeException(sprintf(
'CourseBuilder cannot resolve CourseEntity for course code "%s".',
$effectiveCourseCode
));
}
/** @var SessionEntity|null $sessionEntity */
$sessionEntity = $session_id
? $this->em->getRepository(SessionEntity::class)->find($session_id)
: null;
// Legacy DTO where resources[...] are built
$legacyCourse = $this->course;
foreach ($this->tools_to_build as $toolKey) {
if (!empty($parseOnlyToolList)) {
$const = $this->toolToName[$toolKey] ?? null;
if (null !== $const && !\in_array($const, $parseOnlyToolList, true)) {
continue;
}
}
if ('documents' === $toolKey) {
$ids = $this->specific_id_list['documents'] ?? [];
$this->build_documents_with_repo($courseEntity, $sessionEntity, $withBaseContent, $ids);
}
if ('forums' === $toolKey || 'forum' === $toolKey) {
$ids = $this->specific_id_list['forums'] ?? $this->specific_id_list['forum'] ?? [];
$this->build_forum_category($legacyCourse, $courseEntity, $sessionEntity, $ids);
$this->build_forums($legacyCourse, $courseEntity, $sessionEntity, $ids);
$this->build_forum_topics($legacyCourse, $courseEntity, $sessionEntity, $ids);
$this->build_forum_posts($legacyCourse, $courseEntity, $sessionEntity, $ids);
}
if ('tool_intro' === $toolKey) {
$this->build_tool_intro($legacyCourse, $courseEntity, $sessionEntity);
}
if ('links' === $toolKey) {
$ids = $this->specific_id_list['links'] ?? [];
$this->build_links($legacyCourse, $courseEntity, $sessionEntity, $ids);
}
if ('quizzes' === $toolKey || 'quiz' === $toolKey) {
$ids = $this->specific_id_list['quizzes'] ?? $this->specific_id_list['quiz'] ?? [];
$neededQuestionIds = $this->build_quizzes($legacyCourse, $courseEntity, $sessionEntity, $ids);
// Always export question bucket required by the quizzes
$this->build_quiz_questions($legacyCourse, $courseEntity, $sessionEntity, $neededQuestionIds);
}
if ('quiz_questions' === $toolKey) {
$ids = $this->specific_id_list['quiz_questions'] ?? [];
$this->build_quiz_questions($legacyCourse, $courseEntity, $sessionEntity, $ids);
}
if ('surveys' === $toolKey || 'survey' === $toolKey) {
$ids = $this->specific_id_list['surveys'] ?? $this->specific_id_list['survey'] ?? [];
$neededQ = $this->build_surveys($this->course, $courseEntity, $sessionEntity, $ids);
$this->build_survey_questions($this->course, $courseEntity, $sessionEntity, $neededQ);
}
if ('survey_questions' === $toolKey) {
$this->build_survey_questions($this->course, $courseEntity, $sessionEntity, []);
}
if ('announcements' === $toolKey) {
$ids = $this->specific_id_list['announcements'] ?? [];
$this->build_announcements($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('events' === $toolKey) {
$ids = $this->specific_id_list['events'] ?? [];
$this->build_events($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('course_descriptions' === $toolKey) {
$ids = $this->specific_id_list['course_descriptions'] ?? [];
$this->build_course_descriptions($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('glossary' === $toolKey) {
$ids = $this->specific_id_list['glossary'] ?? [];
$this->build_glossary($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('wiki' === $toolKey) {
$ids = $this->specific_id_list['wiki'] ?? [];
$this->build_wiki($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('thematic' === $toolKey) {
$ids = $this->specific_id_list['thematic'] ?? [];
$this->build_thematic($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('attendance' === $toolKey) {
$ids = $this->specific_id_list['attendance'] ?? [];
$this->build_attendance($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('works' === $toolKey) {
$ids = $this->specific_id_list['works'] ?? [];
$this->build_works($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('gradebook' === $toolKey) {
$this->build_gradebook($this->course, $courseEntity, $sessionEntity);
}
if ('learnpath_category' === $toolKey) {
$ids = $this->specific_id_list['learnpath_category'] ?? [];
$this->build_learnpath_category($this->course, $courseEntity, $sessionEntity, $ids);
}
if ('learnpaths' === $toolKey) {
$ids = $this->specific_id_list['learnpaths'] ?? [];
$this->build_learnpaths($this->course, $courseEntity, $sessionEntity, $ids, true);
}
}
// Always try to include documents referenced inside HTML (images, attachments, etc.).
if ($courseEntity instanceof CourseEntity) {
$this->restoreDocumentsFromList($courseEntity, $sessionEntity);
}
return $this->course;
}
/**
* Export Learnpath categories (CLpCategory).
*
* @param array<int> $ids
*/
public function build_learnpath_category(
object $legacyCourse,
?CourseEntity $courseEntity,
?SessionEntity $sessionEntity,
array $ids
): void {
if (!$courseEntity instanceof CourseEntity) {
return;
}
$repo = Container::getLpCategoryRepository();
// propagate withBaseContent to repo when supported.
$qb = $this->getResourcesByCourseQbFromRepo($repo, $courseEntity, $sessionEntity, $this->withBaseContent);
if (!empty($ids)) {
$qb->andWhere('resource.iid IN (:ids)')
->setParameter('ids', array_values(array_unique(array_map('intval', $ids))))
;
}
/** @var CLpCategory[] $rows */
$rows = $qb->getQuery()->getResult();
foreach ($rows as $cat) {
$iid = (int) $cat->getIid();
$title = (string) $cat->getTitle();
$payload = [
'id' => $iid,
'title' => $title,
];
$legacyCourse->resources[RESOURCE_LEARNPATH_CATEGORY][$iid] =
$this->mkLegacyItem(RESOURCE_LEARNPATH_CATEGORY, $iid, $payload);
}
}
/**
* Export Learnpaths (CLp) + items, with optional SCORM folder packing.
*
* @param array<int> $idList
*/
public function build_learnpaths(
object $legacyCourse,
?CourseEntity $courseEntity,
?SessionEntity $sessionEntity,
array $idList = [],
bool $addScormFolder = true
): void {
if (!$courseEntity instanceof CourseEntity) {
return;
}
$lpRepo = Container::getLpRepository();
// propagate withBaseContent to repo when supported.
$qb = $this->getResourcesByCourseQbFromRepo($lpRepo, $courseEntity, $sessionEntity, $this->withBaseContent);
if (!empty($idList)) {
$qb->andWhere('resource.iid IN (:ids)')
->setParameter('ids', array_values(array_unique(array_map('intval', $idList))))
;
}
/** @var CLp[] $lps */
$lps = $qb->getQuery()->getResult();
// Map SCORM folder name -> LP iid when possible (best-effort, no guesses beyond CLp getters).
$scormLpByDir = [];
foreach ($lps as $lpTmp) {
$lpTypeTmp = (int) $lpTmp->getLpType();
if (CLp::SCORM_TYPE !== $lpTypeTmp) {
continue;
}
$p = trim((string) $lpTmp->getPath());
if ('' === $p) {
continue;
}
// Try direct folder name and basename variants.
$pNorm = trim(str_replace('\\', '/', $p), '/');
if ('' !== $pNorm) {
$scormLpByDir[$pNorm] = (int) ($lpTmp->getIid() ?? 0);
$base = basename($pNorm);
if ('' !== $base) {
$scormLpByDir[$base] = (int) ($lpTmp->getIid() ?? 0);
}
}
}
foreach ($lps as $lp) {
$iid = (int) ($lp->getIid() ?? 0);
if ($iid <= 0) {
continue;
}
$lpType = (int) $lp->getLpType(); // 1=LP, 2=SCORM, 3=AICC
// Build raw items keyed by legacy item iid so we can compute levels safely.
$rawItemsById = [];
$parentById = [];
/** @var CLpItem $it */
foreach ($lp->getItems() as $it) {
$itemId = (int) ($it->getIid() ?? 0);
if ($itemId <= 0) {
continue;
}
$itemType = (string) $it->getItemType();
$itemTypeLower = strtolower($itemType);
// Avoid exporting an eventual root item (restore will use lpItemRepo->getRootItem()).
if ('root' === $itemTypeLower) {
continue;
}
$parentId = (int) $it->getParentItemId();
$parentById[$itemId] = $parentId;
$ref = (string) $it->getRef();
$path = (string) $it->getPath();
$rawItemsById[$itemId] = [
'id' => $itemId,
'item_type' => $itemType,
'ref' => $ref,
'identifier' => $ref, // legacy compatibility
'path' => $path,
'identifierref' => $path, // legacy compatibility
'title' => (string) $it->getTitle(),
'description' => (string) ($it->getDescription() ?? ''),
'min_score' => (float) $it->getMinScore(),
'max_score' => null !== $it->getMaxScore() ? (float) $it->getMaxScore() : null,
'mastery_score' => null !== $it->getMasteryScore() ? (float) $it->getMasteryScore() : null,
'parent_item_id' => $parentId,
'previous_item_id' => null !== $it->getPreviousItemId() ? (int) $it->getPreviousItemId() : null,
'next_item_id' => null !== $it->getNextItemId() ? (int) $it->getNextItemId() : null,
'display_order' => (int) $it->getDisplayOrder(),
'prerequisite' => (string) ($it->getPrerequisite() ?? ''),
'parameters' => (string) ($it->getParameters() ?? ''),
'launch_data' => (string) $it->getLaunchData(),
'audio' => (string) ($it->getAudio() ?? ''),
'duration' => method_exists($it, 'getDuration') ? $it->getDuration() : null,
'export_allowed' => method_exists($it, 'isExportAllowed') ? (bool) $it->isExportAllowed() : null,
];
}
// Compute "level" purely from parent_item_id relationships (no reliance on getLvl()).
$visiting = [];
$levelOf = null;
$levelOf = static function (int $id) use (&$levelOf, &$parentById, &$visiting): int {
if ($id <= 0) {
return 0;
}
if (isset($visiting[$id])) {
// Cycle protection: treat as root-level.
return 0;
}
$pid = $parentById[$id] ?? 0;
if ($pid <= 0) {
return 0;
}
$visiting[$id] = true;
$lvl = 1 + $levelOf($pid);
unset($visiting[$id]);
return $lvl;
};
foreach ($rawItemsById as $itemId => $row) {
$rawItemsById[$itemId]['level'] = $levelOf((int) $itemId);
}
// linked_resources: helps restore minimal deps without relying on selection.
$linked = [
'document' => [],
'quiz' => [],
'link' => [],
'student_publication' => [],
'survey' => [],
'forum' => [],
];
$addLinked = static function (array &$bucket, string $key, $raw): void {
if (!isset($bucket[$key])) {
return;
}
if (null === $raw || '' === $raw) {
return;
}
$s = (string) $raw;
if (!ctype_digit($s)) {
return;
}
$bucket[$key][(int) $s] = true;
};
foreach ($rawItemsById as $row) {
$t = strtolower((string) ($row['item_type'] ?? ''));
$raw = $row['path'] ?? ($row['ref'] ?? ($row['identifierref'] ?? ''));
switch ($t) {
case 'document':
$addLinked($linked, 'document', $raw);
break;
case 'quiz':
case 'exercise':
$addLinked($linked, 'quiz', $raw);
break;
case 'link':
case 'weblink':
case 'url':
$addLinked($linked, 'link', $raw);
break;
case 'work':
case 'student_publication':
$addLinked($linked, 'student_publication', $raw);
break;
case 'survey':
$addLinked($linked, 'survey', $raw);
break;
case 'forum':
$addLinked($linked, 'forum', $raw);
break;
}
}
// Convert linked sets to lists.
foreach ($linked as $k => $set) {
$linked[$k] = array_values(array_map('intval', array_keys($set)));
}
// Stable items ordering for export (level, then display_order, then id).
$items = array_values($rawItemsById);
usort($items, static function (array $a, array $b): int {
$la = (int) ($a['level'] ?? 0);
$lb = (int) ($b['level'] ?? 0);
if ($la !== $lb) {
return $la <=> $lb;
}
$oa = (int) ($a['display_order'] ?? 0);
$ob = (int) ($b['display_order'] ?? 0);
if ($oa !== $ob) {
return $oa <=> $ob;
}
return ((int) ($a['id'] ?? 0)) <=> ((int) ($b['id'] ?? 0));
});
$payload = [
'id' => $iid,
'lp_type' => $lpType,
'title' => (string) $lp->getTitle(),
'path' => (string) $lp->getPath(),
'ref' => (string) ($lp->getRef() ?? ''),
'description' => (string) ($lp->getDescription() ?? ''),
'content_local' => (string) $lp->getContentLocal(),
'default_encoding' => (string) $lp->getDefaultEncoding(),
'default_view_mod' => (string) $lp->getDefaultViewMod(),
'prevent_reinit' => (bool) $lp->getPreventReinit(),
'force_commit' => (bool) $lp->getForceCommit(),
'content_maker' => (string) $lp->getContentMaker(),
'js_lib' => (string) $lp->getJsLib(),
'content_license' => (string) $lp->getContentLicense(),
'debug' => (bool) $lp->getDebug(),
'theme' => (string) $lp->getTheme(),
'author' => (string) $lp->getAuthor(),
'prerequisite' => (int) $lp->getPrerequisite(),
'hide_toc_frame' => method_exists($lp, 'getHideTocFrame') ? (bool) $lp->getHideTocFrame() : null,
'seriousgame_mode' => method_exists($lp, 'getSeriousgameMode') ? (bool) $lp->getSeriousgameMode() : null,
'use_max_score' => (int) $lp->getUseMaxScore(),
'autolaunch' => (int) $lp->getAutolaunch(),
'max_attempts' => method_exists($lp, 'getMaxAttempts') ? (int) $lp->getMaxAttempts() : null,
'subscribe_users' => (int) $lp->getSubscribeUsers(),
'accumulate_scorm_time' => (int) $lp->getAccumulateScormTime(),
'accumulate_work_time' => (int) $lp->getAccumulateWorkTime(),
'next_lp_id' => (int) $lp->getNextLpId(),
'subscribe_user_by_date' => (bool) $lp->getSubscribeUserByDate(),
'display_not_allowed_lp' => (bool) $lp->getDisplayNotAllowedLp(),
'duration' => method_exists($lp, 'getDuration') ? $lp->getDuration() : null,
'auto_forward_video' => method_exists($lp, 'getAutoForwardVideo') ? (bool) $lp->getAutoForwardVideo() : null,
'created_on' => $this->fmtDate($lp->getCreatedOn()),
'modified_on' => $this->fmtDate($lp->getModifiedOn()),
'published_on' => $this->fmtDate($lp->getPublishedOn()),
'expired_on' => $this->fmtDate($lp->getExpiredOn()),
'session_id' => (int) ($sessionEntity?->getId() ?? 0),
'category_id' => (int) ($lp->getCategory()?->getIid() ?? 0),
'linked_resources' => $linked,
'items' => $items,
];
$legacyCourse->resources[RESOURCE_LEARNPATH][$iid] =
$this->mkLegacyItem(RESOURCE_LEARNPATH, $iid, $payload, ['items', 'linked_resources']);
}
// Optional: pack “scorm” folder (legacy parity)
if ($addScormFolder && isset($this->course->backup_path)) {
$scormDir = rtrim((string) $this->course->backup_path, '/').'/scorm';
if (is_dir($scormDir) && ($dh = @opendir($scormDir))) {
$i = 1;
while (false !== ($file = readdir($dh))) {
if ('.' === $file || '..' === $file) {
continue;
}
if (is_dir($scormDir.'/'.$file)) {
$payload = [
'path' => '/'.$file,
'name' => (string) $file,
'source_lp_id' => (int) ($scormLpByDir[$file] ?? 0),
];
$legacyCourse->resources[RESOURCE_SCORM][$i] =
$this->mkLegacyItem(RESOURCE_SCORM, $i, $payload);
$i++;
}
}
closedir($dh);
}
}
}
/**
* Export Gradebook (categories + evaluations + links).
*/
public function build_gradebook(
object $legacyCourse,
?CourseEntity $courseEntity,
?SessionEntity $sessionEntity
): void {
if (!$courseEntity instanceof CourseEntity) {
return;
}
/** @var EntityManagerInterface $em */
$em = Database::getManager();
$catRepo = $em->getRepository(GradebookCategory::class);
$qb = $catRepo->createQueryBuilder('cat')
->andWhere('cat.course = :course')
->setParameter('course', $courseEntity);
if ($sessionEntity instanceof SessionEntity) {
if ($this->withBaseContent) {
// Include base categories (session IS NULL) + session categories
$qb->andWhere(
$qb->expr()->orX(
'cat.session = :session',
'cat.session IS NULL'
)
)->setParameter('session', $sessionEntity);
} else {
// Only session-specific categories
$qb->andWhere('cat.session = :session')
->setParameter('session', $sessionEntity);
}
} else {
// No session context => base only
$qb->andWhere('cat.session IS NULL');
}
$qb->addOrderBy('cat.id', 'ASC');