Project

General

Profile

Support #3785 » CourseRestorer.class.php

Yannick Warnier, 22/08/2011 09:25

 
1
<?php
2
/* For licensing terms, see /license.txt */
3

    
4
require_once 'Course.class.php';
5
require_once 'Event.class.php';
6
require_once 'Link.class.php';
7
require_once 'ToolIntro.class.php';
8
require_once 'LinkCategory.class.php';
9
require_once 'ForumCategory.class.php';
10
require_once 'Forum.class.php';
11
require_once 'ForumTopic.class.php';
12
require_once 'ForumPost.class.php';
13
require_once 'CourseDescription.class.php';
14
require_once 'CourseCopyLearnpath.class.php';
15
require_once 'Survey.class.php';
16
require_once 'SurveyQuestion.class.php';
17
require_once api_get_path(SYS_CODE_PATH).'exercice/question.class.php'; 
18
//require_once 'mkdirr.php';
19
//require_once 'rmdirr.php';
20
require_once 'Glossary.class.php';
21
require_once 'wiki.class.php';
22
require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
23
require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
24
require_once api_get_path(LIBRARY_PATH).'document.lib.php';
25

    
26
define('FILE_SKIP', 1);
27
define('FILE_RENAME', 2);
28
define('FILE_OVERWRITE', 3);
29
// toegevoegd door MDC, augustus 2011
30
define('UTF8_CONVERT', true);
31
/**
32
 * Class to restore items from a course object to a Dokeos-course
33
 * @author Bart Mollet <bart.mollet@hogent.be>
34
 * @author Julio Montoya <gugli100@gmail.com> Several fixes/improvements
35
 * @package chamilo.backup
36
 */
