Skip to content
Snippets Groups Projects
command-core.php 78.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    <?php
    /**
     * Downloads, installs, updates, and manages a CiviCRM installation.
     *
     * ## EXAMPLES
     *
     *     # Download the latest stable CiviCRM core archive.
     *     $ wp civicrm core download
     *     Checking file to download...
     *     Downloading file...
     *     Success: CiviCRM downloaded to /tmp/
     *
     *     # Install the current stable version of CiviCRM with localization files.
     *     $ wp civicrm core install --l10n
     *     Success: Installed 1 of 1 plugins.
     *     Success: CiviCRM localization downloaded and extracted to: /wp-content/plugins/civicrm
     *
     *     # Check for the latest stable version of CiviCRM.
     *     $ wp civicrm core check-update
     *     +-----------+---------+-------------------------------------------------------------------------------------------+
     *     | Package   | Version | Package URL                                                                               |
     *     +-----------+---------+-------------------------------------------------------------------------------------------+
     *     | WordPress | 5.67.0  | https://storage.googleapis.com/civicrm/civicrm-stable/5.67.0/civicrm-5.67.0-wordpress.zip |
     *     | L10n      | 5.67.0  | https://storage.googleapis.com/civicrm/civicrm-stable/5.67.0/civicrm-5.67.0-l10n.tar.gz   |
     *     +-----------+---------+-------------------------------------------------------------------------------------------+
     *
     * @since 5.69
     */
    class CLI_Tools_CiviCRM_Command_Core extends CLI_Tools_CiviCRM_Command {
    
      /**
       * @var string
       * The URL to check for CiviCRM upgrades.
       * @since 5.69
       * @access private
       */
      private $upgrade_url = 'https://download.civicrm.org/check';
    
      /**
       * @var string
       * The Google API URL to check for all top-level CiviCRM prefixes.
       * @since 5.69
       * @access private
       */
      private $google_url = 'https://storage.googleapis.com/storage/v1/b/civicrm/o/?delimiter=/';
    
      /**
       * @var string
       * The Google API query param to append for checking CiviCRM stable versions.
       * @since 5.69
       * @access private
       */
      private $google_prefix_stable = 'prefix=civicrm-stable/';
    
      /**
       * @var string
       * The common part of the Google API URL for CiviCRM release archive downloads.
       * @since 5.69
       * @access private
       */
      private $google_download_url = 'https://storage.googleapis.com/civicrm/';
    
      /**
       * Activates the CiviCRM plugin and loads the database.
       *
       * ## OPTIONS
       *
       * [--dbname=<dbname>]
       * : MySQL database name of your CiviCRM database. Defaults to the WordPress database name.
       *
       * [--dbpass=<dbpass>]
       * : MySQL password for your CiviCRM database. Defaults to the WordPress MySQL database password.
       *
       * [--dbuser=<dbuser>]
       * : MySQL username for your CiviCRM database. Defaults to the WordPress MySQL database username.
       *
       * [--dbhost=<dbhost>]
       * : MySQL host for your CiviCRM database. Defaults to the WordPress MySQL host.
       *
       * [--locale=<locale>]
       * : Locale to use for installation. Defaults to "en_US".
       *
       * [--ssl=<ssl>]
       * : The SSL setting for your website, e.g. '--ssl=on'. Defaults to "on".
       *
       * [--site-url=<site-url>]
       * : Domain for your website, e.g. 'mysite.com'.
       *
       * [--yes]
       * : Answer yes to the confirmation message.
       *
       * ## EXAMPLES
       *
       *     # Activate the CiviCRM plugin.
       *     $ wp civicrm core activate
       *     CiviCRM database credentials:
       *     +----------+-----------------------+
       *     | Field    | Value                 |
       *     +----------+-----------------------+
       *     | Database | civicrm_database_name |
       *     | Username | foo                   |
       *     | Password | dbpassword            |
       *     | Host     | localhost             |
       *     | Locale   | en_US                 |
       *     | SSL      | on                    |
       *     +----------+-----------------------+
       *     Do you want to continue? [y/n] y
       *     Creating file /httpdocs/wp-content/uploads/civicrm/civicrm.settings.php
       *     Success: CiviCRM data files initialized.
       *     Creating civicrm_* database tables in civicrm_database_name
       *     Success: CiviCRM database loaded.
       *     Plugin 'civicrm' activated.
       *     Success: Activated 1 of 1 plugins.
       *
       * @since 5.69
       *
       * @param array $args The WP-CLI positional arguments.
       * @param array $assoc_args The WP-CLI associative arguments.
       */
      public function activate($args, $assoc_args) {
    
        // Only install plugin if not already installed.
        $fetcher = new \WP_CLI\Fetchers\Plugin();
        $plugin_installed = $fetcher->get('civicrm');
        if (!$plugin_installed) {
          WP_CLI::error('You need to install CiviCRM first.');
        }
    
        // Get the path to the CiviCRM plugin directory.
        $plugin_path = $this->plugin_path_get();
    
        /*
         * Check for the presence of the CiviCRM core codebase.
         *
         * NOTE: This is *not* the CiviCRM plugin - it is the directory where the common
         * CiviCRM code lives. It always lives in a sub-directory of the plugin directory
         * called "civicrm".
         */
        global $crmPath;
        $crmPath = trailingslashit($plugin_path) . 'civicrm';
        if (!is_dir($crmPath)) {
          WP_CLI::error('CiviCRM core files are missing.');
        }
    
        // We need the CiviCRM classloader so that we can run `Civi\Setup`.
        $classLoaderPath = "$crmPath/CRM/Core/ClassLoader.php";
        if (!file_exists($classLoaderPath)) {
          WP_CLI::error('CiviCRM installer helper file is missing.');
        }
    
        // Grab associative arguments.
        $dbuser = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'dbuser', (defined('DB_USER') ? DB_USER : ''));
        $dbpass = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'dbpass', (defined('DB_PASSWORD') ? DB_PASSWORD : ''));
        $dbhost = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'dbhost', (defined('DB_HOST') ? DB_HOST : ''));
        $dbname = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'dbname', (defined('DB_NAME') ? DB_NAME : ''));
        $locale = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'locale', 'en_US');
        $ssl = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'ssl', 'on');
        $base_url = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'site-url', '');
    
        // Show database parameters.
        WP_CLI::log(WP_CLI::colorize('%GCiviCRM database credentials:%n'));
        $assoc_args['format'] = 'table';
        $feedback = [
          'Database' => $dbname,
          'Username' => $dbuser,
          'Password' => $dbpass,
          'Host' => $dbhost,
          'Locale' => $locale,
          'SSL' => $ssl,
        ];
        $assoc_args['fields'] = array_keys($feedback);
        $formatter = $this->formatter_get($assoc_args);
        $formatter->display_item($feedback);
    
        // Let's give folks a chance to exit now.
        WP_CLI::confirm(WP_CLI::colorize('%GDo you want to continue?%n'), $assoc_args);
    
        // ----------------------------------------------------------------------------
        // Activation and installation.
        // ----------------------------------------------------------------------------
    
        // Set some constants that CiviCRM requires.
        if (!defined('CIVICRM_PLUGIN_DIR')) {
          define('CIVICRM_PLUGIN_DIR', \WP_CLI\Utils\trailingslashit($plugin_path));
        }
        if (!defined('CIVICRM_PLUGIN_URL')) {
          define('CIVICRM_PLUGIN_URL', plugin_dir_url(CIVICRM_PLUGIN_DIR));
        }
    
        // Maybe set SSL.
        if ('on' === $ssl) {
          $_SERVER['HTTPS'] = 'on';
        }
    
        // Initialize civicrm-setup.
        require_once $classLoaderPath;
        CRM_Core_ClassLoader::singleton()->register();
        \Civi\Setup::assertProtocolCompatibility(1.0);
        \Civi\Setup::init(['cms' => 'WordPress', 'srcPath' => $crmPath]);
        $setup = \Civi\Setup::instance();
    
        // Apply essential arguments.
        $setup->getModel()->db = ['server' => $dbhost, 'username' => $dbuser, 'password' => $dbpass, 'database' => $dbname];
        $setup->getModel()->lang = $locale;
    
        /*
         * The "base URL" should already be known, either by:
         *
         * * The "site_url()" setting in WordPress standalone
         * * The URL flag in WordPress Multisite: --url=https://my-domain.com
         *
         * TODO: This means that the `--site_url` flag is basically redundant.
         */
        if (!empty($base_url)) {
          $protocol = ('on' === $ssl ? 'https' : 'http');
          $base_url = $protocol . '://' . $base_url;
          $setup->getModel()->cmsBaseUrl = trailingslashit($base_url);
        }
    
        // Validate system requirements.
        $reqs = $setup->checkRequirements();
        foreach ($reqs->getWarnings() as $msg) {
          WP_CLI::log(sprintf(WP_CLI::colorize('%YWARNING:%n %y(%s) %s:%n %s'), $msg['section'], $msg['name'], $msg['message']));
        }
        $errors = $reqs->getErrors();
        if ($errors) {
          foreach ($errors as $msg) {
            WP_CLI::log(sprintf(WP_CLI::colorize('%RERROR:%n %r(%s) %s:%n %s'), $msg['section'], $msg['name'], $msg['message']));
          }
          WP_CLI::error('Requirements check failed.');
        }
    
        // Install data files.
        $installed = $setup->checkInstalled();
        if (!$installed->isSettingInstalled()) {
          WP_CLI::log(sprintf(WP_CLI::colorize('%GCreating file%n %Y%s%n'), $setup->getModel()->settingsPath));
          $setup->installFiles();
        }
        else {
          WP_CLI::log(sprintf(WP_CLI::colorize('%gFound existing%n %Y%s%n %Gin%n %Y%s%n'), basename($setup->getModel()->settingsPath), dirname($setup->getModel()->settingsPath)));
          switch ($this->conflict_action_pick('civicrm.settings.php')) {
            case 'abort':
              WP_CLI::log(WP_CLI::colorize('%CAborted%n'));
              WP_CLI::halt(0);
    
            case 'overwrite':
              WP_CLI::log(sprintf(WP_CLI::colorize('%GRemoving%n %Y%s%n %Gfrom%n %Y%s%n'), basename($setup->getModel()->settingsPath), dirname($setup->getModel()->settingsPath)));
              $setup->uninstallFiles();
              WP_CLI::log(sprintf(WP_CLI::colorize('%GCreating%n %Y%s%n %Gin%n %Y%s%n'), basename($setup->getModel()->settingsPath), dirname($setup->getModel()->settingsPath)));
              $setup->installFiles();
              break;
    
            case 'keep':
              break;
    
            default:
              WP_CLI::error('Unrecognized action');
          }
        }
    
        WP_CLI::success('CiviCRM data files initialized.');
    
        // Clean the "templates_c" directory to avoid fatal error when overwriting the database.
        if (function_exists('civicrm_initialize')) {
          $this->bootstrap_civicrm();
          $config = CRM_Core_Config::singleton();
          $config->cleanup(1, FALSE);
        }
    
        // Install database.
        if (!$installed->isDatabaseInstalled()) {
          WP_CLI::log(sprintf(WP_CLI::colorize('%GCreating%n %Ycivicrm_*%n %Gdatabase tables in%n %Y%s%n'), $setup->getModel()->db['database']));
          $setup->installDatabase();
        }
        else {
          WP_CLI::log(sprintf(WP_CLI::colorize('%GFound existing%n %Ycivicrm_*%n database tables in%n %Y%s%n'), $setup->getModel()->db['database']));
          switch ($this->conflict_action_pick('database tables')) {
            case 'abort':
              WP_CLI::log(WP_CLI::colorize('%CAborted%n'));
              WP_CLI::halt(0);
    
            case 'overwrite':
              WP_CLI::log(sprintf(WP_CLI::colorize('%GRemoving%n %Ycivicrm_*%n database tables in%n %Y%s%n'), $setup->getModel()->db['database']));
              $setup->uninstallDatabase();
              WP_CLI::log(sprintf(WP_CLI::colorize('%GCreating%n %Ycivicrm_*%n database tables in%n %Y%s%n'), $setup->getModel()->db['database']));
              $setup->installDatabase();
              break;
    
            case 'keep':
              break;
    
            default:
              WP_CLI::error('Unrecognized action');
          }
        }
    
        WP_CLI::success('CiviCRM database loaded.');
    
        // Looking good, let's activate the CiviCRM plugin.
        WP_CLI::run_command(['plugin', 'activate', 'civicrm'], []);
    
      }
    
      /**
       * Back up the CiviCRM plugin files and database.
       *
       * ## OPTIONS
       *
       * [--backup-dir=<backup-dir>]
       * : Path to your CiviCRM backup directory. Default is one level above ABSPATH.
       *
       * [--also-include=<also-include>]
       * : Comma separated list of additional tables to back up based on wildcard search.
       *
       * [--yes]
       * : Answer yes to the confirmation message.
       *
       * ## EXAMPLES
       *
       *     # Standard backup.
       *     $ wp civicrm core backup
       *     Gathering system information.
       *     +------------------------+-----------------------------------------------------------------------+
       *     | Field                  | Value                                                                 |
       *     +------------------------+-----------------------------------------------------------------------+
       *     | Backup directory       | /example.com/civicrm-backup                                           |
       *     | Plugin path            | /example.com/httpdocs/wp-content/plugins/civicrm/                     |
       *     | Database name          | civicrm_db                                                            |
       *     | Database username      | dbuser                                                                |
       *     | Database password      | dbpassword                                                            |
       *     | Database host          | localhost                                                             |
       *     | Settings file          | /example.com/httpdocs/wp-content/uploads/civicrm/civicrm.settings.php |
       *     | Config and Log         | /example.com/httpdocs/wp-content/uploads/civicrm/ConfigAndLog/        |
       *     | Custom PHP             | Not found                                                             |
       *     | Custom templates       | Not found                                                             |
       *     | Compiled templates     | /example.com/httpdocs/wp-content/uploads/civicrm/templates_c/         |
       *     | Extensions directory   | /example.com/httpdocs/wp-content/uploads/civicrm/ext/                 |
       *     | Uploads directory      | /example.com/httpdocs/wp-content/uploads/civicrm/upload/              |
       *     | Image upload directory | /example.com/httpdocs/wp-content/uploads/civicrm/persist/contribute/  |
       *     | File upload directory  | /example.com/httpdocs/wp-content/uploads/civicrm/custom/              |
       *     +------------------------+-----------------------------------------------------------------------+
       *     Do you want to continue? [y/n] y
       *
       *     # Also back up tables not registered with CiviCRM.
       *     # In this case, also exports tables for the "Canadian Tax Receipts" extension.
       *     $ wp civicrm core backup --also-include='cdntaxreceipts_*'
       *     ...
       *
       * @since 5.69
       *
       * @param array $args The WP-CLI positional arguments.
       * @param array $assoc_args The WP-CLI associative arguments.
       */
      public function backup($args, $assoc_args) {
    
        // Grab associative arguments.
        $backup_dir = \WP_CLI\Utils\get_flag_value($assoc_args, 'backup-dir', trailingslashit(dirname(ABSPATH)) . 'civicrm-backup');
        $also_include = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'also-include', '');
    
        // ----------------------------------------------------------------------------
        // Build feedback table.
        // ----------------------------------------------------------------------------
        WP_CLI::log(WP_CLI::colorize('%GGathering system information.%n'));
    
        // Bootstrap CiviCRM.
        $this->bootstrap_civicrm();
    
        // Let's have a look for some CiviCRM variables.
        $config = CRM_Core_Config::singleton();
    
        // Build feedback.
        $feedback = [];
        if (!empty($backup_dir)) {
          $feedback['Backup directory'] = $backup_dir;
        }
        if (defined('CIVICRM_PLUGIN_DIR')) {
          $feedback['Plugin path'] = CIVICRM_PLUGIN_DIR;
        }
        else {
          $feedback['Plugin path'] = 'Not found';
        }
        if (defined('CIVICRM_DSN')) {
          $dsn = DB::parseDSN(CIVICRM_DSN);
          $feedback['Database name'] = $dsn['database'];
          $feedback['Database username'] = $dsn['username'];
          $feedback['Database password'] = $dsn['password'];
          $feedback['Database host'] = $dsn['hostspec'];
        }
        else {
          $feedback['Database Settings'] = 'Not found';
        }
        if (defined('CIVICRM_SETTINGS_PATH')) {
          $feedback['Settings file'] = CIVICRM_SETTINGS_PATH;
        }
        else {
          $feedback['Settings file'] = 'Not found';
        }
        if (!empty($config->configAndLogDir)) {
          $feedback['Config and Log'] = $config->configAndLogDir;
        }
        else {
          $feedback['Config and Log'] = 'Not found';
        }
        if (!empty($config->customPHPPathDir)) {
          $feedback['Custom PHP'] = $config->customPHPPathDir;
        }
        else {
          $feedback['Custom PHP'] = 'Not found';
        }
        if (!empty($config->customTemplateDir)) {
          $feedback['Custom templates'] = $config->customTemplateDir;
        }
        else {
          $feedback['Custom templates'] = 'Not found';
        }
        if (!empty($config->templateCompileDir)) {
          $feedback['Compiled templates'] = $config->templateCompileDir;
        }
        else {
          $feedback['Compiled templates'] = 'Not found';
        }
        if (!empty($config->extensionsDir)) {
          $feedback['Extensions directory'] = $config->extensionsDir;
        }
        else {
          $feedback['Extensions directory'] = 'Not found';
        }
        if (!empty($config->uploadDir)) {
          $feedback['Uploads directory'] = $config->uploadDir;
        }
        else {
          $feedback['Uploads directory'] = 'Not found';
        }
        if (!empty($config->imageUploadDir)) {
          $feedback['Image upload directory'] = $config->imageUploadDir;
        }
        else {
          $feedback['Image upload directory'] = 'Not found';
        }
        if (!empty($config->customFileUploadDir)) {
          $feedback['File upload directory'] = $config->customFileUploadDir;
        }
        else {
          $feedback['File upload directory'] = 'Not found';
        }
    
        // Render feedback.
        $assoc_args['fields'] = array_keys($feedback);
        $formatter = $this->formatter_get($assoc_args);
        $formatter->display_item($feedback);
    
        // Let's give folks a chance to exit now.
        WP_CLI::confirm(WP_CLI::colorize('%GDo you want to continue?%n'), $assoc_args);
    
        // ----------------------------------------------------------------------------
        // Validate backup directory.
        // ----------------------------------------------------------------------------
        $backup_dir = untrailingslashit($backup_dir);
    
        // Maybe create destination directory.
        if (!is_dir($backup_dir)) {
          if (!is_writable(dirname($backup_dir))) {
            WP_CLI::error("Insufficient permission to create directory '{$backup_dir}'.");
          }
          WP_CLI::log("Creating directory '{$backup_dir}'.");
          // Recursively create directory.
          if (!@mkdir($backup_dir, 0777, TRUE)) {
            $error = error_get_last();
            WP_CLI::error("Failed to create directory '{$backup_dir}': {$error['message']}.");
          }
        }
    
        // Sanity check.
        if (!is_writable($backup_dir)) {
          WP_CLI::error("'{$backup_dir}' is not writable by current user.");
        }
    
        // ----------------------------------------------------------------------------
        // Backup procedure.
        // ----------------------------------------------------------------------------
    
        // Maybe add extra filters.
        $also_include_args = '';
        if (!empty($also_include)) {
          $also_include_args = " --also-include={$also_include}";
        }
    
        // Use "wp civicrm db export" to export the CiviCRM database tables.
        WP_CLI::log('');
        WP_CLI::log(WP_CLI::colorize('%GExporting database...%n'));
        $command = 'civicrm db export' . $also_include_args . ' --result-file=' . $backup_dir . '/civicrm-db.sql';
        $options = ['launch' => FALSE, 'return' => FALSE];
        WP_CLI::runcommand($command, $options);
        WP_CLI::success('Database exported.');
    
        // Back up plugin directory.
        WP_CLI::log('');
        WP_CLI::log(WP_CLI::colorize('%GBacking up plugin directory...%n'));
        $plugin_path = $this->plugin_path_get();
        if (!$this->zip_compress($plugin_path, $backup_dir . '/civicrm.zip')) {
          WP_CLI::error('Could not compress plugin archive.');
        }
        WP_CLI::success('Plugin directory backed up.');
    
        // Back up "civicrm.settings.php" file.
        if (defined('CIVICRM_SETTINGS_PATH')) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Settings File...%n'));
          $dest_path = $backup_dir . '/civicrm.settings.php';
          if (file_exists($dest_path) && is_writable($dest_path)) {
            copy(CIVICRM_SETTINGS_PATH, $dest_path);
          }
          elseif (!file_exists($dest_path)) {
            copy(CIVICRM_SETTINGS_PATH, $dest_path);
          }
          else {
            WP_CLI::error("Could not copy '" . CIVICRM_SETTINGS_PATH . "' to backup directory.");
          }
          WP_CLI::success('Settings File backed up.');
        }
    
        // Back up Config and Log directory.
        if (!empty($config->configAndLogDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Config and Log directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->configAndLogDir), $backup_dir . '/civicrm-config-log.zip')) {
            WP_CLI::error('Could not compress Config and Log archive.');
          }
          WP_CLI::success('Config and Log directory backed up.');
        }
    
        // Back up Custom PHP directory.
        if (!empty($config->customPHPPathDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Custom PHP directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->customPHPPathDir), $backup_dir . '/civicrm-custom-php.zip')) {
            WP_CLI::error('Could not compress Custom PHP archive.');
          }
          WP_CLI::success('Custom PHP directory backed up.');
        }
    
        // Back up Custom templates directory.
        if (!empty($config->customTemplateDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Custom Templates directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->customTemplateDir), $backup_dir . '/civicrm-custom-templates.zip')) {
            WP_CLI::error('Could not compress Custom Templates archive.');
          }
          WP_CLI::success('Custom Templates directory backed up.');
        }
    
        // Back up Compiled templates directory.
        if (!empty($config->templateCompileDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Compiled Templates directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->templateCompileDir), $backup_dir . '/civicrm-compiled-templates.zip')) {
            WP_CLI::error('Could not compress Compiled templates archive.');
          }
          WP_CLI::success('Compiled Templates directory backed up.');
        }
    
        // Back up Extensions directory.
        if (!empty($config->extensionsDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Extensions directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->extensionsDir), $backup_dir . '/civicrm-extensions.zip')) {
            WP_CLI::error('Could not compress Extensions archive.');
          }
          WP_CLI::success('Extensions directory backed up.');
        }
    
        // Back up Uploads directory.
        if (!empty($config->uploadDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Uploads directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->uploadDir), $backup_dir . '/civicrm-uploads.zip')) {
            WP_CLI::error('Could not compress Uploads archive.');
          }
          WP_CLI::success('Uploads directory backed up.');
        }
    
        // Back up Image upload directory.
        if (!empty($config->imageUploadDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up Image Uploads directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->imageUploadDir), $backup_dir . '/civicrm-image-uploads.zip')) {
            WP_CLI::error('Could not compress Image Uploads archive.');
          }
          WP_CLI::success('Image Uploads directory backed up.');
        }
    
        // Back up File Uploads directory.
        if (!empty($config->customFileUploadDir)) {
          WP_CLI::log('');
          WP_CLI::log(WP_CLI::colorize('%GBacking up File Uploads directory...%n'));
          if (!$this->zip_compress(untrailingslashit($config->customFileUploadDir), $backup_dir . '/civicrm-file-uploads.zip')) {
            WP_CLI::error('Could not compress File Uploads archive.');
          }
          WP_CLI::success('File Uploads directory backed up.');
        }
    
      }
    
      /**
       * Checks for a CiviCRM version or matching localization archive.
       *
       * ## OPTIONS
       *
       * [--version=<version>]
       * : Specify the version to check. Accepts a version number, 'stable', 'rc' or 'nightly'.
       *
       * [--l10n]
       * : Get the localization file data for the specified version.
       *
       * [--format=<format>]
       * : Render output in a particular format.
       * ---
       * default: table
       * options:
       *   - table
       *   - json
       *   - url
       *   - version
       * ---
       *
       * ## EXAMPLES
       *
       *     # Check for a stable version of CiviCRM
       *     $ wp civicrm core check-version --version=5.17.2
       *     +-----------+---------+-------------------------------------------------------------------------------------------+
       *     | Package   | Version | Package URL                                                                               |
       *     +-----------+---------+-------------------------------------------------------------------------------------------+
       *     | WordPress | 5.17.2  | https://storage.googleapis.com/civicrm/civicrm-stable/5.17.2/civicrm-5.17.2-wordpress.zip |
       *     | L10n      | 5.17.2  | https://storage.googleapis.com/civicrm/civicrm-stable/5.17.2/civicrm-5.17.2-l10n.tar.gz   |
       *     +-----------+---------+-------------------------------------------------------------------------------------------+
       *
       *     # Get the URL for a stable version of CiviCRM
       *     $ wp civicrm core check-version --version=5.17.2 --format=url
       *     https://storage.googleapis.com/civicrm/civicrm-stable/5.17.2/civicrm-5.17.2-wordpress.zip
       *
       *     # Get the URL for a stable version of the CiviCRM localisation archive
       *     $ wp civicrm core check-version --version=5.17.2 --format=url --l10n
       *     https://storage.googleapis.com/civicrm/civicrm-stable/5.17.2/civicrm-5.17.2-l10n.tar.gz
       *
       *     # Get the JSON-formatted data for a stable version of CiviCRM
       *     $ wp civicrm core check-version --version=5.17.2 --format=json
       *     {"version":"5.17.2","tar":{"L10n":"civicrm-stable\/5.17.2\/civicrm-5.17.2-l10n.tar.gz","WordPress":"civicrm-stable\/5.17.2\/civicrm-5.17.2-wordpress.zip"}}
       *
       *     # Get the latest nightly version of CiviCRM
       *     $ wp civicrm core check-version --version=nightly --format=version
       *     5.59.alpha1
       *
       * @subcommand check-version
       *
       * @since 5.69
       *
       * @param array $args The WP-CLI positional arguments.
       * @param array $assoc_args The WP-CLI associative arguments.
       */
      public function check_version($args, $assoc_args) {
    
        // Grab associative arguments.
        $version = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'version', 'stable');
        $l10n = (bool) \WP_CLI\Utils\get_flag_value($assoc_args, 'l10n', FALSE);
        $format = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'format', 'table');
    
        // Pass to "check-update" for "stable", "rc" or "nightly".
        if (in_array($version, ['stable', 'rc', 'nightly'])) {
          $options = ['launch' => FALSE, 'return' => FALSE];
          $command = 'civicrm core check-update --version=' . $version . ' --format=' . $format . (empty($l10n) ? '' : ' --l10n');
          WP_CLI::runcommand($command, $options);
          return;
        }
    
        // Check for valid release.
        $versions = $this->releases_get();
        if (!in_array($version, $versions)) {
          WP_CLI::error(sprintf(WP_CLI::colorize('Version %Y%s%n is not a valid CiviCRM version.'), $version));
        }
    
        // Get the release data.
        $data = $this->release_data_get($version);
    
        switch ($format) {
    
          // URL-only output.
          case 'url':
            if ($l10n) {
              echo $this->google_download_url . $data['L10n'] . "\n";
            }
            else {
              echo $this->google_download_url . $data['WordPress'] . "\n";
            }
            break;
    
          // Version-only output.
          case 'version':
            echo $version . "\n";
            break;
    
          // Display output as json.
          case 'json':
            // Use a similar format to the Version Check API.
            $info = [
              'version' => $version,
              'tar' => $data,
            ];
            $json = json_encode($info);
            if (JSON_ERROR_NONE !== json_last_error()) {
              WP_CLI::error(sprintf(WP_CLI::colorize('Failed to encode JSON: %Y%s.%n'), json_last_error_msg()));
            }
            echo $json . "\n";
            break;
    
          // Display output as table (default).
          case 'table':
          default:
            // Build the rows.
            $rows = [];
            $fields = ['Package', 'Version', 'Package URL'];
            $rows[] = [
              'Package' => 'WordPress',
              'Version' => $version,
              'Package URL' => $this->google_download_url . $data['WordPress'],
            ];
            $rows[] = [
              'Package'  => 'L10n',
              'Version' => $version,
              'Package URL' => $this->google_download_url . $data['L10n'],
            ];
    
            // Display the rows.
            $args = ['format' => $format];
            $formatter = new \WP_CLI\Formatter($args, $fields);
            $formatter->display_items($rows);
    
        }
    
      }
    
      /**
       * Checks for CiviCRM updates via Version Check API.
       *
       * ## OPTIONS
       *
       * [--version=<version>]
       * : Specify the version to get.
       * ---
       * default: stable
       * options:
       *   - nightly
       *   - rc
       *   - stable
       * ---
       *
       * [--l10n]
       * : Get the localization file data for the specified version.
       *
       * [--format=<format>]
       * : Render output in a particular format.
       * ---
       * default: table
       * options:
       *   - table
       *   - json
       *   - url
       *   - version
       * ---
       *
       * ## EXAMPLES
       *
       *     # Check for the latest stable version of CiviCRM
       *     $ wp civicrm core check-update
       *     +-----------+---------+-------------------------------------------------------------------------------------------+
       *     | Package   | Version | Package URL                                                                               |
       *     +-----------+---------+-------------------------------------------------------------------------------------------+
       *     | WordPress | 5.67.0  | https://storage.googleapis.com/civicrm/civicrm-stable/5.67.0/civicrm-5.67.0-wordpress.zip |
       *     | L10n      | 5.67.0  | https://storage.googleapis.com/civicrm/civicrm-stable/5.67.0/civicrm-5.67.0-l10n.tar.gz   |
       *     +-----------+---------+-------------------------------------------------------------------------------------------+
       *
       *     # Get the URL for the latest stable version of CiviCRM core
       *     $ wp civicrm core check-update --format=url
       *     https://storage.googleapis.com/civicrm/civicrm-stable/5.67.0/civicrm-5.67.0-wordpress.zip
       *
       *     # Get the URL for the latest stable version of CiviCRM localisation archive
       *     $ wp civicrm core check-update --format=url --l10n
       *     https://storage.googleapis.com/civicrm/civicrm-stable/5.67.0/civicrm-5.67.0-l10n.tar.gz
       *
       *     # Get the complete JSON-formatted data for the latest RC version of CiviCRM core
       *     $ wp civicrm core check-update --version=rc --format=json
       *     {"version":"5.58.beta1","rev":"5.58.beta1-202301260741" [...] "pretty":"Thu, 26 Jan 2023 07:41:00 +0000"}}
       *
       * @subcommand check-update
       *
       * @since 5.69
       *
       * @param array $args The WP-CLI positional arguments.
       * @param array $assoc_args The WP-CLI associative arguments.
       */
      public function check_update($args, $assoc_args) {
    
        // Grab associative arguments.
        $version = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'version', 'stable');
        $l10n = (bool) \WP_CLI\Utils\get_flag_value($assoc_args, 'l10n', FALSE);
        $format = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'format', 'table');
    
        // Look up the data.
        $url = $this->upgrade_url . '?stability=' . $version;
        $response = $this->http_get_response($url);
    
        // Try and decode response.
        $lookup = json_decode($response, TRUE);
        if (JSON_ERROR_NONE !== json_last_error()) {
          WP_CLI::error(sprintf(WP_CLI::colorize('Failed to decode JSON: %Y%s.%n'), json_last_error_msg()));
        }
    
        // Sanity checks.
        if (empty($lookup)) {
          WP_CLI::error(sprintf(WP_CLI::colorize('Version not found at: %Y%s%n'), $url));
        }
        if (empty($lookup['tar']['WordPress'])) {
          WP_CLI::error(sprintf(WP_CLI::colorize('No WordPress version found at: %Y%s%n'), $url));
        }
    
        switch ($format) {
    
          // URL-only output.
          case 'url':
            if ($l10n) {
              echo $lookup['tar']['L10n'] . "\n";
            }
            else {
              echo $lookup['tar']['WordPress'] . "\n";
            }
            break;
    
          // Version-only output.
          case 'version':
            echo $lookup['version'] . "\n";
            break;
    
          // Display output as json.
          case 'json':
            echo $response . "\n";
            break;
    
          // Display output as table (default).
          case 'table':
          default:
            // Build the rows.
            $rows = [];
            $fields = ['Package', 'Version', 'Package URL'];
            $rows[] = [
              'Package' => 'WordPress',
              'Version' => $lookup['version'],
              'Package URL' => $lookup['tar']['WordPress'],
            ];
            $rows[] = [
              'Package' => 'L10n',
              'Version' => $lookup['version'],
              'Package URL' => $lookup['tar']['L10n'],
            ];
    
            // Display the rows.
            $args = ['format' => $format];
            $formatter = new \WP_CLI\Formatter($args, $fields);
            $formatter->display_items($rows);
    
        }
    
      }
    
      /**
       * Downloads CiviCRM core files or localization files.
       *
       * Downloads and extracts CiviCRM core files or localization files to the
       * specified path. Uses the local temp directory when no path is specified.
       *
       * ## OPTIONS
       *
       * [--version=<version>]
       * : Specify the CiviCRM version to get. Accepts a version number, 'stable', 'rc' or 'nightly'. Defaults to latest stable version.
       *
       * [--l10n]
       * : Get the localization file for the specified version.
       *
       * [--destination=<destination>]
       * : Specify the absolute path to put the archive file. Defaults to local temp directory.
       *
       * [--insecure]
       * : Retry without certificate validation if TLS handshake fails. Note: This makes the request vulnerable to a MITM attack.
       *
       * [--extract]
       * : Whether to extract the downloaded file. Defaults to false.
       *
       * ## EXAMPLES
       *
       *     # Download the latest stable CiviCRM core archive.
       *     $ wp civicrm core download
       *     Checking file to download...
       *     Downloading file...
       *     Success: CiviCRM downloaded to /tmp/
       *
       *     # Download and extract a stable CiviCRM core archive to a directory.
       *     $ wp civicrm core download --version=5.17.2 --extract --destination=/some/path
       *     Checking file to download...
       *     Downloading file...
       *     Extracting zip archive...
       *     Success: CiviCRM downloaded and extracted to: /some/path/
       *
       *     # Quietly download a stable CiviCRM core archive.
       *     $ wp civicrm core download --version=5.17.2 --quiet
       *     /tmp/civicrm-5.17.2-wordpress.zip
       *
       *     # Download and extract a stable CiviCRM localization archive to a directory.
       *     $ wp civicrm core download --version=5.17.2 --l10n --extract --destination=/some/path
       *     Checking file to download...
       *     Downloading file...
       *     Extracting tar.gz archive...
       *     Success: CiviCRM localization downloaded and extracted to: /some/path/
       *
       *     # Quietly download a stable CiviCRM localization archive.
       *     $ wp civicrm core download --version=5.17.2 --l10n --quiet
       *     /tmp/civicrm-5.17.2-l10n.tar.gz
       *
       * @since 5.69
       *
       * @param array $args The WP-CLI positional arguments.
       * @param array $assoc_args The WP-CLI associative arguments.
       */
      public function download($args, $assoc_args) {
    
        // Grab associative arguments.
        $version = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'version', 'stable');
        $l10n = (bool) \WP_CLI\Utils\get_flag_value($assoc_args, 'l10n', FALSE);
        $download_dir = (string) \WP_CLI\Utils\get_flag_value($assoc_args, 'destination', \WP_CLI\Utils\get_temp_dir());
        $insecure = (bool) \WP_CLI\Utils\get_flag_value($assoc_args, 'insecure', FALSE);
        $extract = (bool) \WP_CLI\Utils\get_flag_value($assoc_args, 'extract', FALSE);
    
        // Maybe create destination directory.
        if (!is_dir($download_dir)) {
          if (!is_writable(dirname($download_dir))) {
            WP_CLI::error("Insufficient permission to create directory '{$download_dir}'.");
          }
          WP_CLI::log("Creating directory '{$download_dir}'.");
          // Recursively create directory.
          if (!@mkdir($download_dir, 0777, TRUE)) {
            $error = error_get_last();
            WP_CLI::error("Failed to create directory '{$download_dir}': {$error['message']}.");
          }
        }
    
        // Sanity check.
        if (!is_writable($download_dir)) {
          WP_CLI::error("'{$download_dir}' is not writable by current user.");
        }
    
        // Use "wp civicrm core check-version" to find out which file to download.
        WP_CLI::log(WP_CLI::colorize('%GChecking' . (empty($l10n) ? '' : ' localization') . ' file to download...%n'));
        $options = ['launch' => FALSE, 'return' => TRUE];
        $command = 'civicrm core check-version --version=' . $version . ' --format=url' . (empty($l10n) ? '' : ' --l10n');
        $url = WP_CLI::runcommand($command, $options);
    
        // Configure the download.
        $headers = [];
        $options = [
          'insecure' => (bool) $insecure,
        ];
    
        // Do the download now.
        WP_CLI::log(WP_CLI::colorize('%GDownloading file...%n'));
        $archive = $this->file_download($url, $download_dir, $headers, $options);
    
        // Stop early if not extracting.
        if (empty($extract)) {
          if (empty($l10n)) {
            WP_CLI::success(sprintf(WP_CLI::colorize('CiviCRM downloaded to: %Y%s%n'), $download_dir));
          }
          else {
            WP_CLI::success(sprintf(WP_CLI::colorize('CiviCRM localization downloaded to: %Y%s%n'), $download_dir));
          }
          if (!empty(WP_CLI::get_config('quiet'))) {
            echo $archive . "\n";
          }
          WP_CLI::halt(0);
        }
    
        // Extract the download.
        if (empty($l10n)) {
          if (!$this->unzip($archive, $download_dir)) {
            WP_CLI::error('Could not extract zipfile.');
          }
          WP_CLI::success(sprintf(WP_CLI::colorize('CiviCRM downloaded and extracted to: %Y%s%n'), $download_dir));
        }
        else {
          if (!$this->untar($archive, $download_dir)) {
            WP_CLI::error('Could not extract tarfile.');
          }
          WP_CLI::success(sprintf(WP_CLI::colorize('CiviCRM localization downloaded and extracted to: %Y%s%n'), $download_dir));
        }