class-file-tree-producer.php
6 days ago
class-hmac-client.php
6 days ago
class-hmac-server.php
6 days ago
class-http-server.php
6 days ago
class-mysql-dump-producer.php
6 days ago
class-pdo-polyfill.php
6 days ago
class-sqlite-driver-pdo.php
6 days ago
class-staged-artifacts.php
6 days ago
class-staged-endpoints.php
6 days ago
class-staged-push-stream-protocol.php
6 days ago
class-wpdb-driver-pdo.php
6 days ago
export.php
6 days ago
utils.php
6 days ago
utils.php
230 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Shared utility functions used by both export.php and import.php. |
| 4 | * |
| 5 | * These helpers live in a namespace so they don't collide with global |
| 6 | * functions of the same name declared by third-party plugins or |
| 7 | * WordPress drop-ins. The package is loaded via Composer's "files" |
| 8 | * autoload, which means every host that pulls in this library (e.g. |
| 9 | * wpcomsh on WordPress.com) gets these symbols on every request — |
| 10 | * generic names like parse_size() or normalize_path() are guaranteed |
| 11 | * to clash sooner or later if they sit in the global namespace. |
| 12 | * |
| 13 | * The two str_* polyfills at the top stay global on purpose: they |
| 14 | * backfill PHP 7.4 built-ins, so callers expect to reach them via |
| 15 | * the global namespace without a use-statement. |
| 16 | */ |
| 17 | |
| 18 | // Polyfill for PHP 7.4 which lacks str_starts_with(). |
| 19 | namespace { |
| 20 | if (!function_exists('str_starts_with')) { |
| 21 | function str_starts_with(string $haystack, string $needle): bool { |
| 22 | return $needle === '' || strncmp($haystack, $needle, strlen($needle)) === 0; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | // Polyfill for PHP 7.4 which lacks str_contains(). |
| 27 | if (!function_exists('str_contains')) { |
| 28 | function str_contains(string $haystack, string $needle): bool { |
| 29 | return $needle === '' || strpos($haystack, $needle) !== false; |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | namespace WordPress\Reprint\Exporter { |
| 35 | |
| 36 | use InvalidArgumentException; |
| 37 | use RuntimeException; |
| 38 | |
| 39 | // Composer's "files" autoload includes this file once per registered |
| 40 | // path. In a monorepo where the same package is mirrored into vendor/ |
| 41 | // (e.g. tests/ pulls in vendor/wp-php-toolkit/reprint-exporter/src/utils.php |
| 42 | // AND packages/reprint-exporter/src/utils.php), both copies are loaded. |
| 43 | // `return` from inside a bracketed namespace block does not abort the |
| 44 | // whole file, so guard the declarations themselves. |
| 45 | if (!function_exists(__NAMESPACE__ . '\\build_pdo_dsn')) { |
| 46 | |
| 47 | /** |
| 48 | * Builds a PDO DSN string from a WordPress DB_HOST value. |
| 49 | * |
| 50 | * WordPress's DB_HOST supports several non-standard formats that shared |
| 51 | * hosts commonly use: |
| 52 | * - "localhost" → standard hostname |
| 53 | * - "db.host.com:3307" → hostname with port |
| 54 | * - "localhost:/path/sock" → hostname with Unix socket |
| 55 | * - "/path/to/mysql.sock" → bare Unix socket path |
| 56 | * - "::1" → IPv6 address |
| 57 | * - "[::1]" → bracketed IPv6 |
| 58 | * - "[::1]:3306" → bracketed IPv6 with port |
| 59 | * - "[::1]:/path/to/socket" → bracketed IPv6 with Unix socket |
| 60 | * |
| 61 | * PDO needs these broken out into separate DSN parameters (host, port, |
| 62 | * unix_socket), so we parse the value the same way WordPress core does. |
| 63 | * |
| 64 | * @param string $db_host Raw DB_HOST value. |
| 65 | * @param string $db_name Database name. |
| 66 | * @return string PDO DSN string. |
| 67 | */ |
| 68 | function build_pdo_dsn(string $db_host, string $db_name): string |
| 69 | { |
| 70 | $socket = ''; |
| 71 | $host = $db_host; |
| 72 | $port = ''; |
| 73 | |
| 74 | if (str_starts_with($db_host, '/') && file_exists($db_host)) { |
| 75 | // Bare socket path: "/var/run/mysqld/mysqld.sock" |
| 76 | $socket = $db_host; |
| 77 | $host = ''; |
| 78 | } elseif ( |
| 79 | str_starts_with($db_host, '[') && |
| 80 | ($bracket_end = strpos($db_host, ']')) !== false |
| 81 | ) { |
| 82 | // Bracketed IPv6: "[::1]", "[::1]:3306", "[::1]:/path/to/socket" |
| 83 | $host = substr($db_host, 1, $bracket_end - 1); |
| 84 | $after = substr($db_host, $bracket_end + 1); |
| 85 | $candidate_socket = str_starts_with($after, ':/') ? substr($after, 1) : ''; |
| 86 | if ($candidate_socket !== '' && file_exists($candidate_socket)) { |
| 87 | $socket = $candidate_socket; |
| 88 | } elseif (str_starts_with($after, ':')) { |
| 89 | $port = substr($after, 1); |
| 90 | } |
| 91 | } elseif (($socket_pos = strpos($db_host, ':/')) !== false) { |
| 92 | // "host:/path/to/socket" — check before general colon split |
| 93 | // to avoid misinterpreting IPv6 addresses as host:port |
| 94 | $candidate_socket = substr($db_host, $socket_pos + 1); |
| 95 | if (file_exists($candidate_socket)) { |
| 96 | $host = substr($db_host, 0, $socket_pos); |
| 97 | $socket = $candidate_socket; |
| 98 | } elseif (substr_count($db_host, ':') === 1) { |
| 99 | // Single colon but not a socket — treat as host:port |
| 100 | [$host, $port] = explode(':', $db_host, 2); |
| 101 | } |
| 102 | } elseif ( |
| 103 | str_contains($db_host, ':') && |
| 104 | substr_count($db_host, ':') === 1 |
| 105 | ) { |
| 106 | // Exactly one colon: "host:port" — not IPv6 |
| 107 | [$host, $port] = explode(':', $db_host, 2); |
| 108 | } |
| 109 | // Otherwise (multiple colons, no socket marker): bare IPv6 like "::1" |
| 110 | // — $host stays as the full value. |
| 111 | |
| 112 | if ($socket !== '') { |
| 113 | return "mysql:unix_socket={$socket};dbname={$db_name};charset=utf8mb4"; |
| 114 | } |
| 115 | |
| 116 | $dsn = "mysql:host={$host}"; |
| 117 | if ($port !== '') { |
| 118 | $dsn .= ";port={$port}"; |
| 119 | } |
| 120 | $dsn .= ";dbname={$db_name};charset=utf8mb4"; |
| 121 | return $dsn; |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Parse a human-readable size string (e.g. "16M", "1G", "512K") into bytes. |
| 126 | * Accepts plain integers as well. |
| 127 | */ |
| 128 | function parse_size(string $value): int |
| 129 | { |
| 130 | $value = trim($value); |
| 131 | if (!preg_match('/^(\d+(?:\.\d+)?)\s*([KMGkmg])?[Bb]?$/', $value, $m)) { |
| 132 | throw new InvalidArgumentException( |
| 133 | "Invalid size value: '{$value}'. Use a number optionally followed by K, M, or G (e.g. 64M)." |
| 134 | ); |
| 135 | } |
| 136 | $num = (float) $m[1]; |
| 137 | $suffix = strtoupper($m[2] ?? ""); |
| 138 | switch ($suffix) { |
| 139 | case "K": |
| 140 | return (int) ($num * 1024); |
| 141 | case "M": |
| 142 | return (int) ($num * 1024 * 1024); |
| 143 | case "G": |
| 144 | return (int) ($num * 1024 * 1024 * 1024); |
| 145 | default: |
| 146 | return (int) $num; |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * Throws on json_encode failure instead of returning false. |
| 152 | * |
| 153 | * Do NOT use inside error/shutdown handlers — those need hardcoded fallback strings. |
| 154 | */ |
| 155 | function json_encode_or_throw($value, int $flags = 0): string |
| 156 | { |
| 157 | $json = json_encode($value, $flags); |
| 158 | if ($json === false) { |
| 159 | throw new RuntimeException("json_encode failed: " . json_last_error_msg()); |
| 160 | } |
| 161 | return $json; |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Resolve ".." and "." segments in a path without touching the filesystem. |
| 166 | * |
| 167 | * Unlike realpath(), this works on paths that don't exist yet. |
| 168 | */ |
| 169 | function normalize_path(string $path): string |
| 170 | { |
| 171 | $parts = explode("/", $path); |
| 172 | $resolved = []; |
| 173 | foreach ($parts as $part) { |
| 174 | if ($part === "" || $part === ".") { |
| 175 | continue; |
| 176 | } |
| 177 | if ($part === "..") { |
| 178 | array_pop($resolved); |
| 179 | } else { |
| 180 | $resolved[] = $part; |
| 181 | } |
| 182 | } |
| 183 | return "/" . implode("/", $resolved); |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Returns true when $path is equal to $root or strictly under it. |
| 188 | */ |
| 189 | function path_is_within_root(string $path, string $root): bool |
| 190 | { |
| 191 | return $path === $root || str_starts_with($path, $root . "/"); |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Validates that a path is a non-empty absolute string without NUL bytes |
| 196 | * or dot-segments (. or ..). |
| 197 | * |
| 198 | * Useful anywhere untrusted or remote paths need to be checked before |
| 199 | * use — both the exporter (directory config) and the importer (remote |
| 200 | * paths from the server) share this validation. |
| 201 | * |
| 202 | * @param string $path The path to validate. |
| 203 | * @param string $label Human-readable label for error messages (e.g. "directory", "remote path"). |
| 204 | * @throws InvalidArgumentException When the path fails any check. |
| 205 | */ |
| 206 | function assert_valid_path(string $path, string $label = "path"): void |
| 207 | { |
| 208 | $path = trim($path); |
| 209 | if ($path === "") { |
| 210 | throw new InvalidArgumentException("{$label} must be a non-empty string"); |
| 211 | } |
| 212 | if ($path[0] !== "/") { |
| 213 | throw new InvalidArgumentException("{$label} must be an absolute path: {$path}"); |
| 214 | } |
| 215 | if (strpos($path, "\0") !== false) { |
| 216 | throw new InvalidArgumentException("{$label} must not contain NUL bytes"); |
| 217 | } |
| 218 | foreach (explode("/", $path) as $segment) { |
| 219 | if ($segment === "." || $segment === "..") { |
| 220 | throw new InvalidArgumentException( |
| 221 | "{$label} must not contain dot-segments (. or ..): {$path}" |
| 222 | ); |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | } // !function_exists guard |
| 228 | |
| 229 | } |
| 230 |