Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
// This file is part of Moodle - http://moodle.org/
4
//
5
// Moodle is free software: you can redistribute it and/or modify
6
// it under the terms of the GNU General Public License as published by
7
// the Free Software Foundation, either version 3 of the License, or
8
// (at your option) any later version.
9
//
10
// Moodle is distributed in the hope that it will be useful,
11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
// GNU General Public License for more details.
14
//
15
// You should have received a copy of the GNU General Public License
16
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17
 
18
/**
19
 * @package    moodlecore
20
 * @subpackage backup-dbops
21
 * @copyright  2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
/**
26
 * Non instantiable helper class providing DB support to the @restore_controller
27
 *
28
 * This class contains various static methods available for all the DB operations
29
 * performed by the restore_controller class
30
 *
31
 * TODO: Finish phpdocs
32
 */
33
abstract class restore_controller_dbops extends restore_dbops {
34
 
35
    /**
36
     * Send one restore controller to DB
37
     *
38
     * @param restore_controller $controller controller to send to DB
39
     * @param string $checksum hash of the controller to be checked
40
     * @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
41
     * @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
42
     * @return int id of the controller record in the DB
43
     * @throws backup_controller_exception|restore_dbops_exception
44
     */
45
    public static function save_controller($controller, $checksum, $includeobj = true, $cleanobj = false) {
46
        global $DB;
47
        // Check we are going to save one backup_controller
48
        if (! $controller instanceof restore_controller) {
49
            throw new backup_controller_exception('restore_controller_expected');
50
        }
51
        // Check checksum is ok. Only if we are including object info. Sounds silly but it isn't ;-).
52
        if ($includeobj and !$controller->is_checksum_correct($checksum)) {
53
            throw new restore_dbops_exception('restore_controller_dbops_saving_checksum_mismatch');
54
        }
55
        // Cannot request to $includeobj and $cleanobj at the same time.
56
        if ($includeobj and $cleanobj) {
57
            throw new restore_dbops_exception('restore_controller_dbops_saving_cannot_include_and_delete');
58
        }
59
        // Get all the columns
60
        $rec = new stdclass();
61
        $rec->backupid     = $controller->get_restoreid();
62
        $rec->operation    = $controller->get_operation();
63
        $rec->type         = $controller->get_type();
64
        $rec->itemid       = $controller->get_courseid();
65
        $rec->format       = $controller->get_format();
66
        $rec->interactive  = $controller->get_interactive();
67
        $rec->purpose      = $controller->get_mode();
68
        $rec->userid       = $controller->get_userid();
69
        $rec->status       = $controller->get_status();
70
        $rec->execution    = $controller->get_execution();
71
        $rec->executiontime= $controller->get_executiontime();
72
        $rec->checksum     = $checksum;
73
        // Serialize information
74
        if ($includeobj) {
75
            $rec->controller = base64_encode(serialize($controller));
76
        } else if ($cleanobj) {
77
            $rec->controller = '';
78
        }
79
        // Send it to DB
80
        if ($recexists = $DB->get_record('backup_controllers', array('backupid' => $rec->backupid))) {
81
            $rec->id = $recexists->id;
82
            $rec->timemodified = time();
83
            $DB->update_record('backup_controllers', $rec);
84
        } else {
85
            $rec->timecreated = time();
86
            $rec->timemodified = 0;
87
            $rec->id = $DB->insert_record('backup_controllers', $rec);
88
        }
89
        return $rec->id;
90
    }
91
 
92
    public static function load_controller($restoreid) {
93
        global $DB;
94
        if (! $controllerrec = $DB->get_record('backup_controllers', array('backupid' => $restoreid))) {
95
            throw new backup_dbops_exception('restore_controller_dbops_nonexisting');
96
        }
97
        $controller = unserialize(base64_decode($controllerrec->controller));
98
        if (!is_object($controller)) {
99
            // The controller field of the table did not contain a serialized object.
100
            // It is made empty after it has been used successfully, it is likely that
101
            // the user has pressed the browser back button at some point.
102
            throw new backup_dbops_exception('restore_controller_dbops_loading_invalid_controller');
103
        }
104
        // Check checksum is ok. Sounds silly but it isn't ;-)
105
        if (!$controller->is_checksum_correct($controllerrec->checksum)) {
106
            throw new backup_dbops_exception('restore_controller_dbops_loading_checksum_mismatch');
107
        }
108
        return $controller;
109
    }
110
 
111
    public static function create_restore_temp_tables($restoreid) {
112
        global $CFG, $DB;
113
        $dbman = $DB->get_manager(); // We are going to use database_manager services
114
 
115
        if ($dbman->table_exists('backup_ids_temp')) { // Table exists, from restore prechecks
116
            // TODO: Improve this by inserting/selecting some record to see there is restoreid match
117
            // TODO: If not match, exception, table corresponds to another backup/restore operation
118
            return true;
119
        }
120
        backup_controller_dbops::create_backup_ids_temp_table($restoreid);
121
        backup_controller_dbops::create_backup_files_temp_table($restoreid);
122
        return false;
123
    }
124
 
125
    public static function drop_restore_temp_tables($backupid) {
126
        global $DB;
127
        $dbman = $DB->get_manager(); // We are going to use database_manager services
128
 
129
        $targettablenames = array('backup_ids_temp', 'backup_files_temp');
130
        foreach ($targettablenames as $targettablename) {
131
            $table = new xmldb_table($targettablename);
132
            $dbman->drop_table($table); // And drop it
133
        }
134
        // Invalidate the backup_ids caches.
135
        restore_dbops::reset_backup_ids_cached();
136
    }
137
 
138
    /**
139
     * Sets the default values for the settings in a restore operation
140
     *
141
     * @param restore_controller $controller
142
     */
143
    public static function apply_config_defaults(restore_controller $controller) {
144
 
145
        $settings = array(
146
            'restore_general_users'              => 'users',
147
            'restore_general_enrolments'         => 'enrolments',
148
            'restore_general_role_assignments'   => 'role_assignments',
149
            'restore_general_permissions'        => 'permissions',
150
            'restore_general_activities'         => 'activities',
151
            'restore_general_blocks'             => 'blocks',
152
            'restore_general_filters'            => 'filters',
153
            'restore_general_comments'           => 'comments',
154
            'restore_general_badges'             => 'badges',
155
            'restore_general_calendarevents'     => 'calendarevents',
156
            'restore_general_userscompletion'    => 'userscompletion',
157
            'restore_general_logs'               => 'logs',
158
            'restore_general_histories'          => 'grade_histories',
159
            'restore_general_groups'             => 'groups',
160
            'restore_general_competencies'       => 'competencies',
1441 ariadna 161
            'restore_general_customfield'        => 'customfield',
1 efrain 162
            'restore_general_contentbankcontent' => 'contentbankcontent',
163
            'restore_general_xapistate'          => 'xapistate',
164
            'restore_general_legacyfiles'        => 'legacyfiles'
165
        );
166
        self::apply_admin_config_defaults($controller, $settings, true);
167
 
168
        $target = $controller->get_target();
169
        if ($target == backup::TARGET_EXISTING_ADDING || $target == backup::TARGET_CURRENT_ADDING) {
170
            $settings = array(
171
                'restore_merge_overwrite_conf'  => 'overwrite_conf',
172
                'restore_merge_course_fullname'  => 'course_fullname',
173
                'restore_merge_course_shortname' => 'course_shortname',
174
                'restore_merge_course_startdate' => 'course_startdate',
175
            );
176
            self::apply_admin_config_defaults($controller, $settings, true);
177
        }
178
 
179
        if ($target == backup::TARGET_EXISTING_DELETING || $target == backup::TARGET_CURRENT_DELETING) {
180
            $settings = array(
181
                'restore_replace_overwrite_conf'  => 'overwrite_conf',
182
                'restore_replace_course_fullname'  => 'course_fullname',
183
                'restore_replace_course_shortname' => 'course_shortname',
184
                'restore_replace_course_startdate' => 'course_startdate',
185
                'restore_replace_keep_roles_and_enrolments' => 'keep_roles_and_enrolments',
186
                'restore_replace_keep_groups_and_groupings' => 'keep_groups_and_groupings',
187
            );
188
            self::apply_admin_config_defaults($controller, $settings, true);
189
        }
190
        if ($controller->get_mode() == backup::MODE_IMPORT &&
191
                (!$controller->get_interactive()) &&
192
                $controller->get_type() == backup::TYPE_1ACTIVITY) {
193
            // This is duplicate - there is no concept of defaults - these settings must be on.
194
            $settings = array(
195
                    'activities',
196
                    'blocks',
197
                    'filters',
198
            );
199
            self::force_enable_settings($controller, $settings);
200
        };
201
 
202
        // Add some dependencies.
203
        $plan = $controller->get_plan();
204
        if ($plan->setting_exists('overwrite_conf')) {
205
            /** @var restore_course_overwrite_conf_setting $overwriteconf */
206
            $overwriteconf = $plan->get_setting('overwrite_conf');
207
            if ($overwriteconf->get_visibility()) {
208
                foreach (['course_fullname', 'course_shortname', 'course_startdate'] as $settingname) {
209
                    if ($plan->setting_exists($settingname)) {
210
                        $setting = $plan->get_setting($settingname);
211
                        $overwriteconf->add_dependency($setting, setting_dependency::DISABLED_FALSE,
212
                            array('defaultvalue' => $setting->get_value()));
213
                    }
214
                }
215
            }
216
        }
217
    }
218
 
219
    /**
220
     * Returns the default value to be used for a setting from the admin restore config
221
     *
222
     * @param string $config
223
     * @param backup_setting $setting
224
     * @return mixed
225
     */
226
    private static function get_setting_default($config, $setting) {
227
        $value = get_config('restore', $config);
228
 
229
        if (in_array($setting->get_name(), ['course_fullname', 'course_shortname', 'course_startdate']) &&
230
                $setting->get_ui() instanceof backup_setting_ui_defaultcustom) {
231
            // Special case - admin config settings course_fullname, etc. are boolean and the restore settings are strings.
232
            $value = (bool)$value;
233
            if ($value) {
234
                $attributes = $setting->get_ui()->get_attributes();
235
                $value = $attributes['customvalue'];
236
            }
237
        }
238
 
239
        if ($setting->get_ui() instanceof backup_setting_ui_select) {
240
            // Make sure the value is a valid option in the select element, otherwise just pick the first from the options list.
241
            // Example: enrolments dropdown may not have the "enrol_withusers" option because users info can not be restored.
242
            $options = array_keys($setting->get_ui()->get_values());
243
            if (!in_array($value, $options)) {
244
                $value = reset($options);
245
            }
246
        }
247
 
248
        return $value;
249
    }
250
 
251
    /**
252
     * Turn these settings on. No defaults from admin settings.
253
     *
254
     * @param restore_controller $controller
255
     * @param array $settings a map from admin config names to setting names (Config name => Setting name)
256
     */
257
    private static function force_enable_settings(restore_controller $controller, array $settings) {
258
        $plan = $controller->get_plan();
259
        foreach ($settings as $config => $settingname) {
260
            $value = true;
261
            if ($plan->setting_exists($settingname)) {
262
                $setting = $plan->get_setting($settingname);
263
                // We do not allow this setting to be locked for a duplicate function.
264
                if ($setting->get_status() !== base_setting::NOT_LOCKED) {
265
                    $setting->set_status(base_setting::NOT_LOCKED);
266
                }
267
                $setting->set_value($value);
268
                $setting->set_status(base_setting::LOCKED_BY_CONFIG);
269
            } else {
270
                $controller->log('Unknown setting: ' . $settingname, BACKUP::LOG_DEBUG);
271
            }
272
        }
273
    }
274
 
275
    /**
276
     * Sets the controller settings default values from the admin config.
277
     *
278
     * @param restore_controller $controller
279
     * @param array $settings a map from admin config names to setting names (Config name => Setting name)
280
     * @param boolean $uselocks whether "locked" admin settings should be honoured
281
     */
282
    private static function apply_admin_config_defaults(restore_controller $controller, array $settings, $uselocks) {
283
        $plan = $controller->get_plan();
284
        foreach ($settings as $config => $settingname) {
285
            if ($plan->setting_exists($settingname)) {
286
                $setting = $plan->get_setting($settingname);
287
                $value = self::get_setting_default($config, $setting);
288
                $locked = (get_config('restore',$config . '_locked') == true);
289
 
290
                // Use the original value when this is an import and the setting is unlocked.
291
                if ($controller->get_mode() == backup::MODE_IMPORT && $controller->get_interactive()) {
292
                    if (!$uselocks || !$locked) {
293
                        $value = $setting->get_value();
294
                    }
295
                }
296
 
297
                // We can only update the setting if it isn't already locked by config or permission.
298
                if ($setting->get_status() != base_setting::LOCKED_BY_CONFIG
299
                        && $setting->get_status() != base_setting::LOCKED_BY_PERMISSION
300
                        && $setting->get_ui()->is_changeable()) {
301
                    $setting->set_value($value);
302
                    if ($uselocks && $locked) {
303
                        $setting->set_status(base_setting::LOCKED_BY_CONFIG);
304
                    }
305
                }
306
            } else {
307
                $controller->log('Unknown setting: ' . $settingname, BACKUP::LOG_DEBUG);
308
            }
309
        }
310
    }
311
}