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