Passed
Push — 1.11.x ( e3bf50...fea804 )
by Julito
15:27
created

CourseBuilder::get_course()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CourseBundle\Component\CourseCopy;
5
6
use Category;
7
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Announcement;
8
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Asset;
9
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Attendance;
10
use Chamilo\CourseBundle\Component\CourseCopy\Resources\CalendarEvent;
11
use Chamilo\CourseBundle\Component\CourseCopy\Resources\CourseCopyLearnpath;
12
use Chamilo\CourseBundle\Component\CourseCopy\Resources\CourseCopyTestCategory;
13
use Chamilo\CourseBundle\Component\CourseCopy\Resources\CourseDescription;
14
use Chamilo\CourseBundle\Component\CourseCopy\Resources\CourseSession;
15
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Document;
16
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Forum;
17
use Chamilo\CourseBundle\Component\CourseCopy\Resources\ForumCategory;
18
use Chamilo\CourseBundle\Component\CourseCopy\Resources\ForumPost;
19
use Chamilo\CourseBundle\Component\CourseCopy\Resources\ForumTopic;
20
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Glossary;
21
use Chamilo\CourseBundle\Component\CourseCopy\Resources\GradeBookBackup;
22
use Chamilo\CourseBundle\Component\CourseCopy\Resources\LearnPathCategory;
23
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Link;
24
use Chamilo\CourseBundle\Component\CourseCopy\Resources\LinkCategory;
25
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Quiz;
26
use Chamilo\CourseBundle\Component\CourseCopy\Resources\QuizQuestion;
27
use Chamilo\CourseBundle\Component\CourseCopy\Resources\QuizQuestionOption;
28
use Chamilo\CourseBundle\Component\CourseCopy\Resources\ScormDocument;
29
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Survey;
30
use Chamilo\CourseBundle\Component\CourseCopy\Resources\SurveyQuestion;
31
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Thematic;
32
use Chamilo\CourseBundle\Component\CourseCopy\Resources\ToolIntro;
33
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Wiki;
34
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Work;
35
use Chamilo\CourseBundle\Entity\CLpCategory;
36
use CourseManager;
37
use Database;
38
use Link as LinkManager;
39
use TestCategory;
40
41
/**
42
 * Class CourseBuilder
43
 * Builds a course-object from a Chamilo-course.
44
 *
45
 * @author Bart Mollet <[email protected]>
46
 *
47
 * @package chamilo.backup
48
 */
