### Install Guzzle 3.x via Composer Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/README.md This snippet shows how to install Guzzle 3.x using Composer, a dependency manager for PHP. It includes commands to install Composer and add Guzzle as a project dependency. ```bash curl -sS https://getcomposer.org/installer | php php composer.phar require guzzle/guzzle:~3.9 ``` -------------------------------- ### GET /client/request Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md Performs a GET request using the updated client interface which now supports an options array for configuration. ```APIDOC ## GET /client/request ### Description Sends a GET request to the specified URI with optional headers and request configuration options. ### Method GET ### Endpoint /client/request ### Parameters #### Query Parameters - **uri** (string) - Required - The target URI. - **headers** (array) - Optional - Key-value pairs for request headers. - **options** (array) - Optional - Configuration options including curl settings, query parameters, or download locations. ### Request Example { "uri": "/resource", "options": { "timeout": 30, "headers": { "Accept": "application/json" } } } ### Response #### Success Response (200) - **body** (mixed) - The response content. #### Response Example { "status": "success", "data": "..." } ``` -------------------------------- ### Implementing PSR-3 Logger Interface in a Class Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/psr/log/README.md This example demonstrates how to inject a PSR-3 LoggerInterface into a class constructor. It shows how to safely check for the logger's existence before invoking logging methods like info(). ```php logger = $logger; } public function doSomething() { if ($this->logger) { $this->logger->info('Doing work'); } // do something useful } } ``` -------------------------------- ### Dropbox Remote Storage Module with Chunked Uploads Source: https://context7.com/wpplugins/updraftplus/llms.txt Manages backup uploads to Dropbox using OAuth2 and chunked uploads for progress tracking. It includes a callback for updating upload progress and an example of initiating a backup. ```php class UpdraftPlus_BackupModule_dropbox extends UpdraftPlus_BackupModule { public function chunked_callback($offset, $uploadid, $fullpath = false) { global $updraftplus; $updraftplus->jobdata_set('updraf_dbid_'.$this->current_file_hash, $uploadid); $updraftplus->jobdata_set('updraf_dbof_'.$this->current_file_hash, $offset); if ($this->current_file_size > 0) { $percent = round(100*($offset/$this->current_file_size), 1); $updraftplus->record_uploaded_chunk($percent, "$uploadid, $offset", $fullpath); } } } $dropbox_module = new UpdraftPlus_BackupModule_dropbox(); $dropbox_module->backup(array('backup_2024-01-15_MySite_abc123-db.gz')); ``` -------------------------------- ### Using Guzzle Static Facade Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md Illustrates how to use Guzzle with static methods by mounting the static facade class. This allows for a more convenient way to interact with Guzzle's functionalities without instantiating a client object directly. ```php use Guzzle\Http\StaticClient; // Mount the static facade class StaticClient::mount(); // Use Guzzle with static methods $response = StaticClient::get('http://example.com/resource'); ``` -------------------------------- ### PHP: Comprehensive Logging with UpdraftPlus Source: https://context7.com/wpplugins/updraftplus/llms.txt Demonstrates the use of the global $updraftplus object's log() method for various logging levels (notice, warning, error) and destinations. It also shows how to open a log file for a specific backup job. Dependencies: UpdraftPlus plugin. ```php global $updraftplus; // Basic notice logging $updraftplus->log("Backup started at " . date('r')); // Warning level - persists through job $updraftplus->log("Low disk space detected", 'warning', 'lowdiskspace'); // Error level - displayed to user $updraftplus->log(__("Backup failed: insufficient permissions", 'updraftplus'), 'error'); // Log with destination specification $updraftplus->log("Restore progress: 50%", 'notice-restore'); // Skip database logging for high-frequency messages $updraftplus->log("Processing file $i of $total", 'notice', false, true); // Open log file for a backup job $updraftplus->logfile_open($nonce); // Log file created at: wp-content/updraft/log.{nonce}.txt ``` -------------------------------- ### Removed Guzzle ParserRegister Methods Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md The `get()` and `set()` methods on `Guzzle\Parser\ParserRegister` have been removed. Use `getParser()` and `registerParser()` respectively. ```PHP // Removed Guzzle\Parser\ParserRegister::get(). Use getParser() ``` ```PHP // Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). ``` -------------------------------- ### Run Acceptance Tests Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/rackspace/php-opencloud/CONTRIBUTING.md Executes the full suite of acceptance tests. Requires specific environment variables (PHP_OpenCloud_USERNAME and PHP_OpenCloud_API_KEY) and proper PHP configuration. ```php php tests/OpenCloud/Smoke/Runner.php ``` -------------------------------- ### Guzzle Request-Response Injection Change Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md Injecting a request object onto a response object is no longer supported. The `get and set` methods still exist but are no-ops until removal. ```PHP // Removed the injecting of a request object onto a response object. The methods to get and set a request still exist but are a no-op until removed. ``` -------------------------------- ### Creating Cache Adapters with Guzzle Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md Demonstrates the use of `Guzzle\Cache\CacheAdapterFactory::fromCache()` for easily creating cache adapters. This method simplifies the process of setting up caching mechanisms within Guzzle applications. ```php use Guzzle\Cache\CacheAdapterFactory; // Create a cache adapter instance $cacheAdapter = CacheAdapterFactory::fromCache('file', array('cache.dir' => '/tmp/cache')); // Use the cache adapter... ``` -------------------------------- ### Run Unit Tests Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/rackspace/php-opencloud/CONTRIBUTING.md Executes the project's unit test suite using PHPUnit. This command should be run from the project root to ensure code coverage and correctness. ```bash vendor/bin/phpunit ``` -------------------------------- ### Include Composer Autoloader in PHP Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/README.md This PHP code snippet demonstrates how to include Composer's autoloader, which is necessary after installing Guzzle or other dependencies via Composer. This allows for automatic loading of classes. ```php require 'vendor/autoload.php'; ``` -------------------------------- ### Render Admin Templates with Variable Extraction Source: https://context7.com/wpplugins/updraftplus/llms.txt Shows how to include admin interface templates using the UpdraftPlus admin object and how to extend template directories via filters. ```php global $updraftplus_admin; $updraftplus_admin->include_template('wp-admin/settings/downloading-and-restoring.php', false, array('backup_history' => $history)); add_filter('updraftplus_template_directories', function($dirs) { $dirs['myaddon'] = '/path/to/my/addon/templates'; return $dirs; }); ``` -------------------------------- ### Deprecated Guzzle Default Headers Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md Marks `Guzzle\Service\Client::getDefaultHeaders()` and `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->getConfig()->getPath('request.options/headers')` for getting and `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')` for setting default headers. ```PHP // Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers'). ``` ```PHP // Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value'). ``` -------------------------------- ### UpdraftPlus Options API for Settings Management Source: https://context7.com/wpplugins/updraftplus/llms.txt Provides static methods for managing plugin options, integrating with the WordPress Settings API. It includes functions to get, update, delete options, check user permissions, and retrieve admin page URLs. ```php $backup_interval = UpdraftPlus_Options::get_updraft_option('updraft_interval', 'daily'); UpdraftPlus_Options::update_updraft_option('updraft_interval', 'twicedaily'); UpdraftPlus_Options::delete_updraft_option('updraft_last_backup'); if (UpdraftPlus_Options::user_can_manage()) { // Show admin interface } $settings_url = UpdraftPlus_Options::admin_page_url() . '?page=updraftplus'; $schedules = array( 'manual', 'every4hours', 'every8hours', 'twicedaily', 'daily', 'weekly', 'fortnightly', 'monthly' ); ``` -------------------------------- ### log() Method Source: https://context7.com/wpplugins/updraftplus/llms.txt Provides a comprehensive logging system that writes messages to log files and can optionally display them in the admin interface. ```APIDOC ## log() Method ### Description Comprehensive logging system that writes to log files and optionally displays messages in the admin interface. ### Method `log(string $message, string $level = 'notice', string $identifier = false, bool $skip_db_logging = false)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php global $updraftplus; // Basic notice logging $updraftplus->log("Backup started at " . date('r')); // Warning level - persists through job $updraftplus->log("Low disk space detected", 'warning', 'lowdiskspace'); // Error level - displayed to user $updraftplus->log(__("Backup failed: insufficient permissions", 'updraftplus'), 'error'); // Log with destination specification $updraftplus->log("Restore progress: 50%", 'notice-restore'); // Skip database logging for high-frequency messages $updraftplus->log("Processing file $i of $total", 'notice', false, true); // Open log file for a backup job $updraftplus->logfile_open($nonce); // Log file created at: wp-content/updraft/log.{nonce}.txt ``` ### Response None (logs are written to file or displayed in admin) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Configuring Request Options via Client Configuration Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md Illustrates how to configure default request options, such as headers or query string parameters, for all requests made by a Guzzle client. This is achieved by setting values in the client's configuration using `setPath`. ```php use Guzzle\Http\Client; $client = new Client('http://example.com'); // Set a default header for all requests $client->getConfig()->setPath('request.options/headers/X-Custom-Header', 'MyValue'); // Set default query string parameters $client->getConfig()->setPath('request.options/query', array('default_param' => 'default_value')); // Retrieve default headers $headers = $client->getConfig()->getPath('request.options/headers'); ``` -------------------------------- ### PHP: Chunked Download Utility with UpdraftPlus Source: https://context7.com/wpplugins/updraftplus/llms.txt Handles downloading large files in chunks with automatic resume support using the UpdraftPlus chunked_download() method. It requires a storage module and specifies download parameters. Dependencies: UpdraftPlus plugin, storage module. ```php global $updraftplus; // Download a backup file from remote storage $result = $updraftplus->chunked_download( $file, // Filename to download $method, // Storage module with chunked_download() method $remote_size, // Total size of remote file $manually_break_up, // Whether to manually chunk (true) or stream (false) $passback, // Value to pass to callback $chunk_size // Chunk size if manually breaking up (default 1MB) ); // Returns true on success, false on failure // Downloaded file stored in: wp-content/updraft/{filename} ``` -------------------------------- ### PHP Action Hooks Source: https://context7.com/wpplugins/updraftplus/llms.txt Standard WordPress actions used to trigger backup processes programmatically. ```APIDOC ## ACTION updraft_backup ### Description Triggers a file-only backup via the WordPress action system. ### Method PHP Hook ### Usage ```php do_action('updraft_backup'); ``` ## ACTION updraft_backup_all ### Description Triggers a full backup including both files and the database. ### Method PHP Hook ### Usage ```php do_action('updraft_backup_all'); ``` ``` -------------------------------- ### POST /wp-admin/admin-ajax.php (Backup Now) Source: https://context7.com/wpplugins/updraftplus/llms.txt Triggers an immediate backup of files, database, or both via the WordPress AJAX interface. ```APIDOC ## POST /wp-admin/admin-ajax.php ### Description Initiates an on-demand backup process. This endpoint is typically called from the WordPress admin dashboard to trigger immediate file or database backups. ### Method POST ### Endpoint /wp-admin/admin-ajax.php ### Parameters #### Request Body - **action** (string) - Required - Must be 'updraft_backup' - **subaction** (string) - Required - Set to 'backupnow' - **backupnow_nodb** (int) - Optional - Set to 1 to exclude database - **backupnow_nofiles** (int) - Optional - Set to 1 to exclude files - **updraftplus_backup_nonce** (string) - Required - Security nonce for verification ### Request Example { "action": "updraft_backup", "subaction": "backupnow", "backupnow_nodb": 0, "backupnow_nofiles": 0, "updraftplus_backup_nonce": "abc123nonce" } ### Response #### Success Response (200) - **status** (string) - Success message indicating the backup process has started. ``` -------------------------------- ### Executing Commands with Guzzle Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/CHANGELOG.md Explains that `Guzzle\Service\ClientInterface::execute()` now accepts an array, a single command, or a Traversable object. This provides flexibility in how commands are executed against a Guzzle client. ```php use Guzzle\Service\ClientInterface; use Guzzle\Service\Command\CommandInterface; // Assuming $client is an instance of ClientInterface // Execute a single command $client->execute($command); // Execute an array of commands $client->execute(array($command1, $command2)); // Execute a Traversable of commands $client->execute(new ArrayIterator(array($command1, $command2))); ``` -------------------------------- ### Migrate ServiceDescription Commands to Operations Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/UPGRADING.md Demonstrates the renaming of command-related methods to operation-related methods in Guzzle ServiceDescription. ```php use Guzzle\Service\Description\ServiceDescription; $sd = new ServiceDescription(); $sd->getOperations(); $sd->hasOperation($name); $sd->getOperation($name); $sd->addOperation($operation); ``` -------------------------------- ### Migrate LogPlugin Implementation Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/guzzle/guzzle/UPGRADING.md Updates the LogPlugin usage to reflect new namespaces and the transition from verbosity levels to MessageFormatter formats. ```php use Guzzle\Log\ClosureLogAdapter; use Guzzle\Log\MessageFormatter; use Guzzle\Plugin\Log\LogPlugin; $client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT))); ``` -------------------------------- ### Implementing PSR-3 LoggerInterface Source: https://github.com/wpplugins/updraftplus/blob/master/vendor/psr/log/README.md How to inject and use the LoggerInterface within a class to perform logging operations. ```APIDOC ## PSR-3 LoggerInterface Usage ### Description This interface defines the standard logging methods (emergency, alert, critical, error, warning, notice, info, debug) that a logger implementation must provide. ### Implementation To use the logger, type-hint `Psr\Log\LoggerInterface` in your constructor or method signatures. ### Request Example ```php use Psr\Log\LoggerInterface; class Foo { private $logger; public function __construct(LoggerInterface $logger = null) { $this->logger = $logger; } public function doSomething() { if ($this->logger) { $this->logger->info('Doing work'); } } } ``` ### Response - **Success**: The logger processes the message according to the specific implementation (e.g., writing to a file, database, or console). ``` -------------------------------- ### schedule_backup() Source: https://context7.com/wpplugins/updraftplus/llms.txt Configures WordPress cron schedules for automatic backups. ```APIDOC ## schedule_backup() ### Description Configures WordPress cron schedules for automatic backups. ### Method This is not a direct method call but rather a configuration via WordPress options and filters. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Schedule configuration via WordPress options update_option('updraft_interval', 'daily'); // File backup schedule update_option('updraft_interval_database', 'daily'); // Database backup schedule update_option('updraft_retain', 4); // Keep last 4 file backups update_option('updraft_retain_db', 7); // Keep last 7 database backups // Schedule hooks registered by UpdraftPlus // 'updraft_backup' - File backup cron hook // 'updraft_backup_database' - Database backup cron hook // Check next scheduled backup $next_file_backup = wp_next_scheduled('updraft_backup'); $next_db_backup = wp_next_scheduled('updraft_backup_database'); if ($next_file_backup) { echo "Next file backup: " . date('Y-m-d H:i:s', $next_file_backup); } // Custom schedule filter add_filter('cron_schedules', function($schedules) { $schedules['every6hours'] = array( 'interval' => 21600, 'display' => __('Every 6 hours') ); return $schedules; }); ``` ### Response Configuration is saved to WordPress options and cron schedules. #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Integrate UpdraftCentral Remote Control Source: https://context7.com/wpplugins/updraftplus/llms.txt Explains how to register custom command classes for remote management and initialize the Remote Procedure Call (RPC) object. ```php add_action('updraftplus_remotecontrol_command_classes', function($classes) { $classes['mycommand'] = 'My_UpdraftCentral_Commands'; return $classes; }); global $updraftplus; $ud_rpc = $updraftplus->get_udrpc('migrator.updraftplus.com'); $ud_rpc->set_can_generate(true); ``` -------------------------------- ### decrypt() Method Source: https://context7.com/wpplugins/updraftplus/llms.txt Decrypts encrypted database backup files using AES-256 encryption. ```APIDOC ## decrypt() Method ### Description Decrypts encrypted database backup files using AES-256 encryption. ### Method `decrypt(string $encrypted_file, string $encryption_key, bool $to_temp_file)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php global $updraftplus; $encrypted_file = '/path/to/backup_2024-01-15_MySite_abc123-db.gz.crypt'; $encryption_key = 'my-secret-encryption-phrase'; // Decrypt to permanent file $result = $updraftplus->decrypt($encrypted_file, $encryption_key, false); // Returns: array('fullpath' => '/path/to/backup_2024-01-15_MySite_abc123-db.gz', 'basename' => 'backup_...-db.gz') // Decrypt to temporary file (for viewing without keeping) $result = $updraftplus->decrypt($encrypted_file, $encryption_key, true); // Returns: array('fullpath' => '/path/to/decrypt_backup_...-db.gz.crypt.tmp', 'basename' => 'backup_...-db.gz') // Encryption uses Rijndael (AES) with phpseclib // Supports OpenSSL, mcrypt, or pure PHP engines ``` ### Response Returns an array with 'fullpath' and 'basename' on success, or false on failure. #### Success Response (200) `array('fullpath' => string, 'basename' => string)` #### Response Example ```json { "fullpath": "/path/to/backup_2024-01-15_MySite_abc123-db.gz", "basename": "backup_2024-01-15_MySite_abc123-db.gz" } ``` ``` -------------------------------- ### Chunked Upload/Download Utilities Source: https://context7.com/wpplugins/updraftplus/llms.txt Utilities for handling large file uploads and downloads in chunks, with automatic resume capabilities. ```APIDOC ## chunked_upload() ### Description Handles large file uploads in chunks with automatic resume capability. ### Method `chunked_upload(object $caller, string $file, string $cloudpath, string $logname, int $chunk_size, int $uploaded_size, bool $singletons)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Chunked upload implementation global $updraftplus; // Upload configuration $chunk_size = 5242880; // 5MB chunks $result = $updraftplus->chunked_upload( $caller, // Storage module object with upload_chunk() method $file, // Filename to upload $cloudpath, // Destination path in cloud storage $logname, // Name for logging purposes $chunk_size, // Size of each chunk $uploaded_size, // Already uploaded bytes (for resume) $singletons // Whether to upload as single file if small ); // The $caller object must implement: // - chunked_upload($file, $fp, $chunk_index, $upload_size, $upload_start, $upload_end) // - chunked_upload_finish($file) [optional] ``` ### Response Returns upload status or result. #### Success Response (200) Details depend on the storage module's implementation. #### Response Example ```json { "status": "success", "message": "Chunk uploaded successfully" } ``` ## chunked_download() ### Description Downloads large files in chunks with automatic resume support. ### Method `chunked_download(string $file, object $method, int $remote_size, bool $manually_break_up, mixed $passback, int $chunk_size = 1048576)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php global $updraftplus; // Download a backup file from remote storage $result = $updraftplus->chunked_download( $file, // Filename to download $method, // Storage module with chunked_download() method $remote_size, // Total size of remote file $manually_break_up, // Whether to manually chunk (true) or stream (false) $passback, // Value to pass to callback $chunk_size // Chunk size if manually breaking up (default 1MB) ); // Returns true on success, false on failure // Downloaded file stored in: wp-content/updraft/{filename} ``` ### Response Returns true on success, false on failure. #### Success Response (200) `true` #### Response Example `true` ``` -------------------------------- ### Manage Backup History via UpdraftPlus Options Source: https://context7.com/wpplugins/updraftplus/llms.txt Demonstrates how to retrieve and update the backup history array stored in WordPress options. The history uses Unix timestamps as keys and maps to arrays containing file paths and metadata. ```php $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); $backup_history = array( 1705312200 => array( 'db' => 'backup_2024-01-15-0930_MySite_abc123def456-db.gz', 'plugins' => array('backup_2024-01-15-0930_MySite_abc123def456-plugins.zip'), 'nonce' => 'abc123def456' ) ); UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backup_history); ``` -------------------------------- ### Initiate WordPress File Backup - PHP Source: https://context7.com/wpplugins/updraftplus/llms.txt This snippet demonstrates how to trigger a complete WordPress file backup using UpdraftPlus actions. It can be initiated manually or through scheduled WordPress cron events. Dependencies include the UpdraftPlus plugin being active. ```php do_action('updraft_backup'); do_action('updraft_backup_all'); global $updraftplus; $updraftplus->backup_files(); ``` -------------------------------- ### Initiate WordPress Database Backup - PHP Source: https://context7.com/wpplugins/updraftplus/llms.txt This code shows how to trigger a WordPress database backup using UpdraftPlus. The backup can be encrypted and uses either mysqldump or a PHP-based method. The output is typically a compressed SQL file stored in the updraft directory. ```php // Trigger database backup via WordPress action do_action('updraft_backup_database'); ```