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