49
class CourseBuilder
50
{
51
    /** @var Course */
52
    public $course;
53
54
    /* With this array you can filter the tools you want to be parsed by
55
    default all tools are included */
56
    public $tools_to_build = [
57
        'announcements',
58
        'attendance',
59
        'course_descriptions',
60
        'documents',
61
        'events',
62
        'forum_category',
63
        'forums',
64
        'forum_topics',
65
        'glossary',
66
        'quizzes',
67
        'test_category',
68
        'learnpath_category',
69
        'learnpaths',
70
        'links',
71
        'surveys',
72
        'tool_intro',
73
        'thematic',
74
        'wiki',
75
        'works',
76
        'gradebook',
77
    ];
78
79
    public $toolToName = [
80
        'announcements' => RESOURCE_ANNOUNCEMENT,
81
        'attendance' => RESOURCE_ATTENDANCE,
82
        'course_descriptions' => RESOURCE_COURSEDESCRIPTION,
83
        'documents' => RESOURCE_DOCUMENT,
84
        'events' => RESOURCE_EVENT,
85
        'forum_category' => RESOURCE_FORUMCATEGORY,
86
        'forums' => RESOURCE_FORUM,
87
        'forum_topics' => RESOURCE_FORUMTOPIC,
88
        'glossary' => RESOURCE_GLOSSARY,
89
        'quizzes' => RESOURCE_QUIZ,
90
        'test_category' => RESOURCE_TEST_CATEGORY,
91
        'learnpath_category' => RESOURCE_LEARNPATH_CATEGORY,
92
        'learnpaths' => RESOURCE_LEARNPATH,
93
        'links' => RESOURCE_LINK,
94
        'surveys' => RESOURCE_SURVEY,
95
        'tool_intro' => RESOURCE_TOOL_INTRO,
96
        'thematic' => RESOURCE_THEMATIC,
97
        'wiki' => RESOURCE_WIKI,
98
        'works' => RESOURCE_WORK,
99
        'gradebook' => RESOURCE_GRADEBOOK,
100
    ];
101
102
    /* With this array you can filter wich elements of the tools are going
103
    to be added in the course obj (only works with LPs) */
104
    public $specific_id_list = [];
105
    public $documentsAddedInText = [];
106
107
    /**
108
     * Create a new CourseBuilder.
109
     *
110
     * @param string $type
111
     * @param null   $course
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $course is correct as it would always require null to be passed?
Loading history...
112
     */
113
    public function __construct($type = '', $course = null)
114
    {
115
        $_course = api_get_course_info();
116
117
        if (!empty($course['official_code'])) {
118
            $_course = $course;
119
        }
120
121
        $this->course = new Course();
122
        $this->course->code = $_course['code'];
123
        $this->course->type = $type;
0 ignored issues
show
Bug introduced by
The property type does not seem to exist on Chamilo\CourseBundle\Component\CourseCopy\Course.
Loading history...
124
        $this->course->path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/';
125
        $this->course->backup_path = api_get_path(SYS_COURSE_PATH).$_course['path'];
126
        $this->course->encoding = api_get_system_encoding();
127
        $this->course->info = $_course;
0 ignored issues
show
Bug introduced by
The property info does not seem to exist on Chamilo\CourseBundle\Component\CourseCopy\Course.
Loading history...
128
    }
129
130
    /**
131
     * @param array $list
132
     */
133
    public function addDocumentList($list)
134
    {
135
        foreach ($list as $item) {
136
            if (!in_array($item[0], $this->documentsAddedInText)) {
137
                $this->documentsAddedInText[$item[0]] = $item;
138
            }
139
        }
140
    }
141
142
    /**
143
     * @param string $text
144
     */
145
    public function findAndSetDocumentsInText($text)
146
    {
147
        $documentList = \DocumentManager::get_resources_from_source_html($text);
148
        $this->addDocumentList($documentList);
149
    }
150
151
    /**
152
     * Parse documents added in the documentsAddedInText variable.
153
     */
154
    public function restoreDocumentsFromList()
155
    {
156
        if (!empty($this->documentsAddedInText)) {
157
            $list = [];
158
            $courseInfo = api_get_course_info();
159
            foreach ($this->documentsAddedInText as $item) {
160
                // Get information about source url
161
                $url = $item[0]; // url
162
                $scope = $item[1]; // scope (local, remote)
163
                $type = $item[2]; // type (rel, abs, url)
164
165
                $origParseUrl = parse_url($url);
166
                $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
167
168
                if ($scope == 'local') {
169
                    if ($type == 'abs' || $type == 'rel') {
170
                        $documentFile = strstr($realOrigPath, 'document');
171
                        if (strpos($realOrigPath, $documentFile) !== false) {
172
                            $documentFile = str_replace('document', '', $documentFile);
173
                            $itemDocumentId = \DocumentManager::get_document_id($courseInfo, $documentFile);
174
                            // Document found! Add it to the list
175
                            if ($itemDocumentId) {
176
                                $list[] = $itemDocumentId;
177
                            }
178
                        }
179
                    }
180
                }
181
            }
182
183
            $this->build_documents(
184
                api_get_session_id(),
185
                api_get_course_int_id(),
186
                true,
187
                $list
188
            );
189
        }
190
    }
191
192
    /**
193
     * @param array $array
194
     */
195
    public function set_tools_to_build($array)
196
    {
197
        $this->tools_to_build = $array;
198
    }
199
200
    /**
201
     * @param array $array
202
     */
203
    public function set_tools_specific_id_list($array)
204
    {
205
        $this->specific_id_list = $array;
206
    }
207
208
    /**
209
     * Get the created course.
210
     *
211
     * @return course The course
212
     */
213
    public function get_course()
214
    {
215
        return $this->course;
216
    }
217
218
    /**
219
     * Build the course-object.
220
     *
221
     * @param int    $session_id
222
     * @param string $courseCode
223
     * @param bool   $withBaseContent   true if you want to get the elements that exists in the course and
224
     *                                  in the session, (session_id = 0 or session_id = X)
225
     * @param array  $parseOnlyToolList
226
     * @param array  $toolsFromPost
227
     *
228
     * @return Course The course object structure
229
     */
230
    public function build(
231
        $session_id = 0,
232
        $courseCode = '',
233
        $withBaseContent = false,
234
        $parseOnlyToolList = [],
235
        $toolsFromPost = []
236
    ) {
237
        $course = api_get_course_info($courseCode);
238
        $courseId = $course['real_id'];
239
        foreach ($this->tools_to_build as $tool) {
240
            if (!empty($parseOnlyToolList) && !in_array($this->toolToName[$tool], $parseOnlyToolList)) {
241
                continue;
242
            }
243
            $function_build = 'build_'.$tool;
244
            $specificIdList = isset($this->specific_id_list[$tool]) ? $this->specific_id_list[$tool] : null;
245
            $buildOrphanQuestions = true;
246
            if ($tool === 'quizzes') {
247
                if (!isset($toolsFromPost[RESOURCE_QUIZ][-1])) {
248
                    $buildOrphanQuestions = false;
249
                }
250
251
                // Force orphan load
252
                if ($this->course->type === 'complete') {
0 ignored issues
show
Bug introduced by
The property type does not seem to exist on Chamilo\CourseBundle\Component\CourseCopy\Course.
Loading history...
253
                    $buildOrphanQuestions = true;
254
                }
255
256
                $this->build_quizzes(
257
                    $session_id,
258
                    $courseId,
259
                    $withBaseContent,
260
                    $specificIdList,
261
                    $buildOrphanQuestions
262
                );
263
            } else {
264
                $this->$function_build(
265
                    $session_id,
266
                    $courseId,
267
                    $withBaseContent,
268
                    $specificIdList
269
                );
270
            }
271
        }
272
273
        // Add asset
274
        if ($course['course_image_source'] && basename($course['course_image_source']) !== 'course.png') {
275
            // Add course image courses/XXX/course-pic85x85.png
276
            $asset = new Asset(
277
                $course['course_image_source'],
278
                basename($course['course_image_source']),
279
                basename($course['course_image_source'])
280
            );
281
            $this->course->add_resource($asset);
282
283
            $asset = new Asset(
284
                $course['course_image_large_source'],
285
                basename($course['course_image_large_source']),
286
                basename($course['course_image_large_source'])
287
            );
288
            $this->course->add_resource($asset);
289
        }
290
291
        // Once we've built the resources array a bit more, try to get items
292
        // from the item_property table and order them in the "resources" array
293
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
294
        foreach ($this->course->resources as $type => $resources) {
295
            if (!empty($parseOnlyToolList) && !in_array($this->toolToName[$tool], $parseOnlyToolList)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $tool does not seem to be defined for all execution paths leading up to this point.
Loading history...
296
                continue;
297
            }
298
            foreach ($resources as $id => $resource) {
299
                if ($resource) {
300
                    $tool = $resource->get_tool();
301
                    if ($tool != null) {
302
                        $sql = "SELECT * FROM $table
303
                                WHERE
304
                                    c_id = $courseId AND
305
                                    tool = '".$tool."' AND
306
                                    ref = '".$resource->get_id()."'";
307
                        $res = Database::query($sql);
308
                        $properties = [];
309
                        while ($property = Database::fetch_array($res)) {
310
                            $properties[] = $property;
311
                        }
312
                        $this->course->resources[$type][$id]->item_properties = $properties;
313
                    }
314
                }
315
            }
316
        }
317
318
        return $this->course;
319
    }
320
321
    /**
322
     * Build the documents.
323
     *
324
     * @param int   $session_id
325
     * @param int   $courseId
326
     * @param bool  $withBaseContent
327
     * @param array $idList
328
     */
329
    public function build_documents(
330
        $session_id = 0,
331
        $courseId = 0,
332
        $withBaseContent = false,
333
        $idList = []
334
    ) {
335
        $table_doc = Database::get_course_table(TABLE_DOCUMENT);
336
        $table_prop = Database::get_course_table(TABLE_ITEM_PROPERTY);
337
338
        // Remove chat_files, shared_folder, exercises files
339
        $avoid_paths = "
340
                         path NOT LIKE '/shared_folder%' AND
341
                         path NOT LIKE '/chat_files%' AND
342
                         path NOT LIKE '/../exercises/%'
343
                         ";
344
        $documentCondition = '';
345
        if (!empty($idList)) {
346
            $idList = array_unique($idList);
347
            $idList = array_map('intval', $idList);
348
            $documentCondition = ' d.iid IN ("'.implode('","', $idList).'") AND ';
349
        }
350
351
        if (!empty($courseId) && !empty($session_id)) {
352
            $session_id = (int) $session_id;
353
            if ($withBaseContent) {
354
                $session_condition = api_get_session_condition(
355
                    $session_id,
356
                    true,
357
                    true,
358
                    'd.session_id'
359
                );
360
            } else {
361
                $session_condition = api_get_session_condition(
362
                    $session_id,
363
                    true,
364
                    false,
365
                    'd.session_id'
366
                );
367
            }
368
369
            if (!empty($this->course->type) && $this->course->type == 'partial') {
0 ignored issues
show
Bug introduced by
The property type does not seem to exist on Chamilo\CourseBundle\Component\CourseCopy\Course.
Loading history...
370
                $sql = "SELECT d.iid, d.path, d.comment, d.title, d.filetype, d.size
371
                        FROM $table_doc d
372
                        INNER JOIN $table_prop p
373
                        ON (p.ref = d.id AND d.c_id = p.c_id)
374
                        WHERE
375
                            d.c_id = $courseId AND
376
                            p.c_id = $courseId AND
377
                            tool = '".TOOL_DOCUMENT."' AND
378
                            $documentCondition
379
                            p.visibility != 2 AND
380
                            path NOT LIKE '/images/gallery%' AND
381
                            $avoid_paths
382
                            $session_condition
383
                        ORDER BY path";
384
            } else {
385
                $sql = "SELECT d.iid, d.path, d.comment, d.title, d.filetype, d.size
386
                        FROM $table_doc d
387
                        INNER JOIN $table_prop p
388
                        ON (p.ref = d.id AND d.c_id = p.c_id)
389
                        WHERE
390
                            d.c_id = $courseId AND
391
                            p.c_id = $courseId AND
392
                            tool = '".TOOL_DOCUMENT."' AND
393
                            $documentCondition
394
                            $avoid_paths AND
395
                            p.visibility != 2 $session_condition
396
                        ORDER BY path";
397
            }
398
399
            $db_result = Database::query($sql);
400
            while ($obj = Database::fetch_object($db_result)) {
401
                $doc = new Document(
402
                    $obj->iid,
403
                    $obj->path,
404
                    $obj->comment,
405
                    $obj->title,
406
                    $obj->filetype,
407
                    $obj->size
408
                );
409
                $this->course->add_resource($doc);
410
            }
411
        } else {
412
            if (!empty($this->course->type) && $this->course->type == 'partial') {
413
                $sql = "SELECT d.iid, d.path, d.comment, d.title, d.filetype, d.size
414
                        FROM $table_doc d
415
                        INNER JOIN $table_prop p
416
                        ON (p.ref = d.id AND d.c_id = p.c_id)
417
                        WHERE
418
                            d.c_id = $courseId AND
419
                            p.c_id = $courseId AND
420
                            tool = '".TOOL_DOCUMENT."' AND
421
                            $documentCondition
422
                            p.visibility != 2 AND
423
                            path NOT LIKE '/images/gallery%' AND
424
                            $avoid_paths AND
425
                            (d.session_id = 0 OR d.session_id IS NULL)
426
                        ORDER BY path";
427
            } else {
428
                $sql = "SELECT d.iid, d.path, d.comment, d.title, d.filetype, d.size
429
                        FROM $table_doc d
430
                        INNER JOIN $table_prop p
431
                        ON (p.ref = d.id AND d.c_id = p.c_id)
432
                        WHERE
433
                            d.c_id = $courseId AND
434
                            p.c_id = $courseId AND
435
                            tool = '".TOOL_DOCUMENT."' AND
436
                            $documentCondition
437
                            p.visibility != 2 AND
438
                            $avoid_paths AND
439
                            (d.session_id = 0 OR d.session_id IS NULL)
440
                        ORDER BY path";
441
            }
442
443
            $result = Database::query($sql);
444
            while ($obj = Database::fetch_object($result)) {
445
                $doc = new Document(
446
                    $obj->iid,
447
                    $obj->path,
448
                    $obj->comment,
449
                    $obj->title,
450
                    $obj->filetype,
451
                    $obj->size
452
                );
453
                $this->course->add_resource($doc);
454
            }
455
        }
456
    }
457
458
    /**
459
     * Build the forums.
460
     *
461
     * @param int   $session_id      Internal session ID
462
     * @param int   $courseId        Internal course ID
463
     * @param bool  $withBaseContent Whether to include content from the course without session or not
464
     * @param array $idList          If you want to restrict the structure to only the given IDs
465
     */
466
    public function build_forums(
467
        $session_id = 0,
468
        $courseId = 0,
469
        $withBaseContent = false,
470
        $idList = []
471
    ) {
472
        $table = Database::get_course_table(TABLE_FORUM);
473
        $sessionCondition = api_get_session_condition(
474
            $session_id,
475
            true,
476
            $withBaseContent
477
        );
478
479
        $idCondition = '';
480
        if (!empty($idList)) {
481
            $idList = array_unique($idList);
482
            $idList = array_map('intval', $idList);
483
            $idCondition = ' AND iid IN ("'.implode('","', $idList).'") ';
484
        }
485
486
        $sql = "SELECT * FROM $table WHERE c_id = $courseId $sessionCondition $idCondition";
487
        $sql .= " ORDER BY forum_title, forum_category";
488
        $db_result = Database::query($sql);
489
        while ($obj = Database::fetch_object($db_result)) {
490
            $forum = new Forum($obj);
491
            $this->course->add_resource($forum);
492
        }
493
    }
494
495
    /**
496
     * Build a forum-category.
497
     *
498
     * @param int   $session_id      Internal session ID
499
     * @param int   $courseId        Internal course ID
500
     * @param bool  $withBaseContent Whether to include content from the course without session or not
501
     * @param array $idList          If you want to restrict the structure to only the given IDs
502
     */
503
    public function build_forum_category(
504
        $session_id = 0,
505
        $courseId = 0,
506
        $withBaseContent = false,
507
        $idList = []
508
    ) {
509
        $table = Database::get_course_table(TABLE_FORUM_CATEGORY);
510
511
        $sessionCondition = api_get_session_condition(
512
            $session_id,
513
            true,
514
            $withBaseContent
515
        );
516
517
        $idCondition = '';
518
        if (!empty($idList)) {
519
            $idList = array_unique($idList);
520
            $idList = array_map('intval', $idList);
521
            $idCondition = ' AND iid IN ("'.implode('","', $idList).'") ';
522
        }
523
524
        $sql = "SELECT * FROM $table
525
                WHERE c_id = $courseId $sessionCondition $idCondition
526
                ORDER BY cat_title";
527
528
        $result = Database::query($sql);
529
        while ($obj = Database::fetch_object($result)) {
530
            $forumCategory = new ForumCategory($obj);
531
            $this->course->add_resource($forumCategory);
532
        }
533
    }
534
535
    /**
536
     * Build the forum-topics.
537
     *
538
     * @param int   $session_id      Internal session ID
539
     * @param int   $courseId        Internal course ID
540
     * @param bool  $withBaseContent Whether to include content from the course without session or not
541
     * @param array $idList          If you want to restrict the structure to only the given IDs
542
     */
543
    public function build_forum_topics(
544
        $session_id = 0,
545
        $courseId = 0,
546
        $withBaseContent = false,
547
        $idList = []
548
    ) {
549
        $table = Database::get_course_table(TABLE_FORUM_THREAD);
550
551
        $sessionCondition = api_get_session_condition(
552
            $session_id,
553
            true,
554
            $withBaseContent
555
        );
556
557
        $idCondition = '';
558
        if (!empty($idList)) {
559
            $idList = array_map('intval', $idList);
560
            $idCondition = ' AND iid IN ("'.implode('","', $idList).'") ';
561
        }
562
563
        $sql = "SELECT * FROM $table WHERE c_id = $courseId
564
                $sessionCondition
565
                $idCondition
566
                ORDER BY thread_title ";
567
        $result = Database::query($sql);
568
569
        while ($obj = Database::fetch_object($result)) {
570
            $forumTopic = new ForumTopic($obj);
571
            $this->course->add_resource($forumTopic);
572
            $this->build_forum_posts($courseId, $obj->thread_id, $obj->forum_id);
573
        }
574
    }
575
576
    /**
577
     * Build the forum-posts
578
     * TODO: All tree structure of posts should be built, attachments for example.
579
     *
580
     * @param int   $courseId  Internal course ID
581
     * @param int   $thread_id Internal thread ID
582
     * @param int   $forum_id  Internal forum ID
583
     * @param array $idList
584
     */
585
    public function build_forum_posts(
586
        $courseId = 0,
587
        $thread_id = null,
588
        $forum_id = null,
589
        $idList = []
590
    ) {
591
        $table = Database::get_course_table(TABLE_FORUM_POST);
592
        $courseId = (int) $courseId;
593
        $sql = "SELECT * FROM $table WHERE c_id = $courseId ";
594
        if (!empty($thread_id) && !empty($forum_id)) {
595
            $forum_id = intval($forum_id);
596
            $thread_id = intval($thread_id);
597
            $sql .= " AND thread_id = $thread_id AND forum_id = $forum_id ";
598
        }
599
600
        if (!empty($idList)) {
601
            $idList = array_map('intval', $idList);
602
            $sql .= ' AND iid IN ("'.implode('","', $idList).'") ';
603
        }
604
605
        $sql .= " ORDER BY post_id ASC LIMIT 1";
606
        $db_result = Database::query($sql);
607
        while ($obj = Database::fetch_object($db_result)) {
608
            $forum_post = new ForumPost($obj);
609
            $this->course->add_resource($forum_post);
610
        }
611
    }
612
613
    /**
614
     * Build the links.
615
     *
616
     * @param int   $session_id      Internal session ID
617
     * @param int   $courseId        Internal course ID
618
     * @param bool  $withBaseContent Whether to include content from the course without session or not
619
     * @param array $idList          If you want to restrict the structure to only the given IDs
620
     */
621
    public function build_links(
622
        $session_id = 0,
623
        $courseId = 0,
624
        $withBaseContent = false,
625
        $idList = []
626
    ) {
627
        $categories = LinkManager::getLinkCategories(
628
            $courseId,
629
            $session_id,
630
            $withBaseContent
631
        );
632
633
        // Adding empty category
634
        $categories[] = ['id' => 0];
635
636
        foreach ($categories as $category) {
637
            $this->build_link_category($category);
638
639
            $links = LinkManager::getLinksPerCategory(
640
                $category['id'],
641
                $courseId,
642
                $session_id,
643
                $withBaseContent
644
            );
645
646
            foreach ($links as $item) {
647
                if (!empty($idList)) {
648
                    if (!in_array($item['id'], $idList)) {
649
                        continue;
650
                    }
651
                }
652
653
                $link = new Link(
654
                    $item['id'],
655
                    $item['title'],
656
                    $item['url'],
657
                    $item['description'],
658
                    $item['category_id'],
659
                    $item['on_homepage']
660
                );
661
                $link->target = $item['target'];
662
                $this->course->add_resource($link);
663
                $this->course->resources[RESOURCE_LINK][$item['id']]->add_linked_resource(
664
                    RESOURCE_LINKCATEGORY,
665
                    $item['category_id']
666
                );
667
            }
668
        }
669
    }
670
671
    /**
672
     * Build tool intro.
673
     *
674
     * @param int   $session_id      Internal session ID
675
     * @param int   $courseId        Internal course ID
676
     * @param bool  $withBaseContent Whether to include content from the course without session or not
677
     * @param array $idList          If you want to restrict the structure to only the given IDs
678
     */
679
    public function build_tool_intro(
680
        $session_id = 0,
681
        $courseId = 0,
682
        $withBaseContent = false,
683
        $idList = []
684
    ) {
685
        $table = Database::get_course_table(TABLE_TOOL_INTRO);
686
687
        $sessionCondition = api_get_session_condition(
688
            $session_id,
689
            true,
690
            $withBaseContent
691
        );
692
693
        $courseId = (int) $courseId;
694
695
        $sql = "SELECT * FROM $table
696
                WHERE c_id = $courseId $sessionCondition";
697
698
        $db_result = Database::query($sql);
699
        while ($obj = Database::fetch_object($db_result)) {
700
            $tool_intro = new ToolIntro($obj->id, $obj->intro_text);
701
            $this->course->add_resource($tool_intro);
702
        }
703
    }
704
705
    /**
706
     * Build a link category.
707
     *
708
     * @return int
709
     */
710
    public function build_link_category($category)
711
    {
712
        if (empty($category) || empty($category['category_title'])) {
713
            return 0;
714
        }
715
716
        $linkCategory = new LinkCategory(
717
            $category['id'],
718
            $category['category_title'],
719
            $category['description'],
720
            $category['display_order']
721
        );
722
        $this->course->add_resource($linkCategory);
723
724
        return $category['id'];
725
    }
726
727
    /**
728
     * Build the Quizzes.
729
     *
730
     * @param int   $session_id           Internal session ID
731
     * @param int   $courseId             Internal course ID
732
     * @param bool  $withBaseContent      Whether to include content from the course without session or not
733
     * @param array $idList               If you want to restrict the structure to only the given IDs
734
     * @param bool  $buildOrphanQuestions
735
     */
736
    public function build_quizzes(
737
        $session_id = 0,
738
        $courseId = 0,
739
        $withBaseContent = false,
740
        $idList = [],
741
        $buildOrphanQuestions = true
742
    ) {
743
        $table_qui = Database::get_course_table(TABLE_QUIZ_TEST);
744
        $table_rel = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
745
        $table_doc = Database::get_course_table(TABLE_DOCUMENT);
746
747
        $courseId = (int) $courseId;
748
        $idCondition = '';
749
        if (!empty($idList)) {
750
            $idList = array_map('intval', $idList);
751
            $idCondition = ' iid IN ("'.implode('","', $idList).'") AND ';
752
        }
753
754
        if (!empty($courseId) && !empty($session_id)) {
755
            $session_id = (int) $session_id;
756
            if ($withBaseContent) {
757
                $sessionCondition = api_get_session_condition(
758
                    $session_id,
759
                    true,
760
                    true
761
                );
762
            } else {
763
                $sessionCondition = api_get_session_condition(
764
                    $session_id,
765
                    true
766
                );
767
            }
768
769
            // Select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
770
            $sql = "SELECT * FROM $table_qui
771
                    WHERE
772
                      c_id = $courseId AND
773
                      $idCondition
774
                      active >=0
775
                      $sessionCondition ";
776
        } else {
777
            // Select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
778
            $sql = "SELECT * FROM $table_qui
779
                    WHERE
780
                      c_id = $courseId AND
781
                      $idCondition
782
                      active >=0 AND
783
                      (session_id = 0 OR session_id IS NULL)";
784
        }
785
786
        $sql .= ' ORDER BY title';
787
        $db_result = Database::query($sql);
788
        $questionList = [];
789
        while ($obj = Database::fetch_object($db_result)) {
790
            if (strlen($obj->sound) > 0) {
791
                $sql = "SELECT id FROM $table_doc
792
                        WHERE c_id = $courseId AND path = '/audio/".$obj->sound."'";
793
                $res = Database::query($sql);
794
                $doc = Database::fetch_object($res);
795
                $obj->sound = $doc->id;
796
            }
797
            $this->findAndSetDocumentsInText($obj->description);
798
799
            $quiz = new Quiz($obj);
800
            $sql = 'SELECT * FROM '.$table_rel.'
801
                    WHERE c_id = '.$courseId.' AND exercice_id = '.$obj->id;
802
            $db_result2 = Database::query($sql);
803
            while ($obj2 = Database::fetch_object($db_result2)) {
804
                $quiz->add_question($obj2->question_id, $obj2->question_order);
805
                $questionList[] = $obj2->question_id;
806
            }
807
            $this->course->add_resource($quiz);
808
        }
809
810
        if (!empty($courseId)) {
811
            $this->build_quiz_questions($courseId, $questionList, $buildOrphanQuestions);
812
        } else {
813
            $this->build_quiz_questions(0, $questionList, $buildOrphanQuestions);
814
        }
815
    }
816
817
    /**
818
     * Build the Quiz-Questions.
819
     *
820
     * @param int   $courseId             Internal course ID
821
     * @param array $questionList
822
     * @param bool  $buildOrphanQuestions
823
     */
824
    public function build_quiz_questions($courseId = 0, $questionList = [], $buildOrphanQuestions = true)
825
    {
826
        $table_qui = Database::get_course_table(TABLE_QUIZ_TEST);
827
        $table_rel = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
828
        $table_que = Database::get_course_table(TABLE_QUIZ_QUESTION);
829
        $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
830
        $courseId = (int) $courseId;
831
        $questionListToString = implode("','", $questionList);
832
833
        // Building normal tests (many queries)
834
        $sql = "SELECT * FROM $table_que
835
                WHERE c_id = $courseId AND id IN ('$questionListToString')";
836
        $result = Database::query($sql);
837
838
        while ($obj = Database::fetch_object($result)) {
839
            // find the question category
840
            // @todo : need to be adapted for multi category questions in 1.10
841
            $question_category_id = TestCategory::getCategoryForQuestion(
842
                $obj->id,
843
                $courseId
844
            );
845
846
            $this->findAndSetDocumentsInText($obj->description);
847
848
            // build the backup resource question object
849
            $question = new QuizQuestion(
850
                $obj->id,
851
                $obj->question,
852
                $obj->description,
853
                $obj->ponderation,
854
                $obj->type,
855
                $obj->position,
856
                $obj->picture,
857
                $obj->level,
858
                $obj->extra,
859
                $question_category_id
860
            );
861
            $question->addPicture($this);
862
863
            $sql = 'SELECT * FROM '.$table_ans.'
864
                    WHERE c_id = '.$courseId.' AND question_id = '.$obj->id;
865
            $db_result2 = Database::query($sql);
866
            while ($obj2 = Database::fetch_object($db_result2)) {
867
                $question->add_answer(
868
                    $obj2->id,
869
                    $obj2->answer,
870
                    $obj2->correct,
871
                    $obj2->comment,
872
                    $obj2->ponderation,
873
                    $obj2->position,
874
                    $obj2->hotspot_coordinates,
875
                    $obj2->hotspot_type
876
                );
877
878
                $this->findAndSetDocumentsInText($obj2->answer);
879
                $this->findAndSetDocumentsInText($obj2->comment);
880
881
                if ($obj->type == MULTIPLE_ANSWER_TRUE_FALSE) {
882
                    $table_options = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
883
                    $sql = 'SELECT * FROM '.$table_options.'
884
                            WHERE c_id = '.$courseId.' AND question_id = '.$obj->id;
885
                    $db_result3 = Database::query($sql);
886
                    while ($obj3 = Database::fetch_object($db_result3)) {
887
                        $question_option = new QuizQuestionOption($obj3);
888
                        $question->add_option($question_option);
889
                    }
890
                }
891
            }
892
            $this->course->add_resource($question);
893
        }
894
895
        if ($buildOrphanQuestions) {
896
            // Building a fictional test for collecting orphan questions.
897
            // When a course is emptied this option should be activated (true).
898
            //$build_orphan_questions = !empty($_POST['recycle_option']);
899
900
            // 1st union gets the orphan questions from deleted exercises
901
            // 2nd union gets the orphan questions from question that were deleted in a exercise.
902
            $sql = " (
903
                        SELECT question_id, q.* FROM $table_que q
904
                        INNER JOIN $table_rel r
905
                        ON (q.c_id = r.c_id AND q.id = r.question_id)
906
                        INNER JOIN $table_qui ex
907
                        ON (ex.id = r.exercice_id AND ex.c_id = r.c_id)
908
                        WHERE ex.c_id = $courseId AND ex.active = '-1'
909
                    )
910
                    UNION
911
                     (
912
                        SELECT question_id, q.* FROM $table_que q
913
                        left OUTER JOIN $table_rel r
914
                        ON (q.c_id = r.c_id AND q.id = r.question_id)
915
                        WHERE q.c_id = $courseId AND r.question_id is null
916
                     )
917
                     UNION
918
                     (
919
                        SELECT question_id, q.* FROM $table_que q
920
                        INNER JOIN $table_rel r
921
                        ON (q.c_id = r.c_id AND q.id = r.question_id)
922
                        WHERE r.c_id = $courseId AND (r.exercice_id = '-1' OR r.exercice_id = '0')
923
                     )
924
                 ";
925
926
            $result = Database::query($sql);
927
            if (Database::num_rows($result) > 0) {
928
                $orphanQuestionIds = [];
929
                while ($obj = Database::fetch_object($result)) {
930
                    // Orphan questions
931
                    if (!empty($obj->question_id)) {
932
                        $obj->id = $obj->question_id;
933
                    }
934
935
                    // Avoid adding the same question twice
936
                    if (!isset($this->course->resources[$obj->id])) {
937
                        // find the question category
938
                        // @todo : need to be adapted for multi category questions in 1.10
939
                        $question_category_id = TestCategory::getCategoryForQuestion($obj->id, $courseId);
940
                        $question = new QuizQuestion(
941
                            $obj->id,
942
                            $obj->question,
943
                            $obj->description,
944
                            $obj->ponderation,
945
                            $obj->type,
946
                            $obj->position,
947
                            $obj->picture,
948
                            $obj->level,
949
                            $obj->extra,
950
                            $question_category_id
951
                        );
952
                        $question->addPicture($this);
953
                        $sql = "SELECT * FROM $table_ans
954
                                WHERE c_id = $courseId AND question_id = ".$obj->id;
955
                        $db_result2 = Database::query($sql);
956
                        if (Database::num_rows($db_result2)) {
957
                            while ($obj2 = Database::fetch_object($db_result2)) {
958
                                $question->add_answer(
959
                                    $obj2->id,
960
                                    $obj2->answer,
961
                                    $obj2->correct,
962
                                    $obj2->comment,
963
                                    $obj2->ponderation,
964
                                    $obj2->position,
965
                                    $obj2->hotspot_coordinates,
966
                                    $obj2->hotspot_type
967
                                );
968
                            }
969
                            $orphanQuestionIds[] = $obj->id;
970
                        }
971
                        $this->course->add_resource($question);
972
                    }
973
                }
974
            }
975
        }
976
977
        $obj = [
978
            'id' => -1,
979
            'title' => get_lang('OrphanQuestions'),
980
            'type' => 2,
981
        ];
982
        $newQuiz = new Quiz((object) $obj);
983
        if (!empty($orphanQuestionIds)) {
984
            foreach ($orphanQuestionIds as $index => $orphanId) {
985
                $order = $index + 1;
986
                $newQuiz->add_question($orphanId, $order);
987
            }
988
        }
989
        $this->course->add_resource($newQuiz);
990
    }
