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