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