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