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