37
class CourseRestorer
38
{
39
	/**
40
	 * The course-object
41
	 */
42
	var $course;
43
	/**
44
	 * What to do with files with same name (FILE_SKIP, FILE_RENAME or
45
	 * FILE_OVERWRITE)
46
	 */
47
	var $file_option;
48
	/**
49
	 * Create a new CourseRestorer
50
	 */
51
	function CourseRestorer($course) {
52
		$this->course = $course;
53
		$this->file_option = FILE_RENAME;
54
	}
55
	/**
56
	 * Set the file-option
57
	 * @param constant $options What to do with files with same name (FILE_SKIP,
58
	 * FILE_RENAME or FILE_OVERWRITE)
59
	 */
60
	function set_file_option($option) {
61
		$this->file_option = $option;
62
	}
63

    
64
	/**
65
	 * Restore a course.
66
	 * @param 	string 	The code of the Chamilo-course in
67
	 * @param	int		The session id
68
	 * @param	bool	Course settings are going to be restore?
69
	 
70
	 */
71
	function restore($destination_course_code = '', $session_id = 0, $update_course_settings = false, $respect_base_content = false) {
72
		if ($destination_course_code == '') {
73
			$course_info = api_get_course_info();
74
			$this->course->destination_db = $course_info['dbName'];
75
			$this->course->destination_path = $course_info['path'];
76
		} else {
77
			$course_info = Database :: get_course_info($destination_course_code);
78
            
79
			$this->course->destination_db = $course_info['database'];
80
			$this->course->destination_path = $course_info['directory'];
81
		}
82

    
83
		// Source platform encoding - reading/detection
84
		// The correspondent data field has been added as of version 1.8.6.1.
85
		if (empty($this->course->encoding)) {
86
			// The archive has been created by a system wich is prior to 1.8.6.1 version.
87
			// In this case we have to detect the encoding.
88
			$sample_text = $this->course->get_sample_text()."\n";
89
			// Let us exclude ASCII lines, probably they are English texts.
90
			$sample_text = explode("\n", $sample_text);
91
			foreach ($sample_text as $key => &$line) {
92
				if (api_is_valid_ascii($line)) {
93
					unset($sample_text[$key]);
94
				}
95
			}
96
			$sample_text = join("\n", $sample_text);
97
			$this->course->encoding = api_detect_encoding($sample_text, $course_info['language']);
98
		}
99

    
100
		// Encoding conversion of the course, if it is needed.
101
		$this->course->to_system_encoding();
102

    
103
		if (!empty($session_id)) {
104
			$this->restore_documents($session_id, $destination_course_code);
105
			$this->restore_quizzes($session_id, $respect_base_content);
106
			$this->restore_glossary($session_id);
107
			$this->restore_learnpaths($session_id, $respect_base_content);
108
			$this->restore_links($session_id);
109
			$this->restore_course_descriptions($session_id);
110
			$this->restore_wiki($session_id);
111
		} else {
112
			$this->restore_links();
113
			$this->restore_tool_intro();
114
			$this->restore_events();
115
			$this->restore_announcements();
116
			$this->restore_documents();
117
			$this->restore_scorm_documents();
118
			$this->restore_course_descriptions();
119
			$this->restore_quizzes(); // after restore_documents! (for correct import of sound/video)
120
			$this->restore_learnpaths();
121
			$this->restore_surveys();
122
			$this->restore_student_publication();
123
			$this->restore_glossary();
124
			$this->restore_wiki();
125
		}
126
		
127
		if ($update_course_settings) {
128
		    $this->restore_course_settings($destination_course_code);
129
		}
130

    
131

    
132
		// Restore the item properties
133
		$table = Database :: get_course_table(TABLE_ITEM_PROPERTY, $this->course->destination_db);
134

    
135
		$condition_session = "";
136

    
137
		if (!empty($session_id)) {
138
			$condition_session = " , id_session='".intval($session_id)."'";
139
		}
140

    
141
		foreach ($this->course->resources as $type => $resources) {
142
			if (is_array($resources)) {
143
				foreach ($resources as $id => $resource) {
144
					foreach ($resource->item_properties as $property)
145
					{
146
						// First check if there isn't allready a record for this resource
147
						$sql = "SELECT * FROM $table WHERE tool = '".$property['tool']."' AND ref = '".$resource->destination_id."'";
148

    
149
						$res = Database::query($sql);
150
						if( Database::num_rows($res) == 0) {
151
							// The to_group_id and to_user_id are set to default values as users/groups possibly not exist in the target course
152
							$sql = "INSERT INTO $table SET
153
									tool 				= '".Database::escape_string($property['tool'])."',
154
									insert_user_id 		= '".Database::escape_string($property['insert_user_id'])."',
155
									insert_date 		= '".Database::escape_string($property['insert_date'])."',
156
									lastedit_date 		= '".Database::escape_string($property['lastedit_date'])."',
157
									ref 				= '".Database::escape_string($resource->destination_id)."',
158
									lastedit_type 		= '".Database::escape_string($property['lastedit_type'])."',
159
									lastedit_user_id 	= '".Database::escape_string($property['lastedit_user_id'])."',
160
									visibility 			= '".Database::escape_string($property['visibility'])."',
161
									start_visible 		= '".Database::escape_string($property['start_visible'])."',
162
									end_visible 		= '".Database::escape_string($property['end_visible'])."',
163
									to_user_id  		= '".Database::escape_string($property['to_user_id'])."',
164
									to_group_id 		= '0' $condition_session" ;
165
													;
166
							Database::query($sql);
167
						}
168
					}
169
				}
170
			}
171
		}
172
		// Restore the linked-resources
173
		$table = Database :: get_course_table(TABLE_LINKED_RESOURCES, $this->course->destination_db);
174
		foreach ($this->course->resources as $type => $resources)
175
		{
176
			if (is_array($resources))
177
				foreach ($resources as $id => $resource)
178
				{
179
					$linked_resources = $resource->get_linked_resources();
180
					foreach ($linked_resources as $to_type => $to_ids)
181
					{
182
						foreach ($to_ids as $index => $to_id)
183
						{
184
							$to_resource = $this->course->resources[$to_type][$to_id];
185
							$sql = "INSERT INTO ".$table." SET source_type = '".$type."', source_id = '".$resource->destination_id."', resource_type='".$to_type."', resource_id='".$to_resource->destination_id."' ";
186
							Database::query($sql);
187
						}
188
					}
189
				}
190
		}
191
	}
192
	
193
	/**
194
	 * Restore only harmless course settings: course_language, visibility, department_name,department_url, subscribe, unsubscribe ,category_code
195
	 * 
196
	 * @return unknown_type
197
	 */
198
	function restore_course_settings($destination_course_code) {	    
199
	    $origin_course_info = api_get_course_info($destination_course_code);
200
	    $course_info = $this->course->info;
201
	    $params['course_language'] = $course_info['language'];
202
	    $params['visibility']      = $course_info['visibility'];
203
	    $params['department_name'] = $course_info['department_name'];
204
	    $params['department_url']  = $course_info['department_url'];
205
	    
206
	    $params['category_code']   = $course_info['categoryCode'];
207
	    $params['subscribe']       = $course_info['subscribe_allowed'];
208
	    $params['unsubscribe']     = $course_info['unubscribe_allowed'];	
209
	  
210
	    CourseManager::update_attributes($origin_course_info['real_id'], $params);
211
	    
212
	}
213
    
214
	/**
215
	 * Restore documents
216
     * @param   int session id
217
     * 
218
	 */
219
	function restore_documents($session_id = 0, $destination_course_code = '') {
220
		$perm = api_get_permissions_for_new_directories();
221
        $course_info = api_get_course_info($destination_course_code);
222
        
223
		if ($this->course->has_resources(RESOURCE_DOCUMENT)) {
224

    
225
			$table = Database :: get_course_table(TABLE_DOCUMENT, $this->course->destination_db);
226
			$resources = $this->course->resources;
227
			$destination_course['dbName']= $this->course->destination_db;
228

    
229
			foreach ($resources[RESOURCE_DOCUMENT] as $id => $document) {
230
			    //var_dump($document);
231
				$path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/';
232
				$dirs = explode('/', dirname($document->path));
233
				      
234
                if (empty($document->item_properties[0]['id_session'])) {
235
                    $my_session_id = 0;
236
                } else {
237
                    $my_session_id = $session_id;
238
                }
239
                
240
                
241
		    	if ($document->file_type == FOLDER) {
242
		    	    
243
		    		$visibility = $document->item_properties[0]['visibility'];
244
		    		if (!empty($document->title))  {
245
		    		    $title      = $document->title;
246
		    		} else {
247
		    		    $title      = basename($document->path);
248
		    		}
249
		    		$new        = substr($document->path, 8);
250

    
251
		    		if (!is_dir($path.'document/'.$new)) {
252
						$created_dir = create_unexisting_directory($destination_course, api_get_user_id(), $my_session_id, 0, 0 ,$path.'document', $new, $title, $visibility);
253
						//echo 'creating dir'; var_dump($created_dir);
254
		    		}                    
255
		    	} elseif ($document->file_type == DOCUMENT) {
256
		    	    /*
257
                    echo 'option'; var_dump($this->file_option);                    
258
                    echo 'file type'; var_dump($document->file_type);
259
                    echo 'session'; var_dump($session_id);                    
260
                    echo 'file _exists';  var_dump($path.$document->path); var_dump(file_exists($path.$document->path));
261
                    */
262
                        
263
                    if (!is_dir($path.dirname($document->path))) {
264
                        continue;
265
                        //echo '! is dir'; var_dump($path.dirname($document->path));
266
                        $visibility = $document->item_properties[0]['visibility'];
267
                        //$new        = $path.dirname($document->path);                        
268
                        //$new        = substr($new, 8);                  
269
                        $new        = substr($document->path, 8);            
270
                        if (!empty($document->title))  {
271
                            $title      = $document->title;
272
                        } else {
273
                            $title      = basename($new);
274
                        }
275
                        
276
                        // This code fixes the possibility for a file without a directory entry to be 
277
                        $created_dir = create_unexisting_directory($destination_course, api_get_user_id(), $my_session_id, 0, 0 , $path.'document', $new, $title, $visibility, true);
278
                    }
279
                    
280
					if (file_exists($path.$document->path)) {	
281
					    //var_dump ('enter');
282
						switch ($this->file_option) {
283
							case FILE_OVERWRITE :
284
								$origin_path = $this->course->backup_path.'/'.$document->path;
285
								if (file_exists($origin_path)) {
286
									copy($origin_path, $path.$document->path);
287
								}                                                                
288
                                //Replace old course code with the new destination code 
289
                                
290
                                $file_info = pathinfo($path.$document->path);                                    
291
                                if (in_array($file_info['extension'], array('html','htm'))) {
292
                                    $content    = file_get_contents($path.$document->path);  
293
                                    if (UTF8_CONVERT) $content = utf8_encode($content);
294
                                    $content    = DocumentManager::replace_urls_inside_content_html_from_copy_course($content ,$this->course->code,$this->course->destination_path);                                   
295
                                    $result     = file_put_contents($path.$document->path,$content);                                   
296
                                }                                
297
                                
298
								$sql = "SELECT id FROM ".$table." WHERE path='/".substr($document->path, 9)."'";
299
								$res = Database::query($sql);
300
								$obj = Database::fetch_object($res);
301
								$this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $obj->id;
302
								$sql = "UPDATE ".$table." SET comment = '".Database::escape_string($document->comment)."', title='".Database::escape_string($document->title)."', size='".$document->size."' WHERE id = '".$obj->id."'";
303
								Database::query($sql);
304
								break;
305
							case FILE_SKIP :
306
								$sql = "SELECT id FROM ".$table." WHERE path='/".Database::escape_string(substr($document->path, 9))."'";
307
								$res = Database::query($sql);
308
								$obj = Database::fetch_object($res);
309
								$this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $obj->id;
310
								break;
311
							case FILE_RENAME :
312
								$i = 1;
313
								$ext = explode('.', basename($document->path));
314
								if (count($ext) > 1) {
315
									$ext = array_pop($ext);
316
									$file_name_no_ext = substr($document->path, 0, - (strlen($ext) + 1));
317
									$ext = '.'.$ext;
318
								} else {
319
									$ext = '';
320
									$file_name_no_ext = $document->path;
321
								}
322
								$new_file_name = $file_name_no_ext.'_'.$i.$ext;
323
								$file_exists = file_exists($path.$new_file_name);
324
								while ($file_exists) {
325
									$i ++;
326
									$new_file_name = $file_name_no_ext.'_'.$i.$ext;
327
									$file_exists = file_exists($path.$new_file_name);
328
								}
329

    
330
								if (!empty($session_id)) {
331

    
332
									$document_path = explode('/',$document->path,3);
333
									$course_path = $path;								// "/var/www/wiener/courses/"
334
									$orig_base_folder = $document_path[1];
335
									$orig_base_path   = $course_path.$document_path[0].'/'.$document_path[1];
336
									//echo '$orig_base_path'; var_dump($orig_base_path);
337
                                    
338
									if (is_dir($orig_base_path)) {
339

    
340
										$new_base_foldername = $orig_base_folder;	// e.g: "carpeta1"
341
										$new_base_path   = $orig_base_path;			// e.g: "/var/www/wiener/courses/CURSO4/document/carpeta1"
342

    
343
										if ($_SESSION['orig_base_foldername'] != $new_base_foldername) {
344
											unset($_SESSION['new_base_foldername']);
345
											unset($_SESSION['orig_base_foldername']);
346
											unset($_SESSION['new_base_path']);
347
										}
348

    
349
										$folder_exists = file_exists($new_base_path);
350
										if ($folder_exists) {
351
											$_SESSION['orig_base_foldername'] = $new_base_foldername; 		// e.g: carpeta1 in session
352
											$x = '';
353
											while ($folder_exists) {
354
												$x = $x + 1;
355
												$new_base_foldername = $document_path[1].'_'.$x;
356
												$new_base_path = $orig_base_path.'_'.$x;
357
												if ($_SESSION['new_base_foldername'] == $new_base_foldername) break;
358
												$folder_exists = file_exists($new_base_path);
359
											}
360
											$_SESSION['new_base_foldername'] = $new_base_foldername;
361
											$_SESSION['new_base_path'] = $new_base_path;
362
										}
363

    
364
										if (isset($_SESSION['new_base_foldername']) && isset($_SESSION['new_base_path'])) {
365
											$new_base_foldername = $_SESSION['new_base_foldername'];
366
											$new_base_path = $_SESSION['new_base_path'];
367
										}
368

    
369
										$dest_document_path = $new_base_path.'/'.$document_path[2];		// e.g: "/var/www/wiener/courses/CURSO4/document/carpeta1_1/subcarpeta1/collaborative.png"
370
										$basedir_dest_path = dirname($dest_document_path);				// e.g: "/var/www/wiener/courses/CURSO4/document/carpeta1_1/subcarpeta1"
371
										$dest_filename = basename($dest_document_path);  				// e.g: "collaborative.png"
372
										$base_path_document = $course_path.$document_path[0];			// e.g: "/var/www/wiener/courses/CURSO4/document"
373
										
374
										$path_title = '/'.$new_base_foldername.'/'.$document_path[2];
375

    
376
										copy_folder_course_session($basedir_dest_path, $base_path_document, $session_id, $course_info, $document);
377
							
378
                                        if (file_exists($course_path.$document->path)) {
379
                                            copy($course_path.$document->path, $dest_document_path);
380
                                        }                                        
381
                                        
382
                                        //Replace old course code with the new destination code see BT#1985
383
                                        if (file_exists($dest_document_path)) {
384
                                            $file_info = pathinfo($dest_document_path);                                    
385
                                            if (in_array($file_info['extension'], array('html','htm'))) {
386
                                                $content    = file_get_contents($dest_document_path);                                    
387
                                                if (UTF8_CONVERT) $content = utf8_encode($content);
388
                                                $content    = DocumentManager::replace_urls_inside_content_html_from_copy_course($content ,$this->course->code,$this->course->destination_path);                                   
389
                                                $result     = file_put_contents($dest_document_path,$content);                                   
390
                                            }
391
                                        }                                        
392
                                        
393
										$sql = "INSERT INTO $table SET path = '$path_title', comment = '".Database::escape_string($document->comment)."', title = '".Database::escape_string(basename($path_title))."' ,filetype='".$document->file_type."', size= '".$document->size."', session_id = '$my_session_id'";
394

    
395
										Database::query($sql);
396
										$document_id = Database::insert_id();
397
                                        $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;                            
398
                                        api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id);                                   
399
                                            
400
									} else {									    
401
									    if (file_exists($path.$document->path)) {
402
										      copy($path.$document->path, $path.$new_file_name);
403
									    }
404
                                        
405
                                        //Replace old course code with the new destination code see BT#1985
406
                                        if (file_exists($path.$new_file_name)) {
407
                                            $file_info = pathinfo($path.$new_file_name);                                    
408
                                            if (in_array($file_info['extension'], array('html','htm'))) {
409
                                                $content    = file_get_contents($path.$new_file_name);   
410
                                                if (UTF8_CONVERT) $content = utf8_encode($content);
411
                                                $content    = DocumentManager::replace_urls_inside_content_html_from_copy_course($content ,$this->course->code,$this->course->destination_path);                                   
412
                                                $result     = file_put_contents($path.$new_file_name, $content);                                   
413
                                            }
414
                                        }                                       
415
                                        
416
										$sql = "INSERT INTO ".$table." SET path = '/".Database::escape_string(substr($new_file_name, 9))."', comment = '".Database::escape_string($document->comment)."', title = '".Database::escape_string($document->title)."' ,filetype='".$document->file_type."', size= '".$document->size."', session_id = '$my_session_id'";
417
										Database::query($sql);
418
										
419
										$document_id = Database::insert_id();
420
                                        $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;                            
421
                                        api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id);                                    
422
    										
423
									}
424

    
425
								} else {
426
									copy($this->course->backup_path.'/'.$document->path, $path.$new_file_name);
427
                                    
428
                                    //Replace old course code with the new destination code see BT#1985
429
                                    if (file_exists($path.$new_file_name)) {
430
                                        $file_info = pathinfo($path.$new_file_name);                                    
431
                                        if (in_array($file_info['extension'], array('html','htm'))) {
432
                                            $content    = file_get_contents($path.$new_file_name);              
433
                                            if (UTF8_CONVERT) $content = utf8_encode($content);
434
                                            $content    = DocumentManager::replace_urls_inside_content_html_from_copy_course($content ,$this->course->code,$this->course->destination_path);                                   
435
                                            $result     = file_put_contents($path.$new_file_name, $content);                                   
436
                                        }
437
                                    }                                    
438
									$sql = "INSERT INTO ".$table." SET path = '/".Database::escape_string(substr($new_file_name, 9))."', comment = '".Database::escape_string($document->comment)."', title = '".Database::escape_string($document->title)."' ,filetype='".$document->file_type."', size= '".$document->size."', session_id = '$my_session_id'";
439
									Database::query($sql);
440
																											
441
									$document_id = Database::insert_id();
442
                                    $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;                            
443
                                    api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id);                                    
444
                            
445
								}
446
								break;
447

    
448
						} // end switch
449
					} else { // end if file exists
450
						//make sure the source file actually exists
451
						if (is_file($this->course->backup_path.'/'.$document->path) && is_readable($this->course->backup_path.'/'.$document->path) && is_dir(dirname($path.$document->path)) && is_writeable(dirname($path.$document->path))) {
452
						    //echo 'Copying';
453
							copy($this->course->backup_path.'/'.$document->path, $path.$document->path);
454
                            
455
                            //Replace old course code with the new destination code see BT#1985
456
                            if (file_exists($path.$document->path)) {
457
                                $file_info = pathinfo($path.$document->path);                                    
458
                                if (in_array($file_info['extension'], array('html','htm'))) {
459
                                    $content    = file_get_contents($path.$document->path);    
460
                                    if (UTF8_CONVERT) $content = utf8_encode($content);
461
                                    $content    = DocumentManager::replace_urls_inside_content_html_from_copy_course($content ,$this->course->code,$this->course->destination_path);                                   
462
                                    $result     = file_put_contents($path.$document->path, $content);                                   
463
                                }
464
                            }                            
465
                            
466
							$sql = "INSERT INTO ".$table." SET path = '/".substr($document->path, 9)."', comment = '".Database::escape_string($document->comment)."', title = '".Database::escape_string($document->title)."' ,filetype='".$document->file_type."', size= '".$document->size."', session_id = '$my_session_id'";										
467
							Database::query($sql);
468
							$document_id = Database::insert_id();
469
							$this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id;							
470
							api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id);
471
						} else {
472
						    //echo 'not Copying';
473
							if(is_file($this->course->backup_path.'/'.$document->path) && is_readable($this->course->backup_path.'/'.$document->path)) {
474
								error_log('Course copy generated an ignoreable error while trying to copy '.$this->course->backup_path.'/'.$document->path.': file not found');
475
							}
476
							if(!is_dir(dirname($path.$document->path))) {
477
								error_log('Course copy generated an ignoreable error while trying to copy to '.dirname($path.$document->path).': directory not found');
478
							}
479
							if(!is_writeable(dirname($path.$document->path))) {
480
								error_log('Course copy generated an ignoreable error while trying to copy to '.dirname($path.$document->path).': directory not writeable');
481
							}
482
						}
483
					} // end file doesn't exist
484
				} else {
485

    
486
					/*$sql = "SELECT id FROM ".$table." WHERE path = '/".Database::escape_string(substr($document->path, 9))."'";
487
					$res = Database::query($sql);
488
					if( Database::num_rows($res)> 0)
489
					{
490
						$obj = Database::fetch_object($res);
491
						$this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $obj->id;
492
					}
493
					else
494
					{
495
						$sql = "INSERT INTO ".$table." SET path = '/".Database::escape_string(substr($document->path, 9))."', comment = '".Database::escape_string($document->comment)."', title = '".Database::escape_string($document->title)."' ,filetype='".$document->file_type."', size= '".$document->size."'";
496
						Database::query($sql);
497
						$this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = Database::insert_id();
498
					}*/
499
				} // end folder
