# This patch file was generated by NetBeans IDE
# This patch can be applied using context Tools: Apply Diff Patch action on respective folder.
# It uses platform neutral UTF-8 encoding.
# Above lines and this line are ignored by the patching process.
Index: moodle/backup/import.php
--- moodle/backup/import.php No Base Revision
+++ moodle/backup/import.php Locally New
@@ -0,0 +1,151 @@
+<?php
+
+// Require both the backup and restore libs
+require_once('../config.php');
+require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
+require_once($CFG->dirroot . '/backup/moodle2/backup_plan_builder.class.php');
+require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
+require_once($CFG->dirroot . '/backup/util/ui/import_extensions.php');
+
+// The courseid we are importing to
+$courseid = required_param('id', PARAM_INT);
+// The id of the course we are importing FROM (will only be set if past first stage
+$importcourseid = optional_param('importid', false, PARAM_INT);
+// The target method for the restore (adding or deleting)
+$restoretarget = optional_param('target', backup::TARGET_CURRENT_ADDING, PARAM_INT);
+
+// Load the course and context
+$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
+$context = get_context_instance(CONTEXT_COURSE, $courseid);
+
+// Must pass login
+require_login($course);
+// Must hold restoretargetimport in the current course
+require_capability('moodle/restore:restoretargetimport', $context);
+
+$heading = get_string('import');
+
+// Set up the page
+$PAGE->set_title($heading);
+$PAGE->set_heading($heading);
+$PAGE->set_url(new moodle_url('/backup/import.php', array('id'=>$courseid)));
+$PAGE->set_context($context);
+$PAGE->set_pagelayout('incourse');
+
+// Prepare the backup renderer
+$renderer = $PAGE->get_renderer('core','backup');
+
+// Check if we already have a import course id
+if ($importcourseid === false) {
+    // Obviously not... show the selector so one can be chosen
+    $url = new moodle_url('/backup/import.php', array('id'=>$courseid));
+    $search = new import_course_search(array('url'=>$url));
+
+    // show the course selector
+    echo $OUTPUT->header();
+    echo $renderer->import_course_selector($url, $search);
+    echo $OUTPUT->footer();
+    die();
+}
+
+// Load the course +context to import from
+$importcourse = $DB->get_record('course', array('id'=>$importcourseid), '*', MUST_EXIST);
+$importcontext = get_context_instance(CONTEXT_COURSE, $importcourseid);
+
+// Make sure the user can backup from that course
+require_capability('moodle/backup:backuptargetimport', $importcontext);
+
+// Attempt to load the existing backup controller (backupid will be false if there isn't one)
+$backupid = optional_param('backup', false, PARAM_ALPHANUM);
+if (!($bc = backup_ui::load_controller($backupid))) {
+    $bc = new backup_controller(backup::TYPE_1COURSE, $importcourse->id, backup::FORMAT_MOODLE,
+                            backup::INTERACTIVE_YES, backup::MODE_GENERAL, $USER->id);
+    $bc->get_plan()->get_setting('users')->set_status(backup_setting::LOCKED_BY_CONFIG);
+    $settings = $bc->get_plan()->get_settings();
+
+    // For the initial stage we want to hide all locked settings and if there are
+    // no visible settings move to the next stage
+    $visiblesettings = false;
+    foreach ($settings as $setting) {
+        if ($setting->get_status() !== backup_setting::NOT_LOCKED) {
+            $setting->set_visibility(backup_setting::HIDDEN);
+        } else {
+            $visiblesettings = true;
+        }
+    }
+    import_ui::skip_current_stage(!$visiblesettings);
+}
+
+// Prepare the import UI
+$backup = new import_ui($bc, array('importid'=>$importcourse->id, 'target'=>$restoretarget));
+// Process the current stage
+$backup->process();
+
+// If this is the confirmation stage remove the filename setting
+if ($backup->get_stage() == backup_ui::STAGE_CONFIRMATION) {
+    $backup->get_setting('filename')->set_visibility(backup_setting::HIDDEN);
+}
+
+// If it's the final stage process the import
+if ($backup->get_stage() == backup_ui::STAGE_FINAL) {
+    // First execute the backup
+    $backup->execute();
+
+    // Check whether the backup directory still exists and if it doesn't extract the
+    // backup file so that we have it
+    $tempdestination = $CFG->dataroot . '/temp/backup/' . $backupid;
+    if (!file_exists($tempdestination) || !is_dir($tempdestination)) {
+        $results = $backup->get_controller()->get_results();
+        $file = $results['backup_destination'];
+        $file->extract_to_pathname(get_file_packer($file->get_mimetype()), $tempdestination);
+    }
+    // Delete the backup file, we only want the directory
+    $results['backup_destination']->delete();
+
+    // Prepare the restore controller. We don't need a UI here as we will just use what
+    // ever the restore has (the user has just chosen).
+    $rc = new restore_controller($backupid, $course->id, backup::INTERACTIVE_YES, backup::MODE_GENERAL, $USER->id, $restoretarget);
+    // Convert the backup if required.... it should NEVER happed
+    if ($rc->get_status() == backup::STATUS_REQUIRE_CONV) {
+        $rc->convert();
+    }
+    // Mark the UI finished.
+    $rc->finish_ui();
+    // Execute prechecks
+    if (!$rc->execute_precheck()) {
+        // TODO handle the precheck results
+        $rc->get_precheck_results();
+    } else {
+        // Execute the restore
+        $rc->execute_plan();
+    }
+
+    // Delete the temp directory now
+    fulldelete($tempdestination);
+
+    // Display a notification and a continue button
+    echo $OUTPUT->header();
+    echo $OUTPUT->notification(get_string('importsuccess', 'backup'),'notifysuccess');
+    echo $OUTPUT->continue_button(new moodle_url('/course/view.php', array('id'=>$course->id)));
+    echo $OUTPUT->footer();
+
+    die();
+
+} else {
+    // Otherwise save the controller and progress
+    $backup->save_controller();
+}
+
+// Adjust the page for the stage
+$PAGE->set_title($heading.': '.$backup->get_stage_name());
+$PAGE->set_heading($heading.': '.$backup->get_stage_name());
+$PAGE->navbar->add($backup->get_stage_name());
+
+// Display the current stage
+echo $OUTPUT->header();
+if ($backup->enforce_changed_dependencies()) {
+    echo $renderer->dependency_notification(get_string('dependenciesenforced','backup'));
+}
+echo $renderer->progress_bar($backup->get_progress_bar());
+echo $backup->display();
+echo $OUTPUT->footer();
\ No newline at end of file
Index: moodle/backup/restore.php
--- moodle/backup/restore.php Base (1.77)
+++ moodle/backup/restore.php Locally Modified (Based On 1.77)
@@ -17,8 +17,6 @@
 require_login($course, null, $cm);
 require_capability('moodle/restore:restorecourse', $context);
 
