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