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