all contrib module security updates done

This commit is contained in:
2020-09-24 22:47:32 +02:00
parent 7d87153100
commit 0fbb9c4610
1612 changed files with 116663 additions and 32269 deletions
@@ -0,0 +1,310 @@
Backup and Migrate 7.x-3.9, 2020-07-15
--------------------------------------
#3158379 by DamienMcKenna, monnerat: Fixed compatibility with PHP 5.4.
Backup and Migrate 7.x-3.8, 2020-07-10
--------------------------------------
#3119038 by solideogloria, gisle: Spelling typo in update scripts.
#3143362 by DamienMcKenna, solideogloria: Undefined variable $machine_name in
install file.
#3143250 by DamienMcKenna: Use utf8mb4 for MySQL files.
#3154166 by DamienMcKenna: Remove use of backup_migrate_include() entirely.
#3129399 by solideogloria, DamienMcKenna: Missing ctools_export_form parameter.
#3158378 by DamienMcKenna, ron_s: Adjust default performance settings.
#3158379 by DamienMcKenna: Coding standards improvements.
Backup and Migrate 7.x-3.7, 2020-02-28
--------------------------------------
#3032453 by DamienMcKenna: Ignore Advanced Aggregator CSS & JS directories.
#3026187 by DamienMcKenna: Configurations don't load correctly when upgrading
from 7.x-2.x to 3.x, clear caches.
#2606586 by Darren Oh, dmargetts, joelpittet, DamienMcKenna, solideogloria: Fix
smart delete not saving files for all periods.
#3026186 by DamienMcKenna: Menus not rebuilt after upgrading from 7.x-2.x.
#2507495 by brankoc, DamienMcKenna, nicorac, lorisbel, crantok, jakeru,
NickWilde, DD 85, rothlive, Oleg Ko, mgstables, szczesuil, Web.Pergamonteam,
Lemontonix, Tranko, aotus, knalstaaf, drugan, lesliewagner1165, Pascal.s,
HansKuiters, mato, lgough, Frosty29, sdowney2002, dhalbert, toomanypets, ckng,
havanablackcu1, myDrupal2014_846824658246, felixmf: Warning: mail(): Multiple
or malformed newlines found in additional_header in mime_mail->send().
#2135813 by RickJ, rlhawk: Support for the Encrypt module.
#3033583 by BrankoC: Add CTools as a test dependency.
#2946311 by DamienMcKenna, k.elizabeth, couturier, jackalope, nelslynn,
rrirower, bmango, Cyberflyer, sharonknieper: Too many connections in
backup_migrate_source_db->_get_db_connection().
#3023804 by DamienMcKenna, solideogloria, adam1, jazzitup, MaxMendez, jprj,
Louis Delacretaz, eloiv, oliverpolden, drupal_jon, mato, VirtualMitra: Error:
Call to undefined function _backup_migrate_temp_files_delete().
#2663066 by BrankoC, DamienMcKenna, bsains, izmeez: Profile Filter field -
hitting 64Kb limit.
#3023414 by BrankoC, DamienMcKenna, wylbur: Provide settings page for the hidden
variables.
#1042672 by fietserwin, BrankoC: hook_help: do not translate texts if not
necessary.
#3060997 by solideogloria, BrankoC: Improve Performance of Schedule Calculation.
#3064783 by BrankoC, DamienMcKenna: Uninstalling this module leaves variable
backup_migrate_schedule_last_run_* intact.
#3051821 by DamienMcKenna, BrankoC, solideogloria, wylbur: Remove NodeSquirrel
integration.
#3033583 by BrankoC, DamienMcKenna, m.stenta, RickJ, wylbur: CTools exportables
code no longer loading.
#2507495 by BrankoC, DamienMcKenna: Update script to disable destinations
affected by the email delivery change.
#3046235 by joelpittet: Slow query 'show table status' on menu rebuild.
#3102427 by izmeez: Readme.txt minor typo and formatting fixes.
#3102506 by DamienMcKenna, BrankoC: Verify destinations work before listing them
in the Quick Backup form; save the file system form before beginning backup
tests to ensure the private file system is configured correctly.
#3102218 by DamienMcKenna, BrankoC, jacob.embree, izmeez, devad, joelpittet,
fietserwin, wylbur: Update 7310 Disable e-mail destinations. Emits syntax
error for MySQL and MariaDB.
#3027709 by BrankoC, DamienMcKenna, ultrabob: "A non-numeric value encountered"
in backup_migrate_to_bytes().
#3116733 by DamienMcKenna, fietserwin: PDOException: SQLSTATE[42S02]: Base table
or view not found: 1146 Table 'variable' doesn't exist.
#2885094 by pdcarto, avergara, couturier: CLI option dumps the ENTIRE database,
ignores 'nodata_tables' setting.
Backup and Migrate 7.x-3.6, 2018-12-15
--------------------------------------
#2293601 by KimNyholm, fastturtle: Errors shown because directory handles are
not closed when no longer needed.
#2937023 by DamienMcKenna: Add a test for the basic UI functionality.
#2945704 by DamienMcKenna: Write tests for each backup filename option.
#2939277 by DamienMcKenna, baronmunchowsen: File mode change on
sources.archivesource.inc.
#2935403 by DamienMcKenna, jacob.embree: Improve coding standards compliance.
#2962822 by laryn: Spelling mistake: "frequecy".
#2917959 by DamienMcKenna: Updated backup_migrate_update_7305() to fix schema
problems.
#2996191 by mwnciau, DamienMcKenna: Special characters in database password
causes PHP notifications.
#2949211 by gturnbull, DamienMcKenna, Alex Bukach, Eli.Stone, joelpittet:
Optional memory limit setting to work around out-of-memory errors during
backups.
#2494757 by pbuyle, DamienMcKenna, Ives, Calystod: Allow running a scheduled
backup with Drush.
#2404113 by DamienMcKenna, John Cook, danharper, salmino: Different host for
AWS type server.
#2829492 by axel.rutz, RickJ, DamienMcKenna, devad, Kris77, pietrocap,
couturier: Big file backup breaks with "MySQL server has gone away".
#3001702 by DamienMcKenna: Code cleanup on 7.x-3.x branch.
#2831470 by snehal.addweb, bfodeke, jigish.addweb: Delete query in
hook_uninstall() can potentially remove unintended variables.
#3004759 by Manthan.addweb, echoz: Notice: Undefined index: exclude_filepaths...
visiting Advanced Backup tab.
#3013355 by jacob.embree: Syntax error in backup_migrate.js.
#2415421 by ron_s, coredumperror, blake.thompson, John Bickar: Backup and
Migrate module and private file system.
#3002975 by DamienMcKenna: Improve logging around the cron and backup processes.
#2747197 by RickJ: Network errors writing to Nodesquirrel handled badly.
#3014594 by DamienMcKenna: backup_migrate_uninstall() doesn't delete all.
variables; renamed "backup_migrate_backup_memory_limit" variable to
"backup_migrate_memory_limit".
#3014601 by DamienMcKenna: Re-enable all tests.
#3014143 by DamienMcKenna: Add master switch to turn off hook_cron.
#3014603 by DamienMcKenna: Add a CHANGELOG.txt file.
#3014596 by DamienMcKenna: Require PHP 5.4.
#2943719 by DamienMcKenna: Reduce memory usage during MySQL database generation.
#2338841 by catch, dasha_v, DamienMcKenna: Incorrect translated string +
menu_rebuild() performance issue.
#1104012 by DamienMcKenna, axel.rutz, EmanueleQuinto, gisle, jacob.embree, Pere
Orga, frenkx: On restore, provide option to drop all tables.
#2891272 by DamienMcKenna, webservant316: phpsnif 7.1 says Method name
\backup_migrate_destination_nodesquirrel::__xmlrpc\" is discouraged; PHP has
reserved all method names with a double underscore prefix for future use.
#3014597 by DamienMcKenna: Document the advanced backup options.
#2382541 by sano, DamienMcKenna, couturier, dman, modulist: Updated
instructions for installing the S3 library.
#3016278 by DamienMcKenna: Some debug messages aren't hidden behind
backup_migrate_verbose.
#3016282 by DamienMcKenna: "Cannot add field
backup_migrate_profiles.machine_name: field already exists" error.
#3017042 by DamienMcKenna, freelylw, gisle: Settings form field dependency
broken.
#3018002 by DamienMcKenna: Improve the module's documentation.
By DamienMcKenna: "server" not "sever" :-)
#3018853 by RickJ: Temporary files not deleted.
#2735337 by RickJ: Settings objects only offer Revert, not Delete.
Backup and Migrate 7.x-3.5, 2018-02-05
--------------------------------------
#2941981 by DamienMcKenna, Rick J, camhoward: Backup files being overwritten
because of a change to the append_timestamp setting.
#2940451 by Darren Oh: Unlimited max_execution_time treated as 0 seconds.
Backup and Migrate 7.x-3.4, 2018-01-24
--------------------------------------
By DamienMcKenna, pere-orga, ikit-claw, cashwilliams: Make all permissions
restricted.
#1058820 by kbasarab, sobi3ch, gbirch, avatxus: Add option to overwrite file.
#2498191 by DamienMcKenna: Unable to backup to NodeSquirrel using PHP 5.6.9
(on Windows) due to changes in SSL validation rules.
#2742855 by hanoii: Caching profile objects led to unwanted behaviors because of
stale data.
#2703351 by DamienMcKenna, ultrabob: Redundant methods in
backup_migrate_location_remote.
#2728345 by Rick J: Nodesquirrel destination class doesn't return its name.
#2728331 by Rick J: Incorrect paging count in saved backup list.
#2498179 by junaidpv: Use drupal_mail() for system notifications.
#2920311 by DamienMcKenna: Check backup directory permissions / web
accessibility.
#2912459 by DamienMcKenna: Add an initial test.
#2880434 by DamienMcKenna, benqwerty: Minor changes to drush help output.
#2914644 by DamienMcKenna, jacob.embree: List all files which contain classes in
the info file so other modules can use the classes.
#2663928 by DamienMcKenna, fietserwin: public://languages should also be
excluded by default.
#2388347 by DamienMcKenna: Nodequirrel destination class doesn't define $errno,
$errstr but assumes they're available.
#2899586 by juankvillegas, DamienMcKenna: Ensure the page variable is numeric in
backup_migrate_nodesquirrel_status_form().
Backup and Migrate 7.x-3.3, 2017-10-18
--------------------------------------
#2290707 by DamienMcKenna, mitsuroseba, Darren Oh: Exclude the data from the
following tables - does not work.
#2830554 by axel.rutz: Support Ultimate Cron.
#2728349 by Rick J: Disabled schedules still run under Elysia cron.
Backup and Migrate 7.x-3.2, 2017-09-27
--------------------------------------
#2702229 by DamienMcKenna: Automatically add all cache tables to the 'nodata'
list, exclude simpletest tables.
#2618516 by rocketeerbkw: Fatal error when restoring "Entire Site".
#2839264 by wizonesolutions: Error: [] operator not supported for strings in
backup_migrate_crud_ui_list_all().
#2633304 by adamelleston: 'clone' is a reserved keyword introduced in PHP
version 5.0 and cannot be invoked as a function.
#2547065 by snehi: Description for filesource location is inaccurate.
#2672478 by serverofworld, lklimek: Wrong destination when running multiple
schedules using the same profile.
#1542274 by dale42, LGLC, AjitS: Restore fails with foreign key constraint error
(due to incorrect comment detection).
#2623598 by SylvainM, joelstein: Deprecated: Methods with the same name as their
class will not be constructors in a future version of PHP.
#2513720 by rrfegade: Code Spell errors.
By ronan: Cleaned up use of manage url generator.
#2495681 by DamienMcKenna: Secure all endpoint connections to NodeSquirrel
destination service.
#2495677 by DamienMcKenna: Inconsistent use of https for manage.nodesquirrel.com
hostname.
#2277383 by hswong3i: Fix schema mismatch after upgrade 7.x-3.x.
Backup and Migrate 7.x-3.1, 2015-05-11
--------------------------------------
By ronan: Added pantheon notice and free notice to NodeSquirrel page.
#2347637: Add a Note to Backup doesn't work with Jquery > 1.7.
By ronan: Set Nodesquirrel schedule to use smart delete by default.
#2477503: Error returned, but exit status is 0.
#2369461: Scheduled Backups stopped working after 7.x-3.0?.
#2390057: Site doesn't come out of maintenance mode when backing up entire site.
#2455265: Update Version Number in README.TXT.
By ronan: Updated NS messaging slightly.
#2393615: Compression not running (only when backing up entire site).
#2324949: Update #7303 Failing.
#2421183: Stream URI - Not ignored (Recognized?) during backups.
#2378739: "Exclude the data from the following tables" not respected when "Use
cli commands" is checked.
#2307655 Fixed adding of full system path to site archive.
#2290707 by marvoey Advanced Backup link on quick backup page goes to wrong
place.
#2290707 Exclude the data from the following tables - does not work.
By ronan: Moved run time check before scheduled backup attempt to fix too-
frequent schedule issue.
#2280743: Files restore duplicating directory structure
(sites/default/files/sites/default/files).
#2276663 Permissions - Access backup files.
#2283701 by alarcombe. Restore not possible from archive.
#2286835 by Fernando Vesga. Advanced backup page link error.
#2287157 by topsitemakers. Links to "Create new destination" and "Create new
schedule" are invalid.
#2287239 by topsitemakers. Minor typo in an error message.
#2278865 by topsitemakers Undefined index: files in
theme_backup_migrate_file_list.
Backup and Migrate 7.x-3.0, 2014-05-27
--------------------------------------
By ronan: Fixed comment on install hook.
#2266381 Warning: Invalid argument supplied for foreach() in
backup_migrate_schedules_cron() on line 48.
#1001654 Fixed ctools exportables.
By ronan: Added nodesquirrel scheduling back. Fixed issue with restore from
previous radios. Added function to retrieve the most recent backup from the
given destination. This may be used in a drush command.
By ronan: Removed link to help text when help module is off.
By ronan: Removed confusing 'Quick Schedule' tab.
#2225335 Drush commands not working.
By ronan: Increased machine_name length in ui for compatibility with migrated
items.
By ronan: Fixed a couple of php errors.
By ronan: Minor wording tweaks.
By ronan: Added better status for NodeSquirrel.
By ronan: Removed dpm.
By ronan: Added dependency to offline message on restore.
By ronan: Removed stray console.log from the js.
By ronan: Added most recent saved backups to the restore tab.
By ronan: Ported MySQL views support.
By ronan: Fixed some issues saving profiles.
By ronan: Added a @TODO to remind me to fix saving on the advance backup page.
#1974740 allow backup of codebase & files to skip unreadable files.
By ronan: Merge branch 'refs/heads/NodeSquirrel-Language' into 7.x-3.x.
By ronan: Fixed up some language and links to NodeSquirrel.
By ronan: Cleaned up directory handling to support more directory structures.
By ronan: Added some description language for NodeSquirrel.
#2166813 Files backup fails when PEAR is not installed.
#2155381 by JulienD Remove useless files[] directive from .info files.
#1947206 by Les Lim. "No data" tables are exported even when they're in the
"Exclude the following tables altogether" list.
#2031393 A debugging function call left behind.
#2031777 Wrong function signature on form callback.
#2065573 wrong default file token.
#2039951 settings page gone for schedules.
#2009392 Settings don't save for file or entire site sources.
#1998788 missing i in NodeSquirrel.
By ronan: Moved NodeSquirrel tab to match the 2.x branch.
By ronan: Some d7 style cleanup.
By ronan: Fixed nodesquirrel destination with new id structure.
By ronan: Added checkplain to description on listing.
By ronan: Fixed an issue with multiselect js invading other pages.
#1564408 Gzip backups are compressed twice when downloaded.
#1991686 thx morningtime. Undefined property: backup_migrate_schedule::$last_run
By ronan: Switch to hourly default to align with smart delete default.
#839254 Switched to using drupal_reapath to allow for stream wrapper schemas.
#839254 Checking absolute paths within the docroot.
#839254 check for access restriction ignores custom destination path.
#1503202 Suhosin refuses sending mail because of to many new lines in mail
header (possible attacker).
#1529174 Fatal Error when database name is longer than 21 characters.
By ronan: Fixed 'Restore again' link.
#1974720 error message on attempting to restore manual backup.
#1974744 warning on creation of new settings profile.
By ronan: Fixed inconsistent use of 'source' and 'destination'.
By ronan: Changed destination_id to machine_name to fix issue with default file
destinations.
By ronan: Fixed error noise caused by ftp not connecting.
By ronan: Fixed error on file delete form.
By ronan: Fixed fatal error in metadata util when a backup fails.
#1968210 error message on attempting backup of entire site.
By ronan: Improved error reporting when a non-existant file (such as a broken
symlink) cannot be backed up.
#1968196 Error message on install in php 5.4.
By ronan: Fixed checkboxes.
By ronan: Fixed fatal error with token replace.
By ronan: Created full upgrade path from 2.x. Fixed source settings.
By ronan: Fixed db scheme issue. Fixed file source realpath issue.
By ronan: Switched type to subtype for ctools compatibility.
By ronan: Added machine_name js and ctools exportables.
By ronan: Fixed source specific settings in backup.
By ronan: Fixed issue with edit screen for source settings in profiles.
By ronan: Fixed export.
By ronan: Cleaned up more fatal errors. Better handling of translatable titles.
@@ -1,94 +1,216 @@
Backup and Migrate
------------------
This module makes the task of backing up a site's Drupal database, code and
all uploaded files and of migrating data from one Drupal install to another
easier.
Database backup files are a list of SQL statements which can be executed with a
tool such as phpMyAdmin or the command-line mysql client. File and code backup
files are tarballs which can be restored by extracting them to the desired
directory.
Installation
-------------------------------------------------------------------------------
Backup and Migrate 2 for Drupal 7.x
by Ronan Dowling, Gorton Studios - ronan (at) gortonstudios (dot) com
-------------------------------------------------------------------------------
DESCRIPTION:
This module 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.
There are options to exclude the data from certain tables (such as cache or
search index tables) to increase efficiency by ignoring data that does not need
to be backed up or migrated.
The backup files are a list of SQL statements which can be executed with a tool
such as phpMyAdmin or the command-line mysql client.
-------------------------------------------------------------------------------
INSTALLATION:
* Put the module in your Drupal modules directory and enable it in
admin/modules.
* Go to admin/people/permissions and grant permission to any roles that need to be
able to backup or restore the database.
* Configure and use the module at admin/config/system/backup_migrate
* Put the module in the Drupal modules directory and enable it via
admin/modules.
* Go to admin/people/permissions and grant permission to any roles that need to
be able to backup or restore the database.
* Configure and use the module at admin/config/system/backup_migrate.
OPTIONAL:
* To drop all tables before import, expand "Advanced options" panel under the
"Restore" and "Saved backups" tabs and tick the option.
* Enable token.module to allow token replacement in backup file names.
* To Backup to Amazon S3:
- Download the S3 library from http://undesigned.org.za/2007/10/22/amazon-s3-php-class
and place the file 'S3.php' in the includes directory in this module.
The stable version (0.4.0 20th Jul 2009) works best with Backup and Migrate.
- Download the most recent version from:
https://github.com/tpyo/amazon-s3-php-class
- Or clone it with command:
git clone https://github.com/tpyo/amazon-s3-php-class.git s3-php5-curl
- Rename the unzipped folder to s3-php5-curl
LIGHTTPD USERS:
Add the following code to your lighttp.conf to secure your backup directories:
The most recent version of the library known to work is 0.5.1.
Advanced settings
-------------------------------------------------------------------------------
Several advanced options are available from the Advanced Settings page:
* admin/config/system/backup_migrate/settings-advanced
These settings should be handled with care, it is recommended to leave them at
their defaults unless there is a specific need to modify them.
Additional requirements for LigHTTPd
-------------------------------------------------------------------------------
Add the following code to the lighttp.conf to secure the backup directories:
$HTTP["url"] =~ "^/sites/default/files/backup_migrate/" {
url.access-deny = ( "" )
url.access-deny = ( "" )
}
You may need to adjust the path to reflect the actual path to the files.
It may be necessary to adjust the path to reflect the actual path to the files.
IIS 7 USERS:
Add the following code to your web.config code to secure your backup directories:
Additional requirements for IIS 7
-------------------------------------------------------------------------------
Add the following code to the web.config code to secure the backup
directories:
<rule name="postinst-redirect" stopProcessing="true">
<match url="sites/default/files/backup_migrate" />
<action type="Rewrite" url=""/>
</rule>
You may need to adjust the path to reflect the actual path to the files.
It may also be necessary to adjust the path to reflect the actual path to the
files.
VERY IMPORTANT SECURITY NOTE
-------------------------------------------------------------------------------
VERY IMPORTANT SECURITY NOTE:
Backup files may contain sensitive data and by default, are saved to your web
Backup files may contain sensitive data and, by default, are saved to the web
server in a directory normally accessible by the public. This could lead to a
very serious security vulnerability. Backup and Migrate attempts to protect
backup files using a .htaccess file, but this is not guaranteed to work on all
environments (and is guaranteed to fail on web servers that are not apache). You
should test to see if your backup files are publicly accessible, and if in doubt
do not save backups to the server, or use the destinations feature to save to a
folder outside of your webroot.
environments (and is guaranteed to fail on web servers that are not Apache). It
is imperative to test to see if the site's backup files are publicly
accessible, and if in doubt do not save backups to the server, or use the
destinations feature to save to a folder outside of the site's webroot.
OTHER WARNINGS:
A failed restore can destroy your database and therefore your entire Drupal
Other warnings
-------------------------------------------------------------------------------
A failed restore can destroy the database and therefore the entire Drupal
installation. ALWAYS TEST BACKUP FILES ON A TEST ENVIRONMENT FIRST. If in doubt
do not use this module.
This module has only been tested with MySQL and does not work with any other dbms.
If you have experiences with Postgres or any other dbms and are willing to help
test and modify the module to work with it, please contact the developer at
ronan (at) gortonstudios (dot) com.
This module has only been tested with MySQL and does not work with any other
dbms. Assistance in adding support for other database systems would be
appreciated, see the issue queue for further details.
Make sure your php timeout is set high enough to complete a backup or restore
Make sure the PHP timeout is set high enough to complete a backup or restore
operation. Larger databases require more time. Also, while the module attempts
to keep memory needs to a minimum, a backup or restore will require
significantly more memory then most Drupal operations.
significantly more memory than most Drupal operations.
If your backup file contains the 'sessions' table all other users will be logged
out after you run a restore. To avoid this, exclude the sessions table when
creating your backups. Be aware though that you will need to recreate the
sessions table if you use this backup on an empty database.
If the backup file contains the 'sessions' table all other users will be logged
out after running a restore. To avoid this, exclude the sessions table when
creating the backups. Be aware though that this table is still required to run
Drupal, so it will need to be recreated if the backup is restored onto an empty
database.
Do not change the file extension of backup files or the restore function will be
unable to determine the compression type the file and will not function
unable to determine the compression type of the file and will not function
correctly.
IF A RESTORE FAILS:
Don't panic, the restore file should work with phpMyAdmin's import function, or
with the mysql command line tool. If it does not, then it is likely corrupt; you
may panic now. MAKE SURE THAT THIS MODULE IS NOT YOUR ONLY FORM OF BACKUP.
The module's permissions should only be given to trusted users due to the
inherent security vulnerabilities in allowing people access to a site's database
and/or files backups.
If a restore fails
-------------------------------------------------------------------------------
Don't panic!
The restore file should still work with phpMyAdmin's import function or with
the mysql command line tool.
If the backup does not restore using either a graphical tool or the command line
tools, then it is likely corrupt; you may panic now.
MAKE SURE THAT THIS MODULE IS NOT THE ONLY FORM OF BACKUP.
Known problems and workarounds
-------------------------------------------------------------------------------
* If backups fail due to an out-of-memory, try adjusting the memory limit using
the "backup_migrate_memory_limit" variable by adding one of these lines
to the site's settings.php file:
// Backup & Migrate: Use 512MB when generating backups.
$conf['backup_migrate_memory_limit'] = '512M';
// Backup & Migrate: Use 1GB when generating backups.
$conf['backup_migrate_memory_limit'] = '1G';
* If backups fail due to a PHP timeout error, especially an error saying "MySQL
server has gone away", use the "backup_migrate_backup_max_time" variable to
adjust the timeout. Before doing this, check to see what PHP's
"max_execution_time" is set to, then set the "backup_migrate_backup_max_time"
variable to a higher number, e.g. if max_execution_time is 180 (seconds) try
setting backup_migrate_backup_max_time to 240 seconds / 4 minutes, or 300
seconds / 5 minutes
// Backup & Migrate: Adjust the PHP timeout to 5 minutes / 300 seconds.
$conf['backup_migrate_backup_max_time'] = 300;
* A variable has been added which may help with problems. Setting the variable
'backup_migrate_verbose' to TRUE will make the module log additional messages
to watchdog as the module performs certain actions.
// Backup & Migrate: Log extra messages as the module is working.
$conf['backup_migrate_verbose'] = TRUE;
* It can be frustrating working from a production database backup on non-prod
servers as schduled backups will automatically run via cron the same as they
run on production. The custom cron tasks may be disabled using the
"backup_migrate_disable_cron" variable. Note: this doesn't prevent people
from manually running backups via the UI or from the Drush commands, so it is
safe to hardcode to TRUE on all site instances and then hardcode to FALSE on
production environments.
// Backup & Migrate: Don't run backups via cron.
$conf['backup_migrate_disable_cron'] = TRUE;
* There are three different variables that control how MySQL data is processed.
Should a site have problems with memory limits, it is worth testing these to
see which ones work the best.
- backup_migrate_data_rows_per_query
Controls how many records are loaded from the database at once. Defaults to
"1000", i.e. 1,000 rows. Note that setting this to a high number can cause
problems when exporting large data sets, e.g. cache tables can have huge
volumes of data per record.
// Backup & Migrate: Load 10,000 rows at once.
$conf['backup_migrate_data_rows_per_query'] = 10000;
- backup_migrate_data_rows_per_line
Controls how many records are included in a single INSERT statement.
Defaults to "30", i.e. 30 records.
// Backup & Migrate: Combine no more than five records in a single row.
$conf['backup_migrate_data_rows_per_line'] = 5;
- backup_migrate_data_bytes_per_line
Controls how much data will be inserted at once using a single INSERT
statement. This works with the "backup_migrate_data_rows_per_line" variable
to ensure that each INSERT statement doesn't end up being too large.
Defaults to "2000", i.e. 2,000 bytes.
// Backup & Migrate: Limit the output to 1000 bytes at a time.
$conf['backup_migrate_data_bytes_per_line'] = 1000;
Development notes
--------------------------------------------------------------------------------
It is worth noting that some of the tests will fail when ran against nginx,
which is the default web server for some local development systems. As a result,
it is recommended to run tests on a server that uses Apache HTTPd Server instead
of nginx.
Credits / contact
--------------------------------------------------------------------------------
Currently maintained by Alex Andrascu [1], Damien McKenna [2] and
Daniel Pickering [3]. All original development up through 2015 was by
Ronan Dowling [4] with help by Drew Gorton [5].
The best way to contact the authors is to submit an issue, be it a support
request, a feature request or a bug report, in the project issue queue:
https://www.drupal.org/project/issues/backup_migrate
References
--------------------------------------------------------------------------------
1: https://www.drupal.org/u/alex-andrascu
2: https://www.drupal.org/u/damienmckenna
3: https://www.drupal.org/u/ikit-claw
4: https://www.drupal.org/u/ronan
5: https://www.drupal.org/u/dgorton
@@ -0,0 +1,188 @@
<?php
/**
* @file
* Functionality required for the advanced settings form.
*/
/**
* The advanced settings form.
*/
function backup_migrate_ui_advanced_settings_form($form, &$form_state) {
$form['backup_migrate_advanced_settings_intro'] = array(
'#markup' => t('These settings should be handled with care, it is recommended to leave them at their defaults unless there is a specific need to modify them.'),
'#prefix' => '<p>',
'#suffix' => '</p>',
);
$form['backup_migrate_memory_limit'] = array(
'#type' => 'textfield',
'#title' => t('Memory Limit'),
'#default_value' => variable_get('backup_migrate_memory_limit', BACKUP_MIGRATE_MEMORY_LIMIT),
'#description' => t('If backups fail due to an out-of-memory, try adjusting the memory limit using a php.ini style value, for example 512M for 512 megabytes or 1G for 1 gigabyte. Default: !default.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_MEMORY_LIMIT) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('backup_migrate_memory_limit_validate'),
);
$form['backup_migrate_backup_max_time'] = array(
'#type' => 'textfield',
'#title' => t('Time Limit'),
'#default_value' => variable_get('backup_migrate_backup_max_time', BACKUP_MIGRATE_BACKUP_MAX_TIME),
'#description' => t('If backups fail due to a PHP timeout error, especially an error saying "MySQL server has gone away", increase this setting. Before doing this, check to see what PHP\'s "max_execution_time" is set to, then set this field to a higher number, e.g. if max_execution_time is 180 (seconds) try setting Time Limit to 240 seconds (4 minutes), or 300 seconds (5 minutes). Default: !default.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_BACKUP_MAX_TIME) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('element_validate_integer_positive'),
);
$form['backup_migrate_verbose'] = array(
'#type' => 'checkbox',
'#title' => t('Verbose Output'),
'#default_value' => variable_get('backup_migrate_verbose', BACKUP_MIGRATE_VERBOSE),
'#description' => t('Enable this to make the module log additional messages to watchdog as the module performs certain actions. Default: !default.', array('!default' => (BACKUP_MIGRATE_VERBOSE ? 'on' : 'off'))),
'#required' => FALSE,
);
$form['backup_migrate_disable_cron'] = array(
'#type' => 'checkbox',
'#title' => t('Disable Cron'),
'#default_value' => variable_get('backup_migrate_disable_cron', BACKUP_MIGRATE_DISABLE_CRON),
'#description' => t('It can be frustrating working from a production database backup on non-prod servers as schduled backups will automatically run via cron the same as they run on production. The custom cron tasks may be disabled using this checkbox. Note: this doesn\'t prevent people from manually running backups via the UI or from the Drush commands, so it is safe to enable on all site instances and then disable on production environments. Default: !default.', array('!default' => (BACKUP_MIGRATE_DISABLE_CRON ? 'on' : 'off'))),
'#required' => FALSE,
);
$form['backup_migrate_data_rows_per_query'] = array(
'#type' => 'textfield',
'#title' => t('Rows Per Query'),
'#default_value' => variable_get('backup_migrate_data_rows_per_query', BACKUP_MIGRATE_DATA_ROWS_PER_QUERY),
'#description' => t('Controls how many records are loaded from the database at once. Defaults to "!default", i.e. !default rows. Note that setting this to a high number can cause problems when exporting large data sets, e.g. cache tables can have huge volumes of data per record.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_DATA_ROWS_PER_QUERY) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('element_validate_integer_positive'),
);
$form['backup_migrate_data_rows_per_line'] = array(
'#type' => 'textfield',
'#title' => t('Rows Per Line'),
'#default_value' => variable_get('backup_migrate_data_rows_per_line', BACKUP_MIGRATE_DATA_ROWS_PER_LINE),
'#description' => t('Controls how many records are included in a single INSERT statement. Defaults to "!default", i.e. !default records.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_DATA_ROWS_PER_LINE) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('element_validate_integer_positive'),
);
$form['backup_migrate_data_bytes_per_line'] = array(
'#type' => 'textfield',
'#title' => t('Data Bytes Per Line'),
'#default_value' => variable_get('backup_migrate_data_bytes_per_line', BACKUP_MIGRATE_DATA_BYTES_PER_LINE),
'#description' => t('Controls how much data will be inserted at once using a single INSERT statement. This works with the "backup_migrate_data_rows_per_line" variable to ensure that each INSERT statement doesn\'t end up being too large. Defaults to "!default", i.e. !default bytes.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_DATA_BYTES_PER_LINE) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('element_validate_integer_positive'),
);
$form['backup_migrate_max_email_size'] = array(
'#type' => 'textfield',
'#title' => t('Maximum E-mail Size'),
'#default_value' => variable_get('backup_migrate_max_email_size', BACKUP_MIGRATE_MAX_EMAIL_SIZE),
'#description' => t('In bytes. Limits the size of e-mails with attached back-ups that can be sent. Default: !default.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_MAX_EMAIL_SIZE) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('backup_migrate_unsigned_integer_validate'),
);
$form['backup_migrate_cleanup_temp_files'] = array(
'#type' => 'checkbox',
'#title' => t('Clean up Temporary Files'),
'#default_value' => variable_get('backup_migrate_cleanup_temp_files', BACKUP_MIGRATE_CLEANUP_TEMP_FILES),
'#description' => t('Should temporary files be deleted during the current back-up run? Default: !default.', array('!default' => (BACKUP_MIGRATE_CLEANUP_TEMP_FILES ? 'on' : 'off'))),
'#required' => FALSE,
);
$form['backup_migrate_cleanup_time'] = array(
'#type' => 'textfield',
'#title' => t('Clean-up Time'),
'#default_value' => variable_get('backup_migrate_cleanup_time', BACKUP_MIGRATE_CLEANUP_TIME),
'#description' => t('Delete temporary files belonging to this modules that are older than the expire time. In seconds. 21600 seconds is 6 hours. Default: !default.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_CLEANUP_TIME) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('element_validate_integer'),
);
$form['backup_migrate_schedule_buffer'] = array(
'#type' => 'textfield',
'#title' => t('Schedule buffer'),
'#default_value' => variable_get('backup_migrate_schedule_buffer', BACKUP_MIGRATE_SCHEDULE_BUFFER),
'#description' => t('Add a small negative buffer (for example 1% of the entire period) to the time to account for slight difference in cron run length. Format: percentage of the period as a decimal fraction between 0 and 1. Default: !default.', array('!default' => '<kbd>' . check_plain(BACKUP_MIGRATE_SCHEDULE_BUFFER) . '</kbd>')),
'#required' => FALSE,
'#element_validate' => array('backup_migrate_fraction_validate'),
);
// Check for overrides and report them to the user.
$keys = array_keys($form);
$query = db_query('SELECT name, value FROM {variable} WHERE name IN (:keys)', array(':keys' => $keys));
$result = $query->fetchAllKeyed();
foreach ($form as $key => $field) {
if (isset($result[$key])) {
// Compare the value with what we have in the database.
$db_value = unserialize($result[$key]);
if ($field['#default_value'] != $db_value) {
$form[$key]['#description'] .= ' <b>Overridden in settings.php: ' . check_plain($field['#default_value']) . '.</b>';
}
}
}
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save configuration'),
);
return $form;
}
/**
* The advanced settings form.
*/
function backup_migrate_ui_advanced_settings_form_submit($form, &$form_state) {
$variables = array(
'backup_migrate_backup_max_time' => BACKUP_MIGRATE_BACKUP_MAX_TIME,
'backup_migrate_cleanup_temp_files' => BACKUP_MIGRATE_CLEANUP_TEMP_FILES,
'backup_migrate_cleanup_time' => BACKUP_MIGRATE_CLEANUP_TIME,
'backup_migrate_data_bytes_per_line' => BACKUP_MIGRATE_DATA_BYTES_PER_LINE,
'backup_migrate_data_rows_per_line' => BACKUP_MIGRATE_DATA_ROWS_PER_LINE,
'backup_migrate_data_rows_per_query' => BACKUP_MIGRATE_DATA_ROWS_PER_QUERY,
'backup_migrate_disable_cron' => BACKUP_MIGRATE_DISABLE_CRON,
'backup_migrate_max_email_size' => BACKUP_MIGRATE_MAX_EMAIL_SIZE,
'backup_migrate_memory_limit' => BACKUP_MIGRATE_MEMORY_LIMIT,
'backup_migrate_schedule_buffer' => BACKUP_MIGRATE_SCHEDULE_BUFFER,
'backup_migrate_verbose' => BACKUP_MIGRATE_VERBOSE,
);
foreach ($variables as $var_name => $var_default) {
if (isset($form_state['values'][$var_name])) {
// There's no need to save the variable if it's just the default.
if ($form_state['values'][$var_name] == $var_default) {
variable_del($var_name);
}
// The variable is not the default, so save it.
else {
variable_set($var_name, $form_state['values'][$var_name]);
}
}
}
}
/**
* Validate fields that require a PHP.ini-like memory_limit value.
*/
function backup_migrate_memory_limit_validate($element, &$form_state, $form) {
if (!_backup_migrate_is_valid_memory_limit($element['#value'])) {
form_error($element, t('%name must be a valid memory limit setting.', array('%name' => $element['#title'])));
}
}
/**
* Validate fields that require zero or a positive integer.
*/
function backup_migrate_unsigned_integer_validate($element, &$form_state, $form) {
$value = $element['#value'];
$test = preg_match('/^[0-9]+$/', $value);
if ($test !== 1) {
form_error($element, t('%name must be zero or a positive integer.', array('%name' => $element['#title'])));
}
}
/**
* Validate fields that require a decimal between 0 and 1.
*
* @todo Better name.
*/
function backup_migrate_fraction_validate($element, &$form_state, $form) {
$value = $element['#value'];
$test = preg_match('/^(0|1|0?\.[0-9]+)$/', $value);
if ($test !== 1) {
form_error($element, t('%name must be a decimal between 0 and 1.', array('%name' => $element['#title'])));
}
}
@@ -1,5 +1,10 @@
/**
* @file
* Custom CSS for the Backup Migrate module.
*/
.schedule-list-disabled {
filter:alpha(opacity=50);
filter: alpha(opacity=50);
-moz-opacity: .50;
opacity: .50;
}
@@ -8,7 +13,7 @@
font-size: 0.85em;
}
.backup-migrate-tables-checkboxes .form-item label {
.backup-migrate-tables-checkboxes .form-item {
width: 15em;
float: left;
overflow: hidden;
@@ -16,24 +21,50 @@
height: 1.75em;
margin: .25em .25em 0 0;
}
.backup-migrate-tables-checkboxes .form-item label.checked {
background-color: #eee;
}
.backup-migrate-tables-checkboxes .form-item label input {
margin-right: .25em;
margin-right: .5em;
}
div.backup-migrate-tables-checkboxes {
max-height: 40em;
height: 20em;
overflow: auto;
}
div.backup-migrate-description {
div.backup-migrate-tags,
div.backup-migrate-description,
div.backup-migrate-date {
font-size: smaller;
}
span.backup-migrate-label {
font-weight: bold;
}
table.backup-migrate-listing td {
vertical-align: top;
}
div.row-error {
color: #FF0000;
color: #ff0000;
font-weight: bold;
}
.backup-migrate-listing {
margin-bottom: 2em;
}
.backup-migrate-actions {
text-align: right;
}
html.js #backup-migrate-ui-manual-quick-backup-form fieldset.collapsed,
.backup-migrate-inline {
margin-bottom: 1em;
}
.backup-migrate-form-dependent {
padding-left: 2em;
padding-bottom: 1em;
}
.backup-migrate-form-dependent .form-item {
margin-top: 0;
}
.backup-migrate-footer-message {
margin-bottom: 1em;
}
@@ -1,17 +1,52 @@
name = Backup and Migrate
description = "Backup or migrate the Drupal Database quickly and without unnecessary data."
description = "Backup the Drupal database and files or migrate them to another environment."
core = 7.x
configure = admin/config/system/backup_migrate
files[] = backup_migrate.module
files[] = backup_migrate.install
; Require PHP 5.4 so that some slightly more advanced PHP logic can be used.
; This is for future usage; removing this will allow the module to continue
; working fine for now.
php = 5.4
; All of the class files used within the module.
files[] = includes/crud.inc
files[] = includes/destinations.inc
files[] = includes/destinations.browser.inc
files[] = includes/destinations.db.inc
files[] = includes/destinations.db.mysql.inc
files[] = includes/destinations.email.inc
files[] = includes/destinations.file.inc
files[] = includes/destinations.ftp.inc
files[] = includes/destinations.s3.inc
files[] = includes/files.inc
files[] = includes/filters.inc
files[] = includes/filters.backup_restore.inc
files[] = includes/filters.compression.inc
files[] = includes/filters.encryption.inc
files[] = includes/filters.statusnotify.inc
files[] = includes/filters.utils.inc
files[] = includes/locations.inc
files[] = includes/profiles.inc
files[] = includes/schedules.inc
files[] = includes/sources.inc
files[] = includes/sources.archivesource.inc
files[] = includes/sources.db.inc
files[] = includes/sources.db.mysql.inc
files[] = includes/sources.filesource.inc
configure = admin/config/system/backup_migrate
; Information added by drupal.org packaging script on 2013-04-10
version = "7.x-2.5"
; Test dependencies.
test_dependencies[] = ctools
; Test suite.
files[] = tests/BmTestBase.test
files[] = tests/BmTestBasics.test
files[] = tests/BmTestProfiles.test
files[] = tests/BmTestEmail.test
files[] = tests/BmTestCtools.test
files[] = tests/BmTestUpdate7310.test
; Information added by Drupal.org packaging script on 2020-07-15
version = "7.x-3.9"
core = "7.x"
project = "backup_migrate"
datestamp = "1365564017"
datestamp = "1594807678"
File diff suppressed because it is too large Load Diff
@@ -1,59 +1,126 @@
/**
* @file
* Custom JS for the Backup and Migrate module.
*/
(function ($) {
Drupal.backup_migrate = {
callbackURL : "",
autoAttach : function() {
if (Drupal.settings.backup_migrate !== undefined) {
if ($("#edit-save-settings").length && !$("#edit-save-settings").attr("checked")) {
// Disable input and hide its description.
// Set display none instead of using hide(), because hide() doesn't work when parent is hidden.
$('div.backup-migrate-save-options').css('display', 'none');
}
$("#edit-save-settings").bind("click", function() {
if (!$("#edit-save-settings").attr("checked")) {
$("div.backup-migrate-save-options").slideUp('slow');
}
else {
// Save unchecked; enable input.
$("div.backup-migrate-save-options").slideDown('slow');
}
});
'use strict';
$('select[multiple]').each(function() {
$(this).after(
$('<div class="description backup-migrate-checkbox-link"></div>').append(
$('<a href="javascript:null;"></a>').text(Drupal.settings.backup_migrate.checkboxLinkText).click(function() {
Drupal.backup_migrate.selectToCheckboxes($(this).parents('.form-item').find('select'));
Drupal.behaviors.backupMigrate = {
attach: function (context, settings) {
if (Drupal.settings.backup_migrate !== undefined) {
if (Drupal.settings.backup_migrate.dependents !== undefined) {
var key;
for (key in Drupal.settings.backup_migrate.dependents) {
info = Drupal.settings.backup_migrate.dependents[key];
var dependent = $('#edit-' + info['dependent']);
for (key in info['dependencies']) {
$('[name="' + key + '"]').each(function () {
var dependentval = info['dependencies'][key];
var dependency = $(this);
(function (dependent, dependency) {
var checkval = function (inval) {
// Do loose comparisons to support things like "true", "1",
// etc.
if (dependency.attr('type') === 'radio') {
var val = $('[name="' + dependency.attr('name') + '"]:checked').val();
return val == inval;
}
else if (dependency.attr('type') === 'checkbox') {
return dependency.is(':checked') && inval == dependency.val();
}
else {
return dependency.val() == inval;
}
return false;
};
if (!checkval(dependentval)) {
// Hide doesn't work inside collapsed fieldsets.
dependent.css('display', 'none');
}
dependency.bind('load change click keypress focus', function () {
if (checkval(dependentval)) {
dependent.slideDown();
}
else {
dependent.slideUp();
}
}).load();
})(dependent, dependency);
});
}
}
for (key in Drupal.settings.backup_migrate.destination_selectors) {
var info = Drupal.settings.backup_migrate.destination_selectors[key];
(function (info) {
var selector = $('#' + info['destination_selector']);
var copy = $('#' + info['copy'])
var copy_selector = $('#' + info['copy_destination_selector']);
var copy_selector_options = {};
// Store a copy of the secondary selector options.
copy_selector.find('optgroup').each(function () {
var label = $(this).attr('label');
copy_selector_options[label] = [];
$(this).find('option').each(function () {
copy_selector_options[label].push(this);
});
$(this).remove();
})
)
);
// Assign an action to the main selector to modify the secondary
// selector.
selector.each(function () {
$(this).bind('load change click keypress focus', function () {
var group = $(this).find('option[value=' + $(this).val() + ']').parents('optgroup').attr('label');
if (group) {
copy.parent().find('.backup-migrate-destination-copy-label').text(info['labels'][group]);
copy_selector.empty();
for (var key in copy_selector_options) {
if (key != group) {
copy_selector.append(copy_selector_options[key]);
}
}
}
}).load();
});
})(info);
}
// Add the convert to checkboxes functionality to all multiselects.
$('#backup-migrate-ui-manual-backup-form select[multiple], #backup-migrate-crud-edit-form select[multiple]').each(function () {
var self = this;
$(self).after(
$('<div class="description backup-migrate-checkbox-link"></div>').append(
$('<a>' + Drupal.settings.backup_migrate.checkboxLinkText + '</a>').click(function () {
var $select = $(self);
var $checkboxes = $('<div></div>').addClass('backup-migrate-tables-checkboxes');
$('option', $select).each(function (i) {
$checkboxes.append(
$('<div class="form-item"></div>').append(
$('<label class="option backup-migrate-table-select">' + this.value + '</label>').prepend(
$('<input type="checkbox" class="backup-migrate-tables-checkbox" name="' + $select.attr('name') + '"' + (this.selected ? 'checked="checked"' : '') + ' value="' + this.value + '"/>')
.bind('click change load', function () {
if (this.checked) {
$(this).parent().addClass('checked');
}
else {
$(this).parent().removeClass('checked');
}
}).load()
)
)
);
});
$select.parent().find('.backup-migrate-checkbox-link').remove();
$select.before($checkboxes);
$select.hide();
})
)
);
});
}
);
}
}
},
selectToCheckboxes : function($select) {
var field_id = $select.attr('id');
var $checkboxes = $('<div></div>').addClass('backup-migrate-tables-checkboxes');
$('option', $select).each(function(i) {
var self = this;
$box = $('<input type="checkbox" class="backup-migrate-tables-checkbox">').bind('change click', function() {
$select.find('option[value="'+self.value+'"]').attr('selected', this.checked);
if (this.checked) {
$(this).parent().addClass('checked');
}
else {
$(this).parent().removeClass('checked');
}
}).attr('checked', this.selected ? 'checked' : '');
$checkboxes.append($('<div class="form-item"></div>').append($('<label class="option backup-migrate-table-select">'+this.value+'</label>').prepend($box)));
});
$select.parent().find('.backup-migrate-checkbox-link').remove();
$select.before($checkboxes);
$select.hide();
}
}
$(document).ready(Drupal.backup_migrate.autoAttach);
})(jQuery);
File diff suppressed because it is too large Load Diff
@@ -1,13 +1,12 @@
<?php
/**
* @file
* Drush commands for backup and migrate.
*/
/**
* Implementation of hook_drush_command().
* Implements hook_drush_command().
*/
function backup_migrate_drush_command() {
$items['bam-backup'] = array(
@@ -15,9 +14,9 @@ function backup_migrate_drush_command() {
'description' => dt('Backup the site\'s database with Backup and Migrate.'),
'aliases' => array('bb'),
'examples' => array(
'drush bam-backup' => 'Backup the default databse to the manual backup directory using the default settings.',
'drush bam-backup db scheduled mysettings' => 'Backup the database to the scheduled directory using a settings profile called "mysettings"',
'drush bam-backup files' => 'Backup the files directory to the manual directory using the default settings. The Backup and Migrate Files module is required for files backups.',
'drush bam-backup' => 'Backup the default database to the manual backup directory using the default settings.',
'drush bam-backup db scheduled mysettings' => 'Backup the database to the scheduled directory using a settings profile called "mysettings"',
'drush bam-backup files' => 'Backup the files directory to the manual directory using the default settings.',
),
'arguments' => array(
'source' => "Optional. The id of the source (usually a database) to backup. Use 'drush bam-sources' to get a list of sources. Defaults to 'db'",
@@ -41,7 +40,6 @@ function backup_migrate_drush_command() {
'callback' => 'backup_migrate_drush_destinations',
'description' => dt('Get a list of available destinations.'),
);
$items['bam-sources'] = array(
'callback' => 'backup_migrate_drush_sources',
'description' => dt('Get a list of available sources.'),
@@ -54,25 +52,40 @@ function backup_migrate_drush_command() {
'callback' => 'backup_migrate_drush_destination_files',
'description' => dt('Get a list of previously created backup files.'),
'arguments' => array(
'destination' => "Required. The id of destination to list backups from. Use 'drush bam-destinations' to get a list of destinations.",
'destination' => "Optional. The id of destination to list backups from. Use 'drush bam-destinations' to get a list of destinations.",
),
);
$items['bam-schedule'] = array(
'callback' => 'backup_migrate_drush_schedule',
'description' => dt('Backup using a specific schedule.'),
'arguments' => array(
'schedule_id' => dt('The ID of the schedule to run.'),
),
);
$items['bam-schedules'] = array(
'callback' => 'backup_migrate_drush_schedules',
'description' => dt('Get a list of available schedules.'),
);
return $items;
}
/**
* Implementation of hook_drush_help().
* Implements hook_drush_help().
*/
function backup_migrate_drush_help($section) {
switch ($section) {
case 'drush:bam-backup':
return dt("Backup the site's database using default settings.");
case 'drush:bam-restore':
return dt('Restore the site\'s database with Backup and Migrate.');
case 'drush:bam-destinations':
return dt('Get a list of available destinations.');
case 'drush:bam-profiles':
return dt('Get a list of available settings profiles.');
case 'drush:bam-backups':
return dt('Get a list of previously created backup files.');
}
@@ -82,12 +95,14 @@ function backup_migrate_drush_help($section) {
* Backup the default database.
*/
function backup_migrate_drush_backup($source_id = 'db', $destination_id = 'manual', $profile_id = 'default') {
backup_migrate_include('profiles', 'destinations');
require_once dirname(__FILE__) . '/destinations.inc';
require_once dirname(__FILE__) . '/profiles.inc';
require_once dirname(__FILE__) . '/sources.inc';
// Set the message mode to logging.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!backup_migrate_get_destination($source_id)) {
if (!backup_migrate_get_source($source_id)) {
_backup_migrate_message("Could not find the source '@source'. Try using 'drush bam-sources' to get a list of available sources or use 'db' to backup the Drupal database.", array('@source' => $source_id), 'error');
return;
}
@@ -96,7 +111,7 @@ function backup_migrate_drush_backup($source_id = 'db', $destination_id = 'manua
return;
}
$settings = backup_migrate_get_profile($profile_id);
if(!$settings) {
if (!$settings) {
_backup_migrate_message("Could not find the profile '@profile'. Try using 'drush bam-profiles' to get a list of available profiles.", array('@profile' => $profile_id), 'error');
return;
}
@@ -108,20 +123,57 @@ function backup_migrate_drush_backup($source_id = 'db', $destination_id = 'manua
}
/**
* Restore to the default database.
* Backup using schedule.
*/
function backup_migrate_drush_restore($source_id = '', $destination_id = '', $file_id = '') {
drush_print(dt('Restoring will delete some or all of your data and cannot be undone. ALWAYS TEST YOUR BACKUPS ON A NON-PRODUCTION SERVER!'));
if (!drush_confirm(dt('Are you sure you want to restore the database?'))) {
return drush_user_abort();
}
backup_migrate_include('profiles', 'destinations');
function backup_migrate_drush_schedule($schedule_id = '') {
require_once dirname(__FILE__) . '/schedules.inc';
// Set the message mode to drush output.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!backup_migrate_get_destination($source_id)) {
if (!($schedule = backup_migrate_get_schedule($schedule_id))) {
_backup_migrate_message("Could not find the schedule '@schedule'. Try using 'drush bam-schedules' to get a list of available schedules.", array('@schedule' => $schedule_id), 'error');
return;
}
if (!$schedule->enabled) {
_backup_migrate_message("Nothing to do, the schedule '@schedule' is disabled.", array('@schedule' => $schedule_id), 'warning');
return;
}
_backup_migrate_message("Starting schedule '$schedule_id'...");
backup_migrate_schedule_run($schedule_id);
}
/**
* Get a list of available destinations.
*/
function backup_migrate_drush_schedules() {
require_once dirname(__FILE__) . '/schedules.inc';
$rows = array(array(dt('ID'), dt('Name')));
foreach (backup_migrate_get_schedules() as $schedule) {
$rows[] = array(
$schedule->get_id(),
$schedule->get_name(),
);
}
drush_print_table($rows, TRUE, array(32, 32));
}
/**
* Restore to the default database.
*/
function backup_migrate_drush_restore($source_id = '', $destination_id = '', $file_id = '') {
require_once dirname(__FILE__) . '/destinations.inc';
require_once dirname(__FILE__) . '/profiles.inc';
require_once dirname(__FILE__) . '/sources.inc';
// Set the message mode to drush output.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!backup_migrate_get_source($source_id)) {
_backup_migrate_message("Could not find the source '@source'. Try using 'drush bam-sources' to get a list of available sources or use 'db' to backup the Drupal database.", array('@source' => $source_id), 'error');
return;
}
@@ -129,14 +181,18 @@ function backup_migrate_drush_restore($source_id = '', $destination_id = '', $fi
_backup_migrate_message("Could not find the destination '@destination'. Try using 'drush bam-destinations' to get a list of available destinations.", array('@destination' => $destination_id), 'error');
return;
}
if (!$file_id || !$file = backup_migrate_destination_get_file($destination_id, $file_id)) {
elseif (!$file_id || !$file = backup_migrate_destination_get_file($destination_id, $file_id)) {
_backup_migrate_message("Could not find the file '@file'. Try using 'drush bam-backups @destination' to get a list of available backup files in this destination destinations.", array('@destination' => $destination_id, '@file' => $file_id), 'error');
return;
}
drush_print(dt('Restoring will delete some or all of your data and cannot be undone. ALWAYS TEST YOUR BACKUPS ON A NON-PRODUCTION SERVER!'));
if (!drush_confirm(dt('Are you sure you want to perform the restore?'))) {
return drush_user_abort();
}
_backup_migrate_message('Starting restore...');
$settings = array('source_id' => $source_id);
backup_migrate_perform_restore($destination_id, $file_id);
backup_migrate_perform_restore($destination_id, $file_id, $settings);
}
/**
@@ -150,21 +206,38 @@ function backup_migrate_drush_destinations() {
* Get a list of available sources.
*/
function backup_migrate_drush_sources() {
return _backup_migrate_drush_destinations('source');
return _backup_migrate_drush_sources('source');
}
/**
* Get a list of available destinations with the given op.
*/
function _backup_migrate_drush_destinations($op = NULL) {
backup_migrate_include('destinations');
require_once dirname(__FILE__) . '/destinations.inc';
$rows = array(array(dt('ID'), dt('Name'), dt('Operations')));
foreach (backup_migrate_get_destinations($op) as $destination) {
$rows[] = array(
$destination->get_id(),
$destination->get_name(),
implode (', ', $destination->ops()),
implode(', ', $destination->ops()),
);
}
drush_print_table($rows, TRUE, array(32, 32));
}
/**
* Get a list of available destinations with the given op.
*/
function _backup_migrate_drush_sources($op = NULL) {
require_once dirname(__FILE__) . '/sources.inc';
$rows = array(array(dt('ID'), dt('Name'), dt('Operations')));
foreach (backup_migrate_get_sources($op) as $destination) {
$rows[] = array(
$destination->get_id(),
$destination->get_name(),
implode(', ', $destination->ops()),
);
}
drush_print_table($rows, TRUE, array(32, 32));
@@ -174,7 +247,8 @@ function _backup_migrate_drush_destinations($op = NULL) {
* Get a list of available profiles.
*/
function backup_migrate_drush_profiles() {
backup_migrate_include('profiles');
require_once dirname(__FILE__) . '/profiles.inc';
$rows = array(array(dt('ID'), dt('Name')));
foreach (backup_migrate_get_profiles() as $profile) {
$rows[] = array(
@@ -186,46 +260,60 @@ function backup_migrate_drush_profiles() {
}
/**
* Get a list of files in a given destination
* Get a list of files in a given destination.
*/
function backup_migrate_drush_destination_files($destination_id = NULL) {
backup_migrate_include('destinations');
require_once dirname(__FILE__) . '/destinations.inc';
$destinations = array();
// Set the message mode to drush output.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!$destination_id) {
_backup_migrate_message("You must specify an existing destination. Try using 'drush bam-destinations' to get a list of available destinations.", array('@destination' => $destination_id), 'error');
return;
}
if (!$destination = backup_migrate_get_destination($destination_id)) {
if ($destination_id && !$destination = backup_migrate_get_destination($destination_id)) {
_backup_migrate_message("Could not find the destination '@destination'. Try using 'drush bam-destinations' to get a list of available destinations.", array('@destination' => $destination_id), 'error');
return;
}
$out = array(array(
dt('Filename'),
dt('Date'),
dt('Age'),
dt('Size'),
));
// Single destination required.
if ($destination) {
$destinations = array($destination);
}
// List all destinations.
else {
$destinations = backup_migrate_get_destinations('list files');
}
$files = $destination->list_files();
$i = 0;
foreach ((array)$files as $file) {
// Show only files that can be restored from.
if ($file->is_recognized_type()) {
// Load all the files.
$rows = $sort = array();
foreach ($destinations as $destination) {
$destination->file_cache_clear();
$dest_files = $destination->list_files();
foreach ($dest_files as $id => $file) {
$info = $file->info();
$out[] = array(
$rows[] = array(
check_plain($info['filename']),
$destination->get_id(),
format_date($info['filetime'], 'small'),
format_interval(time() - $info['filetime'], 1),
format_size($info['filesize']),
);
$sort[] = $info['filetime'];
}
}
if (count($out) > 1) {
drush_print_table($out, TRUE);
$headers = array(
array(
dt('Filename'),
dt('Destination'),
dt('Date'),
dt('Age'),
dt('Size'),
),
);
if (count($rows)) {
array_multisort($sort, SORT_DESC, $rows);
drush_print_table(array_merge($headers, $rows), TRUE);
}
else {
drush_print(dt('There are no backup files to display.'));
@@ -236,8 +324,15 @@ function backup_migrate_drush_destination_files($destination_id = NULL) {
* Send a message to the drush log.
*/
function _backup_migrate_message_drush($message, $replace, $type) {
// Use drush_log to display to the user.
drush_log(strip_tags(dt($message, $replace)), str_replace('status', 'notice', $type));
// If this is an error use drush_set_error to notify the end user and set the
// exit status.
if ($type == 'error') {
drush_set_error(strip_tags(dt($message, $replace)));
}
else {
// Use drush_log to display to the user.
drush_log(strip_tags(dt($message, $replace)), str_replace('status', 'notice', $type));
}
// Watchdog log the message as well for admins.
_backup_migrate_message_log($message, $replace, $type);
}
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,5 @@
<?php
/**
* @file
* Functions to handle the browser upload/download backup destination.
@@ -12,13 +11,15 @@
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_browser extends backup_migrate_destination {
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
*/
public function get_list_row() {
// Return none as this type should not be displayed.
return array();
}
}
/**
@@ -27,19 +28,26 @@ class backup_migrate_destination_browser extends backup_migrate_destination {
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_browser_upload extends backup_migrate_destination_browser {
var $supported_ops = array('restore');
function __construct() {
/**
* {@inheritdoc}
*/
public $supported_ops = array('restore');
/**
* Constructor.
*/
public function __construct() {
$params = array();
$params['name'] = "Upload";
$params['destination_id'] = 'upload';
$params['machine_name'] = 'upload';
parent::__construct($params);
}
/**
* File load destination callback.
*/
function load_file($file_id) {
backup_migrate_include('files');
public function load_file($file_id) {
if ($file = file_save_upload('backup_migrate_restore_upload')) {
$out = new backup_file(array('filepath' => $file->uri));
backup_migrate_temp_files_add($file->uri);
@@ -47,6 +55,7 @@ class backup_migrate_destination_browser_upload extends backup_migrate_destinati
}
return NULL;
}
}
/**
@@ -55,20 +64,35 @@ class backup_migrate_destination_browser_upload extends backup_migrate_destinati
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_browser_download extends backup_migrate_destination_browser {
var $supported_ops = array('manual backup');
function __construct() {
/**
* {@inheritdoc}
*/
public $supported_ops = array('manual backup');
/**
* Browser downloads must always be the last destination as they must end the
* current process when they are done.
*/
public $weight = 1000;
/**
* Constructor.
*/
public function __construct() {
$params = array();
$params['name'] = "Download";
$params['destination_id'] = 'download';
$params['machine_name'] = 'download';
parent::__construct($params);
}
/**
* File save destination callback.
*/
function save_file($file, $settings) {
backup_migrate_include('files');
public function save_file($file, $settings) {
require_once dirname(__FILE__) . '/files.inc';
$file->transfer();
}
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* Functions to handle the direct to database destination.
@@ -12,22 +11,24 @@
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_db extends backup_migrate_destination_remote {
var $supported_ops = array('scheduled backup', 'manual backup', 'configure', 'source');
var $db_target = 'default';
var $connection = null;
public $supported_ops = array('scheduled backup', 'manual backup', 'configure', 'source');
public $db_target = 'default';
public $connection = NULL;
function type_name() {
/**
*
*/
public function type_name() {
return t("Database");
}
/**
* Save the info by importing it into the database.
*/
function save_file($file, $settings) {
backup_migrate_include('files');
public function save_file($file, $settings) {
require_once dirname(__FILE__) . '/files.inc';
// Set the source_id to the destination_id in the settings since for a restore, the source_id is the
// Set the source_id to the destination_id in the settings since for a restore, the source_id is the
// database that gets restored to.
$settings->set_source($this->get_id());
@@ -40,10 +41,10 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Destination configuration callback.
*/
function edit_form() {
public function edit_form() {
$form = parent::edit_form();
$form['scheme']['#title'] = t('Database type');
// $form['scheme']['#options'] = array($GLOBALS['db_type'] => $GLOBALS['db_type']);
// $form['scheme']['#options'] = array($GLOBALS['db_type'] => $GLOBALS['db_type']);
$form['scheme']['#description'] = t('The type of the database. Drupal only supports one database type at a time, so this must be the same as the current database type.');
$form['path']['#title'] = t('Database name');
$form['path']['#description'] = t('The name of the database. The database must exist, it will not be created for you.');
@@ -54,7 +55,7 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Validate the configuration form. Make sure the db info is valid.
*/
function edit_form_validate($form, &$form_state) {
public function edit_form_validate($form, &$form_state) {
if (!preg_match('/[a-zA-Z0-9_\$]+/', $form_state['values']['path'])) {
form_set_error('path', t('The database name is not valid.'));
}
@@ -62,66 +63,74 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
}
/**
* Get the form for the settings for this destination.
* Get the default settings for this object.
*
* Return the default tables whose data can be ignored. These tables mostly contain
* info which can be easily reproducted (such as cache or search index)
* but also tables which can become quite bloated but are not necessarily extremely
* important to back up or migrate during development (such ass access log and watchdog)
* @return array
* The default tables whose data can be ignored. These tables mostly
* contain info which can be easily reproducted (such as cache or search
* index) but also tables which can become quite bloated but are not
* necessarily extremely important to back up or migrate during development
* (such as access log and watchdog).
*/
function backup_settings_default() {
$core = array(
'cache',
'cache_admin_menu',
'cache_browscap',
'cache_content',
'cache_filter',
'cache_calendar_ical',
'cache_location',
'cache_menu',
'cache_page',
'cache_reptag',
'cache_views',
'cache_views_data',
'cache_block',
'cache_update',
'cache_form',
'cache_bootstrap',
'cache_field',
'cache_image',
'cache_path',
'sessions',
'search_dataset',
'search_index',
'search_keywords_log',
'search_total',
'watchdog',
'accesslog',
'devel_queries',
'devel_times',
);
$nodata_tables = array_merge($core, module_invoke_all('devel_caches'));
return array(
'nodata_tables' => $nodata_tables,
'exclude_tables' => array(),
public function backup_settings_default() {
$all_tables = $this->_get_table_names();
// Basic modules that should be excluded.
$basic = array(
// Default core tables.
'accesslog',
'sessions',
'watchdog',
// Search module.
'search_dataset',
'search_index',
'search_keywords_log',
'search_total',
// Devel module.
'devel_queries',
'devel_times',
);
// Identify all cache tables.
$cache = array('cache');
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'cache_') === 0) {
$cache[] = $table_name;
}
}
// Simpletest can create a lot of tables that do not need to be backed up,
// but all of them start with the string 'simpletest' so they can be easily
// excluded.
$simpletest = array();
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'simpletest') === 0) {
$simpletest[] = $table_name;
}
}
return array(
'nodata_tables' => array_merge($basic, $cache, module_invoke_all('devel_caches')),
'exclude_tables' => $simpletest,
'utils_lock_tables' => FALSE,
);
);
}
/**
* Get the form for the backup settings for this destination.
*/
function backup_settings_form($settings) {
$tables = $this->get_table_names();
public function backup_settings_form($settings) {
$objects = $this->get_object_names();
$form['#description'] = t("You may omit specific tables, or specific table data from the backup file. Only omit data that you know you will not need such as cache data, or tables from other applications. Excluding tables can break your Drupal install, so <strong>do not change these settings unless you know what you're doing</strong>.");
$form['exclude_tables'] = array(
"#type" => "select",
"#multiple" => TRUE,
"#title" => t("Exclude the following tables altogether"),
"#options" => $tables,
"#options" => $objects,
"#default_value" => $settings['exclude_tables'],
"#description" => t("The selected tables will not be added to the backup file."),
);
$tables = $this->get_table_names();
$form['nodata_tables'] = array(
"#type" => "select",
"#multiple" => TRUE,
@@ -142,16 +151,15 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Backup from this source.
*/
function backup_to_file($file, $settings) {
public function backup_to_file($file, $settings) {
$file->push_type($this->get_file_type_id());
backup_migrate_filters_invoke_all('pre_backup', $this, $file, $settings);
//$this->lock_tables($settings);
// $this->lock_tables($settings);
// Switch to a different db if specified.
$success = $this->_backup_db_to_file($file, $settings);
//$this->unlock_tables($settings);
// $this->unlock_tables($settings);
backup_migrate_filters_invoke_all('post_backup', $this, $file, $settings, $success);
return $success ? $file : FALSE;
@@ -160,7 +168,7 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Restore to this source.
*/
function restore_from_file($file, &$settings) {
public function restore_from_file($file, &$settings) {
$num = 0;
$type = $this->get_file_type_id();
// Open the file using the file wrapper. Check that the dump is of the right type (allow .sql for legacy reasons).
@@ -182,7 +190,7 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Get the db connection for the specified db.
*/
function _get_db_connection() {
public function _get_db_connection() {
if (!$this->connection) {
$target = $key = '';
$parts = explode(':', $this->get_id());
@@ -195,13 +203,13 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
else {
// If the url is specified build it into a connection info array.
if (!empty($this->dest_url)) {
$info = array(
'driver' => empty($this->dest_url['scheme']) ? NULL : $this->dest_url['scheme'],
'host' => empty($this->dest_url['host']) ? NULL : $this->dest_url['host'],
'port' => empty($this->dest_url['port']) ? NULL : $this->dest_url['port'],
'username' => empty($this->dest_url['user']) ? NULL : $this->dest_url['user'],
'password' => empty($this->dest_url['pass']) ? NULL : $this->dest_url['pass'],
'database' => empty($this->dest_url['path']) ? NULL : $this->dest_url['path'],
$info = array(
'driver' => empty($this->dest_url['scheme']) ? NULL : $this->dest_url['scheme'],
'host' => empty($this->dest_url['host']) ? NULL : $this->dest_url['host'],
'port' => empty($this->dest_url['port']) ? NULL : $this->dest_url['port'],
'username' => empty($this->dest_url['user']) ? NULL : $this->dest_url['user'],
'password' => empty($this->dest_url['pass']) ? NULL : $this->dest_url['pass'],
'database' => empty($this->dest_url['path']) ? NULL : $this->dest_url['path'],
);
$key = uniqid('backup_migrate_tmp_');
$target = 'default';
@@ -222,21 +230,33 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Backup the databases to a file.
*/
function _backup_db_to_file($file, $settings) {
public function _backup_db_to_file($file, $settings) {
// Must be overridden.
}
/**
* Backup the databases to a file.
*/
function _restore_db_from_file($file, $settings) {
public function _restore_db_from_file($file, $settings) {
// Must be overridden.
}
/**
* Get a list of objects in the database.
*/
public function get_object_names() {
// Must be overridden.
$out = $this->_get_table_names();
if (method_exists($this, '_get_view_names')) {
$out += $this->_get_view_names();
}
return $out;
}
/**
* Get a list of tables in the database.
*/
function get_table_names() {
public function get_table_names() {
// Must be overridden.
$out = $this->_get_table_names();
return $out;
@@ -245,7 +265,7 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Get a list of tables in the database.
*/
function _get_table_names() {
public function _get_table_names() {
// Must be overridden.
return array();
}
@@ -253,12 +273,12 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Lock the database in anticipation of a backup.
*/
function lock_tables($settings) {
public function lock_tables($settings) {
if ($settings->filters['utils_lock_tables']) {
$tables = array();
foreach ($this->get_table_names() as $table) {
// There's no need to lock excluded or structure only tables because it doesn't matter if they change.
if (empty($settings->filters['exclude_tables']) || !in_array($table, (array)$settings->filters['exclude_tables'])) {
if (empty($settings->filters['exclude_tables']) || !in_array($table, (array) $settings->filters['exclude_tables'])) {
$tables[] = $table;
}
}
@@ -269,14 +289,14 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Lock the list of given tables in the database.
*/
function _lock_tables($tables) {
public function _lock_tables($tables) {
// Must be overridden.
}
/**
* Unlock any tables that have been locked.
*/
function unlock_tables($settings) {
public function unlock_tables($settings) {
if ($settings->filters['utils_lock_tables']) {
$this->_unlock_tables();
}
@@ -285,14 +305,15 @@ class backup_migrate_destination_db extends backup_migrate_destination_remote {
/**
* Unlock the list of given tables in the database.
*/
function _unlock_tables($tables) {
public function _unlock_tables($tables) {
// Must be overridden.
}
/**
* Get the file type for to backup this destination to.
*/
function get_file_type_id() {
public function get_file_type_id() {
return 'sql';
}
}
@@ -1,6 +1,10 @@
<?php
backup_migrate_include('destinations.db');
/**
* @file
*/
require_once dirname(__FILE__) . '/destinations.db.inc';
/**
* @file
@@ -12,16 +16,40 @@ backup_migrate_include('destinations.db');
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_db_mysql extends backup_migrate_destination_db {
function type_name() {
/**
* The table's data keyed by table name.
*
* @var array
*/
protected static $tableData = array();
/**
* The tables keyed by name.
*
* @var array
*/
protected static $tableNames = array();
/**
* The views keyed by name.
*
* @var array
*/
protected static $viewNames = array();
/**
*
*/
public function type_name() {
return t("MySQL Database");
}
/**
* Return a list of backup filetypes.
*/
function file_types() {
public function file_types() {
return array(
"sql" => array(
"extension" => "sql",
@@ -41,17 +69,27 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
/**
* Declare any mysql databases defined in the settings.php file as a possible destination.
*/
function destinations() {
public function destinations() {
$out = array();
global $databases;
foreach ((array)$databases as $db_key => $target) {
foreach ((array)$target as $tgt_key => $info) {
foreach ((array) $databases as $db_key => $target) {
foreach ((array) $target as $tgt_key => $info) {
// Only mysql/mysqli supported by this destination.
$key = $db_key . ':' . $tgt_key;
if ($info['driver'] === 'mysql') {
$url = $info['driver'] . '://' . $info['username'] . ':' . $info['password'] . '@' . $info['host'] . (isset($info['port']) ? ':' . $info['port'] : '') . '/' . $info['database'];
// Compile the database connection string.
$url = 'mysql://';
$url .= urlencode($info['username']) . ':' . urlencode($info['password']);
$url .= '@';
$url .= urlencode($info['host']);
if (!empty($info['port'])) {
$url .= ':' . $info['port'];
}
$url .= '/' . urlencode($info['database']);
if ($destination = backup_migrate_create_destination('mysql', array('url' => $url))) {
// Treat the default database differently because it is probably the only one available.
// Treat the default database differently because it is probably
// the only one available.
if ($key == 'default:default') {
$destination->set_id('db');
$destination->set_name(t('Default Database'));
@@ -60,8 +98,8 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
$destination->remove_op('manual backup');
}
else {
$destination->set_id('db:'. $key);
$destination->set_name($key .": ". $destination->get_display_location());
$destination->set_id('db:' . $key);
$destination->set_name($key . ": " . $destination->get_display_location());
}
$out[$destination->get_id()] = $destination;
}
@@ -74,35 +112,34 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
/**
* Get the file type for to backup this destination to.
*/
function get_file_type_id() {
public function get_file_type_id() {
return 'mysql';
}
/**
* Get the form for the backup settings for this destination.
*/
function backup_settings_form($settings) {
public function backup_settings_form($settings) {
$form = parent::backup_settings_form($settings);
$form['use_mysqldump'] = array(
"#type" => "checkbox",
"#title" => t("Use mysqldump command"),
"#default_value" => !empty($settings['use_mysqldump']),
"#description" => t("Use the mysqldump command line tool if available. This can be faster for large databases but will not work on all servers. EXPERIMENTAL"),
"#description" => t("Use the mysqldump command line tool if available. This can be faster for large databases but will not work on all servers. Also exporting SQL views is not really solid with this option. EXPERIMENTAL"),
);
return $form;
}
/**
* Backup the databases to a file.
*
* Returns a list of sql commands, one command per line.
* That makes it easier to import without loading the whole file into memory.
* The files are a little harder to read, but human-readability is not a priority
* The files are a little harder to read, but human-readability is not a priority.
*/
function _backup_db_to_file($file, $settings) {
public function _backup_db_to_file($file, $settings) {
if (!empty($settings->filters['use_mysqldump']) && $this->_backup_db_to_file_mysqldump($file, $settings)) {
return TRUE;
}
@@ -113,6 +150,8 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
if ($file->open(TRUE)) {
$file->write($this->_get_sql_file_header());
$alltables = $this->_get_tables();
$allviews = $this->_get_views();
foreach ($alltables as $table) {
if (_backup_migrate_check_timeout()) {
return FALSE;
@@ -125,6 +164,15 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
}
}
}
foreach ($allviews as $view) {
if (_backup_migrate_check_timeout()) {
return FALSE;
}
if ($view['name'] && !isset($exclude[$view['name']])) {
$file->write($this->_get_view_create_sql($view));
}
}
$file->write($this->_get_sql_file_footer());
$file->close();
return $lines;
@@ -134,16 +182,14 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
}
}
/**
* Backup the databases to a file using the mysqldump command.
*/
function _backup_db_to_file_mysqldump($file, $settings) {
public function _backup_db_to_file_mysqldump($file, $settings) {
$success = FALSE;
$nodata_tables = array();
$alltables = $this->_get_tables();
$command = 'mysqldump --result-file=%file --opt -Q --host=%host --port=%port --user=%user --password=%pass %db';
$args = array(
'%file' => $file->filepath(),
@@ -155,17 +201,19 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
);
// Ignore the excluded and no-data tables.
$db = $this->dest_url['path'];
if (!empty($settings->filters['exclude_tables'])) {
$db = $this->dest_url['path'];
foreach ((array)$settings->filters['exclude_tables'] as $table) {
foreach ((array) $settings->filters['exclude_tables'] as $table) {
if (isset($alltables[$table])) {
$command .= ' --ignore-table='. $db .'.'. $table;
$command .= ' --ignore-table=' . $db . '.' . $table;
}
}
foreach ((array)$settings->filters['nodata_tables'] as $table) {
}
if (!empty($settings->filters['nodata_tables'])) {
foreach ((array) $settings->filters['nodata_tables'] as $table) {
if (isset($alltables[$table])) {
$nodata_tables[] = $table;
$command .= ' --ignore-table='. $db .'.'. $table;
$command .= ' --ignore-table=' . $db . '.' . $table;
}
}
}
@@ -183,10 +231,19 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
/**
* Backup the databases to a file.
*/
function _restore_db_from_file($file, $settings) {
public function _restore_db_from_file($file, $settings) {
$num = 0;
if ($file->open() && $conn = $this->_get_db_connection()) {
// Optionally drop all existing tables.
if (!empty($settings->filters['utils_drop_all_tables'])) {
$all_tables = $this->_get_tables();
$table_names = array_map('backup_migrate_array_name_value', $all_tables);
$table_list = join(', ', $table_names);
$stmt = $conn->prepare("DROP TABLE IF EXISTS $table_list;\n");
$stmt->execute();
}
// Read one line at a time and run the query.
while ($line = $this->_read_sql_command_from_file($file)) {
if (_backup_migrate_check_timeout()) {
@@ -209,17 +266,16 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
return $num;
}
/**
* Read a multiline sql command from a file.
*
* Supports the formatting created by mysqldump, but won't handle multiline comments.
*/
function _read_sql_command_from_file($file) {
public function _read_sql_command_from_file($file) {
$out = '';
while ($line = $file->read()) {
$first2 = substr($line, 0, 2);
$first3 = substr($line, 0, 2);
$first3 = substr($line, 0, 3);
// Ignore single line comments. This function doesn't support multiline comments or inline comments.
if ($first2 != '--' && ($first2 != '/*' || $first3 == '/*!')) {
@@ -236,46 +292,90 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
/**
* Get a list of tables in the database.
*/
function _get_table_names() {
$out = array();
foreach ($this->_get_tables() as $table) {
$out[$table['name']] = $table['name'];
public function _get_table_names() {
if (empty(static::$tableNames)) {
static::$tableNames = $this->query("SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE'")
->fetchAllKeyed(0, 0);
}
return $out;
return static::$tableNames;
}
/**
* Get a list of views in the database.
*/
public function _get_view_names() {
if (empty(static::$viewNames)) {
static::$viewNames = $this->query("SHOW FULL TABLES WHERE Table_Type = 'VIEW'")
->fetchAllKeyed(0, 0);
}
return static::$viewNames;
}
/**
* Lock the list of given tables in the database.
*/
function _lock_tables($tables) {
public function _lock_tables($tables) {
if ($tables) {
$tables_escaped = array();
foreach ($tables as $table) {
$tables_escaped[] = '`'. db_escape_table($table) .'` WRITE';
$tables_escaped[] = '`' . db_escape_table($table) . '` WRITE';
}
$this->query('LOCK TABLES '. implode(', ', $tables_escaped));
$this->query('LOCK TABLES ' . implode(', ', $tables_escaped));
}
}
/**
* Unlock all tables in the database.
*/
function _unlock_tables($settings) {
public function _unlock_tables($settings) {
$this->query('UNLOCK TABLES');
}
/**
* Get a list of table and view data in the db.
*/
protected function get_table_data() {
if (empty(static::$tableData)) {
$tables = $this->query('SHOW TABLE STATUS')
->fetchAll(PDO::FETCH_ASSOC);
foreach ($tables as $table) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the
// default query behavior was changed.
// See: http://drupal.org/node/1171866
$table = array_change_key_case($table);
static::$tableData[$table['name']] = $table;
}
}
return static::$tableData;
}
/**
* Get a list of tables in the db.
*/
function _get_tables() {
public function _get_tables() {
$out = array();
// get auto_increment values and names of all tables
$tables = $this->query("show table status", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($tables as $table) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
// See: http://drupal.org/node/1171866
$table = array_change_key_case($table);
$out[$table['name']] = $table;
foreach ($this->get_table_data() as $table) {
if (!empty($table['engine'])) {
$out[$table['name']] = $table;
}
}
return $out;
}
/**
* Get a list of views in the db.
*/
public function _get_views() {
$out = array();
foreach ($this->get_table_data() as $table) {
if (empty($table['engine'])) {
$out[$table['name']] = $table;
}
}
return $out;
}
@@ -283,86 +383,124 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
/**
* Get the sql for the structure of the given table.
*/
function _get_table_structure_sql($table) {
public function _get_table_structure_sql($table) {
$out = "";
$result = $this->query("SHOW CREATE TABLE `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
$result = $this->query("SHOW CREATE TABLE `" . $table['name'] . "`", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $create) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
// See: http://drupal.org/node/1171866
$create = array_change_key_case($create);
$out .= "DROP TABLE IF EXISTS `". $table['name'] ."`;\n";
$out .= "DROP TABLE IF EXISTS `" . $table['name'] . "`;\n";
// Remove newlines and convert " to ` because PDO seems to convert those for some reason.
$out .= strtr($create['create table'], array("\n" => ' ', '"' => '`'));
if ($table['auto_increment']) {
$out .= " AUTO_INCREMENT=". $table['auto_increment'];
$out .= " AUTO_INCREMENT=" . $table['auto_increment'];
}
$out .= ";\n";
}
return $out;
}
/**
* Get the sql to insert the data for a given table
*/
function _dump_table_data_sql_to_file($file, $table) {
$rows_per_line = variable_get('backup_migrate_data_rows_per_line', 30);
$bytes_per_line = variable_get('backup_migrate_data_bytes_per_line', 2000);
$lines = 0;
$data = $this->query("SELECT * FROM `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
$rows = $bytes = 0;
// Escape backslashes, PHP code, special chars
/**
* Get the sql for the structure of the given table.
*/
public function _get_view_create_sql($view) {
$out = "";
// Switch SQL mode to get rid of "CREATE ALGORITHM..." what requires more permissions + troubles with the DEFINER user.
$sql_mode = $this->query("SELECT @@SESSION.sql_mode")->fetchField();
$this->query("SET sql_mode = 'ANSI'");
$result = $this->query("SHOW CREATE VIEW `" . $view['name'] . "`", array(), array('fetch' => PDO::FETCH_ASSOC));
$this->query("SET SQL_mode = :mode", array(':mode' => $sql_mode));
foreach ($result as $create) {
$out .= "DROP VIEW IF EXISTS `" . $view['name'] . "`;\n";
$out .= "SET sql_mode = 'ANSI';\n";
$out .= strtr($create['Create View'], "\n", " ") . ";\n";
$out .= "SET sql_mode = '$sql_mode';\n";
}
return $out;
}
/**
* Get the sql to insert the data for a given table.
*/
public function _dump_table_data_sql_to_file($file, $table) {
$rows_per_query = variable_get('backup_migrate_data_rows_per_query', BACKUP_MIGRATE_DATA_ROWS_PER_QUERY);
$rows_per_line = variable_get('backup_migrate_data_rows_per_line', BACKUP_MIGRATE_DATA_ROWS_PER_LINE);
$bytes_per_line = variable_get('backup_migrate_data_bytes_per_line', BACKUP_MIGRATE_DATA_BYTES_PER_LINE);
if (variable_get('backup_migrate_verbose')) {
_backup_migrate_message('Table: %table', array('%table' => $table['name']), 'success');
}
// Escape backslashes, PHP code, special chars.
$search = array('\\', "'", "\x00", "\x0a", "\x0d", "\x1a");
$replace = array('\\\\', "''", '\0', '\n', '\r', '\Z');
$line = array();
foreach ($data as $row) {
// DB Escape the values.
$items = array();
foreach ($row as $key => $value) {
$items[] = is_null($value) ? "null" : "'". str_replace($search, $replace, $value) ."'";
$lines = 0;
$from = 0;
$args = array('fetch' => PDO::FETCH_ASSOC);
while ($data = $this->query("SELECT * FROM `" . $table['name'] . "`", array(), $args, $from, $rows_per_query)) {
if ($data->rowCount() == 0) {
break;
}
// If there is a row to be added.
if ($items) {
// Start a new line if we need to.
if ($rows == 0) {
$file->write("INSERT INTO `". $table['name'] ."` VALUES ");
$bytes = $rows = 0;
$rows = $bytes = 0;
$line = array();
foreach ($data as $row) {
$from++;
// DB Escape the values.
$items = array();
foreach ($row as $key => $value) {
$items[] = is_null($value) ? "null" : "'" . str_replace($search, $replace, $value) . "'";
}
// Otherwise add a comma to end the previous entry.
else {
$file->write(",");
}
// Write the data itself.
$sql = implode(',', $items);
$file->write('('. $sql .')');
$bytes += strlen($sql);
$rows++;
// Finish the last line if we've added enough items
if ($rows >= $rows_per_line || $bytes >= $bytes_per_line) {
$file->write(";\n");
$lines++;
$bytes = $rows = 0;
// If there is a row to be added.
if ($items) {
// Start a new line if we need to.
if ($rows == 0) {
$file->write("INSERT INTO `" . $table['name'] . "` VALUES ");
$bytes = $rows = 0;
}
// Otherwise add a comma to end the previous entry.
else {
$file->write(",");
}
// Write the data itself.
$sql = implode(',', $items);
$file->write('(' . $sql . ')');
$bytes += strlen($sql);
$rows++;
// Finish the last line if we've added enough items.
if ($rows >= $rows_per_line || $bytes >= $bytes_per_line) {
$file->write(";\n");
$lines++;
$bytes = $rows = 0;
}
}
}
// Finish any unfinished insert statements.
if ($rows > 0) {
$file->write(";\n");
$lines++;
}
}
// Finish any unfinished insert statements.
if ($rows > 0) {
$file->write(";\n");
$lines++;
if (variable_get('backup_migrate_verbose')) {
_backup_migrate_message('Peak memory usage: %mem', array('%mem' => backup_migrate_get_peak_memory_usage() . 'MB'), 'success');
}
return $lines;
}
/**
* Get the db connection for the specified db.
*/
function _get_db_connection() {
public function _get_db_connection() {
if (!$this->connection) {
$this->connection = parent::_get_db_connection();
// Set the sql mode because the default is ANSI,TRADITIONAL which is not aware of collation or storage engine.
@@ -372,11 +510,34 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
}
/**
* Run a db query on this destination's db.
* Run a query on this destination's database using Drupal's MySQL engine.
*
* @param string $query
* The query string.
* @param array $args
* Arguments for the query.
* @param array $options
* Options to pass to the query.
* @param int|null $from
* The starting point for the query; when passed will perform a queryRange()
* method instead of a regular query().
* @param int|null $count
* The number of records to obtain from this query. Will be ignored if the
* $from argument is empty.
*
* @see DatabaseConnection_mysql::query()
* @see DatabaseConnection_mysql::queryRange()
*/
function query($query, $args = array(), $options = array()) {
public function query($query, array $args = array(), array $options = array(), $from = NULL, $count = NULL) {
if ($conn = $this->_get_db_connection()) {
return $conn->query($query, $args, $options);
// If no $from is passed in, just do a basic query.
if (is_null($from)) {
return $conn->query($query, $args, $options);
}
// The $from variable was passed in, so do a ranged query.
else {
return $conn->queryRange($query, $from, $count, $args, $options);
}
}
}
@@ -384,7 +545,7 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
* The header for the top of the sql dump file. These commands set the connection
* character encoding to help prevent encoding conversion issues.
*/
function _get_sql_file_header() {
public function _get_sql_file_header() {
return "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
@@ -392,17 +553,17 @@ class backup_migrate_destination_db_mysql extends backup_migrate_destination_db
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;
SET NAMES utf8;
SET NAMES utf8mb4;
";
}
/**
* The footer of the sql dump file.
*/
function _get_sql_file_footer() {
public function _get_sql_file_footer() {
return "
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
@@ -411,5 +572,5 @@ SET NAMES utf8;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
";
}
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* Functions to handle the email backup destination.
@@ -12,14 +11,14 @@
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_email extends backup_migrate_destination {
var $supported_ops = array('scheduled backup', 'manual backup', 'configure');
public $supported_ops = array('scheduled backup', 'manual backup', 'remote backup', 'configure');
/**
* Save to (ie. email the file) to the email destination.
*/
function save_file($file, $settings) {
public function save_file($file, $settings) {
$size = filesize($file->filepath());
$max = variable_get('backup_migrate_max_email_size', 20971520);
$max = variable_get('backup_migrate_max_email_size', BACKUP_MIGRATE_MAX_EMAIL_SIZE);
if ($size > $max) {
_backup_migrate_message('Could not email the file @file because it is @size and Backup and Migrate only supports emailing files smaller than @max.', array('@file' => $file->filename(), '@size' => format_size($size), '@max' => format_size($max)), 'error');
return FALSE;
@@ -34,14 +33,14 @@ class backup_migrate_destination_email extends backup_migrate_destination {
/**
* Get the form for the settings for this filter.
*/
function edit_form() {
public function edit_form() {
$form = parent::edit_form();
$form['location'] = array(
"#type" => "textfield",
"#title" => t("Email Address"),
"#default_value" => $this->get_location(),
"#required" => TRUE,
"#description" => t('Enter the email address to send the backup files to. Make sure the email sever can handle large file attachments'),
"#description" => t('Enter the email address to send the backup files to. Make sure the email server can handle large file attachments'),
);
return $form;
}
@@ -49,11 +48,12 @@ class backup_migrate_destination_email extends backup_migrate_destination {
/**
* Validate the configuration form. Make sure the email address is valid.
*/
function settings_form_validate($values) {
public function settings_form_validate($values) {
if (!valid_email_address($values['location'])) {
form_set_error('[location]', t('The e-mail address %mail is not valid.', array('%mail' => $form_state['values']['location'])));
}
}
}
/**
@@ -72,69 +72,106 @@ class backup_migrate_destination_email extends backup_migrate_destination {
* filename and "filename" which is just the filename.
*/
function _backup_migrate_destination_email_mail_backup($attachment, $to) {
// Send mail
// Send mail.
$attach = fread(fopen($attachment->path, "r"), filesize($attachment->path));
$mail = new mime_mail();
$mail->from = variable_get('site_mail', ini_get('sendmail_from'));
$mail->headers = 'Errors-To: [EMAIL='. $mail->from .']'. $mail->from .'[/EMAIL]';
$mail->headers = 'Errors-To: [EMAIL=' . $mail->from . ']' . $mail->from . '[/EMAIL]';
$mail->to = $to;
$mail->subject = t('Database backup from !site: !file', array('!site' => variable_get('site_name', 'drupal'), '!file' => $attachment->filename));
$mail->body = t('Database backup attached.') ."\n\n";
$mail->body = t('Database backup attached.') . "\n\n";
$mail->add_attachment("$attach", $attachment->filename, "Content-Transfer-Encoding: base64 /9j/4AAQSkZJRgABAgEASABIAAD/7QT+UGhvdG9zaG", NULL, TRUE);
$mail->add_attachment($attach, $attachment->filename, "application/octet-stream");
$mail->send();
}
/**
*
*/
class mime_mail {
var $parts;
var $to;
var $from;
var $headers;
var $subject;
var $body;
public $parts;
public $to;
public $from;
public $headers;
public $subject;
public $body;
function mime_mail() {
/**
*
*/
public function __construct() {
$this->parts = array();
$this->to = "";
$this->from = "";
$this->headers = "";
$this->headers = array();
$this->subject = "";
$this->body = "";
}
function add_attachment($message, $name = "", $ctype = "application/octet-stream", $encode = NULL, $attach = FALSE) {
/**
*
*/
public function add_attachment($message, $name, $ctype) {
$this->parts[] = array(
"ctype" => $ctype,
"message" => $message,
"encode" => $encode,
"name" => $name,
"attach" => $attach,
"ctype" => $ctype,
);
}
function build_message($part) {
$message = $part["message"];
$message = chunk_split(base64_encode($message));
$encoding = "base64";
$disposition = $part['attach'] ? "Content-Disposition: attachment; filename=$part[name]\n" : '';
return "Content-Type: ". $part["ctype"] . ($part["name"] ? "; name = \"". $part["name"] ."\"" : "") ."\nContent-Transfer-Encoding: $encoding\n$disposition\n$message\n";
}
/**
*
*/
public function build_message($part) {
$crlf = "\r\n";
// See RFC 2184.
$continuation = $crlf . ' ';
$name = $part['name'];
$len = strlen($name);
function build_multipart() {
$boundary = "b". md5(uniqid(time()));
$multipart = "Content-Type: multipart/mixed; boundary = $boundary\n\nThis is a MIME encoded message.\n\n--$boundary";
for ($i = sizeof($this->parts) - 1; $i >= 0; $i--) {
$multipart .= "\n". $this->build_message($this->parts[$i]) ."--$boundary";
// RFC 5322 recommends lines of no longer than 78 chars, which in
// this case comes down to filenames of no longer than 64 chars.
if ($len > 64) {
// We want to preserve the time stamp and extension and such.
$head = substr($name, 0, 28);
$tail = substr($name, ($len - 32));
$name = $head . '___' . $tail;
}
return $multipart .= "--\n";
$message = chunk_split(base64_encode($part["message"]), 70, $crlf);
$disposition = $name ? "Content-Disposition: attachment; {$continuation}filename=\"$name\"$crlf" : "";
return "Content-Type: " . $part["ctype"] . ($name ? ";{$continuation}name=\"$name\"" : "") .
"{$crlf}Content-Transfer-Encoding: base64$crlf$disposition$crlf$message";
}
function send() {
$mime = "";
if (!empty($this->from)) $mime .= "From: ". $this->from ."\n";
if (!empty($this->headers)) $mime .= $this->headers ."\n";
if (!empty($this->body)) $this->add_attachment($this->body, "", "text/plain");
$mime .= "MIME-Version: 1.0\n". $this->build_multipart();
mail($this->to, $this->subject, "", $mime);
/**
*
*/
public function build_multipart($boundary) {
$multipart = "This is a MIME encoded message.\r\n\r\n--$boundary";
for ($i = count($this->parts) - 1; $i >= 0; $i--) {
$multipart .= "\r\n" . $this->build_message($this->parts[$i]) . "--$boundary";
}
return $multipart . "--\r\n";
}
/**
*
*/
public function send() {
$headers = array();
if (!empty($this->body)) {
$this->add_attachment($this->body, "", "text/plain");
}
$headers['MIME-Version'] = "1.0";
$boundary = "b" . md5(uniqid(time()));
$headers['Content-Type'] = "multipart/mixed; boundary=\"$boundary\"";
$message = $this->build_multipart($boundary);
$params = array();
$params['body'] = $message;
$params['headers'] = $headers;
$params['subject'] = $this->subject;
drupal_mail('backup_migrate', 'destination_mail', trim($this->to), '', $params, $this->from);
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* A destination type for saving locally to the server.
@@ -11,79 +10,104 @@
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_files extends backup_migrate_destination {
var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
public $supported_ops = array('scheduled backup', 'manual backup', 'local backup', 'restore', 'list files', 'configure', 'delete');
function type_name() {
/**
*
*/
public function type_name() {
return t("Server Directory");
}
/**
* Get the file location.
*/
function get_realpath() {
return drupal_realpath($this->get_location());
public function get_realpath() {
if ($realpath = drupal_realpath($this->get_location())) {
return $realpath;
}
return $this->get_location();
}
/**
* File save destination callback.
*/
function _save_file($file, $settings) {
if ($dir = $this->get_location()) {
if ($dir = $this->check_dir($dir)) {
$filepath = rtrim($dir, "/") ."/". $file->filename();
if (file_unmanaged_move($file->filepath(), $filepath)) {
// chmod, chown and chgrp the file if needed.
if ($chmod = $this->settings('chmod')) {
if (!@drupal_chmod($filepath, octdec($chmod))) {
_backup_migrate_message('Unable to set the file mode for: @file', array('@file' => $filepath), 'error');
}
}
if ($chgrp = $this->settings('chgrp')) {
if (!@chgrp($filepath, $chgrp)) {
_backup_migrate_message('Unable to set the file group for: @file', array('@file' => $filepath), 'error');
}
}
return $file;
}
else {
_backup_migrate_message('Unable to save the file to the directory: @dir', array('@dir' => $dir), 'error');
public function _save_file($file, $settings) {
if ($this->confirm_destination() && $dir = $this->get_location()) {
$filepath = rtrim($dir, "/") . "/" . $file->filename();
// Allow files to be overwritten by the filesystem.
$replace_method = $settings->append_timestamp == 2 ? FILE_EXISTS_REPLACE : FILE_EXISTS_RENAME;
// Copy the file if there are multiple destinations.
if (count($settings->get_destinations()) > 1) {
file_unmanaged_copy($file->filepath(), $filepath, $replace_method);
}
// Otherwise we can move it and save a delete.
else {
file_unmanaged_move($file->filepath(), $filepath, $replace_method);
}
// chmod, chown and chgrp the file if needed.
if ($chmod = $this->settings('chmod')) {
if (!@drupal_chmod($filepath, octdec($chmod))) {
_backup_migrate_message('Unable to set the file mode for: @file', array('@file' => $filepath), 'error');
}
}
if ($chgrp = $this->settings('chgrp')) {
if (!@chgrp($filepath, $chgrp)) {
_backup_migrate_message('Unable to set the file group for: @file', array('@file' => $filepath), 'error');
}
}
return $file;
}
}
/**
* Determine if we can read the given file.
*/
function can_read_file($file_id) {
public function can_read_file($file_id) {
return $this->op('restore') && is_readable($this->get_filepath($file_id));
}
/**
* File load destination callback.
*/
function load_file($file_id) {
public function load_file($file_id) {
$filepath = $this->get_filepath($file_id);
if (file_exists($filepath)) {
backup_migrate_include('files');
require_once dirname(__FILE__) . '/files.inc';
return new backup_file(array('filepath' => $filepath));
}
}
/**
* Get the file object for the given file.
*/
public function get_file($file_id) {
$files = $this->list_files();
if (isset($files[$file_id])) {
isset($files[$file_id]);
}
return NULL;
}
/**
* File list destination callback.
*/
function _list_files() {
public function _list_files() {
$files = array();
if ($dir = $this->get_realpath()) {
if ($handle = @opendir($dir)) {
backup_migrate_include('files');
require_once dirname(__FILE__) . '/files.inc';
while (FALSE !== ($file = readdir($handle))) {
$filepath = $dir ."/". $file;
$files[$file] = new backup_file(array('filepath' => $filepath));
if (substr($file, 0, 1) !== '.') {
$filepath = $dir . "/" . $file;
$files[$file] = new backup_file(array('filepath' => $filepath));
}
}
}
}
@@ -93,7 +117,7 @@ class backup_migrate_destination_files extends backup_migrate_destination {
/**
* File delete destination callback.
*/
function _delete_file($file_id) {
public function _delete_file($file_id) {
$filepath = $this->get_filepath($file_id);
file_unmanaged_delete($filepath);
}
@@ -101,9 +125,9 @@ class backup_migrate_destination_files extends backup_migrate_destination {
/**
* Get the filepath from the given file id.
*/
function get_filepath($file_id) {
public function get_filepath($file_id) {
if ($dir = $this->get_realpath()) {
$filepath = rtrim($dir, '/') .'/'. $file_id;
$filepath = rtrim($dir, '/') . '/' . $file_id;
return $filepath;
}
return FALSE;
@@ -112,7 +136,7 @@ class backup_migrate_destination_files extends backup_migrate_destination {
/**
* Get the form for the settings for the files destination.
*/
function edit_form() {
public function edit_form() {
$form = parent::edit_form();
$form['location'] = array(
"#type" => "textfield",
@@ -152,7 +176,7 @@ class backup_migrate_destination_files extends backup_migrate_destination {
/**
* Validate the form for the settings for the files destination.
*/
function edit_form_validate($form, &$form_state) {
public function edit_form_validate($form, &$form_state) {
$values = $form_state['values'];
if (isset($values['settings']['chmod']) && !empty($values['settings']['chmod']) && !preg_match('/0?[0-7]{3}/', $values['settings']['chmod'])) {
form_set_error('chmod', t('You must enter a valid chmod octal value (e.g. 644 or 0644) in the change mode field, or leave it blank.'));
@@ -163,7 +187,7 @@ class backup_migrate_destination_files extends backup_migrate_destination {
/**
* Submit the form for the settings for the files destination.
*/
function edit_form_submit($form, &$form_state) {
public function edit_form_submit($form, &$form_state) {
// Add a 0 to the start of a 3 digit file mode to make it proper PHP encoded octal.
if (strlen($form_state['values']['settings']['chmod']) == 3) {
$form_state['values']['settings']['chmod'] = '0' . $form_state['values']['settings']['chmod'];
@@ -171,15 +195,26 @@ class backup_migrate_destination_files extends backup_migrate_destination {
parent::edit_form_submit($form, $form_state);
}
/**
* Check that a destination is valid.
*/
public function confirm_destination() {
if ($dir = $this->get_location()) {
return $this->check_dir($dir);
}
return FALSE;
}
/**
* Prepare the destination directory for the backups.
*/
function check_dir($directory) {
public function check_dir($directory) {
if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
// Unable to create destination directory.
_backup_migrate_message("Unable to create or write to the save directory '%directory'. Please check the file permissions that directory and try again.", array('%directory' => $directory), "error");
_backup_migrate_message("Unable to create or write to the save directory '%directory'. Please check the file permissions of that directory and try again.", array('%directory' => $directory), "error");
return FALSE;
}
// If the destination directory is within the webroot, then secure it as best we can.
if ($this->dir_in_webroot($directory)) {
$directory = $this->check_web_dir($directory);
@@ -191,45 +226,60 @@ class backup_migrate_destination_files extends backup_migrate_destination {
/**
* Check that a web accessible directory has been properly secured, othewise attempt to secure it.
*/
function check_web_dir($directory) {
file_create_htaccess($directory, TRUE);
// Check the user agent to make sure we're not responding to a request from drupal itself.
// That should prevent infinite loops which could be caused by poormanscron in some circumstances.
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Drupal') !== FALSE) {
return FALSE;
public function check_web_dir($directory) {
// Check if the file has already been tested.
if (is_file($directory . '/tested.txt')) {
return $directory;
}
else {
file_create_htaccess($directory, TRUE);
// Check to see if the destination is publicly accessible
$test_contents = "this file should not be publicly accessible";
// Create the the text.txt file if it's not already there.
if (!is_file($directory .'/test.txt') || file_get_contents($directory .'/test.txt') != $test_contents) {
if ($fp = fopen($directory .'/test.txt', 'w')) {
@fputs($fp, $test_contents);
fclose($fp);
}
else {
$message = t("Security notice: Backup and Migrate was unable to write a test text file to the destination directory %directory, and is therefore unable to check the security of the backup destination. Backups to the server will be disabled until the destination becomes writable and secure.", array('%directory' => $directory));
drupal_set_message($message, "error");
// Check the user agent to make sure we're not responding to a request from drupal itself.
// That should prevent infinite loops which could be caused by poormanscron in some circumstances.
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Drupal') !== FALSE) {
return FALSE;
}
}
// Attempt to read the test file via http. This may fail for other reasons,
// so it's not a bullet-proof check.
if ($this->test_file_readable_remotely($directory .'/test.txt', $test_contents)) {
$message = t("Security notice: Backup and Migrate will not save backup files to the server because the destination directory is publicly accessible. If you want to save files to the server, please secure the '%directory' directory", array('%directory' => $directory));
drupal_set_message($message, "error");
return FALSE;
// Check to see if the destination is publicly accessible.
$test_contents = "this file should not be publicly accessible";
// Create the the text.txt file if it's not already there.
if (!is_file($directory . '/test.txt') || file_get_contents($directory . '/test.txt') != $test_contents) {
if ($fp = fopen($directory . '/test.txt', 'w')) {
@fputs($fp, $test_contents);
fclose($fp);
}
else {
$message = t("Security notice: Backup and Migrate was unable to write a test text file to the destination directory %directory, and is therefore unable to check the security of the backup destination. Backups to the server will be disabled until the destination becomes writable and secure.", array('%directory' => $directory));
drupal_set_message($message, "error");
return FALSE;
}
}
// Attempt to read the test file via http. This may fail for other
// reasons, so it's not a bullet-proof check.
if ($this->test_file_readable_remotely($directory . '/test.txt', $test_contents)) {
$message = t("Security notice: Backup and Migrate will not save backup files to the server because the destination directory is publicly accessible. If you want to save files to the server, please secure the '%directory' directory", array('%directory' => $directory));
drupal_set_message($message, "error");
unlink($directory . '/test.txt');
return FALSE;
}
// Directory tested OK, so we mark it as tested.
if ($fp = fopen($directory . '/tested.txt', 'w')) {
$contents = t('The presence of this file indicates that this directory has been tested as safe to use as a destination for Backup and Migrate. If you change the permissions of this directory or change your web server settings, please delete this file so that the directory can be checked again.');
@fputs($fp, $contents);
fclose($fp);
}
return $directory;
}
return $directory;
}
/**
* Check if the given directory is within the webroot and is therefore web accessible.
*/
function dir_in_webroot($directory) {
if (strpos(drupal_realpath($directory), realpath($_SERVER['DOCUMENT_ROOT'])) !== FALSE) {
public function dir_in_webroot($directory) {
$real_dir = drupal_realpath($directory);
$real_root = drupal_realpath(DRUPAL_ROOT);
if ($real_dir == $real_root || strpos($real_dir, $real_root . '/') === 0) {
return TRUE;
}
return FALSE;
@@ -238,35 +288,52 @@ class backup_migrate_destination_files extends backup_migrate_destination {
/**
* Check if a file can be read remotely via http.
*/
function test_file_readable_remotely($path, $contents) {
$url = file_create_url($path);
// TODO: Proper checking for absolute paths.
$result = drupal_http_request($url);
if (!empty($result->data) && strpos($result->data, $contents) !== FALSE) {
return TRUE;
public function test_file_readable_remotely($directory, $contents) {
$real_dir = drupal_realpath($directory);
$real_root = drupal_realpath(DRUPAL_ROOT);
if ($real_dir && $real_root) {
// Get the root relative path.
$path = substr($real_dir, strlen($real_root));
$url = $GLOBALS['base_url'] . str_replace('\\', '/', $path);
$result = drupal_http_request($url);
if (!empty($result->data) && strpos($result->data, $contents) !== FALSE) {
return TRUE;
}
}
return FALSE;
}
}
/**
* The manual files directory.
*/
class backup_migrate_destination_files_manual extends backup_migrate_destination_files {
var $supported_ops = array('manual backup', 'restore', 'list files', 'configure', 'delete');
function __construct($params = array()) {
public $supported_ops = array('manual backup', 'restore', 'list files', 'configure', 'delete');
/**
*
*/
public function __construct($params = array()) {
$dir = 'private://backup_migrate/manual';
parent::__construct($params + array('location' => $dir, 'name' => t('Manual Backups Directory')));
}
}
/**
* The scheduled files directory.
*/
class backup_migrate_destination_files_scheduled extends backup_migrate_destination_files {
var $supported_ops = array('scheduled backup', 'restore', 'list files', 'configure', 'delete');
function __construct($params = array()) {
public $supported_ops = array('scheduled backup', 'restore', 'list files', 'configure', 'delete');
/**
*
*/
public function __construct($params = array()) {
$dir = 'private://backup_migrate/scheduled';
parent::__construct($params + array('location' => $dir, 'name' => t('Scheduled Backups Directory')));
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* Functions to handle the FTP backup destination.
@@ -12,13 +11,13 @@
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_ftp extends backup_migrate_destination_remote {
var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
var $ftp = NULL;
public $supported_ops = array('scheduled backup', 'manual backup', 'remote backup', 'restore', 'list files', 'configure', 'delete');
public $ftp = NULL;
/**
* Save to the ftp destination.
*/
function _save_file($file, $settings) {
public function _save_file($file, $settings) {
$ftp = $this->ftp_object();
if (drupal_ftp_file_to_ftp($file->filepath(), $file->filename(), '.', $ftp)) {
return $file;
@@ -29,8 +28,9 @@ class backup_migrate_destination_ftp extends backup_migrate_destination_remote {
/**
* Load from the ftp destination.
*/
function load_file($file_id) {
backup_migrate_include('files');
public function load_file($file_id) {
require_once dirname(__FILE__) . '/files.inc';
$file = new backup_file(array('filename' => $file_id));
$this->ftp_object();
if (drupal_ftp_ftp_to_file($file->filepath(), $file_id, '.', $this->ftp)) {
@@ -42,16 +42,20 @@ class backup_migrate_destination_ftp extends backup_migrate_destination_remote {
/**
* Delete from the ftp destination.
*/
function _delete_file($file_id) {
public function _delete_file($file_id) {
$this->ftp_object();
drupal_ftp_delete_file($file_id, $this->ftp);
}
function _list_files() {
backup_migrate_include('files');
/**
*
*/
public function _list_files() {
require_once dirname(__FILE__) . '/files.inc';
$files = array();
$this->ftp_object();
$ftp_files = drupal_ftp_file_list('.', $this->ftp);
$ftp_files = (array) drupal_ftp_file_list('.', $this->ftp);
foreach ($ftp_files as $file) {
$files[$file['filename']] = new backup_file($file);
}
@@ -61,7 +65,7 @@ class backup_migrate_destination_ftp extends backup_migrate_destination_remote {
/**
* Get the form for the settings for this filter.
*/
function edit_form() {
public function edit_form() {
$form = parent::edit_form();
$form['scheme']['#type'] = 'value';
$form['scheme']['#value'] = 'ftp';
@@ -80,15 +84,24 @@ class backup_migrate_destination_ftp extends backup_migrate_destination_remote {
return $form;
}
function set_pasv($value) {
$this->settings['pasv'] = (bool)$value;
/**
*
*/
public function set_pasv($value) {
$this->settings['pasv'] = (bool) $value;
}
function get_pasv() {
/**
*
*/
public function get_pasv() {
return isset($this->settings['pasv']) ? $this->settings['pasv'] : FALSE;
}
function ftp_object() {
/**
*
*/
public function ftp_object() {
if (!$this->ftp) {
$this->dest_url['port'] = empty($this->dest_url['port']) ? '21' : $this->dest_url['port'];
$this->dest_url['pasv'] = $this->get_pasv();
@@ -96,19 +109,18 @@ class backup_migrate_destination_ftp extends backup_migrate_destination_remote {
}
return $this->ftp;
}
}
// The FTP code below was taken from the ftp module by Aaron Winborn.
// Inspired by http://www.devarticles.com/c/a/PHP/My-FTP-Wrapper-Class-for-PHP/
// It's been drupalized, however, and most of the bugs from that example have been fixed.
// - winborn 2007-06-22 - 2007-06-28
// - winborn 2007-06-22 - 2007-06-28.
define('DRUPAL_FTP_FT_DIRECTORY', 0);
define('DRUPAL_FTP_FT_FILE', 1);
/**
* creates a new ftp object. if any elements of ftp_map are missing, they'll be filled with the server defaults.
* Creates a new ftp object. if any elements of ftp_map are missing, they'll be filled with the server defaults.
*/
function drupal_ftp_ftp_object($server, $port, $user, $pass, $dir, $pasv) {
$ftp = new stdClass();
@@ -124,17 +136,17 @@ function drupal_ftp_ftp_object($server, $port, $user, $pass, $dir, $pasv) {
}
/**
* The drupal_ftp_connect function
* The drupal_ftp_connect function
* This function connects to an FTP server and attempts to change into the directory specified by
* the fourth parameter, $directory.
*/
function drupal_ftp_connect(&$ftp) {
if (is_NULL($ftp)) {
if (is_null($ftp)) {
$ftp = drupal_ftp_ftp_object();
}
if (empty($ftp->__conn) && !drupal_ftp_connected($ftp)) {
// Attempt to connect to the remote server
if (!$ftp->__conn && !drupal_ftp_connected($ftp)) {
// Attempt to connect to the remote server.
$ftp->__conn = @ftp_connect($ftp->__server, $ftp->__port);
if (!$ftp->__conn) {
@@ -142,7 +154,7 @@ function drupal_ftp_connect(&$ftp) {
return FALSE;
}
// Attempt to login to the remote server
// Attempt to login to the remote server.
$ftp->__login = @ftp_login($ftp->__conn, $ftp->__user, $ftp->__password);
if (!$ftp->__login) {
@@ -150,7 +162,7 @@ function drupal_ftp_connect(&$ftp) {
return FALSE;
}
// Attempt to change into the working directory
// Attempt to change into the working directory.
$chdir = @ftp_chdir($ftp->__conn, $ftp->__directory);
if (!$chdir) {
@@ -158,7 +170,7 @@ function drupal_ftp_connect(&$ftp) {
return FALSE;
}
// Set PASV - if needed
// Set PASV - if needed.
if ($ftp->__pasv) {
$pasv = @ftp_pasv($ftp->__conn, TRUE);
if (!$pasv) {
@@ -168,7 +180,7 @@ function drupal_ftp_connect(&$ftp) {
}
}
// Everything worked OK, return TRUE
// Everything worked OK, return TRUE.
return TRUE;
}
@@ -179,38 +191,36 @@ function drupal_ftp_connect(&$ftp) {
*/
function drupal_ftp_connected(&$ftp) {
// Attempt to call the ftp_systype to see if the connect
// to the FTP server is still alive and kicking
if (is_NULL($ftp)) {
// to the FTP server is still alive and kicking.
if (is_null($ftp)) {
$ftp = drupal_ftp_ftp_object();
return FALSE;
}
if (!@ftp_systype($ftp->__conn)) {
// The connection is dead
// The connection is dead.
return FALSE;
}
else {
// The connection is still alive
// The connection is still alive.
return TRUE;
}
}
/**
* This function tries to retrieve the contents of a file from the FTP server.
* This function tries to retrieve the contents of a file from the FTP server.
* Firstly it changes into the $directory directory, and then attempts to download the file $filename.
* The file is saved locally and its contents are returned to the caller of the function.
*/
function drupal_ftp_ftp_to_file($file, $filename, $directory, &$ftp) {
// Change into the remote directory and retrieve the content
// of a file. Once retrieve, return this value to the caller
// of a file. Once retrieve, return this value to the caller.
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
// We are now connected, so let's retrieve the file contents.
// Firstly, we change into the directory
// Firstly, we change into the directory.
$chdir = @ftp_chdir($ftp->__conn, $directory);
if (!$chdir) {
@@ -218,7 +228,7 @@ function drupal_ftp_ftp_to_file($file, $filename, $directory, &$ftp) {
return FALSE;
}
// We have changed into the directory, let's attempt to get the file
// We have changed into the directory, let's attempt to get the file.
$fp = @fopen($file, 'wb');
$get_file = @ftp_fget($ftp->__conn, $fp, $filename, FTP_BINARY);
fclose($fp);
@@ -229,7 +239,7 @@ function drupal_ftp_ftp_to_file($file, $filename, $directory, &$ftp) {
_backup_migrate_message('FTP Error: Unable to download file: @filename from @directory', array('@filename' => $filename, '@directory' => $directory), 'error');
return FALSE;
}
return TRUE;
}
@@ -242,15 +252,15 @@ function drupal_ftp_file_to_ftp($file, $ftp_filename, $ftp_directory, &$ftp) {
}
if ($source = drupal_realpath($file)) {
// Now we can try to write to the remote file
$complete_filename = $ftp_directory .'/'. $ftp_filename;
// Now we can try to write to the remote file.
$complete_filename = $ftp_directory . '/' . $ftp_filename;
$put_file = @ftp_put($ftp->__conn, $complete_filename, $source, FTP_BINARY);
if (!$put_file) {
_backup_migrate_message('FTP Error: Couldn\'t write to @complete_filename when trying to save file on the ftp server.', array('@complete_filename' => $complete_filename), 'error');
return FALSE;
}
// Everything worked OK
// Everything worked OK.
return TRUE;
}
else {
@@ -260,19 +270,18 @@ function drupal_ftp_file_to_ftp($file, $ftp_filename, $ftp_directory, &$ftp) {
}
/**
* The drupal_ftp_change_directory Function
* The drupal_ftp_change_directory Function
* This function simply changes into the $directory folder on the FTP server.
* If a connection or permission error occurs then _backup_migrate_message() will contain the error message.
*/
function drupal_ftp_change_directory($directory, &$ftp) {
// Switch to another directory on the web server. If we don't
// have permissions then an error will occur
// have permissions then an error will occur.
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
// Try and change into another directory
// Try and change into another directory.
$chdir = ftp_chdir($ftp->__conn, $directory);
if (!$chdir) {
@@ -280,21 +289,20 @@ function drupal_ftp_change_directory($directory, &$ftp) {
return FALSE;
}
else {
// Changing directories worked OK
// Changing directories worked OK.
return TRUE;
}
}
/**
* The drupal_ftp_file_list Function
* The drupal_ftp_file_list Function
* This function will change into the $directory folder and get a list of files and directories contained in that folder.
* This function still needs a lot of work, but should work in most cases.
*/
function drupal_ftp_file_list($directory, &$ftp) {
// This function will attempt to change into the specified
// directory and retrieve a list of files as an associative
// array. This list will include file name, size and date last modified
// array. This list will include file name, size and date last modified.
$file_array = array();
// Can we switch to the desired directory?
@@ -306,14 +314,14 @@ function drupal_ftp_file_list($directory, &$ftp) {
// This is slower than parsing the raw return values, but it is faster.
$file_list = ftp_nlist($ftp->__conn, $directory);
// Save the list of files
// Save the list of files.
if (@is_array($file_list)) {
// Interate through the array
// Interate through the array.
foreach ($file_list as $file) {
$file_array[] = array(
'filename' => $file,
'filesize' => ftp_size($ftp->__conn, $directory ."/". $file),
'filetime' => ftp_mdtm($ftp->__conn, $directory ."/". $file),
'filesize' => ftp_size($ftp->__conn, $directory . "/" . $file),
'filetime' => ftp_mdtm($ftp->__conn, $directory . "/" . $file),
);
}
}
@@ -322,13 +330,12 @@ function drupal_ftp_file_list($directory, &$ftp) {
}
/**
* The drupal_ftp_create_directory Function
* The drupal_ftp_create_directory Function
* This function tries to make a new directory called $folder_name on the FTP server.
* If it can create the folder, then the folder is given appropriate rights with the CHMOD command.
*/
function drupal_ftp_create_directory($folder_name, &$ftp) {
// Makes a new folder on the web server via FTP
// Makes a new folder on the web server via FTP.
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
@@ -337,7 +344,7 @@ function drupal_ftp_create_directory($folder_name, &$ftp) {
if ($create_result == TRUE) {
// Can we change the files permissions?
$exec_result = @ftp_site($ftp->__conn, 'chmod 0777 '. $folder_name .'/');
$exec_result = @ftp_site($ftp->__conn, 'chmod 0777 ' . $folder_name . '/');
if ($exec_result == TRUE) {
return TRUE;
@@ -354,11 +361,11 @@ function drupal_ftp_create_directory($folder_name, &$ftp) {
}
/**
* The drupal_ftp_delete_file Function
* The drupal_ftp_delete_file Function
* This function attempts to delete a file called $filename from the FTP server.
*/
function drupal_ftp_delete_file($filename, &$ftp) {
// Remove the specified file from the FTP server
// Remove the specified file from the FTP server.
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
@@ -366,18 +373,18 @@ function drupal_ftp_delete_file($filename, &$ftp) {
$delete_result = @ftp_delete($ftp->__conn, $filename);
if ($delete_result == TRUE) {
// The file/folder was renamed successfully
// The file/folder was renamed successfully.
return TRUE;
}
else {
// Couldn't delete the selected file
// Couldn't delete the selected file.
_backup_migrate_message('FTP Error: Couldn\'t delete the selected file: @filename', array('@filename' => $filename), 'error');
return FALSE;
}
}
/**
* The drupal_ftp_delete_folder Function
* The drupal_ftp_delete_folder Function
* This function was one of the hardest to write. It recursively deletes all files and folders from a directory called $folder_name.
*/
function drupal_ftp_delete_folder($folder_name, &$ftp) {
@@ -394,18 +401,18 @@ function drupal_ftp_delete_folder($folder_name, &$ftp) {
$file_counter = 0;
$content = @ftp_nlist($ftp->__conn, ".");
for ($i = 0; $i < sizeof($content); $i++) {
for ($i = 0; $i < count($content); $i++) {
// If we can change into this then it's a directory.
// If not, it's a file
// If not, it's a file.
if ($content[$i] != "." && $content[$i] != "..") {
if (@ftp_chdir($ftp->__conn, $content[$i])) {
// We have a directory
// We have a directory.
$directories[] = $content[$i];
$dir_counter++;
@ftp_cdup($ftp->__conn);
}
else {
// We have a file
// We have a file.
$files[] = $content[$i];
$file_counter++;
}
@@ -417,10 +424,10 @@ function drupal_ftp_delete_folder($folder_name, &$ftp) {
}
for ($j = 0; $j < $dir_counter; $j++) {
if ($directories[$j] != "." OR $directories[$j] != "..") {
if ($directories[$j] != "." or $directories[$j] != "..") {
$location = ftp_pwd($ftp->__conn);
drupal_ftp_delete_folder($directories[$j], $ftp);
@ftp_cdup ($ftp->__conn);
@ftp_cdup($ftp->__conn);
@ftp_rmdir($ftp->__conn, $directories[$j]);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,5 @@
<?php
/**
* @file
* Functions to handle the s3 backup destination.
@@ -12,15 +11,14 @@
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
var $s3 = NULL;
var $cache_files = TRUE;
public $supported_ops = array('scheduled backup', 'manual backup', 'remote backup', 'restore', 'list files', 'configure', 'delete');
public $s3 = NULL;
public $cache_files = TRUE;
/**
* Save to to the s3 destination.
*/
function _save_file($file, $settings) {
public function _save_file($file, $settings) {
if ($s3 = $this->s3_object()) {
$path = $file->filename();
if ($s3->putObject($s3->inputFile($file->filepath(), FALSE), $this->get_bucket(), $this->remote_path($file->filename()), S3::ACL_PRIVATE)) {
@@ -33,8 +31,9 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
/**
* Load from the s3 destination.
*/
function load_file($file_id) {
backup_migrate_include('files');
public function load_file($file_id) {
require_once dirname(__FILE__) . '/files.inc';
$file = new backup_file(array('filename' => $file_id));
if ($s3 = $this->s3_object()) {
$data = $s3->getObject($this->get_bucket(), $this->remote_path($file_id), $file->filepath());
@@ -42,13 +41,14 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
return $file;
}
}
return NULL;
}
/**
* Delete from the s3 destination.
*/
function _delete_file($file_id) {
public function _delete_file($file_id) {
if ($s3 = $this->s3_object()) {
$s3->deleteObject($this->get_bucket(), $this->remote_path($file_id));
}
@@ -57,12 +57,13 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
/**
* List all files from the s3 destination.
*/
function _list_files() {
backup_migrate_include('files');
public function _list_files() {
require_once dirname(__FILE__) . '/files.inc';
$files = array();
if ($s3 = $this->s3_object()) {
$s3_files = $s3->getBucket($this->get_bucket(), $this->get_subdir());
foreach ((array)$s3_files as $id => $file) {
foreach ((array) $s3_files as $id => $file) {
$info = array(
'filename' => $this->local_path($file['name']),
'filesize' => $file['size'],
@@ -71,21 +72,21 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
$files[$info['filename']] = new backup_file($info);
}
}
return $files;
}
/**
* Get the form for the settings for this filter.
*/
function edit_form() {
public function edit_form() {
// Check for the library.
$this->s3_object();
$form = parent::edit_form();
$form['scheme']['#type'] = 'value';
$form['scheme']['#value'] = 'https';
$form['host']['#type'] = 'value';
$form['host']['#value'] = 's3.amazonaws.com';
$form['host']['#default_value'] = @$this->dest_url['host'] ? $this->dest_url['host'] : 's3.amazonaws.com';
$form['path']['#title'] = 'S3 Bucket';
$form['path']['#default_value'] = $this->get_bucket();
@@ -98,7 +99,7 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
'#type' => 'textfield',
'#title' => t('Subdirectory'),
'#default_value' => $this->get_subdir(),
'#weight' => 25
'#weight' => 25,
);
$form['settings']['#weight'] = 50;
@@ -108,11 +109,10 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
/**
* Submit the form for the settings for the s3 destination.
*/
function edit_form_submit($form, &$form_state) {
public function edit_form_submit($form, &$form_state) {
// Append the subdir onto the path.
if (!empty($form_state['values']['subdir'])) {
$form_state['values']['path'] .= '/'. trim($form_state['values']['subdir'], '/');
$form_state['values']['path'] .= '/' . trim($form_state['values']['subdir'], '/');
}
parent::edit_form_submit($form, $form_state);
}
@@ -120,9 +120,9 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
/**
* Generate a filepath with the correct prefix.
*/
function remote_path($path) {
public function remote_path($path) {
if ($subdir = $this->get_subdir()) {
$path = $subdir .'/'. $path;
$path = $subdir . '/' . $path;
}
return $path;
}
@@ -130,9 +130,9 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
/**
* Generate a filepath with the correct prefix.
*/
function local_path($path) {
public function local_path($path) {
if ($subdir = $this->get_subdir()) {
$path = str_replace($subdir .'/', '', $path);
$path = str_replace($subdir . '/', '', $path);
}
return $path;
}
@@ -140,7 +140,7 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
/**
* Get the bucket which is the first part of the path.
*/
function get_bucket() {
public function get_bucket() {
$parts = explode('/', @$this->dest_url['path']);
return $parts[0];
}
@@ -148,7 +148,7 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
/**
* Get the bucket which is the first part of the path.
*/
function get_subdir() {
public function get_subdir() {
// Support the older style of subdir saving.
if ($subdir = $this->settings('subdir')) {
return $subdir;
@@ -158,7 +158,10 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
return implode('/', array_filter($parts));
}
function s3_object() {
/**
*
*/
public function s3_object() {
// Try to use libraries module if available to find the path.
if (function_exists('libraries_get_path')) {
$library_paths[] = libraries_get_path('s3-php5-curl');
@@ -169,11 +172,16 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
$library_paths[] = drupal_get_path('module', 'backup_migrate') . '/includes/s3-php5-curl';
$library_paths[] = drupal_get_path('module', 'backup_migrate') . '/includes';
foreach($library_paths as $path) {
foreach ($library_paths as $path) {
if (file_exists($path . '/S3.php')) {
require_once $path . '/S3.php';
if (!$this->s3 && !empty($this->dest_url['user'])) {
$this->s3 = new S3($this->dest_url['user'], $this->dest_url['pass']);
// The hostname can be overridden.
$host = 's3.amazonaws.com';
if (isset($this->dest_url['host'])) {
$host = $this->dest_url['host'];
}
$this->s3 = new S3($this->dest_url['user'], $this->dest_url['pass'], FALSE, $host);
}
return $this->s3;
}
@@ -181,4 +189,5 @@ class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
drupal_set_message(t('Due to drupal.org code hosting policies, the S3 library needed to use an S3 destination is no longer distributed with this module. You must download the library from !link and place it in one of these locations: %locations.', array('%locations' => implode(', ', $library_paths), '!link' => l('http://undesigned.org.za/2007/10/22/amazon-s3-php-class', 'http://undesigned.org.za/2007/10/22/amazon-s3-php-class'))), 'error', FALSE);
return NULL;
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* General file handling code for Backup and Migrate.
@@ -12,7 +11,7 @@ define('BACKUP_MIGRATE_FILENAME_MAXLENGTH', 255);
* Add a file to the temporary files list for deletion when we're done.
*/
function backup_migrate_temp_files_add($filepath = NULL) {
static $files = array();
$files = &drupal_static('backup_migrate_temp_files_add', array());
if (!$filepath) {
return $files;
}
@@ -25,41 +24,104 @@ function backup_migrate_temp_files_add($filepath = NULL) {
* Delete all temporary files.
*/
function _backup_migrate_temp_files_delete() {
// Delete the temp files created during this run.
foreach (backup_migrate_temp_files_add() as $file) {
$file = drupal_realpath($file);
if (file_exists($file) && is_writable($file)) {
if (variable_get('backup_migrate_cleanup_temp_files', BACKUP_MIGRATE_CLEANUP_TEMP_FILES)) {
// Delete the temp files created during this run.
foreach (backup_migrate_temp_files_add() as $file) {
if (file_exists($file) && is_writable($file)) {
_backup_migrate_temp_files_delete_file($file);
}
}
// Delete temp files abandoned for 6 or more hours.
$dir = file_directory_temp();
$expire = time() - variable_get('backup_migrate_cleanup_time', BACKUP_MIGRATE_CLEANUP_TIME);
if (file_exists($dir) && is_dir($dir) && is_readable($dir) && $handle = opendir($dir)) {
while (FALSE !== ($file = @readdir($handle))) {
// Delete 'backup_migrate_' files in the temp directory that are older than the expire time.
// We should only attempt to delete writable files to prevent errors in shared environments.
// This could still cause issues in shared environments with poorly configured file permissions.
if (strpos($file, 'backup_migrate_') === 0 && is_writable("$dir/$file") && @filectime("$dir/$file") < $expire) {
_backup_migrate_temp_files_delete_file("$dir/$file");
}
}
closedir($handle);
}
}
}
/**
* Delete a temporary file or folder.
*/
function _backup_migrate_temp_files_delete_file($file) {
if (file_exists($file) && (is_writable($file) || is_link($file))) {
if (!is_link($file) && is_dir($file) && is_readable($file) && $handle = opendir($file)) {
$dir = $file;
while (FALSE !== ($file = @readdir($handle))) {
if ($file != '..' && $file != '.') {
_backup_migrate_temp_files_delete_file("$dir/$file");
}
}
closedir($handle);
rmdir($dir);
}
else {
unlink($file);
}
}
}
// Delete temp files abandoned for 6 or more hours.
$dir = file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath();
$expire = time() - variable_get('backup_migrate_cleanup_time', 21600);
if (file_exists($dir) && is_dir($dir) && is_readable($dir) && $handle = opendir($dir)) {
while (FALSE !== ($file = @readdir($handle))) {
// Delete 'backup_migrate_' files in the temp directory that are older than the expire time.
// We should only attempt to delete writable files to prevent errors in shared environments.
// This could still cause issues in shared environments with poorly configured file permissions.
if (strpos($file, 'backup_migrate_') === 0 && is_writable("$dir/$file") && @filectime("$dir/$file") < $expire) {
unlink("$dir/$file");
/**
* Move files recursively.
*/
function _backup_migrate_move_files($from, $to) {
if (is_readable($from)) {
if (is_dir($from) && is_readable($from) && $handle = opendir($from)) {
if (!file_exists($to)) {
mkdir($to);
}
while (FALSE !== ($file = @readdir($handle))) {
if ($file != '..' && $file != '.') {
_backup_migrate_move_files("$from/$file", "$to/$file");
}
}
closedir($handle);
}
else {
rename($from, $to);
}
closedir($handle);
}
return FALSE;
}
/**
* Create a temporary directory.
*/
function backup_migrate_temp_directory() {
$tmp = realpath(file_directory_temp());
// Check the writability of the temp directory.
if (!is_writable(realpath(file_directory_temp()))) {
_backup_migrate_message('Your temporary directory %tmp is not writable. Backup and migrate needs to be able to create temporary files.', array('%tmp' => $tmp), 'error');
}
// Use a full path so that the files can be deleted during the shutdown function if needed.
$file = $tmp . '/' . uniqid('backup_migrate_');
mkdir($file);
backup_migrate_temp_files_add($file);
return $file;
}
/**
* Return a list of backup filetypes.
*/
function _backup_migrate_filetypes() {
backup_migrate_include('filters');
require_once dirname(__FILE__) . '/filters.inc';
$out = backup_migrate_filters_file_types();
foreach ($out as $key => $info) {
$out[$key]['id'] = empty($info['id']) ? $key : $info['id'];
}
return $out;
}
@@ -78,19 +140,33 @@ function _backup_migrate_filename_append_prepare($filename, $append_str) {
/**
* Construct a filename using token and some cleaning.
*/
function _backup_migrate_construct_filename($filename, $timestamp='') {
if (module_exists('token')) {
function _backup_migrate_construct_filename($settings) {
// Get the raw filename from the settings.
$filename = $settings->filename;
// Replace any tokens.
if (module_exists('token') && function_exists('token_replace')) {
$filename = token_replace($filename);
}
$filename = preg_replace("/[^a-zA-Z0-9\.\-_]/", "", $filename);
// Remove illegal characters.
$filename = _backup_migrate_clean_filename($filename);
// Generate a timestamp if needed.
$timestamp = '';
if ($settings->append_timestamp == 1 && $settings->timestamp_format) {
$timestamp = format_date(time(), 'custom', $settings->timestamp_format);
}
// Trim to length if needed to allow the timestamp to fit into the max filename.
$filename = _backup_migrate_filename_append_prepare($filename, $timestamp);
$filename .= '-' . $timestamp;
$filename = trim($filename, '-');
// If there is no filename, then just call it untitled.
if (drupal_strlen($filename) == 0) {
$filename = 'untitled';
}
return $filename;
}
@@ -102,11 +178,20 @@ function _backup_migrate_default_filename() {
return '[site:name]';
}
else {
// Cleaning the string isn't strictly necessary but it looks better in the settings field.
return variable_get('site_name', 'backup_migrate');
// Cleaning the string isn't strictly necessary but it looks better in the
// settings field.
return _backup_migrate_clean_filename(variable_get('site_name', "backup_migrate"));
}
}
/**
* Clean up a filename to remove unsafe characters.
*/
function _backup_migrate_clean_filename($filename) {
$filename = preg_replace("/[^a-zA-Z0-9\.\-_]/", "", $filename);
return $filename;
}
/**
* An output buffer callback which simply throws away the buffer instead of sending it to the browser.
*/
@@ -114,22 +199,21 @@ function _backup_migrate_file_dispose_buffer($buffer) {
return "";
}
/**
* A backup file which allows for saving to and reading from the server.
*/
class backup_file {
var $file_info = array();
var $type = array();
var $ext = array();
var $path = "";
var $name = "";
var $handle = NULL;
public $file_info = array();
public $type = array();
public $ext = array();
public $path = "";
public $name = "";
public $handle = NULL;
/**
* Construct a file object given a file path, or create a temp file for writing.
*/
function backup_file($params = array()) {
public function __construct($params = array()) {
if (isset($params['filepath']) && file_exists($params['filepath'])) {
$this->set_filepath($params['filepath']);
}
@@ -142,7 +226,7 @@ class backup_file {
/**
* Get the file_id if the file has been saved to a destination.
*/
function file_id() {
public function file_id() {
// The default file_id is the filename. Destinations can override the file_id if needed.
return isset($this->file_info['file_id']) ? $this->file_info['file_id'] : $this->filename();
}
@@ -150,27 +234,33 @@ class backup_file {
/**
* Get the current filepath.
*/
function filepath() {
return drupal_realpath($this->path);
public function filepath() {
if ($filepath = drupal_realpath($this->path)) {
return $filepath;
}
return $this->path;
}
/**
* Get the final filename.
*/
function filename($name = NULL) {
public function filename($name = NULL) {
if ($name) {
$this->name = $name;
}
return $this->name .'.'. $this->extension();
$extension_str = '.' . $this->extension();
$this->name = _backup_migrate_filename_append_prepare($this->name, $extension_str);
return $this->name . $extension_str;
}
/**
* Set the current filepath.
*/
function set_filepath($path) {
public function set_filepath($path) {
$this->path = $path;
$params = array(
'filename' => basename($path),
'file_id' => basename($path),
);
if (file_exists($path)) {
$params['filesize'] = filesize($path);
@@ -182,67 +272,93 @@ class backup_file {
/**
* Get one or all pieces of info for the file.
*/
function info($key = NULL) {
public function info($key = NULL) {
if ($key) {
return @$this->file_info[$key];
}
return $this->file_info;
}
/**
* Get one or all pieces of info for the file.
*/
public function info_set($key, $value) {
$this->file_info[$key] = $value;
}
/**
* Get the file extension.
*/
function extension() {
public function extension() {
return implode(".", $this->ext);
}
/**
* Get the file type.
*/
function type() {
public function type() {
return $this->type;
}
/**
* Get the file mimetype.
*/
function mimetype() {
public function mimetype() {
return @$this->type['filemime'] ? $this->type['filemime'] : 'application/octet-stream';
}
/**
* Get the file mimetype.
*/
function type_id() {
public function type_id() {
return @$this->type['id'];
}
/**
*
*/
public function filesize() {
if (empty($this->file_info['filesize'])) {
$this->calculate_filesize();
}
return $this->file_info['filesize'];
}
/**
*
*/
public function calculate_filesize() {
$this->file_info['filesize'] = '';
if (!empty($this->path) && file_exists($this->path)) {
$this->file_info['filesize'] = filesize($this->path);
}
}
/**
* Can this file be used to backup to.
*/
function can_backup() {
public function can_backup() {
return @$this->type['backup'];
}
/**
* Can this file be used to restore to.
*/
function can_restore() {
public function can_restore() {
return @$this->type['restore'];
}
/**
* Can this file be used to restore to.
*/
function is_recognized_type() {
public function is_recognized_type() {
return @$this->type['restore'] || @$this->type['backup'];
}
/**
* Open a file for reading or writing.
*/
function open($write = FALSE, $binary = FALSE) {
public function open($write = FALSE, $binary = FALSE) {
if (!$this->handle) {
$path = $this->filepath();
@@ -267,7 +383,7 @@ class backup_file {
/**
* Close a file when we're done reading/writing.
*/
function close() {
public function close() {
fclose($this->handle);
$this->handle = NULL;
}
@@ -275,7 +391,7 @@ class backup_file {
/**
* Write a line to the file.
*/
function write($data) {
public function write($data) {
if (!$this->handle) {
$this->handle = $this->open(TRUE);
}
@@ -287,7 +403,7 @@ class backup_file {
/**
* Read a line from the file.
*/
function read($size = NULL) {
public function read($size = NULL) {
if (!$this->handle) {
$this->handle = $this->open();
}
@@ -300,14 +416,14 @@ class backup_file {
/**
* Write data to the file.
*/
function put_contents($data) {
public function put_contents($data) {
file_put_contents($this->filepath(), $data);
}
/**
* Read data from the file.
*/
function get_contents() {
public function get_contents() {
return file_get_contents($this->filepath());
}
@@ -315,11 +431,16 @@ class backup_file {
* Transfer file using http to client. Similar to the built in file_transfer,
* but it calls module_invoke_all('exit') so that temp files can be deleted.
*/
function transfer() {
public function transfer() {
$headers = array(
array('key' => 'Content-Type', 'value' => $this->mimetype()),
array('key' => 'Content-Disposition', 'value' => 'attachment; filename="'. $this->filename() .'"'),
array('key' => 'Content-Disposition', 'value' => 'attachment; filename="' . $this->filename() . '"'),
);
// In some circumstances, web-servers will double compress gzipped files.
// This may help aleviate that issue by disabling mod-deflate.
if ($this->mimetype() == 'application/x-gzip') {
$headers[] = array('key' => 'Content-Encoding', 'value' => 'gzip');
}
if ($size = $this->info('filesize')) {
$headers[] = array('key' => 'Content-Length', 'value' => $size);
}
@@ -358,7 +479,7 @@ class backup_file {
/**
* Push a file extension onto the file and return the previous file path.
*/
function push_type($extension) {
public function push_type($extension) {
$types = _backup_migrate_filetypes();
if ($type = @$types[$extension]) {
$this->push_filetype($type);
@@ -372,7 +493,7 @@ class backup_file {
/**
* Push a file extension onto the file and return the previous file path.
*/
function pop_type() {
public function pop_type() {
$out = new backup_file(array('filepath' => $this->filepath()));
$this->pop_filetype();
$this->temporary_file();
@@ -382,7 +503,7 @@ class backup_file {
/**
* Set the current file type.
*/
function set_filetype($type) {
public function set_filetype($type) {
$this->type = $type;
$this->ext = array($type['extension']);
}
@@ -390,7 +511,7 @@ class backup_file {
/**
* Set the current file type.
*/
function push_filetype($type) {
public function push_filetype($type) {
$this->ext[] = $type['extension'];
$this->type = $type;
}
@@ -398,7 +519,7 @@ class backup_file {
/**
* Pop the current file type.
*/
function pop_filetype() {
public function pop_filetype() {
array_pop($this->ext);
$this->detect_filetype_from_extension();
}
@@ -406,7 +527,7 @@ class backup_file {
/**
* Set the file info.
*/
function set_file_info($file_info) {
public function set_file_info($file_info) {
$this->file_info = $file_info;
$this->ext = explode('.', @$this->file_info['filename']);
@@ -421,7 +542,7 @@ class backup_file {
/**
* Get the filetype info of the given file, or false if the file is not a valid type.
*/
function detect_filetype_from_extension() {
public function detect_filetype_from_extension() {
$ext = end($this->ext);
$this->type = array();
$types = _backup_migrate_filetypes();
@@ -436,17 +557,17 @@ class backup_file {
/**
* Get a temporary file name with path.
*/
function temporary_file() {
public function temporary_file() {
$file = drupal_tempnam('temporary://', 'backup_migrate_');
// Add the version without the extension. The tempnam function creates this for us.
backup_migrate_temp_files_add($file);
if ($this->extension()) {
$file .= '.'. $this->extension();
$file .= '.' . $this->extension();
// Add the version with the extension. This is the one we will actually use.
backup_migrate_temp_files_add($file);
}
$this->path = $file;
}
}
}
@@ -1,9 +1,10 @@
<?php
/**
* @file
* This filter performs tha actual backup or restore operation. Not technically a filter per-se, but it does need to fit in the call chain.
* This filter performs tha actual backup or restore operation.
*
* Not technically a filter per-se, but it does need to fit in the call chain.
*/
/**
@@ -12,12 +13,12 @@
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_backup_restore extends backup_migrate_filter {
var $op_weights = array('backup' => 0, 'restore' => 0);
public $op_weights = array('backup' => 0, 'restore' => 0);
/**
* Get the default destinations for this filter.
*/
function destinations() {
public function destinations() {
$out = array();
foreach ($this->_get_destination_types() as $destination) {
if (method_exists($destination, 'destinations')) {
@@ -27,15 +28,28 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
return $out;
}
/**
* Get the default sources for this filter.
*/
public function sources() {
$out = array();
foreach ($this->_get_source_types() as $type) {
if (method_exists($type, 'sources')) {
$out += $type->sources();
}
}
return $out;
}
/**
* Get the default backup settings for this filter.
*/
function backup_settings_default() {
backup_migrate_include('destinations');
public function backup_settings_default() {
require_once dirname(__FILE__) . '/sources.inc';
$out = array();
foreach (backup_migrate_get_destinations('source') as $destination) {
$out['destinations'][$destination->get_id()] = $destination->backup_settings_default();
foreach (backup_migrate_get_sources() as $source) {
$out['sources'][$source->get_id()] = $source->backup_settings_default();
}
return $out;
}
@@ -43,7 +57,7 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form_validate($form, &$form_state) {
public function backup_settings_form_validate($form, &$form_state) {
foreach ($this->_get_destination_types() as $destination) {
$destination->backup_settings_form_validate($form, $form_state);
}
@@ -52,7 +66,7 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
/**
* Submit the settings form. Any values returned will be saved.
*/
function backup_settings_form_submit($form, &$form_state) {
public function backup_settings_form_submit($form, &$form_state) {
foreach ($this->_get_destination_types() as $destination) {
$destination->backup_settings_form_submit($form, $form_state);
}
@@ -61,7 +75,7 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
/**
* Get the default restore settings for this filter.
*/
function restore_settings_default() {
public function restore_settings_default() {
$out = array();
foreach ($this->_get_destination_types() as $destination) {
$out += $destination->restore_settings_default();
@@ -72,22 +86,24 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
/**
* Get the form for the backup settings for this filter.
*/
function backup_settings_form($settings) {
backup_migrate_include('destinations');
$out = array('destinations' => array(
'#tree' => TRUE,
));
foreach (backup_migrate_get_destinations('source') as $destination) {
$destination_settings = (array)(@$settings['destinations'][$destination->get_id()]) + $settings;
if ($form = $destination->backup_settings_form($destination_settings)) {
$out['destinations'][$destination->get_id()] = array(
public function backup_settings_form($settings) {
require_once dirname(__FILE__) . '/sources.inc';
$out = array(
'sources' => array(
'#tree' => TRUE,
),
);
foreach (backup_migrate_get_sources() as $source) {
$source_settings = (array) (@$settings['sources'][$source->get_id()]) + $settings;
if ($form = $source->backup_settings_form($source_settings)) {
$out['sources'][$source->get_id()] = array(
'#type' => 'fieldset',
'#title' => t('!name Backup Options', array('!name' => $destination->get('name'))),
'#title' => t('!name Backup Options', array('!name' => $source->get('name'))),
"#collapsible" => TRUE,
"#collapsed" => TRUE,
'#tree' => TRUE,
'#parents' => array('filters', 'destinations', $destination->get_id()),
'#parents' => array('filters', 'sources', $source->get_id()),
) + $form;
}
}
@@ -97,7 +113,7 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
/**
* Get the form for the restore settings for this filter.
*/
function restore_settings_form($settings) {
public function restore_settings_form($settings) {
$form = array();
foreach ($this->_get_destination_types() as $destination) {
$destination->restore_settings_form($form, $settings);
@@ -105,25 +121,72 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
return $form;
}
/**
* Get the before-backup form for the active sources and destinations.
*/
public function before_action_form($op, $settings) {
$form = array();
$method = 'before_' . $op . '_form';
if ($source = $settings->get_source()) {
if (method_exists($source, $method)) {
$form += $source->{$method}($settings);
}
}
foreach ($settings->get_destinations() as $destination) {
if (method_exists($destination, $method)) {
$form += $destination->{$method}($settings);
}
}
return $form;
}
/**
* Get the before-backup form for the active sources and destinations.
*/
public function before_action_form_validate($op, $settings, $form, $form_state) {
$method = 'before_' . $op . '_form_validate';
foreach ($settings->get_all_locations() as $location) {
if (method_exists($location, $method)) {
$location->{$method}($settings, $form, $form_state);
}
}
}
/**
* Get the before-backup form for the active sources and destinations.
*/
public function before_action_form_submit($op, $settings, $form, $form_state) {
$method = 'before_' . $op . '_form_submit';
foreach ($settings->get_all_locations() as $location) {
if (method_exists($location, $method)) {
$location->{$method}($settings, $form, $form_state);
}
}
}
/**
* Get the file types supported by this destination.
*/
function file_types() {
public function file_types() {
$types = array();
foreach ($this->_get_destination_types() as $destination) {
$types += $destination->file_types();
}
foreach ($this->_get_source_types() as $source) {
$types += $source->file_types();
}
return $types;
}
/**
* Backup the data from the source specified in the settings.
*/
function backup($file, &$settings) {
public function backup($file, $settings) {
if ($source = $settings->get_source()) {
if (!empty($settings->filters['destinations'][$source->get_id()])) {
$settings->filters = (array)($settings->filters['destinations'][$source->get_id()]) + $settings->filters;
if (!empty($settings->filters['sources'][$source->get_id()])) {
$settings->filters = (array) ($settings->filters['sources'][$source->get_id()]) + $settings->filters;
}
$file = $source->backup_to_file($file, $settings);
return $file;
}
@@ -134,10 +197,10 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
/**
* Restore the data from to source specified in the settings.
*/
function restore($file, &$settings) {
public function restore($file, $settings) {
if ($source = $settings->get_source()) {
if (!empty($settings->filters['destinations'][$source->get_id()])) {
$settings->filters = (array)($settings->filters['destinations'][$source->get_id()]) + $settings->filters;
if (!empty($settings->filters['sources'][$source->get_id()])) {
$settings->filters = (array) ($settings->filters['sources'][$source->get_id()]) + $settings->filters;
}
$num = $source->restore_from_file($file, $settings);
return $num ? $file : FALSE;
@@ -147,23 +210,54 @@ class backup_migrate_filter_backup_restore extends backup_migrate_filter {
}
/**
* Get a list of dummy destinations representing each of the available destination types.
* Dummy destinations representing each of the available destination types.
*
* @return array
* All of the available destination types.
*/
function _get_destination_types() {
backup_migrate_include('destinations');
static $destinations = NULL;
public function _get_destination_types() {
require_once dirname(__FILE__) . '/destinations.inc';
$destinations = &drupal_static('backup_migrate_filter_backup_restore::_get_destination_types', NULL);
if (!is_array($destinations)) {
$destinations = array();
$types = backup_migrate_get_destination_types();
$types = backup_migrate_get_destination_subtypes();
// If no (valid) node type has been provided, display a node type overview.
foreach ($types as $key => $type) {
// Include the necessary file if specified by the type.
if (!empty($type['file'])) {
require_once './'. $type['file'];
require_once './' . $type['file'];
}
$destinations[] = new $type['class'](array());
}
}
return $destinations;
}
/**
* Dummy destinations representing each of the available source types.
*
* @return array
* All of the available source types.
*/
public function _get_source_types() {
require_once dirname(__FILE__) . '/sources.inc';
$sources = &drupal_static('backup_migrate_filter_backup_restore::_get_source_types', NULL);
if (!is_array($sources)) {
$sources = array();
$types = backup_migrate_get_source_subtypes();
// If no (valid) node type has been provided, display a node type
// overview.
foreach ($types as $key => $type) {
// Include the necessary file if specified by the type.
if (!empty($type['file'])) {
require_once './' . $type['file'];
}
$sources[] = new $type['class'](array());
}
}
return $sources;
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* A filter for compressing bckups with zip, gz bzip etc.
@@ -12,26 +11,26 @@
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_compression extends backup_migrate_filter {
var $op_weights = array('backup' => 100, 'restore' => -100);
public $op_weights = array('backup' => 100, 'restore' => -100);
/**
* This function is called on a backup file after the backup has been completed.
*/
function backup($file, &$settings) {
public function backup($file, $settings) {
return $this->_backup_migrate_file_compress($file, $settings);
}
/**
* This function is called on a backup file before importing it.
*/
function restore($file, &$settings) {
return $this->_backup_migrate_file_decompress($file);
public function restore($file, $settings) {
return $this->_backup_migrate_file_decompress($file, $settings);
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_default() {
public function backup_settings_default() {
$options = $this->_backup_migrate_get_compression_form_item_options();
return array('compression' => isset($options['gzip']) ? 'gzip' : 'none');
}
@@ -39,7 +38,7 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form($settings) {
public function backup_settings_form($settings) {
$form = array();
$compression_options = $this->_backup_migrate_get_compression_form_item_options();
$form['file']['compression'] = array(
@@ -54,7 +53,7 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Return a list of backup filetypes.
*/
function file_types() {
public function file_types() {
return array(
"gzip" => array(
"extension" => "gz",
@@ -86,7 +85,7 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Get the compression options as an options array for a form item.
*/
function _backup_migrate_get_compression_form_item_options() {
public function _backup_migrate_get_compression_form_item_options() {
$compression_options = array("none" => t("No Compression"));
if (@function_exists("gzencode")) {
$compression_options['gzip'] = t("GZip");
@@ -103,10 +102,14 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Gzip encode a file.
*/
function _backup_migrate_gzip_encode($source, $dest, $level = 9) {
public function _backup_migrate_gzip_encode($source, $dest, $level = 9, $settings) {
$success = FALSE;
if (@function_exists("gzopen")) {
if (($fp_out = gzopen($dest, 'wb'. $level)) && ($fp_in = fopen($source, 'rb'))) {
// Try command line gzip first.
if (!empty($settings->filters['use_cli'])) {
$success = backup_migrate_exec("gzip -c -$level %input > %dest", array('%input' => $source, '%dest' => $dest, '%level' => $level));
}
if (!$success && @function_exists("gzopen")) {
if (($fp_out = gzopen($dest, 'wb' . $level)) && ($fp_in = fopen($source, 'rb'))) {
while (!feof($fp_in)) {
gzwrite($fp_out, fread($fp_in, 1024 * 512));
}
@@ -121,9 +124,14 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Gzip decode a file.
*/
function _backup_migrate_gzip_decode($source, $dest) {
public function _backup_migrate_gzip_decode($source, $dest, $settings) {
$success = FALSE;
if (@function_exists("gzopen")) {
if (!empty($settings->filters['use_cli'])) {
$success = backup_migrate_exec("gzip -d -c %input > %dest", array('%input' => $source, '%dest' => $dest));
}
if (!$success && @function_exists("gzopen")) {
if (($fp_out = fopen($dest, 'wb')) && ($fp_in = gzopen($source, 'rb'))) {
while (!feof($fp_in)) {
fwrite($fp_out, gzread($fp_in, 1024 * 512));
@@ -139,7 +147,7 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Bzip encode a file.
*/
function _backup_migrate_bzip_encode($source, $dest) {
public function _backup_migrate_bzip_encode($source, $dest) {
$success = FALSE;
if (@function_exists("bzopen")) {
if (($fp_out = bzopen($dest, 'w')) && ($fp_in = fopen($source, 'rb'))) {
@@ -160,7 +168,7 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Bzip decode a file.
*/
function _backup_migrate_bzip_decode($source, $dest) {
public function _backup_migrate_bzip_decode($source, $dest) {
$success = FALSE;
if (@function_exists("bzopen")) {
if (($fp_out = fopen($dest, 'w')) && ($fp_in = bzopen($source, 'r'))) {
@@ -181,10 +189,10 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Zip encode a file.
*/
function _backup_migrate_zip_encode($source, $dest, $filename) {
public function _backup_migrate_zip_encode($source, $dest, $filename) {
$success = FALSE;
if (class_exists('ZipArchive')) {
$zip = new ZipArchive;
$zip = new ZipArchive();
$res = $zip->open($dest, constant("ZipArchive::CREATE"));
if ($res === TRUE) {
$zip->addFile($source, $filename);
@@ -197,10 +205,10 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
/**
* Zip decode a file.
*/
function _backup_migrate_zip_decode($source, $dest) {
public function _backup_migrate_zip_decode($source, $dest) {
$success = FALSE;
if (class_exists('ZipArchive')) {
$zip = new ZipArchive;
$zip = new ZipArchive();
if (($fp_out = fopen($dest, "w")) && ($zip->open($source))) {
$filename = ($zip->getNameIndex(0));
if ($fp_in = $zip->getStream($filename)) {
@@ -220,11 +228,11 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
* Compress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
*/
function _backup_migrate_file_compress($file, $settings) {
public function _backup_migrate_file_compress($file, $settings) {
switch ($settings->filters['compression']) {
case "gzip":
$from = $file->push_type('gzip');
if (!$success = $this->_backup_migrate_gzip_encode($from, $file->filepath(), 9)) {
if (!$success = $this->_backup_migrate_gzip_encode($from, $file->filepath(), 9, $settings)) {
$file = NULL;
}
break;
@@ -247,7 +255,6 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
if (!$file) {
_backup_migrate_message("Could not compress backup file. Try backing up without compression.", array(), 'error');
}
return $file;
}
@@ -255,13 +262,13 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
* Decompress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
*/
function _backup_migrate_file_decompress($file) {
public function _backup_migrate_file_decompress($file, $settings) {
$success = FALSE;
switch ($file->type_id()) {
case "gzip":
$from = $file->pop_type();
$success = $this->_backup_migrate_gzip_decode($from->filepath(), $file->filepath());
$success = $this->_backup_migrate_gzip_decode($from->filepath(), $file->filepath(), $settings);
break;
case "bzip":
@@ -285,5 +292,5 @@ class backup_migrate_filter_compression extends backup_migrate_filter {
}
return $success ? $file : NULL;
}
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* A filter for encrypting bckups with AES.
@@ -12,59 +11,77 @@
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_encryption extends backup_migrate_filter {
var $op_weights = array('backup' => 170, 'restore' => -170);
public $op_weights = array('backup' => 170, 'restore' => -170);
/**
* This function is called on a backup file after the backup has been completed.
* Called on a backup file after the backup has been completed.
*/
function backup($file, &$settings) {
public function backup($file, $settings) {
return $this->file_encrypt($file, $settings);
}
/**
* This function is called on a backup file before importing it.
* Called on a backup file before importing it.
*/
function restore($file, &$settings) {
public function restore($file, $settings) {
return $this->file_decrypt($file);
}
/**
* Get the form for the settings for this filter.
* Gets the form for the settings for this filter.
*/
function backup_settings_default() {
public function backup_settings_default() {
return array('encryption' => 'none');
}
/**
* Get the form for the settings for this filter.
* Gets the form for the settings for this filter.
*/
function backup_settings_form($settings) {
public function backup_settings_form($settings) {
$form = array();
$options = $this->_backup_migrate_get_encryption_form_item_options();
if (count($options) > 1) {
if (array_intersect_key($options, array_flip(array('aes', 'encrypt')))) {
$form['file']['encryption'] = array(
"#type" => "select",
"#title" => t("File Encryption (EXPERIMENTAL)"),
"#title" => t("File Encryption"),
"#options" => $options,
"#default_value" => @$settings['encryption'],
'#description' => t('Encrypted files can only be restored by Backup and Migrate and only on sites with the same encryption key. <strong>This functionality is experimental, and should only be used for testing.</strong>'),
'#description' => t('Encrypted files can only be restored by Backup and Migrate and only on sites with the same encryption key.'),
);
}
else {
$form['file']['encryption'] = array(
"#type" => 'item',
"#title" => t("File Encryption"),
"#markup" => t('Install the !link to enable backup file encryption.', array('!link' => l(t('AES Encryption Module'), 'http://drupal.org/project/aes'))),
"#markup" => t('Install the !link to enable backup file encryption.', array('!link' => l(t('Encrypt module'), 'http://drupal.org/project/encrypt'))),
);
}
// If the Encrypt method is available add a configuration field.
if (array_key_exists('encrypt', $options)) {
$form['file']['encrypt_config'] = array(
'#type' => 'select',
'#title' => t('Encryption Configuration'),
'#options' => encrypt_get_configs_as_options(),
'#default_value' => @$settings['encrypt_config'],
'#description' => t('Select a configuration to use for encryption.'),
'#states' => array(
'visible' => array(
':input[name="filters[encryption]"]' => array('value' => 'encrypt'),
),
),
);
}
return $form;
}
/**
* Return a list of backup filetypes.
* Returns a list of backup filetypes.
*/
function file_types() {
public function file_types() {
return array(
"aes" => array(
"extension" => "aes",
@@ -72,29 +89,39 @@ class backup_migrate_filter_encryption extends backup_migrate_filter {
"backup" => TRUE,
"restore" => TRUE,
),
"encrypt" => array(
"extension" => "encrypt",
"filemime" => "application/octet-stream",
"backup" => TRUE,
"restore" => TRUE,
),
);
}
/**
* Get the compression options as an options array for a form item.
* Gets the compression options as an options array for a form item.
*/
function _backup_migrate_get_encryption_form_item_options() {
public function _backup_migrate_get_encryption_form_item_options() {
$options = array();
$options = array('' => t('No Encryption'));
if (@function_exists("aes_encrypt")) {
$options['aes'] = t("AES Encryption");
}
if (@function_exists("encrypt")) {
$options['encrypt'] = t("Encryption With Encrypt Module");
}
return $options;
}
/**
* AES encrypt a file.
* AES encrypts a file.
*/
function aes_encrypt($source, $dest) {
public function aes_encrypt($source, $dest) {
$success = FALSE;
if (function_exists('aes_encrypt')) {
if ($data = $source->get_contents()) {
// Add a marker to the end of the data so we can trim the padding on decrpypt.
// Add a marker to the end of the data so we can trim the padding on
// decrpypt.
$data = pack("a*H2", $data, "80");
if ($data = aes_encrypt($data, FALSE)) {
$dest->put_contents($data);
@@ -106,9 +133,9 @@ class backup_migrate_filter_encryption extends backup_migrate_filter {
}
/**
* Gzip decode a file.
* AES decodes a file.
*/
function aes_decrypt($source, $dest) {
public function aes_decrypt($source, $dest) {
$success = FALSE;
if (function_exists('aes_decrypt')) {
if ($data = $source->get_contents()) {
@@ -124,10 +151,54 @@ class backup_migrate_filter_encryption extends backup_migrate_filter {
}
/**
* Compress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
* Encrypts a file with the Encrypt module.
*/
function file_encrypt($file, $settings) {
public function encrypt($source, $dest, $settings) {
$success = FALSE;
if (function_exists('encrypt')) {
if (!empty($settings->filters['encrypt_config'])) {
$config_name = $settings->filters['encrypt_config'];
}
else {
$config = encrypt_get_default_config();
$config_name = $config['name'];
}
if ($data = $source->get_contents()) {
// Add a marker to the end of the data so we can trim the padding on decrypt.
$data = pack("a*H2", $data, "80");
if ($data = encrypt($data, array('base64' => FALSE), NULL, NULL, $config_name)) {
$dest->put_contents($data);
$success = TRUE;
}
}
}
return $success;
}
/**
* Decrypts a file with the Encrypt module.
*/
public function decrypt($source, $dest) {
$success = FALSE;
if (function_exists('decrypt')) {
if ($data = $source->get_contents()) {
if ($data = decrypt($data)) {
// Trim all the padding zeros plus our non-zero marker.
$data = substr(rtrim($data, "\0"), 0, -1);
$dest->put_contents($data);
$success = TRUE;
}
}
}
return $success;
}
/**
* Encrypts a file with the given settings.
*
* Also updates settings to reflect new file mime and file extension.
*/
public function file_encrypt($file, $settings) {
if (!empty($settings->filters['encryption'])) {
switch ($settings->filters['encryption']) {
case "aes":
@@ -137,6 +208,14 @@ class backup_migrate_filter_encryption extends backup_migrate_filter {
$file = NULL;
}
break;
case "encrypt":
$from = $file->push_type('encrypt');
$from = new backup_file(array('filepath' => $from));
if (!$success = $this->encrypt($from, $file, $settings)) {
$file = NULL;
}
break;
}
if (!$file) {
_backup_migrate_message("Could not encrypt backup file. Try backing up without encryption.", array(), 'error');
@@ -146,10 +225,11 @@ class backup_migrate_filter_encryption extends backup_migrate_filter {
}
/**
* Decompress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
* Decrypts a file with the given settings.
*
* Also updates settings to reflect new file mime and file extension.
*/
function file_decrypt($file) {
public function file_decrypt($file) {
$success = FALSE;
if ($file) {
switch ($file->type_id()) {
@@ -157,21 +237,39 @@ class backup_migrate_filter_encryption extends backup_migrate_filter {
$from = $file->pop_type();
$success = $this->aes_decrypt($from, $file);
break;
case "encrypt":
$from = $file->pop_type();
$success = $this->decrypt($from, $file);
break;
default:
return $file;
break;
}
}
if (!$success) {
if (function_exists('aes_decrypt')) {
_backup_migrate_message("Could not decrpyt backup file. Please check that the file is valid and that the encryption key of the server matches the server that created the backup.", array(), 'error');
}
else {
_backup_migrate_message('You must install the !link to restore encrypted backkups.', array('!link' => l(t('AES Encryption Module'), 'http://drupal.org/project/aes')), 'error');
switch ($file->type_id()) {
case 'aes':
if (function_exists('aes_decrypt')) {
_backup_migrate_message("Could not decrpyt backup file. Please check that the file is valid and that the encryption key of the server matches the server that created the backup.", array(), 'error');
}
else {
_backup_migrate_message('You must install the !link to restore encrypted backkups.', array('!link' => l(t('AES Encryption Module'), 'http://drupal.org/project/aes')), 'error');
}
break;
case 'encrypt':
if (function_exists('decrypt')) {
_backup_migrate_message("Could not decrypt backup file. Please check that the file is valid and that the encryption key of the server matches the server that created the backup.", array(), 'error');
}
else {
_backup_migrate_message('You must install the !link to restore encrypted backups.', array('!link' => l(t('Encrypt module'), 'http://drupal.org/project/encrypt')), 'error');
}
break;
}
}
}
return $success ? $file : NULL;
}
}
}
@@ -1,25 +1,24 @@
<?php
/**
* @file
* All of the filter handling code needed for Backup and Migrate.
*/
/**
* Get the available destination types.
* Gets the available destination types.
*/
function backup_migrate_get_filters($op = NULL) {
static $filters = NULL;
$filters = &drupal_static('backup_migrate_get_filters', NULL);
if ($filters === NULL) {
$filters = array();
$definitions = module_invoke_all('backup_migrate_filters');
foreach ($definitions as $definition) {
// Include the necessary file if specified by the filter.
if (!empty($definition['file'])) {
require_once './'. $definition['file'];
require_once './' . $definition['file'];
}
$filters[] = new $definition['class'];
$filters[] = new $definition['class']();
}
}
$sort = array();
@@ -32,37 +31,37 @@ function backup_migrate_get_filters($op = NULL) {
}
/**
* Implementation of hook_backup_migrate_filters().
* Implements hook_backup_migrate_filters().
*
* Get the built in Backup and Migrate filters.
*/
function backup_migrate_backup_migrate_filters() {
return array(
'backup_restore' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.backup_restore.inc',
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/filters.backup_restore.inc',
'class' => 'backup_migrate_filter_backup_restore',
),
'compression' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.compression.inc',
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/filters.compression.inc',
'class' => 'backup_migrate_filter_compression',
),
'encryption' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.encryption.inc',
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/filters.encryption.inc',
'class' => 'backup_migrate_filter_encryption',
),
'statusnotify' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.statusnotify.inc',
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/filters.statusnotify.inc',
'class' => 'backup_migrate_filter_statusnotify',
),
'utils' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.utils.inc',
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/filters.utils.inc',
'class' => 'backup_migrate_filter_utils',
),
);
}
/**
* Invoke the given method on all of the available filters.
* Invokes the given method on all of the available filters.
*/
function backup_migrate_filters_invoke_all() {
$args = func_get_args();
@@ -96,42 +95,47 @@ function backup_migrate_filters_invoke_all() {
}
/**
* Filter a backup file before sending it to the destination.
* Filters a backup file before sending it to the destination.
*/
function backup_migrate_filters_backup($file, &$settings) {
backup_migrate_filters_invoke_all('pre_backup', $file, $settings);
$filters = backup_migrate_get_filters('backup');
foreach ($filters as $filter) {
if ($file) {
$file = $filter->backup($file, $settings);
}
}
backup_migrate_filters_invoke_all('post_backup', $file, $settings);
return $file;
}
/**
* Filter a backup file before sending it to the destination.
* Filters a backup file before sending it to the destination.
*/
function backup_migrate_filters_restore($file, &$settings) {
backup_migrate_filters_invoke_all('pre_restore', $file, $settings);
$filters = backup_migrate_get_filters('restore');
foreach ($filters as $filter) {
if ($file) {
$file = $filter->restore($file, $settings);
}
}
backup_migrate_filters_invoke_all('post_restore', $file, $settings);
return $file;
}
/**
* Get the backup settings for all of the filters.
* Gets the backup settings for all of the filters.
*/
function backup_migrate_filters_settings_form($settings, $op) {
$out = backup_migrate_filters_invoke_all($op .'_settings_form', $settings);
$out = backup_migrate_filters_invoke_all($op . '_settings_form', $settings);
$out = backup_migrate_filters_settings_form_set_parents($out);
return $out;
}
/**
* Add a form parent to the filter settings so that the filter values are saved in the right table.
* Adds form parent to filter settings so the values are saved in correct table.
*/
function backup_migrate_filters_settings_form_set_parents($form) {
foreach (element_children($form) as $key) {
@@ -143,27 +147,51 @@ function backup_migrate_filters_settings_form_set_parents($form) {
return $form;
}
/**
* Validate all the filters.
* Validates all the filters.
*/
function backup_migrate_filters_settings_form_validate($op, $form, &$form_state) {
//backup_migrate_filters_invoke_all($op .'_settings_form_validate', $form, $form_state);
backup_migrate_filters_invoke_all($op . '_settings_form_validate', $form, $form_state);
}
/**
* Submit all of the filters.
* Submits all of the filters.
*/
function backup_migrate_filters_settings_form_submit($op, $form, &$form_state) {
//backup_migrate_filters_invoke_all($op .'_settings_form_submit', $form, $form_state);
backup_migrate_filters_invoke_all($op . '_settings_form_submit', $form, $form_state);
}
/**
* Get the default settings for the filters.
* Gets the default settings for the filters.
*/
function backup_migrate_filters_settings_default($op) {
return backup_migrate_filters_invoke_all($op .'_settings_default');
return backup_migrate_filters_invoke_all($op . '_settings_default');
}
/**
* Get the backup settings for all of the filters.
*/
function backup_migrate_filters_before_action_form($settings, $op) {
$out = array();
$out += backup_migrate_filters_invoke_all('before_action_form', $op, $settings);
$out += backup_migrate_filters_invoke_all('before_' . $op . '_form', $settings);
return $out;
}
/**
* Get the backup settings for all of the filters.
*/
function backup_migrate_filters_before_action_form_validate($settings, $op, $form, &$form_state) {
backup_migrate_filters_invoke_all('before_action_form_validate', $op, $settings, $form, $form_state);
backup_migrate_filters_invoke_all('before_' . $op . '_form_validate', $settings, $form, $form_state);
}
/**
* Get the backup settings for all of the filters.
*/
function backup_migrate_filters_before_action_form_submit($settings, $op, $form, &$form_state) {
backup_migrate_filters_invoke_all('before_action_form_submit', $op, $settings, $form, $form_state);
backup_migrate_filters_invoke_all('before_' . $op . '_form_submit', $settings, $form, $form_state);
}
/**
@@ -177,13 +205,13 @@ function backup_migrate_filters_file_types() {
* A base class for basing filters on.
*/
class backup_migrate_filter {
var $weight = 0;
var $op_weights = array();
public $weight = 0;
public $op_weights = array();
/**
* Get the weight of the filter for the given op.
*/
function weight($op = NULL) {
public function weight($op = NULL) {
if ($op && isset($this->op_weights[$op])) {
return $this->op_weights[$op];
}
@@ -193,98 +221,110 @@ class backup_migrate_filter {
/**
* Get the form for the settings for this filter.
*/
function backup_settings_default() {
public function backup_settings_default() {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form($settings) {
public function backup_settings_form($settings) {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form_validate($form, &$form_state) {
public function backup_settings_form_validate($form, &$form_state) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
function backup_settings_form_submit($form, &$form_state) {
return $form_state['values'];
public function backup_settings_form_submit($form, &$form_state) {
}
/**
* Get the form for the settings for this filter.
*/
function restore_settings_default() {
public function restore_settings_default() {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function restore_settings_form($settings) {
public function restore_settings_form($settings) {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function restore_settings_form_validate($form, &$form_state) {
public function restore_settings_form_validate($form, &$form_state) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
function restore_settings_form_submit($form, &$form_state) {
public function restore_settings_form_submit($form, &$form_state) {
return $form_state['values'];
}
/**
* Get a list of file types handled by this filter.
*/
function file_types() {
public function file_types() {
return array();
}
/**
* Declare any default destinations for this filter.
*/
function destinations() {
public function destinations() {
return array();
}
/**
* This function is called on a backup file after the backup has been completed.
* Called on a backup file after the backup has been completed.
*/
function backup($file, &$settings) {
return $file;
}
/**
* This function is called on a backup file before importing it.
*/
function restore($file, &$settings) {
public function backup($file, $settings) {
return $file;
}
/**
* This function is called immediately prior to backup.
*/
function pre_backup($source, $file, $settings) {
public function pre_backup($file, $settings) {
}
/**
* This function is called immediately post backup.
*/
function post_backup($source, $file, $settings) {
public function post_backup($file, $settings) {
}
}
/**
* This function is called on a backup file before importing it.
*/
public function restore($file, $settings) {
return $file;
}
/**
* This function is called immediately prior to restore.
*/
public function pre_restore($file, $settings) {
}
/**
* This function is called immediately post restore.
*/
public function post_restore($file, $settings) {
}
}
@@ -1,6 +1,5 @@
<?php
/**
* @file
* A filter for compressing bckups with zip, gz bzip etc.
@@ -12,11 +11,11 @@
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_statusnotify extends backup_migrate_filter {
/**
* Get the default backup settings for this filter.
*/
function backup_settings_default() {
public function backup_settings_default() {
return array(
'notify_success_enable' => FALSE,
'notify_failure_enable' => FALSE,
@@ -28,14 +27,20 @@ class backup_migrate_filter_statusnotify extends backup_migrate_filter {
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form($settings) {
public function backup_settings_form($settings) {
$form = array();
$form['advanced']['notify_success_enable'] = array(
"#type" => 'checkbox',
"#title" => t("Send an email if backup succeeds"),
"#default_value" => @$settings['notify_success_enable'],
);
$form['advanced']['notify_success_email'] = array(
$form['advanced']['notify_success_email_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[notify_success_enable]' => TRUE,
),
);
$form['advanced']['notify_success_email_wrapper']['notify_success_email'] = array(
"#type" => "textfield",
"#title" => t("Email Address for Success Notices"),
"#default_value" => @$settings['notify_success_email'],
@@ -45,7 +50,13 @@ class backup_migrate_filter_statusnotify extends backup_migrate_filter {
"#title" => t("Send an email if backup fails"),
"#default_value" => @$settings['notify_failure_enable'],
);
$form['advanced']['notify_failure_email'] = array(
$form['advanced']['notify_failure_email_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[notify_failure_enable]' => TRUE,
),
);
$form['advanced']['notify_failure_email_wrapper']['notify_failure_email'] = array(
"#type" => "textfield",
"#title" => t("Email Address for Failure Notices"),
"#default_value" => @$settings['notify_failure_email'],
@@ -56,41 +67,39 @@ class backup_migrate_filter_statusnotify extends backup_migrate_filter {
/**
* Send the success email.
*/
function backup_succeed($settings) {
public function backup_succeed($settings) {
if (@$settings->filters['notify_success_enable'] && $to = @$settings->filters['notify_success_email']) {
$messages = $this->get_messages();
$subject = t('!site backup succeeded', array('!site' => variable_get('site_name', 'Drupal site')));
if ($messages = $this->get_messages()) {
$body = t("The site backup has completed successfully with the following messages:\n!messages", array('!messages' => $messages));
}
else {
$body = t("The site backup has completed successfully.\n");
}
mail($settings->filters['notify_success_email'], $subject, $body);
drupal_mail('backup_migrate', 'backup_succeed', $settings->filters['notify_success_email'], language_default(), array('body' => $body));
}
}
/**
* Send the failure email.
*/
function backup_fail($settings) {
public function backup_fail($settings) {
if (@$settings->filters['notify_failure_enable'] && $to = @$settings->filters['notify_failure_email']) {
$messages = $this->get_messages();
$subject = t('!site backup failed', array('!site' => variable_get('site_name', 'Drupal site')));
if ($messages = $this->get_messages()) {
$body = t("The site backup has failed with the following messages:\n!messages", array('!messages' => $messages));
}
else {
$body = t("The site backup has failed for an unknown reason.");
}
mail($settings->filters['notify_failure_email'], $subject, $body);
drupal_mail('backup_migrate', 'backup_fail', $settings->filters['notify_failure_email'], language_default(), array('body' => $body));
}
}
/**
* Render the messages and errors for the email.
*/
function get_messages() {
public function get_messages() {
$out = "";
$messages = _backup_migrate_messages();
foreach ($messages as $message) {
@@ -98,5 +107,5 @@ class backup_migrate_filter_statusnotify extends backup_migrate_filter {
}
return $out;
}
}
}
@@ -1,23 +1,23 @@
<?php
/**
* @file
* A filter to run some basic utility functions. Basically any useful option not big enough to justify it's own class.
*/
/**
* A filter to send a notification email on success or failure of backup.
* A filter to run some basic utility functions.
*
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_utils extends backup_migrate_filter {
var $saved_devel_query = NULL;
public $op_weights = array('pre_backup' => -1000, 'post_backup' => 1000);
public $saved_devel_query = NULL;
/**
* Get the default backup settings for this filter.
*/
function backup_settings_default() {
public function backup_settings_default() {
return array(
'utils_disable_query_log' => TRUE,
'utils_site_offline' => FALSE,
@@ -28,7 +28,7 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
/**
* Get the default restore settings for this filter.
*/
function restore_settings_default() {
public function restore_settings_default() {
return array(
'utils_disable_query_log' => TRUE,
'utils_site_offline' => FALSE,
@@ -38,7 +38,7 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
/**
* Get the form for the backup settings for this filter.
*/
function backup_settings_form($settings) {
public function backup_settings_form($settings) {
$form = array();
if (module_exists('devel') && variable_get('dev_query', 0)) {
$form['database']['utils_disable_query_log'] = array(
@@ -54,17 +54,35 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
'#default_value' => !empty($settings['utils_site_offline']) ? $settings['utils_site_offline'] : NULL,
'#description' => t('Take the site offline during backup and show a maintenance message. Site will be taken back online once the backup is complete.'),
);
$form['advanced']['utils_site_offline_message'] = array(
$form['advanced']['utils_site_offline_message_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[utils_site_offline]' => TRUE,
),
);
$form['advanced']['utils_site_offline_message_wrapper']['utils_site_offline_message'] = array(
'#type' => 'textarea',
'#title' => t('Site off-line message'),
'#default_value' => !empty($settings['utils_site_offline_message']) ? $settings['utils_site_offline_message'] : variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
'#description' => t('Message to show visitors when the site is in off-line mode.')
'#default_value' => !empty($settings['utils_site_offline_message']) ? $settings['utils_site_offline_message'] : variable_get('site_offline_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
'#description' => t('Message to show visitors when the site is in off-line mode.'),
);
$form['advanced']['utils_description'] = array(
'#type' => 'textarea',
'#title' => t('Description'),
'#title' => t('Add a note'),
'#default_value' => !empty($settings['utils_description']) ? $settings['utils_description'] : NULL,
'#description' => t('Add a short description to the backup file.'),
'#description' => t('Add a short note to the backup file.'),
);
$form['advanced']['use_cli'] = array(
"#type" => "checkbox",
"#title" => t("Use cli commands"),
"#default_value" => !empty($settings['use_cli']),
"#description" => t("Use the command line tools (mysqldump, tar, gzip etc.) if available. This can be faster for large sites but will not work on all servers. EXPERIMENTAL"),
);
$form['advanced']['ignore_errors'] = array(
"#type" => "checkbox",
"#title" => t("Ignore errors"),
"#default_value" => !empty($settings['ignore_errors']),
"#description" => t("Will attempt to complete backup even if certain recoverable errors occur. This may make the backup files invalid. Enable this if you have unreadable files that you want to ignore during backup."),
);
return $form;
@@ -73,7 +91,7 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
/**
* Get the form for the restore settings for this filter.
*/
function restore_settings_form($settings) {
public function restore_settings_form($settings) {
$form = array();
if (module_exists('devel') && variable_get('dev_query', 0)) {
$form['advanced']['utils_disable_query_log'] = array(
@@ -89,32 +107,70 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
'#default_value' => !empty($settings['utils_site_offline']) ? $settings['utils_site_offline'] : NULL,
'#description' => t('Take the site offline during restore and show a maintenance message. Site will be taken back online once the restore is complete.'),
);
$form['advanced']['utils_site_offline_message'] = array(
$form['advanced']['utils_site_offline_message_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[utils_site_offline]' => TRUE,
),
);
$form['advanced']['utils_site_offline_message_wrapper']['utils_site_offline_message'] = array(
'#type' => 'textarea',
'#title' => t('Site off-line message'),
'#default_value' => !empty($settings['utils_site_offline_message']) ? $settings['utils_site_offline_message'] : variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
'#description' => t('Message to show visitors when the site is in off-line mode.')
'#default_value' => !empty($settings['utils_site_offline_message']) ? $settings['utils_site_offline_message'] : variable_get('site_offline_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
'#description' => t('Message to show visitors when the site is in off-line mode.'),
);
$form['advanced']['utils_drop_all_tables'] = array(
'#type' => 'checkbox',
'#title' => t('Drop all tables before import (MySQL only)'),
'#default_value' => !empty($settings['utils_drop_all_tables']) ? $settings['utils_drop_all_tables'] : NULL,
'#description' => t('Drop all existing database tables before restoring the backup. This option is currently available on MySQL servers only.'),
);
$form['advanced']['use_cli'] = array(
"#type" => "checkbox",
"#title" => t("Use cli commands"),
"#default_value" => !empty($settings['use_cli']),
"#description" => t("Use the command line tools (mysqldump, tar, gzip etc.) if available. This can be faster for large sites but will not work on all servers. EXPERIMENTAL"),
);
// $form['advanced']['ignore_errors'] = array(
// "#type" => "checkbox",
// "#title" => t("Ignore errors"),
// "#default_value" => !empty($settings['ignore_errors']),
// "#description" => t("Will attempt to complete restore even if certain recoverable errors occur. This may could corrupt your site."),
// );
return $form;
}
function pre_backup($source, $file, $settings) {
/**
*
*/
public function pre_backup($file, $settings) {
$this->take_site_offline($settings);
$this->disable_devel_query($settings);
}
function post_backup($source, $file, $settings) {
/**
*
*/
public function post_backup($file, $settings) {
$this->enable_devel_query($settings);
$this->take_site_online($settings);
$this->add_file_info($file, $settings);
if ($file) {
$this->add_file_info($file, $settings);
}
}
function pre_restore($file, $settings) {
/**
*
*/
public function pre_restore($file, $settings) {
$this->disable_devel_query($settings);
$this->take_site_offline($settings);
}
function post_restore($file, $settings) {
/**
*
*/
public function post_restore($file, $settings) {
$this->enable_devel_query($settings);
$this->take_site_online($settings);
}
@@ -122,7 +178,7 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
/**
* Disable devel query logging if it's active and the user has chosen to do so.
*/
function disable_devel_query($settings) {
public function disable_devel_query($settings) {
$this->saved_devel_query = variable_get('dev_query', 0);
if (module_exists('devel') && variable_get('dev_query', 0) && !empty($settings->filters['utils_disable_query_log'])) {
variable_set('dev_query', 0);
@@ -132,7 +188,7 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
/**
* Restore devel query to previous state.
*/
function enable_devel_query($settings) {
public function enable_devel_query($settings) {
if (module_exists('devel')) {
variable_set('dev_query', $this->saved_devel_query);
}
@@ -141,49 +197,61 @@ class backup_migrate_filter_utils extends backup_migrate_filter {
/**
* Add the backup metadata to the file.
*/
function add_file_info($file, $settings) {
$file->file_info['description'] = $settings->filters['utils_description'];
$file->file_info['datestamp'] = time();
$file->file_info['generator'] = 'Backup and Migrate (http://drupal.org/project/backup_migrate)';
$file->file_info['generatorversion'] = BACKUP_MIGRATE_VERSION;
$file->file_info['sites'] = array(
'0' => array(
'version' => VERSION,
'name' => variable_get('site_name', ''),
'url' => url('', array('absolute' => TRUE)),
),
);
public function add_file_info($file, $settings) {
$file->file_info['description'] = $settings->filters['utils_description'];
$file->file_info['datestamp'] = time();
$file->file_info['generator'] = 'Backup and Migrate (http://drupal.org/project/backup_migrate)';
$file->file_info['generatorversion'] = BACKUP_MIGRATE_VERSION;
$file->file_info['siteurl'] = url('', array('absolute' => TRUE));
$file->file_info['sitename'] = variable_get('site_name', '');
$file->file_info['drupalversion'] = VERSION;
$file->calculate_filesize();
$source = $settings->get('source');
$file->file_info['bam_sourceid'] = $source->get('id');
$file->file_info['bam_sourcetype'] = $source->get('subtype');
$file->file_info['bam_sourcename'] = $source->get('name');
// Add any additional info that has been added to the settings by other plugins.
if (!empty($settings->file_info)) {
$file->file_info += $settings->file_info;
}
}
/**
* Take the site offline if configured to do so.
*/
function take_site_offline($settings) {
// Save the current state of the site in case a restore overwrites it.
$this->saved_site_offline = variable_get('maintenance_mode', 0);
if (@$settings->filters['utils_site_offline']) {
$this->saved_site_offline_message = variable_get('maintenance_mode_message', NULL);
if (!empty($settings->filters['utils_site_offline_message'])) {
public function take_site_offline($settings) {
// If the site is already offline then don't do anything.
if (!variable_get('maintenance_mode', 0)) {
// Save the current state of the site in case a restore overwrites it.
if (!empty($settings->filters['utils_site_offline'])) {
$this->saved_site_offline = TRUE;
$this->saved_site_offline_message = variable_get('maintenance_mode_message', NULL);
variable_set('maintenance_mode_message', $settings->filters['utils_site_offline_message']);
if (!empty($settings->filters['utils_site_offline_message'])) {
$this->saved_site_offline_message = variable_get('maintenance_mode_message', NULL);
variable_set('maintenance_mode_message', $settings->filters['utils_site_offline_message']);
}
variable_set('maintenance_mode', 1);
_backup_migrate_message('Site was taken offline.');
}
variable_set('maintenance_mode', 1);
_backup_migrate_message('Site was taken offline.');
}
}
/**
* Take the site online again after backup or restore.
*/
function take_site_online($settings) {
public function take_site_online($settings) {
// Take the site back off/online because the restored db may have changed that setting.
variable_set('maintenance_mode', $this->saved_site_offline);
if ($settings->filters['utils_site_offline']) {
if (!empty($this->saved_site_offline_message)) {
variable_set('maintenance_mode_message', $this->saved_site_offline_message);
if (variable_get('maintenance_mode', 0) && !empty($this->saved_site_offline)) {
variable_set('maintenance_mode', 0);
if ($settings->filters['utils_site_offline']) {
if (!empty($this->saved_site_offline_message)) {
variable_set('maintenance_mode_message', $this->saved_site_offline_message);
}
_backup_migrate_message('Site was taken online.');
}
_backup_migrate_message('Site was taken online.');
}
}
}
}
@@ -0,0 +1,529 @@
<?php
/**
* @file
* All of the location handling code needed for Backup and Migrate.
*/
require_once dirname(__FILE__) . '/crud.inc';
/**
* Get the available location types.
*/
function backup_migrate_get_location_subtypes() {
require_once dirname(__FILE__) . '/crud.inc';
require_once dirname(__FILE__) . '/destinations.inc';
require_once dirname(__FILE__) . '/sources.inc';
return backup_migrate_crud_subtypes('destination') + backup_migrate_crud_subtypes('source');
}
/**
* Implements hook_backup_migrate_locations().
*
* Get the built in backup locations and those in the db.
*/
function backup_migrate_backup_migrate_locations() {
require_once dirname(__FILE__) . '/filters.inc';
$out = array();
// Allow the filter plugins to declare the default locations.
$out += backup_migrate_filters_invoke_all('locations');
return $out;
}
/**
* Get all the available backup location.
*
* @param $op
* The operation which will be performed on the location. Hooks can use this
* to return only those locations appropriate for the given op.
* Options include:
* 'manual backup' - locations available for manual backup
* 'scheduled backup' - locations available for schedules backup
* 'list files' - locations whose backup files can be listed
* 'restore' - locations whose files can be restored from
* 'all' - all available locations should be returned
*/
function backup_migrate_get_locations($op = 'all') {
$locations = &drupal_static('backup_migrate_get_locations', NULL);
// Get the list of locations and cache them locally.
if ($locations === NULL) {
$locations = backup_migrate_crud_get_items('location');
}
// Return all if that's what was asked for.
if ($op == 'all') {
return $locations;
}
// Return only those locations which support the given op.
$out = array();
if ($locations) {
foreach ($locations as $key => $location) {
if ($location->op($op)) {
$out[$key] = $location;
}
}
}
return $out;
}
/**
* Get the location of the given id.
*/
function backup_migrate_get_location($id) {
$locations = backup_migrate_get_locations('all');
return empty($locations[$id]) ? NULL : $locations[$id];
}
/**
* A base class for creating locations.
*/
class backup_migrate_location extends backup_migrate_item {
public $db_table = "backup_migrate_destinations";
public $type_name = "location";
public $default_values = array('settings' => array());
public $singular = 'location';
public $plural = 'locations';
public $title_plural = 'Locations';
public $title_singular = 'Location';
public $subtype = "";
public $supported_ops = array();
/**
* This function is not supposed to be called. It is just here to help the po extractor out.
*/
public function strings() {
// Help the pot extractor find these strings.
t('location');
t('locations');
t('Location');
t('Locations');
}
/**
*
*/
public function ops() {
return $this->supported_ops;
}
/**
* Does this location support the given operation.
*/
public function op($op) {
$ops = (array) $this->ops();
return in_array($op, $ops);
}
/**
* Remove the given op from the support list.
*/
public function remove_op($op) {
$key = array_search($op, $this->supported_ops);
if ($key !== FALSE) {
unset($this->supported_ops[$key]);
}
}
/**
*
*/
public function get_name() {
return @$this->name;
}
/**
*
*/
public function set_name($name) {
return $this->name = $name;
}
/**
*
*/
public function set_location($location) {
$this->location = $location;
}
/**
*
*/
public function get_location() {
return @$this->location;
}
/**
*
*/
public function get_display_location() {
return $this->get_location();
}
/**
*
*/
public function settings($key = NULL) {
$out = $this->settings;
if ($key) {
$out = isset($out[$key]) ? $out[$key] : NULL;
}
return $out;
}
/**
* Get the type name of this location for display to the user.
*/
public function get_subtype_name() {
if ($type = $this->get('subtype')) {
$types = $this->location_types();
return isset($types[$type]['type_name']) ? $types[$type]['type_name'] : $type;
}
}
/**
* Get the edit form for the item.
*/
public function edit_form() {
if (!empty($this->supported_ops)) {
$form = parent::edit_form();
$form['subtype'] = array(
"#type" => "value",
"#default_value" => $this->get('subtype'),
);
}
else {
$types = $this->location_types();
$items = array();
// If no (valid) node type has been provided, display a node type overview.
foreach ($types as $key => $type) {
if (@$type['can_create']) {
$type_url_str = str_replace('_', '-', $key);
$out = '<dt>' . l($type['type_name'], BACKUP_MIGRATE_MENU_PATH . "/settings/$this->type_name/add/$type_url_str", array('attributes' => array('title' => t('Add a new @s location.', array('@s' => $type['type_name']))))) . '</dt>';
$out .= '<dd>' . filter_xss_admin($type['description']) . '</dd>';
$items[] = $out;
}
}
if (count($items)) {
$output = t('Choose the type of location you would like to create:') . '<dl>' . implode('', $items) . '</dl>';
}
else {
$output = t('No types available.');
}
$form['select_type'] = array(
'#type' => 'markup',
'#markup' => $output,
);
}
return $form;
}
/**
* Get the available location types.
*/
public function location_types() {
return backup_migrate_get_location_subtypes();
}
/**
* Get the message to send to the user when confirming the deletion of the item.
*/
public function delete_confirm_message() {
return t('Are you sure you want to delete the %name?', array('%name' => $this->get_name()));
}
/**
* Get the columns needed to list the type.
*/
public function get_list_column_info() {
$out = parent::get_list_column_info();
$out = array(
'name' => array('title' => t('Name')),
'subtype_name' => array('title' => t('Type')),
'display_location' => array('title' => t('Location')),
) + $out;
return $out;
}
/**
* Get a row of data to be used in a list of items of this type.
*/
public function get_list_row() {
$out = parent::get_list_row();
// Suppress locations with no actions as there's no value in showing them (and they may confuse new users).
if (empty($out['actions'])) {
return NULL;
}
return $out;
}
/**
* Get the action links for a location.
*/
public function get_action_links() {
$out = parent::get_action_links();
$item_id = $this->get_id();
// Don't display the download/delete/restore ops if they are not available for this location.
if ($this->op('list files') && user_access("access backup files")) {
$out = array('list files' => l(t("list files"), BACKUP_MIGRATE_MENU_PATH . "/$this->type_name/list/files/" . $item_id)) + $out;
}
if (!$this->op('configure') || !user_access('administer backup and migrate')) {
unset($out['edit']);
}
return $out;
}
/**
* Determine if we can read the given file.
*/
public function can_read_file($file_id) {
return $this->op('restore');
}
/**
* Get the form for the settings for this location type.
*/
public function settings_default() {
return array();
}
/**
* Get the form for the settings for this location.
*/
public function settings_form($form) {
return $form;
}
/**
* Validate the form for the settings for this location.
*/
public function settings_form_validate($form_values) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
public function settings_form_submit($form_values) {
return $form_values;
}
/**
* Get the form for the settings for this filter.
*/
public function backup_settings_default() {
return array();
}
/**
* Get the form for the settings for this filter.
*/
public function backup_settings_form($settings) {
return array();
}
/**
* Get the form for the settings for this filter.
*/
public function backup_settings_form_validate($form, &$form_state) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
public function backup_settings_form_submit($form, &$form_state) {
}
/**
* Get the form for the settings for this filter.
*/
public function restore_settings_default() {
return array();
}
/**
* Get the form for the settings for this filter.
*/
public function restore_settings_form($settings) {
return array();
}
/**
* Get the form for the settings for this filter.
*/
public function restore_settings_form_validate($form_values) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
public function restore_settings_form_submit($form_values) {
return $form_values;
}
/**
* Create a new location of the correct type.
*/
public function create($params = array()) {
$out = NULL;
$types = backup_migrate_get_location_subtypes();
// Get the type passed in in the params, or if none, check the url for a valid type name.
// This is to allow new location type to be specified in the path.
$location_type = !empty($params['subtype']) ? $params['subtype'] : NULL;
if ($location_type && ($type = @$types[$location_type])) {
// Include the necessary file if specified by the type.
if (!empty($type['file'])) {
require_once './' . $type['file'];
}
$out = new $type['class']($params + array('subtype' => $location_type));
}
if (empty($out)) {
$out = parent::create($params);
}
return $out;
}
/**
* Get a url from the parts.
*/
public function url($hide_password = TRUE) {
return $this->glue_url($this->dest_url, $hide_password);
}
/**
* Glue a URLs component parts back into a URL.
*/
public function glue_url($parts, $hide_password = TRUE) {
// Obscure the password if we need to.
$parts['pass'] = $hide_password ? "" : $parts['pass'];
// Assemble the URL.
$out = "";
$out .= $parts['scheme'] . '://';
$out .= $parts['user'] ? urlencode($parts['user']) : '';
$out .= ($parts['user'] && $parts['pass']) ? ":" . urlencode($parts['pass']) : '';
$out .= ($parts['user'] || $parts['pass']) ? "@" : "";
$out .= $parts['host'];
$out .= !empty($parts['port']) ? ':' . $parts['port'] : '';
$out .= "/" . $parts['path'];
return $out;
}
/**
* Break a URL into it's component parts.
*/
public function set_url($url) {
$parts = (array) parse_url($url);
$parts['user'] = urldecode(@$parts['user']);
$parts['pass'] = urldecode(@$parts['pass']);
$parts['path'] = urldecode(@$parts['path']);
$parts['path'] = ltrim(@$parts['path'], "/");
$this->dest_url = $parts;
}
/**
* Retrieve a list of filetypes supported by this source/destination.
*/
public function file_types() {
return array();
}
}
/**
* A base class for creating locations.
*/
class backup_migrate_location_remote extends backup_migrate_location {
/**
* The location is a URI so parse it and store the parts.
*/
public function get_location() {
return $this->url(FALSE);
}
/**
* The location to display is the url without the password.
*/
public function get_display_location() {
return $this->url(TRUE);
}
/**
* Return the location with the password.
*/
public function set_location($location) {
$this->location = $location;
$this->set_url($location);
}
/**
* Location configuration callback.
*/
public function edit_form() {
$form = parent::edit_form();
$form['scheme'] = array(
"#type" => "select",
"#title" => t("Scheme"),
"#default_value" => @$this->dest_url['scheme'] ? $this->dest_url['scheme'] : 'mysql',
"#required" => TRUE,
"#options" => array($GLOBALS['db_type'] => $GLOBALS['db_type']),
"#weight" => 0,
);
$form['host'] = array(
"#type" => "textfield",
"#title" => t("Host"),
"#default_value" => @$this->dest_url['host'] ? $this->dest_url['host'] : 'localhost',
"#required" => TRUE,
"#weight" => 10,
);
$form['path'] = array(
"#type" => "textfield",
"#title" => t("Path"),
"#default_value" => @$this->dest_url['path'],
"#required" => TRUE,
"#weight" => 20,
);
$form['user'] = array(
"#type" => "textfield",
"#title" => t("Username"),
"#default_value" => @$this->dest_url['user'],
"#required" => TRUE,
"#weight" => 30,
);
$form['pass'] = array(
"#type" => "password",
"#title" => t("Password"),
"#default_value" => @$this->dest_url['pass'],
'#description' => '',
"#weight" => 40,
);
if (@$this->dest_url['pass']) {
$form['old_password'] = array(
"#type" => "value",
"#value" => @$this->dest_url['pass'],
);
$form['pass']["#description"] .= t(' You do not need to enter a password unless you wish to change the currently saved password.');
}
return $form;
}
/**
* Submit the configuration form. Glue the url together and add the old password back if a new one was not specified.
*/
public function edit_form_submit($form, &$form_state) {
$form_state['values']['pass'] = $form_state['values']['pass'] ? $form_state['values']['pass'] : $form_state['values']['old_password'];
$form_state['values']['location'] = $this->glue_url($form_state['values'], FALSE);
parent::edit_form_submit($form, $form_state);
}
}
@@ -1,19 +1,35 @@
<?php
/**
* @file
* All of the settings profiles handling code for Backup and Migrate.
*/
backup_migrate_include('crud');
require_once dirname(__FILE__) . '/crud.inc';
/**
* Implements hook_backup_migrate_profile_subtypes().
*
* Get the built in Backup and Migrate profile types.
*/
function backup_migrate_backup_migrate_profile_subtypes() {
$out = array(
'backup' => array(
'include' => 'profiles',
'type_name' => t('Backup Settings Profile'),
'class' => 'backup_migrate_profile',
),
);
return $out;
}
/**
* Get all the available backup profiles.
*/
function backup_migrate_get_profiles() {
backup_migrate_include('filters');
static $profiles = NULL;
require_once dirname(__FILE__) . '/filters.inc';
$profiles = &drupal_static('backup_migrate_get_profiles', NULL);
// Get the list of profiles and cache them locally.
if ($profiles === NULL) {
@@ -23,14 +39,14 @@ function backup_migrate_get_profiles() {
}
/**
* Implementation of hook_backup_migrate_profiles_alter().
* Implements hook_backup_migrate_profiles_alter().
*
* Add default settings for any plugins which didn't exist when the profile was saved.
*/
function backup_migrate_backup_migrate_profiles_alter(&$profiles) {
foreach ($profiles as $id => $profile) {
// Set the default values for filter setting which don't exist in the profile.
$profiles[$id]->filters = (array)@$profile->filters + (array)backup_migrate_filters_settings_default('backup');
$profiles[$id]->filters = (array) @$profile->filters + (array) backup_migrate_filters_settings_default('backup');
}
}
@@ -43,13 +59,13 @@ function backup_migrate_get_profile($profile_id) {
}
/**
* Implementation of hook_backup_migrate_profiles().
* Implements hook_backup_migrate_profiles().
*/
function backup_migrate_backup_migrate_profiles() {
$out = array();
// Get the module default profile.
$out['default'] = backup_migrate_crud_create_item('profile', array('name' => t("Default Settings"), 'profile_id' => 'default'));
$out['default'] = backup_migrate_crud_create_item('profile', array('name' => t("Default Settings"), 'machine_name' => 'default'));
return $out;
}
@@ -61,7 +77,7 @@ function backup_migrate_backup_migrate_profiles() {
*/
function _backup_migrate_get_profile_form_item_options() {
$out = array();
foreach ((array)backup_migrate_get_profiles() as $key => $profile) {
foreach ((array) backup_migrate_get_profiles() as $key => $profile) {
$out[$key] = $profile->get('name');
}
return $out;
@@ -71,13 +87,15 @@ function _backup_migrate_get_profile_form_item_options() {
* Get a form to configure the profile.
*/
function _backup_migrate_ui_backup_settings_form($profile) {
require_once dirname(__FILE__) . '/destinations.inc';
require_once dirname(__FILE__) . '/files.inc';
require_once dirname(__FILE__) . '/filters.inc';
drupal_add_js(array('backup_migrate' => array('checkboxLinkText' => t('View as checkboxes'))), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js', array('type' => 'file', 'scope' => 'footer'));
drupal_add_css(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.css');
drupal_add_js(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.js', array('type' => 'file', 'scope' => 'footer'));
drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
backup_migrate_include('files', 'destinations', 'filters');
$form = array();
$form = array();
$form['file'] = array(
"#type" => "fieldset",
@@ -92,8 +110,6 @@ function _backup_migrate_ui_backup_settings_form($profile) {
"#default_value" => $profile->filename,
);
if (module_exists('token')) {
$form['file']['filename']['#description'] = t('You can use tokens in the file name.');
$form['file']['token_help'] = array(
'#title' => t('Replacement patterns'),
'#type' => 'fieldset',
@@ -105,14 +121,26 @@ function _backup_migrate_ui_backup_settings_form($profile) {
'#token_types' => array('current-date', 'site'),
'#global_types' => FALSE,
);
$form['file']['filename']['#description'] = t('You can use tokens in the file name.');
}
$form['file']['append_timestamp'] = array(
"#type" => "checkbox",
"#title" => t("Append a timestamp."),
"#type" => "radios",
'#options' => array(
0 => t('Create separate backups if `Backup file name` already exists'),
2 => t('Overwrite the existing backup file'),
1 => t('Append the timestamp'),
),
"#title" => t("Save mode"),
"#default_value" => $profile->append_timestamp,
);
$form['file']['timestamp_format'] = array(
$form['file']['timestamp_format_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'append_timestamp' => 1,
),
);
$form['file']['timestamp_format_wrapper']['timestamp_format'] = array(
"#type" => "textfield",
"#title" => t("Timestamp format"),
"#default_value" => $profile->timestamp_format,
@@ -126,12 +154,12 @@ function _backup_migrate_ui_backup_settings_form($profile) {
if ($form['advanced']) {
$form['advanced']['#type'] = 'fieldset';
$form['advanced']['#title'] = t('Advanced Options');
$form['advanced']['#collapsed'] = true;
$form['advanced']['#collapsible'] = true;
$form['advanced']['#collapsed'] = TRUE;
$form['advanced']['#collapsible'] = TRUE;
}
$form['#validate'][] = '_backup_migrate_ui_backup_settings_form_validate';
$form['#submit'][] = '_backup_migrate_ui_backup_settings_form_submit';
$form['#validate'][] = '_backup_migrate_ui_backup_settings_form_validate';
$form['#submit'][] = '_backup_migrate_ui_backup_settings_form_submit';
return $form;
}
@@ -149,12 +177,14 @@ function _backup_migrate_ui_backup_settings_form_validate($form, &$form_state) {
function _backup_migrate_ui_backup_settings_form_submit($form, &$form_state) {
backup_migrate_filters_settings_form_submit('backup', $form, $form_state);
}
/**
* Get the default profile.
*/
function _backup_migrate_profile_default_profile() {
backup_migrate_include('files', 'filters');
require_once dirname(__FILE__) . '/files.inc';
require_once dirname(__FILE__) . '/filters.inc';
return array(
'source_id' => 'db',
'filename' => _backup_migrate_default_filename(),
@@ -183,41 +213,62 @@ function _backup_migrate_profile_saved_default_profile($profile_id = NULL) {
* A profile class for crud operations.
*/
class backup_migrate_profile extends backup_migrate_item {
var $db_table = "backup_migrate_profiles";
var $type_name = "profile";
var $singular = 'profile';
var $plural = 'profiles';
public $db_table = "backup_migrate_profiles";
public $type_name = "profile";
public $singular = 'settings profile';
public $plural = 'settings profiles';
public $title_plural = 'Settings Profiles';
public $title_singular = 'Settings Profile';
/**
* Perform a shallow merge of the defaults and the parameters.
*
* This is needed because otherwise it will *combine* the nested arrays and
* make it impossible to deselect database tables from the 'nodata' setting.
*
* @param array $params
*/
public function __construct(array $params = array()) {
$params = (array) $params;
$defaults = (array) $this->get_default_values();
foreach ($defaults as $key => $val) {
if (!isset($params[$key])) {
$params[$key] = $val;
}
}
$this->from_array($params);
}
/**
* This function is not supposed to be called. It is just here to help the po extractor out.
*/
function strings() {
public function strings() {
// Help the pot extractor find these strings.
t('Profile');
t('Profiles');
t('profile');
t('profiles');
t('Settings Profile');
t('Settings Profiles');
t('settings profile');
t('settings profiles');
}
/**
* Get the default values for standard parameters.
*/
function get_default_values() {
public function get_default_values() {
return _backup_migrate_profile_default_profile() + array('name' => t("Untitled Profile"));
}
/**
* Get a table of all items of this type.
*/
function get_list() {
drupal_add_css(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.css');
*/
public function get_list() {
drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
return parent::get_list();
}
/**
* Get the columns needed to list the type.
*/
function get_list_column_info() {
*/
public function get_list_column_info() {
$out = parent::get_list_column_info();
$out = array(
'name' => array('title' => t('Name')),
@@ -227,23 +278,10 @@ class backup_migrate_profile extends backup_migrate_item {
return $out;
}
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
$row = parent::get_list_row();
if (empty($this->enabled)) {
foreach ($row as $key => $field) {
$row[$key] = array('data' => $field, 'class' => 'profile-list-disabled');
}
}
return $row;
}
/**
* Set the source of this setings profile. Takes either a source object or source id.
*/
function set_source($source) {
public function set_source($source) {
if (is_object($source)) {
$this->source = $source;
$this->source_id = $source->get_id();
@@ -257,10 +295,11 @@ class backup_migrate_profile extends backup_migrate_item {
/**
* Get the source of the profile.
*/
function get_source() {
backup_migrate_include('destinations');
if (!empty($this->source_id) && (empty($this->source) || $this->source->destination_id !== $this->source_id)) {
$this->source = backup_migrate_get_destination($this->source_id);
public function get_source() {
require_once dirname(__FILE__) . '/locations.inc';
if (!empty($this->source_id) && (empty($this->source) || $this->source->get_id() !== $this->source_id)) {
$this->source = backup_migrate_get_source($this->source_id);
}
return empty($this->source) ? NULL : $this->source;
}
@@ -268,7 +307,7 @@ class backup_migrate_profile extends backup_migrate_item {
/**
* Get the name of the source.
*/
function get_source_name() {
public function get_source_name() {
if ($source = $this->get_source()) {
return $source->get_name();
}
@@ -278,28 +317,64 @@ class backup_migrate_profile extends backup_migrate_item {
/**
* Get the destination of the profile.
*/
function get_destination() {
backup_migrate_include('destinations');
if (!empty($this->destination_id) && (empty($this->destination) || $this->destination->destination_id !== $this->destination_id)) {
$this->destination = backup_migrate_get_destination($this->destination_id);
public function get_destination() {
$destinations = (array) $this->get_destinations();
return reset($destinations);
}
/**
* Get the destination of the profile.
*/
public function get_destinations() {
require_once dirname(__FILE__) . '/destinations.inc';
if (empty($this->destinations)) {
$this->destinations = array();
$ids = $weights = array();
if (!empty($this->destination_id)) {
foreach ((array) $this->destination_id as $destination_id) {
if (!in_array($destination_id, $ids) && $destination = backup_migrate_get_destination($destination_id)) {
$this->destinations[] = $destination;
$weights[] = $destination->get('weight');
$ids[] = $destination_id;
}
}
}
// Sort the destinations by weight.
array_multisort($weights, SORT_NUMERIC, $this->destinations);
}
return empty($this->destination) ? NULL : $this->destination;
return $this->destinations;
}
/**
* Get the name of the destination.
*/
function get_destination_name() {
if ($destination = $this->get_destination()) {
return $destination->get_name();
public function get_destination_name() {
$out = array();
foreach ($this->get_destinations() as $destination) {
$out[] = $destination->get_name();
}
if ($out) {
return implode(', ', $out);
}
return t("Missing");
}
/**
* Get the source and destinations specified in the given settings profile.
*/
public function get_all_locations() {
$out = array();
$out += $this->get('destinations');
$out[] = $this->get('source');
return $out;
}
/**
* Get the edit form.
*/
function edit_form() {
public function edit_form() {
$form = parent::edit_form();
$form['name'] = array(
"#type" => "textfield",
@@ -314,8 +389,8 @@ class backup_migrate_profile extends backup_migrate_item {
/**
* Get the message to send to the user when confirming the deletion of the item.
*/
function delete_confirm_message() {
public function delete_confirm_message() {
return t('Are you sure you want to delete the profile %name? Any schedules using this profile will be disabled.', array('%name' => $this->get('name')));
}
}
}
@@ -5,24 +5,82 @@
* All of the schedule handling code needed for Backup and Migrate.
*/
backup_migrate_include('crud');
define('BACKUP_MIGRATE_KEEP_ALL', 0);
define('BACKUP_MIGRATE_STANDARD_DELETE', -1);
define('BACKUP_MIGRATE_SMART_DELETE', -2);
define('BACKUP_MIGRATE_CRON_BUILTIN', 'builtin');
define('BACKUP_MIGRATE_CRON_ELYSIA', 'elysia');
define('BACKUP_MIGRATE_CRON_NONE', 'none');
define('BACKUP_MIGRATE_SMART_KEEP_SUBHOURLY', 3600);
define('BACKUP_MIGRATE_SMART_KEEP_HOURLY', 24);
define('BACKUP_MIGRATE_SMART_KEEP_DAILY', 30);
define('BACKUP_MIGRATE_SMART_KEEP_WEEKLY', PHP_INT_MAX);
define('BACKUP_MIGRATE_KEEP_DEFAULT', 100);
require_once dirname(__FILE__) . '/crud.inc';
/**
* Implements hook_backup_migrate_destination_types().
*
* Get the built in Backup and Migrate destination types.
*/
function backup_migrate_backup_migrate_schedule_types() {
$out = array();
$out += array(
'backup' => array(
'include' => 'schedule',
'type_name' => t('Backup Schedule'),
'class' => 'backup_migrate_schedule',
),
);
return $out;
}
/**
* Run the preconfigured schedules. Called on cron.
*/
function backup_migrate_schedules_run() {
backup_migrate_include('profiles');
function backup_migrate_schedules_cron() {
require_once dirname(__FILE__) . '/profiles.inc';
foreach (backup_migrate_get_schedules() as $schedule) {
$schedule->cron();
}
backup_migrate_cleanup();
}
/**
* Run the preconfigured schedules regardless of scheduled time settings.
*/
function backup_migrate_schedules_run() {
require_once dirname(__FILE__) . '/profiles.inc';
foreach (backup_migrate_get_schedules() as $schedule) {
$schedule->run();
}
backup_migrate_cleanup();
}
/**
* Run the preconfigured schedules. Called on cron.
*/
function backup_migrate_schedule_run($schedule_id) {
require_once dirname(__FILE__) . '/profiles.inc';
if (($schedule = backup_migrate_get_schedule($schedule_id)) && $schedule->is_enabled()) {
$schedule->run();
}
backup_migrate_cleanup();
}
/**
* Get all the available backup schedules.
*/
function backup_migrate_get_schedules() {
static $schedules = NULL;
$schedules = &drupal_static('backup_migrate_get_schedules');
// Get the list of schedules and cache them locally.
if ($schedules === NULL) {
$schedules = backup_migrate_crud_get_items('schedule');
@@ -42,16 +100,18 @@ function backup_migrate_get_schedule($schedule_id) {
* A schedule class for crud operations.
*/
class backup_migrate_schedule extends backup_migrate_item {
var $db_table = "backup_migrate_schedules";
var $type_name = 'schedule';
var $singular = 'schedule';
var $plural = 'schedules';
var $default_values = array();
public $db_table = "backup_migrate_schedules";
public $type_name = 'schedule';
public $singular = 'schedule';
public $plural = 'schedules';
public $title_plural = 'Schedules';
public $title_singular = 'Schedule';
public $default_values = array();
/**
* This function is not supposed to be called. It is just here to help the po extractor out.
*/
function strings() {
public function strings() {
// Help the pot extractor find these strings.
t('Schedule');
t('Schedules');
@@ -62,25 +122,36 @@ class backup_migrate_schedule extends backup_migrate_item {
/**
* Get the default values for this item.
*/
function get_default_values() {
public function get_default_values() {
return array(
'name' => t("Untitled Schedule"),
'source_id' => 'db',
'enabled' => 1,
'keep' => 0,
'period' => 60 * 60 * 24,
'storage' => BACKUP_MIGRATE_STORAGE_NONE
);
'name' => t("Untitled Schedule"),
'source_id' => 'db',
'enabled' => 1,
'keep' => BACKUP_MIGRATE_KEEP_ALL,
'period' => 60 * 60 * 24,
'storage' => BACKUP_MIGRATE_STORAGE_NONE,
'cron' => BACKUP_MIGRATE_CRON_BUILTIN,
'cron_schedule' => '0 4 * * *',
);
}
/**
* Return as an array of values.
*/
public function to_array() {
$out = parent::to_array();
unset($out['last_run']);
return $out;
}
/**
* Get the columns needed to list the type.
*/
function get_list_column_info() {
*/
public function get_list_column_info() {
$out = parent::get_list_column_info();
$out = array(
'name' => array('title' => t('Name')),
'destination_name' => array('title' => t('Destination'), 'html' => TRUE),
'destination_name' => array('title' => t('Destinations'), 'html' => TRUE),
'profile_name' => array('title' => t('Profile'), 'html' => TRUE),
'frequency_description' => array('title' => t('Frequency')),
'keep_description' => array('title' => t('Keep')),
@@ -90,15 +161,40 @@ class backup_migrate_schedule extends backup_migrate_item {
return $out;
}
/**
* Get the columns needed to list the type.
*/
public function get_settings_path() {
// Pull the schedules tab up a level to the top.
return BACKUP_MIGRATE_MENU_PATH . '/' . $this->type_name;
}
/**
* Get the menu items for manipulating this type.
*/
public function get_menu_items() {
$items = parent::get_menu_items();
$path = $this->get_settings_path();
return $items;
}
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
drupal_add_css(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.css');
public function get_list_row() {
drupal_add_css(drupal_get_path('module', 'backup_migrate') . '/backup_migrate.css');
$row = parent::get_list_row();
if (!$this->is_enabled()) {
foreach ($row as $key => $field) {
$row[$key] = array('data' => $field, 'class' => 'schedule-list-disabled');
if (!is_array($field)) {
$row[$key] = array('data' => $field, 'class' => 'schedule-list-disabled');
}
elseif (isset($row[$key]['class'])) {
$row[$key]['class'] .= ' schedule-list-disabled';
}
else {
$row[$key]['class'] = 'schedule-list-disabled';
}
}
}
return $row;
@@ -107,7 +203,7 @@ class backup_migrate_schedule extends backup_migrate_item {
/**
* Is the schedule enabled and valid.
*/
function is_enabled() {
public function is_enabled() {
$destination = $this->get_destination();
$profile = $this->get_profile();
return (!empty($this->enabled) && !empty($destination) && !empty($profile));
@@ -116,66 +212,167 @@ class backup_migrate_schedule extends backup_migrate_item {
/**
* Get the destination object of the schedule.
*/
function get_destination() {
backup_migrate_include('destinations');
return backup_migrate_get_destination($this->get('destination_id'));
public function get_destination() {
$destinations = (array) $this->get_destinations();
return reset($destinations);
}
/**
* Get the destination object of the schedule.
*/
public function get_destination_ids() {
$out = array();
foreach (array('destination_id', 'copy_destination_id') as $key) {
if ($id = $this->get($key)) {
$out[$key] = $id;
}
}
return $out;
}
/**
* Get the destination object of the schedule.
*/
public function get_destinations() {
require_once dirname(__FILE__) . '/destinations.inc';
$out = array();
foreach ($this->get_destination_ids() as $id) {
if ($dest = backup_migrate_get_destination($id)) {
$out[$id] = $dest;
}
}
return $out;
}
/**
* Get the destination object of the schedule.
*/
public function get_destination_remote() {
require_once dirname(__FILE__) . '/destinations.inc';
return backup_migrate_get_destination($this->get('destination_remote_id'));
}
/**
* Get the destination object of the schedule.
*/
public function get_destination_local() {
require_once dirname(__FILE__) . '/destinations.inc';
return backup_migrate_get_destination($this->get('destination_local_id'));
}
/**
* Get the name of the destination.
*/
function get_destination_name() {
if ($destination = $this->get_destination()) {
return check_plain($destination->get_name());
public function get_destination_name() {
if ($destinations = $this->get_destinations()) {
$out = array();
foreach ((array) $destinations as $destination) {
$out[] = check_plain($destination->get_name());
}
return implode(', ', $out);
}
return '<div class="row-error">'. t("Missing") .'</div>';
return '<div class="row-error">' . t("Missing") . '</div>';
}
/**
* Get the destination of the schedule.
*/
function get_profile() {
backup_migrate_include('profiles');
return backup_migrate_get_profile($this->get('profile_id'));
public function get_profile() {
require_once dirname(__FILE__) . '/profiles.inc';
if ($settings = backup_migrate_get_profile($this->get('profile_id'))) {
$settings->file_info = empty($settings->file_info) ? array() : $settings->file_info;
$settings->file_info += array(
'schedule_id' => $this->get_id(),
'schedule_name' => $this->get('name'),
);
}
return $settings;
}
/**
* Get the name of the source.
*/
function get_profile_name() {
public function get_profile_name() {
if ($profile = $this->get_profile()) {
return check_plain($profile->get_name());
}
return '<div class="row-error">'. t("Missing") .'</div>';
return '<div class="row-error">' . t("Missing") . '</div>';
}
/**
* Format a frequency in human-readable form.
*/
function get_frequency_description() {
public function get_frequency_description() {
$period = $this->get_frequency_period();
$out = format_plural(($this->period / $period['seconds']), $period['singular'], $period['plural']);
$cron = $this->get('cron');
if ($cron == BACKUP_MIGRATE_CRON_BUILTIN) {
$out = format_plural(($this->period / $period['seconds']), $period['singular'], $period['plural']);
}
elseif ($cron == BACKUP_MIGRATE_CRON_ELYSIA) {
$out = $this->get('cron_schedule');
}
else {
$out = t('None');
}
return $out;
}
/**
* Format the number to keep in human-readable form.
*/
function get_keep_description() {
return !empty($this->keep) ? $this->keep : t('All');
public function get_keep_description() {
return $this->generate_keep_description($this->keep);
}
/**
* Format a number to keep in human readable from.
*/
public function generate_keep_description($keep, $terse = TRUE) {
if ($keep == BACKUP_MIGRATE_KEEP_ALL) {
return t('all backups');
}
elseif ($keep == BACKUP_MIGRATE_SMART_DELETE) {
$keep_hourly = variable_get('backup_migrate_smart_keep_hourly', BACKUP_MIGRATE_SMART_KEEP_HOURLY);
$keep_daily = variable_get('backup_migrate_smart_keep_daily', BACKUP_MIGRATE_SMART_KEEP_DAILY);
$keep_weekly = variable_get('backup_migrate_smart_keep_weekly', BACKUP_MIGRATE_SMART_KEEP_WEEKLY);
if ($terse) {
return t('!hours hourly, !days daily, !weeks weekly backups',
array(
'!hours' => $keep_hourly == PHP_INT_MAX ? t('all') : $keep_hourly,
'!days' => $keep_daily == PHP_INT_MAX ? t('all') : $keep_daily,
'!weeks' => $keep_weekly == PHP_INT_MAX ? t('all') : $keep_weekly,
));
}
else {
return t('hourly backups !hours, daily backups !days and weekly backups !weeks',
array(
'!hours' => $keep_hourly == PHP_INT_MAX ? t('forever') : format_plural($keep_hourly, 'for 1 hour', 'for the past @count hours'),
'!days' => $keep_daily == PHP_INT_MAX ? t('forever') : format_plural($keep_daily, 'for 1 day', 'for the past @count days'),
'!weeks' => $keep_weekly == PHP_INT_MAX ? t('forever') : format_plural($keep_weekly, 'for 1 week', 'for the past @count weeks'),
)
);
}
}
return format_plural($keep, 'last 1 backup', 'last @count backups');
}
/**
* Format the enabled status in human-readable form.
*/
function get_enabled_description() {
public function get_enabled_description() {
return !empty($this->enabled) ? t('Enabled') : t('Disabled');
}
/**
* Format the enabled status in human-readable form.
*/
function get_last_run_description() {
public function get_last_run_description() {
$last_run = $this->get('last_run');
return !empty($last_run) ? format_date($last_run, 'small') : t('Never');
}
@@ -183,29 +380,27 @@ class backup_migrate_schedule extends backup_migrate_item {
/**
* Get the number of excluded tables.
*/
function get_exclude_tables_count() {
public function get_exclude_tables_count() {
return count($this->exclude_tables) ? count($this->exclude_tables) : t("No tables excluded");
}
/**
* Get the number of excluded tables.
*/
function get_nodata_tables_count() {
public function get_nodata_tables_count() {
return count($this->nodata_tables) ? count($this->nodata_tables) : t("No data omitted");
}
/**
* Get the edit form.
*/
function edit_form() {
$form = parent::edit_form();
backup_migrate_include('destinations', 'profiles');
public function edit_form() {
require_once dirname(__FILE__) . '/destinations.inc';
require_once dirname(__FILE__) . '/sources.inc';
require_once dirname(__FILE__) . '/profiles.inc';
$form = parent::edit_form();
$form['enabled'] = array(
"#type" => "checkbox",
"#title" => t("Enabled"),
"#default_value" => $this->get('enabled'),
);
$form['name'] = array(
"#type" => "textfield",
"#title" => t("Schedule Name"),
@@ -220,7 +415,7 @@ class backup_migrate_schedule extends backup_migrate_item {
"#options" => _backup_migrate_get_profile_form_item_options(),
"#default_value" => $this->get('profile_id'),
);
$form['profile_id']['#description'] = ' '. l(t("Create new profile"), BACKUP_MIGRATE_MENU_PATH . "/profile/add");
$form['profile_id']['#description'] = ' ' . l(t('Create new profile'), BACKUP_MIGRATE_MENU_PATH . '/settings/profile/add');
if (!$form['profile_id']['#options']) {
$form['profile_id']['#options'] = array('0' => t('-- None Available --'));
}
@@ -232,40 +427,138 @@ class backup_migrate_schedule extends backup_migrate_item {
$default_period = $this->get_frequency_period();
$default_period_num = $this->get('period') / $default_period['seconds'];
$form['period'] = array(
$form['enabled'] = array(
'#type' => "checkbox",
'#title' => t('Enabled'),
'#default_value' => $this->get('enabled'),
);
$form['cron_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'enabled' => TRUE,
),
);
$cron = $this->get('cron');
$form['cron_settings']['cron_builtin'] = array(
"#type" => "radio",
"#title" => t('Run using Drupal\'s cron'),
'#return_value' => BACKUP_MIGRATE_CRON_BUILTIN,
"#description" => t('Run this schedule when !cron runs.', array('!cron' => l(t('your cron task'), 'http://drupal.org/cron'))),
"#default_value" => $cron ? $cron : BACKUP_MIGRATE_CRON_BUILTIN,
'#parents' => array('cron'),
);
$form['cron_settings']['period_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'cron' => BACKUP_MIGRATE_CRON_BUILTIN,
),
);
$form['cron_settings']['period_settings']['period'] = array(
"#type" => "item",
"#title" => t("Backup every"),
"#prefix" => '<div class="container-inline">',
"#suffix" => '</div>',
"#tree" => TRUE,
'#parents' => array('period'),
);
$form['period']['number'] = array(
$form['cron_settings']['period_settings']['period']['number'] = array(
"#type" => "textfield",
"#size" => 6,
"#default_value" => $default_period_num,
'#parents' => array('period', 'number'),
);
$form['period']['type'] = array(
$form['cron_settings']['period_settings']['period']['type'] = array(
"#type" => "select",
"#options" => $period_options,
"#default_value" => $default_period['type'],
'#parents' => array('period', 'type'),
);
$form['keep'] = array(
$form['cron_settings']['cron_elysia'] = array(
"#type" => "radio",
"#title" => t('Run using Elysia cron'),
'#return_value' => BACKUP_MIGRATE_CRON_ELYSIA,
"#description" => t('You can specify exactly when this schedule should run using !elysia.', array('!elysia' => l(t('the Elysia Cron module'), 'http://drupal.org/project/elysia_cron'))),
"#default_value" => $cron ? $cron : BACKUP_MIGRATE_CRON_BUILTIN,
'#parents' => array('cron'),
);
if (!module_exists('elysia_cron') && !module_exists('ultimate_cron')) {
$form['cron_settings']['cron_elysia']['#disabled'] = TRUE;
$form['cron_settings']['cron_elysia']['#description'] .= ' ' . t('Install !elysia to enable this option.', array('!elysia' => l(t('Elysia Cron'), 'http://drupal.org/project/elysia_cron')));
}
$form['cron_settings']['cron_schedule_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'cron' => BACKUP_MIGRATE_CRON_ELYSIA,
),
);
$form['cron_settings']['cron_schedule_settings']['cron_schedule'] = array(
"#type" => "textfield",
"#title" => t('Cron Schedule'),
'#length' => 10,
"#description" => t('Specify the frequency of the schedule using standard cron notation. For more information see the !elysiareadme.', array('!elysiareadme' => l(t('the Elysia Cron README'), 'http://drupalcode.org/project/elysia_cron.git/blob/refs/heads/7.x-1.x:/README.txt'))),
"#default_value" => $this->get('cron_schedule'),
'#parents' => array('cron_schedule'),
);
$form['cron_settings']['cron_none'] = array(
"#type" => "radio",
"#title" => t('Do not run automatically'),
'#return_value' => 'none',
"#description" => t('Do not run this schedule automatically. You can still run it using !drush.', array('!drush' => l(t('Drush'), 'http://drupal.org/project/drush'))),
"#default_value" => $cron ? $cron : BACKUP_MIGRATE_CRON_BUILTIN,
'#parents' => array('cron'),
);
$keep = $this->get('keep');
$form['delete'] = array(
'#type' => 'checkbox',
'#default_value' => $keep != 0,
'#title' => t('Automatically delete old backups'),
);
$form['delete_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'delete' => TRUE,
),
);
$keep_hourly = variable_get('backup_migrate_smart_keep_hourly', BACKUP_MIGRATE_SMART_KEEP_HOURLY);
$keep_daily = variable_get('backup_migrate_smart_keep_daily', BACKUP_MIGRATE_SMART_KEEP_DAILY);
$keep_weekly = variable_get('backup_migrate_smart_keep_weekly', BACKUP_MIGRATE_SMART_KEEP_WEEKLY);
$form['delete_settings']['smartdelete'] = array(
"#type" => "radio",
"#title" => t('Smart Delete'),
'#return_value' => BACKUP_MIGRATE_SMART_DELETE,
"#description" => t('Keep !keep. <strong>Recommended</strong>', array('!keep' => $this->generate_keep_description(BACKUP_MIGRATE_SMART_DELETE, FALSE))),
"#default_value" => $keep ? $keep : BACKUP_MIGRATE_SMART_DELETE,
'#parents' => array('deletetype'),
);
$form['delete_settings']['standarddelete'] = array(
"#type" => "radio",
"#title" => t('Simple Delete'),
'#return_value' => BACKUP_MIGRATE_STANDARD_DELETE,
"#description" => t("Keep a specified number of files deleting the oldest ones first."),
"#default_value" => $keep > 0 ? BACKUP_MIGRATE_STANDARD_DELETE : 0,
'#parents' => array('deletetype'),
);
$form['delete_settings']['keep-settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'deletetype' => BACKUP_MIGRATE_STANDARD_DELETE,
),
);
$form['delete_settings']['keep-settings']['keep'] = array(
"#type" => "textfield",
"#size" => 6,
"#title" => t("Number of Backup files to keep"),
"#description" => t("The number of backup files to keep before deleting old ones. Use 0 to never delete backups. <strong>Other files in the destination directory will get deleted if you specify a limit.</strong>"),
"#default_value" => $this->get('keep'),
"#description" => t("The number of backup files to keep before deleting old ones."),
"#default_value" => $keep > 0 ? $keep : BACKUP_MIGRATE_KEEP_DEFAULT,
);
$destination_options = _backup_migrate_get_destination_form_item_options('scheduled backup');
$form['destination_id'] = array(
"#type" => "select",
"#title" => t("Destination"),
"#description" => t("Choose where the backup file will be saved. Backup files contain sensitive data, so be careful where you save them."),
"#options" => $destination_options,
"#default_value" => $this->get('destination_id'),
);
$form['destination_id']['#description'] .= ' '. l(t("Create new destination"), BACKUP_MIGRATE_MENU_PATH . "/destination/add");
$form['destination'] = _backup_migrate_get_destination_pulldown('scheduled backup', $this->get('destination_id'), $this->get('copy_destination_id'));
return $form;
}
@@ -273,12 +566,19 @@ class backup_migrate_schedule extends backup_migrate_item {
/**
* Submit the edit form.
*/
function edit_form_validate($form, &$form_state) {
public function edit_form_validate($form, &$form_state) {
if (!is_numeric($form_state['values']['period']['number']) || $form_state['values']['period']['number'] <= 0) {
form_set_error('period][number', t('Backup period must be a number greater than 0.'));
}
if (!is_numeric($form_state['values']['keep']) || $form_state['values']['keep'] < 0) {
form_set_error('keep', t('Number to keep must be an integer greater than or equal to 0.'));
if (!$form_state['values']['delete']) {
$form_state['values']['keep'] = 0;
}
elseif ($form_state['values']['deletetype'] == BACKUP_MIGRATE_SMART_DELETE) {
$form_state['values']['keep'] = BACKUP_MIGRATE_SMART_DELETE;
}
elseif (!is_numeric($form_state['values']['keep']) || $form_state['values']['keep'] <= 0) {
form_set_error('keep', t('Number to keep must be a number greater than 0.'));
}
parent::edit_form_validate($form, $form_state);
}
@@ -286,7 +586,7 @@ class backup_migrate_schedule extends backup_migrate_item {
/**
* Submit the edit form.
*/
function edit_form_submit($form, &$form_state) {
public function edit_form_submit($form, &$form_state) {
$periods = $this->frequency_periods();
$period = $periods[$form_state['values']['period']['type']];
$form_state['values']['period'] = $form_state['values']['period']['number'] * $period['seconds'];
@@ -294,9 +594,9 @@ class backup_migrate_schedule extends backup_migrate_item {
}
/**
* Get the period of the frequency (ie: seconds, minutes etc.)
* Get the period of the frequency (ie: seconds, minutes etc.).
*/
function get_frequency_period() {
public function get_frequency_period() {
foreach (array_reverse($this->frequency_periods()) as $period) {
if ($period['seconds'] && ($this->period % $period['seconds']) === 0) {
return $period;
@@ -308,7 +608,7 @@ class backup_migrate_schedule extends backup_migrate_item {
* Get a list of available backup periods. Only returns time periods which have a
* (reasonably) consistent number of seconds (ie: no months).
*/
function frequency_periods() {
public function frequency_periods() {
return array(
'seconds' => array('type' => 'seconds', 'seconds' => 1, 'title' => t('Seconds'), 'singular' => t('Once a second'), 'plural' => t('Every @count seconds')),
'minutes' => array('type' => 'minutes', 'seconds' => 60, 'title' => t('Minutes'), 'singular' => t('Once a minute'), 'plural' => t('Every @count minutes')),
@@ -321,83 +621,242 @@ class backup_migrate_schedule extends backup_migrate_item {
/**
* Get the message to send to the user when confirming the deletion of the item.
*/
function delete_confirm_message() {
return t('Are you sure you want to delete the profile %name? Any schedules using this profile will be disabled.', array('%name' => $this->get('name')));
public function delete_confirm_message() {
return t('Are you sure you want to delete the schedule %name? Backups made with this schedule will not be deleted.', array('%name' => $this->get('name')));
}
/**
* Perform the cron action. Run the backup if enough time has elapsed.
*/
function cron() {
public function cron() {
$now = time();
// Add a small negative buffer (1% of the entire period) to the time to account for slight difference in cron run length.
$wait_time = $this->period - ($this->period * variable_get('backup_migrate_schedule_buffer', 0.01));
$wait_time = $this->period - ($this->period * variable_get('backup_migrate_schedule_buffer', BACKUP_MIGRATE_SCHEDULE_BUFFER));
if ($this->is_enabled() && ($now - $this->get('last_run')) >= $wait_time) {
if ($settings = $this->get_profile()) {
$settings->destination_id = $this->destination_id;
$settings->source_id = $this->source_id;
backup_migrate_perform_backup($settings);
$this->update_last_run($now);
$this->remove_expired_backups();
}
else {
backup_migrate_backup_fail("Schedule '%schedule' could not be run because requires a profile which is missing.", array('%schedule' => $schedule->get_name()), $settings);
}
$cron = $this->get('cron');
if ($cron == BACKUP_MIGRATE_CRON_BUILTIN && $this->is_enabled() && ($now - $this->get('last_run')) >= $wait_time) {
$this->run();
}
}
/**
* Run the actual schedule.
*/
public function run() {
// Clear cached profile data as it could have been altered by a previous
// schedule run.
drupal_static_reset('backup_migrate_get_profiles');
if ($settings = $this->get_profile()) {
$settings->source_id = $this->get('source_id');
$settings->destination_id = $this->get('destination_ids');
$this->update_last_run(time());
backup_migrate_perform_backup($settings);
$this->remove_expired_backups();
}
else {
backup_migrate_backup_fail("Schedule '%schedule' could not be run because requires a profile which is missing.", array('%schedule' => $schedule->get_name()), $settings);
}
}
/**
* Set the last run time of a schedule to the given timestamp, or now if none specified.
*/
function update_last_run($timestamp = NULL) {
public function update_last_run($timestamp = NULL) {
if ($timestamp === NULL) {
$timestamp = time();
}
variable_set('backup_migrate_schedule_last_run_' . $this->get('id'), $timestamp);
}
/**
/**
* Set the last run time of a schedule to the given timestamp, or now if none specified.
*/
function get_last_run($timestamp = NULL) {
public function get_last_run() {
return variable_get('backup_migrate_schedule_last_run_' . $this->get('id'), 0);
}
/**
* Remove older backups keeping only the number specified by the aministrator.
*/
function remove_expired_backups() {
backup_migrate_include('destinations');
public function remove_expired_backups() {
require_once dirname(__FILE__) . '/destinations.inc';
$num_to_keep = $this->keep;
// If num to keep is not 0 (0 is infinity).
if ($num_to_keep && ($destination = $this->get_destination())) {
$i = 0;
if ($destination->op('delete') && $destination_files = $destination->list_files()) {
// Sort the files by modified time.
foreach ($destination_files as $file) {
if ($file->is_recognized_type() && $destination->can_delete_file($file->file_id())) {
$files[str_pad($file->info('filetime'), 10, "0", STR_PAD_LEFT) ."-". $i++] = $file;
}
foreach ((array) $this->get_destinations() as $destination) {
if ($destination && $destination->op('delete') && $destination_files = $destination->list_files()) {
if ($num_to_keep == BACKUP_MIGRATE_SMART_DELETE) {
$this->smart_delete_backups(
$destination,
$destination_files,
variable_get('backup_migrate_smart_keep_subhourly', BACKUP_MIGRATE_SMART_KEEP_SUBHOURLY),
variable_get('backup_migrate_smart_keep_hourly', BACKUP_MIGRATE_SMART_KEEP_HOURLY),
variable_get('backup_migrate_smart_keep_daily', BACKUP_MIGRATE_SMART_KEEP_DAILY),
variable_get('backup_migrate_smart_keep_weekly', BACKUP_MIGRATE_SMART_KEEP_WEEKLY)
);
}
// If we are beyond our limit, remove as many as we need.
$num_files = count($files);
if ($num_files > $num_to_keep) {
$num_to_delete = $num_files - $num_to_keep;
// Sort by date.
ksort($files);
// Delete from the start of the list (earliest).
for ($i = 0; $i < $num_to_delete; $i++) {
$file = array_shift($files);
$destination->delete_file($file->file_id());
}
elseif ($num_to_keep != BACKUP_MIGRATE_KEEP_ALL) {
$this->delete_backups($destination, $destination_files, $num_to_keep);
}
}
}
}
/**
* Remove older backups keeping only the number specified by the aministrator.
*/
public function delete_backups($destination, $files, $num_to_keep) {
require_once dirname(__FILE__) . '/destinations.inc';
$num_to_keep = $this->keep;
// Sort the files by modified time.
$i = 0;
foreach ($files as $id => $file) {
if ($file->is_recognized_type()) {
$time = $file->info('filetime');
$sorted[$id] = $time;
}
}
asort($sorted);
// If we are beyond our limit, remove as many as we need.
$num_files = count($files);
if ($num_files > $num_to_keep) {
$num_to_delete = $num_files - $num_to_keep;
// Delete from the start of the list (earliest).
foreach ($sorted as $id => $time) {
if (!$num_to_delete--) {
break;
}
$destination->delete_file($id);
}
}
}
/**
* Delete files keeping the specified number of hourly, daily, weekly and monthly backups.
*/
public function smart_delete_backups($destination, $files, $keep_subhourly = 3600, $keep_hourly = 24, $keep_daily = 14, $keep_weekly = PHP_INT_MAX, $keep_monthly = PHP_INT_MAX) {
// Each period must be an exact multiple of the next smallest period.
$now = time();
$periods = array(
'subhourly' => array(
'delta' => 1,
'keep' => $keep_subhourly,
'last_time' => 0,
'files' => array(),
),
'hourly' => array(
'delta' => 60 * 60,
'keep' => $keep_hourly,
'last_time' => 0,
'files' => array(),
),
'daily' => array(
'delta' => 60 * 60 * 24,
'keep' => $keep_daily,
'last_time' => 0,
'files' => array(),
),
'weekly' => array(
'delta' => 60 * 60 * 24 * 7,
'keep' => $keep_weekly,
'last_time' => 0,
'files' => array(),
),
/*
'monthly' => array(
'delta' => 60*60*24*7*4,
'keep' => $keep_monthly,
'last_time' => 0,
'files' => array(),
),
*/
);
$keep_files = $filetimes = $times = $groups = $sorted = $saved = array();
foreach ($files as $id => $file) {
if ($file->is_recognized_type()) {
$time = $file->info('filetime');
$sorted[$id] = $time;
}
}
// Sort files, oldest first.
asort($sorted);
// Reset internal pointer and get the oldest file time.
$oldest_file_time = reset($sorted);
// Save the oldest file.
$keep_files[key($sorted)] = key($sorted);
foreach ($periods as $i => $period) {
$period_keep_files = array();
$time = $oldest_file_time;
// Set time from which we start saving files.
$period_start_time = $now - (($period['keep'] + 1) * $period['delta']);
// Increase time to within one period time span of the period start
// time. This keeps all the different period starts aligned.
if ($time < $period_start_time) {
$time += ((int) ceil(($period_start_time - $time) / $period['delta'])) * $period['delta'];
}
$file_id = $this->find_nearest_file($sorted, $time);
do {
$period_keep_files[$file_id] = $file_id;
$last_file_id = $file_id;
$time += $period['delta'];
$file_id = $this->find_nearest_file($sorted, $time);
} while ($time < $now);
$keep_files = array_merge($keep_files, $period_keep_files);
}
// Do the delete.
foreach ($files as $id => $file) {
if (!isset($keep_files[$id])) {
$destination->delete_file($file->file_id());
}
}
}
/**
*
*/
protected function find_nearest_file($files, $time) {
$last_file_id = NULL;
$last_file_time = NULL;
foreach ($files as $id => $file_time) {
if ($file_time >= $time) {
if ($last_file_time == NULL) {
return $id;
}
if ($file_time == $time) {
return $id;
}
$time_to_prev = $time - $last_file_time;
$time_to_next = $file_time - $time;
if ($time_to_prev >= $time_to_next) {
return $id;
}
else {
return $last_file_id;
}
// Shouldn't hit this but you never know.
break;
}
$last_file_id = $id;
$last_file_time = $file_time;
}
}
}
@@ -0,0 +1,314 @@
<?php
/**
* @file
*/
require_once dirname(__FILE__) . '/sources.filesource.inc';
/**
* @file
* A destination type for saving locally to the server.
*/
/**
* A destination type for saving locally to the server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_files_destination_archivesource extends backup_migrate_destination_filesource {
public $supported_ops = array('source');
/**
*
*/
public function type_name() {
return t("Site Archive Source");
}
/**
* Declares the current files directory as a backup source..
*/
public function sources() {
$out = array();
$out['archive'] = backup_migrate_create_destination('archive', array(
'machine_name' => 'archive',
'location' => '.',
'name' => t('Entire Site (code, files & DB)'),
'show_in_list' => FALSE,
));
return $out;
}
/**
* Returns a list of backup filetypes.
*/
public function file_types() {
return array(
"sitearchive" => array(
"extension" => "sitearchive.tar",
"filemime" => "application/x-tar",
"backup" => TRUE,
"restore" => FALSE,
),
);
}
/**
* Gets the form for the settings for this destination.
*/
public function backup_settings_default() {
$out = parent::backup_settings_default();
$excludes = explode("\n", $out['exclude_filepaths']);
foreach ($excludes as $i => $exclude) {
$excludes[$i] = 'public://' . $exclude;
}
$excludes[] = 'private://backup_migrate';
$excludes[] = conf_path() . '/settings.php';
$excludes[] = file_directory_temp();
return array(
'exclude_filepaths' => implode("\n", $excludes),
);
}
/**
* Backup from this source.
*/
public function _backup_to_file_php($file, $settings) {
if ($this->check_libs()) {
$base_dir = $this->get_realpath();
$excluded_paths = empty($settings->filters['exclude_filepaths']) ? '' : $settings->filters['exclude_filepaths'];
$exclude = $this->get_excluded_paths($settings);
$files = $this->get_files_to_backup($this->get_realpath(), $settings, $exclude);
if ($files) {
$manifest = $this->generate_manifest();
$db = $this->get_db();
$file->push_type('sitearchive');
$gz = new Archive_Tar($file->filepath(), FALSE);
$gz->addModify(array($manifest), $file->name . '/', dirname($manifest));
$gz->addModify($files, $file->name . '/docroot', $base_dir);
$gz->addModify($db, $file->name . '/', dirname($db));
unlink($manifest);
rmdir(dirname($manifest));
unlink($db);
rmdir(dirname($db));
return $file;
}
backup_migrate_backup_fail('No files available.', array(), $settings);
return FALSE;
}
return FALSE;
}
/**
* Backup from this source.
*/
public function _backup_to_file_cli($file, $settings) {
if (!empty($settings->filters['use_cli']) && function_exists('backup_migrate_exec') && function_exists('escapeshellarg')) {
$excluded_paths = empty($settings->filters['exclude_filepaths']) ? '' : $settings->filters['exclude_filepaths'];
foreach ($this->get_excluded_paths($excluded_paths) as $path) {
$exclude[] = '--exclude=' . escapeshellarg($path);
}
$exclude = implode(' ', $exclude);
// Create a symlink in a temp directory so we can rename the file in the
// archive.
$temp = backup_migrate_temp_directory();
$manifest = $this->generate_manifest();
$db = $this->get_db();
rename($db, $temp . '/database.sql');
rename($manifest, $temp . '/MANIFEST.ini');
$file->push_type('sitearchive');
$link = $temp . '/docroot';
$input = realpath($this->get_location());
backup_migrate_exec("ln -s %input %link; tar --dereference -C %temp -rf %output $exclude .", array(
'%output' => $file->filepath(),
'%input' => $input,
'%temp' => $temp,
'%link' => $link,
));
return $file;
}
return FALSE;
}
/**
* Generates a manifest file.
*/
public function generate_manifest() {
$info = array(
'Global' => array(
'datestamp' => time(),
'formatversion' => '2011-07-02',
'generator' => 'Backup and Migrate (http://drupal.org/project/backup_migrate)',
'generatorversion' => BACKUP_MIGRATE_VERSION,
),
'Site 0' => array(
'version' => VERSION,
'name' => variable_get('site_name', ''),
'docroot' => 'docroot',
'sitedir' => 'docroot/' . conf_path(),
'database-file-default' => 'database.sql',
'database-file-driver' => 'mysql',
),
);
if ($private = variable_get('file_private_path', FALSE)) {
$info['Site 0']['files-private'] = 'docroot/' . $private;
}
$info['Site 0']['files-public'] = 'docroot/' . variable_get('file_public_path', FALSE);
$ini = $this->_array_to_ini($info);
$tmpdir = backup_migrate_temp_directory();
$filepath = $tmpdir . '/MANIFEST.ini';
file_put_contents($filepath, $ini);
return $filepath;
}
/**
* Gets a database dump to add to the archive.
*/
public function get_db() {
require_once dirname(__FILE__) . '/destinations.inc';
require_once dirname(__FILE__) . '/files.inc';
require_once dirname(__FILE__) . '/filters.inc';
require_once dirname(__FILE__) . '/profiles.inc';
$file = new backup_file();
// Clone the default settings so we can make changes without them leaking
// out of this function.
$settings = clone _backup_migrate_profile_saved_default_profile();
$settings->source_id = 'db';
$settings->filters['compression'] = 'none';
// Execute the backup on the db with the default settings.
$file = backup_migrate_filters_backup($file, $settings);
// Generate a tmp file with the correct final title (because ArchiveTar
// doesn't seem to allow renaming).
$tmpdir = backup_migrate_temp_directory();
$filepath = $tmpdir . '/database.sql';
rename($file->filepath(), $filepath);
return $filepath;
}
/**
* Restores to this source.
*/
public function _restore_from_file_php($file, &$settings) {
$success = FALSE;
if ($this->check_libs()) {
$from = $file->pop_type();
$temp = backup_migrate_temp_directory();
$tar = new Archive_Tar($from->filepath());
$tar->extractModify($temp, $file->name);
// Parse the manifest.
$manifest = $this->read_manifest($temp);
// Currently only the first site in the archive is supported.
$site = $manifest['Site 0'];
$docroot = $temp . '/' . $site['docroot'];
$sqlfile = $temp . '/' . $site['database-file-default'];
$filepath = NULL;
if (isset($site['files-private'])) {
$filepath = $temp . '/' . $site['files-private'];
}
elseif (isset($site['files-public'])) {
$filepath = $temp . '/' . $site['files-public'];
}
// Move the files from the temp directory.
if ($filepath && file_exists($filepath)) {
_backup_migrate_move_files($filepath, variable_get('file_public_path', conf_path() . '/files'));
}
else {
_backup_migrate_message('Files were not restored because the archive did not seem to contain a files directory or was in a format that Backup and Migrate couldn\'t read', array(), 'warning');
}
// Restore the sql db.
if ($sqlfile && file_exists($sqlfile)) {
$db_settings = clone $settings;
$db_settings->source_id = 'db';
$file = new backup_file(array('filepath' => $sqlfile));
$success = backup_migrate_filters_restore($file, $db_settings);
}
else {
_backup_migrate_message('The database was not restored because the archive did not seem to contain a database backup or was in a format that Backup and Migrate couldn\'t read', array(), 'warning');
}
if ($docroot) {
_backup_migrate_message('Backup and Migrate cannot restore the php code of the site for security reasons. You will have to copy the code to the server by hand if you wish to restore the full site.', array(), 'warning');
}
return $success && $file;
}
return FALSE;
}
/**
* Restores to this source.
*/
public function _restore_from_file_cli($file, &$settings) {
// @todo implement the cli version of the restore.
return FALSE;
}
/**
* Generates a manifest file.
*/
public function read_manifest($directory) {
// Assume some defaults if values ore the manifest is missing.
$defaults = array(
'docroot' => 'docroot',
'database-file-default' => 'database.sql',
'database-file-driver' => 'mysql',
);
$out = $this->_ini_to_array($directory . '/MANIFEST.ini');
// Set the defaults.
$out['Site 0'] = isset($out['Site 0']) ? $out['Site 0'] : array();
$out['Site 0'] += $defaults;
return $out;
}
/**
* Converts an associated array to an ini format string.
*
* Only allows 2 levels of depth to allow parse_ini_file to parse.
*/
public function _array_to_ini($sections) {
$content = "";
foreach ($sections as $section => $data) {
$content .= '[' . $section . ']' . "\n";
foreach ($data as $key => $val) {
$content .= $key . " = \"" . $val . "\"\n";
}
$content .= "\n";
}
return $content;
}
/**
* Converts an associated array to an ini format string.
*
* Only allows 2 levels of depth to allow parse_ini_file to parse.
*/
public function _ini_to_array($path) {
return parse_ini_file($path, TRUE);
}
}
@@ -0,0 +1,330 @@
<?php
/**
* @file
* Functions to handle the direct to database destination.
*/
/**
* A destination type for saving to a database server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_source_db extends backup_migrate_source_remote {
public $supported_ops = array('configure', 'source');
public $db_target = 'default';
public $connection = NULL;
/**
*
*/
public function type_name() {
return t("Database");
}
/**
* Save the info by importing it into the database.
*/
public function save_file($file, $settings) {
require_once dirname(__FILE__) . '/files.inc';
// Set the source_id to the destination_id in the settings since for a
// restore, the source_id is the database that gets restored to.
$settings->set_source($this->get_id());
// Restore the file to the source database.
$file = backup_migrate_perform_restore($this->get_id(), $file, $settings);
return $file;
}
/**
* Destination configuration callback.
*/
public function edit_form() {
$form = parent::edit_form();
$form['scheme']['#default_value'] = $this->default_scheme();
$form['scheme']['#access'] = FALSE;
$form['path']['#title'] = t('Database name');
$form['path']['#description'] = t('The name of the database. The database must exist, it will not be created for you.');
$form['user']['#description'] = t('Enter the name of a user who has write access to the database.');
return $form;
}
/**
* Validate the configuration form. Make sure the db info is valid.
*/
public function edit_form_validate($form, &$form_state) {
if (!preg_match('/[a-zA-Z0-9_\$]+/', $form_state['values']['path'])) {
form_set_error('path', t('The database name is not valid.'));
}
parent::edit_form_validate($form, $form_state);
}
/**
* Get the default settings for this object.
*
* @return array
* The default tables whose data can be ignored. These tables mostly
* contain info which can be easily reproducted (such as cache or search
* index) but also tables which can become quite bloated but are not
* necessarily extremely important to back up or migrate during development
* (such as access log and watchdog).
*/
public function backup_settings_default() {
$all_tables = $this->_get_table_names();
// Basic modules that should be excluded.
$basic = array(
// Default core tables.
'accesslog',
'sessions',
'watchdog',
// Search module.
'search_dataset',
'search_index',
'search_keywords_log',
'search_total',
// Devel module.
'devel_queries',
'devel_times',
);
// Identify all cache tables.
$cache = array('cache');
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'cache_') === 0) {
$cache[] = $table_name;
}
}
// Simpletest can create a lot of tables that do not need to be backed up,
// but all of them start with the string 'simpletest' so they can be easily
// excluded.
$simpletest = array();
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'simpletest') === 0) {
$simpletest[] = $table_name;
}
}
return array(
'nodata_tables' => drupal_map_assoc(array_merge($basic, $cache, module_invoke_all('devel_caches'))),
'exclude_tables' => $simpletest,
'utils_lock_tables' => FALSE,
);
}
/**
* Get the form for the backup settings for this destination.
*/
public function backup_settings_form($settings) {
$objects = $this->get_object_names();
$form['#description'] = t("You may omit specific tables, or specific table data from the backup file. Only omit data that you know you will not need such as cache data, or tables from other applications. Excluding tables can break your Drupal install, so <strong>do not change these settings unless you know what you're doing</strong>.");
$form['exclude_tables'] = array(
"#type" => "select",
"#multiple" => TRUE,
"#title" => t("Exclude the following tables altogether"),
"#options" => $objects,
"#default_value" => $settings['exclude_tables'],
"#description" => t("The selected tables will not be added to the backup file."),
);
$form['nodata_tables'] = array(
"#type" => "select",
"#multiple" => TRUE,
"#title" => t("Exclude the data from the following tables"),
"#options" => $objects,
"#default_value" => $settings['nodata_tables'],
"#description" => t("The selected tables will have their structure backed up but not their contents. This is useful for excluding cache data to reduce file size."),
);
$form['utils_lock_tables'] = array(
'#type' => 'checkbox',
'#title' => t('Lock tables during backup'),
'#default_value' => !empty($settings['utils_lock_tables']) ? $settings['utils_lock_tables'] : NULL,
'#description' => t('This can help reduce data corruption, but will make your site unresponsive.'),
);
return $form;
}
/**
* Backup from this source.
*/
public function backup_to_file($file, $settings) {
$file->push_type($this->get_file_type_id());
// $this->lock_tables($settings);
// Switch to a different db if specified.
if (variable_get('backup_migrate_verbose')) {
_backup_migrate_message('Start peak memory usage: %mem', array('%mem' => backup_migrate_get_peak_memory_usage() . 'MB'), 'success');
}
$success = $this->_backup_db_to_file($file, $settings);
if (variable_get('backup_migrate_verbose')) {
_backup_migrate_message('Finish peak memory usage: %mem', array('%mem' => backup_migrate_get_peak_memory_usage() . 'MB'), 'success');
}
// $this->unlock_tables($settings);
return $success ? $file : FALSE;
}
/**
* Restore to this source.
*/
public function restore_from_file($file, &$settings) {
$num = 0;
$type = $this->get_file_type_id();
// Open the file using the file wrapper. Check that the dump is of the right type (allow .sql for legacy reasons).
if ($file->type_id() !== $this->get_file_type_id() && $file->type_id() !== 'sql') {
_backup_migrate_message("Unable to restore from file %file because a %type file can't be restored to this database.", array("%file" => $file->filepath(), '%type' => $file->type_id()), 'error');
}
else {
backup_migrate_filters_invoke_all('pre_restore', $file, $settings);
// Restore the database.
$num = $this->_restore_db_from_file($file, $settings);
$settings->performed_action = $num ? t('%num SQL commands executed.', array('%num' => $num)) : '';
backup_migrate_filters_invoke_all('post_restore', $file, $settings, $num);
}
return $num;
}
/**
* Get the db connection for the specified db.
*/
public function _get_db_connection() {
if (!$this->connection) {
$target = $key = '';
$parts = explode(':', $this->get_id());
// One of the predefined databases (set in settings.php)
if ($parts[0] == 'db') {
$key = empty($parts[1]) ? 'default' : $parts[1];
$target = empty($parts[2]) ? 'default' : $parts[2];
}
// Another db url.
else {
// If the url is specified build it into a connection info array.
if (!empty($this->dest_url)) {
$info = array(
'driver' => empty($this->dest_url['scheme']) ? NULL : $this->dest_url['scheme'],
'host' => empty($this->dest_url['host']) ? NULL : $this->dest_url['host'],
'port' => empty($this->dest_url['port']) ? NULL : $this->dest_url['port'],
'username' => empty($this->dest_url['user']) ? NULL : $this->dest_url['user'],
'password' => empty($this->dest_url['pass']) ? NULL : $this->dest_url['pass'],
'database' => empty($this->dest_url['path']) ? NULL : $this->dest_url['path'],
);
$key = uniqid('backup_migrate_tmp_');
$target = 'default';
Database::addConnectionInfo($key, $target, $info);
}
// No database selected. Assume the default.
else {
$key = $target = 'default';
}
}
if ($target && $key) {
$this->connection = Database::getConnection($target, $key);
}
}
return $this->connection;
}
/**
* Backup the databases to a file.
*/
public function _backup_db_to_file($file, $settings) {
// Must be overridden.
}
/**
* Backup the databases to a file.
*/
public function _restore_db_from_file($file, $settings) {
// Must be overridden.
}
/**
* Get a list of objects in the database.
*/
public function get_object_names() {
// Must be overridden.
$out = $this->_get_table_names();
if (method_exists($this, '_get_view_names')) {
$out += $this->_get_view_names();
}
return $out;
}
/**
* Get a list of tables in the database.
*/
public function get_table_names() {
// Must be overridden.
$out = $this->_get_table_names();
return $out;
}
/**
* Get a list of tables in the database.
*/
public function _get_table_names() {
// Must be overridden.
return array();
}
/**
* Lock the database in anticipation of a backup.
*/
public function lock_tables($settings) {
if ($settings->filters['utils_lock_tables']) {
$tables = array();
foreach ($this->get_table_names() as $table) {
// There's no need to lock excluded or structure only tables because it doesn't matter if they change.
if (empty($settings->filters['exclude_tables']) || !in_array($table, (array) $settings->filters['exclude_tables'])) {
$tables[] = $table;
}
}
$this->_lock_tables($tables);
}
}
/**
* Lock the list of given tables in the database.
*/
public function _lock_tables($tables) {
// Must be overridden.
}
/**
* Unlock any tables that have been locked.
*/
public function unlock_tables($settings) {
if ($settings->filters['utils_lock_tables']) {
$this->_unlock_tables();
}
}
/**
* Unlock the list of given tables in the database.
*/
public function _unlock_tables($tables) {
// Must be overridden.
}
/**
* Get the file type for to backup this destination to.
*/
public function get_file_type_id() {
return 'sql';
}
/**
* Get the version info for the given DB.
*/
public function _db_info() {
return array(
'type' => FALSE,
'version' => t('Unknown'),
);
}
}
@@ -0,0 +1,593 @@
<?php
/**
* @file
*/
require_once dirname(__FILE__) . '/sources.db.inc';
/**
* @file
* Functions to handle the direct to database source.
*/
/**
* A source type for backing up from database server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_source_db_mysql extends backup_migrate_source_db {
/**
* The table's data keyed by table name.
*
* @var array
*/
protected static $tableData = array();
/**
* The tables keyed by name.
*
* @var array
*/
protected static $tableNames = array();
/**
* The views keyed by name.
*
* @var array
*/
protected static $viewNames = array();
/**
*
*/
public function type_name() {
return t("MySQL Database");
}
/**
* Return a list of backup filetypes.
*/
public function file_types() {
return array(
"sql" => array(
"extension" => "sql",
"filemime" => "text/x-sql",
"backup" => TRUE,
"restore" => TRUE,
),
"mysql" => array(
"extension" => "mysql",
"filemime" => "text/x-sql",
"backup" => TRUE,
"restore" => TRUE,
),
);
}
/**
* Return the scheme for this db type.
*/
public function default_scheme() {
return 'mysql';
}
/**
* Declare any mysql databases defined in the settings.php file as a possible source.
*/
public function sources() {
$out = array();
global $databases;
foreach ((array) $databases as $db_key => $target) {
foreach ((array) $target as $tgt_key => $info) {
// Only mysql/mysqli supported by this source.
$key = $db_key . ':' . $tgt_key;
if ($info['driver'] === 'mysql') {
// Compile the database connection string.
$url = 'mysql://';
$url .= urlencode($info['username']) . ':' . urlencode($info['password']);
$url .= '@';
$url .= urlencode($info['host']);
if (!empty($info['port'])) {
$url .= ':' . $info['port'];
}
$url .= '/' . urlencode($info['database']);
if ($source = backup_migrate_create_destination('mysql', array('url' => $url))) {
// Treat the default database differently because it is probably
// the only one available.
if ($key == 'default:default') {
$source->set_id('db');
$source->set_name(t('Default Database'));
// Dissalow backing up to the default database because that's confusing and potentially dangerous.
$source->remove_op('scheduled backup');
$source->remove_op('manual backup');
}
else {
$source->set_id('db:' . $key);
$source->set_name($key . ": " . $source->get_display_location());
}
$out[$source->get_id()] = $source;
}
}
}
}
return $out;
}
/**
* Get the file type for to backup this source to.
*/
public function get_file_type_id() {
return 'mysql';
}
/**
* Backup the databases to a file.
*
* Returns a list of sql commands, one command per line.
* That makes it easier to import without loading the whole file into memory.
* The files are a little harder to read, but human-readability is not a priority.
*/
public function _backup_db_to_file($file, $settings) {
if (!empty($settings->filters['use_cli']) && $this->_backup_db_to_file_mysqldump($file, $settings)) {
return TRUE;
}
$lines = 0;
$exclude = !empty($settings->filters['exclude_tables']) ? $settings->filters['exclude_tables'] : array();
$nodata = !empty($settings->filters['nodata_tables']) ? $settings->filters['nodata_tables'] : array();
if ($file->open(TRUE)) {
$file->write($this->_get_sql_file_header());
$alltables = $this->_get_tables();
$allviews = $this->_get_views();
foreach ($alltables as $table) {
if (_backup_migrate_check_timeout()) {
return FALSE;
}
if ($table['name'] && !isset($exclude[$table['name']])) {
$file->write($this->_get_table_structure_sql($table));
$lines++;
if (!in_array($table['name'], $nodata)) {
$lines += $this->_dump_table_data_sql_to_file($file, $table);
}
}
}
foreach ($allviews as $view) {
if (_backup_migrate_check_timeout()) {
return FALSE;
}
if ($view['name'] && !isset($exclude[$view['name']])) {
$file->write($this->_get_view_create_sql($view));
}
}
$file->write($this->_get_sql_file_footer());
$file->close();
return $lines;
}
else {
return FALSE;
}
}
/**
* Backup the databases to a file using the mysqldump command.
*/
public function _backup_db_to_file_mysqldump($file, $settings) {
$success = FALSE;
$nodata_tables = array();
$alltables = $this->_get_tables();
$command = 'mysqldump --result-file=%file --opt -Q --host=%host --port=%port --user=%user --password=%pass %db';
$args = array(
'%file' => $file->filepath(),
'%host' => $this->dest_url['host'],
'%port' => isset($this->dest_url['port']) ? $this->dest_url['port'] : '3306',
'%user' => $this->dest_url['user'],
'%pass' => $this->dest_url['pass'],
'%db' => $this->dest_url['path'],
);
// Ignore the excluded and no-data tables.
$db = $this->dest_url['path'];
if (!empty($settings->filters['exclude_tables'])) {
foreach ((array) $settings->filters['exclude_tables'] as $table) {
if (isset($alltables[$table])) {
$command .= ' --ignore-table=' . $db . '.' . $table;
}
}
}
if (!empty($settings->filters['nodata_tables'])) {
foreach ((array) $settings->filters['nodata_tables'] as $table) {
if (isset($alltables[$table])) {
$nodata_tables[] = $table;
$command .= ' --ignore-table=' . $db . '.' . $table;
}
}
}
$success = backup_migrate_exec($command, $args);
// Get the nodata tables.
if ($success && !empty($nodata_tables)) {
$tables = implode(' ', array_unique($nodata_tables));
$command = "mysqldump --no-data --opt -Q --host=%host --port=%port --user=%user --password=%pass %db $tables >> %file";
$success = backup_migrate_exec($command, $args);
}
return $success;
}
/**
* Backup the databases to a file.
*/
public function _restore_db_from_file($file, $settings) {
$num = 0;
if ($file->open() && $conn = $this->_get_db_connection()) {
// Optionally drop all existing tables.
if (!empty($settings->filters['utils_drop_all_tables'])) {
$all_tables = $this->_get_tables();
$table_names = array_map('backup_migrate_array_name_value', $all_tables);
$table_list = join(', ', $table_names);
$stmt = $conn->prepare("DROP TABLE IF EXISTS $table_list;\n");
$stmt->execute();
}
// Read one line at a time and run the query.
while ($line = $this->_read_sql_command_from_file($file)) {
if (_backup_migrate_check_timeout()) {
return FALSE;
}
if ($line) {
// Prepeare and exexute the statement instead of the api function to avoid substitution of '{' etc.
$stmt = $conn->prepare($line);
$stmt->execute();
$num++;
}
}
// Close the file with fclose/gzclose.
$file->close();
}
else {
drupal_set_message(t("Unable to open file %file to restore database", array("%file" => $file->filepath())), 'error');
$num = FALSE;
}
return $num;
}
/**
* Read a multiline sql command from a file.
*
* Supports the formatting created by mysqldump, but won't handle multiline comments.
*/
public function _read_sql_command_from_file($file) {
$out = '';
while ($line = $file->read()) {
$first2 = substr($line, 0, 2);
$first3 = substr($line, 0, 3);
// Ignore single line comments. This function doesn't support multiline comments or inline comments.
if ($first2 != '--' && ($first2 != '/*' || $first3 == '/*!')) {
$out .= ' ' . trim($line);
// If a line ends in ; or */ it is a sql command.
if (substr($out, strlen($out) - 1, 1) == ';') {
return trim($out);
}
}
}
return trim($out);
}
/**
* Get a list of tables in the database.
*/
public function _get_table_names() {
if (empty(static::$tableNames)) {
static::$tableNames = $this->query("SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE'")
->fetchAllKeyed(0, 0);
}
return static::$tableNames;
}
/**
* Get a list of views in the database.
*/
public function _get_view_names() {
if (empty(static::$viewNames)) {
static::$viewNames = $this->query("SHOW FULL TABLES WHERE Table_Type = 'VIEW'")
->fetchAllKeyed(0, 0);
}
return static::$viewNames;
}
/**
* Lock the list of given tables in the database.
*/
public function _lock_tables($tables) {
if ($tables) {
$tables_escaped = array();
foreach ($tables as $table) {
$tables_escaped[] = '`' . db_escape_table($table) . '` WRITE';
}
$this->query('LOCK TABLES ' . implode(', ', $tables_escaped));
}
}
/**
* Unlock all tables in the database.
*/
public function _unlock_tables($settings) {
$this->query('UNLOCK TABLES');
}
/**
* Get a list of table and view data in the db.
*/
protected function get_table_data() {
if (empty(static::$tableData)) {
$tables = $this->query('SHOW TABLE STATUS')->fetchAll(PDO::FETCH_ASSOC);
foreach ($tables as $table) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the
// default query behavior was changed.
// See: http://drupal.org/node/1171866
$table = array_change_key_case($table);
static::$tableData[$table['name']] = $table;
}
}
return static::$tableData;
}
/**
* Get a list of tables in the db.
*/
public function _get_tables() {
$out = array();
foreach ($this->get_table_data() as $table) {
if (!empty($table['engine'])) {
$out[$table['name']] = $table;
}
}
return $out;
}
/**
* Get a list of views in the db.
*/
public function _get_views() {
$out = array();
foreach ($this->get_table_data() as $table) {
if (empty($table['engine'])) {
$out[$table['name']] = $table;
}
}
return $out;
}
/**
* Get the sql for the structure of the given view.
*/
public function _get_view_create_sql($view) {
$out = "";
// Switch SQL mode to get rid of "CREATE ALGORITHM..." what requires more permissions + troubles with the DEFINER user.
$sql_mode = $this->query("SELECT @@SESSION.sql_mode")->fetchField();
$this->query("SET sql_mode = 'ANSI'");
$result = $this->query("SHOW CREATE VIEW `" . $view['name'] . "`", array(), array('fetch' => PDO::FETCH_ASSOC));
$this->query("SET SQL_mode = :mode", array(':mode' => $sql_mode));
foreach ($result as $create) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
// See: http://drupal.org/node/1171866
$create = array_change_key_case($create);
$out .= "DROP VIEW IF EXISTS `" . $view['name'] . "`;\n";
$out .= "SET sql_mode = 'ANSI';\n";
$out .= strtr($create['create view'], "\n", " ") . ";\n";
$out .= "SET sql_mode = '$sql_mode';\n";
}
return $out;
}
/**
* Get the sql for the structure of the given table.
*/
public function _get_table_structure_sql($table) {
$out = "";
$result = $this->query("SHOW CREATE TABLE `" . $table['name'] . "`", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $create) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
// See: http://drupal.org/node/1171866
$create = array_change_key_case($create);
$out .= "DROP TABLE IF EXISTS `" . $table['name'] . "`;\n";
// Remove newlines and convert " to ` because PDO seems to convert those for some reason.
$out .= strtr($create['create table'], array("\n" => ' ', '"' => '`'));
if ($table['auto_increment']) {
$out .= " AUTO_INCREMENT=" . $table['auto_increment'];
}
$out .= ";\n";
}
return $out;
}
/**
* Get the sql to insert the data for a given table.
*/
public function _dump_table_data_sql_to_file($file, $table) {
$rows_per_query = variable_get('backup_migrate_data_rows_per_query', BACKUP_MIGRATE_DATA_ROWS_PER_QUERY);
$rows_per_line = variable_get('backup_migrate_data_rows_per_line', BACKUP_MIGRATE_DATA_ROWS_PER_LINE);
$bytes_per_line = variable_get('backup_migrate_data_bytes_per_line', BACKUP_MIGRATE_DATA_BYTES_PER_LINE);
if (variable_get('backup_migrate_verbose')) {
_backup_migrate_message('Table: %table', array('%table' => $table['name']), 'success');
}
// Escape backslashes, PHP code, special chars.
$search = array('\\', "'", "\x00", "\x0a", "\x0d", "\x1a");
$replace = array('\\\\', "''", '\0', '\n', '\r', '\Z');
$lines = 0;
$from = 0;
$args = array('fetch' => PDO::FETCH_ASSOC);
while ($data = $this->query("SELECT * FROM `" . $table['name'] . "`", array(), $args, $from, $rows_per_query)) {
if ($data->rowCount() == 0) {
break;
}
$rows = $bytes = 0;
$line = array();
foreach ($data as $row) {
$from++;
// DB Escape the values.
$items = array();
foreach ($row as $key => $value) {
$items[] = is_null($value) ? "null" : "'" . str_replace($search, $replace, $value) . "'";
}
// If there is a row to be added.
if ($items) {
// Start a new line if we need to.
if ($rows == 0) {
$file->write("INSERT INTO `" . $table['name'] . "` VALUES ");
$bytes = $rows = 0;
}
// Otherwise add a comma to end the previous entry.
else {
$file->write(",");
}
// Write the data itself.
$sql = implode(',', $items);
$file->write('(' . $sql . ')');
$bytes += strlen($sql);
$rows++;
// Finish the last line if we've added enough items.
if ($rows >= $rows_per_line || $bytes >= $bytes_per_line) {
$file->write(";\n");
$lines++;
$bytes = $rows = 0;
}
}
}
// Finish any unfinished insert statements.
if ($rows > 0) {
$file->write(";\n");
$lines++;
}
}
if (variable_get('backup_migrate_verbose')) {
_backup_migrate_message('Peak memory usage: %mem', array('%mem' => backup_migrate_get_peak_memory_usage() . 'MB'), 'success');
}
return $lines;
}
/**
* Get the db connection for the specified db.
*/
public function _get_db_connection() {
if (!$this->connection) {
$this->connection = parent::_get_db_connection();
// Set the sql mode because the default is ANSI,TRADITIONAL which is not aware of collation or storage engine.
$this->connection->exec("SET sql_mode=''");
}
return $this->connection;
}
/**
* Run a query on this source's database using Drupal's MySQL engine.
*
* @param string $query
* The query string.
* @param array $args
* Arguments for the query.
* @param array $options
* Options to pass to the query.
* @param int|null $from
* The starting point for the query; when passed will perform a queryRange()
* method instead of a regular query().
* @param int|null $count
* The number of records to obtain from this query. Will be ignored if the
* $from argument is empty.
*
* @see DatabaseConnection_mysql::query()
* @see DatabaseConnection_mysql::queryRange()
*/
public function query($query, array $args = array(), array $options = array(), $from = NULL, $count = NULL) {
if ($conn = $this->_get_db_connection()) {
// If no $from is passed in, just do a basic query.
if (is_null($from)) {
return $conn->query($query, $args, $options);
}
// The $from variable was passed in, so do a ranged query.
else {
return $conn->queryRange($query, $from, $count, $args, $options);
}
}
}
/**
* The header for the top of the sql dump file. These commands set the connection
* character encoding to help prevent encoding conversion issues.
*/
public function _get_sql_file_header() {
$info = $this->_db_info();
return "-- Backup and Migrate (Drupal) MySQL Dump
-- Backup and Migrate Version: " . BACKUP_MIGRATE_VERSION . "
-- http://drupal.org/project/backup_migrate
-- Drupal Version: " . VERSION . "
-- http://drupal.org/
--
-- Host: " . url('', array('absolute' => TRUE)) . "
-- Site Name: " . url('', array('absolute' => TRUE)) . "
-- Generation Time: " . format_date(time(), 'custom', 'r') . "
-- MySQL Version: " . $info['version'] . "
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;
SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";
SET NAMES utf8mb4;
";
}
/**
* The footer of the sql dump file.
*/
public function _get_sql_file_footer() {
return "
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
";
}
/**
* Get the version info for the given DB.
*/
public function _db_info() {
$db = $this->_get_db_connection();
return array(
'type' => 'mysql',
'version' => $db ? $db->version() : t('Unknown'),
);
}
}
@@ -0,0 +1,335 @@
<?php
/**
* @file
* A destination type for saving locally to the server.
*/
/**
* A destination type for saving locally to the server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_filesource extends backup_migrate_source {
public $supported_ops = array('restore', 'configure', 'delete', 'source');
/**
*
*/
public function type_name() {
return t("Files Directory");
}
/**
* Declares the current files directory as a backup source..
*/
public function sources() {
$out = array();
$out['files'] = backup_migrate_create_destination('filesource', array(
'machine_name' => 'files',
'location' => 'public://',
'name' => t('Public Files Directory'),
'show_in_list' => FALSE,
));
if (variable_get('file_private_path', FALSE)) {
$out['files_private'] = backup_migrate_create_destination('filesource', array(
'machine_name' => 'files',
'location' => 'private://',
'name' => t('Private Files Directory'),
'show_in_list' => FALSE,
));
}
return $out;
}
/**
* Gets the form for the settings for the files destination.
*/
public function edit_form() {
$form = parent::edit_form();
$form['location'] = array(
"#type" => "textfield",
"#title" => t("Directory path"),
"#default_value" => $this->get_location(),
"#required" => TRUE,
"#description" => t('Enter the path to the directory to back up. Use a relative path to pick a path relative to your Drupal root directory. The web server must be able to read from this path.'),
);
return $form;
}
/**
* Returns a list of backup filetypes.
*/
public function file_types() {
return array(
"tar" => array(
"extension" => "tar",
"filemime" => "application/x-tar",
"backup" => TRUE,
"restore" => TRUE,
),
);
}
/**
* Gets the form for the settings for this destination.
*
* Return the default directories whose data can be ignored. These directories
* contain info which can be easily reproducted. Also exclude the backup and
* migrate folder to prevent exponential bloat.
*/
public function backup_settings_default() {
return array(
'exclude_filepaths' => "backup_migrate\nstyles\ncss\njs\nctools\nless\nlanguages\nadvagg_css\nadvagg_js",
);
}
/**
* Get the form for the backup settings for this destination.
*/
public function backup_settings_form($settings) {
$form['exclude_filepaths'] = array(
"#type" => "textarea",
"#multiple" => TRUE,
"#title" => t("Exclude the following files or directories"),
"#default_value" => isset($settings['exclude_filepaths']) ? $settings['exclude_filepaths'] : '',
"#description" => t("A list of files or directories to be excluded from backups. Add one path per line relative to the directory being backed up."),
);
return $form;
}
/**
* Backup from this source.
*/
public function backup_to_file($file, $settings) {
if ($out = $this->_backup_to_file_cli($file, $settings)) {
return $out;
}
else {
return $this->_backup_to_file_php($file, $settings);
}
}
/**
* Backup from this source.
*/
public function _backup_to_file_php($file, $settings) {
if ($this->check_libs()) {
$excluded = $this->get_excluded_paths($settings);
$files = $this->get_files_to_backup($this->get_realpath(), $settings, $excluded);
if ($files) {
$file->push_type('tar');
$gz = new Archive_Tar($file->filepath(), FALSE);
$gz->addModify($files, '', $this->get_realpath());
return $file;
}
backup_migrate_backup_fail('No files available.', array(), $settings);
return FALSE;
}
return FALSE;
}
/**
* Backup from this source.
*/
public function _backup_to_file_cli($file, $settings) {
if (!empty($settings->filters['use_cli']) && function_exists('backup_migrate_exec') && function_exists('escapeshellarg')) {
$excluded = $this->get_excluded_paths($settings);
$exclude = array();
foreach ($excluded as $path) {
$exclude[] = '--exclude=' . escapeshellarg($path);
}
$exclude = implode(' ', $exclude);
// Create a symlink in a temp directory so we can rename the file in the
// archive.
$temp = backup_migrate_temp_directory();
$file->push_type('tar');
backup_migrate_exec("tar --dereference -C %input -rf %output $exclude .", array(
'%output' => $file->filepath(),
'%input' => $this->get_realpath(),
'%temp' => $temp,
));
return $file;
}
return FALSE;
}
/**
* Restore to this source.
*/
public function restore_from_file($file, &$settings) {
if ($out = $this->_restore_from_file_cli($file, $settings)) {
return $out;
}
else {
return $this->_restore_from_file_php($file, $settings);
}
}
/**
* Restore to this source.
*/
public function _restore_from_file_php($file, &$settings) {
if ($this->check_libs()) {
$from = $file->pop_type();
$temp = backup_migrate_temp_directory();
$tar = new Archive_Tar($from->filepath());
$tar->extractModify($temp, $file->name);
// Older B&M Files format included a base 'files' directory.
if (file_exists($temp . '/files')) {
$temp = $temp . '/files';
}
if (file_exists($temp . '/' . $file->name . '/files')) {
$temp = $temp . '/files';
}
// Move the files from the temp directory.
_backup_migrate_move_files($temp, $this->get_realpath());
return $file;
}
return FALSE;
}
/**
* Restore to this source.
*/
public function _restore_from_file_cli($file, &$settings) {
if (!empty($settings->filters['use_cli']) && function_exists('backup_migrate_exec')) {
$temp = backup_migrate_temp_directory();
backup_migrate_exec("tar -C %temp -xf %input", array('%input' => $file->filepath(), '%temp' => $temp));
// Older B&M Files format included a base 'files' directory.
if (file_exists($temp . '/files')) {
$temp = $temp . '/files';
}
if (file_exists($temp . '/' . $file->name . '/files')) {
$temp = $temp . '/files';
}
// Move the files from the temp directory.
backup_migrate_exec("mv -rf %temp/* %output", array('%output' => $this->get_realpath(), '%temp' => $temp));
return $file;
}
return FALSE;
}
/**
* Gets a list of files to backup from the given set if dirs.
*
* Exclude any that match the array $exclude.
*/
public function get_files_to_backup($dir, $settings, $exclude = array()) {
$out = $errors = array();
if (!file_exists($dir)) {
backup_migrate_backup_fail('Directory %dir does not exist.', array('%dir' => $dir), $settings);
return FALSE;
}
if ($handle = @opendir($dir)) {
while (($file = readdir($handle)) !== FALSE) {
if ($file != '.' && $file != '..' && !in_array($file, $exclude)) {
$real = realpath($dir . '/' . $file);
// If the path is not excluded.
if (!in_array($real, $exclude)) {
if (is_dir($real)) {
$subdir = $this->get_files_to_backup($real, $settings, $exclude);
// If there was an error reading the subdirectory then abort the
// backup.
if ($subdir === FALSE) {
closedir($handle);
return FALSE;
}
// If the directory is empty, add an empty directory.
if (count($subdir) == 0) {
$out[] = $real;
}
$out = array_merge($out, $subdir);
}
else {
if (is_readable($real)) {
$out[] = $real;
}
else {
$errors[] = $dir . '/' . $file;
}
}
}
}
}
closedir($handle);
}
else {
backup_migrate_backup_fail('Could not open directory %dir', array('%dir' => $dir), $settings);
return FALSE;
}
// Alert the user to any errors there might have been.
if ($errors) {
if (count($errors < 5)) {
$filesmsg = t('The following files: !files', array('!files' => theme('item_list', array('items' => $errors))));
}
else {
$filesmsg = t('!count files', array('!count' => count($errors)));
}
if (empty($settings->filters['ignore_errors'])) {
backup_migrate_backup_fail('The backup could not be completed because !files could not be read. If you want to skip unreadable files use the \'Ignore Errors\' setting under \'Advanced Options\' in \'Advanced Backup\' or in your schedule settings profile.', array('!files' => $filesmsg), 'error');
$out = FALSE;
}
else {
backup_migrate_backup_fail('!files could not be read and were skipped', array('!files' => $filesmsg), 'error');
}
}
return $out;
}
/**
* Breaks the excluded paths string into a usable list of paths.
*/
public function get_excluded_paths($settings) {
$base_dir = $this->get_realpath() . '/';
$paths = empty($settings->filters['exclude_filepaths']) ? '' : $settings->filters['exclude_filepaths'];
$out = explode("\n", $paths);
foreach ($out as $key => $val) {
$path = trim($val, "/ \t\r\n");
// If the path specified is a stream url or absolute path add the
// normalized version.
if ($real = drupal_realpath($path)) {
$out[$key] = $real;
}
// If the path is a relative path add it.
elseif ($real = drupal_realpath($base_dir . $path)) {
$out[$key] = $real;
}
// Otherwise add it as is even though it probably won't match any files.
else {
$out[$key] = $path;
}
}
return $out;
}
/**
* Checks that the required libraries are installed.
*/
public function check_libs() {
$result = TRUE;
// Drupal 7 has Archive_Tar built in so there should be no need to include
// anything here.
return $result;
}
/**
* Get the file location.
*/
public function get_realpath() {
return drupal_realpath($this->get_location());
}
}
@@ -0,0 +1,274 @@
<?php
/**
* @file
* All of the source handling code needed for Backup and Migrate.
*/
require_once dirname(__FILE__) . '/crud.inc';
require_once dirname(__FILE__) . '/destinations.inc';
require_once dirname(__FILE__) . '/locations.inc';
/**
* Get all the available backup sources.
*/
function backup_migrate_get_sources() {
return backup_migrate_crud_get_items('source');
}
/**
* Get the available source types.
*/
function backup_migrate_get_source_subtypes() {
return backup_migrate_crud_subtypes('source');
}
/**
* Get the destination of the given id.
*/
function backup_migrate_get_source($id) {
$sources = backup_migrate_get_sources();
return empty($sources[$id]) ? NULL : $sources[$id];
}
/**
* Create a source object of the given type with the given params.
*/
function backup_migrate_create_source($subtype, $params = array()) {
$params['subtype'] = $subtype;
return backup_migrate_crud_create_item('source', $params);
}
/**
* Implements hook_backup_migrate_source_subtypes().
*
* Get the built in Backup and Migrate source types.
*/
function backup_migrate_backup_migrate_source_subtypes() {
$out = array();
$out += array(
'db' => array(
'type_name' => t('Database'),
'description' => t('Import the backup directly into another database. Database sources can also be used as a source to backup from.'),
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/sources.db.inc',
'class' => 'backup_migrate_source_db',
'can_create' => FALSE,
),
'mysql' => array(
'type_name' => t('MySQL Database'),
'description' => t('Import the backup directly into another MySQL database. Database sources can also be used as a source to backup from.'),
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/sources.db.mysql.inc',
'class' => 'backup_migrate_source_db_mysql',
'can_create' => TRUE,
),
'filesource' => array(
'description' => t('A files directory which can be backed up from.'),
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/sources.filesource.inc',
'class' => 'backup_migrate_destination_filesource',
'type_name' => t('File Directory'),
'can_create' => TRUE,
),
'archive' => array(
'description' => t('Create an archive of your entire site.'),
'file' => drupal_get_path('module', 'backup_migrate') . '/includes/sources.archivesource.inc',
'class' => 'backup_migrate_files_destination_archivesource',
'type_name' => t('Site Archive'),
'can_create' => FALSE,
),
);
return $out;
}
/**
* Implements hook_backup_migrate_sources().
*
* Get the built in backup sources and those in the db.
*/
function backup_migrate_backup_migrate_sources() {
require_once dirname(__FILE__) . '/filters.inc';
// Expose the configured databases as sources.
$out = backup_migrate_filters_invoke_all('sources');
return $out;
}
/**
* Get the source options as a form element.
*/
function _backup_migrate_get_source_form($source_id = 'db') {
require_once dirname(__FILE__) . '/destinations.inc';
$form = array();
$sources = _backup_migrate_get_source_pulldown($source_id);
if (count($sources['#options']) > 1) {
$form['source'] = array(
"#type" => "fieldset",
"#title" => t("Backup Source"),
"#collapsible" => TRUE,
"#collapsed" => FALSE,
"#tree" => FALSE,
);
$sources['#description'] = t("Choose the database to backup. Any database destinations you have created and any databases specified in your settings.php can be backed up.");
$form['source']['source_id'] = $sources;
}
else {
$form = array();
$form['source']['source_id'] = array(
"#type" => "value",
"#value" => $source_id,
);
}
return $form;
}
/**
* Get pulldown to select existing source options.
*/
function _backup_migrate_get_source_pulldown($source_id = NULL) {
$sources = _backup_migrate_get_source_form_item_options();
$form = array(
"#type" => "select",
"#title" => t("Backup Source"),
"#options" => _backup_migrate_get_source_form_item_options(),
"#default_value" => $source_id,
);
return $form;
}
/**
* Get the location options as an options array for a form item.
*/
function _backup_migrate_get_source_form_item_options() {
$out = array();
foreach (backup_migrate_get_sources() as $key => $location) {
$out[$key] = $location->get_name();
}
return $out;
}
/**
* A base class for creating sources.
*/
class backup_migrate_source extends backup_migrate_location {
public $db_table = "backup_migrate_sources";
public $type_name = 'source';
public $singular = 'source';
public $plural = 'sources';
public $title_plural = 'Sources';
public $title_singular = 'Source';
/**
* This function is not supposed to be called.
*
* It is just here to help out the po extractor.
*/
public function strings() {
// Help the pot extractor find these strings.
t('source');
t('sources');
t('Sources');
t('Source');
}
/**
* Get the available location types.
*/
public function location_types() {
return backup_migrate_get_source_subtypes();
}
}
/**
* A base class for creating sources.
*/
class backup_migrate_source_remote extends backup_migrate_source {
/**
* The location is a URI so parse it and store the parts.
*/
public function get_location() {
return $this->url(FALSE);
}
/**
* The location to display is the url without the password.
*/
public function get_display_location() {
return $this->url(TRUE);
}
/**
* Returns the location with the password.
*/
public function set_location($location) {
$this->location = $location;
$this->set_url($location);
}
/**
* Source configuration callback.
*/
public function edit_form() {
$form = parent::edit_form();
$form['scheme'] = array(
"#type" => "textfield",
"#title" => t("Scheme"),
"#default_value" => @$this->dest_url['scheme'] ? $this->dest_url['scheme'] : '',
"#required" => TRUE,
"#weight" => 0,
);
$form['host'] = array(
"#type" => "textfield",
"#title" => t("Host"),
"#default_value" => @$this->dest_url['host'] ? $this->dest_url['host'] : 'localhost',
"#required" => TRUE,
"#weight" => 10,
);
$form['path'] = array(
"#type" => "textfield",
"#title" => t("Path"),
"#default_value" => @$this->dest_url['path'],
"#required" => TRUE,
"#weight" => 20,
);
$form['user'] = array(
"#type" => "textfield",
"#title" => t("Username"),
"#default_value" => @$this->dest_url['user'],
"#required" => TRUE,
"#weight" => 30,
);
$form['pass'] = array(
"#type" => "password",
"#title" => t("Password"),
"#default_value" => @$this->dest_url['pass'],
'#description' => '',
"#weight" => 40,
);
if (@$this->dest_url['pass']) {
$form['old_password'] = array(
"#type" => "value",
"#value" => @$this->dest_url['pass'],
);
$form['pass']["#description"] .= t('You do not need to enter a password unless you wish to change the currently saved password.');
}
return $form;
}
/**
* Submits the configuration form.
*
* Glue the url together and add the old password back if a new one was not
* specified.
*/
public function edit_form_submit($form, &$form_state) {
$form_state['values']['pass'] = $form_state['values']['pass'] ? $form_state['values']['pass'] : $form_state['values']['old_password'];
$form_state['values']['location'] = $this->glue_url($form_state['values'], FALSE);
parent::edit_form_submit($form, $form_state);
}
}
@@ -0,0 +1,301 @@
<?php
/**
* @file
* Shared functionality to make the rest of the tests simpler.
*/
/**
* Base class for testing a module's custom tags.
*/
abstract class BmTestBase extends DrupalWebTestCase {
/**
* {@inheritdoc}
*/
public function setUp(array $modules = array()) {
$modules[] = 'backup_migrate';
parent::setUp($modules);
}
/**
* Log in as user 1.
*
* The benefit of doing this is that it ignores permissions entirely, so the
* raw functionality can be tested.
*/
protected function loginUser1() {
// Load user 1.
$account = user_load(1, TRUE);
// Reset the password.
$password = user_password();
$edit = array(
'pass' => $password,
);
user_save($account, $edit);
$account->pass_raw = $password;
// Login.
$this->drupalLogin($account);
}
/**
* {@inheritdoc}
*/
protected function verbose($message, $title = NULL) {
// Handle arrays, objects, etc.
if (!is_string($message)) {
$message = "<pre>\n" . print_r($message, TRUE) . "\n</pre>\n";
}
// Optional title to go before the output.
if (!empty($title)) {
$title = '<h2>' . check_plain($title) . "</h2>\n";
}
parent::verbose($title . $message);
}
/**
* Confirm that a selector has the expected items.
*/
protected function assertSelectOptions($select_id, array $options, $message = '') {
$elements = $this
->xpath('//select[@id=:id]//option', array(
':id' => $select_id,
));
$results = $this->assertEqual(count($elements), count($options), t('The same number of items were found as were requested'));
$this->verbose($elements);
foreach ($options as $option) {
$elements = $this
->xpath('//select[@id=:id]//option[@value=:option]', array(
':id' => $select_id,
':option' => $option,
));
$this->verbose($elements);
$results *= $this->assertTrue(isset($elements[0]), $message ? $message : t('Option @option for field @id is present.', array(
'@option' => $option,
'@id' => $select_id,
)), t('Browser'));
}
return $results;
}
/**
* Confirm that a specific selector does not have items selected.
*/
protected function assertNoOptionsSelected($id, $message = '') {
$elements = $this
->xpath('//select[@id=:id]//option[@selected="selected"]', array(
':id' => $id,
));
return $this
->assertTrue(!isset($elements[0]), $message ? $message : t('Field @id does not have any selected items.', array(
'@id' => $id,
)), t('Browser'));
}
/**
* Work out which compressor systems are supported by PHP.
*
* @return array
* The list of supported compressors. Will always include the item 'none'.
*/
protected function supportedCompressors() {
$items = array('none');
// Work out which systems are supported.
if (@function_exists("gzencode")) {
$items[] = 'gzip';
}
if (@function_exists("bzcompress")) {
$items[] = 'bzip';
}
if (class_exists('ZipArchive')) {
$items[] = 'zip';
}
return $items;
}
/**
* Get a list of the files in a specific destination.
*
* @param string $destination_id
* The ID of the destination to check. Defaults to the manual file path.
*
* @return array
* The backup files found in the requested backup destination.
*/
protected function listBackupFiles($destination_id = 'manual') {
require_once dirname(__FILE__) . '/../includes/destinations.inc';
$items = array();
// Load the destination object.
$destination = backup_migrate_get_destination($destination_id);
if (!empty($destination)) {
$items = $destination->list_files();
}
return $items;
}
/**
* Run a specific backup.
*
* @param string $destination_id
* The ID of the destination to check. Defaults to the manual file path.
* @param string $source_id
* The ID of the source to check. Defaults to the database.
*/
protected function runBackup($destination_id = 'manual', $source_id = 'db') {
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH);
$this->assertResponse(200);
$edit = array(
'destination_id' => $destination_id,
'source_id' => $source_id,
);
$this->drupalPost(NULL, $edit, 'Backup now');
$this->assertResponse(200);
// Confirm the response is as expected. This is split up into separate
// pieces because it'd be more effort than is necessary right now to confirm
// what the exact filename is.
if ($source_id === 'db') {
$this->assertText('Default Database backed up successfully');
}
else {
$this->assertText(' backed up successfully');
}
$this->assertText('in destination');
if ($source_id === 'db') {
$this->assertLink('download');
$this->assertLink('restore');
$this->assertLink('delete');
}
}
/**
* Delete all of the files in a specific backup destination.
*
* @param string $destination_id
* The ID of the destination to check. Defaults to the manual file path.
*/
protected function deleteBackups($destination_id = 'manual') {
$destination = backup_migrate_get_destination($destination_id);
$files = $this->listBackupFiles($destination_id);
if (!empty($files)) {
foreach ($files as $file_id => $file) {
$destination->delete_file($file_id);
}
}
}
/**
* Work out whether a backup filename includes a timestamp.
*
* @param object $file
* The backup file to examine.
*
* @return mixed
* Returns 1 if found, 0 if not found, FALSE if an error occurs.
*/
protected function fileHasTimestamp($file) {
require_once dirname(__FILE__) . '/../includes/files.inc';
// Get the default filename, this is used later.
$default_filename = _backup_migrate_default_filename();
$ext = implode('.', $file->ext);
$pattern = "/{$default_filename}-(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d)-(\d\d)-(\d\d).{$ext}/";
return preg_match($pattern, $file->file_info['filename']);
}
/**
* Confirm that a backup filename includes a timestamp.
*
* @param object $file
* The backup file to examine.
*
* @return bool
* Indicates whether the file includes a timestamp.
*/
protected function assertFileTimestamp($file) {
return $this->assertTrue($this->fileHasTimestamp($file));
}
/**
* Confirm that a backup filename does not include a timestamp.
*
* @param object $file
* The backup file to examine.
*
* @return bool
* Indicates whether the file does not include a timestamp.
*/
protected function assertNoFileTimestamp($file) {
return !$this->assertFalse($this->fileHasTimestamp($file));
}
/**
* Get a profile.
*
* @param string $profile_id
* The name of the profile to load. Defaults to 'default'.
*
* @return object
* The profile object.
*/
protected function getProfile($profile_id = 'default') {
require_once dirname(__FILE__) . '/../includes/profiles.inc';
return backup_migrate_get_profile($profile_id);
}
/**
* Confirm the most recently sent e-mail(s) contain the expected string.
*
* @param string $field_name
* Name of field or message property to assert: subject, body, id, etc.
* @param string $string
* String to search for.
* @param int $expected
* Number of times $string should occur in the field.
* @param int $email_depth
* Number of emails to search for string, starting with most recent.
*
* @return bool
* TRUE on pass, FALSE on fail.
*
* @see DrupalWebTestCase::assertMailString()
*/
protected function assertMailStringCount($field_name, $string, $expected, $email_depth) {
$mails = $this->drupalGetMails();
$number_of_mails = count($mails);
$string_count = 0;
for ($i = $number_of_mails - 1; $i >= $number_of_mails - $email_depth && $i >= 0; $i--) {
$mail = $mails[$i];
// Normalize whitespace, as it isn't eacy to know what the mail system
// might have done. Any run of whitespace becomes a single space.
$normalized_mail = preg_replace('/\\s+/', ' ', $mail[$field_name]);
$normalized_string = preg_replace('/\\s+/', ' ', $string);
$string_count += substr_count($normalized_mail, $normalized_string);
}
$mail_count = min($number_of_mails, $email_depth);
$message = format_plural($mail_count, 'Text "@needle" was found @stringcount times in field "@field" of the most recent email message.', 'Text "@needle" was found @stringcount times in field "@field" of the @mailcount most recent email messages.', array(
'@needle' => $string,
'@stringcount' => $string_count,
'@field' => $field_name,
'@mailcount' => $mail_count,
));
return $this->assertTrue(($string_count === $expected), $message);
}
}
@@ -0,0 +1,276 @@
<?php
/**
* @file
* Tests for different parts of the Backup Migrate system.
*/
/**
* Test that the front page still loads.
*/
class BmTestBasics extends BmTestBase {
/**
* Define this test class.
*/
public static function getInfo() {
return array(
'name' => 'Basic tests',
'description' => 'Run through basic scenarios and functionality.',
'group' => 'backup_migrate',
);
}
/**
* {@inheritdoc}
*/
public function setUp(array $modules = array()) {
parent::setUp($modules);
// Log in as user 1, so that permissions are irrelevant.
$this->loginUser1();
}
/**
* Verify the main page has the expected form, then run a basic backup.
*/
public function testQuickBackup() {
// Ensure that the private file system is working correctly.
$this->drupalGet('admin/config/media/file-system');
$this->assertResponse(200);
$edit = array();
$this->drupalPost(NULL, $edit, 'Save configuration');
$this->assertResponse(200);
$this->assertText('The configuration options have been saved.');
// Load the main B&M page.
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH);
$this->assertResponse(200);
// @todo Confirm each of the tabs are present.
// @todo Confirm each of the local tasks are present.
// Confirm the form has the expected fields.
$this->assertFieldByName('source_id');
$this->assertFieldByName('destination_id');
$this->assertFieldByName('profile_id');
$this->assertFieldByName('copy');
$this->assertFieldByName('copy_destination_id');
$this->assertFieldByName('description_enabled');
// This item should not have a value "selected", it just defaults to the
// first item being the active item.
$items = array('db', 'files', 'archive');
$this->assertSelectOptions('edit-source-id', $items);
$this->assertNoOptionsSelected('edit-source-id');
// This item should have a value "selected", not just the first item. Note:
// if the 'manual' backup option isn't available then the private directory
// path is not set correctly.
$items = array('manual', 'download');
$this->assertSelectOptions('edit-destination-id', $items);
$this->assertOptionSelected('edit-destination-id', 'download');
// This item should not have a value "selected", it just defaults to the
// first item being the active item.
$items = array('default');
$this->assertSelectOptions('edit-profile-id', $items);
$this->assertNoOptionsSelected('edit-profile-id');
// This item should not have a value "selected", it just defaults to the
// first item being the active item.
$items = array('manual', 'download');
$this->assertSelectOptions('edit-copy-destination-id', $items);
$this->assertNoOptionsSelected('edit-copy-destination-id');
// Generate a backup and confirm it was created correctly.
$edit = array(
'destination_id' => 'manual',
);
$this->drupalPost(NULL, $edit, 'Backup now');
$this->assertResponse(200);
// Confirm the response is as expected. This is split up into separate
// pieces because it'd be more effort than is necessary right now to confirm
// what the exact filename is.
$this->assertText('Default Database backed up successfully');
$this->assertText('in destination Manual Backups Directory');
$this->assertLink('download');
$this->assertLink('restore');
$this->assertLink('delete');
// Try requesting the backup file.
$xpath = $this
->xpath('//a[normalize-space(text())=:label]', array(
':label' => 'download',
));
$this->verbose($xpath);
$this->assertTrue(isset($xpath[0]['href']));
$this->assertNotNull($xpath[0]['href']);
// @todo This doesn't work on drupalci, so work out how to fix it.
// $this->drupalGet($xpath[0]['href']);
$this->assertResponse(200);
}
/**
* Test the custom validators.
*/
public function testFieldValidators() {
// Need this file loaded for the custom validators.
module_load_include('advanced_settings.inc', 'backup_migrate');
$field = 'mock_field';
$element = array(
'#value' => 'a',
'#title' => '',
'#parents' => array($field),
);
// Test the memory limit validator.
$element['#title'] = 'Mock Field (Memory Limit)';
$test_values = array(
// Value to be tested => validity.
// Special meaning: no limit.
'-1' => TRUE,
'50' => TRUE,
// 5 megabytes.
'5M' => TRUE,
// 500 kilobytes.
'.5M' => TRUE,
// 5 gigabytes.
'5G' => TRUE,
'.5G' => TRUE,
'1.5G' => TRUE,
'0' => TRUE,
'a' => FALSE,
'-2' => FALSE,
// You cannot have half a byte.
'1.5' => FALSE,
'5T' => FALSE,
'5 G' => FALSE,
'.5.5G' => FALSE,
);
foreach ($test_values as $value => $valid) {
$this->assertValidFieldValue('backup_migrate_memory_limit_validate', $element, $value, $valid, 'memory limit value');
}
// Test the positive non-zero integer validator.
$element['#title'] = 'Mock Field (Unsigned Integer)';
$test_values = array(
'0' => TRUE,
'1' => TRUE,
'10000' => TRUE,
// NaN.
'a' => FALSE,
// Not an integer.
'.5' => FALSE,
// Not positive.
'-1' => FALSE,
// Largest integer.
// @code
// PHP_INT_MAX => TRUE,
// @endcode
// Resolves to a decimal.
// @code
// (PHP_INT_MAX + 1) => FALSE,
// @endcode
);
foreach ($test_values as $value => $valid) {
$this->assertValidFieldValue('backup_migrate_unsigned_integer_validate', $element, $value, $valid, 'zero or a positive integer');
}
// Test the validator for decimals ranging from 0 to 1.
$element['#title'] = 'Mock Field (Decimal between 0 and 1)';
$test_values = array(
'0' => TRUE,
'1' => TRUE,
'0.1' => TRUE,
'.1' => TRUE,
'1.1' => FALSE,
'-1' => FALSE,
'-1.1' => FALSE,
'2' => FALSE,
'a' => FALSE,
);
foreach ($test_values as $value => $valid) {
$this->assertValidFieldValue('backup_migrate_fraction_validate', $element, $value, $valid, 'decimal between 0 and 1');
}
}
/**
* Asserts that the content of a field passes its associated validation.
*
* @param string $validator
* Drupal validator function callback.
* @param array $element
* Input for error setter.
* @param string $value
* Field value to be tested.
* @param bool $value_is_valid
* Expected outcome.
* @param string $type
* Description of value sub-type.
*/
protected function assertValidFieldValue($validator, array $element, $value, $value_is_valid, $type) {
$form = array();
$form_state = array();
$field = 'mock_field';
$element['#value'] = $value;
form_clear_error();
call_user_func_array($validator, array($element, &$form_state, $form));
$errors = form_get_errors();
if ($value_is_valid) {
$args = array(
'%value' => $value,
'%type' => $type,
);
$msg = t('%value is a valid %type.', $args);
$result = $this->assertTrue(empty($errors[$field]), $msg);
}
else {
$args = array(
'%value' => $value,
'%type' => $type,
'%msg' => strip_tags($errors[$field]),
);
$msg = t('%value is not a valid %type. Error message: "%msg".', $args);
$result = $this->assertFalse(empty($errors[$field]), $msg);
}
return $result;
}
/**
* Confirm backup_migrate_to_bytes() works.
*/
public function testBackupMigrateToBytes() {
// PHP manual:
// http://php.net/manual/en/ini.core.php#ini.memory-limit
// '-1' is a reserved value meaning 'no limit'.
$input = '-1';
$expected = -1;
$this->assertEqual(backup_migrate_to_bytes($input), $expected);
// PHP would halt before this, but let us test anyway.
$input = 'nonsense';
$expected = 0;
$this->assertEqual(backup_migrate_to_bytes($input), $expected);
// This is 123 bytes, but there is a bug in B&M that turns
// this into 12.5 megabytes.
$input = '123';
$expected = 12582912;
$this->assertEqual(backup_migrate_to_bytes($input), $expected);
// 45 megabytes.
$input = '45M';
$expected = 47185920;
$this->assertEqual(backup_migrate_to_bytes($input), $expected);
// 8 gigabytes.
$input = '8G';
$expected = 8589934592;
$this->assertEqual(backup_migrate_to_bytes($input), $expected);
}
}
// @todo Test permissions.
// @todo Test admin forms.
@@ -0,0 +1,104 @@
<?php
/**
* @file
* Test extended functionality as provided by Ctools.
*/
/**
* Class for testing CTools' extended functionality.
*/
class BmTestCtools extends BmTestBase {
/**
* Define this test class.
*/
public static function getInfo() {
return array(
'name' => 'CTools tests',
'description' => 'Test integration with the CTools module.',
'group' => 'backup_migrate',
'dependencies' => array('ctools'),
);
}
/**
* {@inheritdoc}
*/
public function setUp(array $modules = array()) {
$modules[] = 'bm_test';
$modules[] = 'ctools';
parent::setUp($modules);
// Log in as user 1, so that permissions are irrelevant.
$this->loginUser1();
}
/**
* Confirm automated settings exist.
*/
public function testSettingsPage() {
// Load the B&M Settings page.
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/settings');
$this->assertResponse(200);
// Does the mock schedule exist?
$this->assertText('Mock weekly database schedule');
// Does the mock source exist?
$this->assertText('Mock file directory');
// Does the mock destination exist?
$this->assertText('Mock e-mail destination');
// Load the B&M Schedule page.
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/schedule');
$this->assertResponse(200);
// Does the mock schedule exist?
$this->assertText('Mock weekly database schedule');
// Does the mock schedule contain the appropriate values?
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/schedule/edit/mock_db_weekly');
$this->assertResponse(200);
$fields = _bm_test_get_mock_schedule();
// @todo Deal with periods, but now I need sleep.
// See the get_frequency_period() method in includes/schedules.inc.
unset($fields['period']);
// Test the destination selection with its own assertion.
$this->assertOptionSelected('edit-destination-id', $fields['destination_id']);
unset($fields['destination_id']);
foreach ($fields as $key => $field) {
$id = 'edit-' . str_replace('_', '-', $key);
$this->assertFieldById($id, $field, 'Found field by id "' . $id . '" and value "' . $field . '".');
}
// Does the mock source contain the appropriate values?
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/settings/source/edit/mock_file_directory');
$this->assertResponse(200);
$fields = _bm_test_get_mock_source();
unset($fields['subtype']);
foreach ($fields as $key => $field) {
$id = 'edit-' . str_replace('_', '-', $key);
$this->assertFieldById($id, $field, 'Found field by id "' . $id . '" and value "' . $field . '".');
}
// Does the mock destination contain the appropriate values?
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/settings/destination/edit/mock_email');
$this->assertResponse(200);
$fields = _bm_test_get_mock_destination();
unset($fields['subtype']);
foreach ($fields as $key => $field) {
$id = 'edit-' . str_replace('_', '-', $key);
$this->assertFieldById($id, $field, 'Found field by id "' . $id . '" and value "' . $field . '".');
}
}
}
@@ -0,0 +1,207 @@
<?php
/**
* @file
* Test email delivery.
*/
/**
* Test email delivery.
*/
class BmTestEmail extends BmTestBase {
/**
* Define this test class.
*/
public static function getInfo() {
return array(
'name' => 'Email handling',
'description' => 'Confirm email handling works as intended.',
'group' => 'backup_migrate',
);
}
/**
* {@inheritdoc}
*/
public function setUp(array $modules = array()) {
parent::setUp($modules);
// Log in as user 1, so that permissions are irrelevant.
$this->loginUser1();
}
/**
* Confirm the whole email process.
*/
public function testAddEmailDestination() {
// See if we can add a destination.
// Load the email destination Add page.
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/settings/destination/add/email');
$this->assertResponse(200);
// Verify all of the expected fields exist.
$this->assertFieldByName('name');
$this->assertFieldByName('name', 'Untitled Destination');
$this->assertFieldByName('machine_name');
$this->assertFieldByName('location');
// Set up test values.
$test_source = strtolower($this->randomName(16));
$address = strtolower($this->randomName(10)) . '@example.com';
$test_destination = strtolower($this->randomName(16));
// Submit e-mail destination form with invalid values.
$this->submitDestinationEmail('', $test_destination, $address);
$this->assertText(t('Destination name field is required.'), 'Name required.');
$this->submitDestinationEmail($this->randomString(16), '', $address);
$this->assertText(t('Machine-readable name field is required.'), 'Machine name required.');
$this->submitDestinationEmail($this->randomString(16), $test_destination, '');
$this->assertText(t('Email Address field is required.'), 'E-mail required.');
// Step 1, set-up.
// Create a test destination.
$this->submitDestinationEmail($this->randomString(16), $test_destination, $address);
$this->assertText(t('Your destination was saved'));
// Create a test source.
// @todo Test the source add form.
// @todo Maybe add a note somewhere about how we are using a small
// source on purpose, so as to not break the testing system.
$this->submitSourceFiles($this->randomString(16), $test_source, drupal_get_path('module', 'backup_migrate') . '/tests/files/');
$this->assertText(t('Your source was saved'));
// Run a manual back-up so we have a file to compare against.
$this->runBackup('manual', $test_source);
$files = $this->listBackupFiles();
$key = key($files);
// Confirm the back-up file exists.
$this->assertNotEqual($key, NULL, 'A backup file was found.');
$file = $files[$key];
// Copied from destinations.email.inc to build a compatible parameter.
$attachment = new stdClass();
$attachment->filename = $file->name;
$attachment->path = $file->path;
// Step 2, e-mail generated through the Quick Backup form.
// Run a backup per e-mail.
$this->runBackup($test_destination, $test_source);
// Confirm that an e-mail was sent.
$captured_emails = $this->drupalGetMails(array('id' => 'backup_migrate_destination_mail', 'to' => $address));
$this->verboseEmail();
$this->assertEqual(count($captured_emails), 1, 'A back-up was mailed.');
// Does the attachment occur in the captured e-mail?
// Note that the e-mail from Step 2 is tested against the back-up file from
// Step 1.
$file_data = fread(fopen($attachment->path, "r"), filesize($attachment->path));
$encoded_file_data = chunk_split(base64_encode($file_data), 70, "\r\n");
$this->assertMailString('body', $encoded_file_data, 1);
// Step 3, e-mail generated through the main helper function.
// Make sure the new $address is never the same as the old one.
$address = strtolower($this->randomName(1 + strlen($address))) . '@example.com';
_backup_migrate_destination_email_mail_backup($attachment, $address);
// Confirm that an e-mail is sent.
$captured_emails = $this->drupalGetMails(array('id' => 'backup_migrate_destination_mail', 'to' => $address));
$this->verboseEmail();
$this->assertEqual(count($captured_emails), 1, 'A back-up was mailed.');
// Check if the Subject field contains the filename.
$this->assertMailString('subject', $attachment->filename, 1);
// Check if the body contains the filename.
$this->assertMailString('body', $attachment->filename, 1);
// Step 4, (partial) e-mail generated through a mime_mail() object.
// Build an e-mail.
$test_mail = new mime_mail();
$boundary = "b" . md5(uniqid(time()));
// Make sure the new $address is never the same as the old one.
$address = strtolower($this->randomName(1 + strlen($address))) . '@example.com';
$attach = fread(fopen($attachment->path, "r"), filesize($attachment->path));
$test_mail->add_attachment($attach, $attachment->filename, "application/octet-stream");
$message = $test_mail->build_multipart($boundary);
$params = array(
'body' => $message,
'subject' => 'test',
'headers' => array(
'MIME-Version' => "1.0",
'Content-Type' => "multipart/mixed; boundary=\"$boundary\"",
),
);
drupal_mail('backup_migrate', 'destination_mail', $address, '', $params);
$captured_emails = $this->drupalGetMails(array('id' => 'backup_migrate_destination_mail', 'to' => $address));
$this->verboseEmail();
// Confirm that an e-mail was sent.
$this->assertEqual(count($captured_emails), 1, 'A back-up was mailed.');
// Does the boundary occur in the captured e-mail?
$this->assertMailString('body', '--' . $boundary, 1);
// How many boundaries?
$expected = count($test_mail->parts) + 1;
$this->assertMailStringCount('body', '--' . $boundary, $expected, 1);
// Cleanup - purge all backups.
$this->deleteBackups();
}
/**
* Submits the destination form for E-mails.
*
* @param string $name
* The name of the destination.
* @param string $machine_name
* The machine name of the destination.
* @param string $mail
* The e-mail address of the destination.
*/
public function submitDestinationEmail($name, $machine_name, $mail) {
$this->drupalGet('admin/config/system/backup_migrate/settings/destination/add/email');
$this->assertResponse(200);
$edit = array();
$edit['name'] = $name;
$edit['machine_name'] = $machine_name;
$edit['location'] = $mail;
$this->drupalPost(NULL, $edit, t('Save destination'));
$this->assertResponse(200);
}
/**
* Submits the source form for Files.
*
* @param string $name
* The name of the source.
* @param string $machine_name
* The machine name of the source.
* @param string $path
* The path of the source.
*/
public function submitSourceFiles($name, $machine_name, $path) {
$this->drupalGet('admin/config/system/backup_migrate/settings/source/add/filesource');
$this->assertResponse(200);
$edit = array();
$edit['name'] = $name;
$edit['machine_name'] = $machine_name;
$edit['location'] = $path;
$this->drupalPost(NULL, $edit, t('Save source'));
$this->assertResponse(200);
}
}
@@ -0,0 +1,170 @@
<?php
/**
* @file
* Tests the profiles functionality.
*/
/**
* Test that the front page still loads.
*/
class BmTestProfiles extends BmTestBase {
/**
* Define this test class.
*/
public static function getInfo() {
return array(
'name' => 'Profiles tests',
'description' => 'Run through basic scenarios and functionality.',
'group' => 'backup_migrate',
);
}
/**
* {@inheritdoc}
*/
public function setUp(array $modules = array()) {
parent::setUp($modules);
// Log in as user 1, so that permissions are irrelevant.
$this->loginUser1();
}
/**
* Verify the profile page has the expected functionality available.
*/
public function testProfilePage() {
// Load the main B&M page.
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/settings');
$this->assertResponse(200);
// Confirm the page has the expected settings details.
$this->assertText('Settings Profiles');
$this->assertText('Default Settings');
$this->assertLink('Create a new settings profile');
}
/**
* Confirm adding a new backup process works.
*/
public function testAddDefaultProfile() {
require_once dirname(__FILE__) . '/../includes/files.inc';
require_once dirname(__FILE__) . '/../includes/profiles.inc';
// Load the main B&M page.
$this->drupalGet(BACKUP_MIGRATE_MENU_PATH . '/settings/profile/add');
$this->assertResponse(200);
$filename = _backup_migrate_default_filename();
$defaults = _backup_migrate_profile_default_profile();
// Verify all of the expected fields exist.
$this->assertFieldByName('name');
$this->assertFieldByName('name', 'Untitled Profile');
$this->assertFieldByName('machine_name');
$this->assertFieldByName('filename');
$this->assertFieldByName('filename', $filename);
// @todo Confirm all of the expected options are present.
$this->assertFieldByName('append_timestamp');
$this->assertFieldByName('timestamp_format');
$this->assertFieldByName('timestamp_format', $defaults['timestamp_format']);
$this->assertFieldByName('filters[compression]');
$items = $this->supportedCompressors();
$this->assertSelectOptions('edit-filters-compression', $items);
$this->assertOptionSelected('edit-filters-compression', 'gzip');
$this->assertFieldByName('filters[sources][db][exclude_tables][]');
$this->assertFieldByName('filters[sources][db][nodata_tables][]');
$this->assertFieldByName('filters[sources][db][utils_lock_tables]');
$this->assertFieldByName('filters[sources][files][exclude_filepaths]');
$this->assertFieldByName('filters[sources][archive][exclude_filepaths]');
$this->assertFieldByName('filters[utils_site_offline]');
$this->assertFieldByName('filters[utils_site_offline_message]');
$this->assertFieldByName('filters[utils_description]');
$this->assertFieldByName('filters[use_cli]');
$this->assertFieldByName('filters[ignore_errors]');
$this->assertFieldByName('filters[notify_success_enable]');
$this->assertFieldByName('filters[notify_success_email]');
$this->assertFieldByName('filters[notify_failure_enable]');
$this->assertFieldByName('filters[notify_failure_email]');
}
/**
* Confirm the backup filename processes work as expected.
*/
public function testFilenameOptions() {
// Load the profile. This will be interacted with directly because otherwise
// the number of form fields will likely make it impossible to execute
// properly due to the max_input_vars setting defaulting to 1000.
$profile = $this->getProfile();
// Run a backup.
$this->runBackup();
// Confirm that there is only one file and it has a timestamp of some sort.
$files1 = $this->listBackupFiles();
$this->verbose($files1);
$this->assertTrue(count($files1) === 1, 'One backup file was found.');
$this->assertFileTimestamp(array_shift($files1));
// Run another backup.
$this->runBackup();
// Confirm that there are two backup files.
$files1b = $this->listBackupFiles();
$this->verbose($files1b);
$this->assertTrue(count($files1b) === 2, 'Two backup files were found.');
// Cleanup before the next test - purge existing backups.
$this->deleteBackups();
// Change settings to "create separate backups".
$profile->append_timestamp = 0;
$profile->save();
// Run a backup.
$this->runBackup();
// Confirm that separate files are retained.
$files2 = $this->listBackupFiles();
$this->verbose($files2);
$this->assertTrue(count($files2) === 1, 'One backup file was found.');
$this->assertNoFileTimestamp(array_shift($files2));
// Run another backup.
$this->runBackup();
// Confirm that separate files are retained.
$files2b = $this->listBackupFiles();
$this->verbose($files2b);
$this->assertTrue(count($files2b) === 2, 'Two backup files were found.');
// Cleanup before the next test - purge existing backups.
$this->deleteBackups();
// Change settings to "overwrite".
$profile->append_timestamp = 2;
$profile->save();
// Run a backup.
$this->runBackup();
// Confirm that a new file was created.
$files3 = $this->listBackupFiles();
$this->verbose($files3);
$this->assertTrue(count($files3) === 1, 'One backup file was found.');
$this->assertNoFileTimestamp(array_shift($files3));
// Run the backup again.
$this->runBackup();
// Confirm that a new file was not created.
$files3b = $this->listBackupFiles();
$this->verbose($files3b);
$this->assertTrue(count($files3b) === 1, 'One backup file was found.');
// Cleanup - purge all backups.
$this->deleteBackups();
}
}
@@ -0,0 +1,141 @@
<?php
/**
* @file
* Test module updates.
*/
/**
* Test module update 7310.
*/
class BmTestUpdate7310 extends BmTestBase {
/**
* Define this test class.
*/
public static function getInfo() {
return array(
'name' => 'Update 7310',
'description' => 'Confirm update 7310 works as intended.',
'group' => 'backup_migrate',
);
}
/**
* {@inheritdoc}
*/
public function setUp(array $modules = array()) {
parent::setUp($modules);
// Log in as user 1, so that permissions are irrelevant.
$this->loginUser1();
}
/**
* Test update 7310.
*/
public function testUpdate7310() {
require_once dirname(__FILE__) . '/../includes/destinations.inc';
require_once dirname(__FILE__) . '/../includes/schedules.inc';
$this->assertEqual(function_exists('backup_migrate_update_7310'), TRUE, 'Update 7310 exists.');
// First test what happens when there are no e-mail destinations.
// Execute the update function.
$result = backup_migrate_update_7310();
// We should be getting a notice as a result.
$message = "The following notice was displayed: &quot;$result&quot;";
$expected = 'No destinations were affected by this change.';
$this->assertEqual($expected, $result, $message);
// Next, add e-mail destinations and see what happens then.
// Create two mock e-mail destinations.
$address = strtolower($this->randomName(10)) . '@example.com';
$email_destination_id = strtolower($this->randomName(16));
$this->submitDestinationEmail('Mock e-mail destination', $email_destination_id, $address);
$address = strtolower($this->randomName(10)) . '@example.com';
$email_destination_id = strtolower($this->randomName(16));
$this->submitDestinationEmail('Mock e-mail destination', $email_destination_id, $address);
$this->assertText(t('Your destination was saved'));
// Create mock schedules with different types of destinations.
$mock_schedule_1 = $this->randomName(10);
$mock_schedule_2 = $this->randomName(10);
$mock_schedule_3 = $this->randomName(10);
$this->submitSchedule($mock_schedule_1, 'test_1', 'scheduled', '');
$this->assertText(t('Your schedule was saved'));
$this->submitSchedule($mock_schedule_2, 'test_2', $email_destination_id, '');
$this->assertText(t('Your schedule was saved'));
$this->submitSchedule($mock_schedule_3, 'test_3', 'scheduled', $email_destination_id);
$this->assertText(t('Your schedule was saved'));
$destinations = db_select('backup_migrate_destinations', 'bmd')->fields('bmd', array('machine_name'))->condition('subtype', 'email', '=')->execute()->fetchAllAssoc('machine_name', PDO::FETCH_ASSOC);
$destinations = array_keys($destinations);
// Execute the update function.
$result = backup_migrate_update_7310();
// We should be getting a notice as a result.
$expected = htmlspecialchars("Schedules that back up to e-mail destinations have been disabled. Check that you are using the correct e-mail addresses, then re-enable manually. The following schedules have been disabled: <ul><li>{$mock_schedule_2}</li><li>{$mock_schedule_3}</li></ul>");
$message = "The following notice was displayed: &quot;$result&quot;.";
$this->assertEqual($expected, $result, $message);
$schedules_query = db_select('backup_migrate_schedules', 'bms')->fields('bms', array('machine_name', 'enabled'));
$schedules = $schedules_query->execute()->fetchAllAssoc('machine_name', PDO::FETCH_ASSOC);
// Check that the correct values have changed.
$this->assertEqual($schedules['test_1']['enabled'], 1, 'The file back-up schedule remained enabled.');
$this->assertEqual($schedules['test_2']['enabled'], 0, 'The e-mail back-up schedule was disabled.');
$this->assertEqual($schedules['test_2']['enabled'], 0, 'The file back-up schedule with an e-mail copy was disabled.');
}
/**
* Submits the destination form for E-mails.
*
* @param string $name
* The name of the destination.
* @param string $machine_name
* The machine name of the destination.
* @param string $mail
* The e-mail address of the destination.
*/
public function submitDestinationEmail($name, $machine_name, $mail) {
$this->drupalGet('admin/config/system/backup_migrate/settings/destination/add/email');
$this->assertResponse(200);
$edit = array();
$edit['name'] = $name;
$edit['machine_name'] = $machine_name;
$edit['location'] = $mail;
$this->drupalPost(NULL, $edit, t('Save destination'));
$this->assertResponse(200);
}
/**
* Submits the schedule form.
*
* @param string $name
* The name of the destination.
* @param string $machine_name
* The machine name of the destination.
* @param string $destination_id
* The destination ID to use.
* @param string $copy_destination_id
* The destination ID to use for an optional copy.
*/
public function submitSchedule($name, $machine_name, $destination_id, $copy_destination_id = NULL) {
$this->drupalGet('admin/config/system/backup_migrate/schedule/add');
$this->assertResponse(200);
$edit = array();
$edit['name'] = $name;
$edit['machine_name'] = $machine_name;
$edit['destination_id'] = $destination_id;
if (!empty($copy_destination_id)) {
$edit['copy'] = TRUE;
$edit['copy_destination_id'] = $copy_destination_id;
}
$this->drupalPost(NULL, $edit, t('Save schedule'));
$this->assertResponse(200);
}
}
@@ -0,0 +1,13 @@
name = "Backup and Migrate Mock Module"
description = "Mock module for testing the Backup and Migrate module."
package = Other
core = 7.x
hidden = TRUE
dependencies[] = simpletest
dependencies[] = backup_migrate
; Information added by Drupal.org packaging script on 2020-07-15
version = "7.x-3.9"
core = "7.x"
project = "backup_migrate"
datestamp = "1594807678"
@@ -0,0 +1,121 @@
<?php
/**
* @file
* Mock module to help and test hooks.
*/
/**
* A base class for mock exportables.
*/
class BmTestItem {
/**
* Edit this to true to make a default item disabled initially.
*
* @var bool
*/
public $disabled = FALSE;
/**
* Indicates the API version to use.
*
* @var int
*/
public $api_version = 1;
}
/**
* Implements hook_ctools_plugin_api().
*/
function bm_test_ctools_plugin_api($module = NULL, $api = NULL) {
if ($module == "backup_migrate" && $api == "backup_migrate_exportables") {
return array("version" => "1");
}
}
/**
* Implements hook_exportables_backup_migrate_schedules().
*/
function bm_test_exportables_backup_migrate_schedules() {
$export = array();
$item = new BmTestItem();
$mock_record = _bm_test_get_mock_schedule();
foreach ($mock_record as $key => $field) {
$item->$key = $field;
}
$export['mock_db_weekly'] = $item;
return $export;
}
/**
* Helper function to create a mock schedule.
*/
function _bm_test_get_mock_schedule() {
return array(
'machine_name' => 'mock_db_weekly',
'name' => 'Mock weekly database schedule',
'source_id' => 'db',
'destination_id' => 'scheduled',
'copy_destination_id' => '',
'profile_id' => 'default',
'keep' => 4,
'period' => 604800,
'enabled' => TRUE,
'cron' => 'builtin',
'cron_schedule' => '0 4 * * *',
);
}
/**
* Implements hook_exportables_backup_migrate_sources().
*/
function bm_test_exportables_backup_migrate_sources() {
$export = array();
$item = new BmTestItem();
$mock_record = _bm_test_get_mock_source();
foreach ($mock_record as $key => $field) {
$item->$key = $field;
}
$export['mock_file_directory'] = $item;
return $export;
}
/**
* Helper function to create a mock source.
*/
function _bm_test_get_mock_source() {
return array(
'machine_name' => 'mock_file_directory',
'name' => 'Mock file directory',
'location' => '/dev/null',
'subtype' => 'filesource',
);
}
/**
* Implements hook_exportables_backup_migrate_destinations().
*/
function bm_test_exportables_backup_migrate_destinations() {
$export = array();
$item = new BmTestItem();
$mock_record = _bm_test_get_mock_destination();
foreach ($mock_record as $key => $field) {
$item->$key = $field;
}
$export['mock_email'] = $item;
return $export;
}
/**
* Helper function to create a mock destination.
*/
function _bm_test_get_mock_destination() {
return array(
'machine_name' => 'mock_email',
'name' => 'Mock e-mail destination',
'location' => 'test@example.com',
'subtype' => 'email',
);
}
@@ -0,0 +1,7 @@
—Nay, Traveller! rest. This lonely yew-tree stands
Far from all human dwelling: what if here
No sparkling rivulet spread the verdant herb;
What if these barren boughs the bee not loves;
Yet, if the wind breathe soft, the curling waves,
That break against the shore, shall lull thy mind
By one soft impulse saved from vacancy.