500
			} // end for each
501
			
502
    		// Delete sessions for the copy the new folder in session
503
    		unset($_SESSION['new_base_foldername']);
504
    		unset($_SESSION['orig_base_foldername']);
505
    		unset($_SESSION['new_base_path']);
506
		}
507
	}
508
    
509
	/**
510
	 * Restore scorm documents
511
	 * TODO @TODO check that the restore function with renaming doesn't break the scorm structure!
512
	 */
513
	function restore_scorm_documents()
514
	{
515
		$perm = api_get_permissions_for_new_directories();
516

    
517
		if ($this->course->has_resources(RESOURCE_SCORM)) {
518
			$resources = $this->course->resources;
519

    
520
			foreach ($resources[RESOURCE_SCORM] as $id => $document) {
521
				$path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/';
522

    
523
				@api_mkdir(dirname($path.$document->path), $perm, true);
524

    
525
				if (file_exists($path.$document->path)) {
526
					switch ($this->file_option) {
527
						case FILE_OVERWRITE :
528
							rmdirr($path.$document->path);
529
							copyDirTo($this->course->backup_path.'/'.$document->path, $path.dirname($document->path), false);
530

    
531
							break;
532
						case FILE_SKIP :
533
							break;
534
						case FILE_RENAME :
535
							$i = 1;
536

    
537
							$ext = explode('.', basename($document->path));
538

    
539
							if (count($ext) > 1) {
540
								$ext = array_pop($ext);
541
								$file_name_no_ext = substr($document->path, 0, - (strlen($ext) + 1));
542
								$ext = '.'.$ext;
543
							} else {
544
								$ext = '';
545
								$file_name_no_ext = $document->path;
546
							}
547

    
548
							$new_file_name = $file_name_no_ext.'_'.$i.$ext;
549
							$file_exists = file_exists($path.$new_file_name);
550

    
551
							while ($file_exists) {
552
								$i ++;
553
								$new_file_name = $file_name_no_ext.'_'.$i.$ext;
554
								$file_exists = file_exists($path.$new_file_name);
555
							}
556

    
557
							rename($this->course->backup_path.'/'.$document->path,$this->course->backup_path.'/'.$new_file_name);
558

    
559
							copyDirTo($this->course->backup_path.'/'.$new_file_name, $path.dirname($new_file_name), false);
560

    
561
							rename($this->course->backup_path.'/'.$new_file_name,$this->course->backup_path.'/'.$document->path);
562

    
563
							break;
564
					} // end switch
565
				} // end if file exists
566
				else {
567
					copyDirTo($this->course->backup_path.'/'.$document->path, $path.dirname($document->path), false);
568
				}
569
			} // end for each
570
		}
571
	}
572

    
573
	/**
574
	 * Restore forums
575
	 */
576
	function restore_forums()
577
	{
578
		if ($this->course->has_resources(RESOURCE_FORUM))
579
		{
580
			$table_forum = Database :: get_course_table(TABLE_FORUM, $this->course->destination_db);
581
			$table_topic = Database :: get_course_table(TABLE_FORUM_THREAD, $this->course->destination_db);
582
			$table_post = Database :: get_course_table(TABLE_FORUM_POST, $this->course->destination_db);
583
			$resources = $this->course->resources;
584
			foreach ($resources[RESOURCE_FORUM] as $id => $forum)
585
			{
586
				$cat_id = $this->restore_forum_category($forum->category_id);
587
				$sql = "INSERT INTO ".$table_forum.
588
					" SET forum_title = '".Database::escape_string($forum->title).
589
					"', forum_comment = '".Database::escape_string($forum->description).
590
					"', forum_category = ".(int)Database::escape_string($cat_id).
591
					", forum_last_post = ".(int)Database::escape_string($forum->last_post).
592
					", forum_threads = ".(int)Database::escape_string($forum->topics).
593
					", forum_posts = ".(int)Database::escape_string($forum->posts).
594
					", allow_anonymous = ".(int)Database::escape_string($forum->allow_anonymous).
595
					", allow_edit = ".(int)Database::escape_string($forum->allow_edit).
596
					", approval_direct_post = '".Database::escape_string($forum->approval_direct_post).
597
					"', allow_attachments = ".(int)Database::escape_string($forum->allow_attachments).
598
					", allow_new_threads = ".(int)Database::escape_string($forum->allow_new_topics).
599
					", default_view = '".Database::escape_string($forum->default_view).
600
					"', forum_of_group = '".Database::escape_string($forum->of_group).
601
					"', forum_group_public_private = '".Database::escape_string($forum->group_public_private).
602
					"', forum_order = ".(int)Database::escape_string($forum->order).
603
					", locked = ".(int)Database::escape_string($forum->locked).
604
					", session_id = ".(int)Database::escape_string($forum->session_id).
605
					", forum_image = '".Database::escape_string($forum->image)."'";
606
				Database::query($sql);
607
				$new_id = Database::insert_id();
608
				$this->course->resources[RESOURCE_FORUM][$id]->destination_id = $new_id;
609
				$forum_topics = 0;
610
				if (is_array($this->course->resources[RESOURCE_FORUMTOPIC]))
611
				{
612
					foreach ($this->course->resources[RESOURCE_FORUMTOPIC] as $topic_id => $topic)
613
					{
614
						if ($topic->forum_id == $id)
615
						{
616
							$this->restore_topic($topic_id, $new_id);
617
							$forum_topics ++;
618
						}
619
					}
620
				}
621
				if ($forum_topics > 0)
622
				{
623
					$last_post = $this->course->resources[RESOURCE_FORUMPOST][$forum->last_post];
624
					$sql = "UPDATE ".$table_forum." SET forum_threads = ".$forum_topics.", forum_last_post = ".(int)$last_post->destination_id." WHERE forum_id = ".(int)$new_id;
625
					Database::query($sql);
626
				}
627
			}
628
		}
629
	}
630
	/**
631
	 * Restore forum-categories
632
	 */
633
	function restore_forum_category($id)
634
	{
635
		$forum_cat_table = Database :: get_course_table(TABLE_FORUM_CATEGORY, $this->course->destination_db);
636
		$resources = $this->course->resources;
637
		$forum_cat = $resources[RESOURCE_FORUMCATEGORY][$id];
638
		if (!$forum_cat->is_restored()) {
639
			$title = $forum_cat->title;
640
			if (!empty($title)) {
641
    			if (!preg_match('/.*\((.+)\)$/', $title, $matches)) {
642
    			    // This is for avoiding repetitive adding of training code after several backup/restore cycles.
643
    				if ($matches[1] != $this->course->code) {
644
    					$title = $title.' ('.$this->course->code.')';
645
    				}
646
    			}
647
			}
648
			$sql = "INSERT INTO ".$forum_cat_table.
649
				" SET cat_title = '".Database::escape_string($title).
650
				"', cat_comment = '".Database::escape_string($forum_cat->description).
651
				"', cat_order = ".(int)Database::escape_string($forum_cat->order).
652
				", locked = ".(int)Database::escape_string($forum_cat->locked).
653
				", session_id = ".(int)Database::escape_string($forum_cat->session_id);
654
			Database::query($sql);
655
			$new_id = Database::insert_id();
656
			$this->course->resources[RESOURCE_FORUMCATEGORY][$id]->destination_id = $new_id;
657
			return $new_id;
658
		}
659
		return $this->course->resources[RESOURCE_FORUMCATEGORY][$id]->destination_id;
660
	}
661
	/**
662
	 * Restore a forum-topic
663
	 */
664
	function restore_topic($id, $forum_id)
665
	{
666
		$table = Database :: get_course_table(TABLE_FORUM_THREAD, $this->course->destination_db);
667
		$resources = $this->course->resources;
668
		$topic = $resources[RESOURCE_FORUMTOPIC][$id];
669
		$sql = "INSERT INTO ".$table.
670
			" SET thread_title = '".Database::escape_string($topic->title).
671
			"', forum_id = ".(int)Database::escape_string($forum_id).
672
			", thread_date = '".Database::escape_string($topic->time).
673
			"', thread_poster_id = ".(int)Database::escape_string($topic->topic_poster_id).
674
			", thread_poster_name = '".Database::escape_string($topic->topic_poster_name).
675
			"', thread_views = ".(int)Database::escape_string($topic->views).
676
			", thread_sticky = ".(int)Database::escape_string($topic->sticky).
677
			", locked = ".(int)Database::escape_string($topic->locked).
678
			", thread_close_date = '".Database::escape_string($topic->time_closed).
679
			"', thread_weight = ".(float)Database::escape_string($topic->weight).
680
			", thread_title_qualify = '".Database::escape_string($topic->title_qualify).
681
			"', thread_qualify_max = ".(float)Database::escape_string($topic->qualify_max);
682
		Database::query($sql);
683
		$new_id = Database::insert_id();
684
		$this->course->resources[RESOURCE_FORUMTOPIC][$id]->destination_id = $new_id;
685
		$topic_replies = -1;
686
		foreach ($this->course->resources[RESOURCE_FORUMPOST] as $post_id => $post)
687
		{
688
			if ($post->topic_id == $id)
689
			{
690
				$topic_replies ++;
691
				$this->restore_post($post_id, $new_id, $forum_id);
692
			}
693
		}
694
		$last_post = $this->course->resources[RESOURCE_FORUMPOST][$topic->last_post];
695
		if (is_object($last_post))
696
		{
697
			$sql = "UPDATE ".$table." SET thread_last_post = ".(int)$last_post->destination_id;
698
			Database::query($sql);
699
		}
700
		if ($topic_replies >= 0)
701
		{
702
			$sql = "UPDATE ".$table." SET thread_replies = ".$topic_replies;
703
			Database::query($sql);
704
		}
705
		return $new_id;
706
	}
707
	/**
708
	 * Restore a forum-post
709
	 * @TODO Restore tree-structure of posts. For example: attachments to posts.
710
	 */
711
	function restore_post($id, $topic_id, $forum_id)