991
992
    /**
993
     * @deprecated
994
     * Build the orphan questions
995
     */
996
    public function build_quiz_orphan_questions()
997
    {
998
        $table_qui = Database::get_course_table(TABLE_QUIZ_TEST);
999
        $table_rel = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
1000
        $table_que = Database::get_course_table(TABLE_QUIZ_QUESTION);
1001
        $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
1002
1003
        $courseId = api_get_course_int_id();
1004
1005
        $sql = 'SELECT *
1006
                FROM '.$table_que.' as questions
1007
                LEFT JOIN '.$table_rel.' as quizz_questions
1008
                ON questions.id=quizz_questions.question_id
1009
                LEFT JOIN '.$table_qui.' as exercises
1010
                ON quizz_questions.exercice_id = exercises.id
1011
                WHERE
1012
                    questions.c_id = quizz_questions.c_id AND
1013
                    questions.c_id = exercises.c_id AND
1014
                    exercises.c_id = '.$courseId.' AND
1015
                    (quizz_questions.exercice_id IS NULL OR
1016
                    exercises.active = -1)';
1017
1018
        $db_result = Database::query($sql);
1019
        if (Database::num_rows($db_result) > 0) {
1020
            // This is the fictional test for collecting orphan questions.
1021
            $orphan_questions = new Quiz(
1022
                -1,
1023
                get_lang('OrphanQuestions', ''),
1024
                '',
1025
                0,
1026
                0,
1027
                1,
1028
                '',
1029
                0
1030
            );
1031
1032
            $this->course->add_resource($orphan_questions);
1033
            while ($obj = Database::fetch_object($db_result)) {
1034
                $question = new QuizQuestion(
1035
                    $obj->id,
1036
                    $obj->question,
1037
                    $obj->description,
1038
                    $obj->ponderation,
1039
                    $obj->type,
1040
                    $obj->position,
1041
                    $obj->picture,
1042
                    $obj->level,
1043
                    $obj->extra
1044
                );
1045
                $question->addPicture($this);
1046
1047
                $sql = 'SELECT * FROM '.$table_ans.' WHERE question_id = '.$obj->id;
1048
                $db_result2 = Database::query($sql);
1049
                while ($obj2 = Database::fetch_object($db_result2)) {
1050
                    $question->add_answer(
1051
                        $obj2->id,
1052
                        $obj2->answer,
1053
                        $obj2->correct,
1054
                        $obj2->comment,
1055
                        $obj2->ponderation,
1056
                        $obj2->position,
1057
                        $obj2->hotspot_coordinates,
1058
                        $obj2->hotspot_type
1059
                    );
1060
                }
1061
                $this->course->add_resource($question);
1062
            }
1063
        }
1064
    }
