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