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