1065
1066
    /**
1067
     * Build the test category.
1068
     *
1069
     * @param int   $sessionId       Internal session ID
1070
     * @param int   $courseId        Internal course ID
1071
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1072
     * @param array $idList          If you want to restrict the structure to only the given IDs
1073
     *
1074
     * @todo add course session
1075
     */
1076
    public function build_test_category(
1077
        $sessionId = 0,
1078
        $courseId = 0,
1079
        $withBaseContent = false,
1080
        $idList = []
1081
    ) {
1082
        // get all test category in course
1083
        $categories = TestCategory::getCategoryListInfo('', $courseId);
1084
        foreach ($categories as $category) {
1085
            $this->findAndSetDocumentsInText($category->description);
1086
1087
            /** @var TestCategory $category */
1088
            $courseCopyTestCategory = new CourseCopyTestCategory(
1089
                $category->id,
1090
                $category->name,
1091
                $category->description
1092
            );
1093
            $this->course->add_resource($courseCopyTestCategory);
1094
        }
1095
    }
1096
1097
    /**
1098
     * Build the Surveys.
1099
     *
1100
     * @param int   $session_id      Internal session ID
1101
     * @param int   $courseId        Internal course ID
1102
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1103
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1104
     */
1105
    public function build_surveys(
1106
        $session_id = 0,
1107
        $courseId = 0,
1108
        $withBaseContent = false,
1109
        $id_list = []
1110
    ) {
1111
        $table_survey = Database::get_course_table(TABLE_SURVEY);
1112
        $table_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
1113
1114
        $courseId = (int) $courseId;
1115
1116
        $sessionCondition = api_get_session_condition(
1117
            $session_id,
1118
            true,
1119
            $withBaseContent
1120
        );
1121
1122
        $sql = 'SELECT * FROM '.$table_survey.'
1123
                WHERE c_id = '.$courseId.' '.$sessionCondition;
1124
        if ($id_list) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id_list of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1125
            $sql .= " AND iid IN (".implode(', ', $id_list).")";
1126
        }
