Passed
Push — master ( 240539...f3a9f0 )
by Julito
09:42
created

CourseRestorer::set_file_option()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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