backup_migrate.module 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. /**
  216. * Implementation of hook_backup_migrate_destinations().
  217. *
  218. * Get the default NodeSquirrel destination.
  219. */
  220. function backup_migrate_backup_migrate_schedules() {
  221. $schedules = array();
  222. if (variable_get('nodesquirrel_schedule', 60*60*24) && variable_get('nodesquirrel_secret_key', FALSE) != FALSE) {
  223. $schedule = array(
  224. 'schedule_id' => 'nodesquirrel',
  225. 'name' => 'NodeSquirrel',
  226. 'source_id' => 'db',
  227. 'destination_id' => 'nodesquirrel',
  228. 'profile_id' => 'default',
  229. 'period' => variable_get('nodesquirrel_schedule', 60*60*24),
  230. 'enabled' => variable_get('nodesquirrel_secret_key', FALSE) != FALSE,
  231. );
  232. $schedules['nodesquirrel'] = backup_migrate_crud_create_item('schedule', $schedule);
  233. }
  234. return $schedules;
  235. }
  236. /* Menu Callbacks */
  237. /**
  238. * A menu callback helper. Handles file includes and interactivity setting.
  239. */
  240. function backup_migrate_menu_callback($include, $function, $interactive = TRUE) {
  241. if ($include) {
  242. backup_migrate_include($include);
  243. }
  244. // Set the message handler based on interactivity setting.
  245. _backup_migrate_message_callback($interactive ? '_backup_migrate_message_browser' : '_backup_migrate_message_log');
  246. // Get the arguments with the first 3 removed.
  247. $args = array_slice(func_get_args(), 3);
  248. return call_user_func_array($function, $args);
  249. }
  250. /**
  251. * Include views .inc files as necessary.
  252. */
  253. function backup_migrate_include() {
  254. static $used = array();
  255. foreach (func_get_args() as $file) {
  256. if (!isset($used[$file])) {
  257. require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'backup_migrate') . "/includes/$file.inc";
  258. }
  259. $used[$file] = TRUE;
  260. }
  261. }
  262. /**
  263. * The menu callback for easy manual backups.
  264. */
  265. function backup_migrate_ui_manual_backup_quick() {
  266. $out = array();
  267. if (user_access('perform backup')) {
  268. return drupal_get_form('backup_migrate_ui_manual_quick_backup_form');
  269. }
  270. else {
  271. return t('You do not have permission to back up this site.');
  272. }
  273. return $out;
  274. }
  275. /**
  276. * The menu callback for advanced manual backups.
  277. */
  278. function backup_migrate_ui_manual_backup_advanced() {
  279. backup_migrate_include('profiles');
  280. $out = array();
  281. $profile_id = arg(BACKUP_MIGRATE_MENU_DEPTH + 2);
  282. $profile = _backup_migrate_profile_saved_default_profile($profile_id);
  283. $out[] = drupal_get_form('backup_migrate_ui_manual_backup_load_profile_form', $profile);
  284. $out[] = drupal_get_form('backup_migrate_ui_manual_backup_form', $profile);
  285. return $out;
  286. }
  287. /**
  288. * The backup/export load profile form.
  289. */
  290. function backup_migrate_ui_manual_backup_load_profile_form($form, &$form_state, $profile = NULL) {
  291. $form = array();
  292. $profile_options = _backup_migrate_get_profile_form_item_options();
  293. if (count($profile_options) > 0) {
  294. $profile_options = array(0 => t('-- Select a Settings Profile --')) + $profile_options;
  295. $form['profile'] = array(
  296. "#title" => t("Settings Profile"),
  297. "#collapsible" => TRUE,
  298. "#collapsed" => FALSE,
  299. "#prefix" => '<div class="container-inline">',
  300. "#suffix" => '</div>',
  301. "#tree" => FALSE,
  302. "#description" => t("You can load a profile. Any changes you made below will be lost."),
  303. );
  304. $form['profile']['profile_id'] = array(
  305. "#type" => "select",
  306. "#title" => t("Load Settings"),
  307. '#default_value' => is_object($profile) ? $profile->get_id() : 0,
  308. "#options" => $profile_options,
  309. );
  310. $form['profile']['load_profile'] = array(
  311. '#type' => 'submit',
  312. '#value' => t('Load Profile'),
  313. );
  314. }
  315. return $form;
  316. }
  317. /**
  318. * Submit the profile load form.
  319. */
  320. function backup_migrate_ui_manual_backup_load_profile_form_submit($form, &$form_state) {
  321. if ($profile = backup_migrate_get_profile($form_state['values']['profile_id'])) {
  322. variable_set("backup_migrate_profile_id", $profile->get_id());
  323. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . '/export/advanced';
  324. }
  325. else {
  326. variable_set("backup_migrate_profile_id", NULL);
  327. }
  328. }
  329. /**
  330. * The quick backup form.
  331. */
  332. function backup_migrate_ui_manual_quick_backup_form($form, &$form_state) {
  333. backup_migrate_include('profiles', 'destinations');
  334. drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js');
  335. $form = array();
  336. $form['quickbackup'] = array(
  337. '#type' => 'fieldset',
  338. "#title" => t("Quick Backup"),
  339. "#collapsible" => FALSE,
  340. "#collapsed" => FALSE,
  341. "#tree" => FALSE,
  342. );
  343. $form['quickbackup']['source_id'] = _backup_migrate_get_source_pulldown(variable_get('backup_migrate_source_id', NULL));
  344. // Pull the destination ID from the get param if it exists.
  345. $destinations = _backup_migrate_get_destination_form_item_options('manual backup');
  346. $destination_id = variable_get('backup_migrate_destination_id', 'download');
  347. if (isset($_GET['destination_id']) && isset($destinations[$_GET['destination_id']])) {
  348. $destination_id = $_GET['destination_id'];
  349. }
  350. $form['quickbackup']['destination_id'] = array(
  351. "#type" => "select",
  352. "#title" => t("Destination"),
  353. "#options" => $destinations,
  354. "#default_value" => $destination_id,
  355. );
  356. $profile_options = _backup_migrate_get_profile_form_item_options();
  357. $form['quickbackup']['profile_id'] = array(
  358. "#type" => "select",
  359. "#title" => t("Settings Profile"),
  360. '#default_value' => variable_get('backup_migrate_profile_id', NULL),
  361. "#options" => $profile_options,
  362. );
  363. $form['quickbackup']['submit'] = array(
  364. '#type' => 'submit',
  365. '#value' => t('Backup now'),
  366. '#weight' => 1,
  367. );
  368. $form['advanced'] = array(
  369. '#type' => 'markup',
  370. '#markup' => t('For more backup options, try the <a href="!advancedurl">advanced backup page</a>.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/export/advanced'))),
  371. );
  372. return $form;
  373. }
  374. /**
  375. * Validate the quick backup form.
  376. */
  377. function backup_migrate_ui_manual_quick_backup_form_validate($form, &$form_state) {
  378. if ($form_state['values']['source_id'] == $form_state['values']['destination_id']) {
  379. form_set_error('destination_id', t('A source cannot be backed up to itself. Please pick a different destination for this backup.'));
  380. }
  381. }
  382. /**
  383. * Submit the quick backup form.
  384. */
  385. function backup_migrate_ui_manual_quick_backup_form_submit($form, &$form_state) {
  386. backup_migrate_include('profiles', 'destinations');
  387. if (user_access('perform backup')) {
  388. // For a quick backup use the default settings.
  389. $settings = _backup_migrate_profile_saved_default_profile($form_state['values']['profile_id']);
  390. // Set the destination to the one chosen in the pulldown.
  391. $settings->destination_id = $form_state['values']['destination_id'];
  392. $settings->source_id = $form_state['values']['source_id'];
  393. // Save the settings for next time.
  394. variable_set("backup_migrate_source_id", $form_state['values']['source_id']);
  395. variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
  396. variable_set("backup_migrate_profile_id", $form_state['values']['profile_id']);
  397. // Do the backup.
  398. backup_migrate_ui_manual_backup_perform($settings);
  399. }
  400. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH;
  401. }
  402. /**
  403. * Theme the quick backup form.
  404. */
  405. function theme_backup_migrate_ui_manual_quick_backup_form($form) {
  406. $form = $form['form'];
  407. // Remove the titles so that the pulldowns can be displayed inline.
  408. unset($form['quickbackup']['source_id']['#title']);
  409. unset($form['quickbackup']['destination_id']['#title']);
  410. unset($form['quickbackup']['profile_id']['#title']);
  411. $replacements = array(
  412. '!from' => drupal_render($form['quickbackup']['source_id']),
  413. '!to' => drupal_render($form['quickbackup']['destination_id']),
  414. '!profile' => drupal_render($form['quickbackup']['profile_id']),
  415. '!submit' => drupal_render($form['quickbackup']['submit']),
  416. );
  417. $form['quickbackup']['markup'] = array(
  418. '#type' => 'markup',
  419. "#prefix" => '<div class="container-inline">',
  420. "#suffix" => '</div>',
  421. '#markup' => t('Backup from !from to !to using !profile !submit', $replacements),
  422. );
  423. unset($form['quickbackup']['source_id']);
  424. unset($form['quickbackup']['destination_id']);
  425. unset($form['quickbackup']['profile_id']);
  426. unset($form['quickbackup']['submit']);
  427. return drupal_render_children($form);
  428. }
  429. /**
  430. * The backup/export form.
  431. */
  432. function backup_migrate_ui_manual_backup_form($form, &$form_state, $profile) {
  433. drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js', array('type' => 'module', 'scope' => 'footer'));
  434. $form = array();
  435. $form += _backup_migrate_get_source_form('db');
  436. $form += _backup_migrate_ui_backup_settings_form($profile);
  437. $form['profile_id'] = array(
  438. "#type" => "value",
  439. '#default_value' => $profile->get_id(),
  440. );
  441. $form['storage'] = array(
  442. "#type" => "value",
  443. '#default_value' => $profile->storage,
  444. );
  445. $form['destination'] = array(
  446. "#type" => "fieldset",
  447. "#title" => t("Backup Destination"),
  448. "#collapsible" => TRUE,
  449. "#collapsed" => FALSE,
  450. "#tree" => FALSE,
  451. "#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."),
  452. '#weight' => 70,
  453. );
  454. $form['destination']['destination_id'] = array(
  455. "#type" => "select",
  456. "#title" => t("Destination"),
  457. "#options" => _backup_migrate_get_destination_form_item_options('manual backup'),
  458. "#default_value" => variable_get("backup_migrate_destination_id", "download"),
  459. );
  460. if (user_access('administer backup and migrate')) {
  461. $form['destination']['destination_id']['#description'] = l(t("Create new destination"), BACKUP_MIGRATE_MENU_PATH . "/destination/add");
  462. }
  463. if (user_access('administer backup and migrate')) {
  464. $form['save_settings'] = array(
  465. "#type" => "checkbox",
  466. "#title" => t('Save these settings.'),
  467. "#default_value" => FALSE,
  468. '#weight' => 80,
  469. );
  470. $form['save_options'] = array(
  471. '#prefix' => '<div class="backup-migrate-save-options">',
  472. '#suffix' => '</div>',
  473. '#weight' => 90,
  474. );
  475. $name = array(
  476. '#default_value' => $profile->get('name'),
  477. '#type' => 'textfield',
  478. '#title' => t('Save the settings as'),
  479. );
  480. if ($profile->get_id()) {
  481. $form['save_options']['create_new'] = array(
  482. '#default_value' => $profile->get('name'),
  483. '#type' => 'radios',
  484. '#default_value' => 0,
  485. '#options' => array(
  486. 0 => t("Replace the '%profile' profile", array('%profile' => $profile->get('name'))),
  487. 1 => t('Create new profile'),
  488. ),
  489. );
  490. $name["#title"] = t('Profile name');
  491. $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')));
  492. }
  493. else {
  494. $name["#title"] = t('Save the settings as');
  495. $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')));
  496. $name["#default_value"] = t('Untitled Profile');
  497. }
  498. $form['save_options']['name'] = $name;
  499. $form['save_options'][] = array(
  500. '#type' => 'submit',
  501. '#value' => t('Save Without Backing Up'),
  502. );
  503. }
  504. $form['#validate'][] = 'backup_migrate_ui_manual_quick_backup_form_validate';
  505. $form['#submit'][] = 'backup_migrate_ui_manual_backup_form_submit';
  506. $form[] = array(
  507. '#type' => 'submit',
  508. '#value' => t('Backup now'),
  509. '#weight' => 100,
  510. );
  511. return $form;
  512. }
  513. /**
  514. * Submit the form. Save the values as defaults if desired and output the backup file.
  515. */
  516. function backup_migrate_ui_manual_backup_form_submit($form, &$form_state) {
  517. // Save the settings profile if the save box is checked.
  518. // $form_state['values']['nodata_tables'] = array_filter((array)$form_state['values']['nodata_tables']);
  519. // $form_state['values']['exclude_tables'] = array_filter((array)$form_state['values']['exclude_tables']);
  520. $profile = backup_migrate_crud_create_item('profile', $form_state['values']);
  521. // Save the settings profile if the save box is checked.
  522. if ($form_state['values']['save_settings'] && user_access('administer backup and migrate')) {
  523. if (@$form_state['values']['create_new']) {
  524. // Reset the id and storage so a new item will be saved.
  525. $profile->set_id(NULL);
  526. $profile->storage = BACKUP_MIGRATE_STORAGE_NONE;
  527. }
  528. $profile->save();
  529. variable_set("backup_migrate_profile_id", $profile->get_id());
  530. variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
  531. }
  532. // Perform the actual backup if that is what was selected.
  533. if ($form_state['values']['op'] == t('Backup now') && user_access('perform backup')) {
  534. backup_migrate_ui_manual_backup_perform($profile);
  535. }
  536. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . "/export/advanced";
  537. }
  538. /**
  539. * Perform an actual manual backup and tell the user of the progress.
  540. */
  541. function backup_migrate_ui_manual_backup_perform($settings) {
  542. // Peform the actual backup.
  543. backup_migrate_perform_backup($settings);
  544. }
  545. /**
  546. * The restore/import upload page.
  547. */
  548. function backup_migrate_ui_manual_restore() {
  549. return drupal_get_form('backup_migrate_ui_manual_restore_form');
  550. }
  551. /**
  552. * The restore/import upload form.
  553. */
  554. function backup_migrate_ui_manual_restore_form() {
  555. backup_migrate_include('filters', 'destinations');
  556. $form = array();
  557. $sources = _backup_migrate_get_destination_form_item_options('source');
  558. if (count($sources) > 1) {
  559. $form['source_id'] = array(
  560. "#type" => "select",
  561. "#title" => t("Restore to"),
  562. "#options" => _backup_migrate_get_destination_form_item_options('source'),
  563. "#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."),
  564. "#default_value" => 'db',
  565. );
  566. }
  567. else {
  568. $form['source_id'] = array(
  569. "#type" => "value",
  570. "#value" => 'db',
  571. );
  572. }
  573. $form['backup_migrate_restore_upload'] = array(
  574. '#title' => t('Upload a Backup File'),
  575. '#type' => 'file',
  576. '#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()))),
  577. );
  578. 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);
  579. $form = array_merge_recursive($form, backup_migrate_filters_settings_form(backup_migrate_filters_settings_default('restore'), 'restore'));
  580. // Add the advanced fieldset if there are any fields in it.
  581. if (@$form['advanced']) {
  582. $form['advanced']['#type'] = 'fieldset';
  583. $form['advanced']['#title'] = t('Advanced Options');
  584. $form['advanced']['#collapsed'] = true;
  585. $form['advanced']['#collapsible'] = true;
  586. }
  587. $form['submit'] = array(
  588. '#type' => 'submit',
  589. '#value' => t('Restore now'),
  590. );
  591. if (user_access('access backup files')) {
  592. $form[] = array(
  593. '#type' => 'markup',
  594. '#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"))),
  595. );
  596. }
  597. $form['#attributes'] = array('enctype' => 'multipart/form-data');
  598. return $form;
  599. }
  600. /**
  601. * The restore submit. Do the restore.
  602. */
  603. function backup_migrate_ui_manual_restore_form_submit($form, &$form_state) {
  604. $validators = array('file_validate_extensions' => array('gz zip sql mysql bz bz2 aes'));
  605. if ($file = file_save_upload('backup_migrate_restore_upload', $validators)) {
  606. backup_migrate_include('destinations');
  607. backup_migrate_perform_restore('upload', $file->uri, $form_state['values']);
  608. }
  609. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . '/restore';
  610. }
  611. /**
  612. * Convert an item to an 'exportable'.
  613. */
  614. function backup_migrate_ui_export_form($form, &$form_state, $item) {
  615. if ($item && function_exists('ctools_var_export')) {
  616. $code = ctools_var_export($item);
  617. $form = ctools_export_form($form_state, $code);
  618. return $form;
  619. }
  620. return array();
  621. }
  622. /**
  623. * Perform a backup with the given settings.
  624. */
  625. function backup_migrate_perform_backup(&$settings) {
  626. backup_migrate_include('destinations', 'files', 'filters');
  627. timer_start('backup_migrate_backup');
  628. // If not in 'safe mode', increase the maximum execution time:
  629. if (!ini_get('safe_mode') && strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE && ini_get('max_execution_time') != 0 && ini_get('max_execution_time') < variable_get('backup_migrate_backup_max_time', 1200)) {
  630. set_time_limit(variable_get('backup_migrate_backup_max_time', 1200));
  631. }
  632. $timestamp = '';
  633. if ($settings->append_timestamp && $settings->timestamp_format) {
  634. $timestamp = format_date(time(), 'custom', $settings->timestamp_format);
  635. }
  636. $filename = _backup_migrate_construct_filename($settings->filename, $timestamp);
  637. $file = new backup_file(array('filename' => $filename));
  638. if (!$file) {
  639. backup_migrate_backup_fail("Could not run backup because a temporary file could not be created.", array(), $settings);
  640. return FALSE;
  641. }
  642. // Register shutdown callback to deal with timeouts.
  643. register_shutdown_function('backup_migrate_shutdown', $settings);
  644. $file = backup_migrate_filters_backup($file, $settings);
  645. if (!$file) {
  646. if (_backup_migrate_check_timeout()) {
  647. 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);
  648. }
  649. else {
  650. backup_migrate_backup_fail("Could not complete the backup.", array(), $settings);
  651. }
  652. return FALSE;
  653. }
  654. $file = backup_migrate_destination_save_file($file, $settings);
  655. if (!$file) {
  656. backup_migrate_backup_fail("Could not run backup because the file could not be saved to the destination.", array(), $settings);
  657. return FALSE;
  658. }
  659. // Backup succeeded,
  660. $time = timer_stop('backup_migrate_backup');
  661. $message = '%source backed up successfully to %file in destination %dest in !time ms. !action';
  662. $params = array(
  663. '%file' => $filename,
  664. '%dest' => $settings->get_destination_name(),
  665. '%source' => $settings->get_source_name(),
  666. '!time' => $time['time'],
  667. '!action' => !empty($settings->performed_action) ? $settings->performed_action : '',
  668. );
  669. if (($destination = $settings->get_destination()) && ($links = $destination->get_file_links($file->file_id()))) {
  670. $params['!links'] = implode(", ", $links);
  671. }
  672. backup_migrate_backup_succeed($message, $params, $settings);
  673. return $file;
  674. }
  675. /**
  676. * Restore from a file in the given destination.
  677. */
  678. function backup_migrate_perform_restore($destination_id, $file, $settings = array()) {
  679. backup_migrate_include('files', 'filters');
  680. timer_start('backup_migrate_restore');
  681. // If not in 'safe mode', increase the maximum execution time:
  682. if (!ini_get('safe_mode') && strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE && ini_get('max_execution_time') != 0 && ini_get('max_execution_time') < variable_get('backup_migrate_restore_max_time', 1200)) {
  683. set_time_limit(variable_get('backup_migrate_restore_max_time', 1200));
  684. }
  685. // Make the settings into a default profile.
  686. if (!is_object($settings)) {
  687. $settings = backup_migrate_crud_create_item('profile', $settings);
  688. $settings->source_id = empty($settings->source_id) ? 'db' : $settings->source_id;
  689. }
  690. // Register shutdown callback.
  691. register_shutdown_function('backup_migrate_shutdown', $settings);
  692. if (!is_object($file)) {
  693. // Load the file from the destination.
  694. $file = backup_migrate_destination_get_file($destination_id, $file);
  695. if (!$file) {
  696. _backup_migrate_message("Could not restore because the file could not be loaded from the destination.", array(), 'error');
  697. backup_migrate_cleanup();
  698. return FALSE;
  699. }
  700. }
  701. $file_id = $file->file_id();
  702. // Filter the file and perform the restore.
  703. $file = backup_migrate_filters_restore($file, $settings);
  704. if (!$file) {
  705. if (_backup_migrate_check_timeout()) {
  706. 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');
  707. }
  708. else {
  709. backup_migrate_restore_fail("Could not perform the restore.", array(), 'error');
  710. }
  711. backup_migrate_cleanup();
  712. return FALSE;
  713. }
  714. $time = timer_stop('backup_migrate_restore');
  715. if ($file) {
  716. $destination = backup_migrate_get_destination($destination_id);
  717. $message = '%source restored from %dest file %file in !time ms. !action';
  718. $params = array(
  719. '%file' => $file->filename(),
  720. '%source' => $settings->get_source_name(),
  721. '%dest' => $destination->get_name(),
  722. '!time' => $time['time'],
  723. '!action' => !empty($settings->performed_action) ? $settings->performed_action : '',
  724. );
  725. if ($destination && $destination->op('list files')) {
  726. $params['!links'] = t('<a href="!restoreurl">Restore again</a>', array('!restoreurl' => url(BACKUP_MIGRATE_MENU_PATH . '/destination/restorefile/'. $destination_id ."/". $file_id)));
  727. }
  728. backup_migrate_restore_succeed($message, $params, $settings);
  729. }
  730. // Delete any temp files we've created.
  731. backup_migrate_cleanup();
  732. // No errors. Return the file.
  733. return $file;
  734. }
  735. /**
  736. * Clean up when a backup operation fails.
  737. */
  738. function backup_migrate_backup_fail($message, $params, $settings) {
  739. backup_migrate_include('files', 'filters');
  740. _backup_migrate_message($message, $params, 'error');
  741. backup_migrate_cleanup();
  742. backup_migrate_filters_invoke_all('backup_fail', $settings, $message, $params);
  743. return FALSE;
  744. }
  745. /**
  746. * Clean up when a backup operation suceeds.
  747. */
  748. function backup_migrate_backup_succeed($message, $params, $settings) {
  749. backup_migrate_include('filters', 'files');
  750. _backup_migrate_message($message, $params, 'success');
  751. backup_migrate_cleanup();
  752. backup_migrate_filters_invoke_all('backup_succeed', $settings, $message, $params);
  753. return FALSE;
  754. }
  755. /**
  756. * Clean up when a restore operation fails.
  757. */
  758. function backup_migrate_restore_fail($message, $params, $settings) {
  759. backup_migrate_include('files', 'filters');
  760. _backup_migrate_message($message, $params, 'error');
  761. backup_migrate_cleanup();
  762. backup_migrate_filters_invoke_all('restore_fail', $settings, $message, $params);
  763. return FALSE;
  764. }
  765. /**
  766. * Clean up when a restore operation suceeds.
  767. */
  768. function backup_migrate_restore_succeed($message, $params, $settings) {
  769. backup_migrate_include('filters', 'files');
  770. _backup_migrate_message($message, $params, 'success');
  771. backup_migrate_cleanup();
  772. backup_migrate_filters_invoke_all('restore_succeed', $settings, $message, $params);
  773. return FALSE;
  774. }
  775. /**
  776. * Cleanup after a success or failure.
  777. */
  778. function backup_migrate_cleanup() {
  779. // Check that the cleanup function exists. If it doesn't then we probably didn't create any files to be cleaned up.
  780. if (function_exists('_backup_migrate_temp_files_delete')) {
  781. _backup_migrate_temp_files_delete();
  782. }
  783. }
  784. /**
  785. * Shutdown callback. Called when the script terminates even if the script timed out.
  786. */
  787. function backup_migrate_shutdown($settings) {
  788. // If we ran out of time, set an error so the user knows what happened
  789. if (_backup_migrate_check_timeout()) {
  790. backup_migrate_cleanup();
  791. 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);
  792. // The session will have already been written and closed, so we need to write any changes directly.
  793. _drupal_session_write(session_id(), session_encode());
  794. // Add a redirect or we'll just get whitescreened.
  795. drupal_goto(BACKUP_MIGRATE_MENU_PATH);
  796. }
  797. }
  798. /* Actions/Workflow integration */
  799. /**
  800. * Action to backup the drupal site. Requires actions.module.
  801. function action_backup_migrate_backup($op, $edit = array()) {
  802. switch ($op) {
  803. case 'do':
  804. _backup_migrate_backup_with_defaults();
  805. watchdog('action', 'Backed up database');
  806. break;
  807. case 'metadata':
  808. return array(
  809. 'description' => t('Backup the database with the default settings'),
  810. 'type' => t('Backup and Migrate'),
  811. 'batchable' => TRUE,
  812. 'configurable' => FALSE,
  813. );
  814. // Return an HTML config form for the action.
  815. case 'form':
  816. return '';
  817. // Validate the HTML form.
  818. case 'validate':
  819. return TRUE;
  820. // Process the HTML form to store configuration.
  821. case 'submit':
  822. return '';
  823. }
  824. }
  825. */
  826. /*
  827. * Implementation of hook_action_info().
  828. function backup_migrate_action_info() {
  829. return array(
  830. 'backup_migrate_action_backup' => array(
  831. 'label' => t('Backup the database'),
  832. 'description' => t('Backup the database with the default settings.'),
  833. ),
  834. );
  835. }
  836. */
  837. /*
  838. * Action callback.
  839. */
  840. function backup_migrate_action_backup() {
  841. _backup_migrate_backup_with_defaults();
  842. }
  843. /* Utilities */
  844. /**
  845. * Backup the database with the default settings.
  846. */
  847. function _backup_migrate_backup_with_defaults($destination_id = "manual") {
  848. backup_migrate_include('files', 'profiles');
  849. $settings = _backup_migrate_profile_saved_default_profile();
  850. $settings->destination_id = $destination_id;
  851. $settings->source_id = 'db';
  852. backup_migrate_perform_backup($settings);
  853. }
  854. /**
  855. * Helper function to set a drupal message and watchdog message depending on whether the module is being run interactively.
  856. */
  857. function _backup_migrate_message($message, $replace = array(), $type = 'status') {
  858. // Only set a message if there is a callback handler to handle the message.
  859. if (($callback = _backup_migrate_message_callback()) && function_exists($callback)) {
  860. $callback($message, $replace, $type);
  861. }
  862. // Store the message in case it's needed (for the status notification filter for example).
  863. _backup_migrate_messages($message, $replace, $type);
  864. }
  865. /**
  866. * Helper function to set a drupal message and watchdog message depending on whether the module is being run interactively.
  867. */
  868. function _backup_migrate_messages($message = NULL, $replace = array(), $type = 'status') {
  869. static $messages = array();
  870. if ($message) {
  871. $messages[] = array('message' => $message, 'replace' => $replace, 'type' => 'status');
  872. }
  873. return $messages;
  874. }
  875. /**
  876. * Send a message to the browser. The normal type of message handling for interactive use.
  877. */
  878. function _backup_migrate_message_browser($message, $replace, $type) {
  879. // Log the message as well for admins.
  880. _backup_migrate_message_log($message, $replace, $type);
  881. // If there are links, we can display them in the browser.
  882. if (!empty($replace['!links'])) {
  883. $message .= " (!links)";
  884. }
  885. // Use drupal_set_message to display to the user.
  886. drupal_set_message(t($message, $replace), str_replace('success', 'status', $type), FALSE);
  887. }
  888. /**
  889. * Log message if we are in a non-interactive mode such as a cron run.
  890. */
  891. function _backup_migrate_message_log($message, $replace, $type) {
  892. // We only want to log the errors or successful completions.
  893. if (in_array($type, array('error', 'success'))) {
  894. watchdog('backup_migrate', $message, $replace, $type == 'error' ? WATCHDOG_ERROR : WATCHDOG_NOTICE);
  895. }
  896. }
  897. /**
  898. * Set or retrieve a message handler.
  899. */
  900. function _backup_migrate_message_callback($callback = NULL) {
  901. static $current_callback = '_backup_migrate_message_log';
  902. if ($callback !== NULL) {
  903. $current_callback = $callback;
  904. }
  905. return $current_callback;
  906. }
  907. function _backup_migrate_check_timeout() {
  908. static $timeout;
  909. // Max execution of 0 means unlimited.
  910. if (ini_get('max_execution_time') == 0) {
  911. return false;
  912. }
  913. // Figure out when we should stop execution.
  914. if (!$timeout) {
  915. $timeout = (!empty($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time()) + ini_get('max_execution_time') - variable_get('backup_migrate_timeout_buffer', 5);
  916. }
  917. return (time() > $timeout);
  918. }
  919. /**
  920. * Convert an associated array to an ini format string.
  921. */
  922. function _backup_migrate_array_to_ini($data, $prefix = '') {
  923. $content = "";
  924. foreach ($data as $key => $val) {
  925. if ($prefix) {
  926. $key = $prefix . '[' . $key .']';
  927. }
  928. if (is_array($val)) {
  929. $content .= _backup_migrate_array_to_ini($val, $key);
  930. }
  931. else {
  932. $content .= $key . " = \"". $val ."\"\n";
  933. }
  934. }
  935. return $content;
  936. }
  937. /**
  938. * Execute a command line command. Returns false if the function failed.
  939. */
  940. function backup_migrate_exec($command, $args = array()) {
  941. if (!function_exists('exec') || ini_get('safe_mode')) {
  942. return FALSE;
  943. }
  944. // Escape the arguments
  945. foreach ($args as $key => $arg) {
  946. $args[$key] = escapeshellarg($arg);
  947. }
  948. $command = strtr($command, $args);
  949. $output = $result = NULL;
  950. // Run the command.
  951. exec($command . ' 2>&1', $output, $result);
  952. return $result == 0;
  953. }
  954. /**
  955. * Implements hook_mail().
  956. */
  957. function backup_migrate_mail($key, &$message, $params) {
  958. switch($key) {
  959. case 'backup_succeed':
  960. $message['subject'] = t('!site backup succeeded', array('!site' => variable_get('site_name', 'Drupal')));
  961. if ($params['messages']) {
  962. $message['body'][] = t("The site backup has completed successfully with the following messages:");
  963. $message['body'][] = t("!messages", array('!messages' => $params['messages']));
  964. }
  965. else {
  966. $message['body'][] = t("The site backup has completed successfully.");
  967. }
  968. break;
  969. case 'backup_fail':
  970. $message['subject'] = t('!site backup failed', array('!site' => variable_get('site_name', 'Drupal')));
  971. if ($params['messages']) {
  972. $message['body'][] = t("The site backup has failed with the following messages:");
  973. $message['body'][] = t("!messages", array('!messages' => $params['messages']));
  974. }
  975. else {
  976. $message['body'][] = t("The site backup has failed for an unknown reason.");
  977. }
  978. break;
  979. }
  980. }