-$isfrontpage = ($course->id == SITEID);
-
 if ($stage & restore_ui::STAGE_CONFIRM + restore_ui::STAGE_DESTINATION) {
     $restore = restore_ui::engage_independent_stage($stage, $contextid);
 } else {
Index: moodle/backup/util/ui/backup_ui.class.php
--- moodle/backup/util/ui/backup_ui.class.php Base (1.7)
+++ moodle/backup/util/ui/backup_ui.class.php Locally Modified (Based On 1.7)
@@ -42,6 +42,8 @@
     const STAGE_FINAL = 8;
     const STAGE_COMPLETE = 16;
 
+    protected static $skipcurrentstage = false;
+
     /**
      * Intialises what ever stage is requested. If none are requested we check
      * params for 'stage' and default to initial
@@ -53,6 +55,9 @@
         if ($stage == null) {
             $stage = optional_param('stage', self::STAGE_INITIAL, PARAM_INT);
         }
+        if (self::$skipcurrentstage) {
+            $stage *= 2;
+        }
         switch ($stage) {
             case backup_ui::STAGE_INITIAL:
                 $stage = new backup_ui_stage_initial($this, $params);
@@ -150,8 +155,8 @@
                 $classes[] = 'backup_stage_complete';
             }
             $item = array('text' => strlen(decbin($stage)).'. '.get_string('currentstage'.$stage, 'backup'),'class' => join(' ', $classes));
-            if ($stage < $currentstage && $currentstage < self::STAGE_COMPLETE) {
-                $item['link'] = new moodle_url($PAGE->url, array('backup'=>$this->get_backupid(), 'stage'=>$stage));
+            if ($stage < $currentstage && $currentstage < self::STAGE_COMPLETE && (!self::$skipcurrentstage || $stage*2 != $currentstage)) {
+                $item['link'] = new moodle_url($PAGE->url, $this->stage->get_params() + array('backup'=>$this->get_backupid(), 'stage'=>$stage));
             }
             array_unshift($items, $item);
             $stage = floor($stage/2);
@@ -166,7 +171,11 @@
     public function get_first_stage_id() {
         return self::STAGE_INITIAL;
     }
+
+    public static function skip_current_stage($setting=true) {
+        self::$skipcurrentstage = $setting;
 }
+}
\ No newline at end of file
 
 /**
  * Backup user interface exception. Modelled off the backup_exception class
Index: moodle/backup/util/ui/base_moodleform.class.php
--- moodle/backup/util/ui/base_moodleform.class.php Base (1.2)
+++ moodle/backup/util/ui/base_moodleform.class.php Locally Modified (Based On 1.2)
@@ -257,4 +257,33 @@
     public function is_cancelled() {
         return (optional_param('cancel', false, PARAM_BOOL) || parent::is_cancelled());
     }
+
+    public function remove_element($elementName) {
+        return $this->_form->removeElement($elementName);
 }
+
+    /**
+     *
+     * @param string $elementname
+     * @return HTML_QuickForm_input|MoodleQuickForm_group
+     */
+    public function get_element($elementname) {
+        if ($this->_form->elementExists($elementname)) {
+            return $this->_form->getElement($elementname);
+        } else {
+            return false;
+        }
+    }
+
+    public function display() {
+        $this->require_definition_after_data();
+        parent::display();
+    }
+
+    public function require_definition_after_data() {
+        if (!$this->_definition_finalized) {
+            $this->_definition_finalized = true;
+            $this->definition_after_data();
+        }
+    }
+}
\ No newline at end of file
Index: moodle/backup/util/ui/import_extensions.php
--- moodle/backup/util/ui/import_extensions.php No Base Revision
+++ moodle/backup/util/ui/import_extensions.php Locally New
@@ -0,0 +1,98 @@
+<?php
+
+class import_ui extends backup_ui {
+
+    public function get_progress_bar() {
+        global $PAGE;
+        $stage = self::STAGE_COMPLETE;
+        $currentstage = $this->stage->get_stage();
+        $items = array();
+        while ($stage > 0) {
+            $classes = array('backup_stage');
+            if (floor($stage/2) == $currentstage) {
+                $classes[] = 'backup_stage_next';
+            } else if ($stage == $currentstage) {
+                $classes[] = 'backup_stage_current';
+            } else if ($stage < $currentstage) {
+                $classes[] = 'backup_stage_complete';
+            }
+            $item = array('text' => strlen(decbin($stage*2)).'. '.get_string('importcurrentstage'.$stage, 'backup'),'class' => join(' ', $classes));
+            if ($stage < $currentstage && $currentstage < self::STAGE_COMPLETE && (!self::$skipcurrentstage || $stage*2 != $currentstage)) {
+                $item['link'] = new moodle_url($PAGE->url, $this->stage->get_params() + array('backup'=>$this->get_backupid(), 'stage'=>$stage));
+            }
+            array_unshift($items, $item);
+            $stage = floor($stage/2);
+        }
+        $selectorlink = new moodle_url($PAGE->url, $this->stage->get_params());
+        $selectorlink->remove_params('importid');
+        array_unshift($items, array(
+                'text' => '1. '.get_string('importcurrentstage0', 'backup'),
+                'class' => join(' ', $classes),
+                'link' => $selectorlink));
+        return $items;
+    }
+
+    /**
+     * Intialises what ever stage is requested. If none are requested we check
+     * params for 'stage' and default to initial
+     *
+     * @param int|null $stage The desired stage to intialise or null for the default
+     * @return backup_ui_stage_initial|backup_ui_stage_schema|backup_ui_stage_confirmation|backup_ui_stage_final
+     */
+    protected function initialise_stage($stage = null, array $params=null) {
+        if ($stage == null) {
+            $stage = optional_param('stage', self::STAGE_INITIAL, PARAM_INT);
+        }
+        if (self::$skipcurrentstage) {
+            $stage *= 2;
+        }
+        switch ($stage) {
+            case backup_ui::STAGE_INITIAL:
+                $stage = new import_ui_stage_inital($this, $params);
+                break;
+            case backup_ui::STAGE_SCHEMA:
+                $stage = new import_ui_stage_schema($this, $params);
+                break;
+            case backup_ui::STAGE_CONFIRMATION:
+                $stage = new import_ui_stage_confirmation($this, $params);
+                break;
+            case backup_ui::STAGE_FINAL:
+                $stage = new import_ui_stage_final($this, $params);
+                break;
+            default:
+                $stage = false;
+                break;
+        }
+        return $stage;
+    }
+}
+
+class import_ui_stage_inital extends backup_ui_stage_initial {}
+class import_ui_stage_schema extends backup_ui_stage_schema {}
+class import_ui_stage_confirmation extends backup_ui_stage_confirmation {
+
+    protected function initialise_stage_form() {
+        $form = parent::initialise_stage_form();
+        $form->remove_element('filenamesetting');
+        return $form;
+    }
+
+    public function display() {
+        $form = $this->initialise_stage_form();
+        $form->require_definition_after_data();
+        if ($e = $form->get_element('submitbutton')) {
+            $e->setLabel(get_string('import'.$this->get_ui()->get_name().'stage'.$this->get_stage().'action', 'backup'));
+        } else {
+            $elements = $form->get_element('buttonar')->getElements();
+            foreach ($elements as &$element) {
+                if ($element->getName()=='submitbutton') {
+                    $element->setValue(get_string('import'.$this->get_ui()->get_name().'stage'.$this->get_stage().'action', 'backup'));
+                }
+            }
+        }
+        $form->display();
+    }
+}
+class import_ui_stage_final extends backup_ui_stage_final {}
+
+class import_course_search extends restore_course_search {}
\ No newline at end of file
Index: moodle/backup/util/ui/renderer.php
--- moodle/backup/util/ui/renderer.php Base (1.8)
+++ moodle/backup/util/ui/renderer.php Locally Modified (Based On 1.8)
@@ -146,7 +146,7 @@
         return $html;
     }
 
