CourseRestorer::restore_works()   C
last analyzed

Complexity

Conditions 13

Size

Total Lines 94
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 65
nop 1
dl 0
loc 94
rs 6.0569
c 0
b 0
f 0

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