backup_migrate.module

  1. nittany7 modules/contrib/backup_migrate/backup_migrate.module
  2. mooc7 modules/contrib/backup_migrate/backup_migrate.module

Create (manually or scheduled) and restore backups of your Drupal MySQL database with an option to exclude table data (e.g. cache_*)

Functions

Namesort descending Description
backup_migrate_action_backup
backup_migrate_backup_fail Clean up when a backup operation fails.
backup_migrate_backup_succeed Clean up when a backup operation suceeds.
backup_migrate_cleanup Cleanup after a success or failure.
backup_migrate_cron Implementation of hook_cron().
backup_migrate_exec Execute a command line command. Returns false if the function failed.
backup_migrate_help Implementation of hook_help().
backup_migrate_include Include views .inc files as necessary.
backup_migrate_menu Implementation of hook_menu().
backup_migrate_menu_callback A menu callback helper. Handles file includes and interactivity setting.
backup_migrate_perform_backup Perform a backup with the given settings.
backup_migrate_perform_restore Restore from a file in the given destination.
backup_migrate_permission Implementation of hook_permission().
backup_migrate_restore_fail Clean up when a restore operation fails.
backup_migrate_restore_succeed Clean up when a restore operation suceeds.
backup_migrate_shutdown Shutdown callback. Called when the script terminates even if the script timed out.
backup_migrate_simpletest Implementation of hook_simpletest().
backup_migrate_theme Implementation of hook_theme().
backup_migrate_ui_export_form Convert an item to an 'exportable'.
backup_migrate_ui_manual_backup_advanced The menu callback for advanced manual backups.
backup_migrate_ui_manual_backup_form The backup/export form.
backup_migrate_ui_manual_backup_form_submit Submit the form. Save the values as defaults if desired and output the backup file.
backup_migrate_ui_manual_backup_load_profile_form The backup/export load profile form.
backup_migrate_ui_manual_backup_load_profile_form_submit Submit the profile load form.
backup_migrate_ui_manual_backup_perform
backup_migrate_ui_manual_backup_quick The menu callback for easy manual backups.
backup_migrate_ui_manual_quick_backup_form The quick backup form.
backup_migrate_ui_manual_quick_backup_form_submit Submit the quick backup form.
backup_migrate_ui_manual_quick_backup_form_validate Validate the quick backup form.
backup_migrate_ui_manual_restore The restore/import upload page.
backup_migrate_ui_manual_restore_form The restore/import upload form.
backup_migrate_ui_manual_restore_form_submit The restore submit. Do the restore.
theme_backup_migrate_ui_manual_quick_backup_form Theme the quick backup form.
_backup_migrate_array_to_ini Convert an associated array to an ini format string.
_backup_migrate_backup_with_defaults Backup the database with the default settings.
_backup_migrate_check_timeout
_backup_migrate_message Helper function to set a drupal message and watchdog message depending on whether the module is being run interactively.
_backup_migrate_messages Helper function to set a drupal message and watchdog message depending on whether the module is being run interactively.
_backup_migrate_message_browser Send a message to the browser. The normal type of message handling for interactive use.
_backup_migrate_message_callback Set or retrieve a message handler.
_backup_migrate_message_log Log message if we are in a non-interactive mode such as a cron run.

Constants

File