-    public function course_selector(moodle_url $nextstageurl, $details, $categories, restore_course_search $courses=null, $currentcourse = null) {
+    public function course_selector(moodle_url $nextstageurl, $details, restore_category_search $categories = null, restore_course_search $courses=null, $currentcourse = null) {
         global $CFG;
         require_once($CFG->dirroot.'/course/lib.php');
 
@@ -172,7 +172,7 @@
             $html .= html_writer::end_tag('form');
         }
 
-        if ($categories->get_resultscount() > 0 || $categories->get_search() == '') {
+        if (!empty($categories) && ($categories->get_resultscount() > 0 || $categories->get_search() == '')) {
             // New course
             $html .= $form;
             $html .= html_writer::start_tag('div', array('class'=>'bcs-new-course backup-section'));
@@ -185,7 +185,7 @@
             $html .= html_writer::end_tag('form');
         }
 
-        if ($courses->get_resultscount() > 0 || $courses->get_search() == '') {
+        if (!empty($courses) && ($courses->get_resultscount() > 0 || $courses->get_search() == '')) {
             // Existing course
             $html .= $form;
             $html .= html_writer::start_tag('div', array('class'=>'bcs-existing-course backup-section'));
@@ -202,6 +202,24 @@
         return $html;
     }
 
+    public function import_course_selector(moodle_url $nextstageurl, import_course_search $courses=null) {
+        $html  = html_writer::start_tag('div', array('class'=>'import-course-selector backup-restore'));
+        $html .= html_writer::start_tag('form', array('method'=>'post', 'action'=>$nextstageurl->out_omit_querystring()));
+        foreach ($nextstageurl->params() as $key=>$value) {
+            $html .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$key, 'value'=>$value));
+        }
+        $html .= html_writer::start_tag('div', array('class'=>'ics-existing-course backup-section'));
+        $html .= $this->output->heading(get_string('importdatafrom'), 2, array('class'=>'header'));
+        $html .= $this->backup_detail_input(get_string('importadding', 'backup'), 'radio', 'target', backup::TARGET_CURRENT_ADDING, array('checked'=>'checked'), get_string('importadding', 'backup'));
+        $html .= $this->backup_detail_input(get_string('importdeleting', 'backup'), 'radio', 'target', backup::TARGET_CURRENT_DELETING, array(), get_string('importdeletingdesc', 'backup'));
+        $html .= $this->backup_detail_pair(get_string('selectacourse', 'backup'), $this->render($courses));
+        $html .= $this->backup_detail_pair('', html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('continue'))));
+        $html .= html_writer::end_tag('div');
+        $html .= html_writer::end_tag('form');
+        $html .= html_writer::end_tag('div');
+        return $html;
+    }
+
     protected function backup_detail_pair($label, $value) {
         static $count= 0;
         $count++;
@@ -386,6 +404,55 @@
         return $output;
     }
 
