Clean up spacing of doc comments
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2 /**
3 * @defgroup FileRepo File Repository
4 *
5 * @brief This module handles how MediaWiki interacts with filesystems.
6 *
7 * @details
8 */
9
10 use MediaWiki\MediaWikiServices;
11
12 /**
13 * Base code for file repositories.
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License along
26 * with this program; if not, write to the Free Software Foundation, Inc.,
27 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 * http://www.gnu.org/copyleft/gpl.html
29 *
30 * @file
31 * @ingroup FileRepo
32 */
33
34 /**
35 * Base class for file repositories
36 *
37 * @ingroup FileRepo
38 */
39 class FileRepo {
40 const DELETE_SOURCE = 1;
41 const OVERWRITE = 2;
42 const OVERWRITE_SAME = 4;
43 const SKIP_LOCKING = 8;
44
45 const NAME_AND_TIME_ONLY = 1;
46
47 /** @var bool Whether to fetch commons image description pages and display
48 * them on the local wiki
49 */
50 public $fetchDescription;
51
52 /** @var int */
53 public $descriptionCacheExpiry;
54
55 /** @var bool */
56 protected $hasSha1Storage = false;
57
58 /** @var bool */
59 protected $supportsSha1URLs = false;
60
61 /** @var FileBackend */
62 protected $backend;
63
64 /** @var array Map of zones to config */
65 protected $zones = [];
66
67 /** @var string URL of thumb.php */
68 protected $thumbScriptUrl;
69
70 /** @var bool Whether to skip media file transformation on parse and rely
71 * on a 404 handler instead.
72 */
73 protected $transformVia404;
74
75 /** @var string URL of image description pages, e.g.
76 * https://en.wikipedia.org/wiki/File:
77 */
78 protected $descBaseUrl;
79
80 /** @var string URL of the MediaWiki installation, equivalent to
81 * $wgScriptPath, e.g. https://en.wikipedia.org/w
82 */
83 protected $scriptDirUrl;
84
85 /** @var string Equivalent to $wgArticlePath, e.g. https://en.wikipedia.org/wiki/$1 */
86 protected $articleUrl;
87
88 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
89 * determines whether filenames implicitly start with a capital letter.
90 * The current implementation may give incorrect description page links
91 * when the local $wgCapitalLinks and initialCapital are mismatched.
92 */
93 protected $initialCapital;
94
95 /** @var string May be 'paranoid' to remove all parameters from error
96 * messages, 'none' to leave the paths in unchanged, or 'simple' to
97 * replace paths with placeholders. Default for LocalRepo is
98 * 'simple'.
99 */
100 protected $pathDisclosureProtection = 'simple';
101
102 /** @var string|false Public zone URL. */
103 protected $url;
104
105 /** @var string The base thumbnail URL. Defaults to "<url>/thumb". */
106 protected $thumbUrl;
107
108 /** @var int The number of directory levels for hash-based division of files */
109 protected $hashLevels;
110
111 /** @var int The number of directory levels for hash-based division of deleted files */
112 protected $deletedHashLevels;
113
114 /** @var int File names over this size will use the short form of thumbnail
115 * names. Short thumbnail names only have the width, parameters, and the
116 * extension.
117 */
118 protected $abbrvThreshold;
119
120 /** @var string The URL of the repo's favicon, if any */
121 protected $favicon;
122
123 /** @var bool Whether all zones should be private (e.g. private wiki repo) */
124 protected $isPrivate;
125
126 /** @var callable Override these in the base class */
127 protected $fileFactory = [ UnregisteredLocalFile::class, 'newFromTitle' ];
128 /** @var callable|false Override these in the base class */
129 protected $oldFileFactory = false;
130 /** @var callable|false Override these in the base class */
131 protected $fileFactoryKey = false;
132 /** @var callable|false Override these in the base class */
133 protected $oldFileFactoryKey = false;
134
135 /** @var string URL of where to proxy thumb.php requests to.
136 * Example: http://127.0.0.1:8888/wiki/dev/thumb/
137 */
138 protected $thumbProxyUrl;
139 /** @var string Secret key to pass as an X-Swift-Secret header to the proxied thumb service */
140 protected $thumbProxySecret;
141
142 /** @var WANObjectCache */
143 protected $wanCache;
144
145 /**
146 * @param array|null $info
147 * @throws MWException
148 */
149 public function __construct( array $info = null ) {
150 // Verify required settings presence
151 if (
152 $info === null
153 || !array_key_exists( 'name', $info )
154 || !array_key_exists( 'backend', $info )
155 ) {
156 throw new MWException( __CLASS__ .
157 " requires an array of options having both 'name' and 'backend' keys.\n" );
158 }
159
160 // Required settings
161 $this->name = $info['name'];
162 if ( $info['backend'] instanceof FileBackend ) {
163 $this->backend = $info['backend']; // useful for testing
164 } else {
165 $this->backend = FileBackendGroup::singleton()->get( $info['backend'] );
166 }
167
168 // Optional settings that can have no value
169 $optionalSettings = [
170 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
171 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
172 'favicon', 'thumbProxyUrl', 'thumbProxySecret',
173 ];
174 foreach ( $optionalSettings as $var ) {
175 if ( isset( $info[$var] ) ) {
176 $this->$var = $info[$var];
177 }
178 }
179
180 // Optional settings that have a default
181 $this->initialCapital = $info['initialCapital'] ??
182 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE );
183 $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo)
184 if ( isset( $info['thumbUrl'] ) ) {
185 $this->thumbUrl = $info['thumbUrl'];
186 } else {
187 $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
188 }
189 $this->hashLevels = $info['hashLevels'] ?? 2;
190 $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels;
191 $this->transformVia404 = !empty( $info['transformVia404'] );
192 $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255;
193 $this->isPrivate = !empty( $info['isPrivate'] );
194 // Give defaults for the basic zones...
195 $this->zones = $info['zones'] ?? [];
196 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
197 if ( !isset( $this->zones[$zone]['container'] ) ) {
198 $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
199 }
200 if ( !isset( $this->zones[$zone]['directory'] ) ) {
201 $this->zones[$zone]['directory'] = '';
202 }
203 if ( !isset( $this->zones[$zone]['urlsByExt'] ) ) {
204 $this->zones[$zone]['urlsByExt'] = [];
205 }
206 }
207
208 $this->supportsSha1URLs = !empty( $info['supportsSha1URLs'] );
209
210 $this->wanCache = $info['wanCache'] ?? WANObjectCache::newEmpty();
211 }
212
213 /**
214 * Get the file backend instance. Use this function wisely.
215 *
216 * @return FileBackend
217 */
218 public function getBackend() {
219 return $this->backend;
220 }
221
222 /**
223 * Get an explanatory message if this repo is read-only.
224 * This checks if an administrator disabled writes to the backend.
225 *
226 * @return string|bool Returns false if the repo is not read-only
227 */
228 public function getReadOnlyReason() {
229 return $this->backend->getReadOnlyReason();
230 }
231
232 /**
233 * Check if a single zone or list of zones is defined for usage
234 *
235 * @param string[]|string $doZones Only do a particular zones
236 * @throws MWException
237 * @return Status
238 */
239 protected function initZones( $doZones = [] ) {
240 $status = $this->newGood();
241 foreach ( (array)$doZones as $zone ) {
242 $root = $this->getZonePath( $zone );
243 if ( $root === null ) {
244 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
245 }
246 }
247
248 return $status;
249 }
250
251 /**
252 * Determine if a string is an mwrepo:// URL
253 *
254 * @param string $url
255 * @return bool
256 */
257 public static function isVirtualUrl( $url ) {
258 return substr( $url, 0, 9 ) == 'mwrepo://';
259 }
260
261 /**
262 * Get a URL referring to this repository, with the private mwrepo protocol.
263 * The suffix, if supplied, is considered to be unencoded, and will be
264 * URL-encoded before being returned.
265 *
266 * @param string|bool $suffix
267 * @return string
268 */
269 public function getVirtualUrl( $suffix = false ) {
270 $path = 'mwrepo://' . $this->name;
271 if ( $suffix !== false ) {
272 $path .= '/' . rawurlencode( $suffix );
273 }
274
275 return $path;
276 }
277
278 /**
279 * Get the URL corresponding to one of the four basic zones
280 *
281 * @param string $zone One of: public, deleted, temp, thumb
282 * @param string|null $ext Optional file extension
283 * @return string|bool
284 */
285 public function getZoneUrl( $zone, $ext = null ) {
286 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
287 // standard public zones
288 if ( $ext !== null && isset( $this->zones[$zone]['urlsByExt'][$ext] ) ) {
289 // custom URL for extension/zone
290 return $this->zones[$zone]['urlsByExt'][$ext];
291 } elseif ( isset( $this->zones[$zone]['url'] ) ) {
292 // custom URL for zone
293 return $this->zones[$zone]['url'];
294 }
295 }
296 switch ( $zone ) {
297 case 'public':
298 return $this->url;
299 case 'temp':
300 case 'deleted':
301 return false; // no public URL
302 case 'thumb':
303 return $this->thumbUrl;
304 case 'transcoded':
305 return "{$this->url}/transcoded";
306 default:
307 return false;
308 }
309 }
310
311 /**
312 * @return bool Whether non-ASCII path characters are allowed
313 */
314 public function backendSupportsUnicodePaths() {
315 return (bool)( $this->getBackend()->getFeatures() & FileBackend::ATTR_UNICODE_PATHS );
316 }
317
318 /**
319 * Get the backend storage path corresponding to a virtual URL.
320 * Use this function wisely.
321 *
322 * @param string $url
323 * @throws MWException
324 * @return string
325 */
326 public function resolveVirtualUrl( $url ) {
327 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
328 throw new MWException( __METHOD__ . ': unknown protocol' );
329 }
330 $bits = explode( '/', substr( $url, 9 ), 3 );
331 if ( count( $bits ) != 3 ) {
332 throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
333 }
334 list( $repo, $zone, $rel ) = $bits;
335 if ( $repo !== $this->name ) {
336 throw new MWException( __METHOD__ . ": fetching from a foreign repo is not supported" );
337 }
338 $base = $this->getZonePath( $zone );
339 if ( !$base ) {
340 throw new MWException( __METHOD__ . ": invalid zone: $zone" );
341 }
342
343 return $base . '/' . rawurldecode( $rel );
344 }
345
346 /**
347 * The the storage container and base path of a zone
348 *
349 * @param string $zone
350 * @return array (container, base path) or (null, null)
351 */
352 protected function getZoneLocation( $zone ) {
353 if ( !isset( $this->zones[$zone] ) ) {
354 return [ null, null ]; // bogus
355 }
356
357 return [ $this->zones[$zone]['container'], $this->zones[$zone]['directory'] ];
358 }
359
360 /**
361 * Get the storage path corresponding to one of the zones
362 *
363 * @param string $zone
364 * @return string|null Returns null if the zone is not defined
365 */
366 public function getZonePath( $zone ) {
367 list( $container, $base ) = $this->getZoneLocation( $zone );
368 if ( $container === null || $base === null ) {
369 return null;
370 }
371 $backendName = $this->backend->getName();
372 if ( $base != '' ) { // may not be set
373 $base = "/{$base}";
374 }
375
376 return "mwstore://$backendName/{$container}{$base}";
377 }
378
379 /**
380 * Create a new File object from the local repository
381 *
382 * @param Title|string $title Title object or string
383 * @param bool|string $time Time at which the image was uploaded. If this
384 * is specified, the returned object will be an instance of the
385 * repository's old file class instead of a current file. Repositories
386 * not supporting version control should return false if this parameter
387 * is set.
388 * @return File|null A File, or null if passed an invalid Title
389 */
390 public function newFile( $title, $time = false ) {
391 $title = File::normalizeTitle( $title );
392 if ( !$title ) {
393 return null;
394 }
395 if ( $time ) {
396 if ( $this->oldFileFactory ) {
397 return call_user_func( $this->oldFileFactory, $title, $this, $time );
398 } else {
399 return null;
400 }
401 } else {
402 return call_user_func( $this->fileFactory, $title, $this );
403 }
404 }
405
406 /**
407 * Find an instance of the named file created at the specified time
408 * Returns false if the file does not exist. Repositories not supporting
409 * version control should return false if the time is specified.
410 *
411 * @param Title|string $title Title object or string
412 * @param array $options Associative array of options:
413 * time: requested time for a specific file version, or false for the
414 * current version. An image object will be returned which was
415 * created at the specified time (which may be archived or current).
416 * ignoreRedirect: If true, do not follow file redirects
417 * private: If true, return restricted (deleted) files if the current
418 * user is allowed to view them. Otherwise, such files will not
419 * be found. If a User object, use that user instead of the current.
420 * latest: If true, load from the latest available data into File objects
421 * @return File|bool False on failure
422 */
423 public function findFile( $title, $options = [] ) {
424 $title = File::normalizeTitle( $title );
425 if ( !$title ) {
426 return false;
427 }
428 if ( isset( $options['bypassCache'] ) ) {
429 $options['latest'] = $options['bypassCache']; // b/c
430 }
431 $time = $options['time'] ?? false;
432 $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0;
433 # First try the current version of the file to see if it precedes the timestamp
434 $img = $this->newFile( $title );
435 if ( !$img ) {
436 return false;
437 }
438 $img->load( $flags );
439 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
440 return $img;
441 }
442 # Now try an old version of the file
443 if ( $time !== false ) {
444 $img = $this->newFile( $title, $time );
445 if ( $img ) {
446 $img->load( $flags );
447 if ( $img->exists() ) {
448 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
449 return $img; // always OK
450 } elseif ( !empty( $options['private'] ) &&
451 $img->userCan( File::DELETED_FILE,
452 $options['private'] instanceof User ? $options['private'] : null
453 )
454 ) {
455 return $img;
456 }
457 }
458 }
459 }
460
461 # Now try redirects
462 if ( !empty( $options['ignoreRedirect'] ) ) {
463 return false;
464 }
465 $redir = $this->checkRedirect( $title );
466 if ( $redir && $title->getNamespace() == NS_FILE ) {
467 $img = $this->newFile( $redir );
468 if ( !$img ) {
469 return false;
470 }
471 $img->load( $flags );
472 if ( $img->exists() ) {
473 $img->redirectedFrom( $title->getDBkey() );
474
475 return $img;
476 }
477 }
478
479 return false;
480 }
481
482 /**
483 * Find many files at once.
484 *
485 * @param array $items An array of titles, or an array of findFile() options with
486 * the "title" option giving the title. Example:
487 *
488 * $findItem = [ 'title' => $title, 'private' => true ];
489 * $findBatch = [ $findItem ];
490 * $repo->findFiles( $findBatch );
491 *
492 * No title should appear in $items twice, as the result use titles as keys
493 * @param int $flags Supports:
494 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
495 * The search title uses the input titles; the other is the final post-redirect title.
496 * All titles are returned as string DB keys and the inner array is associative.
497 * @return array Map of (file name => File objects) for matches
498 */
499 public function findFiles( array $items, $flags = 0 ) {
500 $result = [];
501 foreach ( $items as $item ) {
502 if ( is_array( $item ) ) {
503 $title = $item['title'];
504 $options = $item;
505 unset( $options['title'] );
506 } else {
507 $title = $item;
508 $options = [];
509 }
510 $file = $this->findFile( $title, $options );
511 if ( $file ) {
512 $searchName = File::normalizeTitle( $title )->getDBkey(); // must be valid
513 if ( $flags & self::NAME_AND_TIME_ONLY ) {
514 $result[$searchName] = [
515 'title' => $file->getTitle()->getDBkey(),
516 'timestamp' => $file->getTimestamp()
517 ];
518 } else {
519 $result[$searchName] = $file;
520 }
521 }
522 }
523
524 return $result;
525 }
526
527 /**
528 * Find an instance of the file with this key, created at the specified time
529 * Returns false if the file does not exist. Repositories not supporting
530 * version control should return false if the time is specified.
531 *
532 * @param string $sha1 Base 36 SHA-1 hash
533 * @param array $options Option array, same as findFile().
534 * @return File|bool False on failure
535 */
536 public function findFileFromKey( $sha1, $options = [] ) {
537 $time = $options['time'] ?? false;
538 # First try to find a matching current version of a file...
539 if ( !$this->fileFactoryKey ) {
540 return false; // find-by-sha1 not supported
541 }
542 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
543 if ( $img && $img->exists() ) {
544 return $img;
545 }
546 # Now try to find a matching old version of a file...
547 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
548 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
549 if ( $img && $img->exists() ) {
550 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
551 return $img; // always OK
552 } elseif ( !empty( $options['private'] ) &&
553 $img->userCan( File::DELETED_FILE,
554 $options['private'] instanceof User ? $options['private'] : null
555 )
556 ) {
557 return $img;
558 }
559 }
560 }
561
562 return false;
563 }
564
565 /**
566 * Get an array or iterator of file objects for files that have a given
567 * SHA-1 content hash.
568 *
569 * STUB
570 * @param string $hash SHA-1 hash
571 * @return File[]
572 */
573 public function findBySha1( $hash ) {
574 return [];
575 }
576
577 /**
578 * Get an array of arrays or iterators of file objects for files that
579 * have the given SHA-1 content hashes.
580 *
581 * @param string[] $hashes An array of hashes
582 * @return array[] An Array of arrays or iterators of file objects and the hash as key
583 */
584 public function findBySha1s( array $hashes ) {
585 $result = [];
586 foreach ( $hashes as $hash ) {
587 $files = $this->findBySha1( $hash );
588 if ( count( $files ) ) {
589 $result[$hash] = $files;
590 }
591 }
592
593 return $result;
594 }
595
596 /**
597 * Return an array of files where the name starts with $prefix.
598 *
599 * STUB
600 * @param string $prefix The prefix to search for
601 * @param int $limit The maximum amount of files to return
602 * @return LocalFile[]
603 */
604 public function findFilesByPrefix( $prefix, $limit ) {
605 return [];
606 }
607
608 /**
609 * Get the URL of thumb.php
610 *
611 * @return string
612 */
613 public function getThumbScriptUrl() {
614 return $this->thumbScriptUrl;
615 }
616
617 /**
618 * Get the URL thumb.php requests are being proxied to
619 *
620 * @return string
621 */
622 public function getThumbProxyUrl() {
623 return $this->thumbProxyUrl;
624 }
625
626 /**
627 * Get the secret key for the proxied thumb service
628 *
629 * @return string
630 */
631 public function getThumbProxySecret() {
632 return $this->thumbProxySecret;
633 }
634
635 /**
636 * Returns true if the repository can transform files via a 404 handler
637 *
638 * @return bool
639 */
640 public function canTransformVia404() {
641 return $this->transformVia404;
642 }
643
644 /**
645 * Get the name of a file from its title object
646 *
647 * @param Title $title
648 * @return string
649 */
650 public function getNameFromTitle( Title $title ) {
651 if (
652 $this->initialCapital !=
653 MediaWikiServices::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE )
654 ) {
655 $name = $title->getUserCaseDBKey();
656 if ( $this->initialCapital ) {
657 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
658 }
659 } else {
660 $name = $title->getDBkey();
661 }
662
663 return $name;
664 }
665
666 /**
667 * Get the public zone root storage directory of the repository
668 *
669 * @return string
670 */
671 public function getRootDirectory() {
672 return $this->getZonePath( 'public' );
673 }
674
675 /**
676 * Get a relative path including trailing slash, e.g. f/fa/
677 * If the repo is not hashed, returns an empty string
678 *
679 * @param string $name Name of file
680 * @return string
681 */
682 public function getHashPath( $name ) {
683 return self::getHashPathForLevel( $name, $this->hashLevels );
684 }
685
686 /**
687 * Get a relative path including trailing slash, e.g. f/fa/
688 * If the repo is not hashed, returns an empty string
689 *
690 * @param string $suffix Basename of file from FileRepo::storeTemp()
691 * @return string
692 */
693 public function getTempHashPath( $suffix ) {
694 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
695 $name = $parts[1] ?? $suffix; // hash path is not based on timestamp
696 return self::getHashPathForLevel( $name, $this->hashLevels );
697 }
698
699 /**
700 * @param string $name
701 * @param int $levels
702 * @return string
703 */
704 protected static function getHashPathForLevel( $name, $levels ) {
705 if ( $levels == 0 ) {
706 return '';
707 } else {
708 $hash = md5( $name );
709 $path = '';
710 for ( $i = 1; $i <= $levels; $i++ ) {
711 $path .= substr( $hash, 0, $i ) . '/';
712 }
713
714 return $path;
715 }
716 }
717
718 /**
719 * Get the number of hash directory levels
720 *
721 * @return int
722 */
723 public function getHashLevels() {
724 return $this->hashLevels;
725 }
726
727 /**
728 * Get the name of this repository, as specified by $info['name]' to the constructor
729 *
730 * @return string
731 */
732 public function getName() {
733 return $this->name;
734 }
735
736 /**
737 * Make an url to this repo
738 *
739 * @param string|string[] $query Query string to append
740 * @param string $entry Entry point; defaults to index
741 * @return string|bool False on failure
742 */
743 public function makeUrl( $query = '', $entry = 'index' ) {
744 if ( isset( $this->scriptDirUrl ) ) {
745 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
746 }
747
748 return false;
749 }
750
751 /**
752 * Get the URL of an image description page. May return false if it is
753 * unknown or not applicable. In general this should only be called by the
754 * File class, since it may return invalid results for certain kinds of
755 * repositories. Use File::getDescriptionUrl() in user code.
756 *
757 * In particular, it uses the article paths as specified to the repository
758 * constructor, whereas local repositories use the local Title functions.
759 *
760 * @param string $name
761 * @return string|false
762 */
763 public function getDescriptionUrl( $name ) {
764 $encName = wfUrlencode( $name );
765 if ( !is_null( $this->descBaseUrl ) ) {
766 # "http://example.com/wiki/File:"
767 return $this->descBaseUrl . $encName;
768 }
769 if ( !is_null( $this->articleUrl ) ) {
770 # "http://example.com/wiki/$1"
771 # We use "Image:" as the canonical namespace for
772 # compatibility across all MediaWiki versions.
773 return str_replace( '$1',
774 "Image:$encName", $this->articleUrl );
775 }
776 if ( !is_null( $this->scriptDirUrl ) ) {
777 # "http://example.com/w"
778 # We use "Image:" as the canonical namespace for
779 # compatibility across all MediaWiki versions,
780 # and just sort of hope index.php is right. ;)
781 return $this->makeUrl( "title=Image:$encName" );
782 }
783
784 return false;
785 }
786
787 /**
788 * Get the URL of the content-only fragment of the description page. For
789 * MediaWiki this means action=render. This should only be called by the
790 * repository's file class, since it may return invalid results. User code
791 * should use File::getDescriptionText().
792 *
793 * @param string $name Name of image to fetch
794 * @param string|null $lang Language to fetch it in, if any.
795 * @return string|false
796 */
797 public function getDescriptionRenderUrl( $name, $lang = null ) {
798 $query = 'action=render';
799 if ( !is_null( $lang ) ) {
800 $query .= '&uselang=' . urlencode( $lang );
801 }
802 if ( isset( $this->scriptDirUrl ) ) {
803 return $this->makeUrl(
804 'title=' .
805 wfUrlencode( 'Image:' . $name ) .
806 "&$query" );
807 } else {
808 $descUrl = $this->getDescriptionUrl( $name );
809 if ( $descUrl ) {
810 return wfAppendQuery( $descUrl, $query );
811 } else {
812 return false;
813 }
814 }
815 }
816
817 /**
818 * Get the URL of the stylesheet to apply to description pages
819 *
820 * @return string|bool False on failure
821 */
822 public function getDescriptionStylesheetUrl() {
823 if ( isset( $this->scriptDirUrl ) ) {
824 // Must match canonical query parameter order for optimum caching
825 // See Title::getCdnUrls
826 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
827 }
828
829 return false;
830 }
831
832 /**
833 * Store a file to a given destination.
834 *
835 * @param string $srcPath Source file system path, storage path, or virtual URL
836 * @param string $dstZone Destination zone
837 * @param string $dstRel Destination relative path
838 * @param int $flags Bitwise combination of the following flags:
839 * self::OVERWRITE Overwrite an existing destination file instead of failing
840 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
841 * same contents as the source
842 * self::SKIP_LOCKING Skip any file locking when doing the store
843 * @return Status
844 */
845 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
846 $this->assertWritableRepo(); // fail out if read-only
847
848 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
849 if ( $status->successCount == 0 ) {
850 $status->setOK( false );
851 }
852
853 return $status;
854 }
855
856 /**
857 * Store a batch of files
858 *
859 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
860 * @param int $flags Bitwise combination of the following flags:
861 * self::OVERWRITE Overwrite an existing destination file instead of failing
862 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
863 * same contents as the source
864 * self::SKIP_LOCKING Skip any file locking when doing the store
865 * @throws MWException
866 * @return Status
867 */
868 public function storeBatch( array $triplets, $flags = 0 ) {
869 $this->assertWritableRepo(); // fail out if read-only
870
871 if ( $flags & self::DELETE_SOURCE ) {
872 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__ );
873 }
874
875 $status = $this->newGood();
876 $backend = $this->backend; // convenience
877
878 $operations = [];
879 // Validate each triplet and get the store operation...
880 foreach ( $triplets as $triplet ) {
881 list( $srcPath, $dstZone, $dstRel ) = $triplet;
882 wfDebug( __METHOD__
883 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
884 );
885
886 // Resolve destination path
887 $root = $this->getZonePath( $dstZone );
888 if ( !$root ) {
889 throw new MWException( "Invalid zone: $dstZone" );
890 }
891 if ( !$this->validateFilename( $dstRel ) ) {
892 throw new MWException( 'Validation error in $dstRel' );
893 }
894 $dstPath = "$root/$dstRel";
895 $dstDir = dirname( $dstPath );
896 // Create destination directories for this triplet
897 if ( !$this->initDirectory( $dstDir )->isOK() ) {
898 return $this->newFatal( 'directorycreateerror', $dstDir );
899 }
900
901 // Resolve source to a storage path if virtual
902 $srcPath = $this->resolveToStoragePath( $srcPath );
903
904 // Get the appropriate file operation
905 if ( FileBackend::isStoragePath( $srcPath ) ) {
906 $opName = 'copy';
907 } else {
908 $opName = 'store';
909 }
910 $operations[] = [
911 'op' => $opName,
912 'src' => $srcPath,
913 'dst' => $dstPath,
914 'overwrite' => $flags & self::OVERWRITE,
915 'overwriteSame' => $flags & self::OVERWRITE_SAME,
916 ];
917 }
918
919 // Execute the store operation for each triplet
920 $opts = [ 'force' => true ];
921 if ( $flags & self::SKIP_LOCKING ) {
922 $opts['nonLocking'] = true;
923 }
924 $status->merge( $backend->doOperations( $operations, $opts ) );
925
926 return $status;
927 }
928
929 /**
930 * Deletes a batch of files.
931 * Each file can be a (zone, rel) pair, virtual url, storage path.
932 * It will try to delete each file, but ignores any errors that may occur.
933 *
934 * @param string[] $files List of files to delete
935 * @param int $flags Bitwise combination of the following flags:
936 * self::SKIP_LOCKING Skip any file locking when doing the deletions
937 * @return Status
938 */
939 public function cleanupBatch( array $files, $flags = 0 ) {
940 $this->assertWritableRepo(); // fail out if read-only
941
942 $status = $this->newGood();
943
944 $operations = [];
945 foreach ( $files as $path ) {
946 if ( is_array( $path ) ) {
947 // This is a pair, extract it
948 list( $zone, $rel ) = $path;
949 $path = $this->getZonePath( $zone ) . "/$rel";
950 } else {
951 // Resolve source to a storage path if virtual
952 $path = $this->resolveToStoragePath( $path );
953 }
954 $operations[] = [ 'op' => 'delete', 'src' => $path ];
955 }
956 // Actually delete files from storage...
957 $opts = [ 'force' => true ];
958 if ( $flags & self::SKIP_LOCKING ) {
959 $opts['nonLocking'] = true;
960 }
961 $status->merge( $this->backend->doOperations( $operations, $opts ) );
962
963 return $status;
964 }
965
966 /**
967 * Import a file from the local file system into the repo.
968 * This does no locking nor journaling and overrides existing files.
969 * This function can be used to write to otherwise read-only foreign repos.
970 * This is intended for copying generated thumbnails into the repo.
971 *
972 * @param string|FSFile $src Source file system path, storage path, or virtual URL
973 * @param string $dst Virtual URL or storage path
974 * @param array|string|null $options An array consisting of a key named headers
975 * listing extra headers. If a string, taken as content-disposition header.
976 * (Support for array of options new in 1.23)
977 * @return Status
978 */
979 final public function quickImport( $src, $dst, $options = null ) {
980 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
981 }
982
983 /**
984 * Purge a file from the repo. This does no locking nor journaling.
985 * This function can be used to write to otherwise read-only foreign repos.
986 * This is intended for purging thumbnails.
987 *
988 * @param string $path Virtual URL or storage path
989 * @return Status
990 */
991 final public function quickPurge( $path ) {
992 return $this->quickPurgeBatch( [ $path ] );
993 }
994
995 /**
996 * Deletes a directory if empty.
997 * This function can be used to write to otherwise read-only foreign repos.
998 *
999 * @param string $dir Virtual URL (or storage path) of directory to clean
1000 * @return Status
1001 */
1002 public function quickCleanDir( $dir ) {
1003 $status = $this->newGood();
1004 $status->merge( $this->backend->clean(
1005 [ 'dir' => $this->resolveToStoragePath( $dir ) ] ) );
1006
1007 return $status;
1008 }
1009
1010 /**
1011 * Import a batch of files from the local file system into the repo.
1012 * This does no locking nor journaling and overrides existing files.
1013 * This function can be used to write to otherwise read-only foreign repos.
1014 * This is intended for copying generated thumbnails into the repo.
1015 *
1016 * All path parameters may be a file system path, storage path, or virtual URL.
1017 * When "headers" are given they are used as HTTP headers if supported.
1018 *
1019 * @param array $triples List of (source path or FSFile, destination path, disposition)
1020 * @return Status
1021 */
1022 public function quickImportBatch( array $triples ) {
1023 $status = $this->newGood();
1024 $operations = [];
1025 foreach ( $triples as $triple ) {
1026 list( $src, $dst ) = $triple;
1027 if ( $src instanceof FSFile ) {
1028 $op = 'store';
1029 } else {
1030 $src = $this->resolveToStoragePath( $src );
1031 $op = FileBackend::isStoragePath( $src ) ? 'copy' : 'store';
1032 }
1033 $dst = $this->resolveToStoragePath( $dst );
1034
1035 if ( !isset( $triple[2] ) ) {
1036 $headers = [];
1037 } elseif ( is_string( $triple[2] ) ) {
1038 // back-compat
1039 $headers = [ 'Content-Disposition' => $triple[2] ];
1040 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1041 $headers = $triple[2]['headers'];
1042 } else {
1043 $headers = [];
1044 }
1045
1046 $operations[] = [
1047 'op' => $op,
1048 'src' => $src,
1049 'dst' => $dst,
1050 'headers' => $headers
1051 ];
1052 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1053 }
1054 $status->merge( $this->backend->doQuickOperations( $operations ) );
1055
1056 return $status;
1057 }
1058
1059 /**
1060 * Purge a batch of files from the repo.
1061 * This function can be used to write to otherwise read-only foreign repos.
1062 * This does no locking nor journaling and is intended for purging thumbnails.
1063 *
1064 * @param array $paths List of virtual URLs or storage paths
1065 * @return Status
1066 */
1067 public function quickPurgeBatch( array $paths ) {
1068 $status = $this->newGood();
1069 $operations = [];
1070 foreach ( $paths as $path ) {
1071 $operations[] = [
1072 'op' => 'delete',
1073 'src' => $this->resolveToStoragePath( $path ),
1074 'ignoreMissingSource' => true
1075 ];
1076 }
1077 $status->merge( $this->backend->doQuickOperations( $operations ) );
1078
1079 return $status;
1080 }
1081
1082 /**
1083 * Pick a random name in the temp zone and store a file to it.
1084 * Returns a Status object with the file Virtual URL in the value,
1085 * file can later be disposed using FileRepo::freeTemp().
1086 *
1087 * @param string $originalName The base name of the file as specified
1088 * by the user. The file extension will be maintained.
1089 * @param string $srcPath The current location of the file.
1090 * @return Status Object with the URL in the value.
1091 */
1092 public function storeTemp( $originalName, $srcPath ) {
1093 $this->assertWritableRepo(); // fail out if read-only
1094
1095 $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1096 $hashPath = $this->getHashPath( $originalName );
1097 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1098 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1099
1100 $result = $this->quickImport( $srcPath, $virtualUrl );
1101 $result->value = $virtualUrl;
1102
1103 return $result;
1104 }
1105
1106 /**
1107 * Remove a temporary file or mark it for garbage collection
1108 *
1109 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1110 * @return bool True on success, false on failure
1111 */
1112 public function freeTemp( $virtualUrl ) {
1113 $this->assertWritableRepo(); // fail out if read-only
1114
1115 $temp = $this->getVirtualUrl( 'temp' );
1116 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1117 wfDebug( __METHOD__ . ": Invalid temp virtual URL\n" );
1118
1119 return false;
1120 }
1121
1122 return $this->quickPurge( $virtualUrl )->isOK();
1123 }
1124
1125 /**
1126 * Concatenate a list of temporary files into a target file location.
1127 *
1128 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1129 * @param string $dstPath Target file system path
1130 * @param int $flags Bitwise combination of the following flags:
1131 * self::DELETE_SOURCE Delete the source files on success
1132 * @return Status
1133 */
1134 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1135 $this->assertWritableRepo(); // fail out if read-only
1136
1137 $status = $this->newGood();
1138
1139 $sources = [];
1140 foreach ( $srcPaths as $srcPath ) {
1141 // Resolve source to a storage path if virtual
1142 $source = $this->resolveToStoragePath( $srcPath );
1143 $sources[] = $source; // chunk to merge
1144 }
1145
1146 // Concatenate the chunks into one FS file
1147 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1148 $status->merge( $this->backend->concatenate( $params ) );
1149 if ( !$status->isOK() ) {
1150 return $status;
1151 }
1152
1153 // Delete the sources if required
1154 if ( $flags & self::DELETE_SOURCE ) {
1155 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1156 }
1157
1158 // Make sure status is OK, despite any quickPurgeBatch() fatals
1159 $status->setResult( true );
1160
1161 return $status;
1162 }
1163
1164 /**
1165 * Copy or move a file either from a storage path, virtual URL,
1166 * or file system path, into this repository at the specified destination location.
1167 *
1168 * Returns a Status object. On success, the value contains "new" or
1169 * "archived", to indicate whether the file was new with that name.
1170 *
1171 * Options to $options include:
1172 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1173 *
1174 * @param string|FSFile $src The source file system path, storage path, or URL
1175 * @param string $dstRel The destination relative path
1176 * @param string $archiveRel The relative path where the existing file is to
1177 * be archived, if there is one. Relative to the public zone root.
1178 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1179 * that the source file should be deleted if possible
1180 * @param array $options Optional additional parameters
1181 * @return Status
1182 */
1183 public function publish(
1184 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1185 ) {
1186 $this->assertWritableRepo(); // fail out if read-only
1187
1188 $status = $this->publishBatch(
1189 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1190 if ( $status->successCount == 0 ) {
1191 $status->setOK( false );
1192 }
1193 $status->value = $status->value[0] ?? false;
1194
1195 return $status;
1196 }
1197
1198 /**
1199 * Publish a batch of files
1200 *
1201 * @param array $ntuples (source, dest, archive) triplets or
1202 * (source, dest, archive, options) 4-tuples as per publish().
1203 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1204 * that the source files should be deleted if possible
1205 * @throws MWException
1206 * @return Status
1207 */
1208 public function publishBatch( array $ntuples, $flags = 0 ) {
1209 $this->assertWritableRepo(); // fail out if read-only
1210
1211 $backend = $this->backend; // convenience
1212 // Try creating directories
1213 $status = $this->initZones( 'public' );
1214 if ( !$status->isOK() ) {
1215 return $status;
1216 }
1217
1218 $status = $this->newGood( [] );
1219
1220 $operations = [];
1221 $sourceFSFilesToDelete = []; // cleanup for disk source files
1222 // Validate each triplet and get the store operation...
1223 foreach ( $ntuples as $ntuple ) {
1224 list( $src, $dstRel, $archiveRel ) = $ntuple;
1225 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1226
1227 $options = $ntuple[3] ?? [];
1228 // Resolve source to a storage path if virtual
1229 $srcPath = $this->resolveToStoragePath( $srcPath );
1230 if ( !$this->validateFilename( $dstRel ) ) {
1231 throw new MWException( 'Validation error in $dstRel' );
1232 }
1233 if ( !$this->validateFilename( $archiveRel ) ) {
1234 throw new MWException( 'Validation error in $archiveRel' );
1235 }
1236
1237 $publicRoot = $this->getZonePath( 'public' );
1238 $dstPath = "$publicRoot/$dstRel";
1239 $archivePath = "$publicRoot/$archiveRel";
1240
1241 $dstDir = dirname( $dstPath );
1242 $archiveDir = dirname( $archivePath );
1243 // Abort immediately on directory creation errors since they're likely to be repetitive
1244 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1245 return $this->newFatal( 'directorycreateerror', $dstDir );
1246 }
1247 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1248 return $this->newFatal( 'directorycreateerror', $archiveDir );
1249 }
1250
1251 // Set any desired headers to be use in GET/HEAD responses
1252 $headers = $options['headers'] ?? [];
1253
1254 // Archive destination file if it exists.
1255 // This will check if the archive file also exists and fail if does.
1256 // This is a sanity check to avoid data loss. On Windows and Linux,
1257 // copy() will overwrite, so the existence check is vulnerable to
1258 // race conditions unless a functioning LockManager is used.
1259 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1260 $operations[] = [
1261 'op' => 'copy',
1262 'src' => $dstPath,
1263 'dst' => $archivePath,
1264 'ignoreMissingSource' => true
1265 ];
1266
1267 // Copy (or move) the source file to the destination
1268 if ( FileBackend::isStoragePath( $srcPath ) ) {
1269 if ( $flags & self::DELETE_SOURCE ) {
1270 $operations[] = [
1271 'op' => 'move',
1272 'src' => $srcPath,
1273 'dst' => $dstPath,
1274 'overwrite' => true, // replace current
1275 'headers' => $headers
1276 ];
1277 } else {
1278 $operations[] = [
1279 'op' => 'copy',
1280 'src' => $srcPath,
1281 'dst' => $dstPath,
1282 'overwrite' => true, // replace current
1283 'headers' => $headers
1284 ];
1285 }
1286 } else { // FS source path
1287 $operations[] = [
1288 'op' => 'store',
1289 'src' => $src, // prefer FSFile objects
1290 'dst' => $dstPath,
1291 'overwrite' => true, // replace current
1292 'headers' => $headers
1293 ];
1294 if ( $flags & self::DELETE_SOURCE ) {
1295 $sourceFSFilesToDelete[] = $srcPath;
1296 }
1297 }
1298 }
1299
1300 // Execute the operations for each triplet
1301 $status->merge( $backend->doOperations( $operations ) );
1302 // Find out which files were archived...
1303 foreach ( $ntuples as $i => $ntuple ) {
1304 list( , , $archiveRel ) = $ntuple;
1305 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1306 if ( $this->fileExists( $archivePath ) ) {
1307 $status->value[$i] = 'archived';
1308 } else {
1309 $status->value[$i] = 'new';
1310 }
1311 }
1312 // Cleanup for disk source files...
1313 foreach ( $sourceFSFilesToDelete as $file ) {
1314 Wikimedia\suppressWarnings();
1315 unlink( $file ); // FS cleanup
1316 Wikimedia\restoreWarnings();
1317 }
1318
1319 return $status;
1320 }
1321
1322 /**
1323 * Creates a directory with the appropriate zone permissions.
1324 * Callers are responsible for doing read-only and "writable repo" checks.
1325 *
1326 * @param string $dir Virtual URL (or storage path) of directory to clean
1327 * @return Status
1328 */
1329 protected function initDirectory( $dir ) {
1330 $path = $this->resolveToStoragePath( $dir );
1331 list( , $container, ) = FileBackend::splitStoragePath( $path );
1332
1333 $params = [ 'dir' => $path ];
1334 if ( $this->isPrivate
1335 || $container === $this->zones['deleted']['container']
1336 || $container === $this->zones['temp']['container']
1337 ) {
1338 # Take all available measures to prevent web accessibility of new deleted
1339 # directories, in case the user has not configured offline storage
1340 $params = [ 'noAccess' => true, 'noListing' => true ] + $params;
1341 }
1342
1343 $status = $this->newGood();
1344 $status->merge( $this->backend->prepare( $params ) );
1345
1346 return $status;
1347 }
1348
1349 /**
1350 * Deletes a directory if empty.
1351 *
1352 * @param string $dir Virtual URL (or storage path) of directory to clean
1353 * @return Status
1354 */
1355 public function cleanDir( $dir ) {
1356 $this->assertWritableRepo(); // fail out if read-only
1357
1358 $status = $this->newGood();
1359 $status->merge( $this->backend->clean(
1360 [ 'dir' => $this->resolveToStoragePath( $dir ) ] ) );
1361
1362 return $status;
1363 }
1364
1365 /**
1366 * Checks existence of a file
1367 *
1368 * @param string $file Virtual URL (or storage path) of file to check
1369 * @return bool
1370 */
1371 public function fileExists( $file ) {
1372 $result = $this->fileExistsBatch( [ $file ] );
1373
1374 return $result[0];
1375 }
1376
1377 /**
1378 * Checks existence of an array of files.
1379 *
1380 * @param string[] $files Virtual URLs (or storage paths) of files to check
1381 * @return array Map of files and existence flags, or false
1382 */
1383 public function fileExistsBatch( array $files ) {
1384 $paths = array_map( [ $this, 'resolveToStoragePath' ], $files );
1385 $this->backend->preloadFileStat( [ 'srcs' => $paths ] );
1386
1387 $result = [];
1388 foreach ( $files as $key => $file ) {
1389 $path = $this->resolveToStoragePath( $file );
1390 $result[$key] = $this->backend->fileExists( [ 'src' => $path ] );
1391 }
1392
1393 return $result;
1394 }
1395
1396 /**
1397 * Move a file to the deletion archive.
1398 * If no valid deletion archive exists, this may either delete the file
1399 * or throw an exception, depending on the preference of the repository
1400 *
1401 * @param mixed $srcRel Relative path for the file to be deleted
1402 * @param mixed $archiveRel Relative path for the archive location.
1403 * Relative to a private archive directory.
1404 * @return Status
1405 */
1406 public function delete( $srcRel, $archiveRel ) {
1407 $this->assertWritableRepo(); // fail out if read-only
1408
1409 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1410 }
1411
1412 /**
1413 * Move a group of files to the deletion archive.
1414 *
1415 * If no valid deletion archive is configured, this may either delete the
1416 * file or throw an exception, depending on the preference of the repository.
1417 *
1418 * The overwrite policy is determined by the repository -- currently LocalRepo
1419 * assumes a naming scheme in the deleted zone based on content hash, as
1420 * opposed to the public zone which is assumed to be unique.
1421 *
1422 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1423 * is a two-element array containing the source file path relative to the
1424 * public root in the first element, and the archive file path relative
1425 * to the deleted zone root in the second element.
1426 * @throws MWException
1427 * @return Status
1428 */
1429 public function deleteBatch( array $sourceDestPairs ) {
1430 $this->assertWritableRepo(); // fail out if read-only
1431
1432 // Try creating directories
1433 $status = $this->initZones( [ 'public', 'deleted' ] );
1434 if ( !$status->isOK() ) {
1435 return $status;
1436 }
1437
1438 $status = $this->newGood();
1439
1440 $backend = $this->backend; // convenience
1441 $operations = [];
1442 // Validate filenames and create archive directories
1443 foreach ( $sourceDestPairs as $pair ) {
1444 list( $srcRel, $archiveRel ) = $pair;
1445 if ( !$this->validateFilename( $srcRel ) ) {
1446 throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1447 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1448 throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1449 }
1450
1451 $publicRoot = $this->getZonePath( 'public' );
1452 $srcPath = "{$publicRoot}/$srcRel";
1453
1454 $deletedRoot = $this->getZonePath( 'deleted' );
1455 $archivePath = "{$deletedRoot}/{$archiveRel}";
1456 $archiveDir = dirname( $archivePath ); // does not touch FS
1457
1458 // Create destination directories
1459 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1460 return $this->newFatal( 'directorycreateerror', $archiveDir );
1461 }
1462
1463 $operations[] = [
1464 'op' => 'move',
1465 'src' => $srcPath,
1466 'dst' => $archivePath,
1467 // We may have 2+ identical files being deleted,
1468 // all of which will map to the same destination file
1469 'overwriteSame' => true // also see T33792
1470 ];
1471 }
1472
1473 // Move the files by execute the operations for each pair.
1474 // We're now committed to returning an OK result, which will
1475 // lead to the files being moved in the DB also.
1476 $opts = [ 'force' => true ];
1477 $status->merge( $backend->doOperations( $operations, $opts ) );
1478
1479 return $status;
1480 }
1481
1482 /**
1483 * Delete files in the deleted directory if they are not referenced in the filearchive table
1484 *
1485 * STUB
1486 * @param string[] $storageKeys
1487 */
1488 public function cleanupDeletedBatch( array $storageKeys ) {
1489 $this->assertWritableRepo();
1490 }
1491
1492 /**
1493 * Get a relative path for a deletion archive key,
1494 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1495 *
1496 * @param string $key
1497 * @throws MWException
1498 * @return string
1499 */
1500 public function getDeletedHashPath( $key ) {
1501 if ( strlen( $key ) < 31 ) {
1502 throw new MWException( "Invalid storage key '$key'." );
1503 }
1504 $path = '';
1505 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1506 $path .= $key[$i] . '/';
1507 }
1508
1509 return $path;
1510 }
1511
1512 /**
1513 * If a path is a virtual URL, resolve it to a storage path.
1514 * Otherwise, just return the path as it is.
1515 *
1516 * @param string $path
1517 * @return string
1518 * @throws MWException
1519 */
1520 protected function resolveToStoragePath( $path ) {
1521 if ( self::isVirtualUrl( $path ) ) {
1522 return $this->resolveVirtualUrl( $path );
1523 }
1524
1525 return $path;
1526 }
1527
1528 /**
1529 * Get a local FS copy of a file with a given virtual URL/storage path.
1530 * Temporary files may be purged when the file object falls out of scope.
1531 *
1532 * @param string $virtualUrl
1533 * @return TempFSFile|null Returns null on failure
1534 */
1535 public function getLocalCopy( $virtualUrl ) {
1536 $path = $this->resolveToStoragePath( $virtualUrl );
1537
1538 return $this->backend->getLocalCopy( [ 'src' => $path ] );
1539 }
1540
1541 /**
1542 * Get a local FS file with a given virtual URL/storage path.
1543 * The file is either an original or a copy. It should not be changed.
1544 * Temporary files may be purged when the file object falls out of scope.
1545 *
1546 * @param string $virtualUrl
1547 * @return FSFile|null Returns null on failure.
1548 */
1549 public function getLocalReference( $virtualUrl ) {
1550 $path = $this->resolveToStoragePath( $virtualUrl );
1551
1552 return $this->backend->getLocalReference( [ 'src' => $path ] );
1553 }
1554
1555 /**
1556 * Get properties of a file with a given virtual URL/storage path.
1557 * Properties should ultimately be obtained via FSFile::getProps().
1558 *
1559 * @param string $virtualUrl
1560 * @return array
1561 */
1562 public function getFileProps( $virtualUrl ) {
1563 $fsFile = $this->getLocalReference( $virtualUrl );
1564 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
1565 if ( $fsFile ) {
1566 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1567 } else {
1568 $props = $mwProps->newPlaceholderProps();
1569 }
1570
1571 return $props;
1572 }
1573
1574 /**
1575 * Get the timestamp of a file with a given virtual URL/storage path
1576 *
1577 * @param string $virtualUrl
1578 * @return string|bool False on failure
1579 */
1580 public function getFileTimestamp( $virtualUrl ) {
1581 $path = $this->resolveToStoragePath( $virtualUrl );
1582
1583 return $this->backend->getFileTimestamp( [ 'src' => $path ] );
1584 }
1585
1586 /**
1587 * Get the size of a file with a given virtual URL/storage path
1588 *
1589 * @param string $virtualUrl
1590 * @return int|bool False on failure
1591 */
1592 public function getFileSize( $virtualUrl ) {
1593 $path = $this->resolveToStoragePath( $virtualUrl );
1594
1595 return $this->backend->getFileSize( [ 'src' => $path ] );
1596 }
1597
1598 /**
1599 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1600 *
1601 * @param string $virtualUrl
1602 * @return string|bool
1603 */
1604 public function getFileSha1( $virtualUrl ) {
1605 $path = $this->resolveToStoragePath( $virtualUrl );
1606
1607 return $this->backend->getFileSha1Base36( [ 'src' => $path ] );
1608 }
1609
1610 /**
1611 * Attempt to stream a file with the given virtual URL/storage path
1612 *
1613 * @param string $virtualUrl
1614 * @param array $headers Additional HTTP headers to send on success
1615 * @param array $optHeaders HTTP request headers (if-modified-since, range, ...)
1616 * @return Status
1617 * @since 1.27
1618 */
1619 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1620 $path = $this->resolveToStoragePath( $virtualUrl );
1621 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1622
1623 // T172851: HHVM does not flush the output properly, causing OOM
1624 ob_start( null, 1048576 );
1625 ob_implicit_flush( true );
1626
1627 $status = $this->newGood();
1628 $status->merge( $this->backend->streamFile( $params ) );
1629
1630 // T186565: Close the buffer, unless it has already been closed
1631 // in HTTPFileStreamer::resetOutputBuffers().
1632 if ( ob_get_status() ) {
1633 ob_end_flush();
1634 }
1635
1636 return $status;
1637 }
1638
1639 /**
1640 * Call a callback function for every public regular file in the repository.
1641 * This only acts on the current version of files, not any old versions.
1642 * May use either the database or the filesystem.
1643 *
1644 * @param callable $callback
1645 * @return void
1646 */
1647 public function enumFiles( $callback ) {
1648 $this->enumFilesInStorage( $callback );
1649 }
1650
1651 /**
1652 * Call a callback function for every public file in the repository.
1653 * May use either the database or the filesystem.
1654 *
1655 * @param callable $callback
1656 * @return void
1657 */
1658 protected function enumFilesInStorage( $callback ) {
1659 $publicRoot = $this->getZonePath( 'public' );
1660 $numDirs = 1 << ( $this->hashLevels * 4 );
1661 // Use a priori assumptions about directory structure
1662 // to reduce the tree height of the scanning process.
1663 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1664 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1665 $path = $publicRoot;
1666 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1667 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1668 }
1669 $iterator = $this->backend->getFileList( [ 'dir' => $path ] );
1670 foreach ( $iterator as $name ) {
1671 // Each item returned is a public file
1672 call_user_func( $callback, "{$path}/{$name}" );
1673 }
1674 }
1675 }
1676
1677 /**
1678 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1679 *
1680 * @param string $filename
1681 * @return bool
1682 */
1683 public function validateFilename( $filename ) {
1684 if ( strval( $filename ) == '' ) {
1685 return false;
1686 }
1687
1688 return FileBackend::isPathTraversalFree( $filename );
1689 }
1690
1691 /**
1692 * Get a callback function to use for cleaning error message parameters
1693 *
1694 * @return callable
1695 */
1696 function getErrorCleanupFunction() {
1697 switch ( $this->pathDisclosureProtection ) {
1698 case 'none':
1699 case 'simple': // b/c
1700 $callback = [ $this, 'passThrough' ];
1701 break;
1702 default: // 'paranoid'
1703 $callback = [ $this, 'paranoidClean' ];
1704 }
1705 return $callback;
1706 }
1707
1708 /**
1709 * Path disclosure protection function
1710 *
1711 * @param string $param
1712 * @return string
1713 */
1714 function paranoidClean( $param ) {
1715 return '[hidden]';
1716 }
1717
1718 /**
1719 * Path disclosure protection function
1720 *
1721 * @param string $param
1722 * @return string
1723 */
1724 function passThrough( $param ) {
1725 return $param;
1726 }
1727
1728 /**
1729 * Create a new fatal error
1730 *
1731 * @param string $message
1732 * @return Status
1733 */
1734 public function newFatal( $message /*, parameters...*/ ) {
1735 $status = Status::newFatal( ...func_get_args() );
1736 $status->cleanCallback = $this->getErrorCleanupFunction();
1737
1738 return $status;
1739 }
1740
1741 /**
1742 * Create a new good result
1743 *
1744 * @param null|mixed $value
1745 * @return Status
1746 */
1747 public function newGood( $value = null ) {
1748 $status = Status::newGood( $value );
1749 $status->cleanCallback = $this->getErrorCleanupFunction();
1750
1751 return $status;
1752 }
1753
1754 /**
1755 * Checks if there is a redirect named as $title. If there is, return the
1756 * title object. If not, return false.
1757 * STUB
1758 *
1759 * @param Title $title Title of image
1760 * @return bool
1761 */
1762 public function checkRedirect( Title $title ) {
1763 return false;
1764 }
1765
1766 /**
1767 * Invalidates image redirect cache related to that image
1768 * Doesn't do anything for repositories that don't support image redirects.
1769 *
1770 * STUB
1771 * @param Title $title Title of image
1772 */
1773 public function invalidateImageRedirect( Title $title ) {
1774 }
1775
1776 /**
1777 * Get the human-readable name of the repo
1778 *
1779 * @return string
1780 */
1781 public function getDisplayName() {
1782 global $wgSitename;
1783
1784 if ( $this->isLocal() ) {
1785 return $wgSitename;
1786 }
1787
1788 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1789 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1790 }
1791
1792 /**
1793 * Get the portion of the file that contains the origin file name.
1794 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1795 *
1796 * @param string $name
1797 * @return string
1798 */
1799 public function nameForThumb( $name ) {
1800 if ( strlen( $name ) > $this->abbrvThreshold ) {
1801 $ext = FileBackend::extensionFromPath( $name );
1802 $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1803 }
1804
1805 return $name;
1806 }
1807
1808 /**
1809 * Returns true if this the local file repository.
1810 *
1811 * @return bool
1812 */
1813 public function isLocal() {
1814 return $this->getName() == 'local';
1815 }
1816
1817 /**
1818 * Get a key on the primary cache for this repository.
1819 * Returns false if the repository's cache is not accessible at this site.
1820 * The parameters are the parts of the key.
1821 *
1822 * STUB
1823 * @return bool
1824 */
1825 public function getSharedCacheKey( /*...*/ ) {
1826 return false;
1827 }
1828
1829 /**
1830 * Get a key for this repo in the local cache domain. These cache keys are
1831 * not shared with remote instances of the repo.
1832 * The parameters are the parts of the key.
1833 *
1834 * @return string
1835 */
1836 public function getLocalCacheKey( /*...*/ ) {
1837 $args = func_get_args();
1838 array_unshift( $args, 'filerepo', $this->getName() );
1839
1840 return $this->wanCache->makeKey( ...$args );
1841 }
1842
1843 /**
1844 * Get a temporary private FileRepo associated with this repo.
1845 *
1846 * Files will be created in the temp zone of this repo.
1847 * It will have the same backend as this repo.
1848 *
1849 * @return TempFileRepo
1850 */
1851 public function getTempRepo() {
1852 return new TempFileRepo( [
1853 'name' => "{$this->name}-temp",
1854 'backend' => $this->backend,
1855 'zones' => [
1856 'public' => [
1857 // Same place storeTemp() uses in the base repo, though
1858 // the path hashing is mismatched, which is annoying.
1859 'container' => $this->zones['temp']['container'],
1860 'directory' => $this->zones['temp']['directory']
1861 ],
1862 'thumb' => [
1863 'container' => $this->zones['temp']['container'],
1864 'directory' => $this->zones['temp']['directory'] == ''
1865 ? 'thumb'
1866 : $this->zones['temp']['directory'] . '/thumb'
1867 ],
1868 'transcoded' => [
1869 'container' => $this->zones['temp']['container'],
1870 'directory' => $this->zones['temp']['directory'] == ''
1871 ? 'transcoded'
1872 : $this->zones['temp']['directory'] . '/transcoded'
1873 ]
1874 ],
1875 'hashLevels' => $this->hashLevels, // performance
1876 'isPrivate' => true // all in temp zone
1877 ] );
1878 }
1879
1880 /**
1881 * Get an UploadStash associated with this repo.
1882 *
1883 * @param User|null $user
1884 * @return UploadStash
1885 */
1886 public function getUploadStash( User $user = null ) {
1887 return new UploadStash( $this, $user );
1888 }
1889
1890 /**
1891 * Throw an exception if this repo is read-only by design.
1892 * This does not and should not check getReadOnlyReason().
1893 *
1894 * @return void
1895 * @throws MWException
1896 */
1897 protected function assertWritableRepo() {
1898 }
1899
1900 /**
1901 * Return information about the repository.
1902 *
1903 * @return array
1904 * @since 1.22
1905 */
1906 public function getInfo() {
1907 $ret = [
1908 'name' => $this->getName(),
1909 'displayname' => $this->getDisplayName(),
1910 'rootUrl' => $this->getZoneUrl( 'public' ),
1911 'local' => $this->isLocal(),
1912 ];
1913
1914 $optionalSettings = [
1915 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1916 'fetchDescription', 'descriptionCacheExpiry', 'favicon'
1917 ];
1918 foreach ( $optionalSettings as $k ) {
1919 if ( isset( $this->$k ) ) {
1920 $ret[$k] = $this->$k;
1921 }
1922 }
1923
1924 return $ret;
1925 }
1926
1927 /**
1928 * Returns whether or not storage is SHA-1 based
1929 * @return bool
1930 */
1931 public function hasSha1Storage() {
1932 return $this->hasSha1Storage;
1933 }
1934
1935 /**
1936 * Returns whether or not repo supports having originals SHA-1s in the thumb URLs
1937 * @return bool
1938 */
1939 public function supportsSha1URLs() {
1940 return $this->supportsSha1URLs;
1941 }
1942 }