* : Ruta base absoluta del ZIP privado; se añade un identificador aleatorio al nombre. * * [--exclude=] * : Rutas relativas a wp-content, separadas por comas; sin patrones glob. * * [--exclude-tables=] * : Nombres completos de tablas a excluir, separados por comas. */ public static function export(array $args, array $options): void { $operation = new DCTSollers_Migration_Operation(); try { $allowed = array ( 'file', 'exclude', 'exclude-tables', ); self::arguments($args, $options, $allowed); DCTSollers_Migration_Package::environment(); $output = self::output($options['file']); $excluded = array_values(array_unique(array_merge(DCTSollers_Migration_Files::exclusions(), self::list($options['exclude'] ?? '')))); foreach ($excluded as $path) { DCTSollers_Migration_Files::path($path); } $tables = self::list($options['exclude-tables'] ?? ''); $directory = $operation->start(); $temporary = $operation->archive($output); WP_CLI::warning('Evita escrituras durante la exportación. La copia no es atómica entre archivos y base de datos.'); DCTSollers_Migration_Package::create($directory, $temporary, $excluded, $tables); $operation->assert_locked(); $validation = $directory . '/verification'; DCTSollers_Migration_Files::directory($validation, 0700); DCTSollers_Migration_Package::extract($temporary, $validation); $operation->assert_locked(); DCTSollers_Migration_Files::publish($temporary, $output); $success = 'Exportación verificada: ' . $output; } catch (Throwable $error) { $message = $error->getMessage(); } finally { $message = $operation->finish($message ?? null); } if (isset($message)) { if (isset($success)) { $message .= ' El ZIP ya se ha publicado y verificado en ' . $output . '; consérvalo y revisa la limpieza pendiente.'; } WP_CLI::error(self::terminal($message)); } WP_CLI::success(self::terminal($success)); } ################################################ # # import # # Valida e importa un paquete confiable con modo obligatorio merge o mirror. # ################################################ /** * Importa un ZIP confiable; no crea copia previa ni garantiza rollback. * * Requiere arranque aislado explícito y finalización manual desde la terminal. * El sitio permanece en mantenimiento hasta completar todos los pasos mostrados. * * ## OPTIONS * * --file= * : Ruta absoluta de un ZIP propio de DCT Sollers. * * --mode= * : merge conserva archivos y tablas extra; mirror elimina extras no excluidos. * --- * options: * - merge * - mirror * --- * * [--dry-run] * : Valida integridad, destinos y datos sin cambiar archivos ni tablas del sitio. * * [--yes] * : Confirma la operación destructiva sin preguntar. * * [--home-url=] * : URL pública final. Por defecto conserva la del destino. * * [--site-url=] * : URL de WordPress final. Por defecto conserva la del destino. */ public static function import(array $args, array $options): void { global $wp_version; $maintenance = false; $operation = new DCTSollers_Migration_Operation(); $database = $operation->database(); try { $allowed = array ( 'file', 'mode', 'dry-run', 'yes', 'home-url', 'site-url', ); self::arguments($args, $options, $allowed); DCTSollers_Migration_Package::environment(); if (($options['mode'] ?? null) !== 'merge' && ($options['mode'] ?? null) !== 'mirror') { throw new RuntimeException('Debes indicar --mode=merge o --mode=mirror.'); } $file = realpath($options['file']); if ($file === false || !is_file($file) || !is_readable($file)) { throw new RuntimeException('El paquete no es un archivo legible.'); } if (file_exists(ABSPATH . '.maintenance') || is_link(ABSPATH . '.maintenance')) { throw new RuntimeException('El sitio ya está en mantenimiento. No se modificará ese estado.'); } if (!isset($options['dry-run'])) { DCTSollers_Migration_Process::isolate($options); } $target = DCTSollers_Migration_Import::target($options); $directory = $operation->start(); WP_CLI::log('Validando ZIP, inventario e integridad…'); $manifest = DCTSollers_Migration_Package::extract($file, $directory); if (version_compare($manifest['context']['wordpress'], $wp_version, '>')) { throw new RuntimeException('Actualiza WordPress del destino antes de importar una versión posterior.'); } if (version_compare($manifest['context']['php'], PHP_VERSION, '>')) { WP_CLI::warning('El origen usa una versión de PHP posterior. Comprueba la compatibilidad de sus plugins.'); } $plan = DCTSollers_Migration_Import::plan($directory, $manifest, $target, $options['mode'], $database); WP_CLI::log('Tablas incluidas: ' . count($manifest['tables'])); WP_CLI::log('Archivos a sustituir/crear: ' . count($plan['files']['write'])); WP_CLI::log('Archivos extra a eliminar: ' . count($plan['files']['delete'])); WP_CLI::log('Directorios extra a eliminar tras vaciarlos: ' . count($plan['files']['directories'])); WP_CLI::log('Tablas extra a eliminar: ' . count($plan['extra_tables'])); WP_CLI::log('Modo: ' . $options['mode'] . '; home: ' . $target['home'] . '; site: ' . $target['site']); if (isset($options['dry-run'])) { $success = 'Validación completada. No se han modificado archivos ni tablas del sitio.'; } else { self::confirm($options); $operation->assert_locked(); $maintenance_token = bin2hex(random_bytes(16)); $content = DCTSollers_Migration_Maintenance::content($maintenance_token); // Exclusively create WordPress maintenance at its required core path, never an uploads/data file. // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $handle = fopen(ABSPATH . '.maintenance', 'x'); if ($handle === false) { throw new RuntimeException('No se puede activar mantenimiento.'); } $maintenance = true; // Write through the exclusive handle so another maintenance file cannot be overwritten. // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite, PluginCheck.CodeAnalysis.WriteFile.ABSPATHDetected $written = fwrite($handle, $content); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose fclose($handle); if ($written !== strlen($content)) { throw new RuntimeException('No se puede escribir mantenimiento.'); } WP_CLI::log('Preparando tablas y adaptando URLs y rutas…'); $database->prepare($directory, $manifest, $plan['map'], false); $operation->assert_locked(); WP_CLI::log('Restaurando archivos…'); DCTSollers_Migration_Import::restore_files($directory, $manifest, $plan['files']); $operation->assert_locked(); $database->publish($plan['existing'], $manifest['excluded_tables'], $options['mode']); $operation->assert_locked(); $finalization = self::finalize($target, $maintenance_token); } } catch (Throwable $error) { $message = $error->getMessage(); if ($maintenance) { $message .= ' El sitio queda en mantenimiento. No hay rollback ni copia automática: revisa el estado parcial antes de retirar .maintenance.'; } } finally { $message = $operation->finish($message ?? null); } if (isset($message)) { WP_CLI::error(self::terminal($message)); } if (isset($finalization)) { WP_CLI::log('Datos importados. El sitio sigue en mantenimiento hasta completar la finalización.'); WP_CLI::log(self::terminal('Finalización pendiente; ejecuta en la terminal: ' . $finalization)); return; } WP_CLI::success(self::terminal($success)); } ################################################ # # arguments # # Rechaza opciones desconocidas, operandos y rutas no absolutas. # ################################################ private static function arguments(array $args, array $options, array $allowed): void { if ($args !== array() || array_diff(array_keys($options), $allowed) !== array()) { throw new RuntimeException('Argumentos no reconocidos. Consulta wp help dct-sollers export/import.'); } if (!is_string($options['file'] ?? null) || !str_starts_with($options['file'], '/') || str_contains($options['file'], "\0")) { throw new RuntimeException('--file requiere una ruta absoluta.'); } foreach ($options as $name => $value) { if ($name === 'yes' || $name === 'dry-run') { if ($value !== true) { // CLI-only diagnostic; terminal() escapes controls at the output boundary. // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped throw new RuntimeException('--' . $name . ' no acepta valor.'); } } elseif (!is_string($value) || $value === '') { // CLI-only diagnostic; terminal() escapes controls at the output boundary. // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped throw new RuntimeException('--' . $name . ' necesita un valor.'); } } } ################################################ # # list # # Normaliza listas explícitas de rutas o tablas separadas por comas. # ################################################ private static function list(string $value): array { if ($value === '') { return array(); } $items = array_map('trim', explode(',', $value)); if (in_array('', $items, true)) { throw new RuntimeException('La lista contiene elementos vacíos.'); } return array_values(array_unique($items)); } ################################################ # # output # # Genera un nombre impredecible para un ZIP privado sin sobrescribir archivos. # ################################################ private static function output(string $file): string { $parent = realpath(dirname($file)); if ($parent === false || !wp_is_writable($parent) || strtolower(pathinfo($file, PATHINFO_EXTENSION)) !== 'zip') { throw new RuntimeException('El destino debe ser un ZIP en un directorio existente y escribible.'); } // Server/CLI paths are not magic-quoted: validate the type and resolve with realpath below. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $document_root = $_SERVER['DOCUMENT_ROOT'] ?? ABSPATH; if (!is_string($document_root)) { throw new RuntimeException('DOCUMENT_ROOT debe ser una cadena cuando esté definido.'); } $public_roots = array_merge(array(ABSPATH, $document_root), array_values(DCTSollers_Migration_Locations::roots())); foreach ($public_roots as $public) { $root = realpath($public); if ($root !== false && ($parent === $root || str_starts_with($parent . '/', rtrim($root, '/') . '/'))) { throw new RuntimeException('Guarda el ZIP fuera del directorio público del sitio.'); } } $target = $parent . '/' . basename($file); if (file_exists($target) || is_link($target)) { throw new RuntimeException('El archivo de destino ya existe; no se sobrescribirá.'); } $target = $parent . '/' . pathinfo($file, PATHINFO_FILENAME) . '-' . bin2hex(random_bytes(16)) . '.zip'; if (file_exists($target) || is_link($target)) { throw new RuntimeException('El archivo de destino ya existe; no se sobrescribirá.'); } return $target; } ################################################ # # confirm # # Exige confirmación explícita sin interrumpir la limpieza de recursos al cancelar. # ################################################ private static function confirm(array $options): void { WP_CLI::warning('Se sobrescribirán archivos, tablas, usuarios y contraseñas. NO se creará copia previa ni habrá rollback. Importa solo paquetes de confianza.'); if (!isset($options['yes'])) { // WP_CLI::confirm() exits on rejection; a native prompt lets our finally blocks clean up before failing. // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite fwrite(STDERR, '¿Continuar? [y/N] '); $answer = fgets(STDIN); if ($answer === false || strtolower(trim($answer)) !== 'y') { throw new RuntimeException('Importación cancelada sin modificar el sitio.'); } } } ################################################ # # finalize # # Genera pasos externos encadenados; mantenimiento se retira solo tras completarlos. # ################################################ private static function finalize(array $target, string $maintenance_token): string { $commands = array ( self::subcommand(array('eval-file', __DIR__ . '/finalize.php', $target['home'], $target['site'], $target['upload_path'], $target['upload_url_path']), true), self::subcommand(array('core', 'update-db'), true), self::subcommand(array('rewrite', 'flush'), false), self::subcommand(array('core', 'is-installed'), false), self::subcommand(array('eval-file', __DIR__ . '/verify.php'), true), self::subcommand(array('eval-file', __DIR__ . '/flush-cache.php'), false), self::subcommand(array('eval-file', __DIR__ . '/finish-maintenance.php', $maintenance_token), true), ); return implode(' && ', $commands); } ################################################ # # subcommand # # Formatea un comando para el operador sin ejecutarlo ni heredar el aislamiento. # ################################################ private static function subcommand(array $arguments, bool $skip_plugins): string { $flags = array ( '--path=' . ABSPATH, '--skip-packages', ); if ($skip_plugins) { $flags[] = '--skip-plugins'; $flags[] = '--skip-themes'; } if (WP_CLI::has_config('allow-root') && WP_CLI::get_config('allow-root') === true) { $flags[] = '--allow-root'; } return 'wp ' . implode(' ', array_map('escapeshellarg', array_merge($flags, $arguments))); } ################################################ # # terminal # # Hace visibles los controles de diagnósticos CLI sin aplicar escape HTML al terminal. # ################################################ private static function terminal(string $message): string { return preg_replace_callback('/[\x00-\x1f\x7f]|\xC2[\x80-\x9f]/', static function (array $match): string { $escaped = ''; foreach (str_split($match[0]) as $byte) { $escaped .= sprintf('\\x%02X', ord($byte)); } return $escaped; }, $message); } }