+    public function render_import_course_search(import_course_search $component) {
+        $url = $component->get_url();
+
+        $output = html_writer::start_tag('div', array('class' => 'import-course-search'));
+        if ($component->get_totalcount() === 0) {
+            $output .= $this->output->notification(get_string('nomatchingcourses', 'backup'));
+            $output .= html_writer::end_tag('div');
+            return $output;
+        }
+
+        $output .= html_writer::tag('div', get_string('totalcoursesearchresults', 'backup', $component->get_totalcount()), array('class'=>'ics-totalresults'));
+
+        $output .= html_writer::start_tag('div', array('class' => 'ics-results'));
+        if ($component->get_totalpages()>1) {
+            $pagingbar = new paging_bar($component->get_totalcount(), $component->get_page(), $component->get_pagelimit(), new moodle_url($url, array('searchcourses'=>1)), restore_course_search::$VAR_PAGE);
+            $output .= $this->output->render($pagingbar);
+        }
+
+        $table = new html_table();
+        $table->head = array('', get_string('shortname'), get_string('fullname'));
+        $table->data = array();
+        foreach ($component->get_results() as $course) {
+            $row = new html_table_row();
+            $row->attributes['class'] = 'ics-course';
+            if (!$course->visible) {
+                $row->attributes['class'] .= ' dimmed';
+            }
+            $row->cells = array(
+                html_writer::empty_tag('input', array('type'=>'radio', 'name'=>'importid', 'value'=>$course->id)),
+                $course->shortname,
+                $course->fullname
+            );
+            $table->data[] = $row;
+        }
+        $output .= html_writer::table($table);
+        if (isset($pagingbar)) {
+            $output .= $this->output->render($pagingbar);
+        }
+        $output .= html_writer::end_tag('div');
+
+        $output .= html_writer::start_tag('div', array('class'=>'ics-search'));
+        $output .= html_writer::empty_tag('input', array('type'=>'text', 'name'=>restore_course_search::$VAR_SEARCH, 'value'=>$component->get_search()));
+        $output .= html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'searchcourses', 'value'=>get_string('search')));
+        $output .= html_writer::end_tag('div');
+
+        $output .= html_writer::end_tag('div');
+        return $output;
+    }
+
     public function render_restore_category_search(restore_category_search $component) {
         $url = $component->get_url();
 
Index: moodle/lang/en/backup.php
--- moodle/lang/en/backup.php Base (1.13)
+++ moodle/lang/en/backup.php Locally Modified (Based On 1.13)
@@ -88,6 +88,22 @@
 $string['generaluserfiles'] = 'Include user files';
 $string['generalusers'] = 'Include users';
 $string['importfile'] = 'Import a backup file';
+$string['importadding'] = 'Import adding';
+$string['importaddingdesc'] = 'Merge the selected course into this course';
+$string['importbackupstage1action'] = 'Next';
+$string['importbackupstage2action'] = 'Next';
+$string['importbackupstage4action'] = 'Perform import';
+$string['importbackupstage8action'] = 'Continue';
+$string['importbackupstage16action'] = 'Continue';
+$string['importcurrentstage0'] = 'Course selection';
+$string['importcurrentstage1'] = 'Initial settings';
+$string['importcurrentstage2'] = 'Schema settings';
+$string['importcurrentstage4'] = 'Confirmation and review';
+$string['importcurrentstage8'] = 'Perform import';
+$string['importcurrentstage16'] = 'Complete';
+$string['importdeleting'] = 'Import deleting';
+$string['importdeletingdesc'] = 'Delete the contents of this course and then import the selected course';
+$string['importsuccess'] = 'Import complete. Click continue to return to the course.';
\ No newline at end of file
 $string['includeactivities'] = 'Choose activities to include';
 $string['includesection'] = 'Include section {$a}';
 $string['includeuserinfo'] = 'Include user information';
Index: moodle/lib/navigationlib.php
--- moodle/lib/navigationlib.php Base (1.171)
+++ moodle/lib/navigationlib.php Locally Modified (Based On 1.171)
@@ -2855,8 +2855,7 @@
 
         // Import data from other courses
         if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
-            $url = new moodle_url('/course/import.php', array('id'=>$course->id));
-            $url = null; // Disabled until restore is implemented. MDL-21432
+            $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
             $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
         }
 
