Passed
Push — master ( 5e8c5a...33aff7 )
by Julito
09:33
created

CourseRestorer::restore_gradebook()   D

Complexity

Conditions 26

Size

Total Lines 107
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
eloc 71
c 0
b 0
f 0
nop 1
dl 0
loc 107
rs 4.1666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
namespace Chamilo\CourseBundle\Component\CourseCopy;
6
7
use Chamilo\CourseBundle\Component\CourseCopy\Resources\GradeBookBackup;
8
use Chamilo\CourseBundle\Component\CourseCopy\Resources\LearnPathCategory;
9
use Chamilo\CourseBundle\Component\CourseCopy\Resources\QuizQuestion;
10
use Chamilo\CourseBundle\Entity\CLpCategory;
11
use Chamilo\CourseBundle\Entity\CQuizAnswer;
12
use CourseManager;
13
use Database;
14
use DocumentManager;
15
use Question;
16
use stdClass;
17
use SurveyManager;
18
use TestCategory;
19
20
/**
21
 * Class CourseRestorer.
22
 *
23
 * Class to restore items from a course object to a Chamilo-course
24
 *
25
 * @author Bart Mollet <[email protected]>
26
 * @author Julio Montoya <[email protected]> Several fixes/improvements
27
 */
28
class CourseRestorer
29
{
30
    /**
31
     * The course-object.
32
     */
33
    public $course;
34
    public $destination_course_info;
35
36
    /**
37
     * What to do with files with same name (FILE_SKIP, FILE_RENAME or
38
     * FILE_OVERWRITE).
39
     */
40
    public $file_option;
41
    public $set_tools_invisible_by_default;
42
    public $skip_content;
43
    public $tools_to_restore = [
44
        'documents', // first restore documents
45
        'announcements',
46
        'attendance',
47
        'course_descriptions',
48
        'events',
49
        'forum_category',
50
        'forums',
51
       // 'forum_topics',
52
        'glossary',
53
        'quizzes',
54
        'test_category',
55
        'links',
56
        'works',
57
        'surveys',
58
        'learnpath_category',
59
        'learnpaths',
60
        //'scorm_documents', ??
61
        'tool_intro',
62
        'thematic',
63
        'wiki',
64
        'gradebook',
65
        'assets',
66
    ];
67
68
    /** Setting per tool */
69
    public $tool_copy_settings = [];
70
71
    /**
72
     * If true adds the text "copy" in the title of an item (only for LPs right now).
73
     */
74
    public $add_text_in_items = false;
75
    public $destination_course_id;
76
77
    /**
78
     * CourseRestorer constructor.
79
     *
80
     * @param Course $course
81
     */
82
    public function __construct($course)
83
    {
84
        $this->course = $course;
85
        $courseInfo = api_get_course_info($this->course->code);
86
        $this->course_origin_id = null;
87
        if (!empty($courseInfo)) {
88
            $this->course_origin_id = $courseInfo['real_id'];
89
        }
90
        $this->file_option = FILE_RENAME;
91
        $this->set_tools_invisible_by_default = false;
92
        $this->skip_content = [];
93
94
        $forceImport = api_get_configuration_value('allow_import_scorm_package_in_course_builder');
95
        if ($forceImport) {
96
            $this->tools_to_restore[] = 'scorm_documents';
97
        }
98
    }
99
100
    /**
101
     * Set the file-option.
102
     *
103
     * @param int $option (optional) What to do with files with same name
104
     *                    FILE_SKIP, FILE_RENAME or FILE_OVERWRITE
105
     */
106
    public function set_file_option($option = FILE_OVERWRITE)
107
    {
108
        $this->file_option = $option;
109
    }
110
111
    /**
112
     * @param bool $status
113
     */
114
    public function set_add_text_in_items($status)
115
    {
116
        $this->add_text_in_items = $status;
117
    }
118
119
    /**
120
     * @param array $array
121
     */
122
    public function set_tool_copy_settings($array)
123
    {
124
        $this->tool_copy_settings = $array;
125
    }
126
127
    /**
128
     * Restore a course.
129
     *
130
     * @param string $destination_course_code code of the Chamilo-course in
131
     * @param int    $session_id
132
     * @param bool   $update_course_settings  Course settings are going to be restore?
133
     * @param bool   $respect_base_content
134
     *
135
     * @return false|null
136
     */
137
    public function restore(
138
        $destination_course_code = '',
139
        $session_id = 0,
140
        $update_course_settings = false,
141
        $respect_base_content = false
142
    ) {
143
        if ('' == $destination_course_code) {
144
            $course_info = api_get_course_info();
145
            $this->destination_course_info = $course_info;
146
            $this->course->destination_path = $course_info['path'];
147
        } else {
148
            $course_info = api_get_course_info($destination_course_code);
149
            $this->destination_course_info = $course_info;
150
            $this->course->destination_path = $course_info['path'];
151
        }
152
        $this->destination_course_id = $course_info['real_id'];
153
154
        // Getting first teacher (for the forums)
155
        $teacher_list = CourseManager::get_teacher_list_from_course_code($course_info['code']);
156
        $this->first_teacher_id = api_get_user_id();
157
158
        if (!empty($teacher_list)) {
159
            foreach ($teacher_list as $teacher) {
160
                $this->first_teacher_id = $teacher['user_id'];
161
162
                break;
163
            }
164
        }
165
166
        if (empty($this->course)) {
167
            return false;
168
        }
169
170
        // Source platform encoding - reading/detection
171
        // The correspondent data field has been added as of version 1.8.6.1
172
        if (empty($this->course->encoding)) {
173
            // The archive has been created by a system which is prior to 1.8.6.1 version.
174
            // In this case we have to detect the encoding.
175
            $sample_text = $this->course->get_sample_text()."\n";
176
            // Let us exclude ASCII lines, probably they are English texts.
177
            $sample_text = explode("\n", $sample_text);
178
            foreach ($sample_text as $key => &$line) {
179
                if (api_is_valid_ascii($line)) {
180
                    unset($sample_text[$key]);
181
                }
182
            }
183
            $sample_text = implode("\n", $sample_text);
184
            $this->course->encoding = api_detect_encoding(
185
                $sample_text,
186
                $course_info['language']
187
            );
188
        }
189
190
        // Encoding conversion of the course, if it is needed.
191
        $this->course->to_system_encoding();
192
193
        foreach ($this->tools_to_restore as $tool) {
194
            $function_build = 'restore_'.$tool;
195
            $this->$function_build(
196
                $session_id,
197
                $respect_base_content,
198
                $destination_course_code
199
            );
200
        }
201
202
        if ($update_course_settings) {
203
            $this->restore_course_settings($destination_course_code);
204
        }
205
206
        // Restore the item properties
207
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
208
        foreach ($this->course->resources as $type => $resources) {
209
            if (is_array($resources)) {
210
                foreach ($resources as $id => $resource) {
211
                    if (isset($resource->item_properties)) {
212
                        foreach ($resource->item_properties as $property) {
213
                            // First check if there isn't already a record for this resource
214
                            $sql = "SELECT * FROM $table
215
                                    WHERE
216
                                        c_id = ".$this->destination_course_id." AND
217
                                        tool = '".$property['tool']."' AND
218
                                        ref = '".$resource->destination_id."'";
219
220
                            $params = [];
221
                            if (!empty($session_id)) {
222
                                $params['session_id'] = (int) $session_id;
223
                            }
224
225
                            $res = Database::query($sql);
226
                            if (0 == Database::num_rows($res)) {
227
                                /* The to_group_id and to_user_id are set to default
228
                                values as users/groups possibly not exist in
229
                                the target course*/
230
231
                                $params['c_id'] = $this->destination_course_id;
232
                                $params['tool'] = self::DBUTF8($property['tool']);
233
                                $params['insert_user_id'] = $this->checkUserId($property['insert_user_id']) ?: null;
234
                                $params['insert_date'] = self::DBUTF8($property['insert_date']);
235
                                $params['lastedit_date'] = self::DBUTF8($property['lastedit_date']);
236
                                $params['ref'] = $resource->destination_id;
237
                                $params['lastedit_type'] = self::DBUTF8($property['lastedit_type']);
238
                                $params['lastedit_user_id'] = $this->checkUserId($property['lastedit_user_id']);
239
                                $params['visibility'] = self::DBUTF8($property['visibility']);
240
                                $params['start_visible'] = self::DBUTF8($property['start_visible']);
241
                                $params['end_visible'] = self::DBUTF8($property['end_visible']);
242
                                $params['to_user_id'] = $this->checkUserId($property['to_user_id']) ?: null;
243
244
                                $id = Database::insert($table, $params);
245
                                if ($id) {
246
                                    $sql = "UPDATE $table SET id = iid WHERE iid = $id";
247
                                    Database::query($sql);
248
                                }
249
                            }
250
                        }
251
                    }
252
                }
253
            }
254
        }
255
    }
256
257
    /**
258
     * Restore only harmless course settings:
259
     * course_language, visibility, department_name,department_url,
260
     * subscribe, unsubscribe, category_id.
261
     *
262
     * @param string $destination_course_code
263
     */
264
    public function restore_course_settings($destination_course_code)
265
    {
266
        $origin_course_info = api_get_course_info($destination_course_code);
267
        $course_info = $this->course->info;
268
        $params['course_language'] = $course_info['language'];
269
        $params['visibility'] = $course_info['visibility'];
270
        $params['department_name'] = $course_info['department_name'];
271
        $params['department_url'] = $course_info['department_url'];
272
        $params['category_id'] = $course_info['category_id'];
273
        $params['subscribe'] = $course_info['subscribe_allowed'];
274
        $params['unsubscribe'] = $course_info['unsubscribe'];
275
        CourseManager::update_attributes($origin_course_info['real_id'], $params);
276
    }
277
278
    /**
279
     * Restore documents.
280
     *
281
     * @param int    $session_id
282
     * @param bool   $respect_base_content
283
     * @param string $destination_course_code
284
     */
285
    public function restore_documents(
286
        $session_id = 0,
287
        $respect_base_content = false,
288
        $destination_course_code = ''
289
    ) {
290
        $course_info = api_get_course_info($destination_course_code);
291
292
        if (!$this->course->has_resources(RESOURCE_DOCUMENT)) {
293
            return;
294
        }
295
296
        $webEditorCss = api_get_path(WEB_CSS_PATH).'editor.css';
297
        $table = Database::get_course_table(TABLE_DOCUMENT);
298
        $resources = $this->course->resources;
299
        $path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/';
300
        $originalFolderNameList = [];
301
        foreach ($resources[RESOURCE_DOCUMENT] as $id => $document) {
302
            $my_session_id = empty($document->item_properties[0]['session_id']) ? 0 : $session_id;
303
            //$path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/';
304
            if (false === $respect_base_content && $session_id) {
305
                if (empty($my_session_id)) {
306
                    $my_session_id = $session_id;
307
                }
308
            }
309
310
            if (FOLDER == $document->file_type) {
311
                $visibility = isset($document->item_properties[0]['visibility']) ? $document->item_properties[0]['visibility'] : '';
312
                $new = substr($document->path, 8);
313
314
                $folderList = explode('/', $new);
315
                $tempFolder = '';
316
317
                // Check if the parent path exists.
318
                foreach ($folderList as $folder) {
319
                    $folderToCreate = $tempFolder.$folder;
320
                    //$sysFolderPath = $path.'document'.$folderToCreate;
321
                    $sysFolderPath = null;
322
                    $tempFolder .= $folder.'/';
323
324
                    if (empty($folderToCreate)) {
325
                        continue;
326
                    }
327
328
                    $title = $document->title;
329
                    $originalFolderNameList[basename($document->path)] = $document->title;
330
                    if (empty($title)) {
331
                        $title = basename($sysFolderPath);
332
                    }
333
334
                    // File doesn't exist in file system.
335
                    if (!is_dir($sysFolderPath)) {
336
                        // Creating directory
337
                        create_unexisting_directory(
338
                            $course_info,
339
                            api_get_user_id(),
340
                            $my_session_id,
341
                            0,
342
                            0,
343
                            $path.'document',
344
                            $folderToCreate,
345
                            $title,
346
                            $visibility
347
                        );
348
349
                        continue;
350
                    }
351
352
                    // File exist in file system.
353
                    $documentData = DocumentManager::get_document_id(
354
                        $course_info,
355
                        $folderToCreate,
356
                        $session_id
357
                    );
358
359
                    if (empty($documentData)) {
360
                        /* This means the folder exists in the
361
                        filesystem but not in the DB, trying to fix it */
362
                        DocumentManager::addDocument(
363
                            $course_info,
364
                            $folderToCreate,
365
                            'folder',
366
                            0,
367
                            $title,
368
                            null,
369
                            null,
370
                            false,
371
                            null,
372
                                $session_id,
373
                            0,
374
                            false
375
                        );
376
                    } else {
377
                        $insertUserId = isset($document->item_properties[0]['insert_user_id']) ? $document->item_properties[0]['insert_user_id'] : api_get_user_id();
378
                        $insertUserId = $this->checkUserId($insertUserId);
379
380
                        // Check if user exists in platform
381
                        $toUserId = isset($document->item_properties[0]['to_user_id']) ? $document->item_properties[0]['to_user_id'] : null;
382
                        $toUserId = $this->checkUserId($toUserId, true);
383
384
                        $groupId = isset($document->item_properties[0]['to_group_id']) ? $document->item_properties[0]['to_group_id'] : null;
385
                        $groupInfo = $this->checkGroupId($groupId);
386
387
                        // if folder exists then just refresh it
388
                        api_item_property_update(
389
                            $course_info,
390
                            TOOL_DOCUMENT,
391
                            $documentData,
392
                            'FolderUpdated',
393
                            $insertUserId,
394
                            $groupInfo,
395
                            $toUserId,
396
                            null,
397
                            null,
398
                            $my_session_id
399
                        );
400
                    }
401
                }
402
            } elseif (DOCUMENT == $document->file_type) {
403
                // Checking if folder exists in the database otherwise we created it
404
                $dir_to_create = dirname($document->path);
405
                if (!empty($dir_to_create) && 'document' != $dir_to_create && '/' != $dir_to_create) {
406
                    if (is_dir($path.dirname($document->path))) {
407
                        $sql = "SELECT id FROM $table
408
                                WHERE
409
                                    c_id = ".$this->destination_course_id." AND
410
                                    path = '/".self::DBUTF8escapestring(substr(dirname($document->path), 9))."'";
411
                        $res = Database::query($sql);
412
413
                        if (0 == Database::num_rows($res)) {
414
                            //continue;
415
                            $visibility = $document->item_properties[0]['visibility'];
416
                            $new = '/'.substr(dirname($document->path), 9);
417
                            $title = $document->title;
418
                            if (empty($title)) {
419
                                $title = str_replace('/', '', $new);
420
                            }
421
422
                            // This code fixes the possibility for a file without a directory entry to be
423
                            $document_id = DocumentManager::addDocument(
424
                                $course_info,
425
                                $new,
426
                                'folder',
427
                                0,
428
                                $title,
429
                                null,
430
                                null,
431
                                false,
432
                                0,
433
                                0,
434
                                0,
435
                                false
436
                            );
437
438
                            $itemProperty = isset($document->item_properties[0]) ? $document->item_properties[0] : '';
439
                            $insertUserId = isset($itemProperty['insert_user_id']) ? $itemProperty['insert_user_id'] : api_get_user_id();
440
                            $toGroupId = isset($itemProperty['to_group_id']) ? $itemProperty['to_group_id'] : 0;
441
                            $toUserId = isset($itemProperty['to_user_id']) ? $itemProperty['to_user_id'] : null;
442
                            $groupInfo = $this->checkGroupId($toGroupId);
443
                            $insertUserId = $this->checkUserId($insertUserId);
444
                            $toUserId = $this->checkUserId($toUserId, true);
445
446
                            /*api_item_property_update(
447
                                $course_info,
448
                                TOOL_DOCUMENT,
449
                                $document_id,
450
                                'FolderCreated',
451
                                $insertUserId,
452
                                $groupInfo,
453
                                $toUserId,
454
                                null,
455
                                null,
456
                                $my_session_id
457
                            );*/
458
                        }
459
                    }
460
                }
461
462
                if (file_exists($path.$document->path)) {
463
                    switch ($this->file_option) {
464
                        case FILE_OVERWRITE:
465
                            $origin_path = $this->course->backup_path.'/'.$document->path;
466
                            if (file_exists($origin_path)) {
467
                                copy($origin_path, $path.$document->path);
468
                                $this->fixEditorHtmlContent($path.$document->path, $webEditorCss);
469
                                $sql = "SELECT id FROM $table
470
                                        WHERE
471
                                            c_id = ".$this->destination_course_id." AND
472
                                            path = '/".self::DBUTF8escapestring(substr($document->path, 9))."'";
473
474
                                $res = Database::query($sql);
475
                                $count = Database::num_rows($res);
476
477
                                if (0 == $count) {
478
                                    $params = [
479
                                        'path' => '/'.self::DBUTF8(substr($document->path, 9)),
480
                                        'c_id' => $this->destination_course_id,
481
                                        'comment' => self::DBUTF8($document->comment),
482
                                        'title' => self::DBUTF8($document->title),
483
                                        'filetype' => self::DBUTF8($document->file_type),
484
                                        'size' => self::DBUTF8($document->size),
485
                                        'session_id' => $my_session_id,
486
                                        'readonly' => 0,
487
                                    ];
488
489
                                    $document_id = Database::insert($table, $params);
490
491
                                    if ($document_id) {
492
                                        $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
493
                                        Database::query($sql);
494
                                    }
495
                                    $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;
496
497
                                    $itemProperty = isset($document->item_properties[0]) ? $document->item_properties[0] : '';
498
                                    $insertUserId = isset($itemProperty['insert_user_id']) ? $itemProperty['insert_user_id'] : api_get_user_id();
499
                                    $toGroupId = isset($itemProperty['to_group_id']) ? $itemProperty['to_group_id'] : 0;
500
                                    $toUserId = isset($itemProperty['to_user_id']) ? $itemProperty['to_user_id'] : null;
501
502
                                    $insertUserId = $this->checkUserId($insertUserId);
503
                                    $toUserId = $this->checkUserId($toUserId, true);
504
                                    $groupInfo = $this->checkGroupId($toGroupId);
505
506
                                    api_item_property_update(
507
                                        $course_info,
508
                                        TOOL_DOCUMENT,
509
                                        $document_id,
510
                                        'DocumentAdded',
511
                                        $insertUserId,
512
                                        $groupInfo,
513
                                        $toUserId,
514
                                        null,
515
                                        null,
516
                                        $my_session_id
517
                                    );
518
                                } else {
519
                                    $obj = Database::fetch_object($res);
520
                                    $document_id = $obj->id;
521
                                    $params = [
522
                                        'path' => '/'.self::DBUTF8(substr($document->path, 9)),
523
                                        'c_id' => $this->destination_course_id,
524
                                        'comment' => self::DBUTF8($document->comment),
525
                                        'title' => self::DBUTF8($document->title),
526
                                        'filetype' => self::DBUTF8($document->file_type),
527
                                        'size' => self::DBUTF8($document->size),
528
                                        'session_id' => $my_session_id,
529
                                    ];
530
531
                                    Database::update(
532
                                        $table,
533
                                        $params,
534
                                        [
535
                                            'c_id = ? AND path = ?' => [
536
                                                $this->destination_course_id,
537
                                                '/'.self::DBUTF8escapestring(substr($document->path, 9)),
538
                                            ],
539
                                        ]
540
                                    );
541
542
                                    $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $obj->id;
543
544
                                    $itemProperty = isset($document->item_properties[0]) ? $document->item_properties[0] : '';
545
                                    $insertUserId = isset($itemProperty['insert_user_id']) ? $itemProperty['insert_user_id'] : api_get_user_id();
546
                                    $toGroupId = isset($itemProperty['to_group_id']) ? $itemProperty['to_group_id'] : 0;
547
                                    $toUserId = isset($itemProperty['to_user_id']) ? $itemProperty['to_user_id'] : null;
548
549
                                    $insertUserId = $this->checkUserId($insertUserId);
550
                                    $toUserId = $this->checkUserId($toUserId, true);
551
                                    $groupInfo = $this->checkGroupId($toGroupId);
552
553
                                    api_item_property_update(
554
                                        $course_info,
555
                                        TOOL_DOCUMENT,
556
                                        $obj->id,
557
                                        'default',
558
                                        $insertUserId,
559
                                        $groupInfo,
560
                                        $toUserId,
561
                                        null,
562
                                        null,
563
                                        $my_session_id
564
                                    );
565
                                }
566
567
                                // Replace old course code with the new destination code
568
                                $file_info = pathinfo($path.$document->path);
569
570
                                if (isset($file_info['extension']) && in_array($file_info['extension'], ['html', 'htm'])) {
571
                                    $content = file_get_contents($path.$document->path);
572
                                    if (UTF8_CONVERT) {
573
                                        $content = utf8_encode($content);
574
                                    }
575
                                    $content = DocumentManager::replaceUrlWithNewCourseCode(
576
                                        $content,
577
                                        $this->course->code,
578
                                        $this->course->destination_path,
579
                                        $this->course->backup_path,
580
                                        $this->course->info['path']
581
                                    );
582
                                    file_put_contents($path.$document->path, $content);
583
                                }
584
585
                                $params = [
586
                                    'comment' => self::DBUTF8($document->comment),
587
                                    'title' => self::DBUTF8($document->title),
588
                                    'size' => self::DBUTF8($document->size),
589
                                ];
590
                                Database::update(
591
                                    $table,
592
                                    $params,
593
                                    [
594
                                        'c_id = ? AND id = ?' => [
595
                                            $this->destination_course_id,
596
                                            $document_id,
597
                                        ],
598
                                    ]
599
                                );
600
                            }
601
602
                            break;
603
                        case FILE_SKIP:
604
                            $sql = "SELECT id FROM $table
605
                                    WHERE
606
                                        c_id = ".$this->destination_course_id." AND
607
                                        path='/".self::DBUTF8escapestring(substr($document->path, 9))."'";
608
                            $res = Database::query($sql);
609
                            $obj = Database::fetch_object($res);
610
                            $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $obj->id;
611
612
                            break;
613
                        case FILE_RENAME:
614
                            $i = 1;
615
                            $ext = explode('.', basename($document->path));
616
                            if (count($ext) > 1) {
617
                                $ext = array_pop($ext);
618
                                $file_name_no_ext = substr($document->path, 0, -(strlen($ext) + 1));
619
                                $ext = '.'.$ext;
620
                            } else {
621
                                $ext = '';
622
                                $file_name_no_ext = $document->path;
623
                            }
624
                            $new_file_name = $file_name_no_ext.'_'.$i.$ext;
625
                            $file_exists = file_exists($path.$new_file_name);
626
                            while ($file_exists) {
627
                                $i++;
628
                                $new_file_name = $file_name_no_ext.'_'.$i.$ext;
629
                                $file_exists = file_exists($path.$new_file_name);
630
                            }
631
632
                            if (!empty($session_id)) {
633
                                $document_path = explode('/', $document->path, 3);
634
                                $course_path = $path;
635
                                $orig_base_folder = $document_path[1];
636
                                $orig_base_path = $course_path.$document_path[0].'/'.$document_path[1];
637
638
                                if (is_dir($orig_base_path)) {
639
                                    $new_base_foldername = $orig_base_folder;
640
                                    $new_base_path = $orig_base_path;
641
642
                                    if (isset($_SESSION['orig_base_foldername']) &&
643
                                        $_SESSION['orig_base_foldername'] != $new_base_foldername
644
                                    ) {
645
                                        unset($_SESSION['new_base_foldername']);
646
                                        unset($_SESSION['orig_base_foldername']);
647
                                        unset($_SESSION['new_base_path']);
648
                                    }
649
650
                                    $folder_exists = file_exists($new_base_path);
651
                                    if ($folder_exists) {
652
                                        // e.g: carpeta1 in session
653
                                        $_SESSION['orig_base_foldername'] = $new_base_foldername;
654
                                        $x = '';
655
                                        while ($folder_exists) {
656
                                            $x++;
657
                                            $new_base_foldername = $document_path[1].'_'.$x;
658
                                            $new_base_path = $orig_base_path.'_'.$x;
659
                                            if ($_SESSION['new_base_foldername'] == $new_base_foldername) {
660
                                                break;
661
                                            }
662
                                            $folder_exists = file_exists($new_base_path);
663
                                        }
664
                                        $_SESSION['new_base_foldername'] = $new_base_foldername;
665
                                        $_SESSION['new_base_path'] = $new_base_path;
666
                                    }
667
668
                                    if (isset($_SESSION['new_base_foldername']) && isset($_SESSION['new_base_path'])) {
669
                                        $new_base_foldername = $_SESSION['new_base_foldername'];
670
                                        $new_base_path = $_SESSION['new_base_path'];
671
                                    }
672
673
                                    $dest_document_path = $new_base_path.'/'.$document_path[2]; // e.g: "/var/www/wiener/courses/CURSO4/document/carpeta1_1/subcarpeta1/collaborative.png"
674
                                    $basedir_dest_path = dirname($dest_document_path); // e.g: "/var/www/wiener/courses/CURSO4/document/carpeta1_1/subcarpeta1"
675
                                    $base_path_document = $course_path.$document_path[0]; // e.g: "/var/www/wiener/courses/CURSO4/document"
676
                                    $path_title = '/'.$new_base_foldername.'/'.$document_path[2];
677
678
                                    copy_folder_course_session(
679
                                        $basedir_dest_path,
680
                                        $base_path_document,
681
                                        $session_id,
682
                                        $course_info,
683
                                        $document,
684
                                        $this->course_origin_id,
685
                                        $originalFolderNameList,
686
                                        $originalPath
687
                                    );
688
689
                                    if (file_exists($course_path.$document->path)) {
690
                                        copy($course_path.$document->path, $dest_document_path);
691
                                    }
692
693
                                    // Replace old course code with the new destination code see BT#1985
694
                                    if (file_exists($dest_document_path)) {
695
                                        $file_info = pathinfo($dest_document_path);
696
                                        if (in_array($file_info['extension'], ['html', 'htm'])) {
697
                                            $content = file_get_contents($dest_document_path);
698
                                            if (UTF8_CONVERT) {
699
                                                $content = utf8_encode($content);
700
                                            }
701
                                            $content = DocumentManager::replaceUrlWithNewCourseCode(
702
                                                $content,
703
                                                $this->course->code,
704
                                                $this->course->destination_path,
705
                                                $this->course->backup_path,
706
                                                $this->course->info['path']
707
                                            );
708
                                            file_put_contents($dest_document_path, $content);
709
                                            $this->fixEditorHtmlContent($dest_document_path, $webEditorCss);
710
                                        }
711
                                    }
712
713
                                    $title = basename($path_title);
714
                                    if (isset($originalFolderNameList[basename($path_title)])) {
715
                                        $title = $originalFolderNameList[basename($path_title)];
716
                                    }
717
718
                                    $params = [
719
                                        'path' => self::DBUTF8($path_title),
720
                                        'c_id' => $this->destination_course_id,
721
                                        'comment' => self::DBUTF8($document->comment),
722
                                        'title' => self::DBUTF8($title),
723
                                        'filetype' => self::DBUTF8($document->file_type),
724
                                        'size' => self::DBUTF8($document->size),
725
                                        'session_id' => $my_session_id,
726
                                    ];
727
728
                                    $document_id = Database::insert($table, $params);
729
730
                                    if ($document_id) {
731
                                        $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
732
                                        Database::query($sql);
733
734
                                        $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;
735
736
                                        $itemProperty = isset($document->item_properties[0]) ? $document->item_properties[0] : '';
737
                                        $insertUserId = isset($itemProperty['insert_user_id']) ? $itemProperty['insert_user_id'] : api_get_user_id();
738
                                        $toGroupId = isset($itemProperty['to_group_id']) ? $itemProperty['to_group_id'] : 0;
739
                                        $toUserId = isset($itemProperty['to_user_id']) ? $itemProperty['to_user_id'] : null;
740
741
                                        $insertUserId = $this->checkUserId($insertUserId);
742
                                        $toUserId = $this->checkUserId($toUserId, true);
743
                                        $groupInfo = $this->checkGroupId($toGroupId);
744
745
                                        api_item_property_update(
746
                                            $course_info,
747
                                            TOOL_DOCUMENT,
748
                                            $document_id,
749
                                            'DocumentAdded',
750
                                            $insertUserId,
751
                                            $groupInfo,
752
                                            $toUserId,
753
                                            null,
754
                                            null,
755
                                            $my_session_id
756
                                        );
757
                                    }
758
                                } else {
759
                                    if (file_exists($path.$document->path)) {
760
                                        copy($path.$document->path, $path.$new_file_name);
761
                                    }
762
                                    // Replace old course code with the new destination code see BT#1985
763
                                    if (file_exists($path.$new_file_name)) {
764
                                        $file_info = pathinfo($path.$new_file_name);
765
                                        if (in_array($file_info['extension'], ['html', 'htm'])) {
766
                                            $content = file_get_contents($path.$new_file_name);
767
                                            if (UTF8_CONVERT) {
768
                                                $content = utf8_encode($content);
769
                                            }
770
                                            $content = DocumentManager::replaceUrlWithNewCourseCode(
771
                                                $content,
772
                                                $this->course->code,
773
                                                $this->course->destination_path,
774
                                                $this->course->backup_path,
775
                                                $this->course->info['path']
776
                                            );
777
                                            file_put_contents($path.$new_file_name, $content);
778
                                            $this->fixEditorHtmlContent($path.$new_file_name, $webEditorCss);
779
                                        }
780
                                    }
781
782
                                    $params = [
783
                                        'path' => '/'.self::DBUTF8escapestring(substr($new_file_name, 9)),
784
                                        'c_id' => $this->destination_course_id,
785
                                        'comment' => self::DBUTF8($document->comment),
786
                                        'title' => self::DBUTF8($document->title),
787
                                        'filetype' => self::DBUTF8($document->file_type),
788
                                        'size' => self::DBUTF8($document->size),
789
                                        'session_id' => $my_session_id,
790
                                    ];
791
792
                                    $document_id = Database::insert($table, $params);
793
794
                                    if ($document_id) {
795
                                        $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
796
                                        Database::query($sql);
797
798
                                        $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;
799
800
                                        $itemProperty = isset($document->item_properties[0]) ? $document->item_properties[0] : '';
801
                                        $insertUserId = isset($itemProperty['insert_user_id']) ? $itemProperty['insert_user_id'] : api_get_user_id();
802
                                        $toGroupId = isset($itemProperty['to_group_id']) ? $itemProperty['to_group_id'] : 0;
803
                                        $toUserId = isset($itemProperty['to_user_id']) ? $itemProperty['to_user_id'] : null;
804
805
                                        $insertUserId = $this->checkUserId($insertUserId);
806
                                        $toUserId = $this->checkUserId($toUserId, true);
807
                                        $groupInfo = $this->checkGroupId($toGroupId);
808
809
                                        api_item_property_update(
810
                                            $course_info,
811
                                            TOOL_DOCUMENT,
812
                                            $document_id,
813
                                            'DocumentAdded',
814
                                            $insertUserId,
815
                                            $groupInfo,
816
                                            $toUserId,
817
                                            null,
818
                                            null,
819
                                            $my_session_id
820
                                        );
821
                                    }
822
                                }
823
                            } else {
824
                                copy(
825
                                    $this->course->backup_path.'/'.$document->path,
826
                                    $path.$new_file_name
827
                                );
828
829
                                // Replace old course code with the new destination code see BT#1985
830
                                if (file_exists($path.$new_file_name)) {
831
                                    $file_info = pathinfo($path.$new_file_name);
832
                                    if (in_array($file_info['extension'], ['html', 'htm'])) {
833
                                        $content = file_get_contents($path.$new_file_name);
834
                                        if (UTF8_CONVERT) {
835
                                            $content = utf8_encode($content);
836
                                        }
837
                                        $content = DocumentManager::replaceUrlWithNewCourseCode(
838
                                            $content,
839
                                            $this->course->code,
840
                                            $this->course->destination_path,
841
                                            $this->course->backup_path,
842
                                            $this->course->info['path']
843
                                        );
844
                                        file_put_contents($path.$new_file_name, $content);
845
                                        $this->fixEditorHtmlContent($path.$new_file_name, $webEditorCss);
846
                                    }
847
                                }
848
849
                                $params = [
850
                                    'c_id' => $this->destination_course_id,
851
                                    'path' => '/'.self::DBUTF8escapestring(substr($new_file_name, 9)),
852
                                    'comment' => self::DBUTF8($document->comment),
853
                                    'title' => self::DBUTF8($document->title),
854
                                    'filetype' => self::DBUTF8($document->file_type),
855
                                    'size' => self::DBUTF8($document->size),
856
                                    'session_id' => $my_session_id,
857
                                ];
858
859
                                $document_id = Database::insert($table, $params);
860
861
                                if ($document_id) {
862
                                    $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
863
                                    Database::query($sql);
864
                                    $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;
865
866
                                    $itemProperty = isset($document->item_properties[0]) ? $document->item_properties[0] : '';
867
                                    $insertUserId = isset($itemProperty['insert_user_id']) ? $itemProperty['insert_user_id'] : api_get_user_id();
868
                                    $toGroupId = isset($itemProperty['to_group_id']) ? $itemProperty['to_group_id'] : 0;
869
                                    $toUserId = isset($itemProperty['to_user_id']) ? $itemProperty['to_user_id'] : null;
870
871
                                    $insertUserId = $this->checkUserId($insertUserId);
872
                                    $toUserId = $this->checkUserId($toUserId, true);
873
                                    $groupInfo = $this->checkGroupId($toGroupId);
874
875
                                    api_item_property_update(
876
                                        $course_info,
877
                                        TOOL_DOCUMENT,
878
                                        $document_id,
879
                                        'DocumentAdded',
880
                                        $insertUserId,
881
                                        $groupInfo,
882
                                        $toUserId,
883
                                        null,
884
                                        null,
885
                                        $my_session_id
886
                                    );
887
                                }
888
                            }
889
890
                            break;
891
                    } // end switch
892
                } else {
893
                    // end if file exists
894
                    //make sure the source file actually exists
895
                    if (is_file($this->course->backup_path.'/'.$document->path) &&
896
                        is_readable($this->course->backup_path.'/'.$document->path) &&
897
                        is_dir(dirname($path.$document->path)) &&
898
                        is_writable(dirname($path.$document->path))
899
                    ) {
900
                        copy(
901
                            $this->course->backup_path.'/'.$document->path,
902
                            $path.$document->path
903
                        );
904
905
                        // Replace old course code with the new destination code see BT#1985
906
                        if (file_exists($path.$document->path)) {
907
                            $file_info = pathinfo($path.$document->path);
908
                            if (isset($file_info['extension']) && in_array($file_info['extension'], ['html', 'htm'])) {
909
                                $content = file_get_contents($path.$document->path);
910
                                if (UTF8_CONVERT) {
911
                                    $content = utf8_encode($content);
912
                                }
913
                                $content = DocumentManager::replaceUrlWithNewCourseCode(
914
                                    $content,
915
                                    $this->course->code,
916
                                    $this->course->destination_path,
917
                                    $this->course->backup_path,
918
                                    $this->course->info['path']
919
                                );
920
                                file_put_contents($path.$document->path, $content);
921
                                $this->fixEditorHtmlContent($path.$document->path, $webEditorCss);
922
                            }
923
                        }
924
925
                        $params = [
926
                            'c_id' => $this->destination_course_id,
927
                            'path' => '/'.self::DBUTF8(substr($document->path, 9)),
928
                            'comment' => self::DBUTF8($document->comment),
929
                            'title' => self::DBUTF8($document->title),
930
                            'filetype' => self::DBUTF8($document->file_type),
931
                            'size' => self::DBUTF8($document->size),
932
                            'session_id' => $my_session_id,
933
                            'readonly' => 0,
934
                        ];
935
936
                        $document_id = Database::insert($table, $params);
937
938
                        if ($document_id) {
939
                            $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
940
                            Database::query($sql);
941
942
                            $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;
943
944
                            $itemProperty = isset($document->item_properties[0]) ? $document->item_properties[0] : '';
945
                            $insertUserId = isset($itemProperty['insert_user_id']) ? $itemProperty['insert_user_id'] : api_get_user_id();
946
                            $toGroupId = isset($itemProperty['to_group_id']) ? $itemProperty['to_group_id'] : 0;
947
                            $toUserId = isset($itemProperty['to_user_id']) ? $itemProperty['to_user_id'] : null;
948
949
                            $insertUserId = $this->checkUserId($insertUserId);
950
                            $toUserId = $this->checkUserId($toUserId, true);
951
                            $groupInfo = $this->checkGroupId($toGroupId);
952
953
                            api_item_property_update(
954
                                $course_info,
955
                                TOOL_DOCUMENT,
956
                                $document_id,
957
                                'DocumentAdded',
958
                                $insertUserId,
959
                                $groupInfo,
960
                                $toUserId,
961
                                null,
962
                                null,
963
                                $my_session_id
964
                            );
965
                        }
966
                    } else {
967
                        // There was an error in checking existence and
968
                        // permissions for files to copy. Try to determine
969
                        // the exact issue
970
                        // Issue with origin document?
971
                        if (!is_file($this->course->backup_path.'/'.$document->path)) {
972
                            error_log(
973
                                'Course copy generated an ignorable error while trying to copy '.
974
                                $this->course->backup_path.'/'.$document->path.': origin file not found'
975
                            );
976
                        } elseif (!is_readable($this->course->backup_path.'/'.$document->path)) {
977
                            error_log(
978
                                'Course copy generated an ignorable error while trying to copy '.
979
                                $this->course->backup_path.'/'.$document->path.': origin file not readable'
980
                            );
981
                        }
982
                        // Issue with destination directories?
983
                        if (!is_dir(dirname($path.$document->path))) {
984
                            error_log(
985
                                'Course copy generated an ignorable error while trying to copy '.
986
                                $this->course->backup_path.'/'.$document->path.' to '.
987
                                dirname($path.$document->path).': destination directory not found'
988
                            );
989
                        }
990
                        if (!is_writable(dirname($path.$document->path))) {
991
                            error_log(
992
                                'Course copy generated an ignorable error while trying to copy '.
993
                                $this->course->backup_path.'/'.$document->path.' to '.
994
                                dirname($path.$document->path).': destination directory not writable'
995
                            );
996
                        }
997
                    }
998
                } // end file doesn't exist
999
            }
1000
1001
            // add image information for area questions
1002
            if (preg_match('/^quiz-.*$/', $document->title) &&
1003
                preg_match('/^document\/images\/.*$/', $document->path)
1004
            ) {
1005
                $this->course->resources[RESOURCE_DOCUMENT]['image_quiz'][$document->title] = [
1006
                    'path' => $document->path,
1007
                    'title' => $document->title,
1008
                    'source_id' => $document->source_id,
1009
                    'destination_id' => $document->destination_id,
1010
                ];
1011
            }
1012
        } // end for each
1013
1014
        // Delete sessions for the copy the new folder in session
1015
        unset($_SESSION['new_base_foldername']);
1016
        unset($_SESSION['orig_base_foldername']);
1017
        unset($_SESSION['new_base_path']);
1018
    }
1019
1020
    /**
1021
     * Restore scorm documents
1022
     * TODO @TODO check that the restore function with renaming doesn't break the scorm structure!
1023
     * see #7029.
1024
     */
1025
    public function restore_scorm_documents()
1026
    {
1027
        /*$perm = api_get_permissions_for_new_directories();
1028
        if ($this->course->has_resources(RESOURCE_SCORM)) {
1029
            $resources = $this->course->resources;
1030
            foreach ($resources[RESOURCE_SCORM] as $document) {
1031
                $path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/';
1032
                @mkdir(dirname($path.$document->path), $perm, true);
1033
                if (file_exists($path.$document->path)) {
1034
                    switch ($this->file_option) {
1035
                        case FILE_OVERWRITE:
1036
                            rmdirr($path.$document->path);
1037
                            copyDirTo(
1038
                                $this->course->backup_path.'/'.$document->path,
1039
                                $path.$document->path,
1040
                                false
1041
                            );
1042
1043
                            break;
1044
                        case FILE_SKIP:
1045
                            break;
1046
                        case FILE_RENAME:
1047
                            $i = 1;
1048
                            $ext = explode('.', basename($document->path));
1049
                            if (count($ext) > 1) {
1050
                                $ext = array_pop($ext);
1051
                                $file_name_no_ext = substr($document->path, 0, -(strlen($ext) + 1));
1052
                                $ext = '.'.$ext;
1053
                            } else {
1054
                                $ext = '';
1055
                                $file_name_no_ext = $document->path;
1056
                            }
1057
1058
                            $new_file_name = $file_name_no_ext.'_'.$i.$ext;
1059
                            $file_exists = file_exists($path.$new_file_name);
1060
1061
                            while ($file_exists) {
1062
                                $i++;
1063
                                $new_file_name = $file_name_no_ext.'_'.$i.$ext;
1064
                                $file_exists = file_exists($path.$new_file_name);
1065
                            }
1066
1067
                            rename(
1068
                                $this->course->backup_path.'/'.$document->path,
1069
                                $this->course->backup_path.'/'.$new_file_name
1070
                            );
1071
                            copyDirTo(
1072
                                $this->course->backup_path.'/'.$new_file_name,
1073
                                $path.dirname($new_file_name),
1074
                                false
1075
                            );
1076
                            rename(
1077
                                $this->course->backup_path.'/'.$new_file_name,
1078
                                $this->course->backup_path.'/'.$document->path
1079
                            );
1080
1081
                            break;
1082
                    } // end switch
1083
                } else {
1084
                    // end if file exists
1085
                    copyDirTo(
1086
                        $this->course->backup_path.'/'.$document->path,
1087
                        $path.$document->path,
1088
                        false
1089
                    );
1090
                }
1091
            } // end for each
1092
        }*/
1093
    }
1094
1095
    /**
1096
     * Restore forums.
1097
     *
1098
     * @param int $sessionId
1099
     */
1100
    public function restore_forums($sessionId = 0)
1101
    {
1102
        if ($this->course->has_resources(RESOURCE_FORUM)) {
1103
            $sessionId = (int) $sessionId;
1104
            $table_forum = Database::get_course_table(TABLE_FORUM);
1105
            $resources = $this->course->resources;
1106
            foreach ($resources[RESOURCE_FORUM] as $id => $forum) {
1107
                $params = (array) $forum->obj;
1108
                $cat_id = '';
1109
                if (isset($this->course->resources[RESOURCE_FORUMCATEGORY]) &&
1110
                    isset($this->course->resources[RESOURCE_FORUMCATEGORY][$params['forum_category']])) {
1111
                    if (-1 == $this->course->resources[RESOURCE_FORUMCATEGORY][$params['forum_category']]->destination_id) {
1112
                        $cat_id = $this->restore_forum_category(
1113
                            $params['forum_category'],
1114
                            $sessionId
1115
                        );
1116
                    } else {
1117
                        $cat_id = $this->course->resources[RESOURCE_FORUMCATEGORY][$params['forum_category']]->destination_id;
1118
                    }
1119
                }
1120
1121
                $params = self::DBUTF8_array($params);
1122
                $params['c_id'] = $this->destination_course_id;
1123
                $params['forum_category'] = $cat_id;
1124
                $params['session_id'] = $sessionId;
1125
                $params['start_time'] = isset($params['start_time']) && '0000-00-00 00:00:00' === $params['start_time'] ? null : $params['start_time'];
1126
                $params['end_time'] = isset($params['end_time']) && '0000-00-00 00:00:00' === $params['end_time'] ? null : $params['end_time'];
1127
                $params['forum_id'] = 0;
1128
                unset($params['iid']);
1129
1130
                $params['forum_comment'] = DocumentManager::replaceUrlWithNewCourseCode(
1131
                    $params['forum_comment'],
1132
                    $this->course->code,
1133
                    $this->course->destination_path,
1134
                    $this->course->backup_path,
1135
                    $this->course->info['path']
1136
                );
1137
1138
                if (!empty($params['forum_image'])) {
1139
                    $original_forum_image = $this->course->path.'upload/forum/images/'.$params['forum_image'];
1140
                    if (file_exists($original_forum_image)) {
1141
                        $new_forum_image = api_get_path(SYS_COURSE_PATH).
1142
                            $this->destination_course_info['path'].'/upload/forum/images/'.$params['forum_image'];
1143
                        @copy($original_forum_image, $new_forum_image);
1144
                    }
1145
                }
1146
1147
                $new_id = Database::insert($table_forum, $params);
1148
1149
                if ($new_id) {
1150
                    $sql = "UPDATE $table_forum SET forum_id = iid WHERE iid = $new_id";
1151
                    Database::query($sql);
1152
1153
                    api_item_property_update(
1154
                        $this->destination_course_info,
1155
                        TOOL_FORUM,
1156
                        $new_id,
1157
                        'ForumUpdated',
1158
                        api_get_user_id()
1159
                    );
1160
1161
                    $this->course->resources[RESOURCE_FORUM][$id]->destination_id = $new_id;
1162
1163
                    $forum_topics = 0;
1164
                    if (isset($this->course->resources[RESOURCE_FORUMTOPIC]) &&
1165
                        is_array($this->course->resources[RESOURCE_FORUMTOPIC])
1166
                    ) {
1167
                        foreach ($this->course->resources[RESOURCE_FORUMTOPIC] as $topic_id => $topic) {
1168
                            if ($topic->obj->forum_id == $id) {
1169
                                $this->restore_topic($topic_id, $new_id, $sessionId);
1170
                                $forum_topics++;
1171
                            }
1172
                        }
1173
                    }
1174
                    if ($forum_topics > 0) {
1175
                        $sql = 'UPDATE '.$table_forum.' SET forum_threads = '.$forum_topics."
1176
                                WHERE c_id = {$this->destination_course_id} AND forum_id = ".(int) $new_id;
1177
                        Database::query($sql);
1178
                    }
1179
                }
1180
            }
1181
        }
1182
    }
1183
1184
    /**
1185
     * Restore forum-categories.
1186
     */
1187
    public function restore_forum_category($my_id = null, $sessionId = 0)
1188
    {
1189
        $forum_cat_table = Database::get_course_table(TABLE_FORUM_CATEGORY);
1190
        $resources = $this->course->resources;
1191
        $sessionId = (int) $sessionId;
1192
        if (!empty($resources[RESOURCE_FORUMCATEGORY])) {
1193
            foreach ($resources[RESOURCE_FORUMCATEGORY] as $id => $forum_cat) {
1194
                if (!empty($my_id)) {
1195
                    if ($my_id != $id) {
1196
                        continue;
1197
                    }
1198
                }
1199
                if ($forum_cat && !$forum_cat->is_restored()) {
1200
                    $params = (array) $forum_cat->obj;
1201
                    $params['c_id'] = $this->destination_course_id;
1202
                    $params['cat_comment'] = DocumentManager::replaceUrlWithNewCourseCode(
1203
                        $params['cat_comment'],
1204
                        $this->course->code,
1205
                        $this->course->destination_path,
1206
                        $this->course->backup_path,
1207
                        $this->course->info['path']
1208
                    );
1209
                    $params['session_id'] = $sessionId;
1210
                    $params['cat_id'] = 0;
1211
                    unset($params['iid']);
1212
1213
                    $params = self::DBUTF8_array($params);
1214
                    $new_id = Database::insert($forum_cat_table, $params);
1215
1216
                    if ($new_id) {
1217
                        $sql = "UPDATE $forum_cat_table SET cat_id = iid WHERE iid = $new_id";
1218
                        Database::query($sql);
1219
1220
                        api_item_property_update(
1221
                            $this->destination_course_info,
1222
                            TOOL_FORUM_CATEGORY,
1223
                            $new_id,
1224
                            'ForumCategoryUpdated',
1225
                            api_get_user_id()
1226
                        );
1227
                        $this->course->resources[RESOURCE_FORUMCATEGORY][$id]->destination_id = $new_id;
1228
                    }
1229
1230
                    if (!empty($my_id)) {
1231
                        return $new_id;
1232
                    }
1233
                }
1234
            }
1235
        }
1236
    }
1237
1238
    /**
1239
     * Restore a forum-topic.
1240
     *
1241
     * @param false|string $forum_id
1242
     *
1243
     * @return int
1244
     */
1245
    public function restore_topic($thread_id, $forum_id, $sessionId = 0)
1246
    {
1247
        $table = Database::get_course_table(TABLE_FORUM_THREAD);
1248
        $topic = $this->course->resources[RESOURCE_FORUMTOPIC][$thread_id];
1249
1250
        $sessionId = (int) $sessionId;
1251
        $params = (array) $topic->obj;
1252
        $params = self::DBUTF8_array($params);
1253
        $params['c_id'] = $this->destination_course_id;
1254
        $params['forum_id'] = $forum_id;
1255
        $params['thread_poster_id'] = $this->first_teacher_id;
1256
        $params['thread_date'] = api_get_utc_datetime();
1257
        $params['thread_close_date'] = null;
1258
        $params['thread_last_post'] = 0;
1259
        $params['thread_replies'] = 0;
1260
        $params['thread_views'] = 0;
1261
        $params['session_id'] = $sessionId;
1262
        $params['thread_id'] = 0;
1263
1264
        unset($params['iid']);
1265
1266
        $new_id = Database::insert($table, $params);
1267
1268
        if ($new_id) {
1269
            $sql = "UPDATE $table SET thread_id = iid WHERE iid = $new_id";
1270
            Database::query($sql);
1271
1272
            api_item_property_update(
1273
                $this->destination_course_info,
1274
                TOOL_FORUM_THREAD,
1275
                $new_id,
1276
                'ThreadAdded',
1277
                api_get_user_id(),
1278
                0,
1279
                0,
1280
                null,
1281
                null,
1282
                $sessionId
1283
            );
1284
1285
            $this->course->resources[RESOURCE_FORUMTOPIC][$thread_id]->destination_id = $new_id;
1286
            foreach ($this->course->resources[RESOURCE_FORUMPOST] as $post_id => $post) {
1287
                if ($post->obj->thread_id == $thread_id) {
1288
                    $this->restore_post($post_id, $new_id, $forum_id, $sessionId);
1289
                }
1290
            }
1291
        }
1292
1293
        return $new_id;
1294
    }
1295
1296
    /**
1297
     * Restore a forum-post.
1298
     *
1299
     * @TODO Restore tree-structure of posts. For example: attachments to posts.
1300
     *
1301
     * @param false|string $topic_id
1302
     *
1303
     * @return int
1304
     */
1305
    public function restore_post($id, $topic_id, $forum_id, $sessionId = 0)
1306
    {
1307
        $table_post = Database::get_course_table(TABLE_FORUM_POST);
1308
        $post = $this->course->resources[RESOURCE_FORUMPOST][$id];
1309
        $params = (array) $post->obj;
1310
        $params['c_id'] = $this->destination_course_id;
1311
        $params['forum_id'] = $forum_id;
1312
        $params['thread_id'] = $topic_id;
1313
        $params['poster_id'] = $this->first_teacher_id;
1314
        $params['post_date'] = api_get_utc_datetime();
1315
        $params['post_id'] = 0;
1316
        unset($params['iid']);
1317
1318
        $params['post_text'] = DocumentManager::replaceUrlWithNewCourseCode(
1319
            $params['post_text'],
1320
            $this->course->code,
1321
            $this->course->destination_path,
1322
            $this->course->backup_path,
1323
            $this->course->info['path']
1324
        );
1325
        $new_id = Database::insert($table_post, $params);
1326
1327
        if ($new_id) {
1328
            $sql = "UPDATE $table_post SET post_id = iid WHERE iid = $new_id";
1329
            Database::query($sql);
1330
1331
            api_item_property_update(
1332
                $this->destination_course_info,
1333
                TOOL_FORUM_POST,
1334
                $new_id,
1335
                'PostAdded',
1336
                api_get_user_id(),
1337
                0,
1338
                0,
1339
                null,
1340
                null,
1341
                $sessionId
1342
            );
1343
            $this->course->resources[RESOURCE_FORUMPOST][$id]->destination_id = $new_id;
1344
        }
1345
1346
        return $new_id;
1347
    }
1348
1349
    /**
1350
     * Restore links.
1351
     */
1352
    public function restore_links($session_id = 0)
1353
    {
1354
        if ($this->course->has_resources(RESOURCE_LINK)) {
1355
            $link_table = Database::get_course_table(TABLE_LINK);
1356
            $resources = $this->course->resources;
1357
1358
            foreach ($resources[RESOURCE_LINK] as $oldLinkId => $link) {
1359
                $cat_id = $this->restore_link_category(
1360
                    $link->category_id,
1361
                    $session_id
1362
                );
1363
                $sql = "SELECT MAX(display_order)
1364
                        FROM $link_table
1365
                        WHERE
1366
                            c_id = ".$this->destination_course_id." AND
1367
                            category_id='".(int) $cat_id."'";
1368
                $result = Database::query($sql);
1369
                list($max_order) = Database::fetch_array($result);
1370
1371
                $params = [];
1372
                if (!empty($session_id)) {
1373
                    $params['session_id'] = $session_id;
1374
                }
1375
1376
                $params['c_id'] = $this->destination_course_id;
1377
                $params['url'] = self::DBUTF8($link->url);
1378
                $params['title'] = self::DBUTF8($link->title);
1379
                $params['description'] = self::DBUTF8($link->description);
1380
                $params['category_id'] = $cat_id;
1381
                $params['on_homepage'] = $link->on_homepage;
1382
                $params['display_order'] = $max_order + 1;
1383
                $params['target'] = $link->target;
1384
1385
                $id = Database::insert($link_table, $params);
1386
1387
                if ($id) {
1388
                    $sql = "UPDATE $link_table SET id = iid WHERE iid = $id";
1389
                    Database::query($sql);
1390
1391
                    api_item_property_update(
1392
                        $this->destination_course_info,
1393
                        TOOL_LINK,
1394
                        $id,
1395
                        'LinkAdded',
1396
                        api_get_user_id()
1397
                    );
1398
1399
                    if (!isset($this->course->resources[RESOURCE_LINK][$oldLinkId])) {
1400
                        $this->course->resources[RESOURCE_LINK][$oldLinkId] = new stdClass();
1401
                    }
1402
                    $this->course->resources[RESOURCE_LINK][$oldLinkId]->destination_id = $id;
1403
                }
1404
            }
1405
        }
1406
    }
1407
1408
    /**
1409
     * Restore a link-category.
1410
     *
1411
     * @param int $id
1412
     * @param int $sessionId
1413
     *
1414
     * @return bool
1415
     */
1416
    public function restore_link_category($id, $sessionId = 0)
1417
    {
1418
        $params = [];
1419
        $sessionId = (int) $sessionId;
1420
        if (!empty($sessionId)) {
1421
            $params['session_id'] = $sessionId;
1422
        }
1423
1424
        if (0 == $id) {
1425
            return 0;
1426
        }
1427
        $link_cat_table = Database::get_course_table(TABLE_LINK_CATEGORY);
1428
        $resources = $this->course->resources;
1429
        $link_cat = $resources[RESOURCE_LINKCATEGORY][$id];
1430
        if (is_object($link_cat) && !$link_cat->is_restored()) {
1431
            $sql = "SELECT MAX(display_order) FROM  $link_cat_table
1432
                    WHERE c_id = ".$this->destination_course_id;
1433
            $result = Database::query($sql);
1434
            list($orderMax) = Database::fetch_array($result, 'NUM');
1435
            $display_order = $orderMax + 1;
1436
1437
            $params['c_id'] = $this->destination_course_id;
1438
            $params['category_title'] = self::DBUTF8($link_cat->title);
1439
            $params['description'] = self::DBUTF8($link_cat->description);
1440
            $params['display_order'] = $display_order;
1441
            $new_id = Database::insert($link_cat_table, $params);
1442
1443
            if ($new_id) {
1444
                $sql = "UPDATE $link_cat_table
1445
                        SET id = iid
1446
                        WHERE iid = $new_id";
1447
                Database::query($sql);
1448
1449
                $courseInfo = api_get_course_info_by_id($this->destination_course_id);
1450
                api_item_property_update(
1451
                    $courseInfo,
1452
                    TOOL_LINK_CATEGORY,
1453
                    $new_id,
1454
                    'LinkCategoryAdded',
1455
                    api_get_user_id()
1456
                );
1457
                api_set_default_visibility(
1458
                    $new_id,
1459
                    TOOL_LINK_CATEGORY,
1460
                    0,
1461
                    $courseInfo
1462
                );
1463
            }
1464
1465
            $this->course->resources[RESOURCE_LINKCATEGORY][$id]->destination_id = $new_id;
1466
1467
            return $new_id;
1468
        }
1469
1470
        return $this->course->resources[RESOURCE_LINKCATEGORY][$id]->destination_id;
1471
    }
1472
1473
    /**
1474
     * Restore tool intro.
1475
     *
1476
     * @param int $sessionId
1477
     */
1478
    public function restore_tool_intro($sessionId = 0)
1479
    {
1480
        if ($this->course->has_resources(RESOURCE_TOOL_INTRO)) {
1481
            $sessionId = (int) $sessionId;
1482
            $tool_intro_table = Database::get_course_table(TABLE_TOOL_INTRO);
1483
            $resources = $this->course->resources;
1484
            foreach ($resources[RESOURCE_TOOL_INTRO] as $id => $tool_intro) {
1485
                $sql = "DELETE FROM $tool_intro_table
1486
                        WHERE
1487
                            c_id = ".$this->destination_course_id." AND
1488
                            id='".self::DBUTF8escapestring($tool_intro->id)."'";
1489
                Database::query($sql);
1490
1491
                $tool_intro->intro_text = DocumentManager::replaceUrlWithNewCourseCode(
1492
                    $tool_intro->intro_text,
1493
                    $this->course->code,
1494
                    $this->course->destination_path,
1495
                    $this->course->backup_path,
1496
                    $this->course->info['path']
1497
                );
1498
1499
                $params = [
1500
                    'c_id' => $this->destination_course_id,
1501
                    'id' => false === $tool_intro->id ? '' : self::DBUTF8($tool_intro->id),
1502
                    'intro_text' => self::DBUTF8($tool_intro->intro_text),
1503
                    'session_id' => $sessionId,
1504
                ];
1505
1506
                $id = Database::insert($tool_intro_table, $params);
1507
                if ($id) {
1508
                    if (!isset($this->course->resources[RESOURCE_TOOL_INTRO][$id])) {
1509
                        $this->course->resources[RESOURCE_TOOL_INTRO][$id] = new stdClass();
1510
                    }
1511
1512
                    $this->course->resources[RESOURCE_TOOL_INTRO][$id]->destination_id = $id;
1513
                }
1514
            }
1515
        }
1516
    }
1517
1518
    /**
1519
     * Restore events.
1520
     *
1521
     * @param int $sessionId
1522
     */
1523
    public function restore_events($sessionId = 0)
1524
    {
1525
        if ($this->course->has_resources(RESOURCE_EVENT)) {
1526
            $sessionId = (int) $sessionId;
1527
            $table = Database::get_course_table(TABLE_AGENDA);
1528
            $resources = $this->course->resources;
1529
            foreach ($resources[RESOURCE_EVENT] as $id => $event) {
1530
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
1531
                $event->content = DocumentManager::replaceUrlWithNewCourseCode(
1532
                    $event->content,
1533
                    $this->course->code,
1534
                    $this->course->destination_path,
1535
                    $this->course->backup_path,
1536
                    $this->course->info['path']
1537
                );
1538
1539
                $params = [
1540
                    'c_id' => $this->destination_course_id,
1541
                    'title' => self::DBUTF8($event->title),
1542
                    'content' => false === $event->content ? '' : self::DBUTF8($event->content),
1543
                    'all_day' => $event->all_day,
1544
                    'start_date' => $event->start_date,
1545
                    'end_date' => $event->end_date,
1546
                    'session_id' => $sessionId,
1547
                ];
1548
                $new_event_id = Database::insert($table, $params);
1549
1550
                if ($new_event_id) {
1551
                    $sql = "UPDATE $table SET id = iid WHERE iid = $new_event_id";
1552
                    Database::query($sql);
1553
1554
                    if (!isset($this->course->resources[RESOURCE_EVENT][$id])) {
1555
                        $this->course->resources[RESOURCE_EVENT][$id] = new stdClass();
1556
                    }
1557
                    $this->course->resources[RESOURCE_EVENT][$id]->destination_id = $new_event_id;
1558
                }
1559
1560
                // Copy event attachment
1561
                $origin_path = $this->course->backup_path.'/upload/calendar/';
1562
                $destination_path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/upload/calendar/';
1563
1564
                if (!empty($this->course->orig)) {
1565
                    $table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
1566
                    $sql = 'SELECT path, comment, size, filename
1567
                            FROM '.$table_attachment.'
1568
                            WHERE c_id = '.$this->destination_course_id.' AND agenda_id = '.$id;
1569
                    $attachment_event = Database::query($sql);
1570
                    $attachment_event = Database::fetch_object($attachment_event);
1571
1572
                    if (file_exists($origin_path.$attachment_event->path) &&
1573
                        !is_dir($origin_path.$attachment_event->path)
1574
                    ) {
1575
                        $new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
1576
                        $copy_result = copy(
1577
                            $origin_path.$attachment_event->path,
1578
                            $destination_path.$new_filename
1579
                        );
1580
                        //$copy_result = true;
1581
                        if ($copy_result) {
1582
                            $table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
1583
1584
                            $params = [
1585
                                'c_id' => $this->destination_course_id,
1586
                                'path' => self::DBUTF8($new_filename),
1587
                                'comment' => self::DBUTF8($attachment_event->comment),
1588
                                'size' => isset($attachment_event->size) ? $attachment_event->size : '',
1589
                                'filename' => isset($attachment_event->filename) ? $attachment_event->filename : '',
1590
                                'agenda_id' => $new_event_id,
1591
                            ];
1592
                            $id = Database::insert($table_attachment, $params);
1593
                            if ($id) {
1594
                                $sql = "UPDATE $table_attachment SET id = iid WHERE iid = $id";
1595
                                Database::query($sql);
1596
                            }
1597
                        }
1598
                    }
1599
                } else {
1600
                    // get the info of the file
1601
                    if (!empty($event->attachment_path) &&
1602
                        is_file($origin_path.$event->attachment_path) &&
1603
                        is_readable($origin_path.$event->attachment_path)
1604
                    ) {
1605
                        $new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
1606
                        $copy_result = copy(
1607
                            $origin_path.$event->attachment_path,
1608
                            $destination_path.$new_filename
1609
                        );
1610
                        if ($copy_result) {
1611
                            $table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
1612
1613
                            $params = [
1614
                                'c_id' => $this->destination_course_id,
1615
                                'path' => self::DBUTF8($new_filename),
1616
                                'comment' => self::DBUTF8($event->attachment_comment),
1617
                                'size' => isset($event->size) ? $event->size : '',
1618
                                'filename' => isset($event->filename) ? $event->filename : '',
1619
                                'agenda_id' => $new_event_id,
1620
                            ];
1621
                            $id = Database::insert($table_attachment, $params);
1622
1623
                            if ($id) {
1624
                                $sql = "UPDATE $table_attachment SET id = iid WHERE iid = $id";
1625
                                Database::query($sql);
1626
                            }
1627
                        }
1628
                    }
1629
                }
1630
            }
1631
        }
1632
    }
1633
1634
    /**
1635
     * Restore course-description.
1636
     *
1637
     * @param int $session_id
1638
     */
1639
    public function restore_course_descriptions($session_id = 0)
1640
    {
1641
        if ($this->course->has_resources(RESOURCE_COURSEDESCRIPTION)) {
1642
            $table = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
1643
            $resources = $this->course->resources;
1644
            foreach ($resources[RESOURCE_COURSEDESCRIPTION] as $id => $cd) {
1645
                $courseDescription = (array) $cd;
1646
1647
                $content = isset($courseDescription['content']) ? $courseDescription['content'] : '';
1648
                $descriptionType = isset($courseDescription['description_type']) ? $courseDescription['description_type'] : '';
1649
                $title = isset($courseDescription['title']) ? $courseDescription['title'] : '';
1650
1651
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
1652
                $description_content = DocumentManager::replaceUrlWithNewCourseCode(
1653
                    $content,
1654
                    $this->course->code,
1655
                    $this->course->destination_path,
1656
                    $this->course->backup_path,
1657
                    $this->course->info['path']
1658
                );
1659
1660
                $params = [];
1661
                $session_id = (int) $session_id;
1662
                $params['session_id'] = $session_id;
1663
                $params['c_id'] = $this->destination_course_id;
1664
                $params['description_type'] = self::DBUTF8($descriptionType);
1665
                $params['title'] = self::DBUTF8($title);
1666
                $params['content'] = false === $description_content ? '' : self::DBUTF8($description_content);
1667
                $params['progress'] = 0;
1668
1669
                $id = Database::insert($table, $params);
1670
                if ($id) {
1671
                    $sql = "UPDATE $table SET id = iid WHERE iid = $id";
1672
                    Database::query($sql);
1673
1674
                    if (!isset($this->course->resources[RESOURCE_COURSEDESCRIPTION][$id])) {
1675
                        $this->course->resources[RESOURCE_COURSEDESCRIPTION][$id] = new stdClass();
1676
                    }
1677
                    $this->course->resources[RESOURCE_COURSEDESCRIPTION][$id]->destination_id = $id;
1678
                }
1679
            }
1680
        }
1681
    }
1682
1683
    /**
1684
     * Restore announcements.
1685
     *
1686
     * @param int $sessionId
1687
     */
1688
    public function restore_announcements($sessionId = 0)
1689
    {
1690
        if ($this->course->has_resources(RESOURCE_ANNOUNCEMENT)) {
1691
            $sessionId = (int) $sessionId;
1692
            $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1693
            $resources = $this->course->resources;
1694
            foreach ($resources[RESOURCE_ANNOUNCEMENT] as $id => $announcement) {
1695
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
1696
                $announcement->content = DocumentManager::replaceUrlWithNewCourseCode(
1697
                    $announcement->content,
1698
                    $this->course->code,
1699
                    $this->course->destination_path,
1700
                    $this->course->backup_path,
1701
                    $this->course->info['path']
1702
                );
1703
1704
                $params = [
1705
                    'c_id' => $this->destination_course_id,
1706
                    'title' => self::DBUTF8($announcement->title),
1707
                    'content' => false === $announcement->content ? '' : self::DBUTF8($announcement->content),
1708
                    'end_date' => $announcement->date,
1709
                    'display_order' => $announcement->display_order,
1710
                    'email_sent' => $announcement->email_sent,
1711
                    'session_id' => $sessionId,
1712
                ];
1713
1714
                $new_announcement_id = Database::insert($table, $params);
1715
1716
                if ($new_announcement_id) {
1717
                    $sql = "UPDATE $table SET id = iid WHERE iid = $new_announcement_id";
1718
                    Database::query($sql);
1719
1720
                    if (!isset($this->course->resources[RESOURCE_ANNOUNCEMENT][$id])) {
1721
                        $this->course->resources[RESOURCE_ANNOUNCEMENT][$id] = new stdClass();
1722
                    }
1723
                    $this->course->resources[RESOURCE_ANNOUNCEMENT][$id]->destination_id = $new_announcement_id;
1724
                }
1725
1726
                $origin_path = $this->course->backup_path.'/upload/announcements/';
1727
                $destination_path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/upload/announcements/';
1728
1729
                // Copy announcement attachment file
1730
                if (!empty($this->course->orig)) {
1731
                    $table_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1732
                    $sql = 'SELECT path, comment, size, filename
1733
                            FROM '.$table_attachment.'
1734
                            WHERE
1735
                                c_id = '.$this->destination_course_id.' AND
1736
                                announcement_id = '.$id;
1737
                    $attachment_event = Database::query($sql);
1738
                    $attachment_event = Database::fetch_object($attachment_event);
1739
1740
                    if (file_exists($origin_path.$attachment_event->path) &&
1741
                        !is_dir($origin_path.$attachment_event->path)
1742
                    ) {
1743
                        $new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
1744
                        $copy_result = copy(
1745
                            $origin_path.$attachment_event->path,
1746
                            $destination_path.$new_filename
1747
                        );
1748
1749
                        if ($copy_result) {
1750
                            $table_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1751
1752
                            $params = [
1753
                                'c_id' => $this->destination_course_id,
1754
                                'path' => self::DBUTF8($new_filename),
1755
                                'comment' => self::DBUTF8($attachment_event->comment),
1756
                                'size' => $attachment_event->size,
1757
                                'filename' => $attachment_event->filename,
1758
                                'announcement_id' => $new_announcement_id,
1759
                            ];
1760
1761
                            $attachmentId = Database::insert($table_attachment, $params);
1762
1763
                            if ($attachmentId) {
1764
                                $sql = "UPDATE $table_attachment SET id = iid WHERE iid = $attachmentId";
1765
                                Database::query($sql);
1766
                            }
1767
                        }
1768
                    }
1769
                } else {
1770
                    // get the info of the file
1771
                    if (!empty($announcement->attachment_path) &&
1772
                        is_file($origin_path.$announcement->attachment_path) &&
1773
                        is_readable($origin_path.$announcement->attachment_path)
1774
                    ) {
1775
                        $new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
1776
                        $copy_result = copy($origin_path.$announcement->attachment_path, $destination_path.$new_filename);
1777
1778
                        if ($copy_result) {
1779
                            $table_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1780
1781
                            $params = [
1782
                                'c_id' => $this->destination_course_id,
1783
                                'path' => self::DBUTF8($new_filename),
1784
                                'comment' => self::DBUTF8($announcement->attachment_comment),
1785
                                'size' => $announcement->attachment_size,
1786
                                'filename' => $announcement->attachment_filename,
1787
                                'announcement_id' => $new_announcement_id,
1788
                            ];
1789
1790
                            $attachmentId = Database::insert($table_attachment, $params);
1791
1792
                            if ($attachmentId) {
1793
                                $sql = "UPDATE $table_attachment SET id = iid WHERE iid = $attachmentId";
1794
                                Database::query($sql);
1795
                            }
1796
                        }
1797
                    }
1798
                }
1799
            }
1800
        }
1801
    }
1802
1803
    /**
1804
     * Restore Quiz.
1805
     *
1806
     * @param int  $session_id
1807
     * @param bool $respect_base_content
1808
     */
1809
    public function restore_quizzes(
1810
        $session_id = 0,
1811
        $respect_base_content = false
1812
    ) {
1813
        if ($this->course->has_resources(RESOURCE_QUIZ)) {
1814
            $table_qui = Database::get_course_table(TABLE_QUIZ_TEST);
1815
            $table_rel = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
1816
            $table_doc = Database::get_course_table(TABLE_DOCUMENT);
1817
            $resources = $this->course->resources;
1818
1819
            foreach ($resources[RESOURCE_QUIZ] as $id => $quiz) {
1820
                if (isset($quiz->obj)) {
1821
                    // For new imports
1822
                    $quiz = $quiz->obj;
1823
                } else {
1824
                    // For backward compatibility
1825
                    $quiz->obj = $quiz;
1826
                }
1827
1828
                $doc = '';
1829
                if (!empty($quiz->sound)) {
1830
                    if (isset($this->course->resources[RESOURCE_DOCUMENT][$quiz->sound]) &&
1831
                        $this->course->resources[RESOURCE_DOCUMENT][$quiz->sound]->is_restored()) {
1832
                        $sql = "SELECT path FROM $table_doc
1833
                                WHERE
1834
                                    c_id = ".$this->destination_course_id.' AND
1835
                                    id = '.$resources[RESOURCE_DOCUMENT][$quiz->sound]->destination_id;
1836
                        $doc = Database::query($sql);
1837
                        $doc = Database::fetch_object($doc);
1838
                        $doc = str_replace('/audio/', '', $doc->path);
1839
                    }
1840
                }
1841
1842
                if (-1 != $id) {
1843
                    // check resources inside html from ckeditor tool and copy correct urls into recipient course
1844
                    $quiz->description = DocumentManager::replaceUrlWithNewCourseCode(
1845
                        $quiz->description,
1846
                        $this->course->code,
1847
                        $this->course->destination_path,
1848
                        $this->course->backup_path,
1849
                        $this->course->info['path']
1850
                    );
1851
1852
                    $quiz->start_time = '0000-00-00 00:00:00' == $quiz->start_time ? null : $quiz->start_time;
1853
                    $quiz->end_time = '0000-00-00 00:00:00' == $quiz->end_time ? null : $quiz->end_time;
1854
1855
                    global $_custom;
1856
                    if (isset($_custom['exercises_clean_dates_when_restoring']) &&
1857
                        $_custom['exercises_clean_dates_when_restoring']
1858
                    ) {
1859
                        $quiz->start_time = null;
1860
                        $quiz->end_time = null;
1861
                    }
1862
1863
                    $params = [
1864
                        'c_id' => $this->destination_course_id,
1865
                        'title' => self::DBUTF8($quiz->title),
1866
                        'description' => false === $quiz->description ? '' : self::DBUTF8($quiz->description),
1867
                        'type' => isset($quiz->quiz_type) ? (int) $quiz->quiz_type : $quiz->type,
1868
                        'random' => (int) $quiz->random,
1869
                        'active' => $quiz->active,
1870
                        'sound' => self::DBUTF8($doc),
1871
                        'max_attempt' => (int) $quiz->max_attempt,
1872
                        'results_disabled' => (int) $quiz->results_disabled,
1873
                        'access_condition' => $quiz->access_condition,
1874
                        'pass_percentage' => $quiz->pass_percentage,
1875
                        'feedback_type' => (int) $quiz->feedback_type,
1876
                        'random_answers' => (int) $quiz->random_answers,
1877
                        'random_by_category' => (int) $quiz->random_by_category,
1878
                        'review_answers' => (int) $quiz->review_answers,
1879
                        'propagate_neg' => (int) $quiz->propagate_neg,
1880
                        'text_when_finished' => (string) $quiz->text_when_finished,
1881
                        'expired_time' => (int) $quiz->expired_time,
1882
                        'start_time' => $quiz->start_time,
1883
                        'end_time' => $quiz->end_time,
1884
                        'save_correct_answers' => 0,
1885
                        'display_category_name' => 0,
1886
                        'save_correct_answers' => isset($quiz->save_correct_answers) ? $quiz->save_correct_answers : 0,
1887
                        'hide_question_title' => isset($quiz->hide_question_title) ? $quiz->hide_question_title : 0,
1888
                    ];
1889
1890
                    $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
1891
                    if ($allow) {
1892
                        $params['notifications'] = isset($quiz->notifications) ? $quiz->notifications : '';
1893
                    }
1894
1895
                    if ($respect_base_content) {
1896
                        $my_session_id = $quiz->session_id;
1897
                        if (!empty($quiz->session_id)) {
1898
                            $my_session_id = $session_id;
1899
                        }
1900
                        $params['session_id'] = $my_session_id;
1901
                    } else {
1902
                        if (!empty($session_id)) {
1903
                            $session_id = (int) $session_id;
1904
                            $params['session_id'] = $session_id;
1905
                        }
1906
                    }
1907
                    $new_id = Database::insert($table_qui, $params);
1908
1909
                    if ($new_id) {
1910
                        $sql = "UPDATE $table_qui SET id = iid WHERE iid = $new_id";
1911
                        Database::query($sql);
1912
                    }
1913
                } else {
1914
                    // $id = -1 identifies the fictionary test for collecting
1915
                    // orphan questions. We do not store it in the database.
1916
                    $new_id = -1;
1917
                }
1918
1919
                $this->course->resources[RESOURCE_QUIZ][$id]->destination_id = $new_id;
1920
                $order = 0;
1921
                if (!empty($quiz->question_ids)) {
1922
                    foreach ($quiz->question_ids as $index => $question_id) {
1923
                        $qid = $this->restore_quiz_question($question_id);
1924
                        $question_order = $quiz->question_orders[$index] ?: $order;
1925
                        $order++;
1926
                        $sql = "INSERT IGNORE INTO $table_rel SET
1927
                                c_id = ".$this->destination_course_id.",
1928
                                question_id = $qid ,
1929
                                exercice_id = $new_id ,
1930
                                question_order = ".$question_order;
1931
                        Database::query($sql);
1932
                    }
1933
                }
1934
            }
1935
        }
1936
    }
1937
1938
    /**
1939
     * Restore quiz-questions.
1940
     *
1941
     * @params int $id question id
1942
     */
1943
    public function restore_quiz_question($id)
1944
    {
1945
        $em = Database::getManager();
1946
        $resources = $this->course->resources;
1947
        /** @var QuizQuestion $question */
1948
        $question = isset($resources[RESOURCE_QUIZQUESTION][$id]) ? $resources[RESOURCE_QUIZQUESTION][$id] : null;
1949
        $new_id = 0;
1950
1951
        if (is_object($question)) {
1952
            if ($question->is_restored()) {
1953
                return $question->destination_id;
1954
            }
1955
            $table_que = Database::get_course_table(TABLE_QUIZ_QUESTION);
1956
            $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
1957
            $table_options = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1958
1959
            // check resources inside html from ckeditor tool and copy correct urls into recipient course
1960
            $question->description = DocumentManager::replaceUrlWithNewCourseCode(
1961
                $question->description,
1962
                $this->course->code,
1963
                $this->course->destination_path,
1964
                $this->course->backup_path,
1965
                $this->course->info['path']
1966
            );
1967
1968
            $imageNewId = '';
1969
            if (preg_match('/^quiz-.*$/', $question->picture) &&
1970
                isset($resources[RESOURCE_DOCUMENT]['image_quiz'][$question->picture])
1971
            ) {
1972
                $imageNewId = $resources[RESOURCE_DOCUMENT]['image_quiz'][$question->picture]['destination_id'];
1973
            } else {
1974
                if (isset($resources[RESOURCE_DOCUMENT][$question->picture])) {
1975
                    $documentsToRestore = $resources[RESOURCE_DOCUMENT][$question->picture];
1976
                    $imageNewId = $documentsToRestore->destination_id;
1977
                }
1978
            }
1979
            $question->question = DocumentManager::replaceUrlWithNewCourseCode(
1980
                $question->question,
1981
                $this->course->code,
1982
                $this->course->destination_path,
1983
                $this->course->backup_path,
1984
                $this->course->info['path']
1985
            );
1986
            $params = [
1987
                'c_id' => $this->destination_course_id,
1988
                'question' => self::DBUTF8($question->question),
1989
                'description' => false === $question->description ? '' : self::DBUTF8($question->description),
1990
                'ponderation' => self::DBUTF8($question->ponderation),
1991
                'position' => self::DBUTF8($question->position),
1992
                'type' => self::DBUTF8($question->quiz_type),
1993
                'picture' => self::DBUTF8($imageNewId),
1994
                'level' => self::DBUTF8($question->level),
1995
                'extra' => self::DBUTF8($question->extra),
1996
            ];
1997
1998
            $new_id = Database::insert($table_que, $params);
1999
2000
            if ($new_id) {
2001
                $sql = "UPDATE $table_que SET id = iid WHERE iid = $new_id";
2002
                Database::query($sql);
2003
            } else {
2004
                return 0;
2005
            }
2006
2007
            $correctAnswers = [];
2008
            $allAnswers = [];
2009
            $onlyAnswers = [];
2010
2011
            if (in_array($question->quiz_type, [DRAGGABLE, MATCHING, MATCHING_DRAGGABLE])) {
2012
                $tempAnswerList = $question->answers;
2013
                foreach ($tempAnswerList as &$value) {
2014
                    $value['answer'] = DocumentManager::replaceUrlWithNewCourseCode(
2015
                        $value['answer'],
2016
                        $this->course->code,
2017
                        $this->course->destination_path,
2018
                        $this->course->backup_path,
2019
                        $this->course->info['path']
2020
                    );
2021
                }
2022
                $allAnswers = array_column($tempAnswerList, 'answer', 'id');
2023
            }
2024
2025
            if (in_array($question->quiz_type, [MATCHING, MATCHING_DRAGGABLE])) {
2026
                $temp = [];
2027
                foreach ($question->answers as $index => $answer) {
2028
                    $temp[$answer['position']] = $answer;
2029
                }
2030
2031
                foreach ($temp as $index => $answer) {
2032
                    // check resources inside html from ckeditor tool and copy correct urls into recipient course
2033
                    $answer['answer'] = DocumentManager::replaceUrlWithNewCourseCode(
2034
                        $answer['answer'],
2035
                        $this->course->code,
2036
                        $this->course->destination_path,
2037
                        $this->course->backup_path,
2038
                        $this->course->info['path']
2039
                    );
2040
2041
                    $answer['comment'] = DocumentManager::replaceUrlWithNewCourseCode(
2042
                        $answer['comment'],
2043
                        $this->course->code,
2044
                        $this->course->destination_path,
2045
                        $this->course->backup_path,
2046
                        $this->course->info['path']
2047
                    );
2048
2049
                    $quizAnswer = new CQuizAnswer();
2050
                    $quizAnswer
2051
                        ->setCId($this->destination_course_id)
2052
                        ->setQuestionId($new_id)
2053
                        ->setAnswer(self::DBUTF8($answer['answer']))
2054
                        ->setCorrect($answer['correct'])
2055
                        ->setComment(false === $answer['comment'] ? '' : self::DBUTF8($answer['comment']))
2056
                        ->setPonderation($answer['ponderation'])
2057
                        ->setPosition($answer['position'])
2058
                        ->setHotspotCoordinates($answer['hotspot_coordinates'])
2059
                        ->setHotspotType($answer['hotspot_type'])
2060
                        ->setIdAuto(0);
2061
2062
                    $em->persist($quizAnswer);
2063
                    $em->flush();
2064
2065
                    $answerId = $quizAnswer->getIid();
2066
2067
                    if ($answerId) {
2068
                        $quizAnswer
2069
                            ->setId($answerId)
2070
                            ->setIdAuto($answerId);
2071
                        $em->merge($quizAnswer);
2072
                        $em->flush();
2073
2074
                        $correctAnswers[$answerId] = $answer['correct'];
2075
                        $onlyAnswers[$answerId] = $answer['answer'];
2076
                    }
2077
                }
2078
            } else {
2079
                foreach ($question->answers as $index => $answer) {
2080
                    // check resources inside html from ckeditor tool and copy correct urls into recipient course
2081
                    $answer['answer'] = DocumentManager::replaceUrlWithNewCourseCode(
2082
                        $answer['answer'],
2083
                        $this->course->code,
2084
                        $this->course->destination_path,
2085
                        $this->course->backup_path,
2086
                        $this->course->info['path']
2087
                    );
2088
2089
                    $answer['comment'] = DocumentManager::replaceUrlWithNewCourseCode(
2090
                        $answer['comment'],
2091
                        $this->course->code,
2092
                        $this->course->destination_path,
2093
                        $this->course->backup_path,
2094
                        $this->course->info['path']
2095
                    );
2096
2097
                    $params = [
2098
                        'c_id' => $this->destination_course_id,
2099
                        'question_id' => $new_id,
2100
                        'answer' => self::DBUTF8($answer['answer']),
2101
                        'correct' => $answer['correct'],
2102
                        'comment' => false === $answer['comment'] ? '' : self::DBUTF8($answer['comment']),
2103
                        'ponderation' => $answer['ponderation'],
2104
                        'position' => $answer['position'],
2105
                        'hotspot_coordinates' => $answer['hotspot_coordinates'],
2106
                        'hotspot_type' => $answer['hotspot_type'],
2107
                        'id_auto' => 0,
2108
                        'destination' => '',
2109
                    ];
2110
2111
                    $answerId = Database::insert($table_ans, $params);
2112
2113
                    if ($answerId) {
2114
                        $sql = "UPDATE $table_ans SET id = iid, id_auto = iid WHERE iid = $answerId";
2115
                        Database::query($sql);
2116
                    }
2117
2118
                    $correctAnswers[$answerId] = $answer['correct'];
2119
                    $onlyAnswers[$answerId] = $answer['answer'];
2120
                }
2121
            }
2122
2123
            // Current course id
2124
            $course_id = api_get_course_int_id();
2125
2126
            // Moving quiz_question_options
2127
            if (MULTIPLE_ANSWER_TRUE_FALSE == $question->quiz_type) {
2128
                $question_option_list = Question::readQuestionOption($id, $course_id);
2129
2130
                // Question copied from the current platform
2131
                if ($question_option_list) {
2132
                    $old_option_ids = [];
2133
                    foreach ($question_option_list as $item) {
2134
                        $old_id = $item['id'];
2135
                        unset($item['id']);
2136
                        if (isset($item['iid'])) {
2137
                            unset($item['iid']);
2138
                        }
2139
                        $item['question_id'] = $new_id;
2140
                        $item['c_id'] = $this->destination_course_id;
2141
                        $question_option_id = Database::insert($table_options, $item);
2142
                        if ($question_option_id) {
2143
                            $old_option_ids[$old_id] = $question_option_id;
2144
                            $sql = "UPDATE $table_options SET id = iid WHERE iid = $question_option_id";
2145
                            Database::query($sql);
2146
                        }
2147
                    }
2148
                    if ($old_option_ids) {
2149
                        $new_answers = Database::select(
2150
                            'iid, correct',
2151
                            $table_ans,
2152
                            [
2153
                                'WHERE' => [
2154
                                    'question_id = ? AND c_id = ? ' => [
2155
                                        $new_id,
2156
                                        $this->destination_course_id,
2157
                                    ],
2158
                                ],
2159
                            ]
2160
                        );
2161
2162
                        foreach ($new_answers as $answer_item) {
2163
                            $params = [];
2164
                            $params['correct'] = $old_option_ids[$answer_item['correct']];
2165
                            Database::update(
2166
                                $table_ans,
2167
                                $params,
2168
                                [
2169
                                    'iid = ? AND c_id = ? AND question_id = ? ' => [
2170
                                        $answer_item['iid'],
2171
                                        $this->destination_course_id,
2172
                                        $new_id,
2173
                                    ],
2174
                                ],
2175
                                false
2176
                            );
2177
                        }
2178
                    }
2179
                } else {
2180
                    $new_options = [];
2181
                    if (isset($question->question_options)) {
2182
                        foreach ($question->question_options as $obj) {
2183
                            $item = [];
2184
                            $item['question_id'] = $new_id;
2185
                            $item['c_id'] = $this->destination_course_id;
2186
                            $item['name'] = $obj->obj->name;
2187
                            $item['position'] = $obj->obj->position;
2188
                            $question_option_id = Database::insert($table_options, $item);
2189
2190
                            if ($question_option_id) {
2191
                                $new_options[$obj->obj->id] = $question_option_id;
2192
                                $sql = "UPDATE $table_options SET id = iid WHERE iid = $question_option_id";
2193
                                Database::query($sql);
2194
                            }
2195
                        }
2196
2197
                        foreach ($correctAnswers as $answer_id => $correct_answer) {
2198
                            $params = [];
2199
                            $params['correct'] = isset($new_options[$correct_answer]) ? $new_options[$correct_answer] : '';
2200
                            Database::update(
2201
                                $table_ans,
2202
                                $params,
2203
                                [
2204
                                    'id = ? AND c_id = ? AND question_id = ? ' => [
2205
                                        $answer_id,
2206
                                        $this->destination_course_id,
2207
                                        $new_id,
2208
                                    ],
2209
                                ],
2210
                                false
2211
                            );
2212
                        }
2213
                    }
2214
                }
2215
            }
2216
2217
            // Fix correct answers
2218
            if (in_array($question->quiz_type, [DRAGGABLE, MATCHING, MATCHING_DRAGGABLE])) {
2219
                foreach ($correctAnswers as $answer_id => $correct_answer) {
2220
                    $params = [];
2221
2222
                    if (isset($allAnswers[$correct_answer])) {
2223
                        $correct = '';
2224
                        foreach ($onlyAnswers as $key => $value) {
2225
                            if ($value == $allAnswers[$correct_answer]) {
2226
                                $correct = $key;
2227
2228
                                break;
2229
                            }
2230
                        }
2231
2232
                        $params['correct'] = $correct;
2233
                        Database::update(
2234
                            $table_ans,
2235
                            $params,
2236
                            [
2237
                                'id = ? AND c_id = ? AND question_id = ? ' => [
2238
                                    $answer_id,
2239
                                    $this->destination_course_id,
2240
                                    $new_id,
2241
                                ],
2242
                            ]
2243
                        );
2244
                    }
2245
                }
2246
            }
2247
2248
            $this->course->resources[RESOURCE_QUIZQUESTION][$id]->destination_id = $new_id;
2249
        }
2250
2251
        return $new_id;
2252
    }
2253
2254
    /**
2255
     * @todo : add session id when used for session
2256
     */
2257
    public function restore_test_category($session_id, $respect_base_content, $destination_course_code)
2258
    {
2259
        if (!empty($session_id)) {
2260
            return false;
2261
        }
2262
        $destinationCourseId = $this->destination_course_info['real_id'];
2263
        // Let's restore the categories
2264
        $categoryOldVsNewList = []; // used to build the quiz_question_rel_category table
2265
        if ($this->course->has_resources(RESOURCE_TEST_CATEGORY)) {
2266
            $resources = $this->course->resources;
2267
            foreach ($resources[RESOURCE_TEST_CATEGORY] as $id => $courseCopyTestCategory) {
2268
                $categoryOldVsNewList[$courseCopyTestCategory->source_id] = $id;
2269
                // check if this test_category already exist in the destination BDD
2270
                // do not Database::escape_string $title and $description, it will be done later
2271
                $title = $courseCopyTestCategory->title;
2272
                $description = $courseCopyTestCategory->description;
2273
                if (TestCategory::categoryTitleExists($title, $destinationCourseId)) {
2274
                    switch ($this->file_option) {
2275
                        case FILE_SKIP:
2276
                            //Do nothing
2277
                            break;
2278
                        case FILE_RENAME:
2279
                            $new_title = $title.'_';
2280
                            while (TestCategory::categoryTitleExists($new_title, $destinationCourseId)) {
2281
                                $new_title .= '_';
2282
                            }
2283
                            $test_category = new TestCategory();
2284
                            $test_category->name = $new_title;
2285
                            $test_category->description = $description;
2286
                            $new_id = $test_category->save($destinationCourseId);
2287
                            $categoryOldVsNewList[$courseCopyTestCategory->source_id] = $new_id;
2288
2289
                            break;
2290
                        case FILE_OVERWRITE:
2291
                            // get category from source
2292
                            $destinationCategoryId = TestCategory::get_category_id_for_title(
2293
                                $title,
2294
                                $destinationCourseId
2295
                            );
2296
                            if ($destinationCategoryId) {
2297
                                $my_cat = new TestCategory();
2298
                                $my_cat = $my_cat->getCategory($destinationCategoryId, $destinationCourseId);
2299
                                $my_cat->name = $title;
2300
                                $my_cat->description = $description;
2301
                                $my_cat->modifyCategory($destinationCourseId);
2302
                                $categoryOldVsNewList[$courseCopyTestCategory->source_id] = $destinationCategoryId;
2303
                            }
2304
2305
                            break;
2306
                    }
2307
                } else {
2308
                    // create a new test_category
2309
                    $test_category = new TestCategory();
2310
                    $test_category->name = $title;
2311
                    $test_category->description = $description;
2312
                    $new_id = $test_category->save($destinationCourseId);
2313
                    $categoryOldVsNewList[$courseCopyTestCategory->source_id] = $new_id;
2314
                }
2315
                $this->course->resources[RESOURCE_TEST_CATEGORY][$id]->destination_id = $categoryOldVsNewList[$courseCopyTestCategory->source_id];
2316
            }
2317
        }
2318
2319
        // lets check if quizzes-question are restored too,
2320
        // to redo the link between test_category and quizzes question for questions restored
2321
        // we can use the source_id field
2322
        // question source_id => category source_id
2323
        if ($this->course->has_resources(RESOURCE_QUIZQUESTION)) {
2324
            // check the category number of each question restored
2325
            if (!empty($resources[RESOURCE_QUIZQUESTION])) {
2326
                foreach ($resources[RESOURCE_QUIZQUESTION] as $id => $courseCopyQuestion) {
2327
                    $newQuestionId = $resources[RESOURCE_QUIZQUESTION][$id]->destination_id;
2328
                    $questionCategoryId = $courseCopyQuestion->question_category;
2329
                    if ($newQuestionId > 0 &&
2330
                        $questionCategoryId > 0 &&
2331
                        isset($categoryOldVsNewList[$questionCategoryId])
2332
                    ) {
2333
                        TestCategory::addCategoryToQuestion(
2334
                            $categoryOldVsNewList[$questionCategoryId],
2335
                            $newQuestionId,
2336
                            $destinationCourseId
2337
                        );
2338
                    }
2339
                }
2340
            }
2341
        }
2342
    }
2343
2344
    /**
2345
     * Restore surveys.
2346
     *
2347
     * @param int $sessionId Optional. The session id
2348
     */
2349
    public function restore_surveys($sessionId = 0)
2350
    {
2351
        $sessionId = (int) $sessionId;
2352
        if ($this->course->has_resources(RESOURCE_SURVEY)) {
2353
            $table_sur = Database::get_course_table(TABLE_SURVEY);
2354
            $table_que = Database::get_course_table(TABLE_SURVEY_QUESTION);
2355
            $table_ans = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2356
            $resources = $this->course->resources;
2357
            foreach ($resources[RESOURCE_SURVEY] as $id => $survey) {
2358
                $sql = 'SELECT survey_id FROM '.$table_sur.'
2359
                        WHERE
2360
                            c_id = '.$this->destination_course_id.' AND
2361
                            code = "'.self::DBUTF8escapestring($survey->code).'" AND
2362
                            lang = "'.self::DBUTF8escapestring($survey->lang).'" ';
2363
2364
                $result_check = Database::query($sql);
2365
2366
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
2367
                $survey->title = DocumentManager::replaceUrlWithNewCourseCode(
2368
                    $survey->title,
2369
                    $this->course->code,
2370
                    $this->course->destination_path,
2371
                    $this->course->backup_path,
2372
                    $this->course->info['path']
2373
                );
2374
2375
                $survey->subtitle = DocumentManager::replaceUrlWithNewCourseCode(
2376
                    $survey->subtitle,
2377
                    $this->course->code,
2378
                    $this->course->destination_path,
2379
                    $this->course->backup_path,
2380
                    $this->course->info['path']
2381
                );
2382
2383
                $survey->intro = DocumentManager::replaceUrlWithNewCourseCode(
2384
                    $survey->intro,
2385
                    $this->course->code,
2386
                    $this->course->destination_path,
2387
                    $this->course->backup_path,
2388
                    $this->course->info['path']
2389
                );
2390
2391
                $survey->surveythanks = DocumentManager::replaceUrlWithNewCourseCode(
2392
                    $survey->surveythanks,
2393
                    $this->course->code,
2394
                    $this->course->destination_path,
2395
                    $this->course->backup_path,
2396
                    $this->course->info['path']
2397
                );
2398
2399
                $params = [
2400
                    'c_id' => $this->destination_course_id,
2401
                    'code' => self::DBUTF8($survey->code),
2402
                    'title' => false === $survey->title ? '' : self::DBUTF8($survey->title),
2403
                    'subtitle' => false === $survey->subtitle ? '' : self::DBUTF8($survey->subtitle),
2404
                    'author' => self::DBUTF8($survey->author),
2405
                    'lang' => self::DBUTF8($survey->lang),
2406
                    'avail_from' => self::DBUTF8($survey->avail_from),
2407
                    'avail_till' => self::DBUTF8($survey->avail_till),
2408
                    'is_shared' => self::DBUTF8($survey->is_shared),
2409
                    'template' => self::DBUTF8($survey->template),
2410
                    'intro' => false === $survey->intro ? '' : self::DBUTF8($survey->intro),
2411
                    'surveythanks' => false === $survey->surveythanks ? '' : self::DBUTF8($survey->surveythanks),
2412
                    'creation_date' => self::DBUTF8($survey->creation_date),
2413
                    'invited' => '0',
2414
                    'answered' => '0',
2415
                    'invite_mail' => self::DBUTF8($survey->invite_mail),
2416
                    'reminder_mail' => self::DBUTF8($survey->reminder_mail),
2417
                    'session_id' => $sessionId,
2418
                    'one_question_per_page' => isset($survey->one_question_per_page) ? $survey->one_question_per_page : 0,
2419
                    'shuffle' => isset($survey->suffle) ? $survey->suffle : 0,
2420
                ];
2421
2422
                // An existing survey exists with the same code and the same language
2423
                if (1 == Database::num_rows($result_check)) {
2424
                    switch ($this->file_option) {
2425
                        case FILE_SKIP:
2426
                            //Do nothing
2427
                            break;
2428
                        case FILE_RENAME:
2429
                            $survey_code = $survey->code.'_';
2430
                            $i = 1;
2431
                            $temp_survey_code = $survey_code.$i;
2432
                            while (!$this->is_survey_code_available($temp_survey_code)) {
2433
                                $temp_survey_code = $survey_code.++$i;
2434
                            }
2435
                            $survey_code = $temp_survey_code;
2436
2437
                            $params['code'] = $survey_code;
2438
                            $new_id = Database::insert($table_sur, $params);
2439
                            if ($new_id) {
2440
                                $sql = "UPDATE $table_sur SET survey_id = iid WHERE iid = $new_id";
2441
                                Database::query($sql);
2442
2443
                                $this->course->resources[RESOURCE_SURVEY][$id]->destination_id = $new_id;
2444
                                foreach ($survey->question_ids as $index => $question_id) {
2445
                                    $qid = $this->restore_survey_question($question_id, $new_id);
2446
                                    $sql = "UPDATE $table_que SET survey_id = $new_id
2447
                                            WHERE c_id = ".$this->destination_course_id." AND question_id = $qid";
2448
                                    Database::query($sql);
2449
                                    $sql = "UPDATE $table_ans SET survey_id = $new_id
2450
                                            WHERE  c_id = ".$this->destination_course_id." AND  question_id = $qid";
2451
                                    Database::query($sql);
2452
                                }
2453
                            }
2454
2455
                            break;
2456
                        case FILE_OVERWRITE:
2457
                            // Delete the existing survey with the same code and language and
2458
                            // import the one of the source course
2459
                            // getting the information of the survey (used for when the survey is shared)
2460
                            $sql = "SELECT * FROM $table_sur
2461
                                    WHERE
2462
                                        c_id = ".$this->destination_course_id." AND
2463
                                        survey_id='".self::DBUTF8escapestring(Database::result($result_check, 0, 0))."'";
2464
                            $result = Database::query($sql);
2465
                            $survey_data = Database::fetch_array($result, 'ASSOC');
2466
2467
                            // if the survey is shared => also delete the shared content
2468
                            if (isset($survey_data['survey_share']) && is_numeric($survey_data['survey_share'])) {
2469
                                SurveyManager::delete_survey(
2470
                                    $survey_data['survey_share'],
2471
                                    true,
2472
                                    $this->destination_course_id
2473
                                );
2474
                            }
2475
                            SurveyManager::delete_survey(
2476
                                $survey_data['survey_id'],
2477
                                false,
2478
                                $this->destination_course_id
2479
                            );
2480
2481
                            // Insert the new source survey
2482
                            $new_id = Database::insert($table_sur, $params);
2483
2484
                            if ($new_id) {
2485
                                $sql = "UPDATE $table_sur SET survey_id = iid WHERE iid = $new_id";
2486
                                Database::query($sql);
2487
2488
                                $this->course->resources[RESOURCE_SURVEY][$id]->destination_id = $new_id;
2489
                                foreach ($survey->question_ids as $index => $question_id) {
2490
                                    $qid = $this->restore_survey_question(
2491
                                        $question_id,
2492
                                        $new_id
2493
                                    );
2494
                                    $sql = "UPDATE $table_que SET survey_id = $new_id
2495
                                            WHERE c_id = ".$this->destination_course_id." AND question_id = $qid";
2496
                                    Database::query($sql);
2497
                                    $sql = "UPDATE $table_ans SET survey_id = $new_id
2498
                                            WHERE c_id = ".$this->destination_course_id." AND question_id = $qid";
2499
                                    Database::query($sql);
2500
                                }
2501
                            }
2502
2503
                            break;
2504
                        default:
2505
                            break;
2506
                    }
2507
                } else {
2508
                    // No existing survey with the same language and the same code, we just copy the survey
2509
                    $new_id = Database::insert($table_sur, $params);
2510
2511
                    if ($new_id) {
2512
                        $sql = "UPDATE $table_sur SET survey_id = iid WHERE iid = $new_id";
2513
                        Database::query($sql);
2514
2515
                        $this->course->resources[RESOURCE_SURVEY][$id]->destination_id = $new_id;
2516
                        foreach ($survey->question_ids as $index => $question_id) {
2517
                            $qid = $this->restore_survey_question(
2518
                                $question_id,
2519
                                $new_id
2520
                            );
2521
                            $sql = "UPDATE $table_que SET survey_id = $new_id
2522
                                    WHERE c_id = ".$this->destination_course_id." AND question_id = $qid";
2523
                            Database::query($sql);
2524
                            $sql = "UPDATE $table_ans SET survey_id = $new_id
2525
                                    WHERE c_id = ".$this->destination_course_id." AND question_id = $qid";
2526
                            Database::query($sql);
2527
                        }
2528
                    }
2529
                }
2530
            }
2531
        }
2532
    }
2533
2534
    /**
2535
     * Check availability of a survey code.
2536
     *
2537
     * @param string $survey_code
2538
     *
2539
     * @return bool
2540
     */
2541
    public function is_survey_code_available($survey_code)
2542
    {
2543
        $table_sur = Database::get_course_table(TABLE_SURVEY);
2544
        $sql = "SELECT * FROM $table_sur
2545
                WHERE
2546
                    c_id = ".$this->destination_course_id." AND
2547
                    code = '".self::DBUTF8escapestring($survey_code)."'";
2548
        $result = Database::query($sql);
2549
        if (Database::num_rows($result) > 0) {
2550
            return false;
2551
        } else {
2552
            return true;
2553
        }
2554
    }
2555
2556
    /**
2557
     * Restore survey-questions.
2558
     *
2559
     * @param int    $id
2560
     * @param string $survey_id
2561
     */
2562
    public function restore_survey_question($id, $survey_id)
2563
    {
2564
        $resources = $this->course->resources;
2565
        $question = $resources[RESOURCE_SURVEYQUESTION][$id];
2566
        $new_id = 0;
2567
2568
        if (is_object($question)) {
2569
            if ($question->is_restored()) {
2570
                return $question->destination_id;
2571
            }
2572
            $table_que = Database::get_course_table(TABLE_SURVEY_QUESTION);
2573
            $table_ans = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2574
2575
            // check resources inside html from ckeditor tool and copy correct urls into recipient course
2576
            $question->survey_question = DocumentManager::replaceUrlWithNewCourseCode(
2577
                $question->survey_question,
2578
                $this->course->code,
2579
                $this->course->destination_path,
2580
                $this->course->backup_path,
2581
                $this->course->info['path']
2582
            );
2583
2584
            $params = [
2585
                'c_id' => $this->destination_course_id,
2586
                'survey_id' => self::DBUTF8($survey_id),
2587
                'survey_question' => false === $question->survey_question ? '' : self::DBUTF8($question->survey_question),
2588
                'survey_question_comment' => self::DBUTF8($question->survey_question_comment),
2589
                'type' => self::DBUTF8($question->survey_question_type),
2590
                'display' => self::DBUTF8($question->display),
2591
                'sort' => self::DBUTF8($question->sort),
2592
                'shared_question_id' => self::DBUTF8($question->shared_question_id),
2593
                'max_value' => self::DBUTF8($question->max_value),
2594
            ];
2595
            if (api_get_configuration_value('allow_required_survey_questions')) {
2596
                if (isset($question->is_required)) {
2597
                    $params['is_required'] = $question->is_required;
2598
                }
2599
            }
2600
2601
            $new_id = Database::insert($table_que, $params);
2602
            if ($new_id) {
2603
                $sql = "UPDATE $table_que SET question_id = iid WHERE iid = $new_id";
2604
                Database::query($sql);
2605
2606
                foreach ($question->answers as $index => $answer) {
2607
                    // check resources inside html from ckeditor tool and copy correct urls into recipient course
2608
                    $answer['option_text'] = DocumentManager::replaceUrlWithNewCourseCode(
2609
                        $answer['option_text'],
2610
                        $this->course->code,
2611
                        $this->course->destination_path,
2612
                        $this->course->backup_path,
2613
                        $this->course->info['path']
2614
                    );
2615
2616
                    $params = [
2617
                        'c_id' => $this->destination_course_id,
2618
                        'question_id' => $new_id,
2619
                        'option_text' => false === $answer['option_text'] ? '' : self::DBUTF8($answer['option_text']),
2620
                        'sort' => $answer['sort'],
2621
                        'survey_id' => self::DBUTF8($survey_id),
2622
                    ];
2623
                    $answerId = Database::insert($table_ans, $params);
2624
                    if ($answerId) {
2625
                        $sql = "UPDATE $table_ans SET question_option_id = iid
2626
                                WHERE iid = $answerId";
2627
                        Database::query($sql);
2628
                    }
2629
                }
2630
                $this->course->resources[RESOURCE_SURVEYQUESTION][$id]->destination_id = $new_id;
2631
            }
2632
        }
2633
2634
        return $new_id;
2635
    }
2636
2637
    /**
2638
     * @param int  $sessionId
2639
     * @param bool $baseContent
2640
     */
2641
    public function restore_learnpath_category($sessionId = 0, $baseContent = false)
2642
    {
2643
        $reuseExisting = false;
2644
2645
        if (isset($this->tool_copy_settings['learnpath_category']) &&
2646
            isset($this->tool_copy_settings['learnpath_category']['reuse_existing']) &&
2647
            true === $this->tool_copy_settings['learnpath_category']['reuse_existing']
2648
        ) {
2649
            $reuseExisting = true;
2650
        }
2651
2652
        $tblLpCategory = Database::get_course_table(TABLE_LP_CATEGORY);
2653
2654
        if ($this->course->has_resources(RESOURCE_LEARNPATH_CATEGORY)) {
2655
            $resources = $this->course->resources;
2656
            /** @var LearnPathCategory $item */
2657
            foreach ($resources[RESOURCE_LEARNPATH_CATEGORY] as $id => $item) {
2658
                /** @var CLpCategory $lpCategory */
2659
                $lpCategory = $item->object;
2660
2661
                if ($lpCategory) {
2662
                    $categoryId = 0;
2663
2664
                    $existingLpCategory = Database::select(
2665
                        'iid',
2666
                        $tblLpCategory,
2667
                        [
2668
                            'WHERE' => [
2669
                                'c_id = ? AND name = ?' => [$this->destination_course_id, $lpCategory->getName()],
2670
                            ],
2671
                        ],
2672
                        'first'
2673
                    );
2674
2675
                    if ($reuseExisting && !empty($existingLpCategory)) {
2676
                        $categoryId = $existingLpCategory['iid'];
2677
                    } else {
2678
                        $values = [
2679
                            'c_id' => $this->destination_course_id,
2680
                            'name' => $lpCategory->getName(),
2681
                        ];
2682
                        $categoryId = \learnpath::createCategory($values);
2683
                    }
2684
2685
                    if ($categoryId) {
2686
                        $this->course->resources[RESOURCE_LEARNPATH_CATEGORY][$id]->destination_id = $categoryId;
2687
                    }
2688
                }
2689
            }
2690
        }
2691
    }
2692
2693
    /**
2694
     * Restoring learning paths.
2695
     *
2696
     * @param int        $session_id
2697
     * @param bool|false $respect_base_content
2698
     */
2699
    public function restore_learnpaths($session_id = 0, $respect_base_content = false)
2700
    {
2701
        $session_id = (int) $session_id;
2702
        if ($this->course->has_resources(RESOURCE_LEARNPATH)) {
2703
            $table_main = Database::get_course_table(TABLE_LP_MAIN);
2704
            $table_item = Database::get_course_table(TABLE_LP_ITEM);
2705
            $table_tool = Database::get_course_table(TABLE_TOOL_LIST);
2706
2707
            $resources = $this->course->resources;
2708
            $origin_path = $this->course->backup_path.'/upload/learning_path/images/';
2709
            $destination_path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/upload/learning_path/images/';
2710
2711
            // Choose default visibility
2712
            $toolVisibility = api_get_setting('tool_visible_by_default_at_creation');
2713
            $defaultLpVisibility = 'invisible';
2714
            if (isset($toolVisibility['learning_path']) && 'true' == $toolVisibility['learning_path']) {
2715
                $defaultLpVisibility = 'visible';
2716
            }
2717
2718
            foreach ($resources[RESOURCE_LEARNPATH] as $id => $lp) {
2719
                $condition_session = '';
2720
                if (!empty($session_id)) {
2721
                    if ($respect_base_content) {
2722
                        $my_session_id = $lp->session_id;
2723
                        if (!empty($lp->session_id)) {
2724
                            $my_session_id = $session_id;
2725
                        }
2726
                        $condition_session = $my_session_id;
2727
                    } else {
2728
                        $session_id = (int) $session_id;
2729
                        $condition_session = $session_id;
2730
                    }
2731
                }
2732
2733
                // Adding the author's image
2734
                if (!empty($lp->preview_image)) {
2735
                    $new_filename = uniqid('').substr(
2736
                        $lp->preview_image,
2737
                        strlen($lp->preview_image) - 7,
2738
                        strlen($lp->preview_image)
2739
                    );
2740
2741
                    if (file_exists($origin_path.$lp->preview_image) &&
2742
                        !is_dir($origin_path.$lp->preview_image)
2743
                    ) {
2744
                        $copy_result = copy(
2745
                            $origin_path.$lp->preview_image,
2746
                            $destination_path.$new_filename
2747
                        );
2748
                        if ($copy_result) {
2749
                            $lp->preview_image = $new_filename;
2750
                            // Create 64 version from original
2751
                            $temp = new \Image($destination_path.$new_filename);
2752
                            $temp->resize(64);
2753
                            $pathInfo = pathinfo($new_filename);
2754
                            if ($pathInfo) {
2755
                                $filename = $pathInfo['filename'];
2756
                                $extension = $pathInfo['extension'];
2757
                                $temp->send_image($destination_path.'/'.$filename.'.64.'.$extension);
2758
                            }
2759
                        } else {
2760
                            $lp->preview_image = '';
2761
                        }
2762
                    }
2763
                }
2764
2765
                if ($this->add_text_in_items) {
2766
                    $lp->name .= ' '.get_lang('Copy');
2767
                }
2768
2769
                if (isset($this->tool_copy_settings['learnpaths'])) {
2770
                    if (isset($this->tool_copy_settings['learnpaths']['reset_dates']) &&
2771
                        $this->tool_copy_settings['learnpaths']['reset_dates']
2772
                    ) {
2773
                        $lp->created_on = api_get_utc_datetime();
2774
                        $lp->modified_on = api_get_utc_datetime();
2775
                        $lp->publicated_on = null;
2776
                    }
2777
                }
2778
2779
                $lp->expired_on = isset($lp->expired_on) && '0000-00-00 00:00:00' === $lp->expired_on ? null : $lp->expired_on;
2780
                $lp->publicated_on = isset($lp->publicated_on) && '0000-00-00 00:00:00' === $lp->publicated_on ? null : $lp->publicated_on;
2781
2782
                if (isset($lp->categoryId)) {
2783
                    $lp->categoryId = (int) $lp->categoryId;
2784
                }
2785
2786
                $categoryId = 0;
2787
                if (!empty($lp->categoryId)) {
2788
                    if (isset($resources[RESOURCE_LEARNPATH_CATEGORY][$lp->categoryId])) {
2789
                        $categoryId = $resources[RESOURCE_LEARNPATH_CATEGORY][$lp->categoryId]->destination_id;
2790
                    }
2791
                }
2792
                $params = [
2793
                    'c_id' => $this->destination_course_id,
2794
                    'lp_type' => $lp->lp_type,
2795
                    'name' => self::DBUTF8($lp->name),
2796
                    'path' => self::DBUTF8($lp->path),
2797
                    'ref' => $lp->ref,
2798
                    'description' => self::DBUTF8($lp->description),
2799
                    'content_local' => self::DBUTF8($lp->content_local),
2800
                    'default_encoding' => self::DBUTF8($lp->default_encoding),
2801
                    'default_view_mod' => self::DBUTF8($lp->default_view_mod),
2802
                    'prevent_reinit' => self::DBUTF8($lp->prevent_reinit),
2803
                    'force_commit' => self::DBUTF8($lp->force_commit),
2804
                    'content_maker' => self::DBUTF8($lp->content_maker),
2805
                    'display_order' => self::DBUTF8($lp->display_order),
2806
                    'js_lib' => self::DBUTF8($lp->js_lib),
2807
                    'content_license' => self::DBUTF8($lp->content_license),
2808
                    'author' => self::DBUTF8($lp->author),
2809
                    //'preview_image' => self::DBUTF8($lp->preview_image),
2810
                    'use_max_score' => self::DBUTF8($lp->use_max_score),
2811
                    'autolaunch' => self::DBUTF8(isset($lp->autolaunch) ? $lp->autolaunch : ''),
2812
                    'created_on' => empty($lp->created_on) ? api_get_utc_datetime() : self::DBUTF8($lp->created_on),
2813
                    'modified_on' => empty($lp->modified_on) ? api_get_utc_datetime() : self::DBUTF8($lp->modified_on),
2814
                    'publicated_on' => empty($lp->publicated_on) ? api_get_utc_datetime() : self::DBUTF8($lp->publicated_on),
2815
                    'expired_on' => self::DBUTF8($lp->expired_on),
2816
                    'debug' => self::DBUTF8($lp->debug),
2817
                    'theme' => '',
2818
                    'session_id' => $session_id,
2819
                    'prerequisite' => 0,
2820
                    'hide_toc_frame' => 0,
2821
                    'seriousgame_mode' => 0,
2822
                    'category_id' => $categoryId,
2823
                    'max_attempts' => 0,
2824
                    'subscribe_users' => 0,
2825
                ];
2826
2827
                if (!empty($condition_session)) {
2828
                    $params['session_id'] = $condition_session;
2829
                }
2830
2831
                $new_lp_id = Database::insert($table_main, $params);
2832
2833
                if ($new_lp_id) {
2834
                    // The following only makes sense if a new LP was
2835
                    // created in the destination course
2836
                    $sql = "UPDATE $table_main SET id = iid WHERE iid = $new_lp_id";
2837
                    Database::query($sql);
2838
2839
                    if ($lp->visibility) {
2840
                        $params = [
2841
                            'c_id' => $this->destination_course_id,
2842
                            'name' => self::DBUTF8($lp->name),
2843
                            'link' => "lp/lp_controller.php?action=view&lp_id=$new_lp_id&sid=$session_id",
2844
                            'image' => 'scormbuilder.gif',
2845
                            'visibility' => '0',
2846
                            'admin' => '0',
2847
                            'address' => 'squaregrey.gif',
2848
                            'session_id' => $session_id,
2849
                        ];
2850
                        $insertId = Database::insert($table_tool, $params);
2851
                        if ($insertId) {
2852
                            $sql = "UPDATE $table_tool SET id = iid WHERE iid = $insertId";
2853
                            Database::query($sql);
2854
                        }
2855
                    }
2856
2857
                    if (isset($lp->extraFields) && !empty($lp->extraFields)) {
2858
                        $extraFieldValue = new \ExtraFieldValue('lp');
2859
                        foreach ($lp->extraFields as $extraField) {
2860
                            $params = [
2861
                                'item_id' => $new_lp_id,
2862
                                'value' => $extraField['value'],
2863
                                'variable' => $extraField['variable'],
2864
                            ];
2865
                            $extraFieldValue->save($params);
2866
                        }
2867
                    }
2868
                    api_item_property_update(
2869
                        $this->destination_course_info,
2870
                        TOOL_LEARNPATH,
2871
                        $new_lp_id,
2872
                        'LearnpathAdded',
2873
                        api_get_user_id(),
2874
                        0,
2875
                        0,
2876
                        0,
2877
                        0,
2878
                        $session_id
2879
                    );
2880
2881
                    // Set the new LP to visible
2882
                    api_item_property_update(
2883
                        $this->destination_course_info,
2884
                        TOOL_LEARNPATH,
2885
                        $new_lp_id,
2886
                        $defaultLpVisibility,
2887
                        api_get_user_id(),
2888
                        0,
2889
                        0,
2890
                        0,
2891
                        0,
2892
                        $session_id
2893
                    );
2894
2895
                    $new_item_ids = [];
2896
                    $parent_item_ids = [];
2897
                    $previous_item_ids = [];
2898
                    $next_item_ids = [];
2899
                    $old_prerequisite = [];
2900
                    $old_refs = [];
2901
                    $prerequisite_ids = [];
2902
2903
                    foreach ($lp->get_items() as $index => $item) {
2904
                        // we set the ref code here and then we update in a for loop
2905
                        $ref = $item['ref'];
2906
2907
                        // Dealing with path the same way as ref as some data has
2908
                        // been put into path when it's a local resource
2909
                        // Only fix the path for no scos
2910
                        if ('sco' == $item['item_type']) {
2911
                            $path = $item['path'];
2912
                        } else {
2913
                            $path = $this->get_new_id($item['item_type'], $item['path']);
2914
                        }
2915
2916
                        $item['item_type'] = 'dokeos_chapter' == $item['item_type'] ? 'dir' : $item['item_type'];
2917
2918
                        $masteryScore = $item['mastery_score'];
2919
                        // If item is a chamilo quiz, then use the max score as mastery_score
2920
                        if ('quiz' == $item['item_type']) {
2921
                            if (empty($masteryScore)) {
2922
                                $masteryScore = $item['max_score'];
2923
                            }
2924
                        }
2925
2926
                        $prerequisiteMinScore = $item['prerequisite_min_score'] ?? null;
2927
                        $prerequisiteMaxScore = $item['prerequisite_max_score'] ?? null;
2928
                        $params = [
2929
                            'c_id' => $this->destination_course_id,
2930
                            'lp_id' => self::DBUTF8($new_lp_id),
2931
                            'item_type' => self::DBUTF8($item['item_type']),
2932
                            'ref' => self::DBUTF8($ref),
2933
                            'path' => self::DBUTF8($path),
2934
                            'title' => self::DBUTF8($item['title']),
2935
                            'description' => self::DBUTF8($item['description']),
2936
                            'min_score' => self::DBUTF8($item['min_score']),
2937
                            'max_score' => self::DBUTF8($item['max_score']),
2938
                            'mastery_score' => self::DBUTF8($masteryScore),
2939
                            'prerequisite_min_score' => $prerequisiteMinScore,
2940
                            'prerequisite_max_score' => $prerequisiteMaxScore,
2941
                            'parent_item_id' => self::DBUTF8($item['parent_item_id']),
2942
                            'previous_item_id' => self::DBUTF8($item['previous_item_id']),
2943
                            'next_item_id' => self::DBUTF8($item['next_item_id']),
2944
                            'display_order' => self::DBUTF8($item['display_order']),
2945
                            'prerequisite' => self::DBUTF8($item['prerequisite']),
2946
                            'parameters' => self::DBUTF8($item['parameters']),
2947
                            'audio' => self::DBUTF8($item['audio']),
2948
                            'launch_data' => self::DBUTF8($item['launch_data']),
2949
                        ];
2950
2951
                        $new_item_id = Database::insert($table_item, $params);
2952
                        if ($new_item_id) {
2953
                            $sql = "UPDATE $table_item SET id = iid WHERE iid = $new_item_id";
2954
                            Database::query($sql);
2955
2956
                            //save a link between old and new item IDs
2957
                            $new_item_ids[$item['id']] = $new_item_id;
2958
                            //save a reference of items that need a parent_item_id refresh
2959
                            $parent_item_ids[$new_item_id] = $item['parent_item_id'];
2960
                            //save a reference of items that need a previous_item_id refresh
2961
                            $previous_item_ids[$new_item_id] = $item['previous_item_id'];
2962
                            //save a reference of items that need a next_item_id refresh
2963
                            $next_item_ids[$new_item_id] = $item['next_item_id'];
2964
2965
                            if (!empty($item['prerequisite'])) {
2966
                                if ('2' == $lp->lp_type) {
2967
                                    // if is an sco
2968
                                    $old_prerequisite[$new_item_id] = $item['prerequisite'];
2969
                                } else {
2970
                                    $old_prerequisite[$new_item_id] = isset($new_item_ids[$item['prerequisite']]) ? $new_item_ids[$item['prerequisite']] : '';
2971
                                }
2972
                            }
2973
2974
                            if (!empty($ref)) {
2975
                                if ('2' == $lp->lp_type) {
2976
                                    // if is an sco
2977
                                    $old_refs[$new_item_id] = $ref;
2978
                                } elseif (isset($new_item_ids[$ref])) {
2979
                                    $old_refs[$new_item_id] = $new_item_ids[$ref];
2980
                                }
2981
                            }
2982
                            $prerequisite_ids[$new_item_id] = $item['prerequisite'];
2983
                        }
2984
                    }
2985
2986
                    // Updating prerequisites
2987
                    foreach ($old_prerequisite as $key => $my_old_prerequisite) {
2988
                        if ('' != $my_old_prerequisite) {
2989
                            $my_old_prerequisite = Database::escape_string($my_old_prerequisite);
2990
                            $sql = "UPDATE $table_item SET prerequisite = '$my_old_prerequisite'
2991
                                    WHERE c_id = ".$this->destination_course_id." AND id = '".$key."'  ";
2992
                            Database::query($sql);
2993
                        }
2994
                    }
2995
2996
                    // Updating refs
2997
                    foreach ($old_refs as $key => $my_old_ref) {
2998
                        if ('' != $my_old_ref) {
2999
                            $my_old_ref = Database::escape_string($my_old_ref);
3000
                            $sql = "UPDATE $table_item SET ref = '$my_old_ref'
3001
                                    WHERE c_id = ".$this->destination_course_id." AND id = $key";
3002
                            Database::query($sql);
3003
                        }
3004
                    }
3005
3006
                    foreach ($parent_item_ids as $new_item_id => $parent_item_old_id) {
3007
                        $new_item_id = (int) $new_item_id;
3008
                        $parent_new_id = 0;
3009
                        if (0 != $parent_item_old_id) {
3010
                            $parent_new_id = isset($new_item_ids[$parent_item_old_id]) ? $new_item_ids[$parent_item_old_id] : 0;
3011
                        }
3012
3013
                        $parent_new_id = Database::escape_string($parent_new_id);
3014
                        $sql = "UPDATE $table_item SET parent_item_id = '$parent_new_id'
3015
                                WHERE c_id = ".$this->destination_course_id." AND id = $new_item_id";
3016
                        Database::query($sql);
3017
                    }
3018
3019
                    foreach ($previous_item_ids as $new_item_id => $previous_item_old_id) {
3020
                        $new_item_id = (int) $new_item_id;
3021
                        $previous_new_id = 0;
3022
                        if (0 != $previous_item_old_id) {
3023
                            $previous_new_id = isset($new_item_ids[$previous_item_old_id]) ? $new_item_ids[$previous_item_old_id] : 0;
3024
                        }
3025
                        $previous_new_id = Database::escape_string($previous_new_id);
3026
                        $sql = "UPDATE $table_item SET previous_item_id = '$previous_new_id'
3027
                                WHERE c_id = ".$this->destination_course_id." AND id = '".$new_item_id."'";
3028
                        Database::query($sql);
3029
                    }
3030
3031
                    foreach ($next_item_ids as $new_item_id => $next_item_old_id) {
3032
                        $new_item_id = (int) $new_item_id;
3033
                        $next_new_id = 0;
3034
                        if (0 != $next_item_old_id) {
3035
                            $next_new_id = isset($new_item_ids[$next_item_old_id]) ? $new_item_ids[$next_item_old_id] : 0;
3036
                        }
3037
                        $next_new_id = Database::escape_string($next_new_id);
3038
                        $sql = "UPDATE $table_item SET next_item_id = '$next_new_id'
3039
                                WHERE c_id = ".$this->destination_course_id." AND id = '".$new_item_id."'";
3040
                        Database::query($sql);
3041
                    }
3042
3043
                    foreach ($prerequisite_ids as $new_item_id => $prerequisite_old_id) {
3044
                        $new_item_id = (int) $new_item_id;
3045
                        $prerequisite_new_id = 0;
3046
                        if (0 != $prerequisite_old_id) {
3047
                            $prerequisite_new_id = $new_item_ids[$prerequisite_old_id];
3048
                        }
3049
                        $sql = "UPDATE $table_item SET prerequisite = $prerequisite_new_id
3050
                                WHERE c_id = ".$this->destination_course_id." AND id = $new_item_id";
3051
                        Database::query($sql);
3052
                    }
3053
                    $this->course->resources[RESOURCE_LEARNPATH][$id]->destination_id = $new_lp_id;
3054
                }
3055
            }
3056
        }
3057
    }
3058
3059
    /**
3060
     * Gets the new ID of one specific tool item from the tool name and the old ID.
3061
     *
3062
     * @param	string	Tool name
3063
     * @param	int	Old ID
3064
     *
3065
     * @return int New ID
3066
     */
3067
    public function get_new_id($tool, $ref)
3068
    {
3069
        // Check if the value exist in the current array.
3070
        if ('hotpotatoes' === $tool) {
3071
            $tool = 'document';
3072
        }
3073
3074
        if ('student_publication' === $tool) {
3075
            $tool = RESOURCE_WORK;
3076
        }
3077
3078
        if (isset($this->course->resources[$tool][$ref]) &&
3079
            isset($this->course->resources[$tool][$ref]->destination_id) &&
3080
            !empty($this->course->resources[$tool][$ref]->destination_id)
3081
        ) {
3082
            return $this->course->resources[$tool][$ref]->destination_id;
3083
        }
3084
3085
        // Check if the course is the same (last hope).
3086
        if ($this->course_origin_id == $this->destination_course_id) {
3087
            return $ref;
3088
        }
3089
3090
        return '';
3091
    }
3092
3093
    /**
3094
     * Restore glossary.
3095
     */
3096
    public function restore_glossary($sessionId = 0)
3097
    {
3098
        $sessionId = (int) $sessionId;
3099
        if ($this->course->has_resources(RESOURCE_GLOSSARY)) {
3100
            $table_glossary = Database::get_course_table(TABLE_GLOSSARY);
3101
            $resources = $this->course->resources;
3102
            foreach ($resources[RESOURCE_GLOSSARY] as $id => $glossary) {
3103
                $params = [];
3104
                if (!empty($sessionId)) {
3105
                    $params['session_id'] = $sessionId;
3106
                }
3107
3108
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
3109
                $glossary->description = DocumentManager::replaceUrlWithNewCourseCode(
3110
                    $glossary->description,
3111
                    $this->course->code,
3112
                    $this->course->destination_path,
3113
                    $this->course->backup_path,
3114
                    $this->course->info['path']
3115
                );
3116
3117
                $params['c_id'] = $this->destination_course_id;
3118
                $params['description'] = false === $glossary->description ? '' : self::DBUTF8($glossary->description);
3119
                $params['display_order'] = $glossary->display_order;
3120
                $params['name'] = self::DBUTF8($glossary->name);
3121
                $params['glossary_id'] = 0;
3122
                $my_id = Database::insert($table_glossary, $params);
3123
                if ($my_id) {
3124
                    $sql = "UPDATE $table_glossary SET glossary_id = iid WHERE iid = $my_id";
3125
                    Database::query($sql);
3126
3127
                    api_item_property_update(
3128
                        $this->destination_course_info,
3129
                        TOOL_GLOSSARY,
3130
                        $my_id,
3131
                        'GlossaryAdded',
3132
                        api_get_user_id()
3133
                    );
3134
3135
                    if (!isset($this->course->resources[RESOURCE_GLOSSARY][$id])) {
3136
                        $this->course->resources[RESOURCE_GLOSSARY][$id] = new stdClass();
3137
                    }
3138
3139
                    $this->course->resources[RESOURCE_GLOSSARY][$id]->destination_id = $my_id;
3140
                }
3141
            }
3142
        }
3143
    }
3144
3145
    /**
3146
     * @param int $sessionId
3147
     */
3148
    public function restore_wiki($sessionId = 0)
3149
    {
3150
        if ($this->course->has_resources(RESOURCE_WIKI)) {
3151
            // wiki table of the target course
3152
            $table_wiki = Database::get_course_table(TABLE_WIKI);
3153
            $table_wiki_conf = Database::get_course_table(TABLE_WIKI_CONF);
3154
3155
            // storing all the resources that have to be copied in an array
3156
            $resources = $this->course->resources;
3157
3158
            foreach ($resources[RESOURCE_WIKI] as $id => $wiki) {
3159
                // the sql statement to insert the groups from the old course to the new course
3160
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
3161
                $wiki->content = DocumentManager::replaceUrlWithNewCourseCode(
3162
                    $wiki->content,
3163
                    $this->course->code,
3164
                    $this->course->destination_path,
3165
                    $this->course->backup_path,
3166
                    $this->course->info['path']
3167
                );
3168
3169
                $params = [
3170
                    'c_id' => $this->destination_course_id,
3171
                    'page_id' => self::DBUTF8($wiki->page_id),
3172
                    'reflink' => self::DBUTF8($wiki->reflink),
3173
                    'title' => self::DBUTF8($wiki->title),
3174
                    'content' => false === $wiki->content ? '' : self::DBUTF8($wiki->content),
3175
                    'user_id' => (int) ($wiki->user_id),
3176
                    'group_id' => (int) ($wiki->group_id),
3177
                    'dtime' => self::DBUTF8($wiki->dtime),
3178
                    'progress' => self::DBUTF8($wiki->progress),
3179
                    'version' => (int) ($wiki->version),
3180
                    'session_id' => !empty($session_id) ? (int) $session_id : 0,
3181
                    'addlock' => 0,
3182
                    'editlock' => 0,
3183
                    'visibility' => 0,
3184
                    'addlock_disc' => 0,
3185
                    'visibility_disc' => 0,
3186
                    'ratinglock_disc' => 0,
3187
                    'assignment' => 0,
3188
                    'comment' => '',
3189
                    'is_editing' => 0,
3190
                    'linksto' => 0,
3191
                    'tag' => '',
3192
                    'user_ip' => '',
3193
                ];
3194
3195
                $new_id = Database::insert($table_wiki, $params);
3196
3197
                if ($new_id) {
3198
                    $sql = "UPDATE $table_wiki SET page_id = '$new_id', id = iid
3199
                            WHERE c_id = ".$this->destination_course_id." AND iid = '$new_id'";
3200
                    Database::query($sql);
3201
3202
                    $this->course->resources[RESOURCE_WIKI][$id]->destination_id = $new_id;
3203
3204
                    // we also add an entry in wiki_conf
3205
                    $params = [
3206
                        'c_id' => $this->destination_course_id,
3207
                        'page_id' => $new_id,
3208
                        'task' => '',
3209
                        'feedback1' => '',
3210
                        'feedback2' => '',
3211
                        'feedback3' => '',
3212
                        'fprogress1' => '',
3213
                        'fprogress2' => '',
3214
                        'fprogress3' => '',
3215
                        'max_size' => 0,
3216
                        'max_text' => 0,
3217
                        'max_version' => 0,
3218
                        'startdate_assig' => null,
3219
                        'enddate_assig' => null,
3220
                        'delayedsubmit' => 0,
3221
                    ];
3222
3223
                    Database::insert($table_wiki_conf, $params);
3224
                }
3225
            }
3226
        }
3227
    }
3228
3229
    /**
3230
     * Restore Thematics.
3231
     *
3232
     * @param int $sessionId
3233
     */
3234
    public function restore_thematic($sessionId = 0)
3235
    {
3236
        if ($this->course->has_resources(RESOURCE_THEMATIC)) {
3237
            $table_thematic = Database::get_course_table(TABLE_THEMATIC);
3238
            $table_thematic_advance = Database::get_course_table(TABLE_THEMATIC_ADVANCE);
3239
            $table_thematic_plan = Database::get_course_table(TABLE_THEMATIC_PLAN);
3240
3241
            $resources = $this->course->resources;
3242
            foreach ($resources[RESOURCE_THEMATIC] as $id => $thematic) {
3243
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
3244
                $thematic->params['content'] = DocumentManager::replaceUrlWithNewCourseCode(
3245
                    $thematic->params['content'],
3246
                    $this->course->code,
3247
                    $this->course->destination_path,
3248
                    $this->course->backup_path,
3249
                    $this->course->info['path']
3250
                );
3251
                $thematic->params['c_id'] = $this->destination_course_id;
3252
                unset($thematic->params['id']);
3253
                unset($thematic->params['iid']);
3254
3255
                $last_id = Database::insert($table_thematic, $thematic->params, false);
3256
3257
                if ($last_id) {
3258
                    $sql = "UPDATE $table_thematic SET id = iid WHERE iid = $last_id";
3259
                    Database::query($sql);
3260
3261
                    api_item_property_update(
3262
                        $this->destination_course_info,
3263
                        'thematic',
3264
                        $last_id,
3265
                        'ThematicAdded',
3266
                        api_get_user_id()
3267
                    );
3268
3269
                    foreach ($thematic->thematic_advance_list as $thematic_advance) {
3270
                        unset($thematic_advance['id']);
3271
                        unset($thematic_advance['iid']);
3272
                        $thematic_advance['attendance_id'] = 0;
3273
                        $thematic_advance['thematic_id'] = $last_id;
3274
                        $thematic_advance['c_id'] = $this->destination_course_id;
3275
3276
                        $my_id = Database::insert(
3277
                            $table_thematic_advance,
3278
                            $thematic_advance,
3279
                            false
3280
                        );
3281
3282
                        if ($my_id) {
3283
                            $sql = "UPDATE $table_thematic_advance SET id = iid WHERE iid = $my_id";
3284
                            Database::query($sql);
3285
3286
                            api_item_property_update(
3287
                                $this->destination_course_info,
3288
                                'thematic_advance',
3289
                                $my_id,
3290
                                'ThematicAdvanceAdded',
3291
                                api_get_user_id()
3292
                            );
3293
                        }
3294
                    }
3295
3296
                    foreach ($thematic->thematic_plan_list as $thematic_plan) {
3297
                        unset($thematic_plan['id']);
3298
                        unset($thematic_plan['iid']);
3299
                        $thematic_plan['thematic_id'] = $last_id;
3300
                        $thematic_plan['c_id'] = $this->destination_course_id;
3301
                        $my_id = Database::insert($table_thematic_plan, $thematic_plan, false);
3302
3303
                        if ($my_id) {
3304
                            $sql = "UPDATE $table_thematic_plan SET id = iid WHERE iid = $my_id";
3305
                            Database::query($sql);
3306
3307
                            api_item_property_update(
3308
                                $this->destination_course_info,
3309
                                'thematic_plan',
3310
                                $my_id,
3311
                                'ThematicPlanAdded',
3312
                                api_get_user_id()
3313
                            );
3314
                        }
3315
                    }
3316
                }
3317
            }
3318
        }
3319
    }
3320
3321
    /**
3322
     * Restore Attendance.
3323
     *
3324
     * @param int $sessionId
3325
     */
3326
    public function restore_attendance($sessionId = 0)
3327
    {
3328
        if ($this->course->has_resources(RESOURCE_ATTENDANCE)) {
3329
            $table_attendance = Database::get_course_table(TABLE_ATTENDANCE);
3330
            $table_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
3331
3332
            $resources = $this->course->resources;
3333
            foreach ($resources[RESOURCE_ATTENDANCE] as $id => $obj) {
3334
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
3335
                $obj->params['description'] = DocumentManager::replaceUrlWithNewCourseCode(
3336
                    $obj->params['description'],
3337
                    $this->course->code,
3338
                    $this->course->destination_path,
3339
                    $this->course->backup_path,
3340
                    $this->course->info['path']
3341
                );
3342
3343
                unset($obj->params['id']);
3344
                unset($obj->params['iid']);
3345
                $obj->params['c_id'] = $this->destination_course_id;
3346
                $last_id = Database::insert($table_attendance, $obj->params);
3347
3348
                if (is_numeric($last_id)) {
3349
                    $sql = "UPDATE $table_attendance SET id = iid WHERE iid = $last_id";
3350
                    Database::query($sql);
3351
3352
                    $this->course->resources[RESOURCE_ATTENDANCE][$id]->destination_id = $last_id;
3353
3354
                    api_item_property_update(
3355
                        $this->destination_course_info,
3356
                        TOOL_ATTENDANCE,
3357
                        $last_id,
3358
                        'AttendanceAdded',
3359
                        api_get_user_id()
3360
                    );
3361
3362
                    foreach ($obj->attendance_calendar as $attendance_calendar) {
3363
                        unset($attendance_calendar['id']);
3364
                        unset($attendance_calendar['iid']);
3365
3366
                        $attendance_calendar['attendance_id'] = $last_id;
3367
                        $attendance_calendar['c_id'] = $this->destination_course_id;
3368
                        $attendanceCalendarId = Database::insert(
3369
                            $table_attendance_calendar,
3370
                            $attendance_calendar
3371
                        );
3372
3373
                        $sql = "UPDATE $table_attendance_calendar SET id = iid WHERE iid = $attendanceCalendarId";
3374
                        Database::query($sql);
3375
                    }
3376
                }
3377
            }
3378
        }
3379
    }
3380
3381
    /**
3382
     * Restore Works.
3383
     *
3384
     * @param int $sessionId
3385
     */
3386
    public function restore_works($sessionId = 0)
3387
    {
3388
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
3389
        if ($this->course->has_resources(RESOURCE_WORK)) {
3390
            $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
3391
3392
            $resources = $this->course->resources;
3393
            foreach ($resources[RESOURCE_WORK] as $obj) {
3394
                // check resources inside html from ckeditor tool and copy correct urls into recipient course
3395
                $obj->params['description'] = DocumentManager::replaceUrlWithNewCourseCode(
3396
                    $obj->params['description'],
3397
                    $this->course->code,
3398
                    $this->course->destination_path,
3399
                    $this->course->backup_path,
3400
                    $this->course->info['path']
3401
                );
3402
3403
                $id_work = $obj->params['id'];
3404
                $obj->params['id'] = null;
3405
                $obj->params['c_id'] = $this->destination_course_info['real_id'];
3406
3407
                // re-create dir
3408
                // @todo check security against injection of dir in crafted course backup here!
3409
                $path = $obj->params['url'];
3410
                $path = '/'.str_replace('/', '', substr($path, 1));
3411
3412
                $workData = [];
3413
3414
                switch ($this->file_option) {
3415
                    case FILE_SKIP:
3416
                        $workData = get_work_data_by_path(
3417
                            $path,
3418
                            $this->destination_course_info['real_id']
3419
                        );
3420
                        if (!empty($workData)) {
3421
                            break;
3422
                        }
3423
3424
                        break;
3425
                    case FILE_OVERWRITE:
3426
                        if (!empty($this->course_origin_id)) {
3427
                            $sql = 'SELECT * FROM '.$table.'
3428
                                    WHERE
3429
                                        c_id = '.$this->course_origin_id.' AND
3430
                                        publication_id = '.$id_work;
3431
                            $result = Database::query($sql);
3432
                            $cant = Database::num_rows($result);
3433
                            if ($cant > 0) {
3434
                                $row = Database::fetch_assoc($result);
3435
                            }
3436
3437
                            $obj->params['enableExpiryDate'] = empty($row['expires_on']) ? false : true;
3438
                            $obj->params['enableEndDate'] = empty($row['ends_on']) ? false : true;
3439
                            $obj->params['expires_on'] = $row['expires_on'];
3440
                            $obj->params['ends_on'] = $row['ends_on'];
3441
                            $obj->params['enable_qualification'] = $row['enable_qualification'];
3442
                            $obj->params['add_to_calendar'] = !empty($row['add_to_calendar']) ? 1 : 0;
3443
                        }
3444
                        //no break
3445
                    case FILE_RENAME:
3446
                        $workData = get_work_data_by_path(
3447
                            $path,
3448
                            $this->destination_course_info['real_id']
3449
                        );
3450
3451
                        break;
3452
                }
3453
3454
                $obj->params['work_title'] = $obj->params['title'];
3455
                $obj->params['new_dir'] = $obj->params['title'];
3456
3457
                if (empty($workData)) {
3458
                    $workId = addDir(
3459
                        $obj->params,
3460
                        api_get_user_id(),
3461
                        $this->destination_course_info,
3462
                        0,
3463
                        $sessionId
3464
                    );
3465
                    $this->course->resources[RESOURCE_WORK][$id_work]->destination_id = $workId;
3466
                } else {
3467
                    $workId = $workData['iid'];
3468
                    updateWork(
3469
                        $workId,
3470
                        $obj->params,
3471
                        $this->destination_course_info,
3472
                        $sessionId
3473
                    );
3474
                    updatePublicationAssignment(
3475
                        $workId,
3476
                        $obj->params,
3477
                        $this->destination_course_info,
3478
                        0
3479
                    );
3480
                    $this->course->resources[RESOURCE_WORK][$id_work]->destination_id = $workId;
3481
                }
3482
            }
3483
        }
3484
    }
3485
3486
    /**
3487
     * Restore gradebook.
3488
     *
3489
     * @param int $sessionId
3490
     *
3491
     * @return bool
3492
     */
3493
    public function restore_gradebook($sessionId = 0)
3494
    {
3495
        if (in_array($this->file_option, [FILE_SKIP, FILE_RENAME])) {
3496
            return false;
3497
        }
3498
        // if overwrite
3499
        if ($this->course->has_resources(RESOURCE_GRADEBOOK)) {
3500
            $resources = $this->course->resources;
3501
            $destinationCourseCode = $this->destination_course_info['code'];
3502
            // Delete destination gradebook
3503
            $cats = \Category:: load(
3504
                null,
3505
                null,
3506
                $destinationCourseCode,
3507
                null,
3508
                null,
3509
                $sessionId
3510
            );
3511
3512
            if (!empty($cats)) {
3513
                /** @var \Category $cat */
3514
                foreach ($cats as $cat) {
3515
                    $cat->delete_all();
3516
                }
3517
            }
3518
3519
            /** @var GradeBookBackup $obj */
3520
            foreach ($resources[RESOURCE_GRADEBOOK] as $id => $obj) {
3521
                if (!empty($obj->categories)) {
3522
                    $categoryIdList = [];
3523
                    /** @var \Category $cat */
3524
                    foreach ($obj->categories as $cat) {
3525
                        $cat->set_course_code($destinationCourseCode);
3526
                        $cat->set_session_id($sessionId);
3527
3528
                        $parentId = $cat->get_parent_id();
3529
                        if (!empty($parentId)) {
3530
                            if (isset($categoryIdList[$parentId])) {
3531
                                $cat->set_parent_id($categoryIdList[$parentId]);
3532
                            }
3533
                        }
3534
                        $oldId = $cat->get_id();
3535
                        $categoryId = $cat->add();
3536
                        $categoryIdList[$oldId] = $categoryId;
3537
                        if (!empty($cat->evaluations)) {
3538
                            /** @var \Evaluation $evaluation */
3539
                            foreach ($cat->evaluations as $evaluation) {
3540
                                $evaluation->set_category_id($categoryId);
3541
                                $evaluation->set_course_code($destinationCourseCode);
3542
                                $evaluation->setSessionId($sessionId);
3543
                                $evaluation->add();
3544
                            }
3545
                        }
3546
3547
                        if (!empty($cat->links)) {
3548
                            /** @var \AbstractLink $link */
3549
                            foreach ($cat->links as $link) {
3550
                                $link->set_category_id($categoryId);
3551
                                $link->set_course_code($destinationCourseCode);
3552
                                $link->set_session_id($sessionId);
3553
                                $import = false;
3554
                                $itemId = $link->get_ref_id();
3555
                                switch ($link->get_type()) {
3556
                                    case LINK_EXERCISE:
3557
                                        $type = RESOURCE_QUIZ;
3558
3559
                                        break;
3560
                                    /*case LINK_DROPBOX:
3561
                                        break;*/
3562
                                    case LINK_STUDENTPUBLICATION:
3563
                                        $type = RESOURCE_WORK;
3564
3565
                                        break;
3566
                                    case LINK_LEARNPATH:
3567
                                        $type = RESOURCE_LEARNPATH;
3568
3569
                                        break;
3570
                                    case LINK_FORUM_THREAD:
3571
                                        $type = RESOURCE_FORUMTOPIC;
3572
3573
                                        break;
3574
                                    case LINK_ATTENDANCE:
3575
                                        $type = RESOURCE_ATTENDANCE;
3576
3577
                                        break;
3578
                                    case LINK_SURVEY:
3579
                                        $type = RESOURCE_ATTENDANCE;
3580
3581
                                        break;
3582
                                    case LINK_HOTPOTATOES:
3583
                                        $type = RESOURCE_QUIZ;
3584
3585
                                        break;
3586
                                }
3587
3588
                                if ($this->course->has_resources($type) &&
3589
                                    isset($this->course->resources[$type][$itemId])
3590
                                ) {
3591
                                    $item = $this->course->resources[$type][$itemId];
3592
                                    if ($item && $item->is_restored()) {
3593
                                        $link->set_ref_id($item->destination_id);
3594
                                        $import = true;
3595
                                    }
3596
                                }
3597
3598
                                if ($import) {
3599
                                    $link->add();
3600
                                }
3601
                            }
3602
                        }
3603
                    }
3604
                }
3605
            }
3606
        }
3607
    }
3608
3609
    /**
3610
     * Restore course assets (not included in documents).
3611
     */
3612
    public function restore_assets()
3613
    {
3614
        if ($this->course->has_resources(RESOURCE_ASSET)) {
3615
            $resources = $this->course->resources;
3616
            $path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/';
3617
3618
            foreach ($resources[RESOURCE_ASSET] as $asset) {
3619
                if (is_file($this->course->backup_path.'/'.$asset->path) &&
3620
                    is_readable($this->course->backup_path.'/'.$asset->path) &&
3621
                    is_dir(dirname($path.$asset->path)) &&
3622
                    is_writeable(dirname($path.$asset->path))
3623
                ) {
3624
                    switch ($this->file_option) {
3625
                        case FILE_SKIP:
3626
                            break;
3627
                        case FILE_OVERWRITE:
3628
                            copy(
3629
                                $this->course->backup_path.'/'.$asset->path,
3630
                                $path.$asset->path
3631
                            );
3632
3633
                            break;
3634
                    }
3635
                }
3636
            }
3637
        }
3638
    }
3639
3640
    /**
3641
     * @param string $str
3642
     *
3643
     * @return string
3644
     */
3645
    public function DBUTF8($str)
3646
    {
3647
        if (UTF8_CONVERT) {
3648
            $str = utf8_encode($str);
3649
        }
3650
3651
        return $str;
3652
    }
3653
3654
    /**
3655
     * @param string $str
3656
     *
3657
     * @return string
3658
     */
3659
    public function DBUTF8escapestring($str)
3660
    {
3661
        if (UTF8_CONVERT) {
3662
            $str = utf8_encode($str);
3663
        }
3664
3665
        return Database::escape_string($str);
3666
    }
3667
3668
    /**
3669
     * @param array $array
3670
     */
3671
    public function DBUTF8_array($array)
3672
    {
3673
        if (UTF8_CONVERT) {
3674
            foreach ($array as &$item) {
3675
                $item = utf8_encode($item);
3676
            }
3677
3678
            return $array;
3679
        } else {
3680
            return $array;
3681
        }
3682
    }
3683
3684
    /**
3685
     * @param int $groupId
3686
     *
3687
     * @return array
3688
     */
3689
    public function checkGroupId($groupId)
3690
    {
3691
        return \GroupManager::get_group_properties($groupId);
3692
    }
3693
3694
    /**
3695
     * @param string $documentPath
3696
     * @param string $webEditorCss
3697
     */
3698
    public function fixEditorHtmlContent($documentPath, $webEditorCss = '')
3699
    {
3700
        $extension = pathinfo(basename($documentPath), PATHINFO_EXTENSION);
3701
3702
        switch ($extension) {
3703
            case 'html':
3704
            case 'htm':
3705
                $contents = file_get_contents($documentPath);
3706
                $contents = str_replace(
3707
                    '{{css_editor}}',
3708
                    $webEditorCss,
3709
                    $contents
3710
                );
3711
                file_put_contents($documentPath, $contents);
3712
3713
                break;
3714
        }
3715
    }
3716
3717
    /**
3718
     * Check if user exist otherwise use current user.
3719
     *
3720
     * @param int  $userId
3721
     * @param bool $returnNull
3722
     *
3723
     * @return int
3724
     */
3725
    private function checkUserId($userId, $returnNull = false)
3726
    {
3727
        if (!empty($userId)) {
3728
            $userInfo = api_get_user_info($userId);
3729
            if (empty($userInfo)) {
3730
                return api_get_user_id();
3731
            }
3732
        }
3733
3734
        if ($returnNull) {
3735
            return null;
3736
        }
3737
3738
        if (empty($userId)) {
3739
            return api_get_user_id();
3740
        }
3741
3742
        return $userId;
3743
    }
3744
}
3745