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