Merge "Fix exception in Import, when import of a revision fails"
[lhc/web/wiklou.git] / includes / filebackend / FileBackendStore.php
1 <?php
2 /**
3 * Base class for all backends using particular storage medium.
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 Base class for all backends using particular storage medium.
27 *
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
30 *
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
34 *
35 * @ingroup FileBackend
36 * @since 1.19
37 */
38 abstract class FileBackendStore extends FileBackend {
39 /** @var WANObjectCache */
40 protected $memCache;
41 /** @var ProcessCacheLRU Map of paths to small (RAM/disk) cache items */
42 protected $cheapCache;
43 /** @var ProcessCacheLRU Map of paths to large (RAM/disk) cache items */
44 protected $expensiveCache;
45
46 /** @var array Map of container names to sharding config */
47 protected $shardViaHashLevels = array();
48
49 /** @var callable Method to get the MIME type of files */
50 protected $mimeCallback;
51
52 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
53
54 const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
55 const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
56 const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
57
58 /**
59 * @see FileBackend::__construct()
60 * Additional $config params include:
61 * - wanCache : WANOBjectCache object to use for persistent caching.
62 * - mimeCallback : Callback that takes (storage path, content, file system path) and
63 * returns the MIME type of the file or 'unknown/unknown'. The file
64 * system path parameter should be used if the content one is null.
65 *
66 * @param array $config
67 */
68 public function __construct( array $config ) {
69 parent::__construct( $config );
70 $this->mimeCallback = isset( $config['mimeCallback'] )
71 ? $config['mimeCallback']
72 : function ( $storagePath, $content, $fsPath ) {
73 // @todo handle the case of extension-less files using the contents
74 return StreamFile::contentTypeFromPath( $storagePath ) ?: 'unknown/unknown';
75 };
76 $this->memCache = WANObjectCache::newEmpty(); // disabled by default
77 $this->cheapCache = new ProcessCacheLRU( self::CACHE_CHEAP_SIZE );
78 $this->expensiveCache = new ProcessCacheLRU( self::CACHE_EXPENSIVE_SIZE );
79 }
80
81 /**
82 * Get the maximum allowable file size given backend
83 * medium restrictions and basic performance constraints.
84 * Do not call this function from places outside FileBackend and FileOp.
85 *
86 * @return int Bytes
87 */
88 final public function maxFileSizeInternal() {
89 return $this->maxFileSize;
90 }
91
92 /**
93 * Check if a file can be created or changed at a given storage path.
94 * FS backends should check if the parent directory exists, files can be
95 * written under it, and that any file already there is writable.
96 * Backends using key/value stores should check if the container exists.
97 *
98 * @param string $storagePath
99 * @return bool
100 */
101 abstract public function isPathUsableInternal( $storagePath );
102
103 /**
104 * Create a file in the backend with the given contents.
105 * This will overwrite any file that exists at the destination.
106 * Do not call this function from places outside FileBackend and FileOp.
107 *
108 * $params include:
109 * - content : the raw file contents
110 * - dst : destination storage path
111 * - headers : HTTP header name/value map
112 * - async : Status will be returned immediately if supported.
113 * If the status is OK, then its value field will be
114 * set to a FileBackendStoreOpHandle object.
115 * - dstExists : Whether a file exists at the destination (optimization).
116 * Callers can use "false" if no existing file is being changed.
117 *
118 * @param array $params
119 * @return Status
120 */
121 final public function createInternal( array $params ) {
122 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
123 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
124 $status = Status::newFatal( 'backend-fail-maxsize',
125 $params['dst'], $this->maxFileSizeInternal() );
126 } else {
127 $status = $this->doCreateInternal( $params );
128 $this->clearCache( array( $params['dst'] ) );
129 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
130 $this->deleteFileCache( $params['dst'] ); // persistent cache
131 }
132 }
133
134 return $status;
135 }
136
137 /**
138 * @see FileBackendStore::createInternal()
139 * @param array $params
140 * @return Status
141 */
142 abstract protected function doCreateInternal( array $params );
143
144 /**
145 * Store a file into the backend from a file on disk.
146 * This will overwrite any file that exists at the destination.
147 * Do not call this function from places outside FileBackend and FileOp.
148 *
149 * $params include:
150 * - src : source path on disk
151 * - dst : destination storage path
152 * - headers : HTTP header name/value map
153 * - async : Status will be returned immediately if supported.
154 * If the status is OK, then its value field will be
155 * set to a FileBackendStoreOpHandle object.
156 * - dstExists : Whether a file exists at the destination (optimization).
157 * Callers can use "false" if no existing file is being changed.
158 *
159 * @param array $params
160 * @return Status
161 */
162 final public function storeInternal( array $params ) {
163 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
164 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
165 $status = Status::newFatal( 'backend-fail-maxsize',
166 $params['dst'], $this->maxFileSizeInternal() );
167 } else {
168 $status = $this->doStoreInternal( $params );
169 $this->clearCache( array( $params['dst'] ) );
170 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
171 $this->deleteFileCache( $params['dst'] ); // persistent cache
172 }
173 }
174
175 return $status;
176 }
177
178 /**
179 * @see FileBackendStore::storeInternal()
180 * @param array $params
181 * @return Status
182 */
183 abstract protected function doStoreInternal( array $params );
184
185 /**
186 * Copy a file from one storage path to another in the backend.
187 * This will overwrite any file that exists at the destination.
188 * Do not call this function from places outside FileBackend and FileOp.
189 *
190 * $params include:
191 * - src : source storage path
192 * - dst : destination storage path
193 * - ignoreMissingSource : do nothing if the source file does not exist
194 * - headers : HTTP header name/value map
195 * - async : Status will be returned immediately if supported.
196 * If the status is OK, then its value field will be
197 * set to a FileBackendStoreOpHandle object.
198 * - dstExists : Whether a file exists at the destination (optimization).
199 * Callers can use "false" if no existing file is being changed.
200 *
201 * @param array $params
202 * @return Status
203 */
204 final public function copyInternal( array $params ) {
205 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
206 $status = $this->doCopyInternal( $params );
207 $this->clearCache( array( $params['dst'] ) );
208 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
209 $this->deleteFileCache( $params['dst'] ); // persistent cache
210 }
211
212 return $status;
213 }
214
215 /**
216 * @see FileBackendStore::copyInternal()
217 * @param array $params
218 * @return Status
219 */
220 abstract protected function doCopyInternal( array $params );
221
222 /**
223 * Delete a file at the storage path.
224 * Do not call this function from places outside FileBackend and FileOp.
225 *
226 * $params include:
227 * - src : source storage path
228 * - ignoreMissingSource : do nothing if the source file does not exist
229 * - async : Status will be returned immediately if supported.
230 * If the status is OK, then its value field will be
231 * set to a FileBackendStoreOpHandle object.
232 *
233 * @param array $params
234 * @return Status
235 */
236 final public function deleteInternal( array $params ) {
237 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
238 $status = $this->doDeleteInternal( $params );
239 $this->clearCache( array( $params['src'] ) );
240 $this->deleteFileCache( $params['src'] ); // persistent cache
241 return $status;
242 }
243
244 /**
245 * @see FileBackendStore::deleteInternal()
246 * @param array $params
247 * @return Status
248 */
249 abstract protected function doDeleteInternal( array $params );
250
251 /**
252 * Move a file from one storage path to another in the backend.
253 * This will overwrite any file that exists at the destination.
254 * Do not call this function from places outside FileBackend and FileOp.
255 *
256 * $params include:
257 * - src : source storage path
258 * - dst : destination storage path
259 * - ignoreMissingSource : do nothing if the source file does not exist
260 * - headers : HTTP header name/value map
261 * - async : Status will be returned immediately if supported.
262 * If the status is OK, then its value field will be
263 * set to a FileBackendStoreOpHandle object.
264 * - dstExists : Whether a file exists at the destination (optimization).
265 * Callers can use "false" if no existing file is being changed.
266 *
267 * @param array $params
268 * @return Status
269 */
270 final public function moveInternal( array $params ) {
271 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
272 $status = $this->doMoveInternal( $params );
273 $this->clearCache( array( $params['src'], $params['dst'] ) );
274 $this->deleteFileCache( $params['src'] ); // persistent cache
275 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
276 $this->deleteFileCache( $params['dst'] ); // persistent cache
277 }
278
279 return $status;
280 }
281
282 /**
283 * @see FileBackendStore::moveInternal()
284 * @param array $params
285 * @return Status
286 */
287 protected function doMoveInternal( array $params ) {
288 unset( $params['async'] ); // two steps, won't work here :)
289 $nsrc = FileBackend::normalizeStoragePath( $params['src'] );
290 $ndst = FileBackend::normalizeStoragePath( $params['dst'] );
291 // Copy source to dest
292 $status = $this->copyInternal( $params );
293 if ( $nsrc !== $ndst && $status->isOK() ) {
294 // Delete source (only fails due to races or network problems)
295 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
296 $status->setResult( true, $status->value ); // ignore delete() errors
297 }
298
299 return $status;
300 }
301
302 /**
303 * Alter metadata for a file at the storage path.
304 * Do not call this function from places outside FileBackend and FileOp.
305 *
306 * $params include:
307 * - src : source storage path
308 * - headers : HTTP header name/value map
309 * - async : Status will be returned immediately if supported.
310 * If the status is OK, then its value field will be
311 * set to a FileBackendStoreOpHandle object.
312 *
313 * @param array $params
314 * @return Status
315 */
316 final public function describeInternal( array $params ) {
317 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
318 if ( count( $params['headers'] ) ) {
319 $status = $this->doDescribeInternal( $params );
320 $this->clearCache( array( $params['src'] ) );
321 $this->deleteFileCache( $params['src'] ); // persistent cache
322 } else {
323 $status = Status::newGood(); // nothing to do
324 }
325
326 return $status;
327 }
328
329 /**
330 * @see FileBackendStore::describeInternal()
331 * @param array $params
332 * @return Status
333 */
334 protected function doDescribeInternal( array $params ) {
335 return Status::newGood();
336 }
337
338 /**
339 * No-op file operation that does nothing.
340 * Do not call this function from places outside FileBackend and FileOp.
341 *
342 * @param array $params
343 * @return Status
344 */
345 final public function nullInternal( array $params ) {
346 return Status::newGood();
347 }
348
349 final public function concatenate( array $params ) {
350 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
351 $status = Status::newGood();
352
353 // Try to lock the source files for the scope of this function
354 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
355 if ( $status->isOK() ) {
356 // Actually do the file concatenation...
357 $start_time = microtime( true );
358 $status->merge( $this->doConcatenate( $params ) );
359 $sec = microtime( true ) - $start_time;
360 if ( !$status->isOK() ) {
361 wfDebugLog( 'FileOperation', get_class( $this ) . "-{$this->name}" .
362 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
363 }
364 }
365
366 return $status;
367 }
368
369 /**
370 * @see FileBackendStore::concatenate()
371 * @param array $params
372 * @return Status
373 */
374 protected function doConcatenate( array $params ) {
375 $status = Status::newGood();
376 $tmpPath = $params['dst']; // convenience
377 unset( $params['latest'] ); // sanity
378
379 // Check that the specified temp file is valid...
380 MediaWiki\suppressWarnings();
381 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
382 MediaWiki\restoreWarnings();
383 if ( !$ok ) { // not present or not empty
384 $status->fatal( 'backend-fail-opentemp', $tmpPath );
385
386 return $status;
387 }
388
389 // Get local FS versions of the chunks needed for the concatenation...
390 $fsFiles = $this->getLocalReferenceMulti( $params );
391 foreach ( $fsFiles as $path => &$fsFile ) {
392 if ( !$fsFile ) { // chunk failed to download?
393 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
394 if ( !$fsFile ) { // retry failed?
395 $status->fatal( 'backend-fail-read', $path );
396
397 return $status;
398 }
399 }
400 }
401 unset( $fsFile ); // unset reference so we can reuse $fsFile
402
403 // Get a handle for the destination temp file
404 $tmpHandle = fopen( $tmpPath, 'ab' );
405 if ( $tmpHandle === false ) {
406 $status->fatal( 'backend-fail-opentemp', $tmpPath );
407
408 return $status;
409 }
410
411 // Build up the temp file using the source chunks (in order)...
412 foreach ( $fsFiles as $virtualSource => $fsFile ) {
413 // Get a handle to the local FS version
414 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
415 if ( $sourceHandle === false ) {
416 fclose( $tmpHandle );
417 $status->fatal( 'backend-fail-read', $virtualSource );
418
419 return $status;
420 }
421 // Append chunk to file (pass chunk size to avoid magic quotes)
422 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
423 fclose( $sourceHandle );
424 fclose( $tmpHandle );
425 $status->fatal( 'backend-fail-writetemp', $tmpPath );
426
427 return $status;
428 }
429 fclose( $sourceHandle );
430 }
431 if ( !fclose( $tmpHandle ) ) {
432 $status->fatal( 'backend-fail-closetemp', $tmpPath );
433
434 return $status;
435 }
436
437 clearstatcache(); // temp file changed
438
439 return $status;
440 }
441
442 final protected function doPrepare( array $params ) {
443 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
444 $status = Status::newGood();
445
446 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
447 if ( $dir === null ) {
448 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
449
450 return $status; // invalid storage path
451 }
452
453 if ( $shard !== null ) { // confined to a single container/shard
454 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
455 } else { // directory is on several shards
456 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
457 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
458 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
459 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
460 }
461 }
462
463 return $status;
464 }
465
466 /**
467 * @see FileBackendStore::doPrepare()
468 * @param string $container
469 * @param string $dir
470 * @param array $params
471 * @return Status
472 */
473 protected function doPrepareInternal( $container, $dir, array $params ) {
474 return Status::newGood();
475 }
476
477 final protected function doSecure( array $params ) {
478 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
479 $status = Status::newGood();
480
481 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
482 if ( $dir === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
484
485 return $status; // invalid storage path
486 }
487
488 if ( $shard !== null ) { // confined to a single container/shard
489 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
490 } else { // directory is on several shards
491 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
492 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
493 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
494 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
495 }
496 }
497
498 return $status;
499 }
500
501 /**
502 * @see FileBackendStore::doSecure()
503 * @param string $container
504 * @param string $dir
505 * @param array $params
506 * @return Status
507 */
508 protected function doSecureInternal( $container, $dir, array $params ) {
509 return Status::newGood();
510 }
511
512 final protected function doPublish( array $params ) {
513 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
514 $status = Status::newGood();
515
516 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
517 if ( $dir === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
519
520 return $status; // invalid storage path
521 }
522
523 if ( $shard !== null ) { // confined to a single container/shard
524 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
525 } else { // directory is on several shards
526 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
527 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
528 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
529 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
530 }
531 }
532
533 return $status;
534 }
535
536 /**
537 * @see FileBackendStore::doPublish()
538 * @param string $container
539 * @param string $dir
540 * @param array $params
541 * @return Status
542 */
543 protected function doPublishInternal( $container, $dir, array $params ) {
544 return Status::newGood();
545 }
546
547 final protected function doClean( array $params ) {
548 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
549 $status = Status::newGood();
550
551 // Recursive: first delete all empty subdirs recursively
552 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
553 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
554 if ( $subDirsRel !== null ) { // no errors
555 foreach ( $subDirsRel as $subDirRel ) {
556 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
557 $status->merge( $this->doClean( array( 'dir' => $subDir ) + $params ) );
558 }
559 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
560 }
561 }
562
563 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
564 if ( $dir === null ) {
565 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
566
567 return $status; // invalid storage path
568 }
569
570 // Attempt to lock this directory...
571 $filesLockEx = array( $params['dir'] );
572 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
573 if ( !$status->isOK() ) {
574 return $status; // abort
575 }
576
577 if ( $shard !== null ) { // confined to a single container/shard
578 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
579 $this->deleteContainerCache( $fullCont ); // purge cache
580 } else { // directory is on several shards
581 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
582 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
583 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
584 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
585 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
586 }
587 }
588
589 return $status;
590 }
591
592 /**
593 * @see FileBackendStore::doClean()
594 * @param string $container
595 * @param string $dir
596 * @param array $params
597 * @return Status
598 */
599 protected function doCleanInternal( $container, $dir, array $params ) {
600 return Status::newGood();
601 }
602
603 final public function fileExists( array $params ) {
604 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
605 $stat = $this->getFileStat( $params );
606
607 return ( $stat === null ) ? null : (bool)$stat; // null => failure
608 }
609
610 final public function getFileTimestamp( array $params ) {
611 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
612 $stat = $this->getFileStat( $params );
613
614 return $stat ? $stat['mtime'] : false;
615 }
616
617 final public function getFileSize( array $params ) {
618 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
619 $stat = $this->getFileStat( $params );
620
621 return $stat ? $stat['size'] : false;
622 }
623
624 final public function getFileStat( array $params ) {
625 $path = self::normalizeStoragePath( $params['src'] );
626 if ( $path === null ) {
627 return false; // invalid storage path
628 }
629 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
630 $latest = !empty( $params['latest'] ); // use latest data?
631 if ( !$latest && !$this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
632 $this->primeFileCache( array( $path ) ); // check persistent cache
633 }
634 if ( $this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
635 $stat = $this->cheapCache->get( $path, 'stat' );
636 // If we want the latest data, check that this cached
637 // value was in fact fetched with the latest available data.
638 if ( is_array( $stat ) ) {
639 if ( !$latest || $stat['latest'] ) {
640 return $stat;
641 }
642 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
643 if ( !$latest || $stat === 'NOT_EXIST_LATEST' ) {
644 return false;
645 }
646 }
647 }
648 $stat = $this->doGetFileStat( $params );
649 if ( is_array( $stat ) ) { // file exists
650 // Strongly consistent backends can automatically set "latest"
651 $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest;
652 $this->cheapCache->set( $path, 'stat', $stat );
653 $this->setFileCache( $path, $stat ); // update persistent cache
654 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
655 $this->cheapCache->set( $path, 'sha1',
656 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
657 }
658 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
659 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
660 $this->cheapCache->set( $path, 'xattr',
661 array( 'map' => $stat['xattr'], 'latest' => $latest ) );
662 }
663 } elseif ( $stat === false ) { // file does not exist
664 $this->cheapCache->set( $path, 'stat', $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
665 $this->cheapCache->set( $path, 'xattr', array( 'map' => false, 'latest' => $latest ) );
666 $this->cheapCache->set( $path, 'sha1', array( 'hash' => false, 'latest' => $latest ) );
667 wfDebug( __METHOD__ . ": File $path does not exist.\n" );
668 } else { // an error occurred
669 wfDebug( __METHOD__ . ": Could not stat file $path.\n" );
670 }
671
672 return $stat;
673 }
674
675 /**
676 * @see FileBackendStore::getFileStat()
677 */
678 abstract protected function doGetFileStat( array $params );
679
680 public function getFileContentsMulti( array $params ) {
681 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
682
683 $params = $this->setConcurrencyFlags( $params );
684 $contents = $this->doGetFileContentsMulti( $params );
685
686 return $contents;
687 }
688
689 /**
690 * @see FileBackendStore::getFileContentsMulti()
691 * @param array $params
692 * @return array
693 */
694 protected function doGetFileContentsMulti( array $params ) {
695 $contents = array();
696 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
697 MediaWiki\suppressWarnings();
698 $contents[$path] = $fsFile ? file_get_contents( $fsFile->getPath() ) : false;
699 MediaWiki\restoreWarnings();
700 }
701
702 return $contents;
703 }
704
705 final public function getFileXAttributes( array $params ) {
706 $path = self::normalizeStoragePath( $params['src'] );
707 if ( $path === null ) {
708 return false; // invalid storage path
709 }
710 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
711 $latest = !empty( $params['latest'] ); // use latest data?
712 if ( $this->cheapCache->has( $path, 'xattr', self::CACHE_TTL ) ) {
713 $stat = $this->cheapCache->get( $path, 'xattr' );
714 // If we want the latest data, check that this cached
715 // value was in fact fetched with the latest available data.
716 if ( !$latest || $stat['latest'] ) {
717 return $stat['map'];
718 }
719 }
720 $fields = $this->doGetFileXAttributes( $params );
721 $fields = is_array( $fields ) ? self::normalizeXAttributes( $fields ) : false;
722 $this->cheapCache->set( $path, 'xattr', array( 'map' => $fields, 'latest' => $latest ) );
723
724 return $fields;
725 }
726
727 /**
728 * @see FileBackendStore::getFileXAttributes()
729 * @return bool|string
730 */
731 protected function doGetFileXAttributes( array $params ) {
732 return array( 'headers' => array(), 'metadata' => array() ); // not supported
733 }
734
735 final public function getFileSha1Base36( array $params ) {
736 $path = self::normalizeStoragePath( $params['src'] );
737 if ( $path === null ) {
738 return false; // invalid storage path
739 }
740 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
741 $latest = !empty( $params['latest'] ); // use latest data?
742 if ( $this->cheapCache->has( $path, 'sha1', self::CACHE_TTL ) ) {
743 $stat = $this->cheapCache->get( $path, 'sha1' );
744 // If we want the latest data, check that this cached
745 // value was in fact fetched with the latest available data.
746 if ( !$latest || $stat['latest'] ) {
747 return $stat['hash'];
748 }
749 }
750 $hash = $this->doGetFileSha1Base36( $params );
751 $this->cheapCache->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
752
753 return $hash;
754 }
755
756 /**
757 * @see FileBackendStore::getFileSha1Base36()
758 * @param array $params
759 * @return bool|string
760 */
761 protected function doGetFileSha1Base36( array $params ) {
762 $fsFile = $this->getLocalReference( $params );
763 if ( !$fsFile ) {
764 return false;
765 } else {
766 return $fsFile->getSha1Base36();
767 }
768 }
769
770 final public function getFileProps( array $params ) {
771 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
772 $fsFile = $this->getLocalReference( $params );
773 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
774
775 return $props;
776 }
777
778 final public function getLocalReferenceMulti( array $params ) {
779 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
780
781 $params = $this->setConcurrencyFlags( $params );
782
783 $fsFiles = array(); // (path => FSFile)
784 $latest = !empty( $params['latest'] ); // use latest data?
785 // Reuse any files already in process cache...
786 foreach ( $params['srcs'] as $src ) {
787 $path = self::normalizeStoragePath( $src );
788 if ( $path === null ) {
789 $fsFiles[$src] = null; // invalid storage path
790 } elseif ( $this->expensiveCache->has( $path, 'localRef' ) ) {
791 $val = $this->expensiveCache->get( $path, 'localRef' );
792 // If we want the latest data, check that this cached
793 // value was in fact fetched with the latest available data.
794 if ( !$latest || $val['latest'] ) {
795 $fsFiles[$src] = $val['object'];
796 }
797 }
798 }
799 // Fetch local references of any remaning files...
800 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
801 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
802 $fsFiles[$path] = $fsFile;
803 if ( $fsFile ) { // update the process cache...
804 $this->expensiveCache->set( $path, 'localRef',
805 array( 'object' => $fsFile, 'latest' => $latest ) );
806 }
807 }
808
809 return $fsFiles;
810 }
811
812 /**
813 * @see FileBackendStore::getLocalReferenceMulti()
814 * @param array $params
815 * @return array
816 */
817 protected function doGetLocalReferenceMulti( array $params ) {
818 return $this->doGetLocalCopyMulti( $params );
819 }
820
821 final public function getLocalCopyMulti( array $params ) {
822 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
823
824 $params = $this->setConcurrencyFlags( $params );
825 $tmpFiles = $this->doGetLocalCopyMulti( $params );
826
827 return $tmpFiles;
828 }
829
830 /**
831 * @see FileBackendStore::getLocalCopyMulti()
832 * @param array $params
833 * @return array
834 */
835 abstract protected function doGetLocalCopyMulti( array $params );
836
837 /**
838 * @see FileBackend::getFileHttpUrl()
839 * @param array $params
840 * @return string|null
841 */
842 public function getFileHttpUrl( array $params ) {
843 return null; // not supported
844 }
845
846 final public function streamFile( array $params ) {
847 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
848 $status = Status::newGood();
849
850 $info = $this->getFileStat( $params );
851 if ( !$info ) { // let StreamFile handle the 404
852 $status->fatal( 'backend-fail-notexists', $params['src'] );
853 }
854
855 // Set output buffer and HTTP headers for stream
856 $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
857 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
858 if ( $res == StreamFile::NOT_MODIFIED ) {
859 // do nothing; client cache is up to date
860 } elseif ( $res == StreamFile::READY_STREAM ) {
861 $status = $this->doStreamFile( $params );
862 if ( !$status->isOK() ) {
863 // Per bug 41113, nasty things can happen if bad cache entries get
864 // stuck in cache. It's also possible that this error can come up
865 // with simple race conditions. Clear out the stat cache to be safe.
866 $this->clearCache( array( $params['src'] ) );
867 $this->deleteFileCache( $params['src'] );
868 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
869 }
870 } else {
871 $status->fatal( 'backend-fail-stream', $params['src'] );
872 }
873
874 return $status;
875 }
876
877 /**
878 * @see FileBackendStore::streamFile()
879 * @param array $params
880 * @return Status
881 */
882 protected function doStreamFile( array $params ) {
883 $status = Status::newGood();
884
885 $fsFile = $this->getLocalReference( $params );
886 if ( !$fsFile ) {
887 $status->fatal( 'backend-fail-stream', $params['src'] );
888 } elseif ( !readfile( $fsFile->getPath() ) ) {
889 $status->fatal( 'backend-fail-stream', $params['src'] );
890 }
891
892 return $status;
893 }
894
895 final public function directoryExists( array $params ) {
896 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
897 if ( $dir === null ) {
898 return false; // invalid storage path
899 }
900 if ( $shard !== null ) { // confined to a single container/shard
901 return $this->doDirectoryExists( $fullCont, $dir, $params );
902 } else { // directory is on several shards
903 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
904 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
905 $res = false; // response
906 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
907 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
908 if ( $exists ) {
909 $res = true;
910 break; // found one!
911 } elseif ( $exists === null ) { // error?
912 $res = null; // if we don't find anything, it is indeterminate
913 }
914 }
915
916 return $res;
917 }
918 }
919
920 /**
921 * @see FileBackendStore::directoryExists()
922 *
923 * @param string $container Resolved container name
924 * @param string $dir Resolved path relative to container
925 * @param array $params
926 * @return bool|null
927 */
928 abstract protected function doDirectoryExists( $container, $dir, array $params );
929
930 final public function getDirectoryList( array $params ) {
931 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
932 if ( $dir === null ) { // invalid storage path
933 return null;
934 }
935 if ( $shard !== null ) {
936 // File listing is confined to a single container/shard
937 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
938 } else {
939 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
940 // File listing spans multiple containers/shards
941 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
942
943 return new FileBackendStoreShardDirIterator( $this,
944 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
945 }
946 }
947
948 /**
949 * Do not call this function from places outside FileBackend
950 *
951 * @see FileBackendStore::getDirectoryList()
952 *
953 * @param string $container Resolved container name
954 * @param string $dir Resolved path relative to container
955 * @param array $params
956 * @return Traversable|array|null Returns null on failure
957 */
958 abstract public function getDirectoryListInternal( $container, $dir, array $params );
959
960 final public function getFileList( array $params ) {
961 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
962 if ( $dir === null ) { // invalid storage path
963 return null;
964 }
965 if ( $shard !== null ) {
966 // File listing is confined to a single container/shard
967 return $this->getFileListInternal( $fullCont, $dir, $params );
968 } else {
969 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
970 // File listing spans multiple containers/shards
971 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
972
973 return new FileBackendStoreShardFileIterator( $this,
974 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
975 }
976 }
977
978 /**
979 * Do not call this function from places outside FileBackend
980 *
981 * @see FileBackendStore::getFileList()
982 *
983 * @param string $container Resolved container name
984 * @param string $dir Resolved path relative to container
985 * @param array $params
986 * @return Traversable|array|null Returns null on failure
987 */
988 abstract public function getFileListInternal( $container, $dir, array $params );
989
990 /**
991 * Return a list of FileOp objects from a list of operations.
992 * Do not call this function from places outside FileBackend.
993 *
994 * The result must have the same number of items as the input.
995 * An exception is thrown if an unsupported operation is requested.
996 *
997 * @param array $ops Same format as doOperations()
998 * @return array List of FileOp objects
999 * @throws FileBackendError
1000 */
1001 final public function getOperationsInternal( array $ops ) {
1002 $supportedOps = array(
1003 'store' => 'StoreFileOp',
1004 'copy' => 'CopyFileOp',
1005 'move' => 'MoveFileOp',
1006 'delete' => 'DeleteFileOp',
1007 'create' => 'CreateFileOp',
1008 'describe' => 'DescribeFileOp',
1009 'null' => 'NullFileOp'
1010 );
1011
1012 $performOps = array(); // array of FileOp objects
1013 // Build up ordered array of FileOps...
1014 foreach ( $ops as $operation ) {
1015 $opName = $operation['op'];
1016 if ( isset( $supportedOps[$opName] ) ) {
1017 $class = $supportedOps[$opName];
1018 // Get params for this operation
1019 $params = $operation;
1020 // Append the FileOp class
1021 $performOps[] = new $class( $this, $params );
1022 } else {
1023 throw new FileBackendError( "Operation '$opName' is not supported." );
1024 }
1025 }
1026
1027 return $performOps;
1028 }
1029
1030 /**
1031 * Get a list of storage paths to lock for a list of operations
1032 * Returns an array with LockManager::LOCK_UW (shared locks) and
1033 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1034 * to a list of storage paths to be locked. All returned paths are
1035 * normalized.
1036 *
1037 * @param array $performOps List of FileOp objects
1038 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1039 */
1040 final public function getPathsToLockForOpsInternal( array $performOps ) {
1041 // Build up a list of files to lock...
1042 $paths = array( 'sh' => array(), 'ex' => array() );
1043 foreach ( $performOps as $fileOp ) {
1044 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1045 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1046 }
1047 // Optimization: if doing an EX lock anyway, don't also set an SH one
1048 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1049 // Get a shared lock on the parent directory of each path changed
1050 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1051
1052 return array(
1053 LockManager::LOCK_UW => $paths['sh'],
1054 LockManager::LOCK_EX => $paths['ex']
1055 );
1056 }
1057
1058 public function getScopedLocksForOps( array $ops, Status $status ) {
1059 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1060
1061 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1062 }
1063
1064 final protected function doOperationsInternal( array $ops, array $opts ) {
1065 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1066 $status = Status::newGood();
1067
1068 // Fix up custom header name/value pairs...
1069 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1070
1071 // Build up a list of FileOps...
1072 $performOps = $this->getOperationsInternal( $ops );
1073
1074 // Acquire any locks as needed...
1075 if ( empty( $opts['nonLocking'] ) ) {
1076 // Build up a list of files to lock...
1077 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1078 // Try to lock those files for the scope of this function...
1079
1080 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1081 if ( !$status->isOK() ) {
1082 return $status; // abort
1083 }
1084 }
1085
1086 // Clear any file cache entries (after locks acquired)
1087 if ( empty( $opts['preserveCache'] ) ) {
1088 $this->clearCache();
1089 }
1090
1091 // Build the list of paths involved
1092 $paths = array();
1093 foreach ( $performOps as $op ) {
1094 $paths = array_merge( $paths, $op->storagePathsRead() );
1095 $paths = array_merge( $paths, $op->storagePathsChanged() );
1096 }
1097
1098 // Enlarge the cache to fit the stat entries of these files
1099 $this->cheapCache->resize( max( 2 * count( $paths ), self::CACHE_CHEAP_SIZE ) );
1100
1101 // Load from the persistent container caches
1102 $this->primeContainerCache( $paths );
1103 // Get the latest stat info for all the files (having locked them)
1104 $ok = $this->preloadFileStat( array( 'srcs' => $paths, 'latest' => true ) );
1105
1106 if ( $ok ) {
1107 // Actually attempt the operation batch...
1108 $opts = $this->setConcurrencyFlags( $opts );
1109 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1110 } else {
1111 // If we could not even stat some files, then bail out...
1112 $subStatus = Status::newFatal( 'backend-fail-internal', $this->name );
1113 foreach ( $ops as $i => $op ) { // mark each op as failed
1114 $subStatus->success[$i] = false;
1115 ++$subStatus->failCount;
1116 }
1117 wfDebugLog( 'FileOperation', get_class( $this ) . "-{$this->name} " .
1118 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1119 }
1120
1121 // Merge errors into status fields
1122 $status->merge( $subStatus );
1123 $status->success = $subStatus->success; // not done in merge()
1124
1125 // Shrink the stat cache back to normal size
1126 $this->cheapCache->resize( self::CACHE_CHEAP_SIZE );
1127
1128 return $status;
1129 }
1130
1131 final protected function doQuickOperationsInternal( array $ops ) {
1132 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1133 $status = Status::newGood();
1134
1135 // Fix up custom header name/value pairs...
1136 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1137
1138 // Clear any file cache entries
1139 $this->clearCache();
1140
1141 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' );
1142 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1143 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1144 $maxConcurrency = $this->concurrency; // throttle
1145
1146 $statuses = array(); // array of (index => Status)
1147 $fileOpHandles = array(); // list of (index => handle) arrays
1148 $curFileOpHandles = array(); // current handle batch
1149 // Perform the sync-only ops and build up op handles for the async ops...
1150 foreach ( $ops as $index => $params ) {
1151 if ( !in_array( $params['op'], $supportedOps ) ) {
1152 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1153 }
1154 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1155 $subStatus = $this->$method( array( 'async' => $async ) + $params );
1156 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1157 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1158 $fileOpHandles[] = $curFileOpHandles; // push this batch
1159 $curFileOpHandles = array();
1160 }
1161 $curFileOpHandles[$index] = $subStatus->value; // keep index
1162 } else { // error or completed
1163 $statuses[$index] = $subStatus; // keep index
1164 }
1165 }
1166 if ( count( $curFileOpHandles ) ) {
1167 $fileOpHandles[] = $curFileOpHandles; // last batch
1168 }
1169 // Do all the async ops that can be done concurrently...
1170 foreach ( $fileOpHandles as $fileHandleBatch ) {
1171 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1172 }
1173 // Marshall and merge all the responses...
1174 foreach ( $statuses as $index => $subStatus ) {
1175 $status->merge( $subStatus );
1176 if ( $subStatus->isOK() ) {
1177 $status->success[$index] = true;
1178 ++$status->successCount;
1179 } else {
1180 $status->success[$index] = false;
1181 ++$status->failCount;
1182 }
1183 }
1184
1185 return $status;
1186 }
1187
1188 /**
1189 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1190 * The resulting Status object fields will correspond
1191 * to the order in which the handles where given.
1192 *
1193 * @param FileBackendStoreOpHandle[] $fileOpHandles
1194 *
1195 * @throws FileBackendError
1196 * @return array Map of Status objects
1197 */
1198 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1199 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1200
1201 foreach ( $fileOpHandles as $fileOpHandle ) {
1202 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1203 throw new FileBackendError( "Given a non-FileBackendStoreOpHandle object." );
1204 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1205 throw new FileBackendError( "Given a FileBackendStoreOpHandle for the wrong backend." );
1206 }
1207 }
1208 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1209 foreach ( $fileOpHandles as $fileOpHandle ) {
1210 $fileOpHandle->closeResources();
1211 }
1212
1213 return $res;
1214 }
1215
1216 /**
1217 * @see FileBackendStore::executeOpHandlesInternal()
1218 *
1219 * @param FileBackendStoreOpHandle[] $fileOpHandles
1220 *
1221 * @throws FileBackendError
1222 * @return Status[] List of corresponding Status objects
1223 */
1224 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1225 if ( count( $fileOpHandles ) ) {
1226 throw new FileBackendError( "This backend supports no asynchronous operations." );
1227 }
1228
1229 return array();
1230 }
1231
1232 /**
1233 * Strip long HTTP headers from a file operation.
1234 * Most headers are just numbers, but some are allowed to be long.
1235 * This function is useful for cleaning up headers and avoiding backend
1236 * specific errors, especially in the middle of batch file operations.
1237 *
1238 * @param array $op Same format as doOperation()
1239 * @return array
1240 */
1241 protected function stripInvalidHeadersFromOp( array $op ) {
1242 static $longs = array( 'Content-Disposition' );
1243 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1244 foreach ( $op['headers'] as $name => $value ) {
1245 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1246 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1247 trigger_error( "Header '$name: $value' is too long." );
1248 unset( $op['headers'][$name] );
1249 } elseif ( !strlen( $value ) ) {
1250 $op['headers'][$name] = ''; // null/false => ""
1251 }
1252 }
1253 }
1254
1255 return $op;
1256 }
1257
1258 final public function preloadCache( array $paths ) {
1259 $fullConts = array(); // full container names
1260 foreach ( $paths as $path ) {
1261 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1262 $fullConts[] = $fullCont;
1263 }
1264 // Load from the persistent file and container caches
1265 $this->primeContainerCache( $fullConts );
1266 $this->primeFileCache( $paths );
1267 }
1268
1269 final public function clearCache( array $paths = null ) {
1270 if ( is_array( $paths ) ) {
1271 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1272 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1273 }
1274 if ( $paths === null ) {
1275 $this->cheapCache->clear();
1276 $this->expensiveCache->clear();
1277 } else {
1278 foreach ( $paths as $path ) {
1279 $this->cheapCache->clear( $path );
1280 $this->expensiveCache->clear( $path );
1281 }
1282 }
1283 $this->doClearCache( $paths );
1284 }
1285
1286 /**
1287 * Clears any additional stat caches for storage paths
1288 *
1289 * @see FileBackend::clearCache()
1290 *
1291 * @param array $paths Storage paths (optional)
1292 */
1293 protected function doClearCache( array $paths = null ) {
1294 }
1295
1296 final public function preloadFileStat( array $params ) {
1297 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1298 $success = true; // no network errors
1299
1300 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1301 $stats = $this->doGetFileStatMulti( $params );
1302 if ( $stats === null ) {
1303 return true; // not supported
1304 }
1305
1306 $latest = !empty( $params['latest'] ); // use latest data?
1307 foreach ( $stats as $path => $stat ) {
1308 $path = FileBackend::normalizeStoragePath( $path );
1309 if ( $path === null ) {
1310 continue; // this shouldn't happen
1311 }
1312 if ( is_array( $stat ) ) { // file exists
1313 // Strongly consistent backends can automatically set "latest"
1314 $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest;
1315 $this->cheapCache->set( $path, 'stat', $stat );
1316 $this->setFileCache( $path, $stat ); // update persistent cache
1317 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1318 $this->cheapCache->set( $path, 'sha1',
1319 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
1320 }
1321 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1322 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1323 $this->cheapCache->set( $path, 'xattr',
1324 array( 'map' => $stat['xattr'], 'latest' => $latest ) );
1325 }
1326 } elseif ( $stat === false ) { // file does not exist
1327 $this->cheapCache->set( $path, 'stat',
1328 $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1329 $this->cheapCache->set( $path, 'xattr',
1330 array( 'map' => false, 'latest' => $latest ) );
1331 $this->cheapCache->set( $path, 'sha1',
1332 array( 'hash' => false, 'latest' => $latest ) );
1333 wfDebug( __METHOD__ . ": File $path does not exist.\n" );
1334 } else { // an error occurred
1335 $success = false;
1336 wfDebug( __METHOD__ . ": Could not stat file $path.\n" );
1337 }
1338 }
1339
1340 return $success;
1341 }
1342
1343 /**
1344 * Get file stat information (concurrently if possible) for several files
1345 *
1346 * @see FileBackend::getFileStat()
1347 *
1348 * @param array $params Parameters include:
1349 * - srcs : list of source storage paths
1350 * - latest : use the latest available data
1351 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1352 * @since 1.23
1353 */
1354 protected function doGetFileStatMulti( array $params ) {
1355 return null; // not supported
1356 }
1357
1358 /**
1359 * Is this a key/value store where directories are just virtual?
1360 * Virtual directories exists in so much as files exists that are
1361 * prefixed with the directory path followed by a forward slash.
1362 *
1363 * @return bool
1364 */
1365 abstract protected function directoriesAreVirtual();
1366
1367 /**
1368 * Check if a short container name is valid
1369 *
1370 * This checks for length and illegal characters.
1371 * This may disallow certain characters that can appear
1372 * in the prefix used to make the full container name.
1373 *
1374 * @param string $container
1375 * @return bool
1376 */
1377 final protected static function isValidShortContainerName( $container ) {
1378 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1379 // might be used by subclasses. Reserve the dot character for sanity.
1380 // The only way dots end up in containers (e.g. resolveStoragePath)
1381 // is due to the wikiId container prefix or the above suffixes.
1382 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1383 }
1384
1385 /**
1386 * Check if a full container name is valid
1387 *
1388 * This checks for length and illegal characters.
1389 * Limiting the characters makes migrations to other stores easier.
1390 *
1391 * @param string $container
1392 * @return bool
1393 */
1394 final protected static function isValidContainerName( $container ) {
1395 // This accounts for NTFS, Swift, and Ceph restrictions
1396 // and disallows directory separators or traversal characters.
1397 // Note that matching strings URL encode to the same string;
1398 // in Swift/Ceph, the length restriction is *after* URL encoding.
1399 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1400 }
1401
1402 /**
1403 * Splits a storage path into an internal container name,
1404 * an internal relative file name, and a container shard suffix.
1405 * Any shard suffix is already appended to the internal container name.
1406 * This also checks that the storage path is valid and within this backend.
1407 *
1408 * If the container is sharded but a suffix could not be determined,
1409 * this means that the path can only refer to a directory and can only
1410 * be scanned by looking in all the container shards.
1411 *
1412 * @param string $storagePath
1413 * @return array (container, path, container suffix) or (null, null, null) if invalid
1414 */
1415 final protected function resolveStoragePath( $storagePath ) {
1416 list( $backend, $shortCont, $relPath ) = self::splitStoragePath( $storagePath );
1417 if ( $backend === $this->name ) { // must be for this backend
1418 $relPath = self::normalizeContainerPath( $relPath );
1419 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1420 // Get shard for the normalized path if this container is sharded
1421 $cShard = $this->getContainerShard( $shortCont, $relPath );
1422 // Validate and sanitize the relative path (backend-specific)
1423 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1424 if ( $relPath !== null ) {
1425 // Prepend any wiki ID prefix to the container name
1426 $container = $this->fullContainerName( $shortCont );
1427 if ( self::isValidContainerName( $container ) ) {
1428 // Validate and sanitize the container name (backend-specific)
1429 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1430 if ( $container !== null ) {
1431 return array( $container, $relPath, $cShard );
1432 }
1433 }
1434 }
1435 }
1436 }
1437
1438 return array( null, null, null );
1439 }
1440
1441 /**
1442 * Like resolveStoragePath() except null values are returned if
1443 * the container is sharded and the shard could not be determined
1444 * or if the path ends with '/'. The later case is illegal for FS
1445 * backends and can confuse listings for object store backends.
1446 *
1447 * This function is used when resolving paths that must be valid
1448 * locations for files. Directory and listing functions should
1449 * generally just use resolveStoragePath() instead.
1450 *
1451 * @see FileBackendStore::resolveStoragePath()
1452 *
1453 * @param string $storagePath
1454 * @return array (container, path) or (null, null) if invalid
1455 */
1456 final protected function resolveStoragePathReal( $storagePath ) {
1457 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1458 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1459 return array( $container, $relPath );
1460 }
1461
1462 return array( null, null );
1463 }
1464
1465 /**
1466 * Get the container name shard suffix for a given path.
1467 * Any empty suffix means the container is not sharded.
1468 *
1469 * @param string $container Container name
1470 * @param string $relPath Storage path relative to the container
1471 * @return string|null Returns null if shard could not be determined
1472 */
1473 final protected function getContainerShard( $container, $relPath ) {
1474 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1475 if ( $levels == 1 || $levels == 2 ) {
1476 // Hash characters are either base 16 or 36
1477 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1478 // Get a regex that represents the shard portion of paths.
1479 // The concatenation of the captures gives us the shard.
1480 if ( $levels === 1 ) { // 16 or 36 shards per container
1481 $hashDirRegex = '(' . $char . ')';
1482 } else { // 256 or 1296 shards per container
1483 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1484 $hashDirRegex = $char . '/(' . $char . '{2})';
1485 } else { // short hash dir format (e.g. "a/b/c")
1486 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1487 }
1488 }
1489 // Allow certain directories to be above the hash dirs so as
1490 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1491 // They must be 2+ chars to avoid any hash directory ambiguity.
1492 $m = array();
1493 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1494 return '.' . implode( '', array_slice( $m, 1 ) );
1495 }
1496
1497 return null; // failed to match
1498 }
1499
1500 return ''; // no sharding
1501 }
1502
1503 /**
1504 * Check if a storage path maps to a single shard.
1505 * Container dirs like "a", where the container shards on "x/xy",
1506 * can reside on several shards. Such paths are tricky to handle.
1507 *
1508 * @param string $storagePath Storage path
1509 * @return bool
1510 */
1511 final public function isSingleShardPathInternal( $storagePath ) {
1512 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1513
1514 return ( $shard !== null );
1515 }
1516
1517 /**
1518 * Get the sharding config for a container.
1519 * If greater than 0, then all file storage paths within
1520 * the container are required to be hashed accordingly.
1521 *
1522 * @param string $container
1523 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1524 */
1525 final protected function getContainerHashLevels( $container ) {
1526 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1527 $config = $this->shardViaHashLevels[$container];
1528 $hashLevels = (int)$config['levels'];
1529 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1530 $hashBase = (int)$config['base'];
1531 if ( $hashBase == 16 || $hashBase == 36 ) {
1532 return array( $hashLevels, $hashBase, $config['repeat'] );
1533 }
1534 }
1535 }
1536
1537 return array( 0, 0, false ); // no sharding
1538 }
1539
1540 /**
1541 * Get a list of full container shard suffixes for a container
1542 *
1543 * @param string $container
1544 * @return array
1545 */
1546 final protected function getContainerSuffixes( $container ) {
1547 $shards = array();
1548 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1549 if ( $digits > 0 ) {
1550 $numShards = pow( $base, $digits );
1551 for ( $index = 0; $index < $numShards; $index++ ) {
1552 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1553 }
1554 }
1555
1556 return $shards;
1557 }
1558
1559 /**
1560 * Get the full container name, including the wiki ID prefix
1561 *
1562 * @param string $container
1563 * @return string
1564 */
1565 final protected function fullContainerName( $container ) {
1566 if ( $this->wikiId != '' ) {
1567 return "{$this->wikiId}-$container";
1568 } else {
1569 return $container;
1570 }
1571 }
1572
1573 /**
1574 * Resolve a container name, checking if it's allowed by the backend.
1575 * This is intended for internal use, such as encoding illegal chars.
1576 * Subclasses can override this to be more restrictive.
1577 *
1578 * @param string $container
1579 * @return string|null
1580 */
1581 protected function resolveContainerName( $container ) {
1582 return $container;
1583 }
1584
1585 /**
1586 * Resolve a relative storage path, checking if it's allowed by the backend.
1587 * This is intended for internal use, such as encoding illegal chars or perhaps
1588 * getting absolute paths (e.g. FS based backends). Note that the relative path
1589 * may be the empty string (e.g. the path is simply to the container).
1590 *
1591 * @param string $container Container name
1592 * @param string $relStoragePath Storage path relative to the container
1593 * @return string|null Path or null if not valid
1594 */
1595 protected function resolveContainerPath( $container, $relStoragePath ) {
1596 return $relStoragePath;
1597 }
1598
1599 /**
1600 * Get the cache key for a container
1601 *
1602 * @param string $container Resolved container name
1603 * @return string
1604 */
1605 private function containerCacheKey( $container ) {
1606 return "filebackend:{$this->name}:{$this->wikiId}:container:{$container}";
1607 }
1608
1609 /**
1610 * Set the cached info for a container
1611 *
1612 * @param string $container Resolved container name
1613 * @param array $val Information to cache
1614 */
1615 final protected function setContainerCache( $container, array $val ) {
1616 $this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1617 }
1618
1619 /**
1620 * Delete the cached info for a container.
1621 * The cache key is salted for a while to prevent race conditions.
1622 *
1623 * @param string $container Resolved container name
1624 */
1625 final protected function deleteContainerCache( $container ) {
1626 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1627 trigger_error( "Unable to delete stat cache for container $container." );
1628 }
1629 }
1630
1631 /**
1632 * Do a batch lookup from cache for container stats for all containers
1633 * used in a list of container names or storage paths objects.
1634 * This loads the persistent cache values into the process cache.
1635 *
1636 * @param array $items
1637 */
1638 final protected function primeContainerCache( array $items ) {
1639 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1640
1641 $paths = array(); // list of storage paths
1642 $contNames = array(); // (cache key => resolved container name)
1643 // Get all the paths/containers from the items...
1644 foreach ( $items as $item ) {
1645 if ( self::isStoragePath( $item ) ) {
1646 $paths[] = $item;
1647 } elseif ( is_string( $item ) ) { // full container name
1648 $contNames[$this->containerCacheKey( $item )] = $item;
1649 }
1650 }
1651 // Get all the corresponding cache keys for paths...
1652 foreach ( $paths as $path ) {
1653 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1654 if ( $fullCont !== null ) { // valid path for this backend
1655 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1656 }
1657 }
1658
1659 $contInfo = array(); // (resolved container name => cache value)
1660 // Get all cache entries for these container cache keys...
1661 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1662 foreach ( $values as $cacheKey => $val ) {
1663 $contInfo[$contNames[$cacheKey]] = $val;
1664 }
1665
1666 // Populate the container process cache for the backend...
1667 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1668 }
1669
1670 /**
1671 * Fill the backend-specific process cache given an array of
1672 * resolved container names and their corresponding cached info.
1673 * Only containers that actually exist should appear in the map.
1674 *
1675 * @param array $containerInfo Map of resolved container names to cached info
1676 */
1677 protected function doPrimeContainerCache( array $containerInfo ) {
1678 }
1679
1680 /**
1681 * Get the cache key for a file path
1682 *
1683 * @param string $path Normalized storage path
1684 * @return string
1685 */
1686 private function fileCacheKey( $path ) {
1687 return "filebackend:{$this->name}:{$this->wikiId}:file:" . sha1( $path );
1688 }
1689
1690 /**
1691 * Set the cached stat info for a file path.
1692 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1693 * salting for the case when a file is created at a path were there was none before.
1694 *
1695 * @param string $path Storage path
1696 * @param array $val Stat information to cache
1697 */
1698 final protected function setFileCache( $path, array $val ) {
1699 $path = FileBackend::normalizeStoragePath( $path );
1700 if ( $path === null ) {
1701 return; // invalid storage path
1702 }
1703 $age = time() - wfTimestamp( TS_UNIX, $val['mtime'] );
1704 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1705 $key = $this->fileCacheKey( $path );
1706 // Set the cache unless it is currently salted.
1707 $this->memCache->set( $key, $val, $ttl );
1708 }
1709
1710 /**
1711 * Delete the cached stat info for a file path.
1712 * The cache key is salted for a while to prevent race conditions.
1713 * Since negatives (404s) are not cached, this does not need to be called when
1714 * a file is created at a path were there was none before.
1715 *
1716 * @param string $path Storage path
1717 */
1718 final protected function deleteFileCache( $path ) {
1719 $path = FileBackend::normalizeStoragePath( $path );
1720 if ( $path === null ) {
1721 return; // invalid storage path
1722 }
1723 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1724 trigger_error( "Unable to delete stat cache for file $path." );
1725 }
1726 }
1727
1728 /**
1729 * Do a batch lookup from cache for file stats for all paths
1730 * used in a list of storage paths or FileOp objects.
1731 * This loads the persistent cache values into the process cache.
1732 *
1733 * @param array $items List of storage paths
1734 */
1735 final protected function primeFileCache( array $items ) {
1736 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1737
1738 $paths = array(); // list of storage paths
1739 $pathNames = array(); // (cache key => storage path)
1740 // Get all the paths/containers from the items...
1741 foreach ( $items as $item ) {
1742 if ( self::isStoragePath( $item ) ) {
1743 $paths[] = FileBackend::normalizeStoragePath( $item );
1744 }
1745 }
1746 // Get rid of any paths that failed normalization...
1747 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1748 // Get all the corresponding cache keys for paths...
1749 foreach ( $paths as $path ) {
1750 list( , $rel, ) = $this->resolveStoragePath( $path );
1751 if ( $rel !== null ) { // valid path for this backend
1752 $pathNames[$this->fileCacheKey( $path )] = $path;
1753 }
1754 }
1755 // Get all cache entries for these container cache keys...
1756 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1757 foreach ( $values as $cacheKey => $val ) {
1758 $path = $pathNames[$cacheKey];
1759 if ( is_array( $val ) ) {
1760 $val['latest'] = false; // never completely trust cache
1761 $this->cheapCache->set( $path, 'stat', $val );
1762 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1763 $this->cheapCache->set( $path, 'sha1',
1764 array( 'hash' => $val['sha1'], 'latest' => false ) );
1765 }
1766 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1767 $val['xattr'] = self::normalizeXAttributes( $val['xattr'] );
1768 $this->cheapCache->set( $path, 'xattr',
1769 array( 'map' => $val['xattr'], 'latest' => false ) );
1770 }
1771 }
1772 }
1773 }
1774
1775 /**
1776 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1777 *
1778 * @param array $xattr
1779 * @return array
1780 * @since 1.22
1781 */
1782 final protected static function normalizeXAttributes( array $xattr ) {
1783 $newXAttr = array( 'headers' => array(), 'metadata' => array() );
1784
1785 foreach ( $xattr['headers'] as $name => $value ) {
1786 $newXAttr['headers'][strtolower( $name )] = $value;
1787 }
1788
1789 foreach ( $xattr['metadata'] as $name => $value ) {
1790 $newXAttr['metadata'][strtolower( $name )] = $value;
1791 }
1792
1793 return $newXAttr;
1794 }
1795
1796 /**
1797 * Set the 'concurrency' option from a list of operation options
1798 *
1799 * @param array $opts Map of operation options
1800 * @return array
1801 */
1802 final protected function setConcurrencyFlags( array $opts ) {
1803 $opts['concurrency'] = 1; // off
1804 if ( $this->parallelize === 'implicit' ) {
1805 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1806 $opts['concurrency'] = $this->concurrency;
1807 }
1808 } elseif ( $this->parallelize === 'explicit' ) {
1809 if ( !empty( $opts['parallelize'] ) ) {
1810 $opts['concurrency'] = $this->concurrency;
1811 }
1812 }
1813
1814 return $opts;
1815 }
1816
1817 /**
1818 * Get the content type to use in HEAD/GET requests for a file
1819 *
1820 * @param string $storagePath
1821 * @param string|null $content File data
1822 * @param string|null $fsPath File system path
1823 * @return string MIME type
1824 */
1825 protected function getContentType( $storagePath, $content, $fsPath ) {
1826 return call_user_func_array( $this->mimeCallback, func_get_args() );
1827 }
1828 }
1829
1830 /**
1831 * FileBackendStore helper class for performing asynchronous file operations.
1832 *
1833 * For example, calling FileBackendStore::createInternal() with the "async"
1834 * param flag may result in a Status that contains this object as a value.
1835 * This class is largely backend-specific and is mostly just "magic" to be
1836 * passed to FileBackendStore::executeOpHandlesInternal().
1837 */
1838 abstract class FileBackendStoreOpHandle {
1839 /** @var array */
1840 public $params = array(); // params to caller functions
1841 /** @var FileBackendStore */
1842 public $backend;
1843 /** @var array */
1844 public $resourcesToClose = array();
1845
1846 public $call; // string; name that identifies the function called
1847
1848 /**
1849 * Close all open file handles
1850 */
1851 public function closeResources() {
1852 array_map( 'fclose', $this->resourcesToClose );
1853 }
1854 }
1855
1856 /**
1857 * FileBackendStore helper function to handle listings that span container shards.
1858 * Do not use this class from places outside of FileBackendStore.
1859 *
1860 * @ingroup FileBackend
1861 */
1862 abstract class FileBackendStoreShardListIterator extends FilterIterator {
1863 /** @var FileBackendStore */
1864 protected $backend;
1865
1866 /** @var array */
1867 protected $params;
1868
1869 /** @var string Full container name */
1870 protected $container;
1871
1872 /** @var string Resolved relative path */
1873 protected $directory;
1874
1875 /** @var array */
1876 protected $multiShardPaths = array(); // (rel path => 1)
1877
1878 /**
1879 * @param FileBackendStore $backend
1880 * @param string $container Full storage container name
1881 * @param string $dir Storage directory relative to container
1882 * @param array $suffixes List of container shard suffixes
1883 * @param array $params
1884 */
1885 public function __construct(
1886 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1887 ) {
1888 $this->backend = $backend;
1889 $this->container = $container;
1890 $this->directory = $dir;
1891 $this->params = $params;
1892
1893 $iter = new AppendIterator();
1894 foreach ( $suffixes as $suffix ) {
1895 $iter->append( $this->listFromShard( $this->container . $suffix ) );
1896 }
1897
1898 parent::__construct( $iter );
1899 }
1900
1901 public function accept() {
1902 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1903 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1904 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1905 return true; // path is only on one shard; no issue with duplicates
1906 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1907 // Don't keep listing paths that are on multiple shards
1908 return false;
1909 } else {
1910 $this->multiShardPaths[$rel] = 1;
1911
1912 return true;
1913 }
1914 }
1915
1916 public function rewind() {
1917 parent::rewind();
1918 $this->multiShardPaths = array();
1919 }
1920
1921 /**
1922 * Get the list for a given container shard
1923 *
1924 * @param string $container Resolved container name
1925 * @return Iterator
1926 */
1927 abstract protected function listFromShard( $container );
1928 }
1929
1930 /**
1931 * Iterator for listing directories
1932 */
1933 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1934 protected function listFromShard( $container ) {
1935 $list = $this->backend->getDirectoryListInternal(
1936 $container, $this->directory, $this->params );
1937 if ( $list === null ) {
1938 return new ArrayIterator( array() );
1939 } else {
1940 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1941 }
1942 }
1943 }
1944
1945 /**
1946 * Iterator for listing regular files
1947 */
1948 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1949 protected function listFromShard( $container ) {
1950 $list = $this->backend->getFileListInternal(
1951 $container, $this->directory, $this->params );
1952 if ( $list === null ) {
1953 return new ArrayIterator( array() );
1954 } else {
1955 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1956 }
1957 }
1958 }