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