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