backup_migrate.module 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159
  1. <?php
  2. /**
  3. * @file
  4. * Backup and restore databases for Drupal.
  5. */
  6. define('BACKUP_MIGRATE_VERSION', '7.x-3.x');
  7. define('BACKUP_MIGRATE_MENU_PATH', 'admin/config/system/backup_migrate');
  8. define('BACKUP_MIGRATE_MENU_DEPTH', 4);
  9. // Default settings.
  10. define('BACKUP_MIGRATE_MEMORY_LIMIT', '256M');
  11. define('BACKUP_MIGRATE_BACKUP_MAX_TIME', 1200);
  12. define('BACKUP_MIGRATE_VERBOSE', NULL);
  13. define('BACKUP_MIGRATE_DISABLE_CRON', FALSE);
  14. define('BACKUP_MIGRATE_DATA_ROWS_PER_QUERY', 50000);
  15. define('BACKUP_MIGRATE_DATA_ROWS_PER_LINE', 10);
  16. define('BACKUP_MIGRATE_DATA_BYTES_PER_LINE', 2 * 1024);
  17. define('BACKUP_MIGRATE_MAX_EMAIL_SIZE', 2 * 1024 * 1024);
  18. define('BACKUP_MIGRATE_CLEANUP_TEMP_FILES', TRUE);
  19. define('BACKUP_MIGRATE_CLEANUP_TIME', 21600);
  20. define('BACKUP_MIGRATE_SCHEDULE_BUFFER', 0.01);
  21. /**
  22. * Implements hook_help().
  23. */
  24. function backup_migrate_help($section, $arg) {
  25. $help = NULL;
  26. switch ($section) {
  27. case BACKUP_MIGRATE_MENU_PATH:
  28. $help = t('Use this form to run simple manual backups of your database and files.');
  29. break;
  30. case BACKUP_MIGRATE_MENU_PATH . '/export/advanced':
  31. $help = t('Use this form to run manual backups of your database and files 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.', array(
  32. "!profilelink" => user_access('administer backup and migrate') ? l(t('settings profiles'), BACKUP_MIGRATE_MENU_PATH . '/profile') : t('settings profiles'),
  33. '!restorelink' => user_access('restore from backup') ? l(t('restore feature'), BACKUP_MIGRATE_MENU_PATH . '/restore') : t('restore feature'),
  34. '!phpmyadminurl' => 'http://www.phpmyadmin.net',
  35. ));
  36. break;
  37. case BACKUP_MIGRATE_MENU_PATH . '/restore':
  38. $help = t('Upload a backup and migrate backup file. The restore function will not work with database dumps from other sources such as phpMyAdmin.');
  39. break;
  40. case BACKUP_MIGRATE_MENU_PATH . '/settings/destination':
  41. $help = t('Destinations are the places you can save your backup files to or them load from.');
  42. break;
  43. case BACKUP_MIGRATE_MENU_PATH . '/settings/source':
  44. $help = t('Sources are the things that can be backed up such as database or file directories.');
  45. break;
  46. case BACKUP_MIGRATE_MENU_PATH . '/settings/profile':
  47. $help = 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.', array(
  48. '!schedulelink' => user_access('administer backup and migrate') ? l(t('schedules'), BACKUP_MIGRATE_MENU_PATH . '/schedule') : t('settings profiles'),
  49. '!manuallink' => user_access('perform backups') ? l(t('manual backups'), BACKUP_MIGRATE_MENU_PATH) : t('manual backups'),
  50. ));
  51. break;
  52. case BACKUP_MIGRATE_MENU_PATH . '/schedule':
  53. $help = t('Automatically backup up your database and files on a regular schedule using <a href="!cronurl">cron</a>.', array(
  54. '!cronurl' => 'http://drupal.org/cron',
  55. ));
  56. break;
  57. case BACKUP_MIGRATE_MENU_PATH . '/settings/import':
  58. $help = t('Import a settings profile, backup schedule, source or destination by pasting the export code into the textarea.', array(
  59. '!cronurl' => 'http://drupal.org/cron',
  60. ));
  61. break;
  62. case 'admin/advanced_help':
  63. // Help link on module list page (admin/modules/list) or advanced help
  64. // module (admin/advanced_help/backup_migrate), use $arg to see if it
  65. // is for this module.
  66. if ($arg[2] != 'backup_migrate') {
  67. break;
  68. }
  69. // Explicit fall-through.
  70. case 'admin/help#backup_migrate':
  71. // Assemble help page based on all strings above plus more.
  72. $help = 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.', array(
  73. '!restorelink' => user_access('restore from backup') ? l(t('restore feature'), BACKUP_MIGRATE_MENU_PATH . '/restore') : t('restore feature'),
  74. '!phpmyadminurl' => 'http://www.phpmyadmin.net',
  75. ));
  76. $help = '<p>' . $help . '</p>';
  77. $help .= backup_migrate_help_section(t('Quick Backup Tab'), BACKUP_MIGRATE_MENU_PATH, NULL, array('perform backup'));
  78. $help .= backup_migrate_help_section(t('Advanced Backup Tab'), BACKUP_MIGRATE_MENU_PATH . '/export/advanced', NULL, array('perform backup'));
  79. $help .= backup_migrate_help_section(t('Restore Tab'), BACKUP_MIGRATE_MENU_PATH . '/restore', NULL, array('restore from backup'));
  80. $help .= backup_migrate_help_section(t('Destinations'), BACKUP_MIGRATE_MENU_PATH . '/settings/destination', 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.'), array('administer backup and migrate'));
  81. $help .= backup_migrate_help_section(t('Sources'), BACKUP_MIGRATE_MENU_PATH . '/settings/source', NULL, array('administer backup and migrate'));
  82. $help .= backup_migrate_help_section(t('Profiles'), BACKUP_MIGRATE_MENU_PATH . '/settings/profile', t('You can create new profiles using the add profiles tab or by checking the "Save these settings" button on the advanced backup page.'), array('administer backup and migrate'));
  83. $help .= backup_migrate_help_section(t('Scheduling'), BACKUP_MIGRATE_MENU_PATH . '/schedule', 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>."), array('administer backup and migrate'));
  84. $help .= backup_migrate_help_section(t('Importing Settings'), BACKUP_MIGRATE_MENU_PATH . '/settings/import', NULL, array());
  85. break;
  86. }
  87. return $help;
  88. }
  89. /**
  90. * Helper function for HOOK_help() to create parts of the help page.
  91. */
  92. function backup_migrate_help_section($title, $section, $more = NULL, $access_arguments = array()) {
  93. $show_this = TRUE;
  94. $help = '';
  95. foreach ($access_arguments as $access) {
  96. $show_this = $show_this && user_access($access);
  97. }
  98. if ($show_this) {
  99. $help = '';
  100. $help .= '<h3>' . l($title, $section) . '</h3>';
  101. $help .= '<p>' . backup_migrate_help($section, NULL) . '</p>';
  102. if ($more !== NULL) {
  103. $help .= '<p>' . $more . '</p>';
  104. }
  105. }
  106. return $help;
  107. }
  108. /**
  109. * Implements hook_menu().
  110. */
  111. function backup_migrate_menu() {
  112. require_once dirname(__FILE__) . '/includes/crud.inc';
  113. $items = array();
  114. $items[BACKUP_MIGRATE_MENU_PATH] = array(
  115. 'title' => 'Backup and Migrate',
  116. 'description' => 'Backup/restore your database and files or migrate data to or from another Drupal site.',
  117. 'page callback' => 'backup_migrate_menu_callback',
  118. 'page arguments' => array('', 'backup_migrate_ui_manual_backup_quick', TRUE),
  119. 'access arguments' => array('access backup and migrate'),
  120. 'type' => MENU_NORMAL_ITEM,
  121. );
  122. $items[BACKUP_MIGRATE_MENU_PATH . '/export'] = array(
  123. 'title' => 'Backup',
  124. 'description' => 'Backup the database.',
  125. 'page callback' => 'backup_migrate_menu_callback',
  126. 'page arguments' => array('', 'backup_migrate_ui_manual_backup_quick', TRUE),
  127. 'access arguments' => array('access backup and migrate'),
  128. 'weight' => 0,
  129. 'type' => MENU_DEFAULT_LOCAL_TASK,
  130. );
  131. $items[BACKUP_MIGRATE_MENU_PATH . '/export/quick'] = array(
  132. 'title' => 'Quick Backup',
  133. 'description' => 'Backup the database.',
  134. 'page callback' => 'backup_migrate_menu_callback',
  135. 'page arguments' => array('', 'backup_migrate_ui_manual_backup_quick', TRUE),
  136. 'access arguments' => array('perform backup'),
  137. 'weight' => 0,
  138. 'type' => MENU_DEFAULT_LOCAL_TASK,
  139. );
  140. $items[BACKUP_MIGRATE_MENU_PATH . '/export/advanced'] = array(
  141. 'title' => 'Advanced Backup',
  142. 'description' => 'Backup the database.',
  143. 'page callback' => 'backup_migrate_menu_callback',
  144. 'page arguments' => array(
  145. '',
  146. 'backup_migrate_ui_manual_backup_advanced',
  147. TRUE,
  148. ),
  149. 'access arguments' => array('perform backup'),
  150. 'weight' => 1,
  151. 'type' => MENU_LOCAL_TASK,
  152. );
  153. $items[BACKUP_MIGRATE_MENU_PATH . '/restore'] = array(
  154. 'title' => 'Restore',
  155. 'description' => 'Restore the database from a previous backup',
  156. 'page callback' => 'backup_migrate_menu_callback',
  157. 'page arguments' => array('', 'backup_migrate_ui_manual_restore', TRUE),
  158. 'access arguments' => array('restore from backup'),
  159. 'weight' => 1,
  160. 'type' => MENU_LOCAL_TASK,
  161. );
  162. $items[BACKUP_MIGRATE_MENU_PATH . '/backups'] = array(
  163. 'title' => 'Saved Backups',
  164. 'description' => 'Previously created backups',
  165. 'page callback' => 'backup_migrate_menu_callback',
  166. 'page arguments' => array('', 'backup_migrate_ui_saved_backups', TRUE),
  167. 'access arguments' => array('access backup files'),
  168. 'weight' => 2,
  169. 'type' => MENU_LOCAL_TASK,
  170. );
  171. // @todo This was removed because it was getting far too complicated for an
  172. // abstraction. Exposing the actual schedules is more direct.
  173. // @code
  174. // $items[BACKUP_MIGRATE_MENU_PATH . '/schedule'] = array(
  175. // 'title' => 'Schedule',
  176. // 'description' => 'Schedule automatic backups',
  177. // 'page callback' => 'backup_migrate_menu_callback',
  178. // 'page arguments' => array('', 'backup_migrate_ui_schedule', TRUE),
  179. // 'access arguments' => array('administer backup and migrate'),
  180. // 'weight' => 3,
  181. // 'type' => MENU_LOCAL_TASK,
  182. // );
  183. // @endcode
  184. $items[BACKUP_MIGRATE_MENU_PATH . '/settings'] = array(
  185. 'title' => 'Settings',
  186. 'description' => 'Module settings.',
  187. 'page callback' => 'backup_migrate_menu_callback',
  188. 'page arguments' => array('crud', 'backup_migrate_crud_ui_list_all', TRUE),
  189. 'access arguments' => array('administer backup and migrate'),
  190. 'weight' => 4,
  191. 'type' => MENU_LOCAL_TASK,
  192. );
  193. $items[BACKUP_MIGRATE_MENU_PATH . '/settings/import'] = array(
  194. 'title' => 'Import',
  195. 'description' => 'Import backup and migrate settings.',
  196. 'page callback' => 'backup_migrate_menu_callback',
  197. 'page arguments' => array('crud', 'backup_migrate_crud_ui_import', TRUE),
  198. 'access arguments' => array('administer backup and migrate'),
  199. 'weight' => 10,
  200. 'type' => MENU_LOCAL_TASK,
  201. );
  202. $items[BACKUP_MIGRATE_MENU_PATH . '/settings-advanced'] = array(
  203. 'title' => 'Advanced settings',
  204. 'description' => 'Optional settings for Backup and Migrate module.',
  205. 'page callback' => 'drupal_get_form',
  206. 'page arguments' => array('backup_migrate_ui_advanced_settings_form'),
  207. 'file' => 'backup_migrate.advanced_settings.inc',
  208. 'access arguments' => array('administer backup and migrate'),
  209. 'weight' => 50,
  210. 'type' => MENU_LOCAL_TASK,
  211. );
  212. $items += backup_migrate_crud_menu();
  213. return $items;
  214. }
  215. /**
  216. * Implements hook_element_info().
  217. */
  218. function backup_migrate_element_info() {
  219. $types['backup_migrate_dependent'] = array(
  220. '#dependencies' => array(),
  221. '#theme' => 'backup_migrate_dependent',
  222. );
  223. $types['backup_migrate_file_list'] = array(
  224. '#theme' => 'backup_migrate_file_list',
  225. '#process' => array('form_process_backup_migrate_file_list'),
  226. '#multiple' => FALSE,
  227. '#files' => array(),
  228. '#display_options' => array(),
  229. '#default_value' => 0,
  230. );
  231. return $types;
  232. }
  233. /**
  234. * Callback function for backup_migrate_file_list '#process' callback.
  235. */
  236. function form_process_backup_migrate_file_list($element) {
  237. if (count($element['#files']) > 0) {
  238. $weight = 0;
  239. $options = array();
  240. $max = $count = $element['#display_options']['limit'];
  241. $files = $element['#files'];
  242. foreach ($files as $id => $file) {
  243. $options[$id] = $file->info('filename');
  244. }
  245. $element['files'] = array(
  246. '#type' => 'radios',
  247. '#options' => $options,
  248. '#default_value' => $element['#default_value'],
  249. '#parents' => $element['#parents'],
  250. );
  251. }
  252. return $element;
  253. }
  254. /**
  255. * Implements hook_form_update_script_selection_form_alter().
  256. */
  257. function backup_migrate_form_update_script_selection_form_alter(&$form, $form_state) {
  258. $msg = t('Before you run any database updates, <strong>make sure you have a backup of your database.</strong> Use !backup_migrate to create that backup now.', array('!backup_migrate' => l(t('Backup and Migrate'), BACKUP_MIGRATE_MENU_PATH)));
  259. drupal_set_message($msg, 'warning');
  260. }
  261. /**
  262. * Implements hook_cron().
  263. */
  264. function backup_migrate_cron() {
  265. // Optionally disable hook_cron().
  266. if (variable_get('backup_migrate_disable_cron', BACKUP_MIGRATE_DISABLE_CRON)) {
  267. if (variable_get('backup_migrate_verbose')) {
  268. watchdog('backup_migrate', 'Cron disabled.');
  269. }
  270. return;
  271. }
  272. require_once dirname(__FILE__) . '/includes/files.inc';
  273. require_once dirname(__FILE__) . '/includes/schedules.inc';
  274. if (variable_get('backup_migrate_verbose')) {
  275. watchdog('backup_migrate', 'Cron starting.');
  276. }
  277. // Takes care of scheduled backups and deletes abandoned temp files.
  278. // Set the message mode to logging.
  279. _backup_migrate_message_callback('_backup_migrate_message_log');
  280. // Clean up any previous abandoned tmp files before we attempt to back up.
  281. if (variable_get('backup_migrate_verbose')) {
  282. watchdog('backup_migrate', 'Deleting temp files.');
  283. }
  284. _backup_migrate_temp_files_delete();
  285. if (variable_get('backup_migrate_verbose')) {
  286. watchdog('backup_migrate', 'Processing schedule(s) backups.');
  287. }
  288. backup_migrate_schedules_cron();
  289. // Clean up any temporary files from this run.
  290. if (variable_get('backup_migrate_verbose')) {
  291. watchdog('backup_migrate', 'Deleting temp files.');
  292. }
  293. _backup_migrate_temp_files_delete();
  294. if (variable_get('backup_migrate_verbose')) {
  295. watchdog('backup_migrate', 'Cron finished.');
  296. }
  297. }
  298. /**
  299. * Implements hook_cronapi().
  300. */
  301. function backup_migrate_cronapi($op, $job = NULL) {
  302. // Optionally disable hook_cron().
  303. if (variable_get('backup_migrate_disable_cron', BACKUP_MIGRATE_DISABLE_CRON)) {
  304. if (variable_get('backup_migrate_verbose')) {
  305. watchdog('backup_migrate', 'Cron disabled.');
  306. }
  307. return;
  308. }
  309. require_once dirname(__FILE__) . '/includes/schedules.inc';
  310. $items = array();
  311. foreach (backup_migrate_get_schedules() as $schedule) {
  312. if ($schedule->get('cron') == BACKUP_MIGRATE_CRON_ELYSIA) {
  313. $id = $schedule->get('id');
  314. $items['backup_migrate_' . $id] = array(
  315. 'description' => t("Run the Backup and Migrate '!name' schedule", array('!name' => $schedule->get('name'))),
  316. 'rule' => $schedule->get('cron_schedule'),
  317. 'callback' => 'backup_migrate_schedule_run',
  318. 'arguments' => array($id),
  319. 'file' => 'includes/schedules.inc',
  320. );
  321. }
  322. }
  323. return $items;
  324. }
  325. /**
  326. * Implements hook_permission().
  327. */
  328. function backup_migrate_permission() {
  329. return array(
  330. 'access backup and migrate' => array(
  331. 'title' => t('Access Backup and Migrate'),
  332. 'description' => t('Access the Backup and Migrate admin section.'),
  333. 'restrict access' => TRUE,
  334. ),
  335. 'perform backup' => array(
  336. 'title' => t('Perform a backup'),
  337. 'description' => t('Back up any of the available databases.'),
  338. 'restrict access' => TRUE,
  339. ),
  340. 'access backup files' => array(
  341. 'title' => t('Access backup files'),
  342. 'description' => t('Access and download the previously created backup files.'),
  343. 'restrict access' => TRUE,
  344. ),
  345. 'delete backup files' => array(
  346. 'title' => t('Delete backup files'),
  347. 'description' => t('Delete the previously created backup files.'),
  348. 'restrict access' => TRUE,
  349. ),
  350. 'restore from backup' => array(
  351. 'title' => t('Restore the site'),
  352. 'description' => t("Restore the site's database from a backup file."),
  353. 'restrict access' => TRUE,
  354. ),
  355. 'administer backup and migrate' => array(
  356. 'title' => t('Administer Backup and Migrate'),
  357. 'description' => t('Edit Backup and Migrate profiles, schedules and destinations.'),
  358. 'restrict access' => TRUE,
  359. ),
  360. );
  361. }
  362. /**
  363. * Implements hook_simpletest().
  364. */
  365. function backup_migrate_simpletest() {
  366. $dir = drupal_get_path('module', 'backup_migrate') . '/tests';
  367. $tests = file_scan_directory($dir, '\.test$');
  368. return array_keys($tests);
  369. }
  370. /**
  371. * Implements hook_theme().
  372. */
  373. function backup_migrate_theme() {
  374. $themes = array(
  375. 'backup_migrate_ui_manual_quick_backup_form_inline' => array(
  376. 'arguments' => array('form'),
  377. 'render element' => 'form',
  378. ),
  379. 'backup_migrate_ui_quick_schedule_form_inline' => array(
  380. 'arguments' => array('form'),
  381. 'render element' => 'form',
  382. ),
  383. 'backup_migrate_dependent' => array(
  384. 'arguments' => array('element'),
  385. 'render element' => 'element',
  386. ),
  387. 'backup_migrate_file_list' => array(
  388. 'arguments' => array('element'),
  389. 'render element' => 'element',
  390. ),
  391. 'backup_migrate_group' => array(
  392. 'variables' => array('title' => '', 'body' => '', 'description' => ''),
  393. ),
  394. );
  395. return $themes;
  396. }
  397. /**
  398. * Implements hook_block_info().
  399. */
  400. function backup_migrate_block_info() {
  401. $blocks = array();
  402. $blocks['quick_backup'] = array(
  403. 'info' => t('Backup and Migrate Quick Backup'),
  404. 'admin' => TRUE,
  405. );
  406. return $blocks;
  407. }
  408. /**
  409. * Implements hook_block_view().
  410. */
  411. function backup_migrate_block_view($delta) {
  412. $function = '_backup_migrate_block_view_' . $delta;
  413. if (function_exists('_backup_migrate_block_view_' . $delta)) {
  414. return $function();
  415. }
  416. }
  417. /**
  418. * Quick Backup block.
  419. */
  420. function _backup_migrate_block_view_quick_backup() {
  421. if (user_access('access backup and migrate') && user_access('perform backup') && $_GET['q'] != BACKUP_MIGRATE_MENU_PATH) {
  422. drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
  423. // Messages should be sent to the browser.
  424. _backup_migrate_message_callback('_backup_migrate_message_browser');
  425. return array(
  426. 'subject' => t('Quick Backup'),
  427. 'content' => drupal_get_form('backup_migrate_ui_manual_quick_backup_form', FALSE),
  428. );
  429. }
  430. return array();
  431. }
  432. /**
  433. * Implements hook_backup_migrate_destinations().
  434. */
  435. function backup_migrate_backup_migrate_schedules() {
  436. require_once dirname(__FILE__) . '/includes/sources.inc';
  437. $schedules = array();
  438. // Declare a default backup for each source that can be enabled.
  439. // @todo This makes setting up scheduled easier, but only when combined with
  440. // the now disabled quick-schedule feature.
  441. // @code
  442. // $sources = backup_migrate_get_sources();
  443. // foreach ($sources as $id => $source) {
  444. // $schedule = array(
  445. // 'schedule_id' => $id,
  446. // 'name' => $source->get('name'),
  447. // 'source_id' => $id,
  448. // 'destination_id' => 'scheduled',
  449. // 'profile_id' => 'default',
  450. // 'period' => variable_get('backup_migrate_default_schedule', 60*60),
  451. // 'keep' => BACKUP_MIGRATE_SMART_DELETE,
  452. // 'enabled' => FALSE,
  453. // );
  454. // $schedules[$id] = backup_migrate_crud_create_item('schedule', $schedule);
  455. // }
  456. // @endcode
  457. return $schedules;
  458. }
  459. /**
  460. * Implements hook_ctools_plugin_api().
  461. */
  462. function backup_migrate_ctools_plugin_api($owner, $api) {
  463. // Tell CTools that we support the default_mymodule_presets API.
  464. if ($owner == 'backup_migrate') {
  465. return array('version' => 1);
  466. }
  467. }
  468. /**
  469. * A menu callback helper. Handles file includes and interactivity setting.
  470. */
  471. function backup_migrate_menu_callback($include, $function, $interactive = TRUE) {
  472. if ($include) {
  473. require_once dirname(__FILE__) . '/includes/' . $include . '.inc';
  474. }
  475. // Set the message handler based on interactivity setting.
  476. _backup_migrate_message_callback($interactive ? '_backup_migrate_message_browser' : '_backup_migrate_message_log');
  477. // Get the arguments with the first 3 removed.
  478. $args = array_slice(func_get_args(), 3);
  479. return call_user_func_array($function, $args);
  480. }
  481. /**
  482. * Include views .inc files as necessary.
  483. *
  484. * @deprecated
  485. */
  486. function backup_migrate_include() {
  487. static $used = array();
  488. foreach (func_get_args() as $file) {
  489. if (!isset($used[$file])) {
  490. require_once backup_migrate_include_path($file);
  491. }
  492. $used[$file] = TRUE;
  493. }
  494. }
  495. /**
  496. * Include .inc files as necessary.
  497. *
  498. * @deprecated
  499. */
  500. function backup_migrate_include_path($file) {
  501. return DRUPAL_ROOT . '/' . drupal_get_path('module', 'backup_migrate') . "/includes/$file.inc";
  502. }
  503. /**
  504. * The menu callback for easy manual backups.
  505. */
  506. function backup_migrate_ui_manual_backup_quick() {
  507. $out = array();
  508. if (user_access('perform backup')) {
  509. return drupal_get_form('backup_migrate_ui_manual_quick_backup_form');
  510. }
  511. else {
  512. return t('You do not have permission to back up this site.');
  513. }
  514. return $out;
  515. }
  516. /**
  517. * The menu callback for advanced manual backups.
  518. */
  519. function backup_migrate_ui_manual_backup_advanced() {
  520. require_once dirname(__FILE__) . '/includes/profiles.inc';
  521. $out = array();
  522. $profile_id = arg(BACKUP_MIGRATE_MENU_DEPTH + 2);
  523. $profile = _backup_migrate_profile_saved_default_profile($profile_id);
  524. $out[] = drupal_get_form('backup_migrate_ui_manual_backup_load_profile_form', $profile);
  525. $out[] = drupal_get_form('backup_migrate_ui_manual_backup_form', $profile);
  526. return $out;
  527. }
  528. /**
  529. * The backup/export load profile form.
  530. */
  531. function backup_migrate_ui_manual_backup_load_profile_form($form, &$form_state, $profile = NULL) {
  532. $form = array();
  533. $profile_options = _backup_migrate_get_profile_form_item_options();
  534. if (count($profile_options) > 0) {
  535. $profile_options = array(0 => t('-- Select a Settings Profile --')) + $profile_options;
  536. $form['profile'] = array(
  537. "#title" => t("Settings Profile"),
  538. "#collapsible" => TRUE,
  539. "#collapsed" => FALSE,
  540. "#prefix" => '<div class="container-inline">',
  541. "#suffix" => '</div>',
  542. "#tree" => FALSE,
  543. "#description" => t("You can load a profile. Any changes you made below will be lost."),
  544. );
  545. $form['profile']['profile_id'] = array(
  546. "#type" => "select",
  547. "#title" => t("Load Settings"),
  548. '#default_value' => is_object($profile) ? $profile->get_id() : 0,
  549. "#options" => $profile_options,
  550. );
  551. $form['profile']['load_profile'] = array(
  552. '#type' => 'submit',
  553. '#value' => t('Load Profile'),
  554. );
  555. }
  556. return $form;
  557. }
  558. /**
  559. * Submit the profile load form.
  560. */
  561. function backup_migrate_ui_manual_backup_load_profile_form_submit($form, &$form_state) {
  562. if ($profile = backup_migrate_get_profile($form_state['values']['profile_id'])) {
  563. variable_set("backup_migrate_profile_id", $profile->get_id());
  564. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . '/export/advanced';
  565. }
  566. else {
  567. variable_set("backup_migrate_profile_id", NULL);
  568. }
  569. }
  570. /**
  571. * The menu callback for quick schedules.
  572. */
  573. function backup_migrate_ui_schedule() {
  574. require_once dirname(__FILE__) . '/includes/sources.inc';
  575. require_once dirname(__FILE__) . '/includes/schedules.inc';
  576. require_once dirname(__FILE__) . '/includes/profiles.inc';
  577. $sources = backup_migrate_get_sources();
  578. $schedules = backup_migrate_get_schedules();
  579. $out = drupal_get_form('backup_migrate_ui_schedule_form', $sources, $schedules);
  580. return $out;
  581. }
  582. /**
  583. * The quick schedule form.
  584. */
  585. function backup_migrate_ui_schedule_form($form, &$form_state, $sources, $schedules) {
  586. $form['quickschedule'] = array('#tree' => TRUE);
  587. // Add a quick schedule item for each source.
  588. foreach ($sources as $id => $source) {
  589. if (isset($schedules[$id])) {
  590. $schedule = $schedules[$id];
  591. $key = preg_replace('/[^A-Za-z0-9\-_]/', '-', $id);
  592. $form['quickschedule'][$key] = array();
  593. $form['quickschedule'][$key]['#theme'] = 'backup_migrate_ui_quick_schedule_form_inline';
  594. $form['quickschedule'][$key]['id'] = array(
  595. '#type' => 'value',
  596. '#value' => $id,
  597. );
  598. $form['quickschedule'][$key]['enabled'] = array(
  599. '#type' => 'checkbox',
  600. '#title' => t('Automatically backup my @source', array('@source' => $source->get('name'))),
  601. '#default_value' => $schedule->get('enabled'),
  602. );
  603. // $form['quickschedule'][$id]['source_id'] = array(
  604. // '#type' => 'item',
  605. // '#title' => t('Backup Source'),
  606. // '#value' => $source->get('name'),
  607. // );
  608. $form['quickschedule'][$key]['settings'] = array(
  609. '#type' => 'backup_migrate_dependent',
  610. '#dependencies' => array(
  611. 'quickschedule[' . $key . '][enabled]' => TRUE,
  612. ),
  613. );
  614. $options = array(
  615. (60 * 60) => t('Once an hour'),
  616. (60 * 60 * 24) => t('Once a day'),
  617. (60 * 60 * 24 * 7) => t('Once a week'),
  618. );
  619. $period = $schedule->get('period');
  620. if (!isset($options[$period])) {
  621. $options[$period] = $schedule->get('frequency_description');
  622. }
  623. $form['quickschedule'][$key]['settings']['period'] = array(
  624. '#type' => 'select',
  625. '#title' => t('Schedule Frequency'),
  626. '#options' => $options,
  627. '#default_value' => $period,
  628. );
  629. $form['quickschedule'][$key]['settings']['destination'] = _backup_migrate_get_destination_pulldown('scheduled backup', $schedule->get('destination_id'), $schedule->get('copy_destination_id'));
  630. $form['quickschedule'][$key]['settings']['destination']['destination_id']['#parents'] = array(
  631. 'quickschedule',
  632. $key,
  633. 'destination_id',
  634. );
  635. $form['quickschedule'][$key]['settings']['destination']['copy']['#parents'] = array(
  636. 'quickschedule',
  637. $key,
  638. 'copy',
  639. );
  640. $form['quickschedule'][$key]['settings']['destination']['copy_destination']['copy_destination_id']['#parents'] = array(
  641. 'quickschedule',
  642. $key,
  643. 'copy_destination_id',
  644. );
  645. array(
  646. '#type' => 'select',
  647. '#title' => t('Backup Destination'),
  648. '#options' => _backup_migrate_get_destination_form_item_options('scheduled backup'),
  649. '#default_value' => $schedule->get('period'),
  650. );
  651. $form['quickschedule'][$key]['settings']['profile_id'] = array(
  652. '#type' => 'select',
  653. '#title' => t('Settings Profile'),
  654. '#default_value' => $schedule->get('profile_id'),
  655. '#options' => _backup_migrate_get_profile_form_item_options(),
  656. );
  657. $keep = $schedule->get('keep');
  658. $option_keys = array_unique(array(
  659. BACKUP_MIGRATE_SMART_DELETE,
  660. 30,
  661. 100,
  662. 500,
  663. BACKUP_MIGRATE_KEEP_ALL,
  664. $keep,
  665. ));
  666. $options = array();
  667. foreach ($option_keys as $i) {
  668. $options[$i] = $schedule->generate_keep_description($i);
  669. }
  670. $form['quickschedule'][$key]['settings']['keep'] = array(
  671. '#type' => 'select',
  672. '#title' => t('Backup retention'),
  673. '#options' => $options,
  674. '#default_value' => $keep,
  675. );
  676. $form['quickschedule'][$key]['settings']['advanced'] = array(
  677. '#type' => 'markup',
  678. '#markup' => l(t('Advanced Settings.'), BACKUP_MIGRATE_MENU_PATH . '/settings/schedule/edit/' . $id, array('query' => drupal_get_destination())),
  679. );
  680. // Set the parent for the setttings up a level.
  681. foreach (element_children($form['quickschedule'][$key]['settings']) as $child) {
  682. $form['quickschedule'][$key]['settings'][$child]['#parents'] = array(
  683. 'quickschedule',
  684. $key,
  685. $child,
  686. );
  687. }
  688. }
  689. }
  690. if (element_children($form['quickschedule'])) {
  691. $form['submit'] = array(
  692. '#type' => 'submit',
  693. '#value' => t('Save Schedules'),
  694. );
  695. }
  696. $form['advanced'] = array(
  697. '#type' => 'markup',
  698. '#markup' => '<div class="clearblock backup-migrate-footer-message">' . t('For more scheduling options and to add additional schedules, try the <a href="!advancedurl">advanced schedule page</a>.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/settings/schedule'))) . '</div>',
  699. );
  700. return $form;
  701. }
  702. /**
  703. * Submit the quick schedule form.
  704. */
  705. function backup_migrate_ui_schedule_form_submit($form, &$form_state) {
  706. require_once dirname(__FILE__) . '/includes/schedules.inc';
  707. if (user_access('adminsiter backup and migrate')) {
  708. // Override the backups.
  709. foreach ($form_state['values']['quickschedule'] as $key => $values) {
  710. $id = $values['id'];
  711. if ($schedule = backup_migrate_get_schedule($id)) {
  712. $schedule->from_array($values);
  713. $schedule->save();
  714. }
  715. }
  716. drupal_set_message(t('Your schedules have been saved'));
  717. }
  718. }
  719. /**
  720. * The quick backup form.
  721. */
  722. function backup_migrate_ui_manual_quick_backup_form($form, &$form_state, $inline = TRUE) {
  723. require_once dirname(__FILE__) . '/includes/profiles.inc';
  724. require_once dirname(__FILE__) . '/includes/destinations.inc';
  725. require_once dirname(__FILE__) . '/includes/sources.inc';
  726. drupal_add_js(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.js');
  727. $form = array();
  728. // Theme the form if we want it inline.
  729. if ($inline) {
  730. $form['#theme'] = 'backup_migrate_ui_manual_quick_backup_form_inline';
  731. }
  732. $form['quickbackup'] = array(
  733. '#type' => 'fieldset',
  734. "#title" => t("Quick Backup"),
  735. "#collapsible" => FALSE,
  736. "#collapsed" => FALSE,
  737. "#tree" => FALSE,
  738. );
  739. $form['quickbackup']['source_id'] = _backup_migrate_get_source_pulldown(variable_get('backup_migrate_source_id', NULL));
  740. $form['quickbackup']['destination'] = _backup_migrate_get_destination_pulldown('manual backup', variable_get('backup_migrate_destination_id', 'download'), variable_get('backup_migrate_copy_destination_id', ''));
  741. $profile_options = _backup_migrate_get_profile_form_item_options();
  742. $form['quickbackup']['profile_id'] = array(
  743. "#type" => "select",
  744. "#title" => t("Settings Profile"),
  745. '#default_value' => variable_get('backup_migrate_profile_id', NULL),
  746. "#options" => $profile_options,
  747. );
  748. $form['quickbackup']['description_enabled'] = array(
  749. '#type' => 'checkbox',
  750. "#title" => t("Add a note to the backup"),
  751. );
  752. $form['quickbackup']['description'] = array(
  753. '#type' => 'backup_migrate_dependent',
  754. '#dependencies' => array(
  755. 'description_enabled' => TRUE,
  756. ),
  757. );
  758. $form['quickbackup']['description']['description'] = array(
  759. '#type' => 'textarea',
  760. "#title" => t("Note"),
  761. '#description' => t('This note will be saved with the backup file and shown on the listing page.'),
  762. );
  763. $form['advanced'] = array(
  764. '#type' => 'markup',
  765. '#markup' => '<div class="clearblock backup-migrate-footer-message">' . t('For more backup options, try the <a href="!advancedurl">advanced backup page</a>.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/export/advanced'))) . '</div>',
  766. );
  767. $form['quickbackup']['submit'] = array(
  768. '#type' => 'submit',
  769. '#value' => t('Backup now'),
  770. '#weight' => 1,
  771. );
  772. $form['#validate'] = array('backup_migrate_ui_manual_quick_backup_form_validate');
  773. $form['#submit'] = array('backup_migrate_ui_manual_quick_backup_form_submit');
  774. return _backup_migrate_ui_action_form($form, $form_state, 'backup');
  775. }
  776. /**
  777. * Validate the quick backup form.
  778. */
  779. function backup_migrate_ui_manual_quick_backup_form_validate($form, &$form_state) {
  780. require_once dirname(__FILE__) . '/includes/profiles.inc';
  781. require_once dirname(__FILE__) . '/includes/destinations.inc';
  782. if ($form_state['values']['source_id'] == $form_state['values']['destination_id']) {
  783. form_set_error('destination_id', t('A source cannot be backed up to itself. Please pick a different destination for this backup.'));
  784. }
  785. // Wrap profile_id for prevent Undefined index notice.
  786. $profile_id = isset($form_state['values']['profile_id']) ? $form_state['values']['profile_id'] : NULL;
  787. // For a quick backup use the default settings.
  788. $settings = _backup_migrate_profile_saved_default_profile($profile_id);
  789. // Set the destination to the one chosen in the pulldown.
  790. $settings->destination_id = array($form_state['values']['destination_id']);
  791. $settings->source_id = $form_state['values']['source_id'];
  792. // Add the second destination.
  793. if (!empty($form_state['values']['copy_destination_id'])) {
  794. $settings->destination_id[] = $form_state['values']['copy_destination_id'];
  795. }
  796. // Add the note.
  797. if (!empty($form_state['values']['description_enabled'])) {
  798. $settings->filters['utils_description'] = $form_state['values']['description'];
  799. }
  800. $form_state['values']['settings'] = $settings;
  801. }
  802. /**
  803. * Submit the quick backup form.
  804. */
  805. function backup_migrate_ui_manual_quick_backup_form_submit($form, &$form_state) {
  806. require_once dirname(__FILE__) . '/includes/destinations.inc';
  807. require_once dirname(__FILE__) . '/includes/profiles.inc';
  808. if (user_access('perform backup') && !empty($form_state['values']['settings'])) {
  809. // Save the settings for next time.
  810. variable_set("backup_migrate_source_id", $form_state['values']['source_id']);
  811. variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
  812. variable_set("backup_migrate_copy_destination_id", $form_state['values']['copy_destination_id']);
  813. variable_set("backup_migrate_profile_id", $form_state['values']['profile_id']);
  814. // Do the backup.
  815. backup_migrate_ui_manual_backup_perform($form_state['values']['settings']);
  816. }
  817. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH;
  818. }
  819. /**
  820. * Theme the quick backup form.
  821. */
  822. function theme_backup_migrate_ui_manual_quick_backup_form_inline($form) {
  823. drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
  824. $form = $form['form'];
  825. // Remove the titles so that the pulldowns can be displayed inline.
  826. unset($form['quickbackup']['source_id']['#title']);
  827. unset($form['quickbackup']['destination']['destination_id']['#title']);
  828. unset($form['quickbackup']['destination']['destination_id']['#description']);
  829. unset($form['quickbackup']['profile_id']['#title']);
  830. unset($form['quickbackup']['destination']['copy_destination']['copy_destination_id']['#title']);
  831. $replacements = array(
  832. '!from' => drupal_render($form['quickbackup']['source_id']),
  833. '!to' => drupal_render($form['quickbackup']['destination']['destination_id']),
  834. '!profile' => drupal_render($form['quickbackup']['profile_id']),
  835. // '!submit' => drupal_render($form['quickbackup']['submit']),
  836. );
  837. $form['quickbackup']['markup'] = array(
  838. '#type' => 'markup',
  839. "#prefix" => '<div class="container-inline backup-migrate-inline">',
  840. "#suffix" => '</div>',
  841. '#markup' => t('Backup my !from to !to using !profile', $replacements),
  842. );
  843. $replacements = array(
  844. '!to' => drupal_render($form['quickbackup']['destination']['copy_destination']['copy_destination_id']),
  845. );
  846. $form['quickbackup']['destination']['copy']["#prefix"] = '<div class="container-inline backup-migrate-inline">';
  847. $form['quickbackup']['destination']['copy']["#suffix"] = $replacements['!to'] . '</div>';
  848. // This is not good translation practice as it relies on the structure of
  849. // English. If I add the pulldown to the label, howerver, the box toggles
  850. // when the pulldown is clicked.
  851. // $form['quickbackup']['destination']['copy']['#title'] = t('Save a copy to');.
  852. unset($form['quickbackup']['source_id']);
  853. unset($form['quickbackup']['destination']['destination_id']);
  854. unset($form['quickbackup']['destination']['copy_destination']);
  855. unset($form['quickbackup']['profile_id']);
  856. // unset($form['quickbackup']['submit']);.
  857. return drupal_render_children($form);
  858. }
  859. /**
  860. * Theme the quick schedule form.
  861. */
  862. function theme_backup_migrate_ui_quick_schedule_form_inline($form) {
  863. drupal_add_js(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.js');
  864. drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
  865. $form = $form['form'];
  866. // Remove the titles so that the pulldowns can be displayed inline.
  867. unset($form['settings']['source_id']['#title']);
  868. unset($form['settings']['period']['#title']);
  869. unset($form['settings']['destination']['destination_id']['#title']);
  870. unset($form['settings']['destination']['destination_id']['#description']);
  871. unset($form['settings']['profile_id']['#title']);
  872. unset($form['settings']['destination']['copy_destination']['copy_destination_id']['#title']);
  873. unset($form['settings']['profile_id']['#title']);
  874. unset($form['settings']['keep']['#title']);
  875. unset($form['settings']['keep']['#field_prefix']);
  876. unset($form['settings']['keep']['#field_suffix']);
  877. $replacements = array(
  878. '!from' => drupal_render($form['settings']['source_id']),
  879. '!to' => drupal_render($form['settings']['destination']['destination_id']),
  880. '!frequency' => drupal_render($form['settings']['period']),
  881. '!profile' => drupal_render($form['settings']['profile_id']),
  882. '!keep' => drupal_render($form['settings']['keep']),
  883. );
  884. $form['settings'] = array(
  885. 'inline' => array(
  886. '#type' => 'markup',
  887. "#prefix" => '<div class="container-inline backup-migrate-quickschedule">',
  888. "#suffix" => '</div>',
  889. '#markup' => t('Backup !frequency to !to using !profile keeping !keep', $replacements),
  890. ),
  891. ) + $form['settings'];
  892. $replacements = array(
  893. '!to' => drupal_render($form['settings']['destination']['copy_destination']['copy_destination_id']),
  894. );
  895. $form['settings']['destination']['copy']["#prefix"] = '<div class="container-inline backup-migrate-inline">';
  896. $form['settings']['destination']['copy']["#suffix"] = $replacements['!to'] . '</div>';
  897. unset($form['settings']['period']);
  898. unset($form['settings']['destination']['destination_id']);
  899. unset($form['settings']['destination']['copy_destination']);
  900. unset($form['settings']['profile_id']);
  901. unset($form['settings']['keep']);
  902. return drupal_render_children($form);
  903. }
  904. /**
  905. * Theme the dependent form section.
  906. */
  907. function theme_backup_migrate_dependent($vars) {
  908. $element = $vars['element'];
  909. drupal_add_js(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.js');
  910. drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
  911. $id = drupal_html_id(implode('-', $element['#array_parents']));
  912. $settings = array(
  913. 'backup_migrate' => array(
  914. 'dependents' => array($id => array('dependent' => $id, 'dependencies' => $element['#dependencies'])),
  915. ),
  916. );
  917. drupal_add_js($settings, 'setting');
  918. return '<div id="edit-' . $id . '" class="backup-migrate-form-dependent">' . drupal_render_children($element) . '</div>';
  919. }
  920. /**
  921. * Theme file list form widget.
  922. */
  923. function theme_backup_migrate_file_list($vars) {
  924. $element = $vars['element'];
  925. // Render the radios so they can be placed in the file list rendering.
  926. $vars['element']['#display_options']['form_elements'] = array();
  927. if (isset($vars['element']['files']) && count($vars['element']['files'])) {
  928. foreach (element_children($vars['element']['files']) as $id) {
  929. $vars['element']['files'][$id]['#title'] = '';
  930. $vars['element']['#display_options']['form_elements'][$id] = render($vars['element']['files'][$id]);
  931. }
  932. }
  933. $out = _backup_migrate_ui_destination_display_file_list($vars['element']['#files'], $vars['element']['#display_options']);
  934. return $out;
  935. }
  936. /**
  937. * Theme the dependent form section.
  938. */
  939. function theme_backup_migrate_group($vars) {
  940. $output = '';
  941. if (!empty($vars['title'])) {
  942. $output .= '<h2 class="backup-migrate-group-title">' . $vars['title'] . '</h2>';
  943. }
  944. if (!empty($vars['description'])) {
  945. $output .= '<div class="backup-migrate-group-description backup-migrate-description description">' . $vars['description'] . '</div>';
  946. }
  947. $output .= '<div class="backup-migrate-group-body">' . $vars['body'] . '</div>';
  948. $output = '<div class="backup-migrate-group">' . $output . '</div>';
  949. return $output;
  950. }
  951. /**
  952. * The backup/export form.
  953. */
  954. function backup_migrate_ui_manual_backup_form($form, &$form_state, $profile) {
  955. drupal_add_js(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.js', array('type' => 'module', 'scope' => 'footer'));
  956. $form = array();
  957. $form += _backup_migrate_get_source_form('db');
  958. $form_state['profile'] = $profile;
  959. $form['machine_name'] = array(
  960. "#type" => "value",
  961. '#default_value' => $profile->get_id(),
  962. );
  963. $form['storage'] = array(
  964. "#type" => "value",
  965. '#default_value' => $profile->storage,
  966. );
  967. $form['destination'] = array(
  968. "#type" => "fieldset",
  969. "#title" => t("Backup Destination"),
  970. "#collapsible" => TRUE,
  971. "#collapsed" => FALSE,
  972. "#tree" => FALSE,
  973. "#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."),
  974. // '#weight' => 70,
  975. );
  976. $form['destination']['destination'] = _backup_migrate_get_destination_pulldown('manual backup', variable_get('backup_migrate_destination_id', 'download'));
  977. $form += _backup_migrate_ui_backup_settings_form($profile);
  978. // Make the source settings dependent on the source selected. Except don't
  979. // because it looks super weird.
  980. // @code
  981. // foreach (element_children($form['sources']) as $source) {
  982. // $form['sources'][$source] = array(
  983. // '#type' => 'backup_migrate_dependent',
  984. // '#dependencies' => array(
  985. // 'source_id' => $source,
  986. // ),
  987. // 'settings' => $form['sources'][$source]
  988. // );
  989. // }
  990. // @endcode
  991. if (user_access('administer backup and migrate')) {
  992. $form['save_settings'] = array(
  993. "#type" => "checkbox",
  994. "#title" => t('Save these settings.'),
  995. "#default_value" => FALSE,
  996. '#weight' => 80,
  997. );
  998. $form['save_options'] = array(
  999. '#type' => 'backup_migrate_dependent',
  1000. '#dependencies' => array(
  1001. 'save_settings' => TRUE,
  1002. ),
  1003. '#weight' => 90,
  1004. );
  1005. $name = array(
  1006. '#default_value' => $profile->get('name'),
  1007. '#type' => 'textfield',
  1008. '#title' => t('Save the settings as'),
  1009. );
  1010. if ($profile->get_id()) {
  1011. $form['save_options']['create_new'] = array(
  1012. '#default_value' => $profile->get('name'),
  1013. '#type' => 'radios',
  1014. '#default_value' => 0,
  1015. '#options' => array(
  1016. 0 => t("Replace the '%profile' profile", array('%profile' => $profile->get('name'))),
  1017. 1 => t('Create new profile'),
  1018. ),
  1019. );
  1020. $name["#title"] = t('Profile name');
  1021. $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')));
  1022. }
  1023. else {
  1024. $name["#title"] = t('Save the settings as');
  1025. $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')));
  1026. $name["#default_value"] = t('Untitled Profile');
  1027. }
  1028. $form['save_options']['name'] = $name;
  1029. $form['save_options'][] = array(
  1030. '#type' => 'submit',
  1031. '#value' => t('Save Without Backing Up'),
  1032. );
  1033. }
  1034. $form['#validate'][] = 'backup_migrate_ui_manual_quick_backup_form_validate';
  1035. $form['#submit'][] = 'backup_migrate_ui_manual_backup_form_submit';
  1036. $form['submit'] = array(
  1037. '#type' => 'submit',
  1038. '#value' => t('Backup now'),
  1039. '#weight' => 100,
  1040. );
  1041. return _backup_migrate_ui_action_form($form, $form_state, 'backup');
  1042. }
  1043. /**
  1044. * Submits the form.
  1045. *
  1046. * Save the values as defaults if desired and output the backup file.
  1047. */
  1048. function backup_migrate_ui_manual_backup_form_submit($form, &$form_state) {
  1049. // Create a profile with the given settings.
  1050. $profile = $form_state['profile'];
  1051. $profile->from_array($form_state['values']);
  1052. // Save the settings profile if the save box is checked.
  1053. if ($form_state['values']['save_settings'] && user_access('administer backup and migrate')) {
  1054. if (@$form_state['values']['create_new']) {
  1055. // Reset the id and storage so a new item will be saved.
  1056. $profile->set_id(NULL);
  1057. $profile->storage = BACKUP_MIGRATE_STORAGE_NONE;
  1058. }
  1059. $profile->save();
  1060. variable_set("backup_migrate_profile_id", $profile->get_id());
  1061. variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
  1062. }
  1063. // Perform the actual backup if that is what was selected.
  1064. if ($form_state['values']['op'] !== t('Save Without Backing Up') && user_access('perform backup')) {
  1065. backup_migrate_ui_manual_backup_perform($profile);
  1066. }
  1067. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . "/export/advanced";
  1068. }
  1069. /**
  1070. * Alters a B&M action (backup/restore) form to allow for filters to add steps.
  1071. */
  1072. function _backup_migrate_ui_action_form($form, &$form_state, $op = 'backup') {
  1073. $form['operation'] = array('#type' => 'value', '#value' => $op);
  1074. // If the form has been submitted at least once then see if there are
  1075. // additional form elements to add.
  1076. if (!empty($form_state['storage']['values']) && !empty($form_state['values']['settings'])) {
  1077. $page = _backup_migrate_filter_before_action_form($form_state['values']['settings'], $op);
  1078. if (!empty($page)) {
  1079. $page['#validate'] = $form['#validate'];
  1080. $page['#submit'] = $form['#submit'];
  1081. $page['submit'] = array(
  1082. '#type' => 'submit',
  1083. '#value' => isset($form_state['values']['op']) ? check_plain($form_state['values']['op']) : t('Continue'),
  1084. '#weight' => 1,
  1085. );
  1086. $form = $page;
  1087. }
  1088. }
  1089. // Add some pre and post processing functions to validate and submit.
  1090. array_unshift($form['#validate'], 'backup_migrate_ui_action_form_pre_validate');
  1091. array_push($form['#validate'], 'backup_migrate_ui_action_form_post_validate');
  1092. array_unshift($form['#submit'], 'backup_migrate_ui_action_form_pre_submit');
  1093. return $form;
  1094. }
  1095. /**
  1096. * Allows filters, sources and destinations to present additional form elements.
  1097. *
  1098. * The additional form elements will be shown to the user before an action is
  1099. * submitted.
  1100. */
  1101. function backup_migrate_ui_action_form_pre_validate($form, &$form_state) {
  1102. if (!empty($form_state['storage']['values'])) {
  1103. $form_state['values'] += $form_state['storage']['values'];
  1104. }
  1105. }
  1106. /**
  1107. * Allows filters, sources and destinations to present additional form elements.
  1108. *
  1109. * The additional form elements will be shown to the user before an action is
  1110. * submitted.
  1111. */
  1112. function backup_migrate_ui_action_form_post_validate($form, &$form_state) {
  1113. require_once dirname(__FILE__) . '/includes/filters.inc';
  1114. if (!empty($form_state['values']['settings'])) {
  1115. // See if there are extra form items to be processed.
  1116. $form = _backup_migrate_filter_before_action_form($form_state['values']['settings'], $form_state['values']['operation']);
  1117. if ($form) {
  1118. // First time through the form simply rebuild the form to show the
  1119. // additional fields.
  1120. if (empty($form_state['storage']['values'])) {
  1121. $form_state['storage']['values'] = $form_state['values'];
  1122. $form_state['rebuild'] = TRUE;
  1123. }
  1124. else {
  1125. backup_migrate_filters_before_action_form_validate($form_state['values']['settings'], $form_state['values']['operation'], $form, $form_state);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. /**
  1131. * Allows filters, sources and destinations to present additional form elements.
  1132. *
  1133. * The additional form elements will be shown to the user before an action is
  1134. * submitted.
  1135. */
  1136. function backup_migrate_ui_action_form_pre_submit($form, &$form_state) {
  1137. if (!empty($form_state['storage']['values']) && !empty($form_state['values']['settings'])) {
  1138. // Check if there are any form elements to submit.
  1139. backup_migrate_filters_before_action_form_submit($form_state['values']['settings'], $form_state['values']['operation'], $form, $form_state);
  1140. // Clear the storage so the form can continue as normal.
  1141. unset($form_state['storage']);
  1142. }
  1143. }
  1144. /**
  1145. * Retrieves form items to be filled out before an action can continue.
  1146. *
  1147. * @return array
  1148. * An array of form items.
  1149. */
  1150. function _backup_migrate_filter_before_action_form($settings, $op) {
  1151. $form = array();
  1152. $form = backup_migrate_filters_before_action_form($settings, $op);
  1153. return $form;
  1154. }
  1155. /**
  1156. * Perform an actual manual backup and tell the user of the progress.
  1157. */
  1158. function backup_migrate_ui_manual_backup_perform($settings) {
  1159. // Peform the actual backup.
  1160. backup_migrate_perform_backup($settings);
  1161. }
  1162. /**
  1163. * The restore/import upload page.
  1164. */
  1165. function backup_migrate_ui_manual_restore() {
  1166. return drupal_get_form('backup_migrate_ui_manual_restore_form');
  1167. }
  1168. /**
  1169. * The restore/import upload form.
  1170. */
  1171. function backup_migrate_ui_manual_restore_form() {
  1172. require_once dirname(__FILE__) . '/includes/destinations.inc';
  1173. require_once dirname(__FILE__) . '/includes/filters.inc';
  1174. require_once dirname(__FILE__) . '/includes/sources.inc';
  1175. 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);
  1176. $form = array();
  1177. $from_default = (isset($_GET['page']) || isset($_GET['sort'])) ? 'saved' : 'upload';
  1178. $form['backup_migrate_restore_from_upload'] = array(
  1179. "#type" => "radio",
  1180. "#title" => t('Restore from an uploaded file'),
  1181. '#return_value' => 'upload',
  1182. '#parents' => array('from'),
  1183. '#default_value' => $from_default,
  1184. );
  1185. $form['backup_migrate_restore_upload'] = array(
  1186. '#type' => 'backup_migrate_dependent',
  1187. '#dependencies' => array(
  1188. 'from' => 'upload',
  1189. ),
  1190. );
  1191. $form['backup_migrate_restore_upload']['backup_migrate_restore_upload'] = array(
  1192. '#title' => t('Upload a Backup File'),
  1193. '#type' => 'file',
  1194. '#description' => t("Upload a backup file created by Backup and Migrate. For other database or file backups please use another tool for import. Max file size: %size", array("%size" => format_size(file_upload_max_size()))),
  1195. );
  1196. $form['backup_migrate_restore_from_saved'] = array(
  1197. "#type" => "radio",
  1198. "#title" => t('Restore from a saved backup'),
  1199. '#return_value' => 'saved',
  1200. '#parents' => array('from'),
  1201. '#default_value' => $from_default,
  1202. );
  1203. $form['backup_migrate_restore_saved'] = array(
  1204. '#type' => 'backup_migrate_dependent',
  1205. '#dependencies' => array(
  1206. 'from' => 'saved',
  1207. ),
  1208. );
  1209. list($files, $fetch_time, $remote) = backup_migrate_get_saved_backups();
  1210. $keys = array_keys($files);
  1211. $default = reset($keys);
  1212. $form['backup_migrate_restore_saved']['file'] = array(
  1213. '#type' => 'backup_migrate_file_list',
  1214. '#display_options' => array(
  1215. 'limit' => 5,
  1216. 'pager' => FALSE,
  1217. 'more' => BACKUP_MIGRATE_MENU_PATH . '/backups',
  1218. 'operations' => FALSE,
  1219. ),
  1220. '#default_value' => $default,
  1221. '#files' => $files,
  1222. );
  1223. $sources = _backup_migrate_get_source_form_item_options();
  1224. if (count($sources) > 1) {
  1225. $form['source_id'] = array(
  1226. "#type" => "select",
  1227. "#title" => t("Restore to"),
  1228. "#options" => $sources,
  1229. "#description" => t("Choose where to restore to. Any database destinations you have created and any databases specified in your settings.php can be restored to."),
  1230. "#default_value" => 'db',
  1231. );
  1232. }
  1233. else {
  1234. $form['source_id'] = array(
  1235. "#type" => "value",
  1236. "#value" => 'db',
  1237. );
  1238. }
  1239. $form = array_merge_recursive($form, backup_migrate_filters_settings_form(backup_migrate_filters_settings_default('restore'), 'restore'));
  1240. // Add the advanced fieldset if there are any fields in it.
  1241. if (isset($form['advanced'])) {
  1242. $form['advanced']['#type'] = 'fieldset';
  1243. $form['advanced']['#title'] = t('Advanced Options');
  1244. $form['advanced']['#collapsed'] = TRUE;
  1245. $form['advanced']['#collapsible'] = TRUE;
  1246. }
  1247. $form['submit'] = array(
  1248. '#type' => 'submit',
  1249. '#value' => t('Restore now'),
  1250. );
  1251. if (user_access('access backup files')) {
  1252. $form[] = array(
  1253. '#type' => 'markup',
  1254. '#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 . '/backups'))),
  1255. );
  1256. }
  1257. $form['#attributes'] = array('enctype' => 'multipart/form-data');
  1258. return $form;
  1259. }
  1260. /**
  1261. * The restore submit. Do the restore.
  1262. */
  1263. function backup_migrate_ui_manual_restore_form_submit($form, &$form_state) {
  1264. require_once dirname(__FILE__) . '/includes/destinations.inc';
  1265. $validators = array(
  1266. 'file_validate_extensions' => array('gz zip sql mysql bz bz2 encrypt'),
  1267. );
  1268. $values = $form_state['values'];
  1269. if ($values['from'] == 'upload' && $file = file_save_upload('backup_migrate_restore_upload', $validators)) {
  1270. backup_migrate_perform_restore('upload', $file->uri, $values);
  1271. }
  1272. elseif ($values['from'] == 'saved' && $file = $values['file']) {
  1273. list($destination, $file_id) = explode('/', $file, 2);
  1274. $file =
  1275. backup_migrate_perform_restore($destination, $file_id, $form_state['values']);
  1276. }
  1277. $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . '/restore';
  1278. }
  1279. /**
  1280. * Convert an item to an 'exportable'.
  1281. */
  1282. function backup_migrate_ui_export_form($form, &$form_state, $item) {
  1283. if ($item && function_exists('ctools_var_export')) {
  1284. $code = ctools_var_export($item);
  1285. $form = ctools_export_form($form, $form_state, $code);
  1286. return $form;
  1287. }
  1288. return array();
  1289. }
  1290. /**
  1291. * List the previously created backups from across multiple destinations.
  1292. */
  1293. function backup_migrate_ui_saved_backups() {
  1294. require_once dirname(__FILE__) . '/includes/destinations.inc';
  1295. require_once dirname(__FILE__) . '/includes/profiles.inc';
  1296. require_once dirname(__FILE__) . '/includes/sources.inc';
  1297. drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
  1298. $remote = FALSE;
  1299. $now = $fetch_time = time();
  1300. $refresh = isset($_GET['refresh']);
  1301. $out = '';
  1302. list($files, $fetch_time, $remote) = backup_migrate_get_saved_backups($refresh);
  1303. // Redirect if refreshing instead of displaying.
  1304. if ($refresh) {
  1305. drupal_goto($_GET['q']);
  1306. }
  1307. $fetch = $out = '';
  1308. // Get the fetch link.
  1309. if ($fetch_time < $now) {
  1310. $fetch = '<div class="description">' . t('This listing was fetched !time ago. !refresh', array(
  1311. '!time' => format_interval($now - $fetch_time, 1),
  1312. '!refresh' => l(t('fetch now'), $_GET['q'], array(
  1313. 'query' => array('refresh' => 'true'),
  1314. )),
  1315. )) . '</div>';
  1316. }
  1317. // Render the list.
  1318. $out .= $fetch;
  1319. $out .= _backup_migrate_ui_destination_display_file_list($files, array('limit' => 20, 'pager' => TRUE));
  1320. $out .= $fetch;
  1321. // Add a remote backups warning if there are no remote backups.
  1322. if (!$remote && user_access('administer backup and migrate')) {
  1323. drupal_set_message(
  1324. t('You do not have any offsite backups. For the highest level of protection, <a href="!addurl">create an offsite destination</a> to save your backups to.',
  1325. array(
  1326. '!addurl' => url(BACKUP_MIGRATE_MENU_PATH . '/settings/destination/add'),
  1327. )), 'warning', FALSE);
  1328. }
  1329. return $out;
  1330. }
  1331. /**
  1332. * List the previously created backups from across multiple destinations.
  1333. */
  1334. function backup_migrate_get_saved_backups($refresh = FALSE) {
  1335. require_once dirname(__FILE__) . '/includes/destinations.inc';
  1336. require_once dirname(__FILE__) . '/includes/profiles.inc';
  1337. require_once dirname(__FILE__) . '/includes/sources.inc';
  1338. drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
  1339. $remote = FALSE;
  1340. $now = $fetch_time = time();
  1341. $out = '';
  1342. $files = $sort = array();
  1343. foreach (backup_migrate_get_destinations('list files') as $destination) {
  1344. $dest_id = $destination->get_id();
  1345. $dest_files = $destination->list_files();
  1346. if ($dest_files) {
  1347. $location = l($destination->get_name(), BACKUP_MIGRATE_MENU_PATH . '/settings/destination/list/files/' . $dest_id);
  1348. if ($destination->get('remote')) {
  1349. $location .= $destination->get('remote') ? ' <strong class="backup-migrate-tag">(' . t('offsite') . ')</strong>' : '';
  1350. $remote = TRUE;
  1351. }
  1352. // Refresh the destination.
  1353. if ($refresh) {
  1354. $destination->file_cache_clear();
  1355. }
  1356. // Get the file fetch time.
  1357. if ($destination->cache_files && $destination->fetch_time) {
  1358. $fetch_time = min($destination->fetch_time, $fetch_time);
  1359. }
  1360. // Add the files from this destination to the full list.
  1361. foreach ($dest_files as $id => $file) {
  1362. $dest_files[$id]->file_info['bam_other_safe'][t('Location:')] = $location;
  1363. $sort[$dest_id . '/' . $id] = $file->info('filetime');
  1364. $files[$dest_id . '/' . $id] = $file;
  1365. }
  1366. }
  1367. }
  1368. array_multisort($sort, SORT_DESC, $files);
  1369. return array($files, $fetch_time, $remote);
  1370. }
  1371. /**
  1372. * Helper function for byte conversion.
  1373. *
  1374. * @see README.txt
  1375. * @see http://php.net/manual/en/ini.core.php#ini.memory-limit
  1376. */
  1377. function backup_migrate_to_bytes($from) {
  1378. $passes_sanity_check = preg_match('/^(-1|[0-9]+|[0-9]*(\.[0-9]+)?[mg])$/i', $from);
  1379. if (!$passes_sanity_check) {
  1380. return 0;
  1381. }
  1382. if ($from === '-1') {
  1383. return -1;
  1384. }
  1385. $number = substr($from, 0, -1);
  1386. $unit = strtoupper(substr($from, -1));
  1387. switch ($unit) {
  1388. case "M":
  1389. return $number * pow(1024, 2);
  1390. break;
  1391. case "G":
  1392. return $number * pow(1024, 3);
  1393. break;
  1394. default:
  1395. return $number * pow(1024, 2);
  1396. }
  1397. }
  1398. /**
  1399. * Perform a backup with the given settings.
  1400. */
  1401. function backup_migrate_perform_backup(&$settings) {
  1402. require_once dirname(__FILE__) . '/includes/destinations.inc';
  1403. require_once dirname(__FILE__) . '/includes/files.inc';
  1404. require_once dirname(__FILE__) . '/includes/filters.inc';
  1405. timer_start('backup_migrate_backup');
  1406. _backup_migrate_set_timeout();
  1407. // Conditionally increase the memory limit.
  1408. // Get the current php memory limit.
  1409. $php_memory_limit = ini_get('memory_limit');
  1410. // If the memory limit is set to -1, there's no need to do anything.
  1411. if ($php_memory_limit !== -1) {
  1412. // Convert the php memory limit to bytes.
  1413. $php_memory_limit_bytes = backup_migrate_to_bytes($php_memory_limit);
  1414. // Get the current Backup Migrate memory limit.
  1415. // Hint: To further increase the memory limit used by Backup Migrate add one
  1416. // of the following line to the settings.php file:
  1417. // * $conf['backup_migrate_memory_limit'] = '512M';
  1418. // * $conf['backup_migrate_memory_limit'] = '1G';.
  1419. $backup_migrate_memory_limit = variable_get('backup_migrate_memory_limit', BACKUP_MIGRATE_MEMORY_LIMIT);
  1420. // Convert the Backup Migrate memory limit to bytes.
  1421. $backup_migrate_memory_limit_bytes = backup_migrate_to_bytes($backup_migrate_memory_limit);
  1422. // If not in 'safe mode', increase the memory limit.
  1423. if (!ini_get('safe_mode') && $php_memory_limit_bytes < $backup_migrate_memory_limit_bytes) {
  1424. // Ensure ini_set() is not disabled.
  1425. if (!strpos(ini_get('disable_functions'), 'ini_set')) {
  1426. // Convert bytes to megabytes, add the 'M' unit.
  1427. $backup_migrate_memory_limit = round($backup_migrate_memory_limit_bytes / 1024 / 1024) . 'M';
  1428. // Update the php memory limit.
  1429. ini_set('memory_limit', $backup_migrate_memory_limit);
  1430. }
  1431. }
  1432. }
  1433. if (variable_get('backup_migrate_verbose')) {
  1434. _backup_migrate_message("Memory limit: %limit", array('%limit' => ini_get('memory_limit')), 'success');
  1435. }
  1436. // Confirm the destinations are valid.
  1437. $valid = backup_migrate_destination_confirm_destination($settings);
  1438. if (!$valid) {
  1439. backup_migrate_backup_fail("Could not run backup because a there was no valid destination to save to.", array(), $settings);
  1440. return FALSE;
  1441. }
  1442. // Create the temporary file object to be backed up into.
  1443. $filename = _backup_migrate_construct_filename($settings);
  1444. $file = new backup_file(array('filename' => $filename));
  1445. if (!$file) {
  1446. backup_migrate_backup_fail("Could not run backup because a temporary file could not be created.", array(), $settings);
  1447. return FALSE;
  1448. }
  1449. // Register shutdown callback to deal with timeouts.
  1450. register_shutdown_function('backup_migrate_shutdown', $settings);
  1451. if (variable_get('backup_migrate_verbose')) {
  1452. watchdog('backup_migrate', "Starting backup: %file", array('%file' => $file->filename()));
  1453. }
  1454. $file = backup_migrate_filters_backup($file, $settings);
  1455. if (!$file) {
  1456. if (_backup_migrate_check_timeout()) {
  1457. 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);
  1458. }
  1459. else {
  1460. backup_migrate_backup_fail("Could not complete the backup.", array(), $settings);
  1461. }
  1462. return FALSE;
  1463. }
  1464. if (variable_get('backup_migrate_verbose')) {
  1465. watchdog('backup_migrate', "Preparing to save backup: %file", array('%file' => $file->filename()));
  1466. }
  1467. $file = backup_migrate_destination_save_file($file, $settings);
  1468. if (!$file) {
  1469. backup_migrate_backup_fail("Could not run backup because the file could not be saved to the destination.", array(), $settings);
  1470. return FALSE;
  1471. }
  1472. if (variable_get('backup_migrate_verbose')) {
  1473. watchdog('backup_migrate', "Backup succeeded: %file", array('%file' => $file->filename()));
  1474. }
  1475. // Backup succeeded.
  1476. $time = timer_stop('backup_migrate_backup');
  1477. $message = '%source backed up successfully to %file (%size) in destination %dest in !time. !action';
  1478. $params = array(
  1479. '%file' => $filename,
  1480. '%dest' => $settings->get_destination_name(),
  1481. '%source' => $settings->get_source_name(),
  1482. '%size' => format_size($file->filesize()),
  1483. '!time' => backup_migrate_format_elapsed_time($time['time']),
  1484. '!action' => !empty($settings->performed_action) ? $settings->performed_action : '',
  1485. );
  1486. if (($destination = $settings->get_destination()) && ($links = $destination->get_file_links($file->file_id()))) {
  1487. $params['!links'] = implode(", ", $links);
  1488. }
  1489. backup_migrate_backup_succeed($message, $params, $settings);
  1490. return $file;
  1491. }
  1492. /**
  1493. * Formats an elapsed time given in milleseconds.
  1494. */
  1495. function backup_migrate_format_elapsed_time($time) {
  1496. $ms = t('!time ms', array('!time' => $time));
  1497. if ($time < 1000) {
  1498. return $ms;
  1499. }
  1500. return '<abbr title="' . $ms . '">' . format_interval($time / 1000) . '</abbr>';
  1501. }
  1502. /**
  1503. * Restore from a file in the given destination.
  1504. */
  1505. function backup_migrate_perform_restore($destination_id, $file, $settings = array()) {
  1506. require_once dirname(__FILE__) . '/includes/files.inc';
  1507. require_once dirname(__FILE__) . '/includes/filters.inc';
  1508. timer_start('backup_migrate_restore');
  1509. _backup_migrate_set_timeout();
  1510. // Make the settings into a default profile.
  1511. if (!is_object($settings)) {
  1512. $settings = backup_migrate_crud_create_item('profile', $settings);
  1513. $settings->source_id = empty($settings->source_id) ? 'db' : $settings->source_id;
  1514. }
  1515. // Register shutdown callback.
  1516. register_shutdown_function('backup_migrate_shutdown', $settings);
  1517. if (!is_object($file)) {
  1518. // Load the file from the destination.
  1519. $file = backup_migrate_destination_get_file($destination_id, $file);
  1520. if (!$file) {
  1521. _backup_migrate_message("Could not restore because the file could not be loaded from the destination.", array(), 'error');
  1522. backup_migrate_cleanup();
  1523. return FALSE;
  1524. }
  1525. }
  1526. // Filter the file and perform the restore.
  1527. $file = backup_migrate_filters_restore($file, $settings);
  1528. if (!$file) {
  1529. if (_backup_migrate_check_timeout()) {
  1530. 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');
  1531. }
  1532. else {
  1533. backup_migrate_restore_fail("Could not perform the restore.", array(), 'error');
  1534. }
  1535. backup_migrate_cleanup();
  1536. return FALSE;
  1537. }
  1538. $time = timer_stop('backup_migrate_restore');
  1539. if ($file) {
  1540. $destination = backup_migrate_get_destination($destination_id);
  1541. $message = '%source restored from %dest file %file in !time. !action';
  1542. $params = array(
  1543. '%file' => $file->filename(),
  1544. '%source' => $settings->get_source_name(),
  1545. '%dest' => $destination->get_name(),
  1546. '!time' => backup_migrate_format_elapsed_time($time['time']),
  1547. '!action' => !empty($settings->performed_action) ? $settings->performed_action : '',
  1548. );
  1549. if ($destination && $destination->op('list files')) {
  1550. $path = $destination->get_settings_path();
  1551. $params['!links'] = t('<a href="!restoreurl">Restore again</a>', array('!restoreurl' => url($path . '/list/restorefile/' . $destination->get_id() . '/' . $file->file_id())));
  1552. }
  1553. backup_migrate_restore_succeed($message, $params, $settings);
  1554. }
  1555. // Delete any temp files we've created.
  1556. backup_migrate_cleanup();
  1557. // No errors. Return the file.
  1558. return $file;
  1559. }
  1560. /**
  1561. * Clean up when a backup operation fails.
  1562. */
  1563. function backup_migrate_backup_fail($message, $params, $settings) {
  1564. require_once dirname(__FILE__) . '/includes/files.inc';
  1565. require_once dirname(__FILE__) . '/includes/filters.inc';
  1566. _backup_migrate_message($message, $params, 'error');
  1567. backup_migrate_cleanup();
  1568. backup_migrate_filters_invoke_all('backup_fail', $settings, $message, $params);
  1569. return FALSE;
  1570. }
  1571. /**
  1572. * Clean up when a backup operation succeeds.
  1573. */
  1574. function backup_migrate_backup_succeed($message, $params, $settings) {
  1575. require_once dirname(__FILE__) . '/includes/files.inc';
  1576. require_once dirname(__FILE__) . '/includes/filters.inc';
  1577. _backup_migrate_message($message, $params, 'success');
  1578. backup_migrate_cleanup();
  1579. backup_migrate_filters_invoke_all('backup_succeed', $settings, $message, $params);
  1580. return FALSE;
  1581. }
  1582. /**
  1583. * Clean up when a restore operation fails.
  1584. */
  1585. function backup_migrate_restore_fail($message, $params, $settings) {
  1586. require_once dirname(__FILE__) . '/includes/files.inc';
  1587. require_once dirname(__FILE__) . '/includes/filters.inc';
  1588. _backup_migrate_message($message, $params, 'error');
  1589. backup_migrate_cleanup();
  1590. backup_migrate_filters_invoke_all('restore_fail', $settings, $message, $params);
  1591. return FALSE;
  1592. }
  1593. /**
  1594. * Clean up when a restore operation succeeds.
  1595. */
  1596. function backup_migrate_restore_succeed($message, $params, $settings) {
  1597. require_once dirname(__FILE__) . '/includes/files.inc';
  1598. require_once dirname(__FILE__) . '/includes/filters.inc';
  1599. _backup_migrate_message($message, $params, 'success');
  1600. backup_migrate_cleanup();
  1601. backup_migrate_filters_invoke_all('restore_succeed', $settings, $message, $params);
  1602. return FALSE;
  1603. }
  1604. /**
  1605. * Cleans up after a success or failure.
  1606. */
  1607. function backup_migrate_cleanup() {
  1608. // Check that the cleanup function exists. If it doesn't then we probably
  1609. // didn't create any files to be cleaned up.
  1610. if (function_exists('_backup_migrate_temp_files_delete')) {
  1611. _backup_migrate_temp_files_delete();
  1612. }
  1613. }
  1614. /**
  1615. * Shutdown callback.
  1616. *
  1617. * Called when the script terminates even if the script timed out.
  1618. */
  1619. function backup_migrate_shutdown($settings) {
  1620. // If we ran out of time, set an error so the user knows what happened.
  1621. if (_backup_migrate_check_timeout()) {
  1622. backup_migrate_cleanup();
  1623. 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);
  1624. // The session will have already been written and closed, so we need to
  1625. // write any changes directly.
  1626. _drupal_session_write(session_id(), session_encode());
  1627. // Add a redirect or we'll just get whitescreened.
  1628. drupal_goto(BACKUP_MIGRATE_MENU_PATH);
  1629. }
  1630. }
  1631. /**
  1632. * Action to backup the drupal site.
  1633. *
  1634. * Requires actions.module.
  1635. *
  1636. * function action_backup_migrate_backup($op, $edit = array()) {
  1637. * switch ($op) {
  1638. * case 'do':
  1639. * _backup_migrate_backup_with_defaults();
  1640. * watchdog('action', 'Backed up database');
  1641. * break;.
  1642. * * Case 'metadata':
  1643. * return array(
  1644. * 'description' => t('Backup the database with the default settings'),
  1645. * 'type' => t('Backup and Migrate'),
  1646. * 'batchable' => TRUE,
  1647. * 'configurable' => FALSE,
  1648. * );
  1649. * * // Return an HTML config form for the action.
  1650. * * case 'form':
  1651. * return '';
  1652. * * // Validate the HTML form.
  1653. * * case 'validate':
  1654. * return TRUE;
  1655. * * // Process the HTML form to store configuration.
  1656. * * case 'submit':
  1657. * return '';
  1658. * }
  1659. * }.
  1660. */
  1661. /**
  1662. * Implements hook_action_info().
  1663. */
  1664. // Function backup_migrate_action_info() {
  1665. // return array(
  1666. // 'backup_migrate_action_backup' => array(
  1667. // 'label' => t('Backup the database'),
  1668. // 'description' => t('Backup the database with the default settings.'),
  1669. // ),
  1670. // );
  1671. // }.
  1672. /**
  1673. * Action callback.
  1674. */
  1675. function backup_migrate_action_backup() {
  1676. _backup_migrate_backup_with_defaults();
  1677. }
  1678. /**
  1679. * Backup the database with the default settings.
  1680. */
  1681. function _backup_migrate_backup_with_defaults($destination_id = "manual") {
  1682. require_once dirname(__FILE__) . '/includes/files.inc';
  1683. require_once dirname(__FILE__) . '/includes/profiles.inc';
  1684. $settings = _backup_migrate_profile_saved_default_profile();
  1685. $settings->destination_id = $destination_id;
  1686. $settings->source_id = 'db';
  1687. backup_migrate_perform_backup($settings);
  1688. }
  1689. /**
  1690. * Helper function to set a Drupal message and watchdog message.
  1691. *
  1692. * Depends on whether the module is being run interactively.
  1693. */
  1694. function _backup_migrate_message($message, $replace = array(), $type = 'status') {
  1695. // Only set a message if there is a callback handler to handle the message.
  1696. if (($callback = _backup_migrate_message_callback()) && function_exists($callback)) {
  1697. $callback($message, $replace, $type);
  1698. }
  1699. // Store the message in case it's needed (for the status notification filter
  1700. // for example).
  1701. _backup_migrate_messages($message, $replace, $type);
  1702. }
  1703. /**
  1704. * Helper function to set a Drupal message and watchdog message.
  1705. *
  1706. * Depends on whether the module is being run interactively.
  1707. */
  1708. function _backup_migrate_messages($message = NULL, $replace = array(), $type = 'status') {
  1709. static $messages = array();
  1710. if ($message) {
  1711. $messages[] = array(
  1712. 'message' => $message,
  1713. 'replace' => $replace,
  1714. 'type' => $type,
  1715. );
  1716. }
  1717. return $messages;
  1718. }
  1719. /**
  1720. * Sends a message to the browser.
  1721. *
  1722. * The normal type of message handling for interactive use.
  1723. */
  1724. function _backup_migrate_message_browser($message, $replace, $type) {
  1725. // Log the message as well for admins.
  1726. _backup_migrate_message_log($message, $replace, $type);
  1727. // If there are links, we can display them in the browser.
  1728. if (!empty($replace['!links'])) {
  1729. $message .= " (!links)";
  1730. }
  1731. // Use drupal_set_message to display to the user.
  1732. drupal_set_message(t($message, $replace), str_replace('success', 'status', $type), FALSE);
  1733. }
  1734. /**
  1735. * Logs a message if we are in a non-interactive mode such as a cron run.
  1736. */
  1737. function _backup_migrate_message_log($message, $replace, $type) {
  1738. // We only want to log the errors or successful completions.
  1739. if (in_array($type, array('error', 'success'))) {
  1740. watchdog('backup_migrate', $message, $replace, $type == 'error' ? WATCHDOG_ERROR : WATCHDOG_NOTICE);
  1741. }
  1742. }
  1743. /**
  1744. * Sets or retrieves a message handler.
  1745. */
  1746. function _backup_migrate_message_callback($callback = NULL) {
  1747. static $current_callback = '_backup_migrate_message_log';
  1748. if ($callback !== NULL) {
  1749. $current_callback = $callback;
  1750. }
  1751. return $current_callback;
  1752. }
  1753. /**
  1754. * Increase the execution timeout, and also the database connection timeout.
  1755. */
  1756. function _backup_migrate_set_timeout() {
  1757. // If not in 'safe mode', increase the maximum execution time:
  1758. $backup_max_time = variable_get('backup_migrate_backup_max_time', BACKUP_MIGRATE_BACKUP_MAX_TIME);
  1759. if (!ini_get('safe_mode') && ini_get('max_execution_time') < $backup_max_time) {
  1760. drupal_set_time_limit($backup_max_time);
  1761. }
  1762. // Also increase the time mysql keeps the connection open.
  1763. if (Database::getConnection() instanceof DatabaseConnection_mysql) {
  1764. $mysql_wait_timeout = db_query('SELECT @@session.wait_timeout')->fetchField();
  1765. if ($mysql_wait_timeout < $backup_max_time) {
  1766. // This does not work with placeholders, so sanitize by casting to int.
  1767. db_query('SET SESSION wait_timeout = ' . (int) $backup_max_time);
  1768. }
  1769. }
  1770. }
  1771. /**
  1772. * Determines if time for a page execution has run out.
  1773. */
  1774. function _backup_migrate_check_timeout() {
  1775. static $timeout;
  1776. // Max execution of 0 means unlimited.
  1777. if (ini_get('max_execution_time') == 0) {
  1778. return FALSE;
  1779. }
  1780. // Figure out when we should stop execution.
  1781. if (!$timeout) {
  1782. $backup_max_time = max(ini_get('max_execution_time'), variable_get('backup_migrate_backup_max_time', BACKUP_MIGRATE_BACKUP_MAX_TIME));
  1783. $timeout = (!empty($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time()) + $backup_max_time - variable_get('backup_migrate_timeout_buffer', 5);
  1784. }
  1785. return (time() > $timeout);
  1786. }
  1787. /**
  1788. * Converts an associated array to an ini format string.
  1789. */
  1790. function _backup_migrate_array_to_ini($data, $prefix = '') {
  1791. $content = '';
  1792. foreach ($data as $key => $val) {
  1793. if ($prefix) {
  1794. $key = $prefix . '[' . $key . ']';
  1795. }
  1796. if (is_array($val)) {
  1797. $content .= _backup_migrate_array_to_ini($val, $key);
  1798. }
  1799. else {
  1800. $content .= $key . ' = "' . $val . "\"\n";
  1801. }
  1802. }
  1803. return $content;
  1804. }
  1805. /**
  1806. * Execute a command line command.
  1807. *
  1808. * @return bool
  1809. * Returns FALSE if the function failed.
  1810. */
  1811. function backup_migrate_exec($command, $args = array()) {
  1812. if (!function_exists('exec') || ini_get('safe_mode')) {
  1813. return FALSE;
  1814. }
  1815. // Escape the arguments.
  1816. foreach ($args as $key => $arg) {
  1817. $args[$key] = escapeshellarg($arg);
  1818. }
  1819. $command = strtr($command, $args);
  1820. $output = $result = NULL;
  1821. // Run the command.
  1822. exec($command, $output, $result);
  1823. return $result == 0;
  1824. }
  1825. /**
  1826. * Format a size, treating 1GB as 1000 MB rather than 1024 MB.
  1827. *
  1828. * This is a more standard and expected version for storage (as opposed to
  1829. * memory).
  1830. */
  1831. function backup_migrate_format_size($size, $langcode = LANGUAGE_NONE) {
  1832. $precision = 2;
  1833. $multiply = pow(10, $precision);
  1834. if ($size == 0) {
  1835. return t('0 bytes', array(), array('langcode' => $langcode));
  1836. }
  1837. if ($size < 1024) {
  1838. return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
  1839. }
  1840. else {
  1841. $size = ceil($size * $multiply / 1024);
  1842. $string = '@size KB';
  1843. if ($size >= (1024 * $multiply)) {
  1844. $size = ceil($size / 1024);
  1845. $string = '@size MB';
  1846. }
  1847. if ($size >= 1000 * $multiply) {
  1848. $size = ceil($size / 1000);
  1849. $string = '@size GB';
  1850. }
  1851. if ($size >= 1000 * $multiply) {
  1852. $size = ceil($size / 1000);
  1853. $string = '@size TB';
  1854. }
  1855. return t($string, array('@size' => round($size / $multiply, $precision)), array('langcode' => $langcode));
  1856. }
  1857. }
  1858. /**
  1859. * Implements hook_mail().
  1860. */
  1861. function backup_migrate_mail($key, &$message, $params) {
  1862. if ($key == 'backup_succeed') {
  1863. $message['id'] = 'backup_migrate_backup_succeed';
  1864. $message['subject'] = t('!site backup succeeded', array('!site' => variable_get('site_name', 'Drupal site')));
  1865. $message['body'][] = $params['body'];
  1866. }
  1867. elseif ($key == 'backup_fail') {
  1868. $message['id'] = 'backup_migrate_backup_fail';
  1869. $message['subject'] = t('!site backup failed', array('!site' => variable_get('site_name', 'Drupal site')));
  1870. $message['body'][] = $params['body'];
  1871. }
  1872. elseif ($key == 'destination_mail') {
  1873. // @todo translate subject and parts of the body?
  1874. $message['subject'] = $params['subject'];
  1875. $message['body'][] = $params['body'];
  1876. $message['headers'] = array_merge($message['headers'], $params['headers']);
  1877. }
  1878. }
  1879. /**
  1880. * Identify the current memory usage.
  1881. *
  1882. * Uses the same formula as the Devel module.
  1883. *
  1884. * @return int
  1885. * The current memory usage, in megabytes.
  1886. */
  1887. function backup_migrate_get_peak_memory_usage() {
  1888. return round(memory_get_peak_usage(TRUE) / 1024 / 1024, 2);
  1889. }
  1890. /**
  1891. * Returns the "name" element from an array.
  1892. *
  1893. * Callback for array_map() within
  1894. * backup_migrate_destination_db_mysql::_restore_db_from_file() and
  1895. * backup_migrate_source_db_mysql::_restore_db_from_file().
  1896. */
  1897. function backup_migrate_array_name_value($a) {
  1898. return $a["name"];
  1899. }
  1900. /**
  1901. * Checks if a php.ini 'memory_limit' style value is valid.
  1902. *
  1903. * See http://php.net/manual/en/ini.core.php#ini.memory-limit for what are
  1904. * valid values.
  1905. */
  1906. function _backup_migrate_is_valid_memory_limit($value) {
  1907. $test = preg_match('/^(-1|[0-9]+|[0-9]*(\.[0-9]+)?[mg])$/i', $value);
  1908. // preg_match() returns truthy or falsy values, this makes it explicit.
  1909. $out = $test ? TRUE : FALSE;
  1910. return $test;
  1911. }