712
	{
713
		$table_post = Database :: get_course_table(TABLE_FORUM_POST, $this->course->destination_db);
714
		$resources = $this->course->resources;
715
		$post = $resources[RESOURCE_FORUMPOST][$id];
716
		$sql = "INSERT INTO ".$table_post.
717
			" SET post_title = '".Database::escape_string($post->title).
718
			"', post_text = '".Database::escape_string($post->text).
719
			"', thread_id = ".(int)Database::escape_string($topic_id).
720
			", post_date = '".Database::escape_string($post->post_time).
721
			"', forum_id = ".(int)Database::escape_string($forum_id).
722
			", poster_id = ".(int)Database::escape_string($post->poster_id).
723
			", poster_name = '".Database::escape_string($post->poster_name).
724
			"', post_notification = ".(int)Database::escape_string($post->topic_notify).
725
			", post_parent_id = ".(int)Database::escape_string($post->parent_post_id).
726
			", visible = ".(int)Database::escape_string($post->visible);
727
		Database::query($sql);
728
		$new_id = Database::insert_id();
729
		$this->course->resources[RESOURCE_FORUMPOST][$id]->destination_id = $new_id;
730
		return $new_id;
731
	}
732
	/**
733
	 * Restore links
734
	 */
735
	function restore_links($session_id = 0)
736
	{
737
		if ($this->course->has_resources(RESOURCE_LINK))
738
		{
739
			$link_table = Database :: get_course_table(TABLE_LINK, $this->course->destination_db);
740
			$resources = $this->course->resources;
741
			foreach ($resources[RESOURCE_LINK] as $id => $link)
742
			{
743
				$cat_id = $this->restore_link_category($link->category_id,$session_id);
744
				$sql = "SELECT MAX(display_order) FROM  $link_table WHERE category_id='" . Database::escape_string($cat_id). "'";
745
				$result = Database::query($sql);
746
    			list($max_order) = Database::fetch_array($result);
747

    
748
    			$condition_session = "";
749
    			if (!empty($session_id)) {
750
    				$condition_session = " , session_id = '$session_id' ";
751
    			}
752

    
753
				$sql = "INSERT INTO ".$link_table." SET url = '".Database::escape_string($link->url)."', title = '".Database::escape_string($link->title)."', description = '".Database::escape_string($link->description)."', category_id='".$cat_id."', on_homepage = '".$link->on_homepage."', display_order='".($max_order+1)."' $condition_session";
754

    
755
				Database::query($sql);
756
				$this->course->resources[RESOURCE_LINK][$id]->destination_id = Database::insert_id();
757
			}
758
		}
759
	}
760
	/**
761
	 * Restore tool intro
762
	 */
763
	function restore_tool_intro() {
764
		if ($this->course->has_resources(RESOURCE_TOOL_INTRO)) {
765
			$tool_intro_table = Database :: get_course_table(TABLE_TOOL_INTRO, $this->course->destination_db);
766
			$resources = $this->course->resources;
767
			foreach ($resources[RESOURCE_TOOL_INTRO] as $id => $tool_intro) {
768
				$sql = "DELETE FROM ".$tool_intro_table." WHERE id='".Database::escape_string($tool_intro->id)."'";
769
				Database::query($sql);  
770
                if (UTF8_CONVERT) $tool_intro->intro_text = utf8_encode($tool_intro->intro_text);
771
                $tool_intro->intro_text = DocumentManager::replace_urls_inside_content_html_from_copy_course($tool_intro->intro_text,$this->course->code,$this->course->destination_path);
772
				$sql = "INSERT INTO ".$tool_intro_table." SET id='".Database::escape_string($tool_intro->id)."', intro_text = '".Database::escape_string($tool_intro->intro_text)."'";
773
				Database::query($sql);
774

    
775
				$this->course->resources[RESOURCE_TOOL_INTRO][$id]->destination_id = Database::insert_id();
776
			}
777
		}
778
	}
779
    
780
	/**
781
	 * Restore a link-category
782
	 */
783
	function restore_link_category($id,$session_id = 0) {
784
		$condition_session = "";
785
		if (!empty($session_id)) {
786
			$condition_session = " , session_id = '$session_id' ";
787
		}
788

    
789
		if ($id == 0)
790
			return 0;
791
		$link_cat_table = Database :: get_course_table(TABLE_LINK_CATEGORY, $this->course->destination_db);
792
		$resources = $this->course->resources;
793
		$link_cat = $resources[RESOURCE_LINKCATEGORY][$id];
794
		if (is_object($link_cat) && !$link_cat->is_restored()) {
795
			$sql = "SELECT MAX(display_order) FROM  $link_cat_table";
796
			$result=Database::query($sql);
797
			list($orderMax)=Database::fetch_array($result,'NUM');
798
			$display_order=$orderMax+1;
799
			$sql = "INSERT INTO ".$link_cat_table." SET category_title = '".Database::escape_string($link_cat->title)."', description='".Database::escape_string($link_cat->description)."', display_order='".$display_order."' $condition_session ";
800
			Database::query($sql);
801
			$new_id = Database::insert_id();
802
			$this->course->resources[RESOURCE_LINKCATEGORY][$id]->destination_id = $new_id;
803
			return $new_id;
804
		}
805
		return $this->course->resources[RESOURCE_LINKCATEGORY][$id]->destination_id;
806
	}
807
    
808
	/**
809
	 * Restore events
810
	 */
811
	function restore_events() {
812
		if ($this->course->has_resources(RESOURCE_EVENT)) {
813
			$table = Database :: get_course_table(TABLE_AGENDA, $this->course->destination_db);
814
			$resources = $this->course->resources;
815
			foreach ($resources[RESOURCE_EVENT] as $id => $event) {
816
				// check resources inside html from fckeditor tool and copy correct urls into recipient course
817
                if (UTF8_CONVERT) $event->content = utf8_encode($event->content);
818
				$event->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($event->content, $this->course->code, $this->course->destination_path);
819

    
820
				$sql = "INSERT INTO ".$table." SET title = '".Database::escape_string($event->title)."', content = '".Database::escape_string($event->content)."', start_date = '".$event->start_date."', end_date = '".$event->end_date."'";
821
				Database::query($sql);
822
				$new_event_id = Database::insert_id();
823
				$this->course->resources[RESOURCE_EVENT][$id]->destination_id = $new_event_id;
824

    
825
				//Copy event attachment
826

    
827
				$origin_path = $this->course->backup_path.'/upload/calendar/';
828
				$destination_path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/upload/calendar/';
829

    
830
				if (!empty($this->course->orig)) {
831

    
832
					$table_attachment = Database :: get_course_table(TABLE_AGENDA_ATTACHMENT, $this->course->orig);
833
					$sql = 'SELECT path, comment, size, filename FROM '.$table_attachment.' WHERE agenda_id = '.$id;
834
					$attachment_event = Database::query($sql);
835
					$attachment_event = Database::fetch_object($attachment_event);
836

    
837
					if (file_exists($origin_path.$attachment_event->path) && !is_dir($origin_path.$attachment_event->path) ) {
838
						$new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
839
						$copy_result = copy($origin_path.$attachment_event->path, $destination_path.$new_filename);
840
						//$copy_result = true;
841
						if ($copy_result) {
842
							$table_attachment = Database :: get_course_table(TABLE_AGENDA_ATTACHMENT, $this->course->destination_db);
843
							$sql = "INSERT INTO ".$table_attachment." SET path = '".Database::escape_string($new_filename)."', comment = '".Database::escape_string($attachment_event->comment)."', size = '".$attachment_event->size."', filename = '".$attachment_event->filename."' , agenda_id = '".$new_event_id."' ";
844
							Database::query($sql);
845
						}
846
					}
847
				} else {
848
					// get the info of the file
849
					if(!empty($event->attachment_path) && is_file($origin_path.$event->attachment_path) && is_readable($origin_path.$event->attachment_path)) {
850
						$new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
851
						$copy_result = copy($origin_path.$event->attachment_path, $destination_path.$new_filename);
852
						if ($copy_result) {
853
							$table_attachment = Database :: get_course_table(TABLE_AGENDA_ATTACHMENT, $this->course->destination_db);
854
							$sql = "INSERT INTO ".$table_attachment." SET path = '".Database::escape_string($new_filename)."', comment = '".Database::escape_string($event->attachment_comment)."', size = '".$event->attachment_size."', filename = '".$event->attachment_filename."' , agenda_id = '".$new_event_id."' ";
855
							Database::query($sql);
856
						}
857
					}
858
				}
859
			}
860
		}
861
	}
862
	/**
863
	 * Restore course-description
864
	 */
865
	function restore_course_descriptions($session_id = 0) {
866
		if ($this->course->has_resources(RESOURCE_COURSEDESCRIPTION)) {
867
			$table = Database :: get_course_table(TABLE_COURSE_DESCRIPTION, $this->course->destination_db);
868
			$resources = $this->course->resources;
869
            $full = array(1=>false,2=>false,3=>false,4=>false,5=>false,6=>false,7=>false,8=>false);
870
			foreach ($resources[RESOURCE_COURSEDESCRIPTION] as $id => $cd) {
871
				if (isset($_POST['destination_course'])) {
872
					$course_destination=Security::remove_XSS($_POST['destination_course']);
873
					$course_destination=api_get_course_info($course_destination);
874
					$course_destination=$course_destination['path'];
875
				} else {
876
					$course_destination=$this->course->destination_path;
877
				}
878

    
879
				// check resources inside html from fckeditor tool and copy correct urls into recipient course
880
                if (UTF8_CONVERT) $cd->title = utf8_encode($cd->title);
881
                if (UTF8_CONVERT) $cd->content = utf8_encode($cd->content);
882
				$description_content = DocumentManager::replace_urls_inside_content_html_from_copy_course($cd->content, $this->course->code, $this->course->destination_path);
883

    
884
				$condition_session = "";
885
				if (!empty($session_id)) {
886
					$session_id = intval($session_id);
887
					$condition_session = " , session_id = '$session_id' ";
888
				}
889
                if ($cd->title=="Algemene beschrijving" && !$full[1]) {
890
                    $full[1] = true;
891
                    $cd->description_type=1;
892
                }
893
                if (($cd->title=="Doelstelling" || $cd->title=="Doelstellingen") && !$full[2]) {
894
                    $full[2] = true;
895
                    $cd->description_type=2;
896
                }
897
                if (($cd->title=="Discussie" || $cd->title=="Discussies") && !$full[3]) {
898
                    $full[3] = true;
899
                    $cd->description_type=3;
900
                }
901
                if (($cd->title=="Methodiek" || $cd->title=="Methodieken") && !$full[4]) {
902
                    $full[4] = true;
903
                    $cd->description_type=4;
904
                }
905
                if (($cd->title=="Cursusmateriaal" || $cd->title=="Lesmateriaal") && !$full[5]) {
906
                    $full[5] = true;
907
                    $cd->description_type=5;
908
                }
909
                if (($cd->title=="Beoordeling" || $cd->title=="Evaluatie") && !$full[7]) {
910
                    $full[7] = true;
911
                    $cd->description_type=7;
912
                }
913
                if (empty($cd->description_type)) {
914
                    for ($ifull=8; $ifull>0; $ifull--) {
915
                        if (!$full[$ifull]) break;
916
                    }
917
                    if ($ifull>0) $full[$ifull] = true;
918
                    $cd->description_type=$ifull;    
919
                }
920
				$sql = "INSERT INTO ".$table." SET description_type = '".Database::escape_string($cd->description_type)."',title = '".Database::escape_string($cd->title)."', content = '".Database::escape_string($description_content)."' $condition_session";
921
				Database::query($sql);
922
				$this->course->resources[RESOURCE_COURSEDESCRIPTION][$id]->destination_id = Database::insert_id();
923
			}
924
		}
925
	}
926
	/**
927
	 * Restore announcements
928
	 */
