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