modules/contrib/backup_migrate/backup_migrate.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Create (manually or scheduled) and restore backups of your Drupal MySQL
  5. * database with an option to exclude table data (e.g. cache_*)
  6. */
  7. define('BACKUP_MIGRATE_VERSION', '7.x-2.x');
  8. define('BACKUP_MIGRATE_MENU_PATH', 'admin/config/system/backup_migrate');
  9. define('BACKUP_MIGRATE_MENU_DEPTH', 4);
  10. /* Drupal Hooks */
  11. /**
  12. * Implementation of hook_help().
  13. */
  14. function backup_migrate_help($section, $arg) {
  15. $help = array(
  16. array(
  17. 'body' =>
  18. t('Backup and Migrate makes the task of backing up your Drupal database and migrating data from one Drupal install to another easier. It provides a function to backup the entire database to file or download, and to restore from a previous backup. You can also schedule the backup operation. Compression of backup files is also supported. The database backup files created with this module can be imported into this or any other Drupal installation with the !restorelink, or you can use a database tool such as <a href="!phpmyadminurl">phpMyAdmin</a> or the mysql command line command.',
  19. array(
  20. '!restorelink' => user_access('restore from backup') ? l(t('restore feature'), BACKUP_MIGRATE_MENU_PATH . '/restore') : t('restore feature'),
  21. '!phpmyadminurl' => 'http://www.phpmyadmin.net'
  22. )
  23. )
  24. ),
  25. BACKUP_MIGRATE_MENU_PATH => array(
  26. 'title' => t('Quick Backup Tab'),
  27. 'body' => t('Use this form to run simple manual backups of your database. Visit the !helppage for more help using this module',
  28. array('!helppage' => l(t('help page'), 'admin/help/backup_migrate'))),
  29. 'access arguments' => array('perform backup'),
  30. ),
  31. BACKUP_MIGRATE_MENU_PATH . '/export/advanced' => array(
  32. 'title' => t('Advanced Backup Tab'),
  33. 'body' => t('Use this form to run manual backups of your database with more advanced options. If you have any !profilelink saved you can load those settings. You can save any of the changes you make to these settings as a new settings profile.',
  34. array("!profilelink" => user_access('administer backup and migrate') ? l(t('settings profiles'), BACKUP_MIGRATE_MENU_PATH . '/profile') : t('settings profiles'), '!restorelink' => user_access('restore from backup') ? l(t('restore feature'), BACKUP_MIGRATE_MENU_PATH . '/restore') : t('restore feature'), '!phpmyadminurl' => 'http://www.phpmyadmin.net')),
  35. 'access arguments' => array('perform backup'),
  36. ),
  37. BACKUP_MIGRATE_MENU_PATH . '/restore' => array(
  38. 'title' => t('Restore Tab'),
  39. 'body' => t('Upload a backup and migrate backup file. The restore function will not work with database dumps from other sources such as phpMyAdmin.'),
  40. 'access arguments' => array('restore from backup'),
  41. ),
  42. BACKUP_MIGRATE_MENU_PATH . '/destination' => array(
  43. 'title' => t('Destinations'),
  44. 'body' => t('Destinations are the places you can save your backup files to or them load from.'),
  45. 'more' => t('Files can be saved to a directory on your web server, downloaded to your desktop or emailed to a specified email account. From the Destinations tab you can create, delete and edit destinations or list the files which have already been backed up to the available destinations.'),
  46. 'access arguments' => array('administer backup and migrate'),
  47. ),
  48. BACKUP_MIGRATE_MENU_PATH . '/profile' => array(
  49. 'title' => t('Profiles'),
  50. 'body' => t('Profiles are saved backup settings. Profiles store your table exclusion settings as well as your backup file name, compression and timestamp settings. You can use profiles in !schedulelink and for !manuallink.',
  51. array('!schedulelink' => user_access('administer backup and migrate') ? l(t('schedules'), BACKUP_MIGRATE_MENU_PATH . '/schedule') : t('settings profiles'), '!manuallink' => user_access('perform backups') ? l(t('manual backups'), BACKUP_MIGRATE_MENU_PATH) : t('manual backups'))),
  52. 'more' => t('You can create new profiles using the add profiles tab or by checking the "Save these settings" button on the advanced backup page.'),
  53. 'access arguments' => array('administer backup and migrate'),
  54. ),
  55. BACKUP_MIGRATE_MENU_PATH . '/schedule' => array(
  56. 'title' => t('Scheduling'),
  57. 'body' => t('Automatically backup up your database on a regular schedule using <a href="!cronurl">cron</a>.',
  58. array('!cronurl' => 'http://drupal.org/cron')),
  59. 'more' => t('Each schedule will run a maximum of once per cron run, so they will not run more frequently than your cron is configured to run. If you specify a number of backups to keep for a schedule, old backups will be deleted as new ones created. <strong>If specifiy a number of files to keep other backup files in that schedule\'s destination will get deleted</strong>.'),
  60. 'access arguments' => array('administer backup and migrate'),
  61. ),
  62. );
  63. if (isset($help[$section])) {
  64. return $help[$section]['body'];
  65. }
  66. if ($section == 'admin/help#backup_migrate') {
  67. $out = "";
  68. foreach ($help as $key => $section) {
  69. if (isset($section['access arguments'])) {
  70. foreach($section['access arguments'] as $access) {
  71. if (!user_access($access)) {
  72. continue 2;
  73. }
  74. }
  75. }
  76. if (@$section['title']) {
  77. if (!is_numeric($key)) {
  78. $section['title'] = l($section['title'], $key);
  79. }
  80. $out .= "<h3>". $section['title'] ."</h3>";
  81. }
  82. $out .= "<p>". $section['body'] ."</p>";
  83. if (!empty($section['more'])) {
  84. $out .= "<p>". $section['more'] ."</p>";
  85. }
  86. }
  87. return $out;
  88. }
  89. }
  90. /**
  91. * Implementation of hook_menu().
  92. */
  93. function backup_migrate_menu() {
  94. $items = array();
  95. $items[BACKUP_MIGRATE_MENU_PATH] = array(
  96. 'title' => 'Backup and Migrate',
  97. 'description' => 'Backup/restore your database or migrate data to or from another Drupal site.',
  98. 'page callback' => 'backup_migrate_menu_callback',
  99. 'page arguments' => array('', 'backup_migrate_ui_manual_backup_quick', TRUE),
  100. 'access arguments' => array('access backup and migrate'),
  101. 'type' => MENU_NORMAL_ITEM,
  102. );
  103. $items[BACKUP_MIGRATE_MENU_PATH . '/export'] = array(
  104. 'title' => 'Backup',
  105. 'description' => 'Backup the database.',
  106. 'page callback' => 'backup_migrate_menu_callback',
  107. 'page arguments' => array('', 'backup_migrate_ui_manual_backup_quick', TRUE),
  108. 'access arguments' => array('access backup and migrate'),
  109. 'weight' => 0,
  110. 'type' => MENU_DEFAULT_LOCAL_TASK,
  111. );
  112. $items[BACKUP_MIGRATE_MENU_PATH . '/export/quick'] = array(
  113. 'title' => 'Quick Backup',
  114. 'description' => 'Backup the database.',
  115. 'page callback' => 'backup_migrate_menu_callback',
  116. 'page arguments' => array('', 'backup_migrate_ui_manual_backup_quick', TRUE),
  117. 'access arguments' => array('access backup and migrate'),
  118. 'weight' => 0,
  119. 'type' => MENU_DEFAULT_LOCAL_TASK,
  120. );
  121. $items[BACKUP_MIGRATE_MENU_PATH . '/export/advanced'] = array(
  122. 'title' => 'Advanced Backup',
  123. 'description' => 'Backup the database.',
  124. 'page callback' => 'backup_migrate_menu_callback',
  125. 'page arguments' => array('', 'backup_migrate_ui_manual_backup_advanced', TRUE),
  126. 'access arguments' => array('perform backup'),
  127. 'weight' => 1,
  128. 'type' => MENU_LOCAL_TASK,
  129. );
  130. $items[BACKUP_MIGRATE_MENU_PATH . '/restore'] = array(
  131. 'title' => 'Restore',
  132. 'description' => 'Restore the database from a previous backup',
  133. 'page callback' => 'backup_migrate_menu_callback',
  134. 'page arguments' => array('', 'backup_migrate_ui_manual_restore', TRUE),
  135. 'access arguments' => array('restore from backup'),
  136. 'weight' => 1,
  137. 'type' => MENU_LOCAL_TASK,
  138. );
  139. $items[BACKUP_MIGRATE_MENU_PATH . '/nodesquirrel'] = array(
  140. 'title' => 'NodeSquirrel',
  141. 'page callback' => 'backup_migrate_menu_callback',
  142. 'page arguments' => array('destinations.nodesquirrel', 'nodesquirrel_settings_page'),
  143. 'access arguments' => array('administer backup and migrate'),
  144. 'weight' => 10,
  145. 'type' => MENU_LOCAL_TASK,
  146. );
  147. backup_migrate_include('crud');
  148. $items += backup_migrate_crud_menu();
  149. return $items;
  150. }
  151. /**
  152. * Implementation of hook_cron().
  153. *
  154. * Takes care of scheduled backups and deletes abandoned temp files.
  155. */
  156. function backup_migrate_cron() {
  157. // Set the message mode to logging.
  158. _backup_migrate_message_callback('_backup_migrate_message_log');
  159. backup_migrate_include('schedules');
  160. backup_migrate_schedules_run();
  161. backup_migrate_include('files');
  162. _backup_migrate_temp_files_delete();
  163. }
  164. /**
  165. * Implementation of hook_permission().
  166. */
  167. function backup_migrate_permission() {
  168. return array(
  169. 'access backup and migrate' => array(
  170. 'title' => t('Access Backup and Migrate'),
  171. 'description' => t('Access the Backup and Migrate admin section.'),
  172. ),
  173. 'perform backup' => array(
  174. 'title' => t('Perform a backup'),
  175. 'description' => t('Back up any of the available databases.'),
  176. ),
  177. 'access backup files' => array(
  178. 'title' => t('Access backup files'),
  179. 'description' => t('Access and download the previously created backup files.'),
  180. ),
  181. 'delete backup files' => array(
  182. 'title' => t('Delete backup files'),
  183. 'description' => t('Delete the previously created backup files.'),
  184. ),
  185. 'restore from backup' => array(
  186. 'title' => t('Restore the site'),
  187. 'description' => t('Restore the site\'s database from a backup file.'),
  188. ),
  189. 'administer backup and migrate' => array(
  190. 'title' => t('Administer Backup and Migrate'),
  191. 'description' => t('Edit Backup and Migrate profiles, schedules and destinations.'),
  192. ),
  193. );
  194. }
  195. /**
  196. * Implementation of hook_simpletest().
  197. */
  198. function backup_migrate_simpletest() {
  199. $dir = drupal_get_path('module', 'backup_migrate') .'/tests';
  200. $tests = file_scan_directory($dir, '\.test$');
  201. return array_keys($tests);
  202. }
  203. /**
  204. * Implementation of hook_theme().
  205. */
  206. function backup_migrate_theme() {
  207. $themes = array(
  208. 'backup_migrate_ui_manual_quick_backup_form' => array(
  209. 'arguments' => array('form'),
  210. 'render element' => 'form',
  211. ),
  212. );
  213. return $themes;
  214. }
  215. /* Menu Callbacks */
  216. /**
  217. * A menu callback helper. Handles file includes and interactivity setting.
  218. */
  219. function backup_migrate_menu_callback($include, $function, $interactive = TRUE) {
  220. if ($include) {
  221. backup_migrate_include($include);
  222. }
  223. // Set the message handler based on interactivity setting.
  224. _backup_migrate_message_callback($interactive ? '_backup_migrate_message_browser' : '_backup_migrate_message_log');
  225. // Get the arguments with the first 3 removed.
  226. $args = array_slice(func_get_args(), 3);
  227. return call_user_func_array($function, $args);
  228. }
  229. /**
  230. * Include views .inc files as necessary.
  231. */
  232. function backup_migrate_include() {
  233. static $used = array();
  234. foreach (func_get_args() as $file) {
  235. if (!isset($used[$file])) {
  236. require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'backup_migrate') . "/includes/$file.inc";
  237. }
  238. $used[$file] = TRUE;
  239. }
  240. }
  241. /**
  242. * The menu callback for easy manual backups.
  243. */
  244. function backup_migrate_ui_manual_backup_quick() {
  245. $out = array();
  246. if (user_access('perform backup')) {
  247. return drupal_get_form('backup_migrate_ui_manual_quick_backup_form');
  248. }
  249. else {
  250. return t('You do not have permission to back up this site.');
  251. }
  252. return $out;
  253. }
  254. /**
  255. * The menu callback for advanced manual backups.
  256. */
  257. function backup_migrate_ui_manual_backup_advanced() {
  258. backup_migrate_include('profiles');
  259. $out = array();
  260. $profile_id = arg(BACKUP_MIGRATE_MENU_DEPTH + 2);
  261. $profile = _backup_migrate_profile_saved_default_profile($profile_id);
  262. $out[] = drupal_get_form('backup_migrate_ui_manual_backup_load_profile_form', $profile);
  263. $out[] = drupal_get_form('backup_migrate_ui_manual_backup_form', $profile);
  264. return $out;
  265. }
  266. /**
  267. * The backup/export load profile form.
  268. */
  269. function backup_migrate_ui_manual_backup_load_profile_form($form, &$form_state, $profile = NULL) {
  270. $form = array();
  271. $profile_options = _backup_migrate_get_profile_form_item_options();
  272. if (count($profile_options) > 0) {
  273. $profile_options = array(0 => t('-- Select a Settings Profile --')) + $profile_options;
  274. $form['profile'] = array(
  275. "#title" => t("Settings Profile"),
  276. "#collapsible" => TRUE,
  277. "#collapsed" => FALSE,
  278. "#prefix" => '<div class="container-inline">',
  279. "#suffix" => '</div>',
  280. "#tree" => FALSE,
  281. "#description" => t("You can load a profile. Any changes you made below will be lost."),
  282. );
  283. $form['profile']['profile_id'] = array(
  284. "#type" => "select",
  285. "#title" => t("Load Settings"),
  286. '#default_value' => is_object($profile) ? $profile->get_id() : 0,
  287. "#options" => $profile_options,
  288. );
  289. $form['profile']['load_profile'] = array(
  290. '#type' => 'submit',
  291. '#value' => t('Load Profile'),
  292. );
  293. }
  294. return $form;
  295. }
  296. /**
  297. * Submit the profile load form.
  298. */
  299. function backup_migrate_ui_manual_backup_load_profile_form_submit($form, &$form_state) {
  300. if ($profile = backup_migrate_get_profile($form_state['values']['profile_id'])) {
  301. variable_set("backup_migrate_profile_id", $profile->get_id());
  302. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . '/export/advanced';
  303. }
  304. else {
  305. variable_set("backup_migrate_profile_id", NULL);
  306. }
  307. }
  308. /**
  309. * The quick backup form.
  310. */
  311. function backup_migrate_ui_manual_quick_backup_form($form, &$form_state) {
  312. backup_migrate_include('profiles', 'destinations');
  313. drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js');
  314. $form = array();
  315. $form['quickbackup'] = array(
  316. '#type' => 'fieldset',
  317. "#title" => t("Quick Backup"),
  318. "#collapsible" => FALSE,
  319. "#collapsed" => FALSE,
  320. "#tree" => FALSE,
  321. );
  322. $form['quickbackup']['source_id'] = _backup_migrate_get_source_pulldown(variable_get('backup_migrate_source_id', NULL));
  323. $form['quickbackup']['destination_id'] = array(
  324. "#type" => "select",
  325. "#title" => t("Destination"),
  326. "#options" => _backup_migrate_get_destination_form_item_options('manual backup'),
  327. "#default_value" => variable_get("backup_migrate_destination_id", "download"),
  328. );
  329. $profile_options = _backup_migrate_get_profile_form_item_options();
  330. $form['quickbackup']['profile_id'] = array(
  331. "#type" => "select",
  332. "#title" => t("Settings Profile"),
  333. '#default_value' => variable_get('backup_migrate_profile_id', NULL),
  334. "#options" => $profile_options,
  335. );
  336. $form['quickbackup']['submit'] = array(
  337. '#type' => 'submit',
  338. '#value' => t('Backup now'),
  339. '#weight' => 1,
  340. );
  341. $form['advanced'] = array(
  342. '#type' => 'markup',
  343. '#markup' => t('For more backup options, try the <a href="!advancedurl">advanced backup page</a>.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/export/advanced'))),
  344. );
  345. return $form;
  346. }
  347. /**
  348. * Validate the quick backup form.
  349. */
  350. function backup_migrate_ui_manual_quick_backup_form_validate($form, &$form_state) {
  351. if ($form_state['values']['source_id'] == $form_state['values']['destination_id']) {
  352. form_set_error('destination_id', t('A source cannot be backed up to itself. Please pick a different destination for this backup.'));
  353. }
  354. }
  355. /**
  356. * Submit the quick backup form.
  357. */
  358. function backup_migrate_ui_manual_quick_backup_form_submit($form, &$form_state) {
  359. backup_migrate_include('profiles', 'destinations');
  360. if (user_access('perform backup')) {
  361. // For a quick backup use the default settings.
  362. $settings = _backup_migrate_profile_saved_default_profile($form_state['values']['profile_id']);
  363. // Set the destination to the one chosen in the pulldown.
  364. $settings->destination_id = $form_state['values']['destination_id'];
  365. $settings->source_id = $form_state['values']['source_id'];
  366. // Save the settings for next time.
  367. variable_set("backup_migrate_source_id", $form_state['values']['source_id']);
  368. variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
  369. variable_set("backup_migrate_profile_id", $form_state['values']['profile_id']);
  370. // Do the backup.
  371. backup_migrate_ui_manual_backup_perform($settings);
  372. }
  373. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH;
  374. }
  375. /**
  376. * Theme the quick backup form.
  377. */
  378. function theme_backup_migrate_ui_manual_quick_backup_form($form) {
  379. $form = $form['form'];
  380. // Remove the titles so that the pulldowns can be displayed inline.
  381. unset($form['quickbackup']['source_id']['#title']);
  382. unset($form['quickbackup']['destination_id']['#title']);
  383. unset($form['quickbackup']['profile_id']['#title']);
  384. $replacements = array(
  385. '!from' => drupal_render($form['quickbackup']['source_id']),
  386. '!to' => drupal_render($form['quickbackup']['destination_id']),
  387. '!profile' => drupal_render($form['quickbackup']['profile_id']),
  388. '!submit' => drupal_render($form['quickbackup']['submit']),
  389. );
  390. $form['quickbackup']['markup'] = array(
  391. '#type' => 'markup',
  392. "#prefix" => '<div class="container-inline">',
  393. "#suffix" => '</div>',
  394. '#markup' => t('Backup from !from to !to using !profile !submit', $replacements),
  395. );
  396. unset($form['quickbackup']['source_id']);
  397. unset($form['quickbackup']['destination_id']);
  398. unset($form['quickbackup']['profile_id']);
  399. unset($form['quickbackup']['submit']);
  400. return drupal_render_children($form);
  401. }
  402. /**
  403. * The backup/export form.
  404. */
  405. function backup_migrate_ui_manual_backup_form($form, &$form_state, $profile) {
  406. drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js', array('type' => 'module', 'scope' => 'footer'));
  407. $form = array();
  408. $form += _backup_migrate_get_source_form('db');
  409. $form += _backup_migrate_ui_backup_settings_form($profile);
  410. $form['profile_id'] = array(
  411. "#type" => "value",
  412. '#default_value' => $profile->get_id(),
  413. );
  414. $form['storage'] = array(
  415. "#type" => "value",
  416. '#default_value' => $profile->storage,
  417. );
  418. $form['destination'] = array(
  419. "#type" => "fieldset",
  420. "#title" => t("Backup Destination"),
  421. "#collapsible" => TRUE,
  422. "#collapsed" => FALSE,
  423. "#tree" => FALSE,
  424. "#description" => t("Choose where the backup file will be saved. Backup files contain sensitive data, so be careful where you save them. Select 'Download' to download the file to your desktop."),
  425. '#weight' => 70,
  426. );
  427. $form['destination']['destination_id'] = array(
  428. "#type" => "select",
  429. "#title" => t("Destination"),
  430. "#options" => _backup_migrate_get_destination_form_item_options('manual backup'),
  431. "#default_value" => variable_get("backup_migrate_destination_id", "download"),
  432. );
  433. if (user_access('administer backup and migrate')) {
  434. $form['destination']['destination_id']['#description'] = l(t("Create new destination"), BACKUP_MIGRATE_MENU_PATH . "/destination/add");
  435. }
  436. if (user_access('administer backup and migrate')) {
  437. $form['save_settings'] = array(
  438. "#type" => "checkbox",
  439. "#title" => t('Save these settings.'),
  440. "#default_value" => FALSE,
  441. '#weight' => 80,
  442. );
  443. $form['save_options'] = array(
  444. '#prefix' => '<div class="backup-migrate-save-options">',
  445. '#suffix' => '</div>',
  446. '#weight' => 90,
  447. );
  448. $name = array(
  449. '#default_value' => $profile->get('name'),
  450. '#type' => 'textfield',
  451. '#title' => t('Save the settings as'),
  452. );
  453. if ($profile->get_id()) {
  454. $form['save_options']['create_new'] = array(
  455. '#default_value' => $profile->get('name'),
  456. '#type' => 'radios',
  457. '#default_value' => 0,
  458. '#options' => array(
  459. 0 => t("Replace the '%profile' profile", array('%profile' => $profile->get('name'))),
  460. 1 => t('Create new profile'),
  461. ),
  462. );
  463. $name["#title"] = t('Profile name');
  464. $name["#description"] = t("This will be the name of your new profile if you select 'Create new profile' otherwise it will become the name of the '%profile' profile.", array('%profile' => $profile->get('name')));
  465. }
  466. else {
  467. $name["#title"] = t('Save the settings as');
  468. $name["#description"] = t('Pick a name for the settings. Your settings will be saved as a profile and will appear in the <a href="!url">Profiles Tab</a>.', array('!url' => url(BACKUP_MIGRATE_MENU_PATH . '/profile')));
  469. $name["#default_value"] = t('Untitled Profile');
  470. }
  471. $form['save_options']['name'] = $name;
  472. $form['save_options'][] = array(
  473. '#type' => 'submit',
  474. '#value' => t('Save Without Backing Up'),
  475. );
  476. }
  477. $form['#validate'][] = 'backup_migrate_ui_manual_quick_backup_form_validate';
  478. $form['#submit'][] = 'backup_migrate_ui_manual_backup_form_submit';
  479. $form[] = array(
  480. '#type' => 'submit',
  481. '#value' => t('Backup now'),
  482. '#weight' => 100,
  483. );
  484. return $form;
  485. }
  486. /**
  487. * Submit the form. Save the values as defaults if desired and output the backup file.
  488. */
  489. function backup_migrate_ui_manual_backup_form_submit($form, &$form_state) {
  490. // Save the settings profile if the save box is checked.
  491. // $form_state['values']['nodata_tables'] = array_filter((array)$form_state['values']['nodata_tables']);
  492. // $form_state['values']['exclude_tables'] = array_filter((array)$form_state['values']['exclude_tables']);
  493. $profile = backup_migrate_crud_create_item('profile', $form_state['values']);
  494. // Save the settings profile if the save box is checked.
  495. if ($form_state['values']['save_settings'] && user_access('administer backup and migrate')) {
  496. if (@$form_state['values']['create_new']) {
  497. // Reset the id and storage so a new item will be saved.
  498. $profile->set_id(NULL);
  499. $profile->storage = BACKUP_MIGRATE_STORAGE_NONE;
  500. }
  501. $profile->save();
  502. variable_set("backup_migrate_profile_id", $profile->get_id());
  503. variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
  504. }
  505. // Perform the actual backup if that is what was selected.
  506. if ($form_state['values']['op'] == t('Backup now') && user_access('perform backup')) {
  507. backup_migrate_ui_manual_backup_perform($profile);
  508. }
  509. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . "/export/advanced";
  510. }
  511. /**
  512. * Perform an actual manual backup and tell the user of the progress.
  513. */
  514. function backup_migrate_ui_manual_backup_perform($settings) {
  515. // Peform the actual backup.
  516. backup_migrate_perform_backup($settings);
  517. }
  518. /**
  519. * The restore/import upload page.
  520. */
  521. function backup_migrate_ui_manual_restore() {
  522. return drupal_get_form('backup_migrate_ui_manual_restore_form');
  523. }
  524. /**
  525. * The restore/import upload form.
  526. */
  527. function backup_migrate_ui_manual_restore_form() {
  528. backup_migrate_include('filters', 'destinations');
  529. $form = array();
  530. $sources = _backup_migrate_get_destination_form_item_options('source');
  531. if (count($sources) > 1) {
  532. $form['source_id'] = array(
  533. "#type" => "select",
  534. "#title" => t("Restore to"),
  535. "#options" => _backup_migrate_get_destination_form_item_options('source'),
  536. "#description" => t("Choose the database to restore to. Any database destinations you have created and any databases specified in your settings.php can be restored to."),
  537. "#default_value" => 'db',
  538. );
  539. }
  540. else {
  541. $form['source_id'] = array(
  542. "#type" => "value",
  543. "#value" => 'db',
  544. );
  545. }
  546. $form['backup_migrate_restore_upload'] = array(
  547. '#title' => t('Upload a Backup File'),
  548. '#type' => 'file',
  549. '#description' => t("Upload a backup file created by this version of this module. For other database backups please use another tool for import. Max file size: %size", array("%size" => format_size(file_upload_max_size()))),
  550. );
  551. drupal_set_message(t('Restoring will delete some or all of your data and cannot be undone. <strong>Always test your backups on a non-production server!</strong>'), 'warning', FALSE);
  552. $form = array_merge_recursive($form, backup_migrate_filters_settings_form(backup_migrate_filters_settings_default('restore'), 'restore'));
  553. // Add the advanced fieldset if there are any fields in it.
  554. if (@$form['advanced']) {
  555. $form['advanced']['#type'] = 'fieldset';
  556. $form['advanced']['#title'] = t('Advanced Options');
  557. $form['advanced']['#collapsed'] = true;
  558. $form['advanced']['#collapsible'] = true;
  559. }
  560. $form['submit'] = array(
  561. '#type' => 'submit',
  562. '#value' => t('Restore now'),
  563. );
  564. if (user_access('access backup files')) {
  565. $form[] = array(
  566. '#type' => 'markup',
  567. '#markup' => t('<p>Or you can restore one of the files in your <a href="!url">saved backup destinations.</a></p>', array("!url" => url(BACKUP_MIGRATE_MENU_PATH . "/destination"))),
  568. );
  569. }
  570. $form['#attributes'] = array('enctype' => 'multipart/form-data');
  571. return $form;
  572. }
  573. /**
  574. * The restore submit. Do the restore.
  575. */
  576. function backup_migrate_ui_manual_restore_form_submit($form, &$form_state) {
  577. $validators = array('file_validate_extensions' => array('gz zip sql mysql bz bz2'));
  578. if ($file = file_save_upload('backup_migrate_restore_upload', $validators)) {
  579. backup_migrate_include('destinations');
  580. backup_migrate_perform_restore('upload', $file->uri, $form_state['values']);
  581. }
  582. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . '/restore';
  583. }
  584. /**
  585. * Convert an item to an 'exportable'.
  586. */
  587. function backup_migrate_ui_export_form($form, &$form_state, $item) {
  588. if ($item && function_exists('ctools_var_export')) {
  589. $code = ctools_var_export($item);
  590. $form = ctools_export_form($form_state, $code);
  591. return $form;
  592. }
  593. return array();
  594. }
  595. /**
  596. * Perform a backup with the given settings.
  597. */
  598. function backup_migrate_perform_backup(&$settings) {
  599. backup_migrate_include('destinations', 'files', 'filters');
  600. timer_start('backup_migrate_backup');
  601. // If not in 'safe mode', increase the maximum execution time:
  602. if (!ini_get('safe_mode') && strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE && ini_get('max_execution_time') < 1200) {
  603. set_time_limit(variable_get('backup_migrate_backup_max_time', 1200));
  604. }
  605. $timestamp = '';
  606. if ($settings->append_timestamp && $settings->timestamp_format) {
  607. $timestamp = format_date(time(), 'custom', $settings->timestamp_format);
  608. }
  609. $filename = _backup_migrate_construct_filename($settings->filename, $timestamp);
  610. $file = new backup_file(array('filename' => $filename));
  611. if (!$file) {
  612. backup_migrate_backup_fail("Could not run backup because a temporary file could not be created.", array(), $settings);
  613. return FALSE;
  614. }
  615. // Register shutdown callback to deal with timeouts.
  616. register_shutdown_function('backup_migrate_shutdown', $settings);
  617. $file = backup_migrate_filters_backup($file, $settings);
  618. if (!$file) {
  619. if (_backup_migrate_check_timeout()) {
  620. backup_migrate_backup_fail('Could not complete the backup because the script timed out. Try increasing your PHP <a href="!url">max_execution_time setting</a>.', array('!url' => 'http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time'), $settings);
  621. }
  622. else {
  623. backup_migrate_backup_fail("Could not complete the backup.", array(), $settings);
  624. }
  625. return FALSE;
  626. }
  627. $file = backup_migrate_destination_save_file($file, $settings);
  628. if (!$file) {
  629. backup_migrate_backup_fail("Could not run backup because the file could not be saved to the destination.", array(), $settings);
  630. return FALSE;
  631. }
  632. // Backup succeeded,
  633. $time = timer_stop('backup_migrate_backup');
  634. $message = '%source backed up successfully to %file in destination %dest in !time ms. !action';
  635. $params = array(
  636. '%file' => $filename,
  637. '%dest' => $settings->get_destination_name(),
  638. '%source' => $settings->get_source_name(),
  639. '!time' => $time['time'],
  640. '!action' => !empty($settings->performed_action) ? $settings->performed_action : '',
  641. );
  642. if (($destination = $settings->get_destination()) && ($links = $destination->get_file_links($file->file_id()))) {
  643. $params['!links'] = implode(", ", $links);
  644. }
  645. backup_migrate_backup_succeed($message, $params, $settings);
  646. return $file;
  647. }
  648. /**
  649. * Restore from a file in the given destination.
  650. */
  651. function backup_migrate_perform_restore($destination_id, $file, $settings = array()) {
  652. backup_migrate_include('files', 'filters');
  653. timer_start('backup_migrate_restore');
  654. // If not in 'safe mode', increase the maximum execution time:
  655. if (!ini_get('safe_mode') && strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE && ini_get('max_execution_time') < variable_get('backup_migrate_backup_max_time', 1200)) {
  656. set_time_limit(variable_get('backup_migrate_restore_max_time', 1200));
  657. }
  658. // Make the settings into a default profile.
  659. if (!is_object($settings)) {
  660. $settings = backup_migrate_crud_create_item('profile', $settings);
  661. $settings->source_id = empty($settings->source_id) ? 'db' : $settings->source_id;
  662. }
  663. // Register shutdown callback.
  664. register_shutdown_function('backup_migrate_shutdown', $settings);
  665. if (!is_object($file)) {
  666. // Load the file from the destination.
  667. $file = backup_migrate_destination_get_file($destination_id, $file);
  668. if (!$file) {
  669. _backup_migrate_message("Could not restore because the file could not be loaded from the destination.", array(), 'error');
  670. backup_migrate_cleanup();
  671. return FALSE;
  672. }
  673. }
  674. $file_id = $file->file_id();
  675. // Filter the file and perform the restore.
  676. $file = backup_migrate_filters_restore($file, $settings);
  677. if (!$file) {
  678. if (_backup_migrate_check_timeout()) {
  679. backup_migrate_restore_fail('Could not perform the restore because the script timed out. Try increasing your PHP <a href="!url">max_execution_time setting</a>.', array('!url' => 'http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time'), 'error');
  680. }
  681. else {
  682. backup_migrate_restore_fail("Could not perform the restore.", array(), 'error');
  683. }
  684. backup_migrate_cleanup();
  685. return FALSE;
  686. }
  687. $time = timer_stop('backup_migrate_restore');
  688. if ($file) {
  689. $destination = backup_migrate_get_destination($destination_id);
  690. $message = '%source restored from %dest file %file in !time ms. !action';
  691. $params = array(
  692. '%file' => $file->filename(),
  693. '%source' => $settings->get_source_name(),
  694. '%dest' => $destination->get_name(),
  695. '!time' => $time['time'],
  696. '!action' => !empty($settings->performed_action) ? $settings->performed_action : '',
  697. );
  698. if ($destination && $destination->op('list files')) {
  699. $params['!links'] = t('<a href="!restoreurl">Restore again</a>', array('!restoreurl' => url(BACKUP_MIGRATE_MENU_PATH . '/destination/restorefile/'. $destination_id ."/". $file_id)));
  700. }
  701. backup_migrate_restore_succeed($message, $params, $settings);
  702. }
  703. // Delete any temp files we've created.
  704. backup_migrate_cleanup();
  705. // No errors. Return the file.
  706. return $file;
  707. }
  708. /**
  709. * Clean up when a backup operation fails.
  710. */
  711. function backup_migrate_backup_fail($message, $params, $settings) {
  712. backup_migrate_include('files', 'filters');
  713. _backup_migrate_message($message, $params, 'error');
  714. backup_migrate_cleanup();
  715. backup_migrate_filters_invoke_all('backup_fail', $settings, $message, $params);
  716. return FALSE;
  717. }
  718. /**
  719. * Clean up when a backup operation suceeds.
  720. */
  721. function backup_migrate_backup_succeed($message, $params, $settings) {
  722. backup_migrate_include('filters', 'files');
  723. _backup_migrate_message($message, $params, 'success');
  724. backup_migrate_cleanup();
  725. backup_migrate_filters_invoke_all('backup_succeed', $settings, $message, $params);
  726. return FALSE;
  727. }
  728. /**
  729. * Clean up when a restore operation fails.
  730. */
  731. function backup_migrate_restore_fail($message, $params, $settings) {
  732. backup_migrate_include('files', 'filters');
  733. _backup_migrate_message($message, $params, 'error');
  734. backup_migrate_cleanup();
  735. backup_migrate_filters_invoke_all('restore_fail', $settings, $message, $params);
  736. return FALSE;
  737. }
  738. /**
  739. * Clean up when a restore operation suceeds.
  740. */
  741. function backup_migrate_restore_succeed($message, $params, $settings) {
  742. backup_migrate_include('filters', 'files');
  743. _backup_migrate_message($message, $params, 'success');
  744. backup_migrate_cleanup();
  745. backup_migrate_filters_invoke_all('restore_succeed', $settings, $message, $params);
  746. return FALSE;
  747. }
  748. /**
  749. * Cleanup after a success or failure.
  750. */
  751. function backup_migrate_cleanup() {
  752. // Check that the cleanup function exists. If it doesn't then we probably didn't create any files to be cleaned up.
  753. if (function_exists('_backup_migrate_temp_files_delete')) {
  754. _backup_migrate_temp_files_delete();
  755. }
  756. }
  757. /**
  758. * Shutdown callback. Called when the script terminates even if the script timed out.
  759. */
  760. function backup_migrate_shutdown($settings) {
  761. // If we ran out of time, set an error so the user knows what happened
  762. if (_backup_migrate_check_timeout()) {
  763. backup_migrate_cleanup();
  764. backup_migrate_backup_fail('The operation timed out. Try increasing your PHP <a href="!url">max_execution_time setting</a>.', array('!url' => 'http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time'), $settings);
  765. // The session will have already been written and closed, so we need to write any changes directly.
  766. _drupal_session_write(session_id(), session_encode());
  767. // Add a redirect or we'll just get whitescreened.
  768. drupal_goto(BACKUP_MIGRATE_MENU_PATH);
  769. }
  770. }
  771. /* Actions/Workflow integration */
  772. /**
  773. * Action to backup the drupal site. Requires actions.module.
  774. function action_backup_migrate_backup($op, $edit = array()) {
  775. switch ($op) {
  776. case 'do':
  777. _backup_migrate_backup_with_defaults();
  778. watchdog('action', 'Backed up database');
  779. break;
  780. case 'metadata':
  781. return array(
  782. 'description' => t('Backup the database with the default settings'),
  783. 'type' => t('Backup and Migrate'),
  784. 'batchable' => TRUE,
  785. 'configurable' => FALSE,
  786. );
  787. // Return an HTML config form for the action.
  788. case 'form':
  789. return '';
  790. // Validate the HTML form.
  791. case 'validate':
  792. return TRUE;
  793. // Process the HTML form to store configuration.
  794. case 'submit':
  795. return '';
  796. }
  797. }
  798. */
  799. /*
  800. * Implementation of hook_action_info().
  801. function backup_migrate_action_info() {
  802. return array(
  803. 'backup_migrate_action_backup' => array(
  804. 'label' => t('Backup the database'),
  805. 'description' => t('Backup the database with the default settings.'),
  806. ),
  807. );
  808. }
  809. */
  810. /*
  811. * Action callback.
  812. */
  813. function backup_migrate_action_backup() {
  814. _backup_migrate_backup_with_defaults();
  815. }
  816. /* Utilities */
  817. /**
  818. * Backup the database with the default settings.
  819. */
  820. function _backup_migrate_backup_with_defaults($destination_id = "manual") {
  821. backup_migrate_include('files', 'profiles');
  822. $settings = _backup_migrate_profile_saved_default_profile();
  823. $settings->destination_id = $destination_id;
  824. $settings->source_id = 'db';
  825. backup_migrate_perform_backup($settings);
  826. }
  827. /**
  828. * Helper function to set a drupal message and watchdog message depending on whether the module is being run interactively.
  829. */
  830. function _backup_migrate_message($message, $replace = array(), $type = 'status') {
  831. // Only set a message if there is a callback handler to handle the message.
  832. if (($callback = _backup_migrate_message_callback()) && function_exists($callback)) {
  833. $callback($message, $replace, $type);
  834. }
  835. // Store the message in case it's needed (for the status notification filter for example).
  836. _backup_migrate_messages($message, $replace, $type);
  837. }
  838. /**
  839. * Helper function to set a drupal message and watchdog message depending on whether the module is being run interactively.
  840. */
  841. function _backup_migrate_messages($message = NULL, $replace = array(), $type = 'status') {
  842. static $messages = array();
  843. if ($message) {
  844. $messages[] = array('message' => $message, 'replace' => $replace, 'type' => 'status');
  845. }
  846. return $messages;
  847. }
  848. /**
  849. * Send a message to the browser. The normal type of message handling for interactive use.
  850. */
  851. function _backup_migrate_message_browser($message, $replace, $type) {
  852. // Log the message as well for admins.
  853. _backup_migrate_message_log($message, $replace, $type);
  854. // If there are links, we can display them in the browser.
  855. if (!empty($replace['!links'])) {
  856. $message .= " (!links)";
  857. }
  858. // Use drupal_set_message to display to the user.
  859. drupal_set_message(t($message, $replace), str_replace('success', 'status', $type), FALSE);
  860. }
  861. /**
  862. * Log message if we are in a non-interactive mode such as a cron run.
  863. */
  864. function _backup_migrate_message_log($message, $replace, $type) {
  865. // We only want to log the errors or successful completions.
  866. if (in_array($type, array('error', 'success'))) {
  867. watchdog('backup_migrate', $message, $replace, $type == 'error' ? WATCHDOG_ERROR : WATCHDOG_NOTICE);
  868. }
  869. }
  870. /**
  871. * Set or retrieve a message handler.
  872. */
  873. function _backup_migrate_message_callback($callback = NULL) {
  874. static $current_callback = '_backup_migrate_message_log';
  875. if ($callback !== NULL) {
  876. $current_callback = $callback;
  877. }
  878. return $current_callback;
  879. }
  880. function _backup_migrate_check_timeout() {
  881. static $timeout;
  882. // Max execution of 0 means unlimited.
  883. if (ini_get('max_execution_time') == 0) {
  884. return false;
  885. }
  886. // Figure out when we should stop execution.
  887. if (!$timeout) {
  888. $timeout = (!empty($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time()) + ini_get('max_execution_time') - variable_get('backup_migrate_timeout_buffer', 5);
  889. }
  890. return (time() > $timeout);
  891. }
  892. /**
  893. * Convert an associated array to an ini format string.
  894. */
  895. function _backup_migrate_array_to_ini($data, $prefix = '') {
  896. $content = "";
  897. foreach ($data as $key => $val) {
  898. if ($prefix) {
  899. $key = $prefix . '[' . $key .']';
  900. }
  901. if (is_array($val)) {
  902. $content .= _backup_migrate_array_to_ini($val, $key);
  903. }
  904. else {
  905. $content .= $key . " = \"". $val ."\"\n";
  906. }
  907. }
  908. return $content;
  909. }
  910. /**
  911. * Execute a command line command. Returns false if the function failed.
  912. */
  913. function backup_migrate_exec($command, $args = array()) {
  914. if (!function_exists('exec') || ini_get('safe_mode')) {
  915. return FALSE;
  916. }
  917. // Escape the arguments
  918. foreach ($args as $key => $arg) {
  919. $args[$key] = escapeshellarg($arg);
  920. }
  921. $command = strtr($command, $args);
  922. $output = $result = NULL;
  923. // Run the command.
  924. exec($command . ' 2>&1', $output, $result);
  925. return $result == 0;
  926. }