1127
        $db_result = Database::query($sql);
1128
        while ($obj = Database::fetch_object($db_result)) {
1129
            $survey = new Survey(
1130
                $obj->survey_id,
1131
                $obj->code,
1132
                $obj->title,
1133
                $obj->subtitle,
1134
                $obj->author,
1135
                $obj->lang,
1136
                $obj->avail_from,
1137
                $obj->avail_till,
1138
                $obj->is_shared,
1139
                $obj->template,
1140
                $obj->intro,
1141
                $obj->surveythanks,
1142
                $obj->creation_date,
1143
                $obj->invited,
1144
                $obj->answered,
1145
                $obj->invite_mail,
1146
                $obj->reminder_mail,
1147
                $obj->one_question_per_page,
1148
                $obj->shuffle
1149
            );
1150
            $sql = 'SELECT * FROM '.$table_question.'
1151
                    WHERE c_id = '.$courseId.' AND survey_id = '.$obj->survey_id;
1152
            $db_result2 = Database::query($sql);
1153
            while ($obj2 = Database::fetch_object($db_result2)) {
1154
                $survey->add_question($obj2->question_id);
1155
            }
1156
            $this->course->add_resource($survey);
1157
        }
1158
        $this->build_survey_questions($courseId);
1159
    }
1160
1161
    /**
1162
     * Build the Survey Questions.
1163
     *
1164
     * @param int $courseId Internal course ID
1165
     */
1166
    public function build_survey_questions($courseId)
1167
    {
1168
        $table_que = Database::get_course_table(TABLE_SURVEY_QUESTION);
1169
        $table_opt = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1170
1171
        $courseId = (int) $courseId;
1172
        $idList = isset($this->specific_id_list['surveys']) ? $this->specific_id_list['surveys'] : [];
1173
1174
        $sql = 'SELECT * FROM '.$table_que.' WHERE c_id = '.$courseId.'  ';
1175
1176
        if (!empty($idList)) {
1177
            $sql .= " AND survey_id IN (".implode(', ', $idList).")";
1178
        }
1179
1180
        $db_result = Database::query($sql);
1181
        $is_required = 0;
1182
        while ($obj = Database::fetch_object($db_result)) {
1183
            if (api_get_configuration_value('allow_required_survey_questions')) {
1184
                if (isset($obj->is_required)) {
1185
                    $is_required = $obj->is_required;
1186
                }
1187
            }
1188
            $question = new SurveyQuestion(
1189
                $obj->question_id,
1190
                $obj->survey_id,
1191
                $obj->survey_question,
1192
                $obj->survey_question_comment,
1193
                $obj->type,
1194
                $obj->display,
1195
                $obj->sort,
1196
                $obj->shared_question_id,
1197
                $obj->max_value,
1198
                $is_required
1199
            );
1200
            $sql = 'SELECT * FROM '.$table_opt.'
1201
                    WHERE c_id = '.$courseId.' AND question_id = '.$obj->question_id;
1202
            $db_result2 = Database::query($sql);
1203
            while ($obj2 = Database::fetch_object($db_result2)) {
1204
                $question->add_answer($obj2->option_text, $obj2->sort);
1205
            }
1206
            $this->course->add_resource($question);
1207
        }
1208
    }
1209
1210
    /**
1211
     * Build the announcements.
1212
     *
1213
     * @param int   $session_id      Internal session ID
1214
     * @param int   $courseId        Internal course ID
1215
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1216
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1217
     */
