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