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