1218
    public function build_announcements(
1219
        $session_id = 0,
1220
        $courseId = 0,
1221
        $withBaseContent = false,
1222
        $id_list = []
1223
    ) {
1224
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1225
1226
        $sessionCondition = api_get_session_condition(
1227
            $session_id,
1228
            true,
1229
            $withBaseContent
1230
        );
1231
1232
        $courseId = (int) $courseId;
1233
1234
        $sql = 'SELECT * FROM '.$table.'
1235
                WHERE c_id = '.$courseId.' '.$sessionCondition;
1236
        $db_result = Database::query($sql);
1237
        $table_attachment = Database::get_course_table(
1238
            TABLE_ANNOUNCEMENT_ATTACHMENT
1239
        );
1240
        while ($obj = Database::fetch_object($db_result)) {
1241
            if (empty($obj->id)) {
1242
                continue;
1243
            }
1244
            $sql = 'SELECT path, comment, filename, size
1245
                    FROM '.$table_attachment.'
1246
                    WHERE c_id = '.$courseId.' AND announcement_id = '.$obj->id.'';
1247
            $result = Database::query($sql);
1248
            $attachment_obj = Database::fetch_object($result);
1249
            $att_path = $att_filename = $att_size = $atth_comment = '';
1250
1251
            if (!empty($attachment_obj)) {
1252
                $att_path = $attachment_obj->path;
1253
                $att_filename = $attachment_obj->filename;
1254
                $att_size = $attachment_obj->size;
1255
                $atth_comment = $attachment_obj->comment;
1256
            }
1257
1258
            $announcement = new Announcement(
1259
                $obj->id,
1260
                $obj->title,
1261
                $obj->content,
1262
                $obj->end_date,
1263
                $obj->display_order,
1264
                $obj->email_sent,
1265
                $att_path,
1266
                $att_filename,
1267
                $att_size,
1268
                $atth_comment
1269
            );
1270
            $this->course->add_resource($announcement);
1271
        }
1272
    }
1273
1274
    /**
1275
     * Build the events.
1276
     *
1277
     * @param int   $session_id      Internal session ID
1278
     * @param int   $courseId        Internal course ID
1279
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1280
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1281
     */
1282
    public function build_events(
1283
        $session_id = 0,
1284
        $courseId = 0,
1285
        $withBaseContent = false,
1286
        $id_list = []
1287
    ) {
1288
        $table = Database::get_course_table(TABLE_AGENDA);
1289
1290
        $sessionCondition = api_get_session_condition(
1291
            $session_id,
1292
            true,
1293
            $withBaseContent
1294
        );
1295
1296
        $courseId = (int) $courseId;
1297
1298
        $sql = 'SELECT * FROM '.$table.'
1299
                WHERE c_id = '.$courseId.' '.$sessionCondition;
1300
        $db_result = Database::query($sql);
1301
        while ($obj = Database::fetch_object($db_result)) {
1302
            $table_attachment = Database::get_course_table(
1303
                TABLE_AGENDA_ATTACHMENT
1304
            );
1305
            $sql = 'SELECT path, comment, filename, size
1306
                    FROM '.$table_attachment.'
1307
                    WHERE c_id = '.$courseId.' AND agenda_id = '.$obj->id.'';
1308
            $result = Database::query($sql);
1309
1310
            $attachment_obj = Database::fetch_object($result);
1311
            $att_path = $att_filename = $att_size = $atth_comment = '';
1312
            if (!empty($attachment_obj)) {
1313
                $att_path = $attachment_obj->path;
1314
                $att_filename = $attachment_obj->filename;
1315
                $att_size = $attachment_obj->size;
1316
                $atth_comment = $attachment_obj->comment;
1317
            }
1318
            $event = new CalendarEvent(
1319
                $obj->id,
1320
                $obj->title,
1321
                $obj->content,
1322
                $obj->start_date,
1323
                $obj->end_date,
1324
                $att_path,
1325
                $att_filename,
1326
                $att_size,
1327
                $atth_comment,
1328
                $obj->all_day
1329
            );
1330
            $this->course->add_resource($event);
1331
        }
1332
    }
1333
1334
    /**
1335
     * Build the course-descriptions.
1336
     *
1337
     * @param int   $session_id      Internal session ID
1338
     * @param int   $courseId        Internal course ID
1339
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1340
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1341
     */
1342
    public function build_course_descriptions(
1343
        $session_id = 0,
1344
        $courseId = 0,
1345
        $withBaseContent = false,
1346
        $id_list = []
1347
    ) {
1348
        $table = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
1349
        $courseId = (int) $courseId;
1350
1351
        if (!empty($session_id) && !empty($courseId)) {
1352
            $session_id = intval($session_id);
1353
            if ($withBaseContent) {
1354
                $sessionCondition = api_get_session_condition(
1355
                    $session_id,
1356
                    true,
1357
                    true
1358
                );
1359
            } else {
1360
                $sessionCondition = api_get_session_condition(
1361
                    $session_id,
1362
                    true
1363
                );
1364
            }
1365
            $sql = 'SELECT * FROM '.$table.'
1366
                    WHERE c_id = '.$courseId.' '.$sessionCondition;
1367
        } else {
1368
            $table = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
1369
            $sql = 'SELECT * FROM '.$table.'
1370
                    WHERE c_id = '.$courseId.'  AND session_id = 0';
1371
        }
1372
1373
        $db_result = Database::query($sql);
1374
        while ($obj = Database::fetch_object($db_result)) {
1375
            $cd = new CourseDescription(
1376
                $obj->id,
1377
                $obj->title,
1378
                $obj->content,
1379
                $obj->description_type
1380
            );
1381
            $this->course->add_resource($cd);
1382
        }
1383
    }
1384
1385
    /**
1386
     * @param int   $session_id
1387
     * @param int   $courseId
1388
     * @param bool  $withBaseContent
1389
     * @param array $idList
1390
     */
1391
    public function build_learnpath_category($session_id = 0, $courseId = 0, $withBaseContent = false, $idList = [])
1392
    {
1393
        $categories = \learnpath::getCategories($courseId);
1394
1395
        /** @var CLpCategory $item */
1396
        foreach ($categories as $item) {
1397
            $categoryId = $item->getId();
1398
            if (!empty($idList)) {
1399
                if (!in_array($categoryId, $idList)) {
1400
                    continue;
1401
                }
1402
            }
1403
            $category = new LearnPathCategory($categoryId, $item);
1404
            $this->course->add_resource($category);
1405
        }
1406
    }
1407
1408
    /**
1409
     * Build the learnpaths.
1410
     *
1411
     * @param int   $session_id      Internal session ID
1412
     * @param int   $courseId        Internal course ID
1413
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1414
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1415
     * @param bool  $addScormFolder
1416
     */
