Merge "(Bug 41352) Provide tests for edit conflicts."
[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::doStoreInternal()
182 * @return Status
183 */
184 protected function doStoreInternal( 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 $cmd = implode( ' ', array(
195 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
196 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
197 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
198 ) );
199 $status->value = new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
200 } else { // immediate write
201 $ok = copy( $params['src'], $dest );
202 // In some cases (at least over NFS), copy() returns true when it fails
203 if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
204 if ( $ok ) { // PHP bug
205 unlink( $dest ); // remove broken file
206 trigger_error( __METHOD__ . ": copy() failed but returned true." );
207 }
208 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
209 return $status;
210 }
211 $this->chmod( $dest );
212 }
213
214 return $status;
215 }
216
217 /**
218 * @see FSFileBackend::doExecuteOpHandlesInternal()
219 */
220 protected function _getResponseStore( $errors, Status $status, array $params, $cmd ) {
221 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
222 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
223 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
224 }
225 }
226
227 /**
228 * @see FileBackendStore::doCopyInternal()
229 * @return Status
230 */
231 protected function doCopyInternal( array $params ) {
232 $status = Status::newGood();
233
234 $source = $this->resolveToFSPath( $params['src'] );
235 if ( $source === null ) {
236 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
237 return $status;
238 }
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 ( !is_file( $source ) ) {
247 if ( empty( $params['ignoreMissingSource'] ) ) {
248 $status->fatal( 'backend-fail-copy', $params['src'] );
249 }
250 return $status; // do nothing; either OK or bad status
251 }
252
253 if ( !empty( $params['async'] ) ) { // deferred
254 $cmd = implode( ' ', array(
255 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
256 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
257 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
258 ) );
259 $status->value = new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
260 } else { // immediate write
261 $ok = copy( $source, $dest );
262 // In some cases (at least over NFS), copy() returns true when it fails
263 if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
264 if ( $ok ) { // PHP bug
265 unlink( $dest ); // remove broken file
266 trigger_error( __METHOD__ . ": copy() failed but returned true." );
267 }
268 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
269 return $status;
270 }
271 $this->chmod( $dest );
272 }
273
274 return $status;
275 }
276
277 /**
278 * @see FSFileBackend::doExecuteOpHandlesInternal()
279 */
280 protected function _getResponseCopy( $errors, Status $status, array $params, $cmd ) {
281 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
282 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
283 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
284 }
285 }
286
287 /**
288 * @see FileBackendStore::doMoveInternal()
289 * @return Status
290 */
291 protected function doMoveInternal( array $params ) {
292 $status = Status::newGood();
293
294 $source = $this->resolveToFSPath( $params['src'] );
295 if ( $source === null ) {
296 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
297 return $status;
298 }
299
300 $dest = $this->resolveToFSPath( $params['dst'] );
301 if ( $dest === null ) {
302 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
303 return $status;
304 }
305
306 if ( !is_file( $source ) ) {
307 if ( empty( $params['ignoreMissingSource'] ) ) {
308 $status->fatal( 'backend-fail-move', $params['src'] );
309 }
310 return $status; // do nothing; either OK or bad status
311 }
312
313 if ( !empty( $params['async'] ) ) { // deferred
314 $cmd = implode( ' ', array(
315 wfIsWindows() ? 'MOVE /Y' : 'mv', // (overwrite)
316 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
317 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
318 ) );
319 $status->value = new FSFileOpHandle( $this, $params, 'Move', $cmd );
320 } else { // immediate write
321 $ok = rename( $source, $dest );
322 clearstatcache(); // file no longer at source
323 if ( !$ok ) {
324 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
325 return $status;
326 }
327 }
328
329 return $status;
330 }
331
332 /**
333 * @see FSFileBackend::doExecuteOpHandlesInternal()
334 */
335 protected function _getResponseMove( $errors, Status $status, array $params, $cmd ) {
336 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
337 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
338 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
339 }
340 }
341
342 /**
343 * @see FileBackendStore::doDeleteInternal()
344 * @return Status
345 */
346 protected function doDeleteInternal( array $params ) {
347 $status = Status::newGood();
348
349 $source = $this->resolveToFSPath( $params['src'] );
350 if ( $source === null ) {
351 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
352 return $status;
353 }
354
355 if ( !is_file( $source ) ) {
356 if ( empty( $params['ignoreMissingSource'] ) ) {
357 $status->fatal( 'backend-fail-delete', $params['src'] );
358 }
359 return $status; // do nothing; either OK or bad status
360 }
361
362 if ( !empty( $params['async'] ) ) { // deferred
363 $cmd = implode( ' ', array(
364 wfIsWindows() ? 'DEL' : 'unlink',
365 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
366 ) );
367 $status->value = new FSFileOpHandle( $this, $params, 'Copy', $cmd );
368 } else { // immediate write
369 $ok = unlink( $source );
370 if ( !$ok ) {
371 $status->fatal( 'backend-fail-delete', $params['src'] );
372 return $status;
373 }
374 }
375
376 return $status;
377 }
378
379 /**
380 * @see FSFileBackend::doExecuteOpHandlesInternal()
381 */
382 protected function _getResponseDelete( $errors, Status $status, array $params, $cmd ) {
383 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
384 $status->fatal( 'backend-fail-delete', $params['src'] );
385 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
386 }
387 }
388
389 /**
390 * @see FileBackendStore::doCreateInternal()
391 * @return Status
392 */
393 protected function doCreateInternal( array $params ) {
394 $status = Status::newGood();
395
396 $dest = $this->resolveToFSPath( $params['dst'] );
397 if ( $dest === null ) {
398 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
399 return $status;
400 }
401
402 if ( !empty( $params['async'] ) ) { // deferred
403 $tempFile = TempFSFile::factory( 'create_', 'tmp' );
404 if ( !$tempFile ) {
405 $status->fatal( 'backend-fail-create', $params['dst'] );
406 return $status;
407 }
408 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
409 if ( $bytes === false ) {
410 $status->fatal( 'backend-fail-create', $params['dst'] );
411 return $status;
412 }
413 $cmd = implode( ' ', array(
414 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
415 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
416 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
417 ) );
418 $status->value = new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
419 $tempFile->bind( $status->value );
420 } else { // immediate write
421 $bytes = file_put_contents( $dest, $params['content'] );
422 if ( $bytes === false ) {
423 $status->fatal( 'backend-fail-create', $params['dst'] );
424 return $status;
425 }
426 $this->chmod( $dest );
427 }
428
429 return $status;
430 }
431
432 /**
433 * @see FSFileBackend::doExecuteOpHandlesInternal()
434 */
435 protected function _getResponseCreate( $errors, Status $status, array $params, $cmd ) {
436 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
437 $status->fatal( 'backend-fail-create', $params['dst'] );
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 }