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