1417
    public function build_learnpaths(
1418
        $session_id = 0,
1419
        $courseId = 0,
1420
        $withBaseContent = false,
1421
        $id_list = [],
1422
        $addScormFolder = true
1423
    ) {
1424
        $lpTable = Database::get_course_table(TABLE_LP_MAIN);
1425
        $table_item = Database::get_course_table(TABLE_LP_ITEM);
1426
        $table_tool = Database::get_course_table(TABLE_TOOL_LIST);
1427
1428
        $courseId = (int) $courseId;
1429
1430
        if (!empty($session_id) && !empty($courseId)) {
1431
            $session_id = (int) $session_id;
1432
            if ($withBaseContent) {
1433
                $sessionCondition = api_get_session_condition(
1434
                    $session_id,
1435
                    true,
1436
                    true
1437
                );
1438
            } else {
1439
                $sessionCondition = api_get_session_condition(
1440
                    $session_id,
1441
                    true
1442
                );
1443
            }
1444
            $sql = 'SELECT * FROM '.$lpTable.'
1445
                    WHERE c_id = '.$courseId.'  '.$sessionCondition;
1446
        } else {
1447
            $sql = 'SELECT * FROM '.$lpTable.'
1448
                    WHERE c_id = '.$courseId.' AND (session_id = 0 OR session_id IS NULL)';
1449
        }
1450
1451
        if (!empty($id_list)) {
1452
            $id_list = array_map('intval', $id_list);
1453
            $sql .= " AND id IN (".implode(', ', $id_list).") ";
1454
        }
1455
1456
        $result = Database::query($sql);
1457
        if ($result) {
0 ignored issues
show
introduced by
$result is of type Doctrine\DBAL\Driver\Statement, thus it always evaluated to true.
Loading history...
1458
            while ($obj = Database::fetch_object($result)) {
1459
                $items = [];
1460
                $sql = "SELECT * FROM $table_item
1461
                        WHERE c_id = '$courseId' AND lp_id = ".$obj->id;
1462
                $resultItem = Database::query($sql);
1463
                while ($obj_item = Database::fetch_object($resultItem)) {
1464
                    $item['id'] = $obj_item->iid;
1465
                    $item['item_type'] = $obj_item->item_type;
1466
                    $item['ref'] = $obj_item->ref;
1467
                    $item['title'] = $obj_item->title;
1468
                    $item['description'] = $obj_item->description;
1469
                    $item['path'] = $obj_item->path;
1470
                    $item['min_score'] = $obj_item->min_score;
1471
                    $item['max_score'] = $obj_item->max_score;
1472
                    $item['mastery_score'] = $obj_item->mastery_score;
1473
                    $item['parent_item_id'] = $obj_item->parent_item_id;
1474
                    $item['previous_item_id'] = $obj_item->previous_item_id;
1475
                    $item['next_item_id'] = $obj_item->next_item_id;
1476
                    $item['display_order'] = $obj_item->display_order;
1477
                    $item['prerequisite'] = $obj_item->prerequisite;
1478
                    $item['prerequisite_min_score'] = $obj_item->prerequisite_min_score;
1479
                    $item['prerequisite_max_score'] = $obj_item->prerequisite_max_score;
1480
                    $item['parameters'] = $obj_item->parameters;
1481
                    $item['launch_data'] = $obj_item->launch_data;
1482
                    $item['audio'] = $obj_item->audio;
1483
                    $items[] = $item;
1484
                }
1485
1486
                $sql = "SELECT id FROM $table_tool
1487
                        WHERE
1488
                            c_id = $courseId AND
1489
                            (link LIKE '%lp_controller.php%lp_id=".$obj->id."%' AND image='scormbuilder.gif') AND
1490
                            visibility = '1' ";
1491
                $db_tool = Database::query($sql);
1492
                $visibility = '0';
1493
                if (Database::num_rows($db_tool)) {
1494
                    $visibility = '1';
1495
                }
1496
1497
                $accumulateWorkTime = 0;
1498
                if (api_get_configuration_value('lp_minimum_time')) {
1499
                    if (isset($obj->accumulateWorkTime) && !empty($obj->accumulateWorkTime)) {
1500
                        $accumulateWorkTime = $obj->accumulateWorkTime;
1501
                    }
1502
                }
1503
1504
                $lp = new CourseCopyLearnpath(
1505
                    $obj->id,
1506
                    $obj->lp_type,
1507
                    $obj->name,
1508
                    $obj->path,
1509
                    $obj->ref,
1510
                    $obj->description,
1511
                    $obj->content_local,
1512
                    $obj->default_encoding,
1513
                    $obj->default_view_mod,
1514
                    $obj->prevent_reinit,
1515
                    $obj->force_commit,
1516
                    $obj->content_maker,
1517
                    $obj->display_order,
1518
                    $obj->js_lib,
1519
                    $obj->content_license,
1520
                    $obj->debug,
1521
                    $visibility,
1522
                    $obj->author,
1523
                    $obj->preview_image,
1524
                    $obj->use_max_score,
1525
                    $obj->autolaunch,
1526
                    $obj->created_on,
1527
                    $obj->modified_on,
1528
                    $obj->publicated_on,
1529
                    $obj->expired_on,
1530
                    $obj->session_id,
1531
                    $obj->category_id,
1532
                    $obj->subscribe_users,
1533
                    $obj->hide_toc_frame,
1534
                    $items,
1535
                    $accumulateWorkTime
1536
                );
1537
                $extraFieldValue = new \ExtraFieldValue('lp');
1538
                $lp->extraFields = $extraFieldValue->getAllValuesByItem($obj->id);
1539
                $this->course->add_resource($lp);
1540
1541
                if (!empty($obj->preview_image)) {
1542
                    // Add LP image
1543
                    $asset = new Asset(
1544
                        $obj->preview_image,
1545
                        '/upload/learning_path/images/'.$obj->preview_image,
1546
                        '/upload/learning_path/images/'.$obj->preview_image
1547
                    );
1548
                    $this->course->add_resource($asset);
1549
                }
1550
            }
1551
        }
1552
1553
        // Save scorm directory (previously build_scorm_documents())
1554
        if ($addScormFolder) {
1555
            $i = 1;
1556
            if ($dir = @opendir($this->course->backup_path.'/scorm')) {
1557
                while ($file = readdir($dir)) {
1558
                    if (is_dir($this->course->backup_path.'/scorm/'.$file) &&
1559
                        !in_array($file, ['.', '..'])
1560
                    ) {
1561
                        $doc = new ScormDocument($i++, '/'.$file, $file);
1562
                        $this->course->add_resource($doc);
1563
                    }
1564
                }
1565
                closedir($dir);
1566
            }
1567
        }
1568
    }
1569
1570
    /**
1571
     * Build the glossaries.
1572
     *
1573
     * @param int   $session_id      Internal session ID
1574
     * @param int   $courseId        Internal course ID
1575
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1576
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1577
     */
1578
    public function build_glossary(
1579
        $session_id = 0,
1580
        $courseId = 0,
1581
        $withBaseContent = false,
1582
        $id_list = []
1583
    ) {
1584
        $table_glossary = Database::get_course_table(TABLE_GLOSSARY);
1585
1586
        $courseId = (int) $courseId;
1587
1588
        if (!empty($session_id) && !empty($courseId)) {
1589
            $session_id = intval($session_id);
1590
            if ($withBaseContent) {
1591
                $sessionCondition = api_get_session_condition(
1592
                    $session_id,
1593
                    true,
1594
                    true
1595
                );
1596
            } else {
1597
                $sessionCondition = api_get_session_condition(
1598
                    $session_id,
1599
                    true
1600
                );
1601
            }
1602
1603
            //@todo check this queries are the same ...
1604
            if (!empty($this->course->type) && $this->course->type == 'partial') {
0 ignored issues
show
Bug introduced by
The property type does not seem to exist on Chamilo\CourseBundle\Component\CourseCopy\Course.
Loading history...
1605
                $sql = 'SELECT * FROM '.$table_glossary.' g
1606
                        WHERE g.c_id = '.$courseId.' '.$sessionCondition;
1607
            } else {
1608
                $sql = 'SELECT * FROM '.$table_glossary.' g
1609
                        WHERE g.c_id = '.$courseId.' '.$sessionCondition;
1610
            }
1611
        } else {
1612
            $table_glossary = Database::get_course_table(TABLE_GLOSSARY);
1613
            //@todo check this queries are the same ... ayayay
1614
            if (!empty($this->course->type) && $this->course->type == 'partial') {
1615
                $sql = 'SELECT * FROM '.$table_glossary.' g
1616
                        WHERE g.c_id = '.$courseId.' AND (session_id = 0 OR session_id IS NULL)';
1617
            } else {
1618
                $sql = 'SELECT * FROM '.$table_glossary.' g
1619
                        WHERE g.c_id = '.$courseId.' AND (session_id = 0 OR session_id IS NULL)';
1620
            }
1621
        }
1622
        $db_result = Database::query($sql);
1623
        while ($obj = Database::fetch_object($db_result)) {
1624
            $doc = new Glossary(
1625
                $obj->glossary_id,
1626
                $obj->name,
1627
                $obj->description,
1628
                $obj->display_order
1629
            );
1630
            $this->course->add_resource($doc);
1631
        }
1632
    }
1633
1634
    /*
1635
     * Build session course by jhon
1636
     */
1637
    public function build_session_course()
1638
    {
1639
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1640
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1641
        $list_course = CourseManager::get_course_list();
1642
        $list = [];
1643
        foreach ($list_course as $_course) {
1644
            $this->course = new Course();
1645
            $this->course->code = $_course['code'];
1646
            $this->course->type = 'partial';
0 ignored issues
show
Bug introduced by
The property type does not seem to exist on Chamilo\CourseBundle\Component\CourseCopy\Course.
Loading history...
1647
            $this->course->path = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/';
1648
            $this->course->backup_path = api_get_path(SYS_COURSE_PATH).$_course['directory'];
1649
            $this->course->encoding = api_get_system_encoding(); //current platform encoding
1650
            $courseId = $_course['real_id'];
1651
            $sql = "SELECT s.id, name, c_id
1652
                    FROM $tbl_session_course sc
1653
                    INNER JOIN $tbl_session s
1654
                    ON sc.session_id = s.id
1655
                    WHERE sc.c_id = '$courseId' ";
1656
            $query_session = Database::query($sql);
1657
            while ($rows_session = Database::fetch_assoc($query_session)) {
1658
                $session = new CourseSession(
1659
                    $rows_session['id'],
1660
                    $rows_session['name']
1661
                );
1662
                $this->course->add_resource($session);
1663
            }
1664
            $list[] = $this->course;
1665
        }
1666
1667
        return $list;
1668
    }