929
	function restore_announcements() {
930
		if ($this->course->has_resources(RESOURCE_ANNOUNCEMENT)) {
931
			$table = Database :: get_course_table(TABLE_ANNOUNCEMENT, $this->course->destination_db);
932
			$resources = $this->course->resources;
933
			foreach ($resources[RESOURCE_ANNOUNCEMENT] as $id => $announcement) {
934

    
935
				// check resources inside html from fckeditor tool and copy correct urls into recipient course
936
                if (UTF8_CONVERT) $announcement->content = utf8_encode($announcement->content);
937
				$announcement->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($announcement->content, $this->course->code, $this->course->destination_path);
938

    
939
				$sql = "INSERT INTO ".$table." " .
940
						"SET title = '".Database::escape_string($announcement->title)."'," .
941
							"content = '".Database::escape_string($announcement->content)."', " .
942
							"end_date = '".$announcement->date."', " .
943
							"display_order = '".$announcement->display_order."', " .
944
							"email_sent = '".$announcement->email_sent."'";
945
				Database::query($sql);
946
				$new_announcement_id = Database::insert_id();
947
				$this->course->resources[RESOURCE_ANNOUNCEMENT][$id]->destination_id = $new_announcement_id;
948

    
949

    
950
				$origin_path = $this->course->backup_path.'/upload/announcements/';
951
				$destination_path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/upload/announcements/';
952

    
953
				//Copy announcement attachment file
954
				if (!empty($this->course->orig)) {
955

    
956
					$table_attachment = Database :: get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT, $this->course->orig);
957

    
958
					$sql = 'SELECT path, comment, size, filename FROM '.$table_attachment.' WHERE announcement_id = '.$id;
959
					$attachment_event = Database::query($sql);
960
					$attachment_event = Database::fetch_object($attachment_event);
961

    
962
					if (file_exists($origin_path.$attachment_event->path) && !is_dir($origin_path.$attachment_event->path) ) {
963
						$new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
964
						$copy_result = copy($origin_path.$attachment_event->path, $destination_path.$new_filename);
965
						//error_log($destination_path.$new_filename); error_log($copy_result);
966
						//$copy_result = true;
967
						if ($copy_result) {
968
							$table_attachment = Database :: get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT, $this->course->destination_db);
969
							$sql = "INSERT INTO ".$table_attachment." SET path = '".Database::escape_string($new_filename)."', comment = '".Database::escape_string($attachment_event->comment)."', size = '".$attachment_event->size."', filename = '".$attachment_event->filename."' , announcement_id = '".$new_announcement_id."' ";
970
							Database::query($sql);
971
						}
972
					}
973
				} else {
974
					// get the info of the file
975
					if(!empty($announcement->attachment_path) && is_file($origin_path.$announcement->attachment_path) && is_readable($origin_path.$announcement->attachment_path)) {
976
						$new_filename = uniqid(''); //ass seen in the add_agenda_attachment_file() function in agenda.inc.php
977
						$copy_result = copy($origin_path.$announcement->attachment_path, $destination_path.$new_filename);
978

    
979
						if ($copy_result) {
980
							$table_attachment = Database :: get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT, $this->course->destination_db);
981
							$sql = "INSERT INTO ".$table_attachment." SET path = '".Database::escape_string($new_filename)."', comment = '".Database::escape_string($announcement->attachment_comment)."', size = '".$announcement->attachment_size."', filename = '".$announcement->attachment_filename."' , announcement_id = '".$new_announcement_id."' ";
982
							Database::query($sql);
983
						}
984
					}
985
				}
986
			}
987
		}
988
	}
989
    
990
	/**
991
	 * Restore Quiz
992
	 */
993
	function restore_quizzes($session_id = 0, $respect_base_content = false) {
994
		if ($this->course->has_resources(RESOURCE_QUIZ)) {
995
			$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST, $this->course->destination_db);
996
			$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION, $this->course->destination_db);
997
			$table_doc = Database :: get_course_table(TABLE_DOCUMENT, $this->course->destination_db);
998
			$resources = $this->course->resources;
999
			foreach ($resources[RESOURCE_QUIZ] as $id => $quiz) {
1000
				$doc = '';
1001
				if (strlen($quiz->media) > 0) {
1002
					if ($this->course->resources[RESOURCE_DOCUMENT][$quiz->media]->is_restored()) {
1003
						$sql = "SELECT path FROM ".$table_doc." WHERE id = ".$resources[RESOURCE_DOCUMENT][$quiz->media]->destination_id;
1004
						$doc = Database::query($sql);
1005
						$doc = Database::fetch_object($doc);
1006
						$doc = str_replace('/audio/', '', $doc->path);
1007
					}
1008
				}
1009
				if ($id != -1) {				   
1010
                    if ($respect_base_content) {
1011
                        $my_session_id = $quiz->session_id; 
1012
                        if (!empty($quiz->session_id)) {
1013
                            $my_session_id = $session_id;
1014
                        }
1015
                        $condition_session = " , session_id = '$my_session_id' ";
1016
                    } else {
1017
    					$condition_session = "";
1018
        				if (!empty($session_id)) {
1019
        					$session_id = intval($session_id);
1020
        					$condition_session = " , session_id = '$session_id' ";
1021
    				    }
1022
                    }
1023

    
1024
					// check resources inside html from fckeditor tool and copy correct urls into recipient course
1025
                    if (UTF8_CONVERT) $quiz->description = utf8_encode($quiz->description);
1026
					$quiz->description = DocumentManager::replace_urls_inside_content_html_from_copy_course($quiz->description, $this->course->code, $this->course->destination_path);
1027

    
1028
					// Normal tests are stored in the database.
1029
					$sql = "INSERT INTO ".$table_qui.
1030
						" SET title = '".Database::escape_string($quiz->title).
1031
						"', description = '".Database::escape_string($quiz->description).
1032
						"', type = '".$quiz->quiz_type.
1033
						"', random = '".$quiz->random.
1034
						"', active = '".$quiz->active.
1035
						"', sound = '".Database::escape_string($doc).
1036
						"', max_attempt = ".(int)$quiz->attempts.
1037
						",  results_disabled = ".(int)$quiz->results_disabled.
1038
						",  access_condition = '".$quiz->access_condition.
1039
						"', start_time = '".$quiz->start_time.
1040
						"', end_time = '".$quiz->end_time.
1041
						"', feedback_type = ".(int)$quiz->feedback_type.
1042
						", random_answers = ".(int)$quiz->random_answers.
1043
						", expired_time = ".(int)$quiz->expired_time.
1044
						$condition_session;
1045
					Database::query($sql);
1046
					$new_id = Database::insert_id();
1047
				} else {
1048
					// $id = -1 identifies the fictionary test for collecting orphan questions. We do not store it in the database.
1049
					$new_id = -1;
1050
				}
1051
				$this->course->resources[RESOURCE_QUIZ][$id]->destination_id = $new_id;
1052
				foreach ($quiz->question_ids as $index => $question_id) {
1053
					$qid = $this->restore_quiz_question($question_id);
1054
					$question_order = $quiz->question_orders[$index] ? $quiz->question_orders[$index] : 1;
1055
					$sql = "INSERT IGNORE INTO ".$table_rel." SET question_id = ".$qid.", exercice_id = ".$new_id.", question_order = ".$question_order;
1056
					Database::query($sql);     
1057
				}
1058
			}
1059
		}
1060
	}
1061
    
1062
	/**
1063
	 * Restore quiz-questions
1064
	 */
1065
	function restore_quiz_question($id) {
1066
		$resources = $this->course->resources;
1067
		$question = $resources[RESOURCE_QUIZQUESTION][$id];
1068

    
1069
		$new_id=0;
1070

    
1071
		if(is_object($question)) {
1072
			if ($question->is_restored()) {
1073
				return $question->destination_id;
1074
			}
1075
			$table_que = Database :: get_course_table(TABLE_QUIZ_QUESTION, $this->course->destination_db);
1076
			$table_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER, $this->course->destination_db);
1077
            $table_options = Database :: get_course_table(TABLE_QUIZ_QUESTION_OPTION, $this->course->destination_db);
1078

    
1079
			// check resources inside html from fckeditor tool and copy correct urls into recipient course
1080
            if (UTF8_CONVERT) $question->description = utf8_encode($question->description);
1081
			$question->description = DocumentManager::replace_urls_inside_content_html_from_copy_course($question->description, $this->course->code, $this->course->destination_path);
1082

    
1083
			$sql = "INSERT INTO ".$table_que." SET question = '".addslashes($question->question)."', description = '".addslashes($question->description)."', ponderation = '".addslashes($question->ponderation)."', position = '".addslashes($question->position)."', type='".addslashes($question->quiz_type)."', picture='".addslashes($question->picture)."', level='".addslashes($question->level)."', extra='".addslashes($question->extra)."'";
1084
			Database::query($sql);
1085
			$new_id = Database::insert_id();
1086

    
1087

    
1088
			if ($question->quiz_type == MATCHING) { // for answer type matching
1089
				foreach ($question->answers as $index => $answer) {
1090
					$sql = "INSERT INTO ".$table_ans." SET id= '".$answer['id']."',question_id = '".$new_id."', answer = '".Database::escape_string($answer['answer'])."', correct = '".$answer['correct']."', comment = '".Database::escape_string($answer['comment'])."', ponderation='".$answer['ponderation']."', position = '".$answer['position']."', hotspot_coordinates = '".$answer['hotspot_coordinates']."', hotspot_type = '".$answer['hotspot_type']."'";
1091
					Database::query($sql);
1092
				}
1093
			} else {
1094
				foreach ($question->answers as $index => $answer) {
1095

    
1096
					// check resources inside html from fckeditor tool and copy correct urls into recipient course
1097
                    if (UTF8_CONVERT) $answer['answer']  = utf8_encode($answer['answer']);
1098
                    if (UTF8_CONVERT) $answer['comment'] = utf8_encode($answer['comment']);
1099
					$answer['answer']  = DocumentManager::replace_urls_inside_content_html_from_copy_course($answer['answer'], $this->course->code, $this->course->destination_path);
1100
					$answer['comment'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($answer['comment'], $this->course->code, $this->course->destination_path);
1101

    
1102
					$sql = "INSERT INTO ".$table_ans." SET id= '". ($index +1)."',question_id = '".$new_id."', answer = '".Database::escape_string($answer['answer'])."', correct = '".$answer['correct']."', comment = '".Database::escape_string($answer['comment'])."', ponderation='".$answer['ponderation']."', position = '".$answer['position']."', hotspot_coordinates = '".$answer['hotspot_coordinates']."', hotspot_type = '".$answer['hotspot_type']."'";
1103
					Database::query($sql);
1104
				}
1105
			}           
1106
            
1107
            //Moving quiz_question_options
1108
            if ($question->quiz_type == MULTIPLE_ANSWER_TRUE_FALSE) {                
1109
                $question_option_list = Question::readQuestionOption($id);                
1110
                $old_option_ids = array();            
1111
                foreach ($question_option_list  as $item) {
1112
                    $old_id = $item['id'];                    
1113
                    unset($item['id']);                    
1114
                    $item['question_id'] = $new_id;
1115
                    $question_option_id = Database::insert($table_options, $item);
1116
                    $old_option_ids[$old_id] = $question_option_id;
1117
                }               
1118
                $new_answers = Database::select('id, correct', $table_ans, array('where'=>array('question_id = ?'=>$new_id)));
1119
                foreach ($new_answers as $answer_item) {                	
1120
                    $params['correct'] = $old_option_ids[$answer_item['correct']];
1121
                    $question_option_id = Database::update($table_ans, $params, array('id = ?'=>$answer_item['id']));
1122
                }                
1123
            }            
1124
			$this->course->resources[RESOURCE_QUIZQUESTION][$id]->destination_id = $new_id;
1125
		}
1126
		return $new_id;
1127
	}
