Merge "Add and use Title::getOtherPage()"
[lhc/web/wiklou.git] / includes / filebackend / FSFileBackend.php
1 <?php
2 /**
3 * File system based backend.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
23 */
24
25 /**
26 * @brief Class for a file system (FS) based file backend.
27 *
28 * All "containers" each map to a directory under the backend's base directory.
29 * For backwards-compatibility, some container paths can be set to custom paths.
30 * The wiki ID will not be used in any custom paths, so this should be avoided.
31 *
32 * Having directories with thousands of files will diminish performance.
33 * Sharding can be accomplished by using FileRepo-style hash paths.
34 *
35 * Status messages should avoid mentioning the internal FS paths.
36 * PHP warnings are assumed to be logged rather than output.
37 *
38 * @ingroup FileBackend
39 * @since 1.19
40 */
41 class FSFileBackend extends FileBackendStore {
42 /** @var string Directory holding the container directories */
43 protected $basePath;
44
45 /** @var array Map of container names to root paths for custom container paths */
46 protected $containerPaths = array();
47
48 /** @var int File permission mode */
49 protected $fileMode;
50
51 /** @var string Required OS username to own files */
52 protected $fileOwner;
53
54 /** @var string OS username running this script */
55 protected $currentUser;
56
57 /** @var array */
58 protected $hadWarningErrors = array();
59
60 /**
61 * @see FileBackendStore::__construct()
62 * Additional $config params include:
63 * - basePath : File system directory that holds containers.
64 * - containerPaths : Map of container names to custom file system directories.
65 * This should only be used for backwards-compatibility.
66 * - fileMode : Octal UNIX file permissions to use on files stored.
67 */
68 public function __construct( array $config ) {
69 parent::__construct( $config );
70
71 // Remove any possible trailing slash from directories
72 if ( isset( $config['basePath'] ) ) {
73 $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
74 } else {
75 $this->basePath = null; // none; containers must have explicit paths
76 }
77
78 if ( isset( $config['containerPaths'] ) ) {
79 $this->containerPaths = (array)$config['containerPaths'];
80 foreach ( $this->containerPaths as &$path ) {
81 $path = rtrim( $path, '/' ); // remove trailing slash
82 }
83 }
84
85 $this->fileMode = isset( $config['fileMode'] ) ? $config['fileMode'] : 0644;
86 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
87 $this->fileOwner = $config['fileOwner'];
88 $info = posix_getpwuid( posix_getuid() );
89 $this->currentUser = $info['name']; // cache this, assuming it doesn't change
90 }
91 }
92
93 public function getFeatures() {
94 return !wfIsWindows() ? FileBackend::ATTR_UNICODE_PATHS : 0;
95 }
96
97 protected function resolveContainerPath( $container, $relStoragePath ) {
98 // Check that container has a root directory
99 if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
100 // Check for sane relative paths (assume the base paths are OK)
101 if ( $this->isLegalRelPath( $relStoragePath ) ) {
102 return $relStoragePath;
103 }
104 }
105
106 return null;
107 }
108
109 /**
110 * Sanity check a relative file system path for validity
111 *
112 * @param string $path Normalized relative path
113 * @return bool
114 */
115 protected function isLegalRelPath( $path ) {
116 // Check for file names longer than 255 chars
117 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
118 return false;
119 }
120 if ( wfIsWindows() ) { // NTFS
121 return !preg_match( '![:*?"<>|]!', $path );
122 } else {
123 return true;
124 }
125 }
126
127 /**
128 * Given the short (unresolved) and full (resolved) name of
129 * a container, return the file system path of the container.
130 *
131 * @param string $shortCont
132 * @param string $fullCont
133 * @return string|null
134 */
135 protected function containerFSRoot( $shortCont, $fullCont ) {
136 if ( isset( $this->containerPaths[$shortCont] ) ) {
137 return $this->containerPaths[$shortCont];
138 } elseif ( isset( $this->basePath ) ) {
139 return "{$this->basePath}/{$fullCont}";
140 }
141
142 return null; // no container base path defined
143 }
144
145 /**
146 * Get the absolute file system path for a storage path
147 *
148 * @param string $storagePath Storage path
149 * @return string|null
150 */
151 protected function resolveToFSPath( $storagePath ) {
152 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
153 if ( $relPath === null ) {
154 return null; // invalid
155 }
156 list( , $shortCont, ) = FileBackend::splitStoragePath( $storagePath );
157 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
158 if ( $relPath != '' ) {
159 $fsPath .= "/{$relPath}";
160 }
161
162 return $fsPath;
163 }
164
165 public function isPathUsableInternal( $storagePath ) {
166 $fsPath = $this->resolveToFSPath( $storagePath );
167 if ( $fsPath === null ) {
168 return false; // invalid
169 }
170 $parentDir = dirname( $fsPath );
171
172 if ( file_exists( $fsPath ) ) {
173 $ok = is_file( $fsPath ) && is_writable( $fsPath );
174 } else {
175 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
176 }
177
178 if ( $this->fileOwner !== null && $this->currentUser !== $this->fileOwner ) {
179 $ok = false;
180 trigger_error( __METHOD__ . ": PHP process owner is not '{$this->fileOwner}'." );
181 }
182
183 return $ok;
184 }
185
186 protected function doCreateInternal( array $params ) {
187 $status = Status::newGood();
188
189 $dest = $this->resolveToFSPath( $params['dst'] );
190 if ( $dest === null ) {
191 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
192
193 return $status;
194 }
195
196 if ( !empty( $params['async'] ) ) { // deferred
197 $tempFile = TempFSFile::factory( 'create_', 'tmp' );
198 if ( !$tempFile ) {
199 $status->fatal( 'backend-fail-create', $params['dst'] );
200
201 return $status;
202 }
203 $this->trapWarnings();
204 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
205 $this->untrapWarnings();
206 if ( $bytes === false ) {
207 $status->fatal( 'backend-fail-create', $params['dst'] );
208
209 return $status;
210 }
211 $cmd = implode( ' ', array(
212 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
213 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
214 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
215 ) );
216 $handler = function ( $errors, Status $status, array $params, $cmd ) {
217 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
218 $status->fatal( 'backend-fail-create', $params['dst'] );
219 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
220 }
221 };
222 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
223 $tempFile->bind( $status->value );
224 } else { // immediate write
225 $this->trapWarnings();
226 $bytes = file_put_contents( $dest, $params['content'] );
227 $this->untrapWarnings();
228 if ( $bytes === false ) {
229 $status->fatal( 'backend-fail-create', $params['dst'] );
230
231 return $status;
232 }
233 $this->chmod( $dest );
234 }
235
236 return $status;
237 }
238
239 protected function doStoreInternal( array $params ) {
240 $status = Status::newGood();
241
242 $dest = $this->resolveToFSPath( $params['dst'] );
243 if ( $dest === null ) {
244 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
245
246 return $status;
247 }
248
249 if ( !empty( $params['async'] ) ) { // deferred
250 $cmd = implode( ' ', array(
251 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
252 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
253 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
254 ) );
255 $handler = function ( $errors, Status $status, array $params, $cmd ) {
256 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
257 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
258 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
259 }
260 };
261 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
262 } else { // immediate write
263 $this->trapWarnings();
264 $ok = copy( $params['src'], $dest );
265 $this->untrapWarnings();
266 // In some cases (at least over NFS), copy() returns true when it fails
267 if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
268 if ( $ok ) { // PHP bug
269 unlink( $dest ); // remove broken file
270 trigger_error( __METHOD__ . ": copy() failed but returned true." );
271 }
272 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
273
274 return $status;
275 }
276 $this->chmod( $dest );
277 }
278
279 return $status;
280 }
281
282 protected function doCopyInternal( array $params ) {
283 $status = Status::newGood();
284
285 $source = $this->resolveToFSPath( $params['src'] );
286 if ( $source === null ) {
287 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
288
289 return $status;
290 }
291
292 $dest = $this->resolveToFSPath( $params['dst'] );
293 if ( $dest === null ) {
294 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
295
296 return $status;
297 }
298
299 if ( !is_file( $source ) ) {
300 if ( empty( $params['ignoreMissingSource'] ) ) {
301 $status->fatal( 'backend-fail-copy', $params['src'] );
302 }
303
304 return $status; // do nothing; either OK or bad status
305 }
306
307 if ( !empty( $params['async'] ) ) { // deferred
308 $cmd = implode( ' ', array(
309 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
310 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
311 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
312 ) );
313 $handler = function ( $errors, Status $status, array $params, $cmd ) {
314 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
315 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
316 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
317 }
318 };
319 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
320 } else { // immediate write
321 $this->trapWarnings();
322 $ok = ( $source === $dest ) ? true : copy( $source, $dest );
323 $this->untrapWarnings();
324 // In some cases (at least over NFS), copy() returns true when it fails
325 if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
326 if ( $ok ) { // PHP bug
327 $this->trapWarnings();
328 unlink( $dest ); // remove broken file
329 $this->untrapWarnings();
330 trigger_error( __METHOD__ . ": copy() failed but returned true." );
331 }
332 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
333
334 return $status;
335 }
336 $this->chmod( $dest );
337 }
338
339 return $status;
340 }
341
342 protected function doMoveInternal( array $params ) {
343 $status = Status::newGood();
344
345 $source = $this->resolveToFSPath( $params['src'] );
346 if ( $source === null ) {
347 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
348
349 return $status;
350 }
351
352 $dest = $this->resolveToFSPath( $params['dst'] );
353 if ( $dest === null ) {
354 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
355
356 return $status;
357 }
358
359 if ( !is_file( $source ) ) {
360 if ( empty( $params['ignoreMissingSource'] ) ) {
361 $status->fatal( 'backend-fail-move', $params['src'] );
362 }
363
364 return $status; // do nothing; either OK or bad status
365 }
366
367 if ( !empty( $params['async'] ) ) { // deferred
368 $cmd = implode( ' ', array(
369 wfIsWindows() ? 'MOVE /Y' : 'mv', // (overwrite)
370 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
371 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
372 ) );
373 $handler = function ( $errors, Status $status, array $params, $cmd ) {
374 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
375 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
376 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
377 }
378 };
379 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
380 } else { // immediate write
381 $this->trapWarnings();
382 $ok = ( $source === $dest ) ? true : rename( $source, $dest );
383 $this->untrapWarnings();
384 clearstatcache(); // file no longer at source
385 if ( !$ok ) {
386 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
387
388 return $status;
389 }
390 }
391
392 return $status;
393 }
394
395 protected function doDeleteInternal( array $params ) {
396 $status = Status::newGood();
397
398 $source = $this->resolveToFSPath( $params['src'] );
399 if ( $source === null ) {
400 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
401
402 return $status;
403 }
404
405 if ( !is_file( $source ) ) {
406 if ( empty( $params['ignoreMissingSource'] ) ) {
407 $status->fatal( 'backend-fail-delete', $params['src'] );
408 }
409
410 return $status; // do nothing; either OK or bad status
411 }
412
413 if ( !empty( $params['async'] ) ) { // deferred
414 $cmd = implode( ' ', array(
415 wfIsWindows() ? 'DEL' : 'unlink',
416 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
417 ) );
418 $handler = function ( $errors, Status $status, array $params, $cmd ) {
419 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
420 $status->fatal( 'backend-fail-delete', $params['src'] );
421 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
422 }
423 };
424 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
425 } else { // immediate write
426 $this->trapWarnings();
427 $ok = unlink( $source );
428 $this->untrapWarnings();
429 if ( !$ok ) {
430 $status->fatal( 'backend-fail-delete', $params['src'] );
431
432 return $status;
433 }
434 }
435
436 return $status;
437 }
438
439 /**
440 * @param string $fullCont
441 * @param string $dirRel
442 * @param array $params
443 * @return Status
444 */
445 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
446 $status = Status::newGood();
447 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
448 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
449 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
450 $existed = is_dir( $dir ); // already there?
451 // Create the directory and its parents as needed...
452 $this->trapWarnings();
453 if ( !wfMkdirParents( $dir ) ) {
454 wfDebugLog( 'FSFileBackend', __METHOD__ . ": cannot create directory $dir" );
455 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
456 } elseif ( !is_writable( $dir ) ) {
457 wfDebugLog( 'FSFileBackend', __METHOD__ . ": directory $dir is read-only" );
458 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
459 } elseif ( !is_readable( $dir ) ) {
460 wfDebugLog( 'FSFileBackend', __METHOD__ . ": directory $dir is not readable" );
461 $status->fatal( 'directorynotreadableerror', $params['dir'] );
462 }
463 $this->untrapWarnings();
464 // Respect any 'noAccess' or 'noListing' flags...
465 if ( is_dir( $dir ) && !$existed ) {
466 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
467 }
468
469 return $status;
470 }
471
472 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
473 $status = Status::newGood();
474 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
475 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
476 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
477 // Seed new directories with a blank index.html, to prevent crawling...
478 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
479 $this->trapWarnings();
480 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
481 $this->untrapWarnings();
482 if ( $bytes === false ) {
483 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
484 }
485 }
486 // Add a .htaccess file to the root of the container...
487 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
488 $this->trapWarnings();
489 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
490 $this->untrapWarnings();
491 if ( $bytes === false ) {
492 $storeDir = "mwstore://{$this->name}/{$shortCont}";
493 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
494 }
495 }
496
497 return $status;
498 }
499
500 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
501 $status = Status::newGood();
502 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
503 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
504 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
505 // Unseed new directories with a blank index.html, to allow crawling...
506 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
507 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
508 $this->trapWarnings();
509 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
510 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
511 }
512 $this->untrapWarnings();
513 }
514 // Remove the .htaccess file from the root of the container...
515 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
516 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
517 $this->trapWarnings();
518 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
519 $storeDir = "mwstore://{$this->name}/{$shortCont}";
520 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
521 }
522 $this->untrapWarnings();
523 }
524
525 return $status;
526 }
527
528 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
529 $status = Status::newGood();
530 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
531 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
532 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
533 $this->trapWarnings();
534 if ( is_dir( $dir ) ) {
535 rmdir( $dir ); // remove directory if empty
536 }
537 $this->untrapWarnings();
538
539 return $status;
540 }
541
542 protected function doGetFileStat( array $params ) {
543 $source = $this->resolveToFSPath( $params['src'] );
544 if ( $source === null ) {
545 return false; // invalid storage path
546 }
547
548 $this->trapWarnings(); // don't trust 'false' if there were errors
549 $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
550 $hadError = $this->untrapWarnings();
551
552 if ( $stat ) {
553 return array(
554 'mtime' => wfTimestamp( TS_MW, $stat['mtime'] ),
555 'size' => $stat['size']
556 );
557 } elseif ( !$hadError ) {
558 return false; // file does not exist
559 } else {
560 return null; // failure
561 }
562 }
563
564 /**
565 * @see FileBackendStore::doClearCache()
566 */
567 protected function doClearCache( array $paths = null ) {
568 clearstatcache(); // clear the PHP file stat cache
569 }
570
571 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
572 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
573 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
574 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
575
576 $this->trapWarnings(); // don't trust 'false' if there were errors
577 $exists = is_dir( $dir );
578 $hadError = $this->untrapWarnings();
579
580 return $hadError ? null : $exists;
581 }
582
583 /**
584 * @see FileBackendStore::getDirectoryListInternal()
585 * @param string $fullCont
586 * @param string $dirRel
587 * @param array $params
588 * @return array|null
589 */
590 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
591 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
592 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
593 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
594 $exists = is_dir( $dir );
595 if ( !$exists ) {
596 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
597
598 return array(); // nothing under this dir
599 } elseif ( !is_readable( $dir ) ) {
600 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
601
602 return null; // bad permissions?
603 }
604
605 return new FSFileBackendDirList( $dir, $params );
606 }
607
608 /**
609 * @see FileBackendStore::getFileListInternal()
610 * @param string $fullCont
611 * @param string $dirRel
612 * @param array $params
613 * @return array|FSFileBackendFileList|null
614 */
615 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
616 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
617 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
618 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
619 $exists = is_dir( $dir );
620 if ( !$exists ) {
621 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
622
623 return array(); // nothing under this dir
624 } elseif ( !is_readable( $dir ) ) {
625 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
626
627 return null; // bad permissions?
628 }
629
630 return new FSFileBackendFileList( $dir, $params );
631 }
632
633 protected function doGetLocalReferenceMulti( array $params ) {
634 $fsFiles = array(); // (path => FSFile)
635
636 foreach ( $params['srcs'] as $src ) {
637 $source = $this->resolveToFSPath( $src );
638 if ( $source === null || !is_file( $source ) ) {
639 $fsFiles[$src] = null; // invalid path or file does not exist
640 } else {
641 $fsFiles[$src] = new FSFile( $source );
642 }
643 }
644
645 return $fsFiles;
646 }
647
648 protected function doGetLocalCopyMulti( array $params ) {
649 $tmpFiles = array(); // (path => TempFSFile)
650
651 foreach ( $params['srcs'] as $src ) {
652 $source = $this->resolveToFSPath( $src );
653 if ( $source === null ) {
654 $tmpFiles[$src] = null; // invalid path
655 } else {
656 // Create a new temporary file with the same extension...
657 $ext = FileBackend::extensionFromPath( $src );
658 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
659 if ( !$tmpFile ) {
660 $tmpFiles[$src] = null;
661 } else {
662 $tmpPath = $tmpFile->getPath();
663 // Copy the source file over the temp file
664 $this->trapWarnings();
665 $ok = copy( $source, $tmpPath );
666 $this->untrapWarnings();
667 if ( !$ok ) {
668 $tmpFiles[$src] = null;
669 } else {
670 $this->chmod( $tmpPath );
671 $tmpFiles[$src] = $tmpFile;
672 }
673 }
674 }
675 }
676
677 return $tmpFiles;
678 }
679
680 protected function directoriesAreVirtual() {
681 return false;
682 }
683
684 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
685 $statuses = array();
686
687 $pipes = array();
688 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
689 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
690 }
691
692 $errs = array();
693 foreach ( $pipes as $index => $pipe ) {
694 // Result will be empty on success in *NIX. On Windows,
695 // it may be something like " 1 file(s) [copied|moved].".
696 $errs[$index] = stream_get_contents( $pipe );
697 fclose( $pipe );
698 }
699
700 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
701 $status = Status::newGood();
702 $function = $fileOpHandle->call;
703 $function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
704 $statuses[$index] = $status;
705 if ( $status->isOK() && $fileOpHandle->chmodPath ) {
706 $this->chmod( $fileOpHandle->chmodPath );
707 }
708 }
709
710 clearstatcache(); // files changed
711 return $statuses;
712 }
713
714 /**
715 * Chmod a file, suppressing the warnings
716 *
717 * @param string $path Absolute file system path
718 * @return bool Success
719 */
720 protected function chmod( $path ) {
721 $this->trapWarnings();
722 $ok = chmod( $path, $this->fileMode );
723 $this->untrapWarnings();
724
725 return $ok;
726 }
727
728 /**
729 * Return the text of an index.html file to hide directory listings
730 *
731 * @return string
732 */
733 protected function indexHtmlPrivate() {
734 return '';
735 }
736
737 /**
738 * Return the text of a .htaccess file to make a directory private
739 *
740 * @return string
741 */
742 protected function htaccessPrivate() {
743 return "Deny from all\n";
744 }
745
746 /**
747 * Clean up directory separators for the given OS
748 *
749 * @param string $path FS path
750 * @return string
751 */
752 protected function cleanPathSlashes( $path ) {
753 return wfIsWindows() ? strtr( $path, '/', '\\' ) : $path;
754 }
755
756 /**
757 * Listen for E_WARNING errors and track whether any happen
758 */
759 protected function trapWarnings() {
760 $this->hadWarningErrors[] = false; // push to stack
761 set_error_handler( array( $this, 'handleWarning' ), E_WARNING );
762 }
763
764 /**
765 * Stop listening for E_WARNING errors and return true if any happened
766 *
767 * @return bool
768 */
769 protected function untrapWarnings() {
770 restore_error_handler(); // restore previous handler
771 return array_pop( $this->hadWarningErrors ); // pop from stack
772 }
773
774 /**
775 * @param int $errno
776 * @param string $errstr
777 * @return bool
778 * @access private
779 */
780 public function handleWarning( $errno, $errstr ) {
781 wfDebugLog( 'FSFileBackend', $errstr ); // more detailed error logging
782 $this->hadWarningErrors[count( $this->hadWarningErrors ) - 1] = true;
783
784 return true; // suppress from PHP handler
785 }
786 }
787
788 /**
789 * @see FileBackendStoreOpHandle
790 */
791 class FSFileOpHandle extends FileBackendStoreOpHandle {
792 public $cmd; // string; shell command
793 public $chmodPath; // string; file to chmod
794
795 /**
796 * @param FSFileBackend $backend
797 * @param array $params
798 * @param callable $call
799 * @param string $cmd
800 * @param int|null $chmodPath
801 */
802 public function __construct(
803 FSFileBackend $backend, array $params, $call, $cmd, $chmodPath = null
804 ) {
805 $this->backend = $backend;
806 $this->params = $params;
807 $this->call = $call;
808 $this->cmd = $cmd;
809 $this->chmodPath = $chmodPath;
810 }
811 }
812
813 /**
814 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
815 * catches exception or does any custom behavoir that we may want.
816 * Do not use this class from places outside FSFileBackend.
817 *
818 * @ingroup FileBackend
819 */
820 abstract class FSFileBackendList implements Iterator {
821 /** @var Iterator */
822 protected $iter;
823
824 /** @var int */
825 protected $suffixStart;
826
827 /** @var int */
828 protected $pos = 0;
829
830 /** @var array */
831 protected $params = array();
832
833 /**
834 * @param string $dir File system directory
835 * @param array $params
836 */
837 public function __construct( $dir, array $params ) {
838 $path = realpath( $dir ); // normalize
839 if ( $path === false ) {
840 $path = $dir;
841 }
842 $this->suffixStart = strlen( $path ) + 1; // size of "path/to/dir/"
843 $this->params = $params;
844
845 try {
846 $this->iter = $this->initIterator( $path );
847 } catch ( UnexpectedValueException $e ) {
848 $this->iter = null; // bad permissions? deleted?
849 }
850 }
851
852 /**
853 * Return an appropriate iterator object to wrap
854 *
855 * @param string $dir File system directory
856 * @return Iterator
857 */
858 protected function initIterator( $dir ) {
859 if ( !empty( $this->params['topOnly'] ) ) { // non-recursive
860 # Get an iterator that will get direct sub-nodes
861 return new DirectoryIterator( $dir );
862 } else { // recursive
863 # Get an iterator that will return leaf nodes (non-directories)
864 # RecursiveDirectoryIterator extends FilesystemIterator.
865 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
866 $flags = FilesystemIterator::CURRENT_AS_SELF | FilesystemIterator::SKIP_DOTS;
867
868 return new RecursiveIteratorIterator(
869 new RecursiveDirectoryIterator( $dir, $flags ),
870 RecursiveIteratorIterator::CHILD_FIRST // include dirs
871 );
872 }
873 }
874
875 /**
876 * @see Iterator::key()
877 * @return int
878 */
879 public function key() {
880 return $this->pos;
881 }
882
883 /**
884 * @see Iterator::current()
885 * @return string|bool String or false
886 */
887 public function current() {
888 return $this->getRelPath( $this->iter->current()->getPathname() );
889 }
890
891 /**
892 * @see Iterator::next()
893 * @throws FileBackendError
894 */
895 public function next() {
896 try {
897 $this->iter->next();
898 $this->filterViaNext();
899 } catch ( UnexpectedValueException $e ) { // bad permissions? deleted?
900 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
901 }
902 ++$this->pos;
903 }
904
905 /**
906 * @see Iterator::rewind()
907 * @throws FileBackendError
908 */
909 public function rewind() {
910 $this->pos = 0;
911 try {
912 $this->iter->rewind();
913 $this->filterViaNext();
914 } catch ( UnexpectedValueException $e ) { // bad permissions? deleted?
915 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
916 }
917 }
918
919 /**
920 * @see Iterator::valid()
921 * @return bool
922 */
923 public function valid() {
924 return $this->iter && $this->iter->valid();
925 }
926
927 /**
928 * Filter out items by advancing to the next ones
929 */
930 protected function filterViaNext() {
931 }
932
933 /**
934 * Return only the relative path and normalize slashes to FileBackend-style.
935 * Uses the "real path" since the suffix is based upon that.
936 *
937 * @param string $dir
938 * @return string
939 */
940 protected function getRelPath( $dir ) {
941 $path = realpath( $dir );
942 if ( $path === false ) {
943 $path = $dir;
944 }
945
946 return strtr( substr( $path, $this->suffixStart ), '\\', '/' );
947 }
948 }
949
950 class FSFileBackendDirList extends FSFileBackendList {
951 protected function filterViaNext() {
952 while ( $this->iter->valid() ) {
953 if ( $this->iter->current()->isDot() || !$this->iter->current()->isDir() ) {
954 $this->iter->next(); // skip non-directories and dot files
955 } else {
956 break;
957 }
958 }
959 }
960 }
961
962 class FSFileBackendFileList extends FSFileBackendList {
963 protected function filterViaNext() {
964 while ( $this->iter->valid() ) {
965 if ( !$this->iter->current()->isFile() ) {
966 $this->iter->next(); // skip non-files and dot files
967 } else {
968 break;
969 }
970 }
971 }
972 }