Merge "Fix most PHP CodeSniffer warnings in includes/api"
[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 # We use "Image:" as the canonical namespace for
757 # compatibility across all MediaWiki versions.
758 return str_replace( '$1',
759 "Image:$encName", $this->articleUrl );
760 }
761 if ( !is_null( $this->scriptDirUrl ) ) {
762 # "http://example.com/w"
763 # We use "Image:" as the canonical namespace for
764 # compatibility across all MediaWiki versions,
765 # and just sort of hope index.php is right. ;)
766 return $this->makeUrl( "title=Image:$encName" );
767 }
768
769 return false;
770 }
771
772 /**
773 * Get the URL of the content-only fragment of the description page. For
774 * MediaWiki this means action=render. This should only be called by the
775 * repository's file class, since it may return invalid results. User code
776 * should use File::getDescriptionText().
777 *
778 * @param string $name Name of image to fetch
779 * @param string $lang Language to fetch it in, if any.
780 * @return string
781 */
782 public function getDescriptionRenderUrl( $name, $lang = null ) {
783 $query = 'action=render';
784 if ( !is_null( $lang ) ) {
785 $query .= '&uselang=' . $lang;
786 }
787 if ( isset( $this->scriptDirUrl ) ) {
788 return $this->makeUrl(
789 'title=' .
790 wfUrlencode( 'Image:' . $name ) .
791 "&$query" );
792 } else {
793 $descUrl = $this->getDescriptionUrl( $name );
794 if ( $descUrl ) {
795 return wfAppendQuery( $descUrl, $query );
796 } else {
797 return false;
798 }
799 }
800 }
801
802 /**
803 * Get the URL of the stylesheet to apply to description pages
804 *
805 * @return string|bool False on failure
806 */
807 public function getDescriptionStylesheetUrl() {
808 if ( isset( $this->scriptDirUrl ) ) {
809 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
810 wfArrayToCgi( Skin::getDynamicStylesheetQuery() ) );
811 }
812
813 return false;
814 }
815
816 /**
817 * Store a file to a given destination.
818 *
819 * @param string $srcPath Source file system path, storage path, or virtual URL
820 * @param string $dstZone Destination zone
821 * @param string $dstRel Destination relative path
822 * @param int $flags Bitwise combination of the following flags:
823 * self::DELETE_SOURCE Delete the source file after upload
824 * self::OVERWRITE Overwrite an existing destination file instead of failing
825 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
826 * same contents as the source
827 * self::SKIP_LOCKING Skip any file locking when doing the store
828 * @return FileRepoStatus
829 */
830 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
831 $this->assertWritableRepo(); // fail out if read-only
832
833 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
834 if ( $status->successCount == 0 ) {
835 $status->ok = false;
836 }
837
838 return $status;
839 }
840
841 /**
842 * Store a batch of files
843 *
844 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
845 * @param int $flags Bitwise combination of the following flags:
846 * self::DELETE_SOURCE Delete the source file after upload
847 * self::OVERWRITE Overwrite an existing destination file instead of failing
848 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
849 * same contents as the source
850 * self::SKIP_LOCKING Skip any file locking when doing the store
851 * @throws MWException
852 * @return FileRepoStatus
853 */
854 public function storeBatch( array $triplets, $flags = 0 ) {
855 $this->assertWritableRepo(); // fail out if read-only
856
857 $status = $this->newGood();
858 $backend = $this->backend; // convenience
859
860 $operations = array();
861 $sourceFSFilesToDelete = array(); // cleanup for disk source files
862 // Validate each triplet and get the store operation...
863 foreach ( $triplets as $triplet ) {
864 list( $srcPath, $dstZone, $dstRel ) = $triplet;
865 wfDebug( __METHOD__
866 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
867 );
868
869 // Resolve destination path
870 $root = $this->getZonePath( $dstZone );
871 if ( !$root ) {
872 throw new MWException( "Invalid zone: $dstZone" );
873 }
874 if ( !$this->validateFilename( $dstRel ) ) {
875 throw new MWException( 'Validation error in $dstRel' );
876 }
877 $dstPath = "$root/$dstRel";
878 $dstDir = dirname( $dstPath );
879 // Create destination directories for this triplet
880 if ( !$this->initDirectory( $dstDir )->isOK() ) {
881 return $this->newFatal( 'directorycreateerror', $dstDir );
882 }
883
884 // Resolve source to a storage path if virtual
885 $srcPath = $this->resolveToStoragePath( $srcPath );
886
887 // Get the appropriate file operation
888 if ( FileBackend::isStoragePath( $srcPath ) ) {
889 $opName = ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy';
890 } else {
891 $opName = 'store';
892 if ( $flags & self::DELETE_SOURCE ) {
893 $sourceFSFilesToDelete[] = $srcPath;
894 }
895 }
896 $operations[] = array(
897 'op' => $opName,
898 'src' => $srcPath,
899 'dst' => $dstPath,
900 'overwrite' => $flags & self::OVERWRITE,
901 'overwriteSame' => $flags & self::OVERWRITE_SAME,
902 );
903 }
904
905 // Execute the store operation for each triplet
906 $opts = array( 'force' => true );
907 if ( $flags & self::SKIP_LOCKING ) {
908 $opts['nonLocking'] = true;
909 }
910 $status->merge( $backend->doOperations( $operations, $opts ) );
911 // Cleanup for disk source files...
912 foreach ( $sourceFSFilesToDelete as $file ) {
913 MediaWiki\suppressWarnings();
914 unlink( $file ); // FS cleanup
915 MediaWiki\restoreWarnings();
916 }
917
918 return $status;
919 }
920
921 /**
922 * Deletes a batch of files.
923 * Each file can be a (zone, rel) pair, virtual url, storage path.
924 * It will try to delete each file, but ignores any errors that may occur.
925 *
926 * @param array $files List of files to delete
927 * @param int $flags Bitwise combination of the following flags:
928 * self::SKIP_LOCKING Skip any file locking when doing the deletions
929 * @return FileRepoStatus
930 */
931 public function cleanupBatch( array $files, $flags = 0 ) {
932 $this->assertWritableRepo(); // fail out if read-only
933
934 $status = $this->newGood();
935
936 $operations = array();
937 foreach ( $files as $path ) {
938 if ( is_array( $path ) ) {
939 // This is a pair, extract it
940 list( $zone, $rel ) = $path;
941 $path = $this->getZonePath( $zone ) . "/$rel";
942 } else {
943 // Resolve source to a storage path if virtual
944 $path = $this->resolveToStoragePath( $path );
945 }
946 $operations[] = array( 'op' => 'delete', 'src' => $path );
947 }
948 // Actually delete files from storage...
949 $opts = array( 'force' => true );
950 if ( $flags & self::SKIP_LOCKING ) {
951 $opts['nonLocking'] = true;
952 }
953 $status->merge( $this->backend->doOperations( $operations, $opts ) );
954
955 return $status;
956 }
957
958 /**
959 * Import a file from the local file system into the repo.
960 * This does no locking nor journaling and overrides existing files.
961 * This function can be used to write to otherwise read-only foreign repos.
962 * This is intended for copying generated thumbnails into the repo.
963 *
964 * @param string $src Source file system path, storage path, or virtual URL
965 * @param string $dst Virtual URL or storage path
966 * @param array|string|null $options An array consisting of a key named headers
967 * listing extra headers. If a string, taken as content-disposition header.
968 * (Support for array of options new in 1.23)
969 * @return FileRepoStatus
970 */
971 final public function quickImport( $src, $dst, $options = null ) {
972 return $this->quickImportBatch( array( array( $src, $dst, $options ) ) );
973 }
974
975 /**
976 * Purge a file from the repo. This does no locking nor journaling.
977 * This function can be used to write to otherwise read-only foreign repos.
978 * This is intended for purging thumbnails.
979 *
980 * @param string $path Virtual URL or storage path
981 * @return FileRepoStatus
982 */
983 final public function quickPurge( $path ) {
984 return $this->quickPurgeBatch( array( $path ) );
985 }
986
987 /**
988 * Deletes a directory if empty.
989 * This function can be used to write to otherwise read-only foreign repos.
990 *
991 * @param string $dir Virtual URL (or storage path) of directory to clean
992 * @return Status
993 */
994 public function quickCleanDir( $dir ) {
995 $status = $this->newGood();
996 $status->merge( $this->backend->clean(
997 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
998
999 return $status;
1000 }
1001
1002 /**
1003 * Import a batch of files from the local file system into the repo.
1004 * This does no locking nor journaling and overrides existing files.
1005 * This function can be used to write to otherwise read-only foreign repos.
1006 * This is intended for copying generated thumbnails into the repo.
1007 *
1008 * All path parameters may be a file system path, storage path, or virtual URL.
1009 * When "headers" are given they are used as HTTP headers if supported.
1010 *
1011 * @param array $triples List of (source path, destination path, disposition)
1012 * @return FileRepoStatus
1013 */
1014 public function quickImportBatch( array $triples ) {
1015 $status = $this->newGood();
1016 $operations = array();
1017 foreach ( $triples as $triple ) {
1018 list( $src, $dst ) = $triple;
1019 $src = $this->resolveToStoragePath( $src );
1020 $dst = $this->resolveToStoragePath( $dst );
1021
1022 if ( !isset( $triple[2] ) ) {
1023 $headers = array();
1024 } elseif ( is_string( $triple[2] ) ) {
1025 // back-compat
1026 $headers = array( 'Content-Disposition' => $triple[2] );
1027 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1028 $headers = $triple[2]['headers'];
1029 }
1030 // @fixme: $headers might not be defined
1031 $operations[] = array(
1032 'op' => FileBackend::isStoragePath( $src ) ? 'copy' : 'store',
1033 'src' => $src,
1034 'dst' => $dst,
1035 'headers' => $headers
1036 );
1037 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1038 }
1039 $status->merge( $this->backend->doQuickOperations( $operations ) );
1040
1041 return $status;
1042 }
1043
1044 /**
1045 * Purge a batch of files from the repo.
1046 * This function can be used to write to otherwise read-only foreign repos.
1047 * This does no locking nor journaling and is intended for purging thumbnails.
1048 *
1049 * @param array $paths List of virtual URLs or storage paths
1050 * @return FileRepoStatus
1051 */
1052 public function quickPurgeBatch( array $paths ) {
1053 $status = $this->newGood();
1054 $operations = array();
1055 foreach ( $paths as $path ) {
1056 $operations[] = array(
1057 'op' => 'delete',
1058 'src' => $this->resolveToStoragePath( $path ),
1059 'ignoreMissingSource' => true
1060 );
1061 }
1062 $status->merge( $this->backend->doQuickOperations( $operations ) );
1063
1064 return $status;
1065 }
1066
1067 /**
1068 * Pick a random name in the temp zone and store a file to it.
1069 * Returns a FileRepoStatus object with the file Virtual URL in the value,
1070 * file can later be disposed using FileRepo::freeTemp().
1071 *
1072 * @param string $originalName The base name of the file as specified
1073 * by the user. The file extension will be maintained.
1074 * @param string $srcPath The current location of the file.
1075 * @return FileRepoStatus Object with the URL in the value.
1076 */
1077 public function storeTemp( $originalName, $srcPath ) {
1078 $this->assertWritableRepo(); // fail out if read-only
1079
1080 $date = MWTimestamp::getInstance()->format( 'YmdHis' );
1081 $hashPath = $this->getHashPath( $originalName );
1082 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1083 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1084
1085 $result = $this->quickImport( $srcPath, $virtualUrl );
1086 $result->value = $virtualUrl;
1087
1088 return $result;
1089 }
1090
1091 /**
1092 * Remove a temporary file or mark it for garbage collection
1093 *
1094 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1095 * @return bool True on success, false on failure
1096 */
1097 public function freeTemp( $virtualUrl ) {
1098 $this->assertWritableRepo(); // fail out if read-only
1099
1100 $temp = $this->getVirtualUrl( 'temp' );
1101 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
1102 wfDebug( __METHOD__ . ": Invalid temp virtual URL\n" );
1103
1104 return false;
1105 }
1106
1107 return $this->quickPurge( $virtualUrl )->isOK();
1108 }
1109
1110 /**
1111 * Concatenate a list of temporary files into a target file location.
1112 *
1113 * @param array $srcPaths Ordered list of source virtual URLs/storage paths
1114 * @param string $dstPath Target file system path
1115 * @param int $flags Bitwise combination of the following flags:
1116 * self::DELETE_SOURCE Delete the source files
1117 * @return FileRepoStatus
1118 */
1119 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1120 $this->assertWritableRepo(); // fail out if read-only
1121
1122 $status = $this->newGood();
1123
1124 $sources = array();
1125 foreach ( $srcPaths as $srcPath ) {
1126 // Resolve source to a storage path if virtual
1127 $source = $this->resolveToStoragePath( $srcPath );
1128 $sources[] = $source; // chunk to merge
1129 }
1130
1131 // Concatenate the chunks into one FS file
1132 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
1133 $status->merge( $this->backend->concatenate( $params ) );
1134 if ( !$status->isOK() ) {
1135 return $status;
1136 }
1137
1138 // Delete the sources if required
1139 if ( $flags & self::DELETE_SOURCE ) {
1140 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1141 }
1142
1143 // Make sure status is OK, despite any quickPurgeBatch() fatals
1144 $status->setResult( true );
1145
1146 return $status;
1147 }
1148
1149 /**
1150 * Copy or move a file either from a storage path, virtual URL,
1151 * or file system path, into this repository at the specified destination location.
1152 *
1153 * Returns a FileRepoStatus object. On success, the value contains "new" or
1154 * "archived", to indicate whether the file was new with that name.
1155 *
1156 * Options to $options include:
1157 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1158 *
1159 * @param string $srcPath The source file system path, storage path, or URL
1160 * @param string $dstRel The destination relative path
1161 * @param string $archiveRel The relative path where the existing file is to
1162 * be archived, if there is one. Relative to the public zone root.
1163 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1164 * that the source file should be deleted if possible
1165 * @param array $options Optional additional parameters
1166 * @return FileRepoStatus
1167 */
1168 public function publish(
1169 $srcPath, $dstRel, $archiveRel, $flags = 0, array $options = array()
1170 ) {
1171 $this->assertWritableRepo(); // fail out if read-only
1172
1173 $status = $this->publishBatch(
1174 array( array( $srcPath, $dstRel, $archiveRel, $options ) ), $flags );
1175 if ( $status->successCount == 0 ) {
1176 $status->ok = false;
1177 }
1178 if ( isset( $status->value[0] ) ) {
1179 $status->value = $status->value[0];
1180 } else {
1181 $status->value = false;
1182 }
1183
1184 return $status;
1185 }
1186
1187 /**
1188 * Publish a batch of files
1189 *
1190 * @param array $ntuples (source, dest, archive) triplets or
1191 * (source, dest, archive, options) 4-tuples as per publish().
1192 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1193 * that the source files should be deleted if possible
1194 * @throws MWException
1195 * @return FileRepoStatus
1196 */
1197 public function publishBatch( array $ntuples, $flags = 0 ) {
1198 $this->assertWritableRepo(); // fail out if read-only
1199
1200 $backend = $this->backend; // convenience
1201 // Try creating directories
1202 $status = $this->initZones( 'public' );
1203 if ( !$status->isOK() ) {
1204 return $status;
1205 }
1206
1207 $status = $this->newGood( array() );
1208
1209 $operations = array();
1210 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1211 // Validate each triplet and get the store operation...
1212 foreach ( $ntuples as $ntuple ) {
1213 list( $srcPath, $dstRel, $archiveRel ) = $ntuple;
1214 $options = isset( $ntuple[3] ) ? $ntuple[3] : array();
1215 // Resolve source to a storage path if virtual
1216 $srcPath = $this->resolveToStoragePath( $srcPath );
1217 if ( !$this->validateFilename( $dstRel ) ) {
1218 throw new MWException( 'Validation error in $dstRel' );
1219 }
1220 if ( !$this->validateFilename( $archiveRel ) ) {
1221 throw new MWException( 'Validation error in $archiveRel' );
1222 }
1223
1224 $publicRoot = $this->getZonePath( 'public' );
1225 $dstPath = "$publicRoot/$dstRel";
1226 $archivePath = "$publicRoot/$archiveRel";
1227
1228 $dstDir = dirname( $dstPath );
1229 $archiveDir = dirname( $archivePath );
1230 // Abort immediately on directory creation errors since they're likely to be repetitive
1231 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1232 return $this->newFatal( 'directorycreateerror', $dstDir );
1233 }
1234 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1235 return $this->newFatal( 'directorycreateerror', $archiveDir );
1236 }
1237
1238 // Set any desired headers to be use in GET/HEAD responses
1239 $headers = isset( $options['headers'] ) ? $options['headers'] : array();
1240
1241 // Archive destination file if it exists.
1242 // This will check if the archive file also exists and fail if does.
1243 // This is a sanity check to avoid data loss. On Windows and Linux,
1244 // copy() will overwrite, so the existence check is vulnerable to
1245 // race conditions unless a functioning LockManager is used.
1246 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1247 $operations[] = array(
1248 'op' => 'copy',
1249 'src' => $dstPath,
1250 'dst' => $archivePath,
1251 'ignoreMissingSource' => true
1252 );
1253
1254 // Copy (or move) the source file to the destination
1255 if ( FileBackend::isStoragePath( $srcPath ) ) {
1256 if ( $flags & self::DELETE_SOURCE ) {
1257 $operations[] = array(
1258 'op' => 'move',
1259 'src' => $srcPath,
1260 'dst' => $dstPath,
1261 'overwrite' => true, // replace current
1262 'headers' => $headers
1263 );
1264 } else {
1265 $operations[] = array(
1266 'op' => 'copy',
1267 'src' => $srcPath,
1268 'dst' => $dstPath,
1269 'overwrite' => true, // replace current
1270 'headers' => $headers
1271 );
1272 }
1273 } else { // FS source path
1274 $operations[] = array(
1275 'op' => 'store',
1276 'src' => $srcPath,
1277 'dst' => $dstPath,
1278 'overwrite' => true, // replace current
1279 'headers' => $headers
1280 );
1281 if ( $flags & self::DELETE_SOURCE ) {
1282 $sourceFSFilesToDelete[] = $srcPath;
1283 }
1284 }
1285 }
1286
1287 // Execute the operations for each triplet
1288 $status->merge( $backend->doOperations( $operations ) );
1289 // Find out which files were archived...
1290 foreach ( $ntuples as $i => $ntuple ) {
1291 list( , , $archiveRel ) = $ntuple;
1292 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1293 if ( $this->fileExists( $archivePath ) ) {
1294 $status->value[$i] = 'archived';
1295 } else {
1296 $status->value[$i] = 'new';
1297 }
1298 }
1299 // Cleanup for disk source files...
1300 foreach ( $sourceFSFilesToDelete as $file ) {
1301 MediaWiki\suppressWarnings();
1302 unlink( $file ); // FS cleanup
1303 MediaWiki\restoreWarnings();
1304 }
1305
1306 return $status;
1307 }
1308
1309 /**
1310 * Creates a directory with the appropriate zone permissions.
1311 * Callers are responsible for doing read-only and "writable repo" checks.
1312 *
1313 * @param string $dir Virtual URL (or storage path) of directory to clean
1314 * @return Status
1315 */
1316 protected function initDirectory( $dir ) {
1317 $path = $this->resolveToStoragePath( $dir );
1318 list( , $container, ) = FileBackend::splitStoragePath( $path );
1319
1320 $params = array( 'dir' => $path );
1321 if ( $this->isPrivate
1322 || $container === $this->zones['deleted']['container']
1323 || $container === $this->zones['temp']['container']
1324 ) {
1325 # Take all available measures to prevent web accessibility of new deleted
1326 # directories, in case the user has not configured offline storage
1327 $params = array( 'noAccess' => true, 'noListing' => true ) + $params;
1328 }
1329
1330 return $this->backend->prepare( $params );
1331 }
1332
1333 /**
1334 * Deletes a directory if empty.
1335 *
1336 * @param string $dir Virtual URL (or storage path) of directory to clean
1337 * @return Status
1338 */
1339 public function cleanDir( $dir ) {
1340 $this->assertWritableRepo(); // fail out if read-only
1341
1342 $status = $this->newGood();
1343 $status->merge( $this->backend->clean(
1344 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1345
1346 return $status;
1347 }
1348
1349 /**
1350 * Checks existence of a a file
1351 *
1352 * @param string $file Virtual URL (or storage path) of file to check
1353 * @return bool
1354 */
1355 public function fileExists( $file ) {
1356 $result = $this->fileExistsBatch( array( $file ) );
1357
1358 return $result[0];
1359 }
1360
1361 /**
1362 * Checks existence of an array of files.
1363 *
1364 * @param array $files Virtual URLs (or storage paths) of files to check
1365 * @return array Map of files and existence flags, or false
1366 */
1367 public function fileExistsBatch( array $files ) {
1368 $paths = array_map( array( $this, 'resolveToStoragePath' ), $files );
1369 $this->backend->preloadFileStat( array( 'srcs' => $paths ) );
1370
1371 $result = array();
1372 foreach ( $files as $key => $file ) {
1373 $path = $this->resolveToStoragePath( $file );
1374 $result[$key] = $this->backend->fileExists( array( 'src' => $path ) );
1375 }
1376
1377 return $result;
1378 }
1379
1380 /**
1381 * Move a file to the deletion archive.
1382 * If no valid deletion archive exists, this may either delete the file
1383 * or throw an exception, depending on the preference of the repository
1384 *
1385 * @param mixed $srcRel Relative path for the file to be deleted
1386 * @param mixed $archiveRel Relative path for the archive location.
1387 * Relative to a private archive directory.
1388 * @return FileRepoStatus
1389 */
1390 public function delete( $srcRel, $archiveRel ) {
1391 $this->assertWritableRepo(); // fail out if read-only
1392
1393 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1394 }
1395
1396 /**
1397 * Move a group of files to the deletion archive.
1398 *
1399 * If no valid deletion archive is configured, this may either delete the
1400 * file or throw an exception, depending on the preference of the repository.
1401 *
1402 * The overwrite policy is determined by the repository -- currently LocalRepo
1403 * assumes a naming scheme in the deleted zone based on content hash, as
1404 * opposed to the public zone which is assumed to be unique.
1405 *
1406 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1407 * is a two-element array containing the source file path relative to the
1408 * public root in the first element, and the archive file path relative
1409 * to the deleted zone root in the second element.
1410 * @throws MWException
1411 * @return FileRepoStatus
1412 */
1413 public function deleteBatch( array $sourceDestPairs ) {
1414 $this->assertWritableRepo(); // fail out if read-only
1415
1416 // Try creating directories
1417 $status = $this->initZones( array( 'public', 'deleted' ) );
1418 if ( !$status->isOK() ) {
1419 return $status;
1420 }
1421
1422 $status = $this->newGood();
1423
1424 $backend = $this->backend; // convenience
1425 $operations = array();
1426 // Validate filenames and create archive directories
1427 foreach ( $sourceDestPairs as $pair ) {
1428 list( $srcRel, $archiveRel ) = $pair;
1429 if ( !$this->validateFilename( $srcRel ) ) {
1430 throw new MWException( __METHOD__ . ':Validation error in $srcRel' );
1431 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1432 throw new MWException( __METHOD__ . ':Validation error in $archiveRel' );
1433 }
1434
1435 $publicRoot = $this->getZonePath( 'public' );
1436 $srcPath = "{$publicRoot}/$srcRel";
1437
1438 $deletedRoot = $this->getZonePath( 'deleted' );
1439 $archivePath = "{$deletedRoot}/{$archiveRel}";
1440 $archiveDir = dirname( $archivePath ); // does not touch FS
1441
1442 // Create destination directories
1443 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1444 return $this->newFatal( 'directorycreateerror', $archiveDir );
1445 }
1446
1447 $operations[] = array(
1448 'op' => 'move',
1449 'src' => $srcPath,
1450 'dst' => $archivePath,
1451 // We may have 2+ identical files being deleted,
1452 // all of which will map to the same destination file
1453 'overwriteSame' => true // also see bug 31792
1454 );
1455 }
1456
1457 // Move the files by execute the operations for each pair.
1458 // We're now committed to returning an OK result, which will
1459 // lead to the files being moved in the DB also.
1460 $opts = array( 'force' => true );
1461 $status->merge( $backend->doOperations( $operations, $opts ) );
1462
1463 return $status;
1464 }
1465
1466 /**
1467 * Delete files in the deleted directory if they are not referenced in the filearchive table
1468 *
1469 * STUB
1470 * @param array $storageKeys
1471 */
1472 public function cleanupDeletedBatch( array $storageKeys ) {
1473 $this->assertWritableRepo();
1474 }
1475
1476 /**
1477 * Get a relative path for a deletion archive key,
1478 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1479 *
1480 * @param string $key
1481 * @throws MWException
1482 * @return string
1483 */
1484 public function getDeletedHashPath( $key ) {
1485 if ( strlen( $key ) < 31 ) {
1486 throw new MWException( "Invalid storage key '$key'." );
1487 }
1488 $path = '';
1489 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1490 $path .= $key[$i] . '/';
1491 }
1492
1493 return $path;
1494 }
1495
1496 /**
1497 * If a path is a virtual URL, resolve it to a storage path.
1498 * Otherwise, just return the path as it is.
1499 *
1500 * @param string $path
1501 * @return string
1502 * @throws MWException
1503 */
1504 protected function resolveToStoragePath( $path ) {
1505 if ( $this->isVirtualUrl( $path ) ) {
1506 return $this->resolveVirtualUrl( $path );
1507 }
1508
1509 return $path;
1510 }
1511
1512 /**
1513 * Get a local FS copy of a file with a given virtual URL/storage path.
1514 * Temporary files may be purged when the file object falls out of scope.
1515 *
1516 * @param string $virtualUrl
1517 * @return TempFSFile|null Returns null on failure
1518 */
1519 public function getLocalCopy( $virtualUrl ) {
1520 $path = $this->resolveToStoragePath( $virtualUrl );
1521
1522 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1523 }
1524
1525 /**
1526 * Get a local FS file with a given virtual URL/storage path.
1527 * The file is either an original or a copy. It should not be changed.
1528 * Temporary files may be purged when the file object falls out of scope.
1529 *
1530 * @param string $virtualUrl
1531 * @return FSFile|null Returns null on failure.
1532 */
1533 public function getLocalReference( $virtualUrl ) {
1534 $path = $this->resolveToStoragePath( $virtualUrl );
1535
1536 return $this->backend->getLocalReference( array( 'src' => $path ) );
1537 }
1538
1539 /**
1540 * Get properties of a file with a given virtual URL/storage path.
1541 * Properties should ultimately be obtained via FSFile::getProps().
1542 *
1543 * @param string $virtualUrl
1544 * @return array
1545 */
1546 public function getFileProps( $virtualUrl ) {
1547 $path = $this->resolveToStoragePath( $virtualUrl );
1548
1549 return $this->backend->getFileProps( array( 'src' => $path ) );
1550 }
1551
1552 /**
1553 * Get the timestamp of a file with a given virtual URL/storage path
1554 *
1555 * @param string $virtualUrl
1556 * @return string|bool False on failure
1557 */
1558 public function getFileTimestamp( $virtualUrl ) {
1559 $path = $this->resolveToStoragePath( $virtualUrl );
1560
1561 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1562 }
1563
1564 /**
1565 * Get the size of a file with a given virtual URL/storage path
1566 *
1567 * @param string $virtualUrl
1568 * @return int|bool False on failure
1569 */
1570 public function getFileSize( $virtualUrl ) {
1571 $path = $this->resolveToStoragePath( $virtualUrl );
1572
1573 return $this->backend->getFileSize( array( 'src' => $path ) );
1574 }
1575
1576 /**
1577 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1578 *
1579 * @param string $virtualUrl
1580 * @return string|bool
1581 */
1582 public function getFileSha1( $virtualUrl ) {
1583 $path = $this->resolveToStoragePath( $virtualUrl );
1584
1585 return $this->backend->getFileSha1Base36( array( 'src' => $path ) );
1586 }
1587
1588 /**
1589 * Attempt to stream a file with the given virtual URL/storage path
1590 *
1591 * @param string $virtualUrl
1592 * @param array $headers Additional HTTP headers to send on success
1593 * @return bool Success
1594 */
1595 public function streamFile( $virtualUrl, $headers = array() ) {
1596 $path = $this->resolveToStoragePath( $virtualUrl );
1597 $params = array( 'src' => $path, 'headers' => $headers );
1598
1599 return $this->backend->streamFile( $params )->isOK();
1600 }
1601
1602 /**
1603 * Call a callback function for every public regular file in the repository.
1604 * This only acts on the current version of files, not any old versions.
1605 * May use either the database or the filesystem.
1606 *
1607 * @param callable $callback
1608 * @return void
1609 */
1610 public function enumFiles( $callback ) {
1611 $this->enumFilesInStorage( $callback );
1612 }
1613
1614 /**
1615 * Call a callback function for every public file in the repository.
1616 * May use either the database or the filesystem.
1617 *
1618 * @param callable $callback
1619 * @return void
1620 */
1621 protected function enumFilesInStorage( $callback ) {
1622 $publicRoot = $this->getZonePath( 'public' );
1623 $numDirs = 1 << ( $this->hashLevels * 4 );
1624 // Use a priori assumptions about directory structure
1625 // to reduce the tree height of the scanning process.
1626 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1627 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1628 $path = $publicRoot;
1629 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1630 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1631 }
1632 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1633 foreach ( $iterator as $name ) {
1634 // Each item returned is a public file
1635 call_user_func( $callback, "{$path}/{$name}" );
1636 }
1637 }
1638 }
1639
1640 /**
1641 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1642 *
1643 * @param string $filename
1644 * @return bool
1645 */
1646 public function validateFilename( $filename ) {
1647 if ( strval( $filename ) == '' ) {
1648 return false;
1649 }
1650
1651 return FileBackend::isPathTraversalFree( $filename );
1652 }
1653
1654 /**
1655 * Get a callback function to use for cleaning error message parameters
1656 *
1657 * @return array
1658 */
1659 function getErrorCleanupFunction() {
1660 switch ( $this->pathDisclosureProtection ) {
1661 case 'none':
1662 case 'simple': // b/c
1663 $callback = array( $this, 'passThrough' );
1664 break;
1665 default: // 'paranoid'
1666 $callback = array( $this, 'paranoidClean' );
1667 }
1668 return $callback;
1669 }
1670
1671 /**
1672 * Path disclosure protection function
1673 *
1674 * @param string $param
1675 * @return string
1676 */
1677 function paranoidClean( $param ) {
1678 return '[hidden]';
1679 }
1680
1681 /**
1682 * Path disclosure protection function
1683 *
1684 * @param string $param
1685 * @return string
1686 */
1687 function passThrough( $param ) {
1688 return $param;
1689 }
1690
1691 /**
1692 * Create a new fatal error
1693 *
1694 * @param string $message
1695 * @return Status
1696 */
1697 public function newFatal( $message /*, parameters...*/ ) {
1698 $status = call_user_func_array( array( 'Status', 'newFatal' ), func_get_args() );
1699 $status->cleanCallback = $this->getErrorCleanupFunction();
1700
1701 return $status;
1702 }
1703
1704 /**
1705 * Create a new good result
1706 *
1707 * @param null|string $value
1708 * @return Status
1709 */
1710 public function newGood( $value = null ) {
1711 $status = Status::newGood( $value );
1712 $status->cleanCallback = $this->getErrorCleanupFunction();
1713
1714 return $status;
1715 }
1716
1717 /**
1718 * Checks if there is a redirect named as $title. If there is, return the
1719 * title object. If not, return false.
1720 * STUB
1721 *
1722 * @param Title $title Title of image
1723 * @return bool
1724 */
1725 public function checkRedirect( Title $title ) {
1726 return false;
1727 }
1728
1729 /**
1730 * Invalidates image redirect cache related to that image
1731 * Doesn't do anything for repositories that don't support image redirects.
1732 *
1733 * STUB
1734 * @param Title $title Title of image
1735 */
1736 public function invalidateImageRedirect( Title $title ) {
1737 }
1738
1739 /**
1740 * Get the human-readable name of the repo
1741 *
1742 * @return string
1743 */
1744 public function getDisplayName() {
1745 global $wgSitename;
1746
1747 if ( $this->isLocal() ) {
1748 return $wgSitename;
1749 }
1750
1751 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1752 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1753 }
1754
1755 /**
1756 * Get the portion of the file that contains the origin file name.
1757 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1758 *
1759 * @param string $name
1760 * @return string
1761 */
1762 public function nameForThumb( $name ) {
1763 if ( strlen( $name ) > $this->abbrvThreshold ) {
1764 $ext = FileBackend::extensionFromPath( $name );
1765 $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1766 }
1767
1768 return $name;
1769 }
1770
1771 /**
1772 * Returns true if this the local file repository.
1773 *
1774 * @return bool
1775 */
1776 public function isLocal() {
1777 return $this->getName() == 'local';
1778 }
1779
1780 /**
1781 * Get a key on the primary cache for this repository.
1782 * Returns false if the repository's cache is not accessible at this site.
1783 * The parameters are the parts of the key, as for wfMemcKey().
1784 *
1785 * STUB
1786 * @return bool
1787 */
1788 public function getSharedCacheKey( /*...*/ ) {
1789 return false;
1790 }
1791
1792 /**
1793 * Get a key for this repo in the local cache domain. These cache keys are
1794 * not shared with remote instances of the repo.
1795 * The parameters are the parts of the key, as for wfMemcKey().
1796 *
1797 * @return string
1798 */
1799 public function getLocalCacheKey( /*...*/ ) {
1800 $args = func_get_args();
1801 array_unshift( $args, 'filerepo', $this->getName() );
1802
1803 return call_user_func_array( 'wfMemcKey', $args );
1804 }
1805
1806 /**
1807 * Get a temporary private FileRepo associated with this repo.
1808 *
1809 * Files will be created in the temp zone of this repo.
1810 * It will have the same backend as this repo.
1811 *
1812 * @return TempFileRepo
1813 */
1814 public function getTempRepo() {
1815 return new TempFileRepo( array(
1816 'name' => "{$this->name}-temp",
1817 'backend' => $this->backend,
1818 'zones' => array(
1819 'public' => array(
1820 // Same place storeTemp() uses in the base repo, though
1821 // the path hashing is mismatched, which is annoying.
1822 'container' => $this->zones['temp']['container'],
1823 'directory' => $this->zones['temp']['directory']
1824 ),
1825 'thumb' => array(
1826 'container' => $this->zones['temp']['container'],
1827 'directory' => $this->zones['temp']['directory'] == ''
1828 ? 'thumb'
1829 : $this->zones['temp']['directory'] . '/thumb'
1830 ),
1831 'transcoded' => array(
1832 'container' => $this->zones['temp']['container'],
1833 'directory' => $this->zones['temp']['directory'] == ''
1834 ? 'transcoded'
1835 : $this->zones['temp']['directory'] . '/transcoded'
1836 )
1837 ),
1838 'hashLevels' => $this->hashLevels, // performance
1839 'isPrivate' => true // all in temp zone
1840 ) );
1841 }
1842
1843 /**
1844 * Get an UploadStash associated with this repo.
1845 *
1846 * @param User $user
1847 * @return UploadStash
1848 */
1849 public function getUploadStash( User $user = null ) {
1850 return new UploadStash( $this, $user );
1851 }
1852
1853 /**
1854 * Throw an exception if this repo is read-only by design.
1855 * This does not and should not check getReadOnlyReason().
1856 *
1857 * @return void
1858 * @throws MWException
1859 */
1860 protected function assertWritableRepo() {
1861 }
1862
1863 /**
1864 * Return information about the repository.
1865 *
1866 * @return array
1867 * @since 1.22
1868 */
1869 public function getInfo() {
1870 $ret = array(
1871 'name' => $this->getName(),
1872 'displayname' => $this->getDisplayName(),
1873 'rootUrl' => $this->getZoneUrl( 'public' ),
1874 'local' => $this->isLocal(),
1875 );
1876
1877 $optionalSettings = array(
1878 'url', 'thumbUrl', 'initialCapital', 'descBaseUrl', 'scriptDirUrl', 'articleUrl',
1879 'fetchDescription', 'descriptionCacheExpiry', 'scriptExtension', 'favicon'
1880 );
1881 foreach ( $optionalSettings as $k ) {
1882 if ( isset( $this->$k ) ) {
1883 $ret[$k] = $this->$k;
1884 }
1885 }
1886
1887 return $ret;
1888 }
1889
1890 /**
1891 * Returns whether or not storage is SHA-1 based
1892 * @return boolean
1893 */
1894 public function hasSha1Storage() {
1895 return $this->hasSha1Storage;
1896 }
1897 }
1898
1899 /**
1900 * FileRepo for temporary files created via FileRepo::getTempRepo()
1901 */
1902 class TempFileRepo extends FileRepo {
1903 public function getTempRepo() {
1904 throw new MWException( "Cannot get a temp repo from a temp repo." );
1905 }
1906 }