1128
	/**
1129
	 * Restore surveys
1130
	 */
1131
	function restore_surveys() {
1132
		if ($this->course->has_resources(RESOURCE_SURVEY)) {
1133
			$table_sur = Database :: get_course_table(TABLE_SURVEY, $this->course->destination_db);
1134
			$table_que = Database :: get_course_table(TABLE_SURVEY_QUESTION, $this->course->destination_db);
1135
			$table_ans = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION, $this->course->destination_db);
1136
			$resources = $this->course->resources;
1137
			foreach ($resources[RESOURCE_SURVEY] as $id => $survey) {
1138

    
1139
				$sql_check =   'SELECT survey_id FROM '.$table_sur.'
1140
								WHERE code = "'.Database::escape_string($survey->code).'"
1141
								AND lang="'.Database::escape_string($survey->lang).'"
1142
								';
1143

    
1144
				$result_check = Database::query($sql_check);
1145

    
1146
				// check resources inside html from fckeditor tool and copy correct urls into recipient course
1147
                if (UTF8_CONVERT) {
1148
                    $survey->title = utf8_encode($survey->title);
1149
                    $survey->subtitle = utf8_encode($survey->subtitle);
1150
                    $survey->intro = utf8_encode($survey->intro);
1151
                    $survey->surveythanks = utf8_encode($survey->surveythanks);
1152
                }
1153
				$survey->title 		  = DocumentManager::replace_urls_inside_content_html_from_copy_course($survey->title, $this->course->code, $this->course->destination_path);
1154
				$survey->subtitle 	  = DocumentManager::replace_urls_inside_content_html_from_copy_course($survey->subtitle, $this->course->code, $this->course->destination_path);
1155
				$survey->intro 		  = DocumentManager::replace_urls_inside_content_html_from_copy_course($survey->intro, $this->course->code, $this->course->destination_path);
1156
				$survey->surveythanks = DocumentManager::replace_urls_inside_content_html_from_copy_course($survey->surveythanks, $this->course->code, $this->course->destination_path);
1157

    
1158
				$doc = '';
1159
				$sql = "INSERT INTO ".$table_sur." " .
1160
						"SET code = '".Database::escape_string($survey->code)."', " .
1161
						"title = '".Database::escape_string($survey->title)."', " .
1162
						"subtitle = '".Database::escape_string($survey->subtitle)."', " .
1163
						"author = '".Database::escape_string($survey->author)."', " .
1164
						"lang = '".Database::escape_string($survey->lang)."', " .
1165
						"avail_from = '".Database::escape_string($survey->avail_from)."', " .
1166
						"avail_till = '".Database::escape_string($survey->avail_till)."', " .
1167
						"is_shared = '".Database::escape_string($survey->is_shared)."', " .
1168
						"template = '".Database::escape_string($survey->template)."', " .
1169
						"intro = '".Database::escape_string($survey->intro)."', " .
1170
						"surveythanks = '".Database::escape_string($survey->surveythanks)."', " .
1171
						"creation_date = '".Database::escape_string($survey->creation_date)."', " .
1172
						"invited = '0', " .
1173
						"answered = '0', " .
1174
						"invite_mail = '".Database::escape_string($survey->invite_mail)."', " .
1175
						"reminder_mail = '".Database::escape_string($survey->reminder_mail)."'";
1176

    
1177
				//An existing survey exists with the same code and the same language
1178
				if (Database::num_rows($result_check) == 1) {
1179

    
1180
					switch ($this->file_option) {
1181

    
1182
						case FILE_SKIP:
1183
							//Do nothing
1184
							break;
1185

    
1186
						case FILE_RENAME:
1187

    
1188
							$survey_code = $survey->code.'_';
1189
							$i=1;
1190
							$temp_survey_code = $survey_code.$i;
1191
							while (!$this->is_survey_code_available($temp_survey_code))
1192
							{
1193
								$temp_survey_code = $survey_code.++$i;
1194
							}
1195
							$survey_code = $temp_survey_code;
1196

    
1197
							$sql = "INSERT INTO ".$table_sur." " .
1198
									"SET code = '".Database::escape_string($survey_code)."', " .
1199
									"title = '".Database::escape_string($survey->title)."', " .
1200
									"subtitle = '".Database::escape_string($survey->subtitle)."', " .
1201
									"author = '".Database::escape_string($survey->author)."', " .
1202
									"lang = '".Database::escape_string($survey->lang)."', " .
1203
									"avail_from = '".Database::escape_string($survey->avail_from)."', " .
1204
									"avail_till = '".Database::escape_string($survey->avail_till)."', " .
1205
									"is_shared = '".Database::escape_string($survey->is_shared)."', " .
1206
									"template = '".Database::escape_string($survey->template)."', " .
1207
									"intro = '".Database::escape_string($survey->intro)."', " .
1208
									"surveythanks = '".Database::escape_string($survey->surveythanks)."', " .
1209
									"creation_date = '".Database::escape_string($survey->creation_date)."', " .
1210
									"invited = '0', " .
1211
									"answered = '0', " .
1212
									"invite_mail = '".Database::escape_string($survey->invite_mail)."', " .
1213
									"reminder_mail = '".Database::escape_string($survey->reminder_mail)."'";
1214

    
1215
							//Insert the new source survey
1216
							Database::query($sql);
1217

    
1218
							$new_id = Database::insert_id();
1219
							$this->course->resources[RESOURCE_SURVEY][$id]->destination_id = $new_id;
1220
							foreach ($survey->question_ids as $index => $question_id)
1221
							{
1222
								$qid = $this->restore_survey_question($question_id);
1223
								$sql = "UPDATE ".$table_que." " .
1224
										"SET survey_id = ".$new_id." WHERE " .
1225
										"question_id = ".$qid."";
1226
								Database::query($sql);
1227
								$sql = "UPDATE ".$table_ans." ".
1228
										"SET survey_id = ".$new_id." WHERE " .
1229
										"question_id = ".$qid."";
1230
								Database::query($sql);
1231
							}
1232

    
1233
							break;
1234

    
1235
						case FILE_OVERWRITE:
1236

    
1237
							// Delete the existing survey with the same code and language and import the one of the source course
1238

    
1239
							// getting the information of the survey (used for when the survey is shared)
1240
							require_once(api_get_path(SYS_CODE_PATH).'survey/survey.lib.php');
1241

    
1242
							$sql_select_existing_survey = "SELECT * FROM $table_sur WHERE survey_id='".Database::escape_string(Database::result($result_check,0,0))."'";
1243
							$result = Database::query($sql_select_existing_survey);
1244
							$survey_data = Database::fetch_array($result,'ASSOC');
1245

    
1246
							// if the survey is shared => also delete the shared content
1247
							if (is_numeric($survey_data['survey_share']))
1248
							{
1249
								survey_manager::delete_survey($survey_data['survey_share'], true,$this->course->destination_db);
1250
							}
1251
							$return = survey_manager :: delete_survey($survey_data['survey_id'],false,$this->course->destination_db);
1252

    
1253
							//Insert the new source survey
1254
							Database::query($sql);
1255

    
1256
							$new_id = Database::insert_id();
1257
							$this->course->resources[RESOURCE_SURVEY][$id]->destination_id = $new_id;
1258
							foreach ($survey->question_ids as $index => $question_id)
1259
							{
1260
								$qid = $this->restore_survey_question($question_id);
1261
								$sql = "UPDATE ".$table_que." " .
1262
										"SET survey_id = ".$new_id." WHERE " .
1263
										"question_id = ".$qid."";
1264
								Database::query($sql);
1265
								$sql = "UPDATE ".$table_ans." ".
1266
										"SET survey_id = ".$new_id." WHERE " .
1267
										"question_id = ".$qid."";
1268
								Database::query($sql);
1269
							}
1270

    
1271
							break;
1272

    
1273
						default:
1274
							break;
1275
					}
1276

    
1277

    
1278
				}
1279
				//No existing survey with the same language and the same code, we just copy the survey
1280
				else
1281
				{
1282
					Database::query($sql);
1283
					$new_id = Database::insert_id();
1284
					$this->course->resources[RESOURCE_SURVEY][$id]->destination_id = $new_id;
1285
					foreach ($survey->question_ids as $index => $question_id)
1286
					{
1287
						$qid = $this->restore_survey_question($question_id);
1288
						$sql = "UPDATE ".$table_que." " .
1289
								"SET survey_id = ".$new_id." WHERE " .
1290
								"question_id = ".$qid."";
1291
						Database::query($sql);
1292
						$sql = "UPDATE ".$table_ans." ".
1293
								"SET survey_id = ".$new_id." WHERE " .
1294
								"question_id = ".$qid."";
1295
						Database::query($sql);
1296
					}
1297
				}
1298

    
1299
			}
1300
		}
1301
	}
1302

    
1303
	/**
1304
	 * Check availability of a survey code
1305
	 */
1306
	function is_survey_code_available($survey_code)
1307
	{
1308
		$table_sur = Database :: get_course_table(TABLE_SURVEY, $this->course->destination_db);
1309
		$sql = "SELECT * FROM $table_sur WHERE code='".Database::escape_string($survey_code)."'";
1310
		$result = Database::query($sql);
1311
		if(Database::num_rows($result) > 0) return false; else return true;
1312

    
1313
	}
1314

    
1315
	/**
1316
	 * Restore survey-questions
1317
	 */
1318
	function restore_survey_question($id)
1319
	{
1320
		$resources = $this->course->resources;
1321
		$question = $resources[RESOURCE_SURVEYQUESTION][$id];
1322

    
1323
		$new_id=0;
1324

    
1325
		if(is_object($question))
1326
		{
1327
			if ($question->is_restored())
1328
			{
1329
				return $question->destination_id;
1330
			}
1331
			$table_que = Database :: get_course_table(TABLE_SURVEY_QUESTION, $this->course->destination_db);
1332
			$table_ans = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION, $this->course->destination_db);
1333

    
1334
			// check resources inside html from fckeditor tool and copy correct urls into recipient course
1335
            if (UTF8_CONVERT) $question->survey_question = utf8_encode($question->survey_question);
1336
			$question->survey_question = DocumentManager::replace_urls_inside_content_html_from_copy_course($question->survey_question, $this->course->code, $this->course->destination_path);
1337

    
1338
			$sql = "INSERT INTO ".$table_que." " .
1339
					"SET survey_id = 		'".Database::escape_string($question->survey_id)."', " .
1340
					"survey_question = 		'".Database::escape_string($question->survey_question)."', " .
1341
					"survey_question_comment = '".Database::escape_string($question->survey_question_comment)."', " .
1342
					"type = 				'".Database::escape_string($question->survey_question_type)."', " .
1343
					"display = 				'".Database::escape_string($question->display)."', " .
1344
					"sort = 				'".Database::escape_string($question->sort)."', " .
1345
					"shared_question_id = 	'".Database::escape_string($question->shared_question_id)."', " .
1346
					"max_value = 			'".Database::escape_string($question->max_value)."' ";
1347
			Database::query($sql);
1348

    
1349
			$new_id = Database::insert_id();
1350
			foreach ($question->answers as $index => $answer) {
1351

    
1352
				// check resources inside html from fckeditor tool and copy correct urls into recipient course
1353
                if (UTF8_CONVERT) $answer['option_text'] = utf8_encode($answer['option_text']);
1354
				$answer['option_text'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($answer['option_text'], $this->course->code, $this->course->destination_path);
1355

    
1356
				$sql = "INSERT INTO ".$table_ans." " .
1357
						"SET " .
1358
						"question_id = '".Database::escape_string($new_id)."', " .
1359
						"option_text = '".Database::escape_string($answer['option_text'])."', " .
1360
						"sort 		 = '".Database::escape_string($answer['sort'])."', " .
1361
						"survey_id 	 = '".Database::escape_string($question->survey_id)."'";
1362

    
1363
				Database::query($sql);
1364
			}
1365
			$this->course->resources[RESOURCE_SURVEYQUESTION][$id]->destination_id = $new_id;
1366
		}
1367

    
1368
		return $new_id;
1369
	}