1669
1670
    /**
1671
     * @param int   $session_id      Internal session ID
1672
     * @param int   $courseId        Internal course ID
1673
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1674
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1675
     */
1676
    public function build_wiki(
1677
        $session_id = 0,
1678
        $courseId = 0,
1679
        $withBaseContent = false,
1680
        $id_list = []
1681
    ) {
1682
        $tbl_wiki = Database::get_course_table(TABLE_WIKI);
1683
        $courseId = (int) $courseId;
1684
1685
        if (!empty($session_id) && !empty($courseId)) {
1686
            $session_id = intval($session_id);
1687
            if ($withBaseContent) {
1688
                $sessionCondition = api_get_session_condition(
1689
                    $session_id,
1690
                    true,
1691
                    true
1692
                );
1693
            } else {
1694
                $sessionCondition = api_get_session_condition(
1695
                    $session_id,
1696
                    true
1697
                );
1698
            }
1699
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1700
                    WHERE c_id = '.$courseId.' '.$sessionCondition;
1701
        } else {
1702
            $tbl_wiki = Database::get_course_table(TABLE_WIKI);
1703
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1704
                    WHERE c_id = '.$courseId.' AND (session_id = 0 OR session_id IS NULL)';
1705
        }
1706
        $db_result = Database::query($sql);
1707
        while ($obj = Database::fetch_object($db_result)) {
1708
            $wiki = new Wiki(
1709
                $obj->id,
1710
                $obj->page_id,
1711
                $obj->reflink,
1712
                $obj->title,
1713
                $obj->content,
1714
                $obj->user_id,
1715
                $obj->group_id,
1716
                $obj->dtime,
1717
                $obj->progress,
1718
                $obj->version
1719
            );
1720
            $this->course->add_resource($wiki);
1721
        }
1722
    }
1723
1724
    /**
1725
     * Build the Surveys.
1726
     *
1727
     * @param int   $session_id      Internal session ID
1728
     * @param int   $courseId        Internal course ID
1729
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1730
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1731
     */
1732
    public function build_thematic(
1733
        $session_id = 0,
1734
        $courseId = 0,
1735
        $withBaseContent = false,
1736
        $id_list = []
1737
    ) {
1738
        $table_thematic = Database::get_course_table(TABLE_THEMATIC);
1739
        $table_thematic_advance = Database::get_course_table(TABLE_THEMATIC_ADVANCE);
1740
        $table_thematic_plan = Database::get_course_table(TABLE_THEMATIC_PLAN);
1741
        $courseId = (int) $courseId;
1742
1743
        $courseInfo = api_get_course_info_by_id($courseId);
1744
        $session_id = intval($session_id);
1745
        if ($withBaseContent) {
1746
            $sessionCondition = api_get_session_condition(
1747
                $session_id,
1748
                true,
1749
                true
1750
            );
1751
        } else {
1752
            $sessionCondition = api_get_session_condition($session_id, true);
1753
        }
1754
1755
        $sql = "SELECT * FROM $table_thematic
1756
                WHERE c_id = $courseId $sessionCondition ";
1757
        $db_result = Database::query($sql);
1758
        while ($row = Database::fetch_array($db_result, 'ASSOC')) {
1759
            $thematic = new Thematic($row);
1760
            $sql = 'SELECT * FROM '.$table_thematic_advance.'
1761
                    WHERE c_id = '.$courseId.' AND thematic_id = '.$row['id'];
1762
1763
            $result = Database::query($sql);
1764
            while ($sub_row = Database::fetch_array($result, 'ASSOC')) {
1765
                $thematic->addThematicAdvance($sub_row);
1766
            }
1767
1768
            $items = api_get_item_property_by_tool(
1769
                'thematic_plan',
1770
                $courseInfo['code'],
1771
                $session_id
1772
            );
1773
1774
            $thematic_plan_id_list = [];
1775
            if (!empty($items)) {
1776
                foreach ($items as $item) {
1777
                    $thematic_plan_id_list[] = $item['ref'];
1778
                }
1779
            }
1780
            if (count($thematic_plan_id_list) > 0) {
1781
                $sql = "SELECT tp.*
1782
                        FROM $table_thematic_plan tp
1783
                            INNER JOIN $table_thematic t ON (t.id=tp.thematic_id)
1784
                        WHERE
1785
                            t.c_id = $courseId AND
1786
                            tp.c_id = $courseId AND
1787
                            thematic_id = {$row['id']}  AND
1788
                            tp.id IN (".implode(', ', $thematic_plan_id_list).") ";
1789
1790
                $result = Database::query($sql);
1791
                while ($sub_row = Database::fetch_array($result, 'ASSOC')) {
1792
                    $thematic->addThematicPlan($sub_row);
1793
                }
1794
            }
1795
            $this->course->add_resource($thematic);
1796
        }
1797
    }
1798
1799
    /**
1800
     * Build the attendances.
1801
     *
1802
     * @param int   $session_id      Internal session ID
1803
     * @param int   $courseId        Internal course ID
1804
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1805
     * @param array $id_list         If you want to restrict the structure to only the given IDs
1806
     */
1807
    public function build_attendance(
1808
        $session_id = 0,
1809
        $courseId = 0,
1810
        $withBaseContent = false,
1811
        $id_list = []
1812
    ) {
1813
        $table_attendance = Database::get_course_table(TABLE_ATTENDANCE);
1814
        $table_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1815
        $sessionCondition = api_get_session_condition($session_id, true, $withBaseContent);
1816
        $courseId = (int) $courseId;
1817
1818
        $sql = 'SELECT * FROM '.$table_attendance.'
1819
                WHERE c_id = '.$courseId.' '.$sessionCondition;
1820
        $db_result = Database::query($sql);
1821
        while ($row = Database::fetch_array($db_result, 'ASSOC')) {
1822
            $obj = new Attendance($row);
1823
            $sql = 'SELECT * FROM '.$table_attendance_calendar.'
1824
                    WHERE c_id = '.$courseId.' AND attendance_id = '.$row['id'];
1825
1826
            $result = Database::query($sql);
1827
            while ($sub_row = Database::fetch_array($result, 'ASSOC')) {
1828
                $obj->add_attendance_calendar($sub_row);
1829
            }
1830
            $this->course->add_resource($obj);
1831
        }
1832
    }
1833
1834
    /**
1835
     * Build the works (or "student publications", or "assignments").
1836
     *
1837
     * @param int   $session_id      Internal session ID
1838
     * @param int   $courseId        Internal course ID
1839
     * @param bool  $withBaseContent Whether to include content from the course without session or not
1840
     * @param array $idList          If you want to restrict the structure to only the given IDs
1841
     */
1842
    public function build_works(
1843
        $session_id = 0,
1844
        $courseId = 0,
1845
        $withBaseContent = false,
1846
        $idList = []
1847
    ) {
1848
        $table_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1849
        $sessionCondition = api_get_session_condition(
1850
            $session_id,
1851
            true,
1852
            $withBaseContent
1853
        );
1854
        $courseId = (int) $courseId;
1855
1856
        $idCondition = '';
1857
        if (!empty($idList)) {
1858
            $idList = array_map('intval', $idList);
1859
            $idCondition = ' AND iid IN ("'.implode('","', $idList).'") ';
1860
        }
1861
1862
        $sql = "SELECT * FROM $table_work
1863
                WHERE
1864
                    c_id = $courseId
1865
                    $sessionCondition AND
1866
                    filetype = 'folder' AND
1867
                    parent_id = 0 AND
1868
                    active = 1
1869
                    $idCondition
1870
                ";
1871
        $result = Database::query($sql);
1872
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1873
            $obj = new Work($row);
1874
            $this->course->add_resource($obj);
1875
        }
1876
    }
1877
1878
    /**
1879
     * @param int  $session_id
1880
     * @param int  $courseId
1881
     * @param bool $withBaseContent
1882
     */
1883
    public function build_gradebook(
1884
        $session_id = 0,
1885
        $courseId = 0,
1886
        $withBaseContent = false
1887
    ) {
1888
        $courseInfo = api_get_course_info_by_id($courseId);
1889
        $courseCode = $courseInfo['code'];
1890
        $cats = Category:: load(
1891
            null,
1892
            null,
1893
            $courseCode,
1894
            null,
1895
            null,
1896
            $session_id
1897
        );
1898
1899
        if (!empty($cats)) {
1900
            /** @var Category $cat */
1901
            foreach ($cats as $cat) {
1902
                $cat->evaluations = $cat->get_evaluations(null, false);
1903
                $cat->links = $cat->get_links(null, false);
1904
                $cat->subCategories = $cat->get_subcategories(
1905
                    null,
1906
                    $courseCode,
1907
                    $session_id
1908
                );
1909
            }
1910
            $obj = new GradeBookBackup($cats);
1911
            $this->course->add_resource($obj);
1912
        }
1913
    }
1914
}
1915