4ec81ecde12a896fed40b51866265a880fe80f1a
[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, 'sanitizeOpHeaders' ), $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, 'sanitizeOpHeaders' ), $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 * Normalize and filter HTTP headers from a file operation
1234 *
1235 * This normalizes and strips long HTTP headers from a file operation.
1236 * Most headers are just numbers, but some are allowed to be long.
1237 * This function is useful for cleaning up headers and avoiding backend
1238 * specific errors, especially in the middle of batch file operations.
1239 *
1240 * @param array $op Same format as doOperation()
1241 * @return array
1242 */
1243 protected function sanitizeOpHeaders( array $op ) {
1244 static $longs = array( 'content-disposition' );
1245
1246 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1247 $newHeaders = array();
1248 foreach ( $op['headers'] as $name => $value ) {
1249 $name = strtolower( $name );
1250 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1251 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1252 trigger_error( "Header '$name: $value' is too long." );
1253 } else {
1254 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1255 }
1256 }
1257 $op['headers'] = $newHeaders;
1258 }
1259
1260 return $op;
1261 }
1262
1263 final public function preloadCache( array $paths ) {
1264 $fullConts = array(); // full container names
1265 foreach ( $paths as $path ) {
1266 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1267 $fullConts[] = $fullCont;
1268 }
1269 // Load from the persistent file and container caches
1270 $this->primeContainerCache( $fullConts );
1271 $this->primeFileCache( $paths );
1272 }
1273
1274 final public function clearCache( array $paths = null ) {
1275 if ( is_array( $paths ) ) {
1276 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1277 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1278 }
1279 if ( $paths === null ) {
1280 $this->cheapCache->clear();
1281 $this->expensiveCache->clear();
1282 } else {
1283 foreach ( $paths as $path ) {
1284 $this->cheapCache->clear( $path );
1285 $this->expensiveCache->clear( $path );
1286 }
1287 }
1288 $this->doClearCache( $paths );
1289 }
1290
1291 /**
1292 * Clears any additional stat caches for storage paths
1293 *
1294 * @see FileBackend::clearCache()
1295 *
1296 * @param array $paths Storage paths (optional)
1297 */
1298 protected function doClearCache( array $paths = null ) {
1299 }
1300
1301 final public function preloadFileStat( array $params ) {
1302 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1303 $success = true; // no network errors
1304
1305 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1306 $stats = $this->doGetFileStatMulti( $params );
1307 if ( $stats === null ) {
1308 return true; // not supported
1309 }
1310
1311 $latest = !empty( $params['latest'] ); // use latest data?
1312 foreach ( $stats as $path => $stat ) {
1313 $path = FileBackend::normalizeStoragePath( $path );
1314 if ( $path === null ) {
1315 continue; // this shouldn't happen
1316 }
1317 if ( is_array( $stat ) ) { // file exists
1318 // Strongly consistent backends can automatically set "latest"
1319 $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest;
1320 $this->cheapCache->set( $path, 'stat', $stat );
1321 $this->setFileCache( $path, $stat ); // update persistent cache
1322 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1323 $this->cheapCache->set( $path, 'sha1',
1324 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
1325 }
1326 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1327 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1328 $this->cheapCache->set( $path, 'xattr',
1329 array( 'map' => $stat['xattr'], 'latest' => $latest ) );
1330 }
1331 } elseif ( $stat === false ) { // file does not exist
1332 $this->cheapCache->set( $path, 'stat',
1333 $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1334 $this->cheapCache->set( $path, 'xattr',
1335 array( 'map' => false, 'latest' => $latest ) );
1336 $this->cheapCache->set( $path, 'sha1',
1337 array( 'hash' => false, 'latest' => $latest ) );
1338 wfDebug( __METHOD__ . ": File $path does not exist.\n" );
1339 } else { // an error occurred
1340 $success = false;
1341 wfDebug( __METHOD__ . ": Could not stat file $path.\n" );
1342 }
1343 }
1344
1345 return $success;
1346 }
1347
1348 /**
1349 * Get file stat information (concurrently if possible) for several files
1350 *
1351 * @see FileBackend::getFileStat()
1352 *
1353 * @param array $params Parameters include:
1354 * - srcs : list of source storage paths
1355 * - latest : use the latest available data
1356 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1357 * @since 1.23
1358 */
1359 protected function doGetFileStatMulti( array $params ) {
1360 return null; // not supported
1361 }
1362
1363 /**
1364 * Is this a key/value store where directories are just virtual?
1365 * Virtual directories exists in so much as files exists that are
1366 * prefixed with the directory path followed by a forward slash.
1367 *
1368 * @return bool
1369 */
1370 abstract protected function directoriesAreVirtual();
1371
1372 /**
1373 * Check if a short container name is valid
1374 *
1375 * This checks for length and illegal characters.
1376 * This may disallow certain characters that can appear
1377 * in the prefix used to make the full container name.
1378 *
1379 * @param string $container
1380 * @return bool
1381 */
1382 final protected static function isValidShortContainerName( $container ) {
1383 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1384 // might be used by subclasses. Reserve the dot character for sanity.
1385 // The only way dots end up in containers (e.g. resolveStoragePath)
1386 // is due to the wikiId container prefix or the above suffixes.
1387 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1388 }
1389
1390 /**
1391 * Check if a full container name is valid
1392 *
1393 * This checks for length and illegal characters.
1394 * Limiting the characters makes migrations to other stores easier.
1395 *
1396 * @param string $container
1397 * @return bool
1398 */
1399 final protected static function isValidContainerName( $container ) {
1400 // This accounts for NTFS, Swift, and Ceph restrictions
1401 // and disallows directory separators or traversal characters.
1402 // Note that matching strings URL encode to the same string;
1403 // in Swift/Ceph, the length restriction is *after* URL encoding.
1404 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1405 }
1406
1407 /**
1408 * Splits a storage path into an internal container name,
1409 * an internal relative file name, and a container shard suffix.
1410 * Any shard suffix is already appended to the internal container name.
1411 * This also checks that the storage path is valid and within this backend.
1412 *
1413 * If the container is sharded but a suffix could not be determined,
1414 * this means that the path can only refer to a directory and can only
1415 * be scanned by looking in all the container shards.
1416 *
1417 * @param string $storagePath
1418 * @return array (container, path, container suffix) or (null, null, null) if invalid
1419 */
1420 final protected function resolveStoragePath( $storagePath ) {
1421 list( $backend, $shortCont, $relPath ) = self::splitStoragePath( $storagePath );
1422 if ( $backend === $this->name ) { // must be for this backend
1423 $relPath = self::normalizeContainerPath( $relPath );
1424 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1425 // Get shard for the normalized path if this container is sharded
1426 $cShard = $this->getContainerShard( $shortCont, $relPath );
1427 // Validate and sanitize the relative path (backend-specific)
1428 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1429 if ( $relPath !== null ) {
1430 // Prepend any wiki ID prefix to the container name
1431 $container = $this->fullContainerName( $shortCont );
1432 if ( self::isValidContainerName( $container ) ) {
1433 // Validate and sanitize the container name (backend-specific)
1434 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1435 if ( $container !== null ) {
1436 return array( $container, $relPath, $cShard );
1437 }
1438 }
1439 }
1440 }
1441 }
1442
1443 return array( null, null, null );
1444 }
1445
1446 /**
1447 * Like resolveStoragePath() except null values are returned if
1448 * the container is sharded and the shard could not be determined
1449 * or if the path ends with '/'. The later case is illegal for FS
1450 * backends and can confuse listings for object store backends.
1451 *
1452 * This function is used when resolving paths that must be valid
1453 * locations for files. Directory and listing functions should
1454 * generally just use resolveStoragePath() instead.
1455 *
1456 * @see FileBackendStore::resolveStoragePath()
1457 *
1458 * @param string $storagePath
1459 * @return array (container, path) or (null, null) if invalid
1460 */
1461 final protected function resolveStoragePathReal( $storagePath ) {
1462 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1463 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1464 return array( $container, $relPath );
1465 }
1466
1467 return array( null, null );
1468 }
1469
1470 /**
1471 * Get the container name shard suffix for a given path.
1472 * Any empty suffix means the container is not sharded.
1473 *
1474 * @param string $container Container name
1475 * @param string $relPath Storage path relative to the container
1476 * @return string|null Returns null if shard could not be determined
1477 */
1478 final protected function getContainerShard( $container, $relPath ) {
1479 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1480 if ( $levels == 1 || $levels == 2 ) {
1481 // Hash characters are either base 16 or 36
1482 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1483 // Get a regex that represents the shard portion of paths.
1484 // The concatenation of the captures gives us the shard.
1485 if ( $levels === 1 ) { // 16 or 36 shards per container
1486 $hashDirRegex = '(' . $char . ')';
1487 } else { // 256 or 1296 shards per container
1488 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1489 $hashDirRegex = $char . '/(' . $char . '{2})';
1490 } else { // short hash dir format (e.g. "a/b/c")
1491 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1492 }
1493 }
1494 // Allow certain directories to be above the hash dirs so as
1495 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1496 // They must be 2+ chars to avoid any hash directory ambiguity.
1497 $m = array();
1498 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1499 return '.' . implode( '', array_slice( $m, 1 ) );
1500 }
1501
1502 return null; // failed to match
1503 }
1504
1505 return ''; // no sharding
1506 }
1507
1508 /**
1509 * Check if a storage path maps to a single shard.
1510 * Container dirs like "a", where the container shards on "x/xy",
1511 * can reside on several shards. Such paths are tricky to handle.
1512 *
1513 * @param string $storagePath Storage path
1514 * @return bool
1515 */
1516 final public function isSingleShardPathInternal( $storagePath ) {
1517 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1518
1519 return ( $shard !== null );
1520 }
1521
1522 /**
1523 * Get the sharding config for a container.
1524 * If greater than 0, then all file storage paths within
1525 * the container are required to be hashed accordingly.
1526 *
1527 * @param string $container
1528 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1529 */
1530 final protected function getContainerHashLevels( $container ) {
1531 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1532 $config = $this->shardViaHashLevels[$container];
1533 $hashLevels = (int)$config['levels'];
1534 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1535 $hashBase = (int)$config['base'];
1536 if ( $hashBase == 16 || $hashBase == 36 ) {
1537 return array( $hashLevels, $hashBase, $config['repeat'] );
1538 }
1539 }
1540 }
1541
1542 return array( 0, 0, false ); // no sharding
1543 }
1544
1545 /**
1546 * Get a list of full container shard suffixes for a container
1547 *
1548 * @param string $container
1549 * @return array
1550 */
1551 final protected function getContainerSuffixes( $container ) {
1552 $shards = array();
1553 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1554 if ( $digits > 0 ) {
1555 $numShards = pow( $base, $digits );
1556 for ( $index = 0; $index < $numShards; $index++ ) {
1557 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1558 }
1559 }
1560
1561 return $shards;
1562 }
1563
1564 /**
1565 * Get the full container name, including the wiki ID prefix
1566 *
1567 * @param string $container
1568 * @return string
1569 */
1570 final protected function fullContainerName( $container ) {
1571 if ( $this->wikiId != '' ) {
1572 return "{$this->wikiId}-$container";
1573 } else {
1574 return $container;
1575 }
1576 }
1577
1578 /**
1579 * Resolve a container name, checking if it's allowed by the backend.
1580 * This is intended for internal use, such as encoding illegal chars.
1581 * Subclasses can override this to be more restrictive.
1582 *
1583 * @param string $container
1584 * @return string|null
1585 */
1586 protected function resolveContainerName( $container ) {
1587 return $container;
1588 }
1589
1590 /**
1591 * Resolve a relative storage path, checking if it's allowed by the backend.
1592 * This is intended for internal use, such as encoding illegal chars or perhaps
1593 * getting absolute paths (e.g. FS based backends). Note that the relative path
1594 * may be the empty string (e.g. the path is simply to the container).
1595 *
1596 * @param string $container Container name
1597 * @param string $relStoragePath Storage path relative to the container
1598 * @return string|null Path or null if not valid
1599 */
1600 protected function resolveContainerPath( $container, $relStoragePath ) {
1601 return $relStoragePath;
1602 }
1603
1604 /**
1605 * Get the cache key for a container
1606 *
1607 * @param string $container Resolved container name
1608 * @return string
1609 */
1610 private function containerCacheKey( $container ) {
1611 return "filebackend:{$this->name}:{$this->wikiId}:container:{$container}";
1612 }
1613
1614 /**
1615 * Set the cached info for a container
1616 *
1617 * @param string $container Resolved container name
1618 * @param array $val Information to cache
1619 */
1620 final protected function setContainerCache( $container, array $val ) {
1621 $this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1622 }
1623
1624 /**
1625 * Delete the cached info for a container.
1626 * The cache key is salted for a while to prevent race conditions.
1627 *
1628 * @param string $container Resolved container name
1629 */
1630 final protected function deleteContainerCache( $container ) {
1631 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1632 trigger_error( "Unable to delete stat cache for container $container." );
1633 }
1634 }
1635
1636 /**
1637 * Do a batch lookup from cache for container stats for all containers
1638 * used in a list of container names or storage paths objects.
1639 * This loads the persistent cache values into the process cache.
1640 *
1641 * @param array $items
1642 */
1643 final protected function primeContainerCache( array $items ) {
1644 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1645
1646 $paths = array(); // list of storage paths
1647 $contNames = array(); // (cache key => resolved container name)
1648 // Get all the paths/containers from the items...
1649 foreach ( $items as $item ) {
1650 if ( self::isStoragePath( $item ) ) {
1651 $paths[] = $item;
1652 } elseif ( is_string( $item ) ) { // full container name
1653 $contNames[$this->containerCacheKey( $item )] = $item;
1654 }
1655 }
1656 // Get all the corresponding cache keys for paths...
1657 foreach ( $paths as $path ) {
1658 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1659 if ( $fullCont !== null ) { // valid path for this backend
1660 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1661 }
1662 }
1663
1664 $contInfo = array(); // (resolved container name => cache value)
1665 // Get all cache entries for these container cache keys...
1666 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1667 foreach ( $values as $cacheKey => $val ) {
1668 $contInfo[$contNames[$cacheKey]] = $val;
1669 }
1670
1671 // Populate the container process cache for the backend...
1672 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1673 }
1674
1675 /**
1676 * Fill the backend-specific process cache given an array of
1677 * resolved container names and their corresponding cached info.
1678 * Only containers that actually exist should appear in the map.
1679 *
1680 * @param array $containerInfo Map of resolved container names to cached info
1681 */
1682 protected function doPrimeContainerCache( array $containerInfo ) {
1683 }
1684
1685 /**
1686 * Get the cache key for a file path
1687 *
1688 * @param string $path Normalized storage path
1689 * @return string
1690 */
1691 private function fileCacheKey( $path ) {
1692 return "filebackend:{$this->name}:{$this->wikiId}:file:" . sha1( $path );
1693 }
1694
1695 /**
1696 * Set the cached stat info for a file path.
1697 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1698 * salting for the case when a file is created at a path were there was none before.
1699 *
1700 * @param string $path Storage path
1701 * @param array $val Stat information to cache
1702 */
1703 final protected function setFileCache( $path, array $val ) {
1704 $path = FileBackend::normalizeStoragePath( $path );
1705 if ( $path === null ) {
1706 return; // invalid storage path
1707 }
1708 $age = time() - wfTimestamp( TS_UNIX, $val['mtime'] );
1709 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1710 $key = $this->fileCacheKey( $path );
1711 // Set the cache unless it is currently salted.
1712 $this->memCache->set( $key, $val, $ttl );
1713 }
1714
1715 /**
1716 * Delete the cached stat info for a file path.
1717 * The cache key is salted for a while to prevent race conditions.
1718 * Since negatives (404s) are not cached, this does not need to be called when
1719 * a file is created at a path were there was none before.
1720 *
1721 * @param string $path Storage path
1722 */
1723 final protected function deleteFileCache( $path ) {
1724 $path = FileBackend::normalizeStoragePath( $path );
1725 if ( $path === null ) {
1726 return; // invalid storage path
1727 }
1728 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1729 trigger_error( "Unable to delete stat cache for file $path." );
1730 }
1731 }
1732
1733 /**
1734 * Do a batch lookup from cache for file stats for all paths
1735 * used in a list of storage paths or FileOp objects.
1736 * This loads the persistent cache values into the process cache.
1737 *
1738 * @param array $items List of storage paths
1739 */
1740 final protected function primeFileCache( array $items ) {
1741 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1742
1743 $paths = array(); // list of storage paths
1744 $pathNames = array(); // (cache key => storage path)
1745 // Get all the paths/containers from the items...
1746 foreach ( $items as $item ) {
1747 if ( self::isStoragePath( $item ) ) {
1748 $paths[] = FileBackend::normalizeStoragePath( $item );
1749 }
1750 }
1751 // Get rid of any paths that failed normalization...
1752 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1753 // Get all the corresponding cache keys for paths...
1754 foreach ( $paths as $path ) {
1755 list( , $rel, ) = $this->resolveStoragePath( $path );
1756 if ( $rel !== null ) { // valid path for this backend
1757 $pathNames[$this->fileCacheKey( $path )] = $path;
1758 }
1759 }
1760 // Get all cache entries for these file cache keys...
1761 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1762 foreach ( $values as $cacheKey => $val ) {
1763 $path = $pathNames[$cacheKey];
1764 if ( is_array( $val ) ) {
1765 $val['latest'] = false; // never completely trust cache
1766 $this->cheapCache->set( $path, 'stat', $val );
1767 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1768 $this->cheapCache->set( $path, 'sha1',
1769 array( 'hash' => $val['sha1'], 'latest' => false ) );
1770 }
1771 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1772 $val['xattr'] = self::normalizeXAttributes( $val['xattr'] );
1773 $this->cheapCache->set( $path, 'xattr',
1774 array( 'map' => $val['xattr'], 'latest' => false ) );
1775 }
1776 }
1777 }
1778 }
1779
1780 /**
1781 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1782 *
1783 * @param array $xattr
1784 * @return array
1785 * @since 1.22
1786 */
1787 final protected static function normalizeXAttributes( array $xattr ) {
1788 $newXAttr = array( 'headers' => array(), 'metadata' => array() );
1789
1790 foreach ( $xattr['headers'] as $name => $value ) {
1791 $newXAttr['headers'][strtolower( $name )] = $value;
1792 }
1793
1794 foreach ( $xattr['metadata'] as $name => $value ) {
1795 $newXAttr['metadata'][strtolower( $name )] = $value;
1796 }
1797
1798 return $newXAttr;
1799 }
1800
1801 /**
1802 * Set the 'concurrency' option from a list of operation options
1803 *
1804 * @param array $opts Map of operation options
1805 * @return array
1806 */
1807 final protected function setConcurrencyFlags( array $opts ) {
1808 $opts['concurrency'] = 1; // off
1809 if ( $this->parallelize === 'implicit' ) {
1810 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1811 $opts['concurrency'] = $this->concurrency;
1812 }
1813 } elseif ( $this->parallelize === 'explicit' ) {
1814 if ( !empty( $opts['parallelize'] ) ) {
1815 $opts['concurrency'] = $this->concurrency;
1816 }
1817 }
1818
1819 return $opts;
1820 }
1821
1822 /**
1823 * Get the content type to use in HEAD/GET requests for a file
1824 *
1825 * @param string $storagePath
1826 * @param string|null $content File data
1827 * @param string|null $fsPath File system path
1828 * @return string MIME type
1829 */
1830 protected function getContentType( $storagePath, $content, $fsPath ) {
1831 return call_user_func_array( $this->mimeCallback, func_get_args() );
1832 }
1833 }
1834
1835 /**
1836 * FileBackendStore helper class for performing asynchronous file operations.
1837 *
1838 * For example, calling FileBackendStore::createInternal() with the "async"
1839 * param flag may result in a Status that contains this object as a value.
1840 * This class is largely backend-specific and is mostly just "magic" to be
1841 * passed to FileBackendStore::executeOpHandlesInternal().
1842 */
1843 abstract class FileBackendStoreOpHandle {
1844 /** @var array */
1845 public $params = array(); // params to caller functions
1846 /** @var FileBackendStore */
1847 public $backend;
1848 /** @var array */
1849 public $resourcesToClose = array();
1850
1851 public $call; // string; name that identifies the function called
1852
1853 /**
1854 * Close all open file handles
1855 */
1856 public function closeResources() {
1857 array_map( 'fclose', $this->resourcesToClose );
1858 }
1859 }
1860
1861 /**
1862 * FileBackendStore helper function to handle listings that span container shards.
1863 * Do not use this class from places outside of FileBackendStore.
1864 *
1865 * @ingroup FileBackend
1866 */
1867 abstract class FileBackendStoreShardListIterator extends FilterIterator {
1868 /** @var FileBackendStore */
1869 protected $backend;
1870
1871 /** @var array */
1872 protected $params;
1873
1874 /** @var string Full container name */
1875 protected $container;
1876
1877 /** @var string Resolved relative path */
1878 protected $directory;
1879
1880 /** @var array */
1881 protected $multiShardPaths = array(); // (rel path => 1)
1882
1883 /**
1884 * @param FileBackendStore $backend
1885 * @param string $container Full storage container name
1886 * @param string $dir Storage directory relative to container
1887 * @param array $suffixes List of container shard suffixes
1888 * @param array $params
1889 */
1890 public function __construct(
1891 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1892 ) {
1893 $this->backend = $backend;
1894 $this->container = $container;
1895 $this->directory = $dir;
1896 $this->params = $params;
1897
1898 $iter = new AppendIterator();
1899 foreach ( $suffixes as $suffix ) {
1900 $iter->append( $this->listFromShard( $this->container . $suffix ) );
1901 }
1902
1903 parent::__construct( $iter );
1904 }
1905
1906 public function accept() {
1907 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1908 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1909 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1910 return true; // path is only on one shard; no issue with duplicates
1911 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1912 // Don't keep listing paths that are on multiple shards
1913 return false;
1914 } else {
1915 $this->multiShardPaths[$rel] = 1;
1916
1917 return true;
1918 }
1919 }
1920
1921 public function rewind() {
1922 parent::rewind();
1923 $this->multiShardPaths = array();
1924 }
1925
1926 /**
1927 * Get the list for a given container shard
1928 *
1929 * @param string $container Resolved container name
1930 * @return Iterator
1931 */
1932 abstract protected function listFromShard( $container );
1933 }
1934
1935 /**
1936 * Iterator for listing directories
1937 */
1938 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1939 protected function listFromShard( $container ) {
1940 $list = $this->backend->getDirectoryListInternal(
1941 $container, $this->directory, $this->params );
1942 if ( $list === null ) {
1943 return new ArrayIterator( array() );
1944 } else {
1945 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1946 }
1947 }
1948 }
1949
1950 /**
1951 * Iterator for listing regular files
1952 */
1953 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1954 protected function listFromShard( $container ) {
1955 $list = $this->backend->getFileListInternal(
1956 $container, $this->directory, $this->params );
1957 if ( $list === null ) {
1958 return new ArrayIterator( array() );
1959 } else {
1960 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1961 }
1962 }
1963 }