Merge "Use MediaWiki\SuppressWarnings around trigger_error('') instead @"
[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 if ( !in_array( $action, [ 'update', 'verify', 'make-sri' ] ) ) {
73 throw new Exception( 'Invalid action parameter.' );
74 }
75 $this->action = $action;
76
77 $registry = $this->parseBasicYaml( file_get_contents( $this->registryFile ) );
78 if ( $module === 'all' ) {
79 $modules = $registry;
80 } elseif ( isset( $registry[ $module ] ) ) {
81 $modules = [ $module => $registry[ $module ] ];
82 } else {
83 throw new Exception( 'Unknown module name.' );
84 }
85
86 foreach ( $modules as $moduleName => $info ) {
87 $this->verbose( "\n### {$moduleName}\n\n" );
88 $destDir = "{$this->libDir}/$moduleName";
89
90 if ( $this->action === 'update' ) {
91 $this->output( "... updating '{$moduleName}'\n" );
92 $this->verbose( "... emptying directory for $moduleName\n" );
93 wfRecursiveRemoveDir( $destDir );
94 } elseif ( $this->action === 'verify' ) {
95 $this->output( "... verifying '{$moduleName}'\n" );
96 } else {
97 $this->output( "... checking '{$moduleName}'\n" );
98 }
99
100 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
101 wfRecursiveRemoveDir( $this->tmpParentDir );
102 if ( !wfMkdirParents( $this->tmpParentDir ) ) {
103 throw new Exception( "Unable to create {$this->tmpParentDir}" );
104 }
105
106 if ( !isset( $info['type'] ) ) {
107 throw new Exception( "Module '$moduleName' must have a 'type' key." );
108 }
109 switch ( $info['type'] ) {
110 case 'tar':
111 $this->handleTypeTar( $moduleName, $destDir, $info );
112 break;
113 case 'file':
114 $this->handleTypeFile( $moduleName, $destDir, $info );
115 break;
116 case 'multi-file':
117 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
118 break;
119 default:
120 throw new Exception( "Unknown type '{$info['type']}' for '$moduleName'" );
121 }
122 }
123
124 $this->cleanUp();
125 $this->output( "\nDone!\n" );
126 if ( $this->hasErrors ) {
127 // The verify mode should check all modules/files and fail after, not during.
128 return false;
129 }
130
131 return true;
132 }
133
134 private function fetch( $src, $integrity ) {
135 $data = Http::get( $src, [ 'followRedirects' => false ] );
136 if ( $data === false ) {
137 throw new Exception( "Failed to download resource at {$src}" );
138 }
139 $algo = $integrity === null ? $this->defaultAlgo : explode( '-', $integrity )[0];
140 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
141 if ( $integrity === $actualIntegrity ) {
142 $this->verbose( "... passed integrity check for {$src}\n" );
143 } else {
144 if ( $this->action === 'make-sri' ) {
145 $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" );
146 } else {
147 throw new Exception( "Integrity check failed for {$src}\n" .
148 "\tExpected: {$integrity}\n" .
149 "\tActual: {$actualIntegrity}"
150 );
151 }
152 }
153 return $data;
154 }
155
156 private function handleTypeFile( $moduleName, $destDir, array $info ) {
157 if ( !isset( $info['src'] ) ) {
158 throw new Exception( "Module '$moduleName' must have a 'src' key." );
159 }
160 $data = $this->fetch( $info['src'], $info['integrity'] ?? null );
161 $dest = $info['dest'] ?? basename( $info['src'] );
162 $path = "$destDir/$dest";
163 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
164 throw new Exception( "File for '$moduleName' is different." );
165 }
166 if ( $this->action === 'update' ) {
167 wfMkdirParents( $destDir );
168 file_put_contents( "$destDir/$dest", $data );
169 }
170 }
171
172 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
173 if ( !isset( $info['files'] ) ) {
174 throw new Exception( "Module '$moduleName' must have a 'files' key." );
175 }
176 foreach ( $info['files'] as $dest => $file ) {
177 if ( !isset( $file['src'] ) ) {
178 throw new Exception( "Module '$moduleName' file '$dest' must have a 'src' key." );
179 }
180 $data = $this->fetch( $file['src'], $file['integrity'] ?? null );
181 $path = "$destDir/$dest";
182 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
183 throw new Exception( "File '$dest' for '$moduleName' is different." );
184 } elseif ( $this->action === 'update' ) {
185 wfMkdirParents( $destDir );
186 file_put_contents( "$destDir/$dest", $data );
187 }
188 }
189 }
190
191 private function handleTypeTar( $moduleName, $destDir, array $info ) {
192 $info += [ 'src' => null, 'integrity' => null, 'dest' => null ];
193 if ( $info['src'] === null ) {
194 throw new Exception( "Module '$moduleName' must have a 'src' key." );
195 }
196 // Download the resource to a temporary file and open it
197 $data = $this->fetch( $info['src'], $info['integrity' ] );
198 $tmpFile = "{$this->tmpParentDir}/$moduleName.tar";
199 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
200 file_put_contents( $tmpFile, $data );
201 $p = new PharData( $tmpFile );
202 $tmpDir = "{$this->tmpParentDir}/$moduleName";
203 $p->extractTo( $tmpDir );
204 unset( $data, $p );
205
206 if ( $info['dest'] === null ) {
207 // Default: Replace the entire directory
208 $toCopy = [ $tmpDir => $destDir ];
209 } else {
210 // Expand and normalise the 'dest' entries
211 $toCopy = [];
212 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
213 // Use glob() to expand wildcards and check existence
214 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE );
215 if ( !$fromPaths ) {
216 throw new Exception( "Path '$fromSubPath' of '$moduleName' not found." );
217 }
218 foreach ( $fromPaths as $fromPath ) {
219 $toCopy[$fromPath] = $toSubPath === null
220 ? "$destDir/" . basename( $fromPath )
221 : "$destDir/$toSubPath/" . basename( $fromPath );
222 }
223 }
224 }
225 foreach ( $toCopy as $from => $to ) {
226 if ( $this->action === 'verify' ) {
227 $this->verbose( "... verifying $to\n" );
228 if ( is_dir( $from ) ) {
229 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
230 $from,
231 RecursiveDirectoryIterator::SKIP_DOTS
232 ) );
233 foreach ( $rii as $file ) {
234 $remote = $file->getPathname();
235 $local = strtr( $remote, [ $from => $to ] );
236 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
237 $this->error( "File '$local' is different." );
238 $this->hasErrors = true;
239 }
240 }
241 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
242 $this->error( "File '$to' is different." );
243 $this->hasErrors = true;
244 }
245 } elseif ( $this->action === 'update' ) {
246 $this->verbose( "... moving $from to $to\n" );
247 wfMkdirParents( dirname( $to ) );
248 if ( !rename( $from, $to ) ) {
249 throw new Exception( "Could not move $from to $to." );
250 }
251 }
252 }
253 }
254
255 private function verbose( $text ) {
256 ( $this->verbosePrinter )( $text );
257 }
258
259 private function output( $text ) {
260 ( $this->infoPrinter )( $text );
261 }
262
263 private function error( $text ) {
264 ( $this->errorPrinter )( $text );
265 }
266
267 private function cleanUp() {
268 wfRecursiveRemoveDir( $this->tmpParentDir );
269 }
270
271 /**
272 * Basic YAML parser.
273 *
274 * Supports only string or object values, and 2 spaces indentation.
275 *
276 * @todo Just ship symfony/yaml.
277 * @param string $input
278 * @return array
279 */
280 private function parseBasicYaml( $input ) {
281 $lines = explode( "\n", $input );
282 $root = [];
283 $stack = [ &$root ];
284 $prev = 0;
285 foreach ( $lines as $i => $text ) {
286 $line = $i + 1;
287 $trimmed = ltrim( $text, ' ' );
288 if ( $trimmed === '' || $trimmed[0] === '#' ) {
289 continue;
290 }
291 $indent = strlen( $text ) - strlen( $trimmed );
292 if ( $indent % 2 !== 0 ) {
293 throw new Exception( __METHOD__ . ": Odd indentation on line $line." );
294 }
295 $depth = $indent === 0 ? 0 : ( $indent / 2 );
296 if ( $depth < $prev ) {
297 // Close previous branches we can't re-enter
298 array_splice( $stack, $depth + 1 );
299 }
300 if ( !array_key_exists( $depth, $stack ) ) {
301 throw new Exception( __METHOD__ . ": Too much indentation on line $line." );
302 }
303 if ( strpos( $trimmed, ':' ) === false ) {
304 throw new Exception( __METHOD__ . ": Missing colon on line $line." );
305 }
306 $dest =& $stack[ $depth ];
307 if ( $dest === null ) {
308 // Promote from null to object
309 $dest = [];
310 }
311 list( $key, $val ) = explode( ':', $trimmed, 2 );
312 $val = ltrim( $val, ' ' );
313 if ( $val !== '' ) {
314 // Add string
315 $dest[ $key ] = $val;
316 } else {
317 // Add null (may become an object later)
318 $val = null;
319 $stack[] = &$val;
320 $dest[ $key ] = &$val;
321 }
322 $prev = $depth;
323 unset( $dest, $val );
324 }
325 return $root;
326 }
327 }