1370
	/**
1371
	 * Restore learnpaths
1372
	 */
1373
	function restore_learnpaths($session_id = 0, $respect_base_content = false)
1374
	{
1375
		if ($this->course->has_resources(RESOURCE_LEARNPATH)) {
1376
			$table_main 	= Database::get_course_table(TABLE_LP_MAIN,  $this->course->destination_db);
1377
			$table_item 	= Database::get_course_table(TABLE_LP_ITEM,  $this->course->destination_db);
1378
			$table_tool 	= Database::get_course_table(TABLE_TOOL_LIST,$this->course->destination_db);
1379

    
1380
			$resources = $this->course->resources;
1381

    
1382
			$origin_path = $this->course->backup_path.'/upload/learning_path/images/';
1383
			$destination_path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/upload/learning_path/images/';
1384

    
1385
			foreach ($resources[RESOURCE_LEARNPATH] as $id => $lp) {
1386

    
1387
				$condition_session = "";				  
1388
				if (!empty($session_id)) {			    
1389
                    if ($respect_base_content) {
1390
                        $my_session_id = $lp->session_id; 
1391
                        if (!empty($lp->session_id)) {
1392
                            $my_session_id = $session_id;
1393
                        }
1394
                        $condition_session = " , session_id = '$my_session_id' ";                        
1395
                    } else {
1396
                        $session_id = intval($session_id);
1397
                        $condition_session = " , session_id = '$session_id' ";  
1398
                    }					
1399
				}
1400

    
1401
				//Adding the author's image
1402
				if (!empty($lp->preview_image)) {
1403
					$new_filename = uniqid('').$new_filename.substr($lp->preview_image,strlen($lp->preview_image)-7, strlen($lp->preview_image));
1404
					if (file_exists($origin_path.$lp->preview_image) && !is_dir($origin_path.$lp->preview_image)) {
1405
						$copy_result = copy($origin_path.$lp->preview_image, $destination_path.$new_filename);
1406
						//$copy_result = true;
1407
						if ($copy_result) {
1408
							$lp->preview_image = $new_filename;
1409
						} else {
1410
							$lp->preview_image ='';
1411
						}
1412
					}
1413
				}
1414

    
1415
				$sql = "INSERT INTO ".$table_main." SET " .
1416
						"lp_type            = '".$lp->lp_type."', " .
1417
						"name               = '".Database::escape_string($lp->name)."', " .
1418
						"path               = '".Database::escape_string($lp->path)."', " .
1419
						"ref                = '".$lp->ref."', " .
1420
						"description        = '".Database::escape_string($lp->description)."', " .
1421
						"content_local      = '".Database::escape_string($lp->content_local)."', " .
1422
						"default_encoding   = '".Database::escape_string($lp->default_encoding)."', " .
1423
						"default_view_mod   = '".Database::escape_string($lp->default_view_mod)."', " .
1424
						"prevent_reinit     = '".Database::escape_string($lp->prevent_reinit)."', " .
1425
						"force_commit       = '".Database::escape_string($lp->force_commit)."', " .
1426
						"content_maker      = '".Database::escape_string($lp->content_maker)."', " .
1427
						"display_order      = '".Database::escape_string($lp->display_order)."', " .
1428
						"js_lib             = '".Database::escape_string($lp->js_lib)."', " .
1429
						"content_license    = '".Database::escape_string($lp->content_license)."', " .
1430
						"author             = '".Database::escape_string($lp->author)."', " .
1431
						"preview_image      = '".Database::escape_string($lp->preview_image)."', " .
1432
        				"use_max_score      = '".Database::escape_string($lp->use_max_score)."', " .
1433
        				"autolunch          = '".Database::escape_string($lp->autolunch)."', " .
1434
        				"created_on         = '".Database::escape_string($lp->created_on)."', " .
1435
        				"modified_on        = '".Database::escape_string($lp->modified_on)."', " .
1436
        				"publicated_on      = '".Database::escape_string($lp->publicated_on)."', " .
1437
				        "expired_on         = '".Database::escape_string($lp->expired_on)."', " .
1438
						"debug              = '".Database::escape_string($lp->debug)."' $condition_session ";
1439

    
1440
				Database::query($sql);
1441

    
1442
				$new_lp_id = Database::insert_id();
1443

    
1444
				if($lp->visibility) {
1445
					$sql = "INSERT INTO $table_tool SET name='".Database::escape_string($lp->name)."', link='newscorm/lp_controller.php?action=view&lp_id=$new_lp_id', image='scormbuilder.gif', visibility='1', admin='0', address='squaregrey.gif'";
1446
					Database::query($sql);
1447
				}
1448

    
1449
				$new_item_ids 		= array();
1450
				$parent_item_ids 	= array();
1451
				$previous_item_ids 	= array();
1452
				$next_item_ids 		= array();
1453
				$old_prerequisite 	= array();
1454
				$old_refs 			= array();
1455
				$prerequisite_ids 	= array();
1456

    
1457
				foreach ($lp->get_items() as $index => $item) {
1458
					/*
1459
					if ($item['id'] != 0)
1460
					{
1461
						 // Links in learnpath have types 'Link _self' or 'Link _blank'. We only need 'Link' here.
1462
						 $type_parts = explode(' ',$item['type']);
1463
						 $item['id'] = $this->course->resources[$type_parts[0]][$item['id']]->destination_id;
1464
					}
1465
					*/
1466
					/*
1467
					//Get the new ref ID for all items that are not sco (dokeos quizzes, documents, etc)
1468
					$ref = '';
1469
					if(!empty($item['ref']) && $lp->lp_type!='2'){
1470
						$ref = $this->get_new_id($item['item_type'],$item['ref']);
1471
					} else {
1472
						$ref = $item['ref'];
1473
					}*/
1474

    
1475
					// we set the ref code here and then we update in a for loop
1476
					$ref = $item['ref'];
1477

    
1478
					//Dealing with path the same way as ref as some data has been put into path when it's a
1479
					//local resource
1480
					$path = Database::escape_string($item['path']);
1481
					if(strval(intval($path)) === $path) {
1482
						if (!empty($session_id)) {
1483
							$path = intval($path);
1484
						} else {
1485
							$path = $this->get_new_id($item['item_type'],$path);
1486
						}
1487
					}
1488

    
1489
					$sql = "INSERT INTO ".$table_item." SET " .
1490
							"lp_id = '".			Database::escape_string($new_lp_id)."', " .
1491
							"item_type='".			Database::escape_string($item['item_type'])."', " .
1492
							"ref = '".				Database::escape_string($ref)."', " .
1493
							"title = '".			Database::escape_string($item['title'])."', " .
1494
							"description ='".		Database::escape_string($item['description'])."', " .
1495
							"path = '".				Database::escape_string($path)."', " .
1496
							"min_score = '".		Database::escape_string($item['min_score'])."', " .
1497
							"max_score = '".		Database::escape_string($item['max_score'])."', " .
1498
							"mastery_score = '".	Database::escape_string($item['mastery_score'])."', " .
1499
							"parent_item_id = '".	Database::escape_string($item['parent_item_id'])."', " .
1500
							"previous_item_id = '".	Database::escape_string($item['previous_item_id'])."', " .
1501
							"next_item_id = '".		Database::escape_string($item['next_item_id'])."', " .
1502
							"display_order = '".	Database::escape_string($item['display_order'])."', " .
1503
							"prerequisite = '".		Database::escape_string($item['prerequisite'])."', " .
1504
							"parameters='".			Database::escape_string($item['parameters'])."', " .
1505
							"audio='".				Database::escape_string($item['audio'])."', " .
1506
							"launch_data = '".		Database::escape_string($item['launch_dataprereq_type'])."'";
1507

    
1508
					Database::query($sql);
1509
					$new_item_id = Database::insert_id();
1510
					//save a link between old and new item IDs
1511
					$new_item_ids[$item['id']] = $new_item_id;
1512
					//save a reference of items that need a parent_item_id refresh
1513
					$parent_item_ids[$new_item_id] = $item['parent_item_id'];
1514
					//save a reference of items that need a previous_item_id refresh
1515
					$previous_item_ids[$new_item_id] = $item['previous_item_id'];
1516
					//save a reference of items that need a next_item_id refresh
1517
					$next_item_ids[$new_item_id] = $item['next_item_id'];
1518

    
1519
					if (!empty($item['prerequisite'])) {
1520
						if ($lp->lp_type =='2') {
1521
							// if is an sco
1522
							$old_prerequisite[$new_item_id]= $item['prerequisite'];
1523
						} else {
1524
							$old_prerequisite[$new_item_id]= $new_item_ids[$item['prerequisite']];
1525
						}
1526
					}
1527

    
1528
					if (!empty($ref)) {
1529
						if ($lp->lp_type =='2') {
1530
							// if is an sco
1531
							$old_refs[$new_item_id]= $ref;
1532
						} else {
1533
							$old_refs[$new_item_id]= $new_item_ids[$ref];
1534
						}
1535
					}
1536

    
1537
					$prerequisite_ids[$new_item_id] = $item['prerequisite'];
1538
				}
1539

    
1540
				// updating prerequisites
1541
				foreach ($old_prerequisite  as $key=>$my_old_prerequisite) {
1542
					if($my_old_prerequisite != ''){
1543
						$sql = "UPDATE ".$table_item." SET prerequisite = '".$my_old_prerequisite."' WHERE id = '".$key."'  ";
1544
						Database::query($sql);
1545
					}
1546
				}
1547

    
1548
				//updating refs
1549
				foreach ($old_refs  as $key=>$my_old_ref) {
1550
					if ($my_old_ref != '') {
1551
						$sql = "UPDATE ".$table_item." SET ref = '".$my_old_ref."' WHERE id = '".$key."'  ";
1552
						Database::query($sql);
1553
					}
1554
				}
1555

    
1556
				foreach ($parent_item_ids as $new_item_id => $parent_item_old_id) {
1557
					$parent_new_id = 0;
1558
					if($parent_item_old_id != 0){
1559
						$parent_new_id = $new_item_ids[$parent_item_old_id];
1560
					}
1561
					$sql = "UPDATE ".$table_item." SET parent_item_id = '".$parent_new_id."' WHERE id = '".$new_item_id."'";
1562
					Database::query($sql);
1563
				}
1564
				foreach ($previous_item_ids as $new_item_id => $previous_item_old_id) {
1565
					$previous_new_id = 0;
1566
					if($previous_item_old_id != 0){
1567
						$previous_new_id = $new_item_ids[$previous_item_old_id];
1568
					}
1569
					$sql = "UPDATE ".$table_item." SET previous_item_id = '".$previous_new_id."' WHERE id = '".$new_item_id."'";
1570
					Database::query($sql);
1571
				}
1572

    
1573
				foreach ($next_item_ids as $new_item_id => $next_item_old_id) {
1574
					$next_new_id = 0;
1575
					if($next_item_old_id != 0){
1576
						$next_new_id = $new_item_ids[$next_item_old_id];
1577
					}
1578
					$sql = "UPDATE ".$table_item." SET next_item_id = '".$next_new_id."' WHERE id = '".$new_item_id."'";
1579
					Database::query($sql);
1580
				}
1581

    
1582
				foreach ($prerequisite_ids as $new_item_id => $prerequisite_old_id) {
1583
					$prerequisite_new_id = 0;
1584
					if($prerequisite_old_id != 0){
1585
						$prerequisite_new_id = $new_item_ids[$prerequisite_old_id];
1586
					}
1587
					$sql = "UPDATE ".$table_item." SET prerequisite = '".$prerequisite_new_id."' WHERE id = '".$new_item_id."'";
1588
					Database::query($sql);
1589
				}
1590

    
1591
				$this->course->resources[RESOURCE_LEARNPATH][$id]->destination_id = $new_lp_id;
1592
			}
1593

    
1594
		}
1595
	}