Index: moodle/mod/data/lib.php
--- moodle/mod/data/lib.php Base (1.287)
+++ moodle/mod/data/lib.php Locally Modified (Based On 1.287)
@@ -22,16 +22,21 @@
  */
 
 // Some constants
-define ('DATA_MAX_ENTRIES', 50);
-define ('DATA_PERPAGE_SINGLE', 1);
+define('DATA_MAX_ENTRIES', 50);
+define('DATA_PERPAGE_SINGLE', 1);
 
-define ('DATA_FIRSTNAME', -1);
-define ('DATA_LASTNAME', -2);
-define ('DATA_APPROVED', -3);
-define ('DATA_TIMEADDED', 0);
-define ('DATA_TIMEMODIFIED', -4);
+define('DATA_FIRSTNAME', -1);
+define('DATA_LASTNAME', -2);
+define('DATA_APPROVED', -3);
+define('DATA_TIMEADDED', 0);
+define('DATA_TIMEMODIFIED', -4);
 
-define ('DATA_CAP_EXPORT', 'mod/data:viewalluserpresets');
+define('DATA_CAP_EXPORT', 'mod/data:viewalluserpresets');
+
+define('DATA_PRESET_COMPONENT', 'mod_data');
+define('DATA_PRESET_FILEAREA', 'site_presets');
+define('DATA_PRESET_CONTEXT', SYSCONTEXTID);
+
 // Users having assigned the default role "Non-editing teacher" can export database records
 // Using the mod/data capability "viewalluserpresets" existing in Moodle 1.9.x.
 // In Moodle >= 2, new roles may be introduced and used instead.
