98e785f19db6a7ef983170014bd41d77db34f8bf
[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 array|null $info
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 string $url
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 string|bool $suffix
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|bool 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 string $url
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 string $zone
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 string $zone
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|string $title Title object or string
381 * @param bool|string $time Time at which the image was uploaded. If this
382 * is specified, the returned object will be an instance of the
383 * repository's old file class instead of a current file. Repositories
384 * not supporting version control should return false if this parameter
385 * 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|string $title 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 * ignoreRedirect: If true, do not follow file redirects
415 * private: If true, return restricted (deleted) files if the current
416 * user is allowed to view them. Otherwise, such files will not
417 * be found.
418 * @return File|bool False on failure
419 */
420 public function findFile( $title, $options = array() ) {
421 $title = File::normalizeTitle( $title );
422 if ( !$title ) {
423 return false;
424 }
425 $time = isset( $options['time'] ) ? $options['time'] : false;
426 # First try the current version of the file to see if it precedes the timestamp
427 $img = $this->newFile( $title );
428 if ( !$img ) {
429 return false;
430 }
431 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
432 return $img;
433 }
434 # Now try an old version of the file
435 if ( $time !== false ) {
436 $img = $this->newFile( $title, $time );
437 if ( $img && $img->exists() ) {
438 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
439 return $img; // always OK
440 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
441 return $img;
442 }
443 }
444 }
445
446 # Now try redirects
447 if ( !empty( $options['ignoreRedirect'] ) ) {
448 return false;
449 }
450 $redir = $this->checkRedirect( $title );
451 if ( $redir && $title->getNamespace() == NS_FILE ) {
452 $img = $this->newFile( $redir );
453 if ( !$img ) {
454 return false;
455 }
456 if ( $img->exists() ) {
457 $img->redirectedFrom( $title->getDBkey() );
458
459 return $img;
460 }
461 }
462
463 return false;
464 }
465
466 /**
467 * Find many files at once.
468 *
469 * @param array $items An array of titles, or an array of findFile() options with
470 * the "title" option giving the title. Example:
471 *
472 * $findItem = array( 'title' => $title, 'private' => true );
473 * $findBatch = array( $findItem );
474 * $repo->findFiles( $findBatch );
475 * @return array
476 */
477 public function findFiles( array $items ) {
478 $result = array();
479 foreach ( $items as $item ) {
480 if ( is_array( $item ) ) {
481 $title = $item['title'];
482 $options = $item;
483 unset( $options['title'] );
484 } else {
485 $title = $item;
486 $options = array();
487 }
488 $file = $this->findFile( $title, $options );
489 if ( $file ) {
490 $result[$file->getTitle()->getDBkey()] = $file;
491 }
492 }
493
494 return $result;
495 }
496
497 /**
498 * Find an instance of the file with this key, created at the specified time
499 * Returns false if the file does not exist. Repositories not supporting
500 * version control should return false if the time is specified.
501 *
502 * @param string $sha1 Base 36 SHA-1 hash
503 * @param array $options Option array, same as findFile().
504 * @return File|bool False on failure
505 */
506 public function findFileFromKey( $sha1, $options = array() ) {
507 $time = isset( $options['time'] ) ? $options['time'] : false;
508 # First try to find a matching current version of a file...
509 if ( $this->fileFactoryKey ) {
510 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
511 } else {
512 return false; // find-by-sha1 not supported
513 }
514 if ( $img && $img->exists() ) {
515 return $img;
516 }
517 # Now try to find a matching old version of a file...
518 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
519 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
520 if ( $img && $img->exists() ) {
521 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
522 return $img; // always OK
523 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
524 return $img;
525 }
526 }
527 }
528
529 return false;
530 }
531
532 /**
533 * Get an array or iterator of file objects for files that have a given
534 * SHA-1 content hash.
535 *
536 * STUB
537 * @param string $hash SHA-1 hash
538 * @return array
539 */
540 public function findBySha1( $hash ) {
541 return array();
542 }
543
544 /**
545 * Get an array of arrays or iterators of file objects for files that
546 * have the given SHA-1 content hashes.
547 *
548 * @param array $hashes An array of hashes
549 * @return array An Array of arrays or iterators of file objects and the hash as key
550 */
551 public function findBySha1s( array $hashes ) {
552 $result = array();
553 foreach ( $hashes as $hash ) {
554 $files = $this->findBySha1( $hash );
555 if ( count( $files ) ) {
556 $result[$hash] = $files;
557 }
558 }
559
560 return $result;
561 }
562
563 /**
564 * Return an array of files where the name starts with $prefix.
565 *
566 * STUB
567 * @param string $prefix The prefix to search for
568 * @param int $limit The maximum amount of files to return
569 * @return array
570 */
571 public function findFilesByPrefix( $prefix, $limit ) {
572 return array();
573 }
574
575 /**
576 * Get the public root URL of the repository
577 *
578 * @deprecated since 1.20
579 * @return string
580 */
581 public function getRootUrl() {
582 return $this->getZoneUrl( 'public' );
583 }
584
585 /**
586 * Get the URL of thumb.php
587 *
588 * @return string
589 */
590 public function getThumbScriptUrl() {
591 return $this->thumbScriptUrl;
592 }
593
594 /**
595 * Returns true if the repository can transform files via a 404 handler
596 *
597 * @return bool
598 */
599 public function canTransformVia404() {
600 return $this->transformVia404;
601 }
602
603 /**
604 * Get the name of a file from its title object
605 *
606 * @param Title $title
607 * @return string
608 */
609 public function getNameFromTitle( Title $title ) {
610 global $wgContLang;
611 if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
612 $name = $title->getUserCaseDBKey();
613 if ( $this->initialCapital ) {
614 $name = $wgContLang->ucfirst( $name );
615 }
616 } else {
617 $name = $title->getDBkey();
618 }
619
620 return $name;
621 }
622
623 /**
624 * Get the public zone root storage directory of the repository
625 *
626 * @return string
627 */
628 public function getRootDirectory() {
629 return $this->getZonePath( 'public' );
630 }
631
632 /**
633 * Get a relative path including trailing slash, e.g. f/fa/
634 * If the repo is not hashed, returns an empty string
635 *
636 * @param string $name Name of file
637 * @return string
638 */
639 public function getHashPath( $name ) {
640 return self::getHashPathForLevel( $name, $this->hashLevels );
641 }
642
643 /**
644 * Get a relative path including trailing slash, e.g. f/fa/
645 * If the repo is not hashed, returns an empty string
646 *
647 * @param string $suffix Basename of file from FileRepo::storeTemp()
648 * @return string
649 */
650 public function getTempHashPath( $suffix ) {
651 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
652 $name = isset( $parts[1] ) ? $parts[1] : $suffix; // hash path is not based on timestamp
653 return self::getHashPathForLevel( $name, $this->hashLevels );
654 }
655
656 /**
657 * @param string $name
658 * @param int $levels
659 * @return string
660 */
661 protected static function getHashPathForLevel( $name, $levels ) {
662 if ( $levels == 0 ) {
663 return '';
664 } else {
665 $hash = md5( $name );
666 $path = '';
667 for ( $i = 1; $i <= $levels; $i++ ) {
668 $path .= substr( $hash, 0, $i ) . '/';
669 }
670
671 return $path;
672 }
673 }
674
675 /**
676 * Get the number of hash directory levels
677 *
678 * @return int
679 */
680 public function getHashLevels() {
681 return $this->hashLevels;
682 }
683
684 /**
685 * Get the name of this repository, as specified by $info['name]' to the constructor
686 *
687 * @return string
688 */
689 public function getName() {
690 return $this->name;
691 }
692
693 /**
694 * Make an url to this repo
695 *
696 * @param string $query Query string to append
697 * @param string $entry Entry point; defaults to index
698 * @return string|bool False on failure
699 */
700 public function makeUrl( $query = '', $entry = 'index' ) {
701 if ( isset( $this->scriptDirUrl ) ) {
702 $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
703
704 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
705 }
706
707 return false;
708 }
709
710 /**
711 * Get the URL of an image description page. May return false if it is
712 * unknown or not applicable. In general this should only be called by the
713 * File class, since it may return invalid results for certain kinds of
714 * repositories. Use File::getDescriptionUrl() in user code.
715 *
716 * In particular, it uses the article paths as specified to the repository
717 * constructor, whereas local repositories use the local Title functions.
718 *
719 * @param string $name
720 * @return string
721 */
722 public function getDescriptionUrl( $name ) {
723 $encName = wfUrlencode( $name );
724 if ( !is_null( $this->descBaseUrl ) ) {
725 # "http://example.com/wiki/File:"
726 return $this->descBaseUrl . $encName;
727 }
728 if ( !is_null( $this->articleUrl ) ) {
729 # "http://example.com/wiki/$1"
730 #
731 # We use "Image:" as the canonical namespace for
732 # compatibility across all MediaWiki versions.
733 return str_replace( '$1',
734 "Image:$encName", $this->articleUrl );
735 }
736 if ( !is_null( $this->scriptDirUrl ) ) {
737 # "http://example.com/w"
738 #
739 # We use "Image:" as the canonical namespace for
740 # compatibility across all MediaWiki versions,
741 # and just sort of hope index.php is right. ;)
742 return $this->makeUrl( "title=Image:$encName" );
743 }
744
745 return false;
746 }
747
748 /**
749 * Get the URL of the content-only fragment of the description page. For
750 * MediaWiki this means action=render. This should only be called by the
751 * repository's file class, since it may return invalid results. User code
752 * should use File::getDescriptionText().
753 *
754 * @param string $name Name of image to fetch
755 * @param string $lang Language to fetch it in, if any.
756 * @return string
757 */
758 public function getDescriptionRenderUrl( $name, $lang = null ) {
759 $query = 'action=render';
760 if ( !is_null( $lang ) ) {
761 $query .= '&uselang=' . $lang;
762 }
763 if ( isset( $this->scriptDirUrl ) ) {
764 return $this->makeUrl(
765 'title=' .
766 wfUrlencode( 'Image:' . $name ) .
767 "&$query" );
768 } else {
769 $descUrl = $this->getDescriptionUrl( $name );
770 if ( $descUrl ) {
771 return wfAppendQuery( $descUrl, $query );
772 } else {
773 return false;
774 }
775 }
776 }
777
778 /**
779 * Get the URL of the stylesheet to apply to description pages
780 *
781 * @return string|bool False on failure
782 */
783 public function getDescriptionStylesheetUrl() {
784 if ( isset( $this->scriptDirUrl ) ) {
785 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
786 wfArrayToCgi( Skin::getDynamicStylesheetQuery() ) );
787 }
788
789 return false;
790 }
791
792 /**
793 * Store a file to a given destination.
794 *
795 * @param string $srcPath Source file system path, storage path, or virtual URL
796 * @param string $dstZone Destination zone
797 * @param string $dstRel Destination relative path
798 * @param int $flags Bitwise combination of the following flags:
799 * self::DELETE_SOURCE Delete the source file after upload
800 * self::OVERWRITE Overwrite an existing destination file instead of failing
801 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
802 * same contents as the source
803 * self::SKIP_LOCKING Skip any file locking when doing the store
804 * @return FileRepoStatus
805 */
806 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
807 $this->assertWritableRepo(); // fail out if read-only
808
809 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
810 if ( $status->successCount == 0 ) {
811 $status->ok = false;
812 }
813
814 return $status;
815 }
816
817 /**
818 * Store a batch of files
819 *
820 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
821 * @param int $flags Bitwise combination of the following flags:
822 * self::DELETE_SOURCE Delete the source file after upload
823 * self::OVERWRITE Overwrite an existing destination file instead of failing
824 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
825 * same contents as the source
826 * self::SKIP_LOCKING Skip any file locking when doing the store
827 * @throws MWException
828 * @return FileRepoStatus
829 */
830 public function storeBatch( array $triplets, $flags = 0 ) {
831 $this->assertWritableRepo(); // fail out if read-only
832
833 $status = $this->newGood();
834 $backend = $this->backend; // convenience
835
836 $operations = array();
837 $sourceFSFilesToDelete = array(); // cleanup for disk source files
838 // Validate each triplet and get the store operation...
839 foreach ( $triplets as $triplet ) {
840 list( $srcPath, $dstZone, $dstRel ) = $triplet;
841 wfDebug( __METHOD__
842 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
843 );
844
845 // Resolve destination path
846 $root = $this->getZonePath( $dstZone );
847 if ( !$root ) {
848 throw new MWException( "Invalid zone: $dstZone" );
849 }
850 if ( !$this->validateFilename( $dstRel ) ) {
851 throw new MWException( 'Validation error in $dstRel' );
852 }
853 $dstPath = "$root/$dstRel";
854 $dstDir = dirname( $dstPath );
855 // Create destination directories for this triplet
856 if ( !$this->initDirectory( $dstDir )->isOK() ) {
857 return $this->newFatal( 'directorycreateerror', $dstDir );
858 }
859
860 // Resolve source to a storage path if virtual
861 $srcPath = $this->resolveToStoragePath( $srcPath );
862
863 // Get the appropriate file operation
864 if ( FileBackend::isStoragePath( $srcPath ) ) {
865 $opName = ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy';
866 } else {
867 $opName = 'store';
868 if ( $flags & self::DELETE_SOURCE ) {
869 $sourceFSFilesToDelete[] = $srcPath;
870 }
871 }
872 $operations[] = array(
873 'op' => $opName,
874 'src' => $srcPath,
875 'dst' => $dstPath,
876 'overwrite' => $flags & self::OVERWRITE,
877 'overwriteSame' => $flags & self::OVERWRITE_SAME,
878 );
879 }
880
881 // Execute the store operation for each triplet
882 $opts = array( 'force' => true );
883 if ( $flags & self::SKIP_LOCKING ) {
884 $opts['nonLocking'] = true;
885 }
886 $status->merge( $backend->doOperations( $operations, $opts ) );
887 // Cleanup for disk source files...
888 foreach ( $sourceFSFilesToDelete as $file ) {
889 wfSuppressWarnings();
890 unlink( $file ); // FS cleanup
891 wfRestoreWarnings();
892 }
893
894 return $status;
895 }
896
897 /**
898 * Deletes a batch of files.
899 * Each file can be a (zone, rel) pair, virtual url, storage path.
900 * It will try to delete each file, but ignores any errors that may occur.
901 *
902 * @param array $files List of files to delete
903 * @param int $flags Bitwise combination of the following flags:
904 * self::SKIP_LOCKING Skip any file locking when doing the deletions
905 * @return FileRepoStatus
906 */
907 public function cleanupBatch( array $files, $flags = 0 ) {
908 $this->assertWritableRepo(); // fail out if read-only
909
910 $status = $this->newGood();
911
912 $operations = array();
913 foreach ( $files as $path ) {
914 if ( is_array( $path ) ) {
915 // This is a pair, extract it
916 list( $zone, $rel ) = $path;
917 $path = $this->getZonePath( $zone ) . "/$rel";
918 } else {
919 // Resolve source to a storage path if virtual
920 $path = $this->resolveToStoragePath( $path );
921 }
922 $operations[] = array( 'op' => 'delete', 'src' => $path );
923 }
924 // Actually delete files from storage...
925 $opts = array( 'force' => true );
926 if ( $flags & self::SKIP_LOCKING ) {
927 $opts['nonLocking'] = true;
928 }
929 $status->merge( $this->backend->doOperations( $operations, $opts ) );
930
931 return $status;
932 }
933
934 /**
935 * Import a file from the local file system into the repo.
936 * This does no locking nor journaling and overrides existing files.
937 * This function can be used to write to otherwise read-only foreign repos.
938 * This is intended for copying generated thumbnails into the repo.
939 *
940 * @param string $src Source file system path, storage path, or virtual URL
941 * @param string $dst Virtual URL or storage path
942 * @param string|null $disposition Content-Disposition if given and supported
943 * @return FileRepoStatus
944 */
945 final public function quickImport( $src, $dst, $disposition = null ) {
946 return $this->quickImportBatch( array( array( $src, $dst, $disposition ) ) );
947 }
948
949 /**
950 * Purge a file from the repo. This does no locking nor journaling.
951 * This function can be used to write to otherwise read-only foreign repos.
952 * This is intended for purging thumbnails.
953 *
954 * @param string $path Virtual URL or storage path
955 * @return FileRepoStatus
956 */
957 final public function quickPurge( $path ) {
958 return $this->quickPurgeBatch( array( $path ) );
959 }
960
961 /**
962 * Deletes a directory if empty.
963 * This function can be used to write to otherwise read-only foreign repos.
964 *
965 * @param string $dir Virtual URL (or storage path) of directory to clean
966 * @return Status
967 */
968 public function quickCleanDir( $dir ) {
969 $status = $this->newGood();
970 $status->merge( $this->backend->clean(
971 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
972
973 return $status;
974 }
975
976 /**
977 * Import a batch of files from the local file system into the repo.
978 * This does no locking nor journaling and overrides existing files.
979 * This function can be used to write to otherwise read-only foreign repos.
980 * This is intended for copying generated thumbnails into the repo.
981 *
982 * All path parameters may be a file system path, storage path, or virtual URL.
983 * When "dispositions" are given they are used as Content-Disposition if supported.
984 *
985 * @param array $triples List of (source path, destination path, disposition)
986 * @return FileRepoStatus
987 */
988 public function quickImportBatch( array $triples ) {
989 $status = $this->newGood();
990 $operations = array();
991 foreach ( $triples as $triple ) {
992 list( $src, $dst ) = $triple;
993 $src = $this->resolveToStoragePath( $src );
994 $dst = $this->resolveToStoragePath( $dst );
995 $operations[] = array(
996 'op' => FileBackend::isStoragePath( $src ) ? 'copy' : 'store',
997 'src' => $src,
998 'dst' => $dst,
999 'disposition' => isset( $triple[2] ) ? $triple[2] : null
1000 );
1001 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1002 }
1003 $status->merge( $this->backend->doQuickOperations( $operations ) );
1004
1005 return $status;
1006 }
1007
1008 /**
1009 * Purge a batch of files from the repo.
1010 * This function can be used to write to otherwise read-only foreign repos.
1011 * This does no locking nor journaling and is intended for purging thumbnails.
1012 *
1013 * @param array $paths List of virtual URLs or storage paths
1014 * @return FileRepoStatus
1015 */
1016 public function quickPurgeBatch( array $paths ) {
1017 $status = $this->newGood();
1018 $operations = array();
1019 foreach ( $paths as $path ) {
1020 $operations[] = array(
1021 'op' => 'delete',
1022 'src' => $this->resolveToStoragePath( $path ),
1023 'ignoreMissingSource' => true
1024 );
1025 }
1026 $status->merge( $this->backend->doQuickOperations( $operations ) );
1027
1028 return $status;
1029 }
1030
1031 /**
1032 * Pick a random name in the temp zone and store a file to it.
1033 * Returns a FileRepoStatus object with the file Virtual URL in the value,
1034 * file can later be disposed using FileRepo::freeTemp().
1035 *
1036 * @param string $originalName the base name of the file as specified
1037 * by the user. The file extension will be maintained.
1038 * @param string $srcPath The current location of the file.
1039 * @return FileRepoStatus Object with the URL in the value.
1040 */
1041 public function storeTemp( $originalName, $srcPath ) {
1042 $this->assertWritableRepo(); // fail out if read-only
1043
1044 $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1045 $hashPath = $this->getHashPath( $originalName );
1046 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1047 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1048
1049 $result = $this->quickImport( $srcPath, $virtualUrl );
1050 $result->value = $virtualUrl;
1051
1052 return $result;
1053 }
1054
1055 /**
1056 * Remove a temporary file or mark it for garbage collection
1057 *
1058 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1059 * @return bool True on success, false on failure
1060 */
1061 public function freeTemp( $virtualUrl ) {
1062 $this->assertWritableRepo(); // fail out if read-only
1063
1064 $temp = $this->getVirtualUrl( 'temp' );
1065 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1066 wfDebug( __METHOD__ . ": Invalid temp virtual URL\n" );
1067
1068 return false;
1069 }
1070
1071 return $this->quickPurge( $virtualUrl )->isOK();
1072 }
1073
1074 /**
1075 * Concatenate a list of temporary files into a target file location.
1076 *
1077 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1078 * @param string $dstPath Target file system path
1079 * @param int $flags Bitwise combination of the following flags:
1080 * self::DELETE_SOURCE Delete the source files
1081 * @return FileRepoStatus
1082 */
1083 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1084 $this->assertWritableRepo(); // fail out if read-only
1085
1086 $status = $this->newGood();
1087
1088 $sources = array();
1089 foreach ( $srcPaths as $srcPath ) {
1090 // Resolve source to a storage path if virtual
1091 $source = $this->resolveToStoragePath( $srcPath );
1092 $sources[] = $source; // chunk to merge
1093 }
1094
1095 // Concatenate the chunks into one FS file
1096 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
1097 $status->merge( $this->backend->concatenate( $params ) );
1098 if ( !$status->isOK() ) {
1099 return $status;
1100 }
1101
1102 // Delete the sources if required
1103 if ( $flags & self::DELETE_SOURCE ) {
1104 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1105 }
1106
1107 // Make sure status is OK, despite any quickPurgeBatch() fatals
1108 $status->setResult( true );
1109
1110 return $status;
1111 }
1112
1113 /**
1114 * Copy or move a file either from a storage path, virtual URL,
1115 * or file system path, into this repository at the specified destination location.
1116 *
1117 * Returns a FileRepoStatus object. On success, the value contains "new" or
1118 * "archived", to indicate whether the file was new with that name.
1119 *
1120 * Options to $options include:
1121 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1122 *
1123 * @param string $srcPath The source file system path, storage path, or URL
1124 * @param string $dstRel The destination relative path
1125 * @param string $archiveRel The relative path where the existing file is to
1126 * be archived, if there is one. Relative to the public zone root.
1127 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1128 * that the source file should be deleted if possible
1129 * @param array $options Optional additional parameters
1130 * @return FileRepoStatus
1131 */
1132 public function publish(
1133 $srcPath, $dstRel, $archiveRel, $flags = 0, array $options = array()
1134 ) {
1135 $this->assertWritableRepo(); // fail out if read-only
1136
1137 $status = $this->publishBatch(
1138 array( array( $srcPath, $dstRel, $archiveRel, $options ) ), $flags );
1139 if ( $status->successCount == 0 ) {
1140 $status->ok = false;
1141 }
1142 if ( isset( $status->value[0] ) ) {
1143 $status->value = $status->value[0];
1144 } else {
1145 $status->value = false;
1146 }
1147
1148 return $status;
1149 }
1150
1151 /**
1152 * Publish a batch of files
1153 *
1154 * @param array $ntuples (source, dest, archive) triplets or
1155 * (source, dest, archive, options) 4-tuples as per publish().
1156 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1157 * that the source files should be deleted if possible
1158 * @throws MWException
1159 * @return FileRepoStatus
1160 */
1161 public function publishBatch( array $ntuples, $flags = 0 ) {
1162 $this->assertWritableRepo(); // fail out if read-only
1163
1164 $backend = $this->backend; // convenience
1165 // Try creating directories
1166 $status = $this->initZones( 'public' );
1167 if ( !$status->isOK() ) {
1168 return $status;
1169 }
1170
1171 $status = $this->newGood( array() );
1172
1173 $operations = array();
1174 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1175 // Validate each triplet and get the store operation...
1176 foreach ( $ntuples as $ntuple ) {
1177 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1178 $options = isset( $ntuple[3] ) ? $ntuple[3] : array();
1179 // Resolve source to a storage path if virtual
1180 $srcPath = $this->resolveToStoragePath( $srcPath );
1181 if ( !$this->validateFilename( $dstRel ) ) {
1182 throw new MWException( 'Validation error in $dstRel' );
1183 }
1184 if ( !$this->validateFilename( $archiveRel ) ) {
1185 throw new MWException( 'Validation error in $archiveRel' );
1186 }
1187
1188 $publicRoot = $this->getZonePath( 'public' );
1189 $dstPath = "$publicRoot/$dstRel";
1190 $archivePath = "$publicRoot/$archiveRel";
1191
1192 $dstDir = dirname( $dstPath );
1193 $archiveDir = dirname( $archivePath );
1194 // Abort immediately on directory creation errors since they're likely to be repetitive
1195 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1196 return $this->newFatal( 'directorycreateerror', $dstDir );
1197 }
1198 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1199 return $this->newFatal( 'directorycreateerror', $archiveDir );
1200 }
1201
1202 // Set any desired headers to be use in GET/HEAD responses
1203 $headers = isset( $options['headers'] ) ? $options['headers'] : array();
1204
1205 // Archive destination file if it exists.
1206 // This will check if the archive file also exists and fail if does.
1207 // This is a sanity check to avoid data loss. On Windows and Linux,
1208 // copy() will overwrite, so the existence check is vulnerable to
1209 // race conditions unless an functioning LockManager is used.
1210 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1211 $operations[] = array(
1212 'op' => 'copy',
1213 'src' => $dstPath,
1214 'dst' => $archivePath,
1215 'ignoreMissingSource' => true
1216 );
1217
1218 // Copy (or move) the source file to the destination
1219 if ( FileBackend::isStoragePath( $srcPath ) ) {
1220 if ( $flags & self::DELETE_SOURCE ) {
1221 $operations[] = array(
1222 'op' => 'move',
1223 'src' => $srcPath,
1224 'dst' => $dstPath,
1225 'overwrite' => true, // replace current
1226 'headers' => $headers
1227 );
1228 } else {
1229 $operations[] = array(
1230 'op' => 'copy',
1231 'src' => $srcPath,
1232 'dst' => $dstPath,
1233 'overwrite' => true, // replace current
1234 'headers' => $headers
1235 );
1236 }
1237 } else { // FS source path
1238 $operations[] = array(
1239 'op' => 'store',
1240 'src' => $srcPath,
1241 'dst' => $dstPath,
1242 'overwrite' => true, // replace current
1243 'headers' => $headers
1244 );
1245 if ( $flags & self::DELETE_SOURCE ) {
1246 $sourceFSFilesToDelete[] = $srcPath;
1247 }
1248 }
1249 }
1250
1251 // Execute the operations for each triplet
1252 $status->merge( $backend->doOperations( $operations ) );
1253 // Find out which files were archived...
1254 foreach ( $ntuples as $i => $ntuple ) {
1255 list( , , $archiveRel ) = $ntuple;
1256 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1257 if ( $this->fileExists( $archivePath ) ) {
1258 $status->value[$i] = 'archived';
1259 } else {
1260 $status->value[$i] = 'new';
1261 }
1262 }
1263 // Cleanup for disk source files...
1264 foreach ( $sourceFSFilesToDelete as $file ) {
1265 wfSuppressWarnings();
1266 unlink( $file ); // FS cleanup
1267 wfRestoreWarnings();
1268 }
1269
1270 return $status;
1271 }
1272
1273 /**
1274 * Creates a directory with the appropriate zone permissions.
1275 * Callers are responsible for doing read-only and "writable repo" checks.
1276 *
1277 * @param string $dir Virtual URL (or storage path) of directory to clean
1278 * @return Status
1279 */
1280 protected function initDirectory( $dir ) {
1281 $path = $this->resolveToStoragePath( $dir );
1282 list( , $container, ) = FileBackend::splitStoragePath( $path );
1283
1284 $params = array( 'dir' => $path );
1285 if ( $this->isPrivate || $container === $this->zones['deleted']['container'] ) {
1286 # Take all available measures to prevent web accessibility of new deleted
1287 # directories, in case the user has not configured offline storage
1288 $params = array( 'noAccess' => true, 'noListing' => true ) + $params;
1289 }
1290
1291 return $this->backend->prepare( $params );
1292 }
1293
1294 /**
1295 * Deletes a directory if empty.
1296 *
1297 * @param string $dir Virtual URL (or storage path) of directory to clean
1298 * @return Status
1299 */
1300 public function cleanDir( $dir ) {
1301 $this->assertWritableRepo(); // fail out if read-only
1302
1303 $status = $this->newGood();
1304 $status->merge( $this->backend->clean(
1305 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1306
1307 return $status;
1308 }
1309
1310 /**
1311 * Checks existence of a a file
1312 *
1313 * @param string $file Virtual URL (or storage path) of file to check
1314 * @return bool
1315 */
1316 public function fileExists( $file ) {
1317 $result = $this->fileExistsBatch( array( $file ) );
1318
1319 return $result[0];
1320 }
1321
1322 /**
1323 * Checks existence of an array of files.
1324 *
1325 * @param array $files Virtual URLs (or storage paths) of files to check
1326 * @return array|bool Either array of files and existence flags, or false
1327 */
1328 public function fileExistsBatch( array $files ) {
1329 $result = array();
1330 foreach ( $files as $key => $file ) {
1331 $file = $this->resolveToStoragePath( $file );
1332 $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
1333 }
1334
1335 return $result;
1336 }
1337
1338 /**
1339 * Move a file to the deletion archive.
1340 * If no valid deletion archive exists, this may either delete the file
1341 * or throw an exception, depending on the preference of the repository
1342 *
1343 * @param mixed $srcRel Relative path for the file to be deleted
1344 * @param mixed $archiveRel Relative path for the archive location.
1345 * Relative to a private archive directory.
1346 * @return FileRepoStatus object
1347 */
1348 public function delete( $srcRel, $archiveRel ) {
1349 $this->assertWritableRepo(); // fail out if read-only
1350
1351 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1352 }
1353
1354 /**
1355 * Move a group of files to the deletion archive.
1356 *
1357 * If no valid deletion archive is configured, this may either delete the
1358 * file or throw an exception, depending on the preference of the repository.
1359 *
1360 * The overwrite policy is determined by the repository -- currently LocalRepo
1361 * assumes a naming scheme in the deleted zone based on content hash, as
1362 * opposed to the public zone which is assumed to be unique.
1363 *
1364 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1365 * is a two-element array containing the source file path relative to the
1366 * public root in the first element, and the archive file path relative
1367 * to the deleted zone root in the second element.
1368 * @throws MWException
1369 * @return FileRepoStatus
1370 */
1371 public function deleteBatch( array $sourceDestPairs ) {
1372 $this->assertWritableRepo(); // fail out if read-only
1373
1374 // Try creating directories
1375 $status = $this->initZones( array( 'public', 'deleted' ) );
1376 if ( !$status->isOK() ) {
1377 return $status;
1378 }
1379
1380 $status = $this->newGood();
1381
1382 $backend = $this->backend; // convenience
1383 $operations = array();
1384 // Validate filenames and create archive directories
1385 foreach ( $sourceDestPairs as $pair ) {
1386 list( $srcRel, $archiveRel ) = $pair;
1387 if ( !$this->validateFilename( $srcRel ) ) {
1388 throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1389 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1390 throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1391 }
1392
1393 $publicRoot = $this->getZonePath( 'public' );
1394 $srcPath = "{$publicRoot}/$srcRel";
1395
1396 $deletedRoot = $this->getZonePath( 'deleted' );
1397 $archivePath = "{$deletedRoot}/{$archiveRel}";
1398 $archiveDir = dirname( $archivePath ); // does not touch FS
1399
1400 // Create destination directories
1401 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1402 return $this->newFatal( 'directorycreateerror', $archiveDir );
1403 }
1404
1405 $operations[] = array(
1406 'op' => 'move',
1407 'src' => $srcPath,
1408 'dst' => $archivePath,
1409 // We may have 2+ identical files being deleted,
1410 // all of which will map to the same destination file
1411 'overwriteSame' => true // also see bug 31792
1412 );
1413 }
1414
1415 // Move the files by execute the operations for each pair.
1416 // We're now committed to returning an OK result, which will
1417 // lead to the files being moved in the DB also.
1418 $opts = array( 'force' => true );
1419 $status->merge( $backend->doOperations( $operations, $opts ) );
1420
1421 return $status;
1422 }
1423
1424 /**
1425 * Delete files in the deleted directory if they are not referenced in the filearchive table
1426 *
1427 * STUB
1428 */
1429 public function cleanupDeletedBatch( array $storageKeys ) {
1430 $this->assertWritableRepo();
1431 }
1432
1433 /**
1434 * Get a relative path for a deletion archive key,
1435 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1436 *
1437 * @param string $key
1438 * @throws MWException
1439 * @return string
1440 */
1441 public function getDeletedHashPath( $key ) {
1442 if ( strlen( $key ) < 31 ) {
1443 throw new MWException( "Invalid storage key '$key'." );
1444 }
1445 $path = '';
1446 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1447 $path .= $key[$i] . '/';
1448 }
1449
1450 return $path;
1451 }
1452
1453 /**
1454 * If a path is a virtual URL, resolve it to a storage path.
1455 * Otherwise, just return the path as it is.
1456 *
1457 * @param string $path
1458 * @return string
1459 * @throws MWException
1460 */
1461 protected function resolveToStoragePath( $path ) {
1462 if ( $this->isVirtualUrl( $path ) ) {
1463 return $this->resolveVirtualUrl( $path );
1464 }
1465
1466 return $path;
1467 }
1468
1469 /**
1470 * Get a local FS copy of a file with a given virtual URL/storage path.
1471 * Temporary files may be purged when the file object falls out of scope.
1472 *
1473 * @param string $virtualUrl
1474 * @return TempFSFile|null Returns null on failure
1475 */
1476 public function getLocalCopy( $virtualUrl ) {
1477 $path = $this->resolveToStoragePath( $virtualUrl );
1478
1479 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1480 }
1481
1482 /**
1483 * Get a local FS file with a given virtual URL/storage path.
1484 * The file is either an original or a copy. It should not be changed.
1485 * Temporary files may be purged when the file object falls out of scope.
1486 *
1487 * @param string $virtualUrl
1488 * @return FSFile|null Returns null on failure.
1489 */
1490 public function getLocalReference( $virtualUrl ) {
1491 $path = $this->resolveToStoragePath( $virtualUrl );
1492
1493 return $this->backend->getLocalReference( array( 'src' => $path ) );
1494 }
1495
1496 /**
1497 * Get properties of a file with a given virtual URL/storage path.
1498 * Properties should ultimately be obtained via FSFile::getProps().
1499 *
1500 * @param string $virtualUrl
1501 * @return Array
1502 */
1503 public function getFileProps( $virtualUrl ) {
1504 $path = $this->resolveToStoragePath( $virtualUrl );
1505
1506 return $this->backend->getFileProps( array( 'src' => $path ) );
1507 }
1508
1509 /**
1510 * Get the timestamp of a file with a given virtual URL/storage path
1511 *
1512 * @param string $virtualUrl
1513 * @return string|bool False on failure
1514 */
1515 public function getFileTimestamp( $virtualUrl ) {
1516 $path = $this->resolveToStoragePath( $virtualUrl );
1517
1518 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1519 }
1520
1521 /**
1522 * Get the size of a file with a given virtual URL/storage path
1523 *
1524 * @param string $virtualUrl
1525 * @return integer|bool False on failure
1526 */
1527 public function getFileSize( $virtualUrl ) {
1528 $path = $this->resolveToStoragePath( $virtualUrl );
1529
1530 return $this->backend->getFileSize( array( 'src' => $path ) );
1531 }
1532
1533 /**
1534 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1535 *
1536 * @param string $virtualUrl
1537 * @return string|bool
1538 */
1539 public function getFileSha1( $virtualUrl ) {
1540 $path = $this->resolveToStoragePath( $virtualUrl );
1541
1542 return $this->backend->getFileSha1Base36( array( 'src' => $path ) );
1543 }
1544
1545 /**
1546 * Attempt to stream a file with the given virtual URL/storage path
1547 *
1548 * @param string $virtualUrl
1549 * @param array $headers Additional HTTP headers to send on success
1550 * @return bool Success
1551 */
1552 public function streamFile( $virtualUrl, $headers = array() ) {
1553 $path = $this->resolveToStoragePath( $virtualUrl );
1554 $params = array( 'src' => $path, 'headers' => $headers );
1555
1556 return $this->backend->streamFile( $params )->isOK();
1557 }
1558
1559 /**
1560 * Call a callback function for every public regular file in the repository.
1561 * This only acts on the current version of files, not any old versions.
1562 * May use either the database or the filesystem.
1563 *
1564 * @param array|string $callback
1565 * @return void
1566 */
1567 public function enumFiles( $callback ) {
1568 $this->enumFilesInStorage( $callback );
1569 }
1570
1571 /**
1572 * Call a callback function for every public file in the repository.
1573 * May use either the database or the filesystem.
1574 *
1575 * @param array|string $callback
1576 * @return void
1577 */
1578 protected function enumFilesInStorage( $callback ) {
1579 $publicRoot = $this->getZonePath( 'public' );
1580 $numDirs = 1 << ( $this->hashLevels * 4 );
1581 // Use a priori assumptions about directory structure
1582 // to reduce the tree height of the scanning process.
1583 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1584 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1585 $path = $publicRoot;
1586 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1587 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1588 }
1589 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1590 foreach ( $iterator as $name ) {
1591 // Each item returned is a public file
1592 call_user_func( $callback, "{$path}/{$name}" );
1593 }
1594 }
1595 }
1596
1597 /**
1598 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1599 *
1600 * @param $filename string
1601 * @return bool
1602 */
1603 public function validateFilename( $filename ) {
1604 if ( strval( $filename ) == '' ) {
1605 return false;
1606 }
1607
1608 return FileBackend::isPathTraversalFree( $filename );
1609 }
1610
1611 /**
1612 * Get a callback function to use for cleaning error message parameters
1613 *
1614 * @return array
1615 */
1616 function getErrorCleanupFunction() {
1617 switch ( $this->pathDisclosureProtection ) {
1618 case 'none':
1619 case 'simple': // b/c
1620 $callback = array( $this, 'passThrough' );
1621 break;
1622 default: // 'paranoid'
1623 $callback = array( $this, 'paranoidClean' );
1624 }
1625 return $callback;
1626 }
1627
1628 /**
1629 * Path disclosure protection function
1630 *
1631 * @param string $param
1632 * @return string
1633 */
1634 function paranoidClean( $param ) {
1635 return '[hidden]';
1636 }
1637
1638 /**
1639 * Path disclosure protection function
1640 *
1641 * @param string $param
1642 * @return string
1643 */
1644 function passThrough( $param ) {
1645 return $param;
1646 }
1647
1648 /**
1649 * Create a new fatal error
1650 *
1651 * @param $message
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 null|string $value
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 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 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 }