1596
	/**
1597
	 * restore works
1598
	 */
1599
	function restore_student_publication() {
1600

    
1601
		$my_tbl_db_spa_origin        = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT, $this->course->db_name);
1602
		$my_tbl_db_spa_destination   = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT, $this->course->destination_db);
1603

    
1604
		$my_tbl_db_origin            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION, $this->course->db_name);
1605
		$my_tbl_db_destination       = Database :: get_course_table(TABLE_STUDENT_PUBLICATION, $this->course->destination_db);
1606

    
1607
		$my_tbl_db_item_property_origin      = Database :: get_course_table(TABLE_ITEM_PROPERTY, $this->course->db_name);
1608
		$my_tbl_db_item_property_destination = Database :: get_course_table(TABLE_ITEM_PROPERTY, $this->course->destination_db);
1609

    
1610
		//query in student publication
1611

    
1612
		$query_sql_fin_sp='INSERT IGNORE INTO '.$my_tbl_db_destination.'' .
1613
		'(id,url,title,description,author,active,accepted,post_group_id,sent_date,' .
1614
		'filetype,has_properties,view_properties,qualification,date_of_qualification,' .
1615
		'parent_id,qualificator_id,session_id) ';
1616

    
1617
		$query_sql_ini_sp='SELECT id,url,title,description,author,active,accepted,post_group_id,' .
1618
		'sent_date,filetype,has_properties,view_properties,qualification,date_of_qualification,' .
1619
		'parent_id,qualificator_id,session_id FROM '.$my_tbl_db_origin.' WHERE filetype="folder" ';
1620
		//var_dump($query_sql_ini_sp);
1621
		$destination='../../courses/'.$this->course->destination_path.'/work/';
1622
		
1623
		$origin='../../courses/'.$this->course->info['path'].'/work/';
1624

    
1625
		self::allow_create_all_directory($origin,$destination,false);
1626

    
1627
		//query in item property
1628

    
1629
		$query_sql_fin_ip='INSERT IGNORE INTO '.$my_tbl_db_item_property_destination.'' .
1630
		'(tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,' .
1631
		'to_user_id,visibility,start_visible,end_visible) ';
1632

    
1633
		$query_sql_ini_ip='SELECT tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,' .
1634
		'lastedit_user_id,to_group_id,to_user_id,visibility,start_visible,
1635
		end_visible FROM '.$my_tbl_db_item_property_origin.' ip INNER JOIN '.$my_tbl_db_origin.' sp' .
1636
		' ON ip.ref=sp.id WHERE tool="work" ';
1637

    
1638

    
1639
		$query_sql_fin_sa='INSERT IGNORE INTO '.$my_tbl_db_spa_destination.'' .
1640
		'(id,expires_on,ends_on,add_to_calendar,enable_qualification,publication_id) ';
1641

    
1642
		$query_sql_ini_sa='SELECT sa.id,sa.expires_on,sa.ends_on,sa.add_to_calendar,sa.enable_qualification,sa.publication_id FROM '.$my_tbl_db_spa_origin.' sa INNER JOIN '.$my_tbl_db_origin.' sp
1643
		ON sa.publication_id=sp.id WHERE filetype="folder" ';
1644

    
1645
		$query_sql_sp    = $query_sql_fin_sp.$query_sql_ini_sp;
1646
		$query_sql_ip    = $query_sql_fin_ip.$query_sql_ini_ip;
1647
		$query_sql_sa    = $query_sql_fin_sa.$query_sql_ini_sa;
1648

    
1649
		Database::query($query_sql_sp);
1650
		Database::query($query_sql_ip);
1651
		Database::query($query_sql_sa);
1652

    
1653
	}
1654

    
1655
/**
1656
 * copy all directory and sub directory
1657
 * @param string The path origin
1658
 * @param string The path destination
1659
 * @param boolean Option Overwrite
1660
 * @return void()
1661
 */
1662
	function allow_create_all_directory($source, $dest, $overwrite = false) {
1663
   		if(!is_dir($dest)) {
1664
   			api_mkdir($dest, api_get_permissions_for_new_directories());
1665
   		}
1666

    
1667
	    if ($handle = opendir($source)) {        // if the folder exploration is sucsessful, continue
1668
	        while (false !== ($file = readdir($handle))) { // as long as storing the next file to $file is successful, continue
1669
	            if ($file != '.' && $file != '..') {
1670
	                $path = $source . '/' . $file;
1671
	                if (is_file($path)) {
1672
	                   /* if (!is_file($dest . '/' . $file) || $overwrite)
1673
	                    if (!@copy($path, $dest . '/' . $file)) {
1674
	                        echo '<font color="red">File ('.$path.') '.get_lang('NotHavePermission').'</font>';
1675
	                    }*/
1676
	                } elseif(is_dir($path)) {
1677
	                    if (!is_dir($dest . '/' . $file))
1678
	                    api_mkdir($dest . '/' . $file);
1679
	                   self:: allow_create_all_directory($path, $dest . '/' . $file, $overwrite);
1680
	                }
1681
	            }
1682
	        }
1683
	        closedir($handle);
1684
	    }
1685
	}
1686

    
1687
	/**
1688
	 * Gets the new ID of one specific tool item from the tool name and the old ID
1689
	 * @param	string	Tool name
1690
	 * @param	integer	Old ID
1691
	 * @return	integer	New ID
1692
	 */
1693
	function get_new_id($tool,$ref)
1694
	{
1695
		//transform $tool into one backup/restore constant
1696
		if($tool == 'hotpotatoes'){$tool = 'document';}
1697
		if(!empty($this->course->resources[$tool][$ref]->destination_id)){
1698
			return $this->course->resources[$tool][$ref]->destination_id;
1699
		}
1700
		return '';
1701
	}
1702
	/**
1703
	 * Restore glossary
1704
	 */
1705
	function restore_glossary($session_id = 0)
1706
	{
1707
		if ($this->course->has_resources(RESOURCE_GLOSSARY))
1708
		{
1709
			$table_glossary = Database :: get_course_table(TABLE_GLOSSARY, $this->course->destination_db);
1710
			$t_item_propery = Database :: get_course_table(TABLE_ITEM_PROPERTY, $this->course->destination_db);
1711
			$resources = $this->course->resources;
1712
			foreach ($resources[RESOURCE_GLOSSARY] as $id => $glossary) {
1713

    
1714
				$condition_session = "";
1715
    			if (!empty($session_id)) {
1716
    				$session_id = intval($session_id);
1717
    				$condition_session = " , session_id = '$session_id' ";
1718
    			}
1719

    
1720
				// check resources inside html from fckeditor tool and copy correct urls into recipient course
1721
                if (UTF8_CONVERT) $glossary->description = utf8_encode($glossary->description);
1722
				$glossary->description = DocumentManager::replace_urls_inside_content_html_from_copy_course($glossary->description, $this->course->code, $this->course->destination_path);
1723

    
1724
				$sql = "INSERT INTO ".$table_glossary." SET  name = '".Database::escape_string($glossary->name)."', description = '".Database::escape_string($glossary->description)."', display_order='".Database::escape_string($glossary->display_order)."' $condition_session ";
1725
				Database::query($sql);
1726
				$this->course->resources[RESOURCE_GLOSSARY][$id]->destination_id = Database::insert_id();
1727

    
1728
			}
1729
		}
1730
	}
1731

    
1732
	function restore_wiki($session_id = 0)
1733
	{
1734
		if ($this->course->has_resources(RESOURCE_WIKI))
1735
		{
1736
			// wiki table of the target course
1737
			$table_wiki = Database :: get_course_table('wiki', $this->course->destination_db);
1738
			$table_wiki_conf 	= Database :: get_course_table('wiki_conf', $this->course->destination_db);
1739

    
1740
			// storing all the resources that have to be copied in an array
1741
			$resources = $this->course->resources;
1742

    
1743
			foreach ($resources[RESOURCE_WIKI] as $id => $wiki)
1744
			{
1745
				//$wiki = new Wiki($obj->page_id, $obj->reflink, $obj->title, $obj->content, $obj->user_id, $obj->group_id, $obj->dtime);
1746
				// the sql statement to insert the groups from the old course to the new course
1747

    
1748
				// check resources inside html from fckeditor tool and copy correct urls into recipient course
1749
                if (UTF8_CONVERT) $wiki->content = utf8_encode($wiki->content);
1750
				$wiki->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($wiki->content, $this->course->code, $this->course->destination_path);
1751

    
1752
				$sql = "INSERT INTO $table_wiki (page_id, reflink, title, content, user_id, group_id, dtime, progress, version, session_id)
1753
							VALUES (
1754
							'".Database::escape_string($wiki->page_id)."',
1755
							'".Database::escape_string($wiki->reflink)."',
1756
							'".Database::escape_string($wiki->title)."',
1757
							'".Database::escape_string($wiki->content)."',
1758
							'".intval($wiki->user_id)."',
1759
							'".intval($wiki->group_id)."',
1760
							'".Database::escape_string($wiki->dtime)."',
1761
							'".Database::escape_string($wiki->progress)."',
1762
							'".intval($wiki->version)."',
1763
							'".(!empty($session_id)?intval($session_id):0)."')";
1764
				$rs2 = Database::query($sql);
1765
				$new_id = Database::insert_id();
1766
				$this->course->resources[RESOURCE_WIKI][$id]->destination_id = $new_id;
1767
				$sql = "UPDATE $table_wiki set page_id = '$new_id' WHERE id = '$new_id'";
1768
				Database::query($sql);
1769

    
1770
				// we also add an entry in wiki_conf
1771
				$sql = "INSERT INTO $table_wiki_conf
1772
						(page_id, task, feedback1, feedback2, feedback3, fprogress1, fprogress2, fprogress3, max_size, max_text, max_version, startdate_assig, enddate_assig, delayedsubmit)
1773
						VALUES
1774
						('".intval($new_id)."', '', '', '', '', '', '', '', NULL, 0, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0)";
1775
				$rs1 = Database::query($sql);
1776
			}
1777
		}
1778
	}
1779
}
(2-2/2)