@@ -1868,37 +1873,49 @@
             }
         }
     }
+    $presets = data_get_available_site_presets($context, $presets);
+    return $presets;
+}
 
-    if ($userids = get_list_of_plugins('data/preset', '', $CFG->dataroot)) {
+function data_get_available_site_presets($context, array $presets=array()) {
+    $fs = get_file_storage();
+    $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
         $canviewall = has_capability('mod/data:viewalluserpresets', $context);
-        foreach ($userids as $userid) {
-            $fulldir = $CFG->dataroot.'/data/preset/'.$userid;
-            if ($userid == 0 || $USER->id == $userid || $canviewall) {
-                if ($dirs = get_list_of_plugins('data/preset/'.$userid, '', $CFG->dataroot)) {
-                    foreach ($dirs as $dir) {
-                        $fulldir = $CFG->dataroot.'/data/preset/'.$userid.'/'.$dir;
-                        if (is_directory_a_preset($fulldir)) {
-                            $preset = new object;
-                            $preset->path = $fulldir;
-                            $preset->userid = $userid;
-                            $preset->shortname = $dir;
-                            $preset->name = $preset->shortname;
-                            if (file_exists($fulldir.'/screenshot.jpg')) {
-                                $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
-                            } else if (file_exists($fulldir.'/screenshot.png')) {
-                                $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
-                            } else if (file_exists($fulldir.'/screenshot.gif')) {
-                                $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
+    if (empty($files)) {
+        return $presets;
                             }
+    foreach ($files as $file) {
+        if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
+            continue;
+        }
+        $preset = new stdClass;
+        $preset->path = $file->get_filepath();
+        $preset->name = trim($preset->path, '/');
+        $preset->shortname = $preset->name;
+        $preset->userid = $file->get_userid();
+        $preset->id = $file->get_id();
+        $preset->storedfile = $file;
                             $presets[] = $preset;
                         }
+    return $presets;
                     }
+
+function data_delete_site_preset($name) {
+    $fs = get_file_storage();
+
+    $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
+    if (!empty($files)) {
+        foreach ($files as $file) {
+            $file->delete();
                 }
             }
+
+    $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
+    if (!empty($dir)) {
+        $dir->delete();
         }
-    }
 
-    return $presets;
+    return true;
 }
 
 /**
@@ -2857,13 +2874,54 @@
     }
 }
 
-function data_presets_export($course, $cm, $data) {
-    global $CFG, $DB;
-    $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
-    $exportsubdir = "$course->id/moddata/data/$data->id/$presetname";
-    make_upload_directory($exportsubdir);
-    $exportdir = "$CFG->dataroot/$exportsubdir";
+function data_presets_save($course, $cm, $data, $path) {
+    $fs = get_file_storage();
+    $filerecord = new stdClass;
+    $filerecord->contextid = DATA_PRESET_CONTEXT;
+    $filerecord->component = DATA_PRESET_COMPONENT;
+    $filerecord->filearea = DATA_PRESET_FILEAREA;
+    $filerecord->itemid = 0;
+    $filerecord->filepath = '/'.$path.'/';
 
+    $filerecord->filename = 'preset.xml';
+    $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
+
+    $filerecord->filename = 'singletemplate.html';
+    $fs->create_file_from_string($filerecord, $data->singletemplate);
+
+    $filerecord->filename = 'listtemplateheader.html';
+    $fs->create_file_from_string($filerecord, $data->listtemplateheader);
+
+    $filerecord->filename = 'listtemplate.html';
+    $fs->create_file_from_string($filerecord, $data->listtemplate);
+
+    $filerecord->filename = 'listtemplatefooter.html';
+    $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
+
+    $filerecord->filename = 'addtemplate.html';
+    $fs->create_file_from_string($filerecord, $data->addtemplate);
+
+    $filerecord->filename = 'rsstemplate.html';
+    $fs->create_file_from_string($filerecord, $data->rsstemplate);
+
+    $filerecord->filename = 'rsstitletemplate.html';
+    $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
+
+    $filerecord->filename = 'csstemplate.css';
+    $fs->create_file_from_string($filerecord, $data->csstemplate);
+
+    $filerecord->filename = 'jstemplate.js';
+    $fs->create_file_from_string($filerecord, $data->jstemplate);
+
+    $filerecord->filename = 'asearchtemplate.html';
+    $fs->create_file_from_string($filerecord, $data->asearchtemplate);
+
+    return true;
+}
+
+function data_presets_generate_xml($course, $cm, $data) {
+    global $DB;
+    
     // Assemble "preset.xml":
     $presetxmldata = "<preset>\n\n";
 
@@ -2892,7 +2950,6 @@
         $presetxmldata .= "<defaultsort>0</defaultsort>\n";
     }
     $presetxmldata .= "</settings>\n\n";
-
     // Now for the fields. Grab all that are non-empty
     $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
     ksort($fields);
@@ -2908,7 +2965,22 @@
         }
     }
     $presetxmldata .= '</preset>';
+    return $presetxmldata;
+}
 
+function data_presets_export($course, $cm, $data, $tostorage=false) {
+    global $CFG, $DB;
+
+    $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
+    $exportsubdir = "$course->id/moddata/data/$data->id/$presetname";
+    make_upload_directory($exportsubdir);
+    $exportdir = "$CFG->dataroot/$exportsubdir";
+
+    
+
+    // Assemble "preset.xml":
+    $presetxmldata = data_presets_generate_xml($course, $cm, $data);
+
\ No newline at end of file
     // After opening a file in write mode, close it asap
     $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
     fwrite($presetxmlfile, $presetxmldata);
Index: moodle/mod/data/preset.php
--- moodle/mod/data/preset.php Base (1.56)
+++ moodle/mod/data/preset.php Locally Modified (Based On 1.56)
@@ -135,21 +135,21 @@
 
     } else if ($formdata = $form_save->get_data()) {
 
-        $presetdirectory = "/data/preset/$USER->id/{$formdata->name}";
+        debug($formdata);
+        if (!empty($formdata->overwrite)) {
+            debug('deleteing now');
+            data_delete_site_preset($formdata->name);
+        }
 
-        if (file_exists($CFG->dataroot.$presetdirectory)) {
-            if (!$formdata->overwrite) {
+        $sitepresets = data_get_available_site_presets($context);
+        foreach ($sitepresets as $key=>$preset) {
+            if ($formdata->name == $preset->name) {
                 print_error('errorpresetexists', 'preset');
-            } else {
-                fulldelete($CFG->dataroot.$presetdirectory);
             }
         }
-        make_upload_directory($presetdirectory);
 
-        $file = data_presets_export($course, $cm, $data);
-        if (!unzip_file($file, $CFG->dataroot.$presetdirectory, false)) {
-            print_error('cannotunziptopreset', 'data');
-        }
\ No newline at end of file
+        data_presets_save($course, $cm, $data, $formdata->name);
+
\ No newline at end of file
         echo $OUTPUT->notification(get_string('savesuccess', 'data'), 'notifysuccess');
         echo $OUTPUT->continue_button($PAGE->url);
         echo $OUTPUT->footer();
Index: moodle/mod/data/preset_form.php
--- moodle/mod/data/preset_form.php Base (1.1)
+++ moodle/mod/data/preset_form.php Locally Modified (Based On 1.1)
@@ -51,7 +51,7 @@
         $this->_form->addElement('text', 'name', get_string('shortname'));
         $this->_form->setType('name', PARAM_FILE);
         $this->_form->addRule('name', null, 'required');
-        $this->_form->addElement('checkbox', 'override', get_string('overwrite', 'data'), get_string('overrwritedesc', 'data'));
\ No newline at end of file
+        $this->_form->addElement('checkbox', 'overwrite', get_string('overwrite', 'data'), get_string('overrwritedesc', 'data'));
\ No newline at end of file
         $this->_form->addElement('submit', 'saveaspreset', get_string('continue'));
     }
 }
