merge latest master.
[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 FS 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 File system path
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 * When "dispositions" are given they are used as Content-Disposition if supported.
887 *
888 * @param $pairs Array List of tuples (file system path, virtual URL/storage path, disposition)
889 * @return FileRepoStatus
890 */
891 public function quickImportBatch( array $pairs ) {
892 $status = $this->newGood();
893 $operations = array();
894 foreach ( $pairs as $pair ) {
895 list ( $src, $dst ) = $pair;
896 $dst = $this->resolveToStoragePath( $dst );
897 $operations[] = array(
898 'op' => 'store',
899 'src' => $src,
900 'dst' => $dst,
901 'disposition' => isset( $pair[2] ) ? $pair[2] : null
902 );
903 $status->merge( $this->initDirectory( dirname( $dst ) ) );
904 }
905 $status->merge( $this->backend->doQuickOperations( $operations ) );
906
907 return $status;
908 }
909
910 /**
911 * Purge a batch of files from the repo.
912 * This function can be used to write to otherwise read-only foreign repos.
913 * This does no locking nor journaling and is intended for purging thumbnails.
914 *
915 * @param $paths Array List of virtual URLs or storage paths
916 * @return FileRepoStatus
917 */
918 public function quickPurgeBatch( array $paths ) {
919 $status = $this->newGood();
920 $operations = array();
921 foreach ( $paths as $path ) {
922 $operations[] = array(
923 'op' => 'delete',
924 'src' => $this->resolveToStoragePath( $path ),
925 'ignoreMissingSource' => true
926 );
927 }
928 $status->merge( $this->backend->doQuickOperations( $operations ) );
929
930 return $status;
931 }
932
933 /**
934 * Pick a random name in the temp zone and store a file to it.
935 * Returns a FileRepoStatus object with the file Virtual URL in the value,
936 * file can later be disposed using FileRepo::freeTemp().
937 *
938 * @param $originalName String: the base name of the file as specified
939 * by the user. The file extension will be maintained.
940 * @param $srcPath String: the current location of the file.
941 * @return FileRepoStatus object with the URL in the value.
942 */
943 public function storeTemp( $originalName, $srcPath ) {
944 $this->assertWritableRepo(); // fail out if read-only
945
946 $date = gmdate( "YmdHis" );
947 $hashPath = $this->getHashPath( $originalName );
948 $dstRel = "{$hashPath}{$date}!{$originalName}";
949 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
950 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
951
952 $result = $this->quickImport( $srcPath, $virtualUrl );
953 $result->value = $virtualUrl;
954
955 return $result;
956 }
957
958 /**
959 * Remove a temporary file or mark it for garbage collection
960 *
961 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
962 * @return Boolean: true on success, false on failure
963 */
964 public function freeTemp( $virtualUrl ) {
965 $this->assertWritableRepo(); // fail out if read-only
966
967 $temp = $this->getVirtualUrl( 'temp' );
968 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
969 wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
970 return false;
971 }
972
973 return $this->quickPurge( $virtualUrl )->isOK();
974 }
975
976 /**
977 * Concatenate a list of temporary files into a target file location.
978 *
979 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
980 * @param $dstPath String Target file system path
981 * @param $flags Integer: bitwise combination of the following flags:
982 * self::DELETE_SOURCE Delete the source files
983 * @return FileRepoStatus
984 */
985 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
986 $this->assertWritableRepo(); // fail out if read-only
987
988 $status = $this->newGood();
989
990 $sources = array();
991 foreach ( $srcPaths as $srcPath ) {
992 // Resolve source to a storage path if virtual
993 $source = $this->resolveToStoragePath( $srcPath );
994 $sources[] = $source; // chunk to merge
995 }
996
997 // Concatenate the chunks into one FS file
998 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
999 $status->merge( $this->backend->concatenate( $params ) );
1000 if ( !$status->isOK() ) {
1001 return $status;
1002 }
1003
1004 // Delete the sources if required
1005 if ( $flags & self::DELETE_SOURCE ) {
1006 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1007 }
1008
1009 // Make sure status is OK, despite any quickPurgeBatch() fatals
1010 $status->setResult( true );
1011
1012 return $status;
1013 }
1014
1015 /**
1016 * Copy or move a file either from a storage path, virtual URL,
1017 * or FS path, into this repository at the specified destination location.
1018 *
1019 * Returns a FileRepoStatus object. On success, the value contains "new" or
1020 * "archived", to indicate whether the file was new with that name.
1021 *
1022 * @param $srcPath String: the source FS path, storage path, or URL
1023 * @param $dstRel String: the destination relative path
1024 * @param $archiveRel String: the relative path where the existing file is to
1025 * be archived, if there is one. Relative to the public zone root.
1026 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1027 * that the source file should be deleted if possible
1028 * @return FileRepoStatus
1029 */
1030 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
1031 $this->assertWritableRepo(); // fail out if read-only
1032
1033 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1034 if ( $status->successCount == 0 ) {
1035 $status->ok = false;
1036 }
1037 if ( isset( $status->value[0] ) ) {
1038 $status->value = $status->value[0];
1039 } else {
1040 $status->value = false;
1041 }
1042
1043 return $status;
1044 }
1045
1046 /**
1047 * Publish a batch of files
1048 *
1049 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1050 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1051 * that the source files should be deleted if possible
1052 * @throws MWException
1053 * @return FileRepoStatus
1054 */
1055 public function publishBatch( array $triplets, $flags = 0 ) {
1056 $this->assertWritableRepo(); // fail out if read-only
1057
1058 $backend = $this->backend; // convenience
1059 // Try creating directories
1060 $status = $this->initZones( 'public' );
1061 if ( !$status->isOK() ) {
1062 return $status;
1063 }
1064
1065 $status = $this->newGood( array() );
1066
1067 $operations = array();
1068 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1069 // Validate each triplet and get the store operation...
1070 foreach ( $triplets as $i => $triplet ) {
1071 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1072 // Resolve source to a storage path if virtual
1073 $srcPath = $this->resolveToStoragePath( $srcPath );
1074 if ( !$this->validateFilename( $dstRel ) ) {
1075 throw new MWException( 'Validation error in $dstRel' );
1076 }
1077 if ( !$this->validateFilename( $archiveRel ) ) {
1078 throw new MWException( 'Validation error in $archiveRel' );
1079 }
1080
1081 $publicRoot = $this->getZonePath( 'public' );
1082 $dstPath = "$publicRoot/$dstRel";
1083 $archivePath = "$publicRoot/$archiveRel";
1084
1085 $dstDir = dirname( $dstPath );
1086 $archiveDir = dirname( $archivePath );
1087 // Abort immediately on directory creation errors since they're likely to be repetitive
1088 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1089 return $this->newFatal( 'directorycreateerror', $dstDir );
1090 }
1091 if ( !$this->initDirectory($archiveDir )->isOK() ) {
1092 return $this->newFatal( 'directorycreateerror', $archiveDir );
1093 }
1094
1095 // Archive destination file if it exists
1096 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1097 // Check if the archive file exists
1098 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1099 // unlinks the destination file if it exists. DB-based synchronisation in
1100 // publishBatch's caller should prevent races. In Windows there's no
1101 // problem because the rename primitive fails if the destination exists.
1102 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1103 $operations[] = array( 'op' => 'null' );
1104 continue;
1105 } else {
1106 $operations[] = array(
1107 'op' => 'move',
1108 'src' => $dstPath,
1109 'dst' => $archivePath
1110 );
1111 }
1112 $status->value[$i] = 'archived';
1113 } else {
1114 $status->value[$i] = 'new';
1115 }
1116 // Copy (or move) the source file to the destination
1117 if ( FileBackend::isStoragePath( $srcPath ) ) {
1118 if ( $flags & self::DELETE_SOURCE ) {
1119 $operations[] = array(
1120 'op' => 'move',
1121 'src' => $srcPath,
1122 'dst' => $dstPath
1123 );
1124 } else {
1125 $operations[] = array(
1126 'op' => 'copy',
1127 'src' => $srcPath,
1128 'dst' => $dstPath
1129 );
1130 }
1131 } else { // FS source path
1132 $operations[] = array(
1133 'op' => 'store',
1134 'src' => $srcPath,
1135 'dst' => $dstPath
1136 );
1137 if ( $flags & self::DELETE_SOURCE ) {
1138 $sourceFSFilesToDelete[] = $srcPath;
1139 }
1140 }
1141 }
1142
1143 // Execute the operations for each triplet
1144 $opts = array( 'force' => true );
1145 $status->merge( $backend->doOperations( $operations, $opts ) );
1146 // Cleanup for disk source files...
1147 foreach ( $sourceFSFilesToDelete as $file ) {
1148 wfSuppressWarnings();
1149 unlink( $file ); // FS cleanup
1150 wfRestoreWarnings();
1151 }
1152
1153 return $status;
1154 }
1155
1156 /**
1157 * Creates a directory with the appropriate zone permissions.
1158 * Callers are responsible for doing read-only and "writable repo" checks.
1159 *
1160 * @param $dir string Virtual URL (or storage path) of directory to clean
1161 * @return Status
1162 */
1163 protected function initDirectory( $dir ) {
1164 $path = $this->resolveToStoragePath( $dir );
1165 list( $b, $container, $r ) = FileBackend::splitStoragePath( $path );
1166
1167 $params = array( 'dir' => $path );
1168 if ( $this->isPrivate || $container === $this->zones['deleted']['container'] ) {
1169 # Take all available measures to prevent web accessibility of new deleted
1170 # directories, in case the user has not configured offline storage
1171 $params = array( 'noAccess' => true, 'noListing' => true ) + $params;
1172 }
1173
1174 return $this->backend->prepare( $params );
1175 }
1176
1177 /**
1178 * Deletes a directory if empty.
1179 *
1180 * @param $dir string Virtual URL (or storage path) of directory to clean
1181 * @return Status
1182 */
1183 public function cleanDir( $dir ) {
1184 $this->assertWritableRepo(); // fail out if read-only
1185
1186 $status = $this->newGood();
1187 $status->merge( $this->backend->clean(
1188 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1189
1190 return $status;
1191 }
1192
1193 /**
1194 * Checks existence of a a file
1195 *
1196 * @param $file string Virtual URL (or storage path) of file to check
1197 * @return bool
1198 */
1199 public function fileExists( $file ) {
1200 $result = $this->fileExistsBatch( array( $file ) );
1201 return $result[0];
1202 }
1203
1204 /**
1205 * Checks existence of an array of files.
1206 *
1207 * @param $files Array: Virtual URLs (or storage paths) of files to check
1208 * @return array|bool Either array of files and existence flags, or false
1209 */
1210 public function fileExistsBatch( array $files ) {
1211 $result = array();
1212 foreach ( $files as $key => $file ) {
1213 $file = $this->resolveToStoragePath( $file );
1214 $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
1215 }
1216 return $result;
1217 }
1218
1219 /**
1220 * Move a file to the deletion archive.
1221 * If no valid deletion archive exists, this may either delete the file
1222 * or throw an exception, depending on the preference of the repository
1223 *
1224 * @param $srcRel Mixed: relative path for the file to be deleted
1225 * @param $archiveRel Mixed: relative path for the archive location.
1226 * Relative to a private archive directory.
1227 * @return FileRepoStatus object
1228 */
1229 public function delete( $srcRel, $archiveRel ) {
1230 $this->assertWritableRepo(); // fail out if read-only
1231
1232 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1233 }
1234
1235 /**
1236 * Move a group of files to the deletion archive.
1237 *
1238 * If no valid deletion archive is configured, this may either delete the
1239 * file or throw an exception, depending on the preference of the repository.
1240 *
1241 * The overwrite policy is determined by the repository -- currently LocalRepo
1242 * assumes a naming scheme in the deleted zone based on content hash, as
1243 * opposed to the public zone which is assumed to be unique.
1244 *
1245 * @param $sourceDestPairs Array of source/destination pairs. Each element
1246 * is a two-element array containing the source file path relative to the
1247 * public root in the first element, and the archive file path relative
1248 * to the deleted zone root in the second element.
1249 * @throws MWException
1250 * @return FileRepoStatus
1251 */
1252 public function deleteBatch( array $sourceDestPairs ) {
1253 $this->assertWritableRepo(); // fail out if read-only
1254
1255 // Try creating directories
1256 $status = $this->initZones( array( 'public', 'deleted' ) );
1257 if ( !$status->isOK() ) {
1258 return $status;
1259 }
1260
1261 $status = $this->newGood();
1262
1263 $backend = $this->backend; // convenience
1264 $operations = array();
1265 // Validate filenames and create archive directories
1266 foreach ( $sourceDestPairs as $pair ) {
1267 list( $srcRel, $archiveRel ) = $pair;
1268 if ( !$this->validateFilename( $srcRel ) ) {
1269 throw new MWException( __METHOD__.':Validation error in $srcRel' );
1270 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1271 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
1272 }
1273
1274 $publicRoot = $this->getZonePath( 'public' );
1275 $srcPath = "{$publicRoot}/$srcRel";
1276
1277 $deletedRoot = $this->getZonePath( 'deleted' );
1278 $archivePath = "{$deletedRoot}/{$archiveRel}";
1279 $archiveDir = dirname( $archivePath ); // does not touch FS
1280
1281 // Create destination directories
1282 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1283 return $this->newFatal( 'directorycreateerror', $archiveDir );
1284 }
1285
1286 $operations[] = array(
1287 'op' => 'move',
1288 'src' => $srcPath,
1289 'dst' => $archivePath,
1290 // We may have 2+ identical files being deleted,
1291 // all of which will map to the same destination file
1292 'overwriteSame' => true // also see bug 31792
1293 );
1294 }
1295
1296 // Move the files by execute the operations for each pair.
1297 // We're now committed to returning an OK result, which will
1298 // lead to the files being moved in the DB also.
1299 $opts = array( 'force' => true );
1300 $status->merge( $backend->doOperations( $operations, $opts ) );
1301
1302 return $status;
1303 }
1304
1305 /**
1306 * Delete files in the deleted directory if they are not referenced in the filearchive table
1307 *
1308 * STUB
1309 */
1310 public function cleanupDeletedBatch( array $storageKeys ) {
1311 $this->assertWritableRepo();
1312 }
1313
1314 /**
1315 * Get a relative path for a deletion archive key,
1316 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1317 *
1318 * @param $key string
1319 * @return string
1320 */
1321 public function getDeletedHashPath( $key ) {
1322 $path = '';
1323 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1324 $path .= $key[$i] . '/';
1325 }
1326 return $path;
1327 }
1328
1329 /**
1330 * If a path is a virtual URL, resolve it to a storage path.
1331 * Otherwise, just return the path as it is.
1332 *
1333 * @param $path string
1334 * @return string
1335 * @throws MWException
1336 */
1337 protected function resolveToStoragePath( $path ) {
1338 if ( $this->isVirtualUrl( $path ) ) {
1339 return $this->resolveVirtualUrl( $path );
1340 }
1341 return $path;
1342 }
1343
1344 /**
1345 * Get a local FS copy of a file with a given virtual URL/storage path.
1346 * Temporary files may be purged when the file object falls out of scope.
1347 *
1348 * @param $virtualUrl string
1349 * @return TempFSFile|null Returns null on failure
1350 */
1351 public function getLocalCopy( $virtualUrl ) {
1352 $path = $this->resolveToStoragePath( $virtualUrl );
1353 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1354 }
1355
1356 /**
1357 * Get a local FS file with a given virtual URL/storage path.
1358 * The file is either an original or a copy. It should not be changed.
1359 * Temporary files may be purged when the file object falls out of scope.
1360 *
1361 * @param $virtualUrl string
1362 * @return FSFile|null Returns null on failure.
1363 */
1364 public function getLocalReference( $virtualUrl ) {
1365 $path = $this->resolveToStoragePath( $virtualUrl );
1366 return $this->backend->getLocalReference( array( 'src' => $path ) );
1367 }
1368
1369 /**
1370 * Get properties of a file with a given virtual URL/storage path.
1371 * Properties should ultimately be obtained via FSFile::getProps().
1372 *
1373 * @param $virtualUrl string
1374 * @return Array
1375 */
1376 public function getFileProps( $virtualUrl ) {
1377 $path = $this->resolveToStoragePath( $virtualUrl );
1378 return $this->backend->getFileProps( array( 'src' => $path ) );
1379 }
1380
1381 /**
1382 * Get the timestamp of a file with a given virtual URL/storage path
1383 *
1384 * @param $virtualUrl string
1385 * @return string|bool False on failure
1386 */
1387 public function getFileTimestamp( $virtualUrl ) {
1388 $path = $this->resolveToStoragePath( $virtualUrl );
1389 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1390 }
1391
1392 /**
1393 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1394 *
1395 * @param $virtualUrl string
1396 * @return string|bool
1397 */
1398 public function getFileSha1( $virtualUrl ) {
1399 $path = $this->resolveToStoragePath( $virtualUrl );
1400 return $this->backend->getFileSha1Base36( array( 'src' => $path ) );
1401 }
1402
1403 /**
1404 * Attempt to stream a file with the given virtual URL/storage path
1405 *
1406 * @param $virtualUrl string
1407 * @param $headers Array Additional HTTP headers to send on success
1408 * @return bool Success
1409 */
1410 public function streamFile( $virtualUrl, $headers = array() ) {
1411 $path = $this->resolveToStoragePath( $virtualUrl );
1412 $params = array( 'src' => $path, 'headers' => $headers );
1413 return $this->backend->streamFile( $params )->isOK();
1414 }
1415
1416 /**
1417 * Call a callback function for every public regular file in the repository.
1418 * This only acts on the current version of files, not any old versions.
1419 * May use either the database or the filesystem.
1420 *
1421 * @param $callback Array|string
1422 * @return void
1423 */
1424 public function enumFiles( $callback ) {
1425 $this->enumFilesInStorage( $callback );
1426 }
1427
1428 /**
1429 * Call a callback function for every public file in the repository.
1430 * May use either the database or the filesystem.
1431 *
1432 * @param $callback Array|string
1433 * @return void
1434 */
1435 protected function enumFilesInStorage( $callback ) {
1436 $publicRoot = $this->getZonePath( 'public' );
1437 $numDirs = 1 << ( $this->hashLevels * 4 );
1438 // Use a priori assumptions about directory structure
1439 // to reduce the tree height of the scanning process.
1440 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1441 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1442 $path = $publicRoot;
1443 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1444 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1445 }
1446 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1447 foreach ( $iterator as $name ) {
1448 // Each item returned is a public file
1449 call_user_func( $callback, "{$path}/{$name}" );
1450 }
1451 }
1452 }
1453
1454 /**
1455 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1456 *
1457 * @param $filename string
1458 * @return bool
1459 */
1460 public function validateFilename( $filename ) {
1461 if ( strval( $filename ) == '' ) {
1462 return false;
1463 }
1464 return FileBackend::isPathTraversalFree( $filename );
1465 }
1466
1467 /**
1468 * Get a callback function to use for cleaning error message parameters
1469 *
1470 * @return Array
1471 */
1472 function getErrorCleanupFunction() {
1473 switch ( $this->pathDisclosureProtection ) {
1474 case 'none':
1475 case 'simple': // b/c
1476 $callback = array( $this, 'passThrough' );
1477 break;
1478 default: // 'paranoid'
1479 $callback = array( $this, 'paranoidClean' );
1480 }
1481 return $callback;
1482 }
1483
1484 /**
1485 * Path disclosure protection function
1486 *
1487 * @param $param string
1488 * @return string
1489 */
1490 function paranoidClean( $param ) {
1491 return '[hidden]';
1492 }
1493
1494 /**
1495 * Path disclosure protection function
1496 *
1497 * @param $param string
1498 * @return string
1499 */
1500 function passThrough( $param ) {
1501 return $param;
1502 }
1503
1504 /**
1505 * Create a new fatal error
1506 *
1507 * @return FileRepoStatus
1508 */
1509 public function newFatal( $message /*, parameters...*/ ) {
1510 $params = func_get_args();
1511 array_unshift( $params, $this );
1512 return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1513 }
1514
1515 /**
1516 * Create a new good result
1517 *
1518 * @param $value null|string
1519 * @return FileRepoStatus
1520 */
1521 public function newGood( $value = null ) {
1522 return FileRepoStatus::newGood( $this, $value );
1523 }
1524
1525 /**
1526 * Checks if there is a redirect named as $title. If there is, return the
1527 * title object. If not, return false.
1528 * STUB
1529 *
1530 * @param $title Title of image
1531 * @return Bool
1532 */
1533 public function checkRedirect( Title $title ) {
1534 return false;
1535 }
1536
1537 /**
1538 * Invalidates image redirect cache related to that image
1539 * Doesn't do anything for repositories that don't support image redirects.
1540 *
1541 * STUB
1542 * @param $title Title of image
1543 */
1544 public function invalidateImageRedirect( Title $title ) {}
1545
1546 /**
1547 * Get the human-readable name of the repo
1548 *
1549 * @return string
1550 */
1551 public function getDisplayName() {
1552 // We don't name our own repo, return nothing
1553 if ( $this->isLocal() ) {
1554 return null;
1555 }
1556 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1557 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1558 }
1559
1560 /**
1561 * Get the portion of the file that contains the origin file name.
1562 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1563 *
1564 * @param $name string
1565 * @return string
1566 */
1567 public function nameForThumb( $name ) {
1568 if ( strlen( $name ) > $this->abbrvThreshold ) {
1569 $ext = FileBackend::extensionFromPath( $name );
1570 $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
1571 }
1572 return $name;
1573 }
1574
1575 /**
1576 * Returns true if this the local file repository.
1577 *
1578 * @return bool
1579 */
1580 public function isLocal() {
1581 return $this->getName() == 'local';
1582 }
1583
1584 /**
1585 * Get a key on the primary cache for this repository.
1586 * Returns false if the repository's cache is not accessible at this site.
1587 * The parameters are the parts of the key, as for wfMemcKey().
1588 *
1589 * STUB
1590 * @return bool
1591 */
1592 public function getSharedCacheKey( /*...*/ ) {
1593 return false;
1594 }
1595
1596 /**
1597 * Get a key for this repo in the local cache domain. These cache keys are
1598 * not shared with remote instances of the repo.
1599 * The parameters are the parts of the key, as for wfMemcKey().
1600 *
1601 * @return string
1602 */
1603 public function getLocalCacheKey( /*...*/ ) {
1604 $args = func_get_args();
1605 array_unshift( $args, 'filerepo', $this->getName() );
1606 return call_user_func_array( 'wfMemcKey', $args );
1607 }
1608
1609 /**
1610 * Get an temporary FileRepo associated with this repo.
1611 * Files will be created in the temp zone of this repo and
1612 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1613 * It will have the same backend as this repo.
1614 *
1615 * @return TempFileRepo
1616 */
1617 public function getTempRepo() {
1618 return new TempFileRepo( array(
1619 'name' => "{$this->name}-temp",
1620 'backend' => $this->backend,
1621 'zones' => array(
1622 'public' => array(
1623 'container' => $this->zones['temp']['container'],
1624 'directory' => $this->zones['temp']['directory']
1625 ),
1626 'thumb' => array(
1627 'container' => $this->zones['thumb']['container'],
1628 'directory' => ( $this->zones['thumb']['directory'] == '' )
1629 ? 'temp'
1630 : $this->zones['thumb']['directory'] . '/temp'
1631 )
1632 ),
1633 'url' => $this->getZoneUrl( 'temp' ),
1634 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1635 'hashLevels' => $this->hashLevels // performance
1636 ) );
1637 }
1638
1639 /**
1640 * Get an UploadStash associated with this repo.
1641 *
1642 * @return UploadStash
1643 */
1644 public function getUploadStash() {
1645 return new UploadStash( $this );
1646 }
1647
1648 /**
1649 * Throw an exception if this repo is read-only by design.
1650 * This does not and should not check getReadOnlyReason().
1651 *
1652 * @return void
1653 * @throws MWException
1654 */
1655 protected function assertWritableRepo() {}
1656 }
1657
1658 /**
1659 * FileRepo for temporary files created via FileRepo::getTempRepo()
1660 */
1661 class TempFileRepo extends FileRepo {
1662 public function getTempRepo() {
1663 throw new MWException( "Cannot get a temp repo from a temp repo." );
1664 }
1665 }