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