Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.23% covered (success)
94.23%
49 / 52
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
SQL_Importer
94.23% covered (success)
94.23%
49 / 52
33.33% covered (danger)
33.33%
1 / 3
19.07
0.00% covered (danger)
0.00%
0 / 1
 import
93.55% covered (success)
93.55%
29 / 31
0.00% covered (danger)
0.00%
0 / 1
11.03
 pop_exit_status
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_error_details
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
4.00
1<?php
2/**
3 * SQL_Importer file.
4 *
5 * @package wpcomsh
6 */
7
8namespace Imports;
9
10use WP_Error;
11
12/**
13 * Import a SQL dump in current database.
14 */
15class SQL_Importer {
16    /**
17     * How much of mysql's output to keep in an error. Its errors quote the SQL near the failure.
18     */
19    private const MAX_ERROR_DETAILS_BYTES = 500;
20
21    /**
22     * How much of mysql's output to read back. Its error comes last, and on some hosts it first echoes
23     * the failing statement, which can be hundreds of MB.
24     */
25    private const MAX_OUTPUT_BYTES = 4096;
26
27    /**
28     * Marks the line that carries mysql's exit status, since the shell reports tail's.
29     */
30    private const EXIT_STATUS_MARKER = 'wpcomsh-mysql-exit:';
31
32    /**
33     * Import the dump file.
34     *
35     * @param string $sql_file_path The path of the SQL file.
36     * @param bool   $verbose       Whether to run the command in verbose mode.
37     *
38     * @return bool|WP_Error
39     */
40    public static function import( string $sql_file_path, $verbose = false ) {
41        // Bail if the file doesn't exist.
42        if ( ! is_file( $sql_file_path ) || ! is_readable( $sql_file_path ) ) {
43            return new WP_Error( 'sql-file-not-exists', __( 'SQL file not exists', 'wpcomsh' ) );
44        }
45
46        $host = DB_HOST;
47        $port = '';
48        if ( preg_match( '/^(.+):(\d+)$/', $host, $m ) ) {
49            $host = $m[1];
50            $port = $m[2];
51        }
52
53        $output  = null;
54        $ret     = null;
55        $command = sprintf(
56            'mysql -u %s%s -h %s%s %s%s < %s',
57            escapeshellarg( DB_USER ),
58            DB_PASSWORD === '' ? '' : ' -p' . escapeshellarg( DB_PASSWORD ),
59            escapeshellarg( $host ),
60            $port === '' ? '' : ' --port=' . escapeshellarg( $port ),
61            escapeshellarg( DB_NAME ),
62            $verbose ? '' : ' 2>&1',
63            escapeshellarg( $sql_file_path )
64        );
65
66        if ( ! $verbose ) {
67            // Read back only the end of mysql's output, so a huge echoed statement can't exhaust PHP's memory,
68            // and append mysql's exit status, since the pipeline's status is tail's.
69            $command = sprintf( '{ %s; echo "%s$?"; } | tail -c %d', $command, self::EXIT_STATUS_MARKER, self::MAX_OUTPUT_BYTES );
70        }
71
72        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_exec
73        exec( $command, $output, $ret );
74
75        if ( ! $verbose ) {
76            $ret = self::pop_exit_status( $output, $ret );
77        }
78
79        if ( $ret === 0 ) {
80            return true;
81        }
82
83        // Keep mysql's error, e.g. a packet over max_allowed_packet, so the failure can be told apart.
84        $message = __( 'SQL import failed', 'wpcomsh' );
85        $details = self::get_error_details( (array) $output );
86        if ( $details !== '' ) {
87            $message .= ': ' . $details;
88        }
89
90        return new WP_Error( 'sql-import-failed', $message );
91    }
92
93    /**
94     * Remove the exit status line from the output and return mysql's exit status.
95     *
96     * @param string[] $output   Lines of output.
97     * @param int|null $fallback The pipeline's exit status, used if the marker is missing.
98     *
99     * @return int
100     */
101    private static function pop_exit_status( array &$output, $fallback ): int {
102        $last = end( $output );
103        if ( is_string( $last ) && str_starts_with( $last, self::EXIT_STATUS_MARKER ) ) {
104            array_pop( $output );
105            return (int) substr( $last, strlen( self::EXIT_STATUS_MARKER ) );
106        }
107
108        // No marker: the pipeline itself failed. Never report success.
109        return $fallback ? (int) $fallback : 1;
110    }
111
112    /**
113     * The mysql client's error on one line, truncated, without its password warning.
114     *
115     * Prefers mysql's ERROR lines, since some hosts echo the failing statement before them.
116     *
117     * @param string[] $output Lines of output.
118     *
119     * @return string
120     */
121    private static function get_error_details( array $output ): string {
122        $lines = array_filter(
123            array_map( 'trim', $output ),
124            static function ( $line ) {
125                return $line !== '' && ! str_contains( $line, 'Using a password on the command line' );
126            }
127        );
128
129        $errors = array_filter(
130            $lines,
131            static function ( $line ) {
132                return str_starts_with( $line, 'ERROR' );
133            }
134        );
135
136        $details = implode( ' ', $errors ? $errors : $lines );
137        if ( strlen( $details ) > self::MAX_ERROR_DETAILS_BYTES ) {
138            // Keep the end, where mysql reports the error.
139            $details = '…' . mb_strcut( $details, strlen( $details ) - self::MAX_ERROR_DETAILS_BYTES );
140        }
141
142        return $details;
143    }
144}