Merge "resources: Improve foreign-resources docs and error messages"
[lhc/web/wiklou.git] / includes / ForeignResourceManager.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Maintenance
20 */
21
22 /**
23 * Manage foreign resources registered with ResourceLoader.
24 *
25 * @since 1.32
26 */
27 class ForeignResourceManager {
28 private $defaultAlgo = 'sha384';
29 private $hasErrors = false;
30 private $registryFile;
31 private $libDir;
32 private $tmpParentDir;
33 private $infoPrinter;
34 private $errorPrinter;
35 private $verbosePrinter;
36 private $action;
37
38 /**
39 * @param string $registryFile Path to YAML file
40 * @param string $libDir Path to a modules directory
41 * @param callable|null $infoPrinter Callback for printing info about the run.
42 * @param callable|null $errorPrinter Callback for printing errors from the run.
43 * @param callable|null $verbosePrinter Callback for printing extra verbose
44 * progress information from the run.
45 */
46 public function __construct(
47 $registryFile,
48 $libDir,
49 callable $infoPrinter = null,
50 callable $errorPrinter = null,
51 callable $verbosePrinter = null
52 ) {
53 $this->registryFile = $registryFile;
54 $this->libDir = $libDir;
55 $this->infoPrinter = $infoPrinter ?? function () {
56 };
57 $this->errorPrinter = $errorPrinter ?? $this->infoPrinter;
58 $this->verbosePrinter = $verbosePrinter ?? function () {
59 };
60
61 // Use a temporary directory under the destination directory instead
62 // of wfTempDir() because PHP's rename() does not work across file
63 // systems, as the user's /tmp and $IP may be on different filesystems.
64 $this->tmpParentDir = "{$this->libDir}/.tmp";
65 }
66
67 /**
68 * @return bool
69 * @throws Exception
70 */
71 public function run( $action, $module ) {
72 $actions = [ 'update', 'verify', 'make-sri' ];
73 if ( !in_array( $action, $actions ) ) {
74 $this->error( "Invalid action.\n\nMust be one of " . implode( ', ', $actions ) . '.' );
75 return false;
76 }
77 $this->action = $action;
78
79 $registry = $this->parseBasicYaml( file_get_contents( $this->registryFile ) );
80 if ( $module === 'all' ) {
81 $modules = $registry;
82 } elseif ( isset( $registry[ $module ] ) ) {
83 $modules = [ $module => $registry[ $module ] ];
84 } else {
85 $this->error( "Unknown module name.\n\nMust be one of:\n" .
86 wordwrap( implode( ', ', array_keys( $registry ) ), 80 ) .
87 '.'
88 );
89 return false;
90 }
91
92 foreach ( $modules as $moduleName => $info ) {
93 $this->verbose( "\n### {$moduleName}\n\n" );
94 $destDir = "{$this->libDir}/$moduleName";
95
96 if ( $this->action === 'update' ) {
97 $this->output( "... updating '{$moduleName}'\n" );
98 $this->verbose( "... emptying directory for $moduleName\n" );
99 wfRecursiveRemoveDir( $destDir );
100 } elseif ( $this->action === 'verify' ) {
101 $this->output( "... verifying '{$moduleName}'\n" );
102 } else {
103 $this->output( "... checking '{$moduleName}'\n" );
104 }
105
106 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
107 wfRecursiveRemoveDir( $this->tmpParentDir );
108 if ( !wfMkdirParents( $this->tmpParentDir ) ) {
109 throw new Exception( "Unable to create {$this->tmpParentDir}" );
110 }
111
112 if ( !isset( $info['type'] ) ) {
113 throw new Exception( "Module '$moduleName' must have a 'type' key." );
114 }
115 switch ( $info['type'] ) {
116 case 'tar':
117 $this->handleTypeTar( $moduleName, $destDir, $info );
118 break;
119 case 'file':
120 $this->handleTypeFile( $moduleName, $destDir, $info );
121 break;
122 case 'multi-file':
123 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
124 break;
125 default:
126 throw new Exception( "Unknown type '{$info['type']}' for '$moduleName'" );
127 }
128 }
129
130 $this->cleanUp();
131 $this->output( "\nDone!\n" );
132 if ( $this->hasErrors ) {
133 // The verify mode should check all modules/files and fail after, not during.
134 return false;
135 }
136
137 return true;
138 }
139
140 private function fetch( $src, $integrity ) {
141 $req = MWHttpRequest::factory( $src, [ 'method' => 'GET', 'followRedirects' => false ] );
142 if ( !$req->execute()->isOK() ) {
143 throw new Exception( "Failed to download resource at {$src}" );
144 }
145 if ( $req->getStatus() !== 200 ) {
146 throw new Exception( "Unexpected HTTP {$req->getStatus()} response from {$src}" );
147 }
148 $data = $req->getContent();
149 $algo = $integrity === null ? $this->defaultAlgo : explode( '-', $integrity )[0];
150 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
151 if ( $integrity === $actualIntegrity ) {
152 $this->verbose( "... passed integrity check for {$src}\n" );
153 } else {
154 if ( $this->action === 'make-sri' ) {
155 $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" );
156 } else {
157 throw new Exception( "Integrity check failed for {$src}\n" .
158 "\tExpected: {$integrity}\n" .
159 "\tActual: {$actualIntegrity}"
160 );
161 }
162 }
163 return $data;
164 }
165
166 private function handleTypeFile( $moduleName, $destDir, array $info ) {
167 if ( !isset( $info['src'] ) ) {
168 throw new Exception( "Module '$moduleName' must have a 'src' key." );
169 }
170 $data = $this->fetch( $info['src'], $info['integrity'] ?? null );
171 $dest = $info['dest'] ?? basename( $info['src'] );
172 $path = "$destDir/$dest";
173 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
174 throw new Exception( "File for '$moduleName' is different." );
175 }
176 if ( $this->action === 'update' ) {
177 wfMkdirParents( $destDir );
178 file_put_contents( "$destDir/$dest", $data );
179 }
180 }
181
182 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
183 if ( !isset( $info['files'] ) ) {
184 throw new Exception( "Module '$moduleName' must have a 'files' key." );
185 }
186 foreach ( $info['files'] as $dest => $file ) {
187 if ( !isset( $file['src'] ) ) {
188 throw new Exception( "Module '$moduleName' file '$dest' must have a 'src' key." );
189 }
190 $data = $this->fetch( $file['src'], $file['integrity'] ?? null );
191 $path = "$destDir/$dest";
192 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
193 throw new Exception( "File '$dest' for '$moduleName' is different." );
194 } elseif ( $this->action === 'update' ) {
195 wfMkdirParents( $destDir );
196 file_put_contents( "$destDir/$dest", $data );
197 }
198 }
199 }
200
201 private function handleTypeTar( $moduleName, $destDir, array $info ) {
202 $info += [ 'src' => null, 'integrity' => null, 'dest' => null ];
203 if ( $info['src'] === null ) {
204 throw new Exception( "Module '$moduleName' must have a 'src' key." );
205 }
206 // Download the resource to a temporary file and open it
207 $data = $this->fetch( $info['src'], $info['integrity' ] );
208 $tmpFile = "{$this->tmpParentDir}/$moduleName.tar";
209 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
210 file_put_contents( $tmpFile, $data );
211 $p = new PharData( $tmpFile );
212 $tmpDir = "{$this->tmpParentDir}/$moduleName";
213 $p->extractTo( $tmpDir );
214 unset( $data, $p );
215
216 if ( $info['dest'] === null ) {
217 // Default: Replace the entire directory
218 $toCopy = [ $tmpDir => $destDir ];
219 } else {
220 // Expand and normalise the 'dest' entries
221 $toCopy = [];
222 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
223 // Use glob() to expand wildcards and check existence
224 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE );
225 if ( !$fromPaths ) {
226 throw new Exception( "Path '$fromSubPath' of '$moduleName' not found." );
227 }
228 foreach ( $fromPaths as $fromPath ) {
229 $toCopy[$fromPath] = $toSubPath === null
230 ? "$destDir/" . basename( $fromPath )
231 : "$destDir/$toSubPath/" . basename( $fromPath );
232 }
233 }
234 }
235 foreach ( $toCopy as $from => $to ) {
236 if ( $this->action === 'verify' ) {
237 $this->verbose( "... verifying $to\n" );
238 if ( is_dir( $from ) ) {
239 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
240 $from,
241 RecursiveDirectoryIterator::SKIP_DOTS
242 ) );
243 /** @var SplFileInfo $file */
244 foreach ( $rii as $file ) {
245 $remote = $file->getPathname();
246 $local = strtr( $remote, [ $from => $to ] );
247 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
248 $this->error( "File '$local' is different." );
249 $this->hasErrors = true;
250 }
251 }
252 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
253 $this->error( "File '$to' is different." );
254 $this->hasErrors = true;
255 }
256 } elseif ( $this->action === 'update' ) {
257 $this->verbose( "... moving $from to $to\n" );
258 wfMkdirParents( dirname( $to ) );
259 if ( !rename( $from, $to ) ) {
260 throw new Exception( "Could not move $from to $to." );
261 }
262 }
263 }
264 }
265
266 private function verbose( $text ) {
267 ( $this->verbosePrinter )( $text );
268 }
269
270 private function output( $text ) {
271 ( $this->infoPrinter )( $text );
272 }
273
274 private function error( $text ) {
275 ( $this->errorPrinter )( $text );
276 }
277
278 private function cleanUp() {
279 wfRecursiveRemoveDir( $this->tmpParentDir );
280 }
281
282 /**
283 * Basic YAML parser.
284 *
285 * Supports only string or object values, and 2 spaces indentation.
286 *
287 * @todo Just ship symfony/yaml.
288 * @param string $input
289 * @return array
290 */
291 private function parseBasicYaml( $input ) {
292 $lines = explode( "\n", $input );
293 $root = [];
294 $stack = [ &$root ];
295 $prev = 0;
296 foreach ( $lines as $i => $text ) {
297 $line = $i + 1;
298 $trimmed = ltrim( $text, ' ' );
299 if ( $trimmed === '' || $trimmed[0] === '#' ) {
300 continue;
301 }
302 $indent = strlen( $text ) - strlen( $trimmed );
303 if ( $indent % 2 !== 0 ) {
304 throw new Exception( __METHOD__ . ": Odd indentation on line $line." );
305 }
306 $depth = $indent === 0 ? 0 : ( $indent / 2 );
307 if ( $depth < $prev ) {
308 // Close previous branches we can't re-enter
309 array_splice( $stack, $depth + 1 );
310 }
311 if ( !array_key_exists( $depth, $stack ) ) {
312 throw new Exception( __METHOD__ . ": Too much indentation on line $line." );
313 }
314 if ( strpos( $trimmed, ':' ) === false ) {
315 throw new Exception( __METHOD__ . ": Missing colon on line $line." );
316 }
317 $dest =& $stack[ $depth ];
318 if ( $dest === null ) {
319 // Promote from null to object
320 $dest = [];
321 }
322 list( $key, $val ) = explode( ':', $trimmed, 2 );
323 $val = ltrim( $val, ' ' );
324 if ( $val !== '' ) {
325 // Add string
326 $dest[ $key ] = $val;
327 } else {
328 // Add null (may become an object later)
329 $val = null;
330 $stack[] = &$val;
331 $dest[ $key ] = &$val;
332 }
333 $prev = $depth;
334 unset( $dest, $val );
335 }
336 return $root;
337 }
338 }