b9e1db7b335046109b82fddca96557cfe548a842
[lhc/web/wiklou.git] / includes / filerepo / File.php
1 <?php
2 /**
3 * Base code for files.
4 *
5 * @file
6 * @ingroup FileRepo
7 */
8
9 /**
10 * Implements some public methods and some protected utility functions which
11 * are required by multiple child classes. Contains stub functionality for
12 * unimplemented public methods.
13 *
14 * Stub functions which should be overridden are marked with STUB. Some more
15 * concrete functions are also typically overridden by child classes.
16 *
17 * Note that only the repo object knows what its file class is called. You should
18 * never name a file class explictly outside of the repo class. Instead use the
19 * repo's factory functions to generate file objects, for example:
20 *
21 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
22 *
23 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
24 * in most cases.
25 *
26 * @ingroup FileRepo
27 */
28 abstract class File {
29 const DELETED_FILE = 1;
30 const DELETED_COMMENT = 2;
31 const DELETED_USER = 4;
32 const DELETED_RESTRICTED = 8;
33 const RENDER_NOW = 1;
34
35 const DELETE_SOURCE = 1;
36
37 /**
38 * Some member variables can be lazy-initialised using __get(). The
39 * initialisation function for these variables is always a function named
40 * like getVar(), where Var is the variable name with upper-case first
41 * letter.
42 *
43 * The following variables are initialised in this way in this base class:
44 * name, extension, handler, path, canRender, isSafeFile,
45 * transformScript, hashPath, pageCount, url
46 *
47 * Code within this class should generally use the accessor function
48 * directly, since __get() isn't re-entrant and therefore causes bugs that
49 * depend on initialisation order.
50 */
51
52 /**
53 * The following member variables are not lazy-initialised
54 */
55 var $repo, $title, $lastError, $redirected, $redirectedTitle;
56
57 /**
58 * Call this constructor from child classes
59 */
60 function __construct( $title, $repo ) {
61 $this->title = $title;
62 $this->repo = $repo;
63 }
64
65 function __get( $name ) {
66 $function = array( $this, 'get' . ucfirst( $name ) );
67 if ( !is_callable( $function ) ) {
68 return null;
69 } else {
70 $this->$name = call_user_func( $function );
71 return $this->$name;
72 }
73 }
74
75 /**
76 * Normalize a file extension to the common form, and ensure it's clean.
77 * Extensions with non-alphanumeric characters will be discarded.
78 *
79 * @param $ext string (without the .)
80 * @return string
81 */
82 static function normalizeExtension( $ext ) {
83 $lower = strtolower( $ext );
84 $squish = array(
85 'htm' => 'html',
86 'jpeg' => 'jpg',
87 'mpeg' => 'mpg',
88 'tiff' => 'tif',
89 'ogv' => 'ogg' );
90 if( isset( $squish[$lower] ) ) {
91 return $squish[$lower];
92 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
93 return $lower;
94 } else {
95 return '';
96 }
97 }
98
99 /**
100 * Checks if file extensions are compatible
101 *
102 * @param $old File Old file
103 * @param $new string New name
104 */
105 static function checkExtensionCompatibility( File $old, $new ) {
106 $oldMime = $old->getMimeType();
107 $n = strrpos( $new, '.' );
108 $newExt = self::normalizeExtension(
109 $n ? substr( $new, $n + 1 ) : '' );
110 $mimeMagic = MimeMagic::singleton();
111 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
112 }
113
114 /**
115 * Upgrade the database row if there is one
116 * Called by ImagePage
117 * STUB
118 */
119 function upgradeRow() {}
120
121 /**
122 * Split an internet media type into its two components; if not
123 * a two-part name, set the minor type to 'unknown'.
124 *
125 * @param $mime "text/html" etc
126 * @return array ("text", "html") etc
127 */
128 static function splitMime( $mime ) {
129 if( strpos( $mime, '/' ) !== false ) {
130 return explode( '/', $mime, 2 );
131 } else {
132 return array( $mime, 'unknown' );
133 }
134 }
135
136 /**
137 * Return the name of this file
138 */
139 public function getName() {
140 if ( !isset( $this->name ) ) {
141 $this->name = $this->repo->getNameFromTitle( $this->title );
142 }
143 return $this->name;
144 }
145
146 /**
147 * Get the file extension, e.g. "svg"
148 */
149 function getExtension() {
150 if ( !isset( $this->extension ) ) {
151 $n = strrpos( $this->getName(), '.' );
152 $this->extension = self::normalizeExtension(
153 $n ? substr( $this->getName(), $n + 1 ) : '' );
154 }
155 return $this->extension;
156 }
157
158 /**
159 * Return the associated title object
160 * @return Title
161 */
162 public function getTitle() { return $this->title; }
163
164 /**
165 * Return the title used to find this file
166 */
167 public function getOriginalTitle() {
168 if ( $this->redirected )
169 return $this->getRedirectedTitle();
170 return $this->title;
171 }
172
173 /**
174 * Return the URL of the file
175 */
176 public function getUrl() {
177 if ( !isset( $this->url ) ) {
178 $this->url = $this->repo->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
179 }
180 return $this->url;
181 }
182
183 /**
184 * Return a fully-qualified URL to the file.
185 * Upload URL paths _may or may not_ be fully qualified, so
186 * we check. Local paths are assumed to belong on $wgServer.
187 *
188 * @return String
189 */
190 public function getFullUrl() {
191 return wfExpandUrl( $this->getUrl() );
192 }
193
194 function getViewURL() {
195 if( $this->mustRender()) {
196 if( $this->canRender() ) {
197 return $this->createThumb( $this->getWidth() );
198 }
199 else {
200 wfDebug(__METHOD__.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
201 return $this->getURL(); #hm... return NULL?
202 }
203 } else {
204 return $this->getURL();
205 }
206 }
207
208 /**
209 * Return the full filesystem path to the file. Note that this does
210 * not mean that a file actually exists under that location.
211 *
212 * This path depends on whether directory hashing is active or not,
213 * i.e. whether the files are all found in the same directory,
214 * or in hashed paths like /images/3/3c.
215 *
216 * May return false if the file is not locally accessible.
217 */
218 public function getPath() {
219 if ( !isset( $this->path ) ) {
220 $this->path = $this->repo->getZonePath('public') . '/' . $this->getRel();
221 }
222 return $this->path;
223 }
224
225 /**
226 * Alias for getPath()
227 */
228 public function getFullPath() {
229 return $this->getPath();
230 }
231
232 /**
233 * Return the width of the image. Returns false if the width is unknown
234 * or undefined.
235 *
236 * STUB
237 * Overridden by LocalFile, UnregisteredLocalFile
238 */
239 public function getWidth( $page = 1 ) { return false; }
240
241 /**
242 * Return the height of the image. Returns false if the height is unknown
243 * or undefined
244 *
245 * STUB
246 * Overridden by LocalFile, UnregisteredLocalFile
247 */
248 public function getHeight( $page = 1 ) { return false; }
249
250 /**
251 * Returns ID or name of user who uploaded the file
252 * STUB
253 *
254 * @param $type string 'text' or 'id'
255 */
256 public function getUser( $type='text' ) { return null; }
257
258 /**
259 * Get the duration of a media file in seconds
260 */
261 public function getLength() {
262 $handler = $this->getHandler();
263 if ( $handler ) {
264 return $handler->getLength( $this );
265 } else {
266 return 0;
267 }
268 }
269
270 /**
271 * Return true if the file is vectorized
272 */
273 public function isVectorized() {
274 $handler = $this->getHandler();
275 if ( $handler ) {
276 return $handler->isVectorized( $this );
277 } else {
278 return false;
279 }
280 }
281
282
283 /**
284 * Get handler-specific metadata
285 * Overridden by LocalFile, UnregisteredLocalFile
286 * STUB
287 */
288 public function getMetadata() { return false; }
289
290 /**
291 * Return the bit depth of the file
292 * Overridden by LocalFile
293 * STUB
294 */
295 public function getBitDepth() { return 0; }
296
297 /**
298 * Return the size of the image file, in bytes
299 * Overridden by LocalFile, UnregisteredLocalFile
300 * STUB
301 */
302 public function getSize() { return false; }
303
304 /**
305 * Returns the mime type of the file.
306 * Overridden by LocalFile, UnregisteredLocalFile
307 * STUB
308 */
309 function getMimeType() { return 'unknown/unknown'; }
310
311 /**
312 * Return the type of the media in the file.
313 * Use the value returned by this function with the MEDIATYPE_xxx constants.
314 * Overridden by LocalFile,
315 * STUB
316 */
317 function getMediaType() { return MEDIATYPE_UNKNOWN; }
318
319 /**
320 * Checks if the output of transform() for this file is likely
321 * to be valid. If this is false, various user elements will
322 * display a placeholder instead.
323 *
324 * Currently, this checks if the file is an image format
325 * that can be converted to a format
326 * supported by all browsers (namely GIF, PNG and JPEG),
327 * or if it is an SVG image and SVG conversion is enabled.
328 */
329 function canRender() {
330 if ( !isset( $this->canRender ) ) {
331 $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
332 }
333 return $this->canRender;
334 }
335
336 /**
337 * Accessor for __get()
338 */
339 protected function getCanRender() {
340 return $this->canRender();
341 }
342
343 /**
344 * Return true if the file is of a type that can't be directly
345 * rendered by typical browsers and needs to be re-rasterized.
346 *
347 * This returns true for everything but the bitmap types
348 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
349 * also return true for any non-image formats.
350 *
351 * @return bool
352 */
353 function mustRender() {
354 return $this->getHandler() && $this->handler->mustRender( $this );
355 }
356
357 /**
358 * Alias for canRender()
359 */
360 function allowInlineDisplay() {
361 return $this->canRender();
362 }
363
364 /**
365 * Determines if this media file is in a format that is unlikely to
366 * contain viruses or malicious content. It uses the global
367 * $wgTrustedMediaFormats list to determine if the file is safe.
368 *
369 * This is used to show a warning on the description page of non-safe files.
370 * It may also be used to disallow direct [[media:...]] links to such files.
371 *
372 * Note that this function will always return true if allowInlineDisplay()
373 * or isTrustedFile() is true for this file.
374 */
375 function isSafeFile() {
376 if ( !isset( $this->isSafeFile ) ) {
377 $this->isSafeFile = $this->_getIsSafeFile();
378 }
379 return $this->isSafeFile;
380 }
381
382 /** Accessor for __get() */
383 protected function getIsSafeFile() {
384 return $this->isSafeFile();
385 }
386
387 /** Uncached accessor */
388 protected function _getIsSafeFile() {
389 if ($this->allowInlineDisplay()) return true;
390 if ($this->isTrustedFile()) return true;
391
392 global $wgTrustedMediaFormats;
393
394 $type= $this->getMediaType();
395 $mime= $this->getMimeType();
396 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
397
398 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
399 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
400
401 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
402 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
403
404 return false;
405 }
406
407 /** Returns true if the file is flagged as trusted. Files flagged that way
408 * can be linked to directly, even if that is not allowed for this type of
409 * file normally.
410 *
411 * This is a dummy function right now and always returns false. It could be
412 * implemented to extract a flag from the database. The trusted flag could be
413 * set on upload, if the user has sufficient privileges, to bypass script-
414 * and html-filters. It may even be coupled with cryptographics signatures
415 * or such.
416 */
417 function isTrustedFile() {
418 #this could be implemented to check a flag in the databas,
419 #look for signatures, etc
420 return false;
421 }
422
423 /**
424 * Returns true if file exists in the repository.
425 *
426 * Overridden by LocalFile to avoid unnecessary stat calls.
427 *
428 * @return boolean Whether file exists in the repository.
429 */
430 public function exists() {
431 return $this->getPath() && file_exists( $this->path );
432 }
433
434 /**
435 * Returns true if file exists in the repository and can be included in a page.
436 * It would be unsafe to include private images, making public thumbnails inadvertently
437 *
438 * @return boolean Whether file exists in the repository and is includable.
439 * @public
440 */
441 function isVisible() {
442 return $this->exists();
443 }
444
445 function getTransformScript() {
446 if ( !isset( $this->transformScript ) ) {
447 $this->transformScript = false;
448 if ( $this->repo ) {
449 $script = $this->repo->getThumbScriptUrl();
450 if ( $script ) {
451 $this->transformScript = "$script?f=" . urlencode( $this->getName() );
452 }
453 }
454 }
455 return $this->transformScript;
456 }
457
458 /**
459 * Get a ThumbnailImage which is the same size as the source
460 */
461 function getUnscaledThumb( $handlerParams = array() ) {
462 $hp =& $handlerParams;
463 $page = isset( $hp['page'] ) ? $hp['page'] : false;
464 $width = $this->getWidth( $page );
465 if ( !$width ) {
466 return $this->iconThumb();
467 }
468 $hp['width'] = $width;
469 return $this->transform( $hp );
470 }
471
472 /**
473 * Return the file name of a thumbnail with the specified parameters
474 *
475 * @param $params Array: handler-specific parameters
476 * @private -ish
477 */
478 function thumbName( $params ) {
479 return $this->generateThumbName( $this->getName(), $params );
480 }
481
482 /**
483 * Generate a thumbnail file name from a name and specified parameters
484 *
485 * @param string $name
486 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
487 */
488 function generateThumbName( $name, $params ) {
489 if ( !$this->getHandler() ) {
490 return null;
491 }
492 $extension = $this->getExtension();
493 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
494 $thumbName = $this->handler->makeParamString( $params ) . '-' . $name;
495 if ( $thumbExt != $extension ) {
496 $thumbName .= ".$thumbExt";
497 }
498 return $thumbName;
499 }
500
501 /**
502 * Create a thumbnail of the image having the specified width/height.
503 * The thumbnail will not be created if the width is larger than the
504 * image's width. Let the browser do the scaling in this case.
505 * The thumbnail is stored on disk and is only computed if the thumbnail
506 * file does not exist OR if it is older than the image.
507 * Returns the URL.
508 *
509 * Keeps aspect ratio of original image. If both width and height are
510 * specified, the generated image will be no bigger than width x height,
511 * and will also have correct aspect ratio.
512 *
513 * @param $width Integer: maximum width of the generated thumbnail
514 * @param $height Integer: maximum height of the image (optional)
515 */
516 public function createThumb( $width, $height = -1 ) {
517 $params = array( 'width' => $width );
518 if ( $height != -1 ) {
519 $params['height'] = $height;
520 }
521 $thumb = $this->transform( $params );
522 if( is_null( $thumb ) || $thumb->isError() ) return '';
523 return $thumb->getUrl();
524 }
525
526 /**
527 * As createThumb, but returns a ThumbnailImage object. This can
528 * provide access to the actual file, the real size of the thumb,
529 * and can produce a convenient \<img\> tag for you.
530 *
531 * For non-image formats, this may return a filetype-specific icon.
532 *
533 * @param $width Integer: maximum width of the generated thumbnail
534 * @param $height Integer: maximum height of the image (optional)
535 * @param $render Integer: Deprecated
536 *
537 * @return ThumbnailImage or null on failure
538 *
539 * @deprecated use transform()
540 */
541 public function getThumbnail( $width, $height=-1, $render = true ) {
542 wfDeprecated( __METHOD__ );
543 $params = array( 'width' => $width );
544 if ( $height != -1 ) {
545 $params['height'] = $height;
546 }
547 return $this->transform( $params, 0 );
548 }
549
550 /**
551 * Transform a media file
552 *
553 * @param $params Array: an associative array of handler-specific parameters.
554 * Typical keys are width, height and page.
555 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
556 * @return MediaTransformOutput | false
557 */
558 function transform( $params, $flags = 0 ) {
559 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
560
561 wfProfileIn( __METHOD__ );
562 do {
563 if ( !$this->canRender() ) {
564 // not a bitmap or renderable image, don't try.
565 $thumb = $this->iconThumb();
566 break;
567 }
568
569 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
570 $descriptionUrl = $this->getDescriptionUrl();
571 if ( $descriptionUrl ) {
572 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
573 }
574
575 $script = $this->getTransformScript();
576 if ( $script && !($flags & self::RENDER_NOW) ) {
577 // Use a script to transform on client request, if possible
578 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
579 if( $thumb ) {
580 break;
581 }
582 }
583
584 $normalisedParams = $params;
585 $this->handler->normaliseParams( $this, $normalisedParams );
586 $thumbName = $this->thumbName( $normalisedParams );
587 $thumbPath = $this->getThumbPath( $thumbName );
588 $thumbUrl = $this->getThumbUrl( $thumbName );
589
590 if ( $this->repo && $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
591 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
592 break;
593 }
594
595 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
596 $this->migrateThumbFile( $thumbName );
597 if ( file_exists( $thumbPath )) {
598 $thumbTime = filemtime( $thumbPath );
599 if ( $thumbTime !== FALSE &&
600 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
601
602 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
603 break;
604 }
605 }
606 $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
607
608 // Ignore errors if requested
609 if ( !$thumb ) {
610 $thumb = null;
611 } elseif ( $thumb->isError() ) {
612 $this->lastError = $thumb->toText();
613 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
614 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
615 }
616 }
617
618 // Purge. Useful in the event of Core -> Squid connection failure or squid
619 // purge collisions from elsewhere during failure. Don't keep triggering for
620 // "thumbs" which have the main image URL though (bug 13776)
621 if ( $wgUseSquid && ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL()) ) {
622 SquidUpdate::purge( array( $thumbUrl ) );
623 }
624 } while (false);
625
626 wfProfileOut( __METHOD__ );
627 return is_object( $thumb ) ? $thumb : false;
628 }
629
630 /**
631 * Hook into transform() to allow migration of thumbnail files
632 * STUB
633 * Overridden by LocalFile
634 */
635 function migrateThumbFile( $thumbName ) {}
636
637 /**
638 * Get a MediaHandler instance for this file
639 * @return MediaHandler
640 */
641 function getHandler() {
642 if ( !isset( $this->handler ) ) {
643 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
644 }
645 return $this->handler;
646 }
647
648 /**
649 * Get a ThumbnailImage representing a file type icon
650 * @return ThumbnailImage
651 */
652 function iconThumb() {
653 global $wgStylePath, $wgStyleDirectory;
654
655 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
656 foreach( $try as $icon ) {
657 $path = '/common/images/icons/' . $icon;
658 $filepath = $wgStyleDirectory . $path;
659 if( file_exists( $filepath ) ) {
660 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
661 }
662 }
663 return null;
664 }
665
666 /**
667 * Get last thumbnailing error.
668 * Largely obsolete.
669 */
670 function getLastError() {
671 return $this->lastError;
672 }
673
674 /**
675 * Get all thumbnail names previously generated for this file
676 * STUB
677 * Overridden by LocalFile
678 */
679 function getThumbnails() { return array(); }
680
681 /**
682 * Purge shared caches such as thumbnails and DB data caching
683 * STUB
684 * Overridden by LocalFile
685 */
686 function purgeCache() {}
687
688 /**
689 * Purge the file description page, but don't go after
690 * pages using the file. Use when modifying file history
691 * but not the current data.
692 */
693 function purgeDescription() {
694 $title = $this->getTitle();
695 if ( $title ) {
696 $title->invalidateCache();
697 $title->purgeSquid();
698 }
699 }
700
701 /**
702 * Purge metadata and all affected pages when the file is created,
703 * deleted, or majorly updated.
704 */
705 function purgeEverything() {
706 // Delete thumbnails and refresh file metadata cache
707 $this->purgeCache();
708 $this->purgeDescription();
709
710 // Purge cache of all pages using this file
711 $title = $this->getTitle();
712 if ( $title ) {
713 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
714 $update->doUpdate();
715 }
716 }
717
718 /**
719 * Return a fragment of the history of file.
720 *
721 * STUB
722 * @param $limit integer Limit of rows to return
723 * @param $start timestamp Only revisions older than $start will be returned
724 * @param $end timestamp Only revisions newer than $end will be returned
725 * @param $inc bool Include the endpoints of the time range
726 */
727 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
728 return array();
729 }
730
731 /**
732 * Return the history of this file, line by line. Starts with current version,
733 * then old versions. Should return an object similar to an image/oldimage
734 * database row.
735 *
736 * STUB
737 * Overridden in LocalFile
738 */
739 public function nextHistoryLine() {
740 return false;
741 }
742
743 /**
744 * Reset the history pointer to the first element of the history.
745 * Always call this function after using nextHistoryLine() to free db resources
746 * STUB
747 * Overridden in LocalFile.
748 */
749 public function resetHistory() {}
750
751 /**
752 * Get the filename hash component of the directory including trailing slash,
753 * e.g. f/fa/
754 * If the repository is not hashed, returns an empty string.
755 */
756 function getHashPath() {
757 if ( !isset( $this->hashPath ) ) {
758 $this->hashPath = $this->repo->getHashPath( $this->getName() );
759 }
760 return $this->hashPath;
761 }
762
763 /**
764 * Get the path of the file relative to the public zone root
765 */
766 function getRel() {
767 return $this->getHashPath() . $this->getName();
768 }
769
770 /**
771 * Get urlencoded relative path of the file
772 */
773 function getUrlRel() {
774 return $this->getHashPath() . rawurlencode( $this->getName() );
775 }
776
777 /** Get the relative path for an archive file */
778 function getArchiveRel( $suffix = false ) {
779 $path = 'archive/' . $this->getHashPath();
780 if ( $suffix === false ) {
781 $path = substr( $path, 0, -1 );
782 } else {
783 $path .= $suffix;
784 }
785 return $path;
786 }
787
788 /** Get the path of the archive directory, or a particular file if $suffix is specified */
789 function getArchivePath( $suffix = false ) {
790 return $this->repo->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
791 }
792
793 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
794 function getThumbPath( $suffix = false ) {
795 $path = $this->repo->getZonePath('thumb') . '/' . $this->getRel();
796 if ( $suffix !== false ) {
797 $path .= '/' . $suffix;
798 }
799 return $path;
800 }
801
802 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
803 function getArchiveUrl( $suffix = false ) {
804 $path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
805 if ( $suffix === false ) {
806 $path = substr( $path, 0, -1 );
807 } else {
808 $path .= rawurlencode( $suffix );
809 }
810 return $path;
811 }
812
813 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
814 function getThumbUrl( $suffix = false ) {
815 $path = $this->repo->getZoneUrl('thumb') . '/' . $this->getUrlRel();
816 if ( $suffix !== false ) {
817 $path .= '/' . rawurlencode( $suffix );
818 }
819 return $path;
820 }
821
822 /** Get the virtual URL for an archive file or directory */
823 function getArchiveVirtualUrl( $suffix = false ) {
824 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
825 if ( $suffix === false ) {
826 $path = substr( $path, 0, -1 );
827 } else {
828 $path .= rawurlencode( $suffix );
829 }
830 return $path;
831 }
832
833 /** Get the virtual URL for a thumbnail file or directory */
834 function getThumbVirtualUrl( $suffix = false ) {
835 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
836 if ( $suffix !== false ) {
837 $path .= '/' . rawurlencode( $suffix );
838 }
839 return $path;
840 }
841
842 /** Get the virtual URL for the file itself */
843 function getVirtualUrl( $suffix = false ) {
844 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
845 if ( $suffix !== false ) {
846 $path .= '/' . rawurlencode( $suffix );
847 }
848 return $path;
849 }
850
851 /**
852 * @return bool
853 */
854 function isHashed() {
855 return $this->repo->isHashed();
856 }
857
858 function readOnlyError() {
859 throw new MWException( get_class($this) . ': write operations are not supported' );
860 }
861
862 /**
863 * Record a file upload in the upload log and the image table
864 * STUB
865 * Overridden by LocalFile
866 */
867 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
868 $this->readOnlyError();
869 }
870
871 /**
872 * Move or copy a file to its public location. If a file exists at the
873 * destination, move it to an archive. Returns a FileRepoStatus object with
874 * the archive name in the "value" member on success.
875 *
876 * The archive name should be passed through to recordUpload for database
877 * registration.
878 *
879 * @param $srcPath String: local filesystem path to the source image
880 * @param $flags Integer: a bitwise combination of:
881 * File::DELETE_SOURCE Delete the source file, i.e. move
882 * rather than copy
883 * @return FileRepoStatus object. On success, the value member contains the
884 * archive name, or an empty string if it was a new file.
885 *
886 * STUB
887 * Overridden by LocalFile
888 */
889 function publish( $srcPath, $flags = 0 ) {
890 $this->readOnlyError();
891 }
892
893 /**
894 * Get an array of Title objects which are articles which use this file
895 * Also adds their IDs to the link cache
896 *
897 * This is mostly copied from Title::getLinksTo()
898 *
899 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
900 */
901 function getLinksTo( $options = array() ) {
902 wfDeprecated( __METHOD__ );
903 wfProfileIn( __METHOD__ );
904
905 // Note: use local DB not repo DB, we want to know local links
906 if ( count( $options ) > 0 ) {
907 $db = wfGetDB( DB_MASTER );
908 } else {
909 $db = wfGetDB( DB_SLAVE );
910 }
911 $linkCache = LinkCache::singleton();
912
913 $encName = $db->addQuotes( $this->getName() );
914 $res = $db->select( array( 'page', 'imagelinks'),
915 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
916 array( 'page_id=il_from', 'il_to' => $encName ),
917 __METHOD__,
918 $options );
919
920 $retVal = array();
921 if ( $db->numRows( $res ) ) {
922 foreach ( $res as $row ) {
923 $titleObj = Title::newFromRow( $row );
924 if ( $titleObj ) {
925 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
926 $retVal[] = $titleObj;
927 }
928 }
929 }
930 wfProfileOut( __METHOD__ );
931 return $retVal;
932 }
933
934 function formatMetadata() {
935 if ( !$this->getHandler() ) {
936 return false;
937 }
938 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
939 }
940
941 /**
942 * Returns true if the file comes from the local file repository.
943 *
944 * @return bool
945 */
946 function isLocal() {
947 $repo = $this->getRepo();
948 return $repo && $repo->isLocal();
949 }
950
951 /**
952 * Returns the name of the repository.
953 *
954 * @return string
955 */
956 function getRepoName() {
957 return $this->repo ? $this->repo->getName() : 'unknown';
958 }
959 /*
960 * Returns the repository
961 */
962 function getRepo() {
963 return $this->repo;
964 }
965
966 /**
967 * Returns true if the image is an old version
968 * STUB
969 */
970 function isOld() {
971 return false;
972 }
973
974 /**
975 * Is this file a "deleted" file in a private archive?
976 * STUB
977 */
978 function isDeleted( $field ) {
979 return false;
980 }
981
982 /**
983 * Return the deletion bitfield
984 * STUB
985 */
986 function getVisibility() {
987 return 0;
988 }
989
990 /**
991 * Was this file ever deleted from the wiki?
992 *
993 * @return bool
994 */
995 function wasDeleted() {
996 $title = $this->getTitle();
997 return $title && $title->isDeletedQuick();
998 }
999
1000 /**
1001 * Move file to the new title
1002 *
1003 * Move current, old version and all thumbnails
1004 * to the new filename. Old file is deleted.
1005 *
1006 * Cache purging is done; checks for validity
1007 * and logging are caller's responsibility
1008 *
1009 * @param $target Title New file name
1010 * @return FileRepoStatus object.
1011 */
1012 function move( $target ) {
1013 $this->readOnlyError();
1014 }
1015
1016 /**
1017 * Delete all versions of the file.
1018 *
1019 * Moves the files into an archive directory (or deletes them)
1020 * and removes the database rows.
1021 *
1022 * Cache purging is done; logging is caller's responsibility.
1023 *
1024 * @param $reason String
1025 * @param $suppress Boolean: hide content from sysops?
1026 * @return true on success, false on some kind of failure
1027 * STUB
1028 * Overridden by LocalFile
1029 */
1030 function delete( $reason, $suppress = false ) {
1031 $this->readOnlyError();
1032 }
1033
1034 /**
1035 * Restore all or specified deleted revisions to the given file.
1036 * Permissions and logging are left to the caller.
1037 *
1038 * May throw database exceptions on error.
1039 *
1040 * @param $versions set of record ids of deleted items to restore,
1041 * or empty to restore all revisions.
1042 * @param $unsuppress remove restrictions on content upon restoration?
1043 * @return the number of file revisions restored if successful,
1044 * or false on failure
1045 * STUB
1046 * Overridden by LocalFile
1047 */
1048 function restore( $versions=array(), $unsuppress=false ) {
1049 $this->readOnlyError();
1050 }
1051
1052 /**
1053 * Returns 'true' if this file is a type which supports multiple pages,
1054 * e.g. DJVU or PDF. Note that this may be true even if the file in
1055 * question only has a single page.
1056 *
1057 * @return Bool
1058 */
1059 function isMultipage() {
1060 return $this->getHandler() && $this->handler->isMultiPage( $this );
1061 }
1062
1063 /**
1064 * Returns the number of pages of a multipage document, or false for
1065 * documents which aren't multipage documents
1066 */
1067 function pageCount() {
1068 if ( !isset( $this->pageCount ) ) {
1069 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1070 $this->pageCount = $this->handler->pageCount( $this );
1071 } else {
1072 $this->pageCount = false;
1073 }
1074 }
1075 return $this->pageCount;
1076 }
1077
1078 /**
1079 * Calculate the height of a thumbnail using the source and destination width
1080 */
1081 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1082 // Exact integer multiply followed by division
1083 if ( $srcWidth == 0 ) {
1084 return 0;
1085 } else {
1086 return round( $srcHeight * $dstWidth / $srcWidth );
1087 }
1088 }
1089
1090 /**
1091 * Get an image size array like that returned by getImageSize(), or false if it
1092 * can't be determined.
1093 *
1094 * @param $fileName String: The filename
1095 * @return Array
1096 */
1097 function getImageSize( $fileName ) {
1098 if ( !$this->getHandler() ) {
1099 return false;
1100 }
1101 return $this->handler->getImageSize( $this, $fileName );
1102 }
1103
1104 /**
1105 * Get the URL of the image description page. May return false if it is
1106 * unknown or not applicable.
1107 */
1108 function getDescriptionUrl() {
1109 return $this->repo->getDescriptionUrl( $this->getName() );
1110 }
1111
1112 /**
1113 * Get the HTML text of the description page, if available
1114 * For local files ImagePage does not use it, because it skips the parser cache.
1115 */
1116 function getDescriptionText() {
1117 if( $this->isLocal() ) {
1118 global $wgParser;
1119 $revision = Revision::newFromTitle( $this->title );
1120 if ( !$revision ) return false;
1121 $text = $revision->getText();
1122 if ( !$text ) return false;
1123 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1124 return $pout->getText();
1125 }
1126
1127 global $wgMemc, $wgLang;
1128 if ( !$this->repo->fetchDescription ) {
1129 return false;
1130 }
1131 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1132 if ( $renderUrl ) {
1133 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1134 wfDebug("Attempting to get the description from cache...");
1135 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1136 $this->getName() );
1137 $obj = $wgMemc->get($key);
1138 if ($obj) {
1139 wfDebug("success!\n");
1140 return $obj;
1141 }
1142 wfDebug("miss\n");
1143 }
1144 wfDebug( "Fetching shared description from $renderUrl\n" );
1145 $res = Http::get( $renderUrl );
1146 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
1147 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
1148 }
1149 return $res;
1150 } else {
1151 return false;
1152 }
1153 }
1154
1155 /**
1156 * Get discription of file revision
1157 * STUB
1158 */
1159 function getDescription() {
1160 return null;
1161 }
1162
1163 /**
1164 * Get the 14-character timestamp of the file upload, or false if
1165 * it doesn't exist
1166 */
1167 function getTimestamp() {
1168 $path = $this->getPath();
1169 if ( !file_exists( $path ) ) {
1170 return false;
1171 }
1172 return wfTimestamp( TS_MW, filemtime( $path ) );
1173 }
1174
1175 /**
1176 * Get the SHA-1 base 36 hash of the file
1177 */
1178 function getSha1() {
1179 return self::sha1Base36( $this->getPath() );
1180 }
1181
1182 /**
1183 * Get the deletion archive key, <sha1>.<ext>
1184 */
1185 function getStorageKey() {
1186 $hash = $this->getSha1();
1187 if ( !$hash ) {
1188 return false;
1189 }
1190 $ext = $this->getExtension();
1191 $dotExt = $ext === '' ? '' : ".$ext";
1192 return $hash . $dotExt;
1193 }
1194
1195 /**
1196 * Determine if the current user is allowed to view a particular
1197 * field of this file, if it's marked as deleted.
1198 * STUB
1199 * @param $field Integer
1200 * @return Boolean
1201 */
1202 function userCan( $field ) {
1203 return true;
1204 }
1205
1206 /**
1207 * Get an associative array containing information about a file in the local filesystem.
1208 *
1209 * @param $path String: absolute local filesystem path
1210 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1211 * Set it to false to ignore the extension.
1212 */
1213 static function getPropsFromPath( $path, $ext = true ) {
1214 wfProfileIn( __METHOD__ );
1215 wfDebug( __METHOD__.": Getting file info for $path\n" );
1216 $info = array(
1217 'fileExists' => file_exists( $path ) && !is_dir( $path )
1218 );
1219 $gis = false;
1220 if ( $info['fileExists'] ) {
1221 $magic = MimeMagic::singleton();
1222
1223 if ( $ext === true ) {
1224 $i = strrpos( $path, '.' );
1225 $ext = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1226 }
1227
1228 # mime type according to file contents
1229 $info['file-mime'] = $magic->guessMimeType( $path, false );
1230 # logical mime type
1231 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1232
1233 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1234 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1235
1236 # Get size in bytes
1237 $info['size'] = filesize( $path );
1238
1239 # Height, width and metadata
1240 $handler = MediaHandler::getHandler( $info['mime'] );
1241 if ( $handler ) {
1242 $tempImage = (object)array();
1243 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1244 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1245 } else {
1246 $gis = false;
1247 $info['metadata'] = '';
1248 }
1249 $info['sha1'] = self::sha1Base36( $path );
1250
1251 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1252 } else {
1253 $info['mime'] = null;
1254 $info['media_type'] = MEDIATYPE_UNKNOWN;
1255 $info['metadata'] = '';
1256 $info['sha1'] = '';
1257 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1258 }
1259 if( $gis ) {
1260 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1261 $info['width'] = $gis[0];
1262 $info['height'] = $gis[1];
1263 if ( isset( $gis['bits'] ) ) {
1264 $info['bits'] = $gis['bits'];
1265 } else {
1266 $info['bits'] = 0;
1267 }
1268 } else {
1269 $info['width'] = 0;
1270 $info['height'] = 0;
1271 $info['bits'] = 0;
1272 }
1273 wfProfileOut( __METHOD__ );
1274 return $info;
1275 }
1276
1277 /**
1278 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1279 * encoding, zero padded to 31 digits.
1280 *
1281 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1282 * fairly neatly.
1283 *
1284 * Returns false on failure
1285 */
1286 static function sha1Base36( $path ) {
1287 wfSuppressWarnings();
1288 $hash = sha1_file( $path );
1289 wfRestoreWarnings();
1290 if ( $hash === false ) {
1291 return false;
1292 } else {
1293 return wfBaseConvert( $hash, 16, 36, 31 );
1294 }
1295 }
1296
1297 function getLongDesc() {
1298 $handler = $this->getHandler();
1299 if ( $handler ) {
1300 return $handler->getLongDesc( $this );
1301 } else {
1302 return MediaHandler::getGeneralLongDesc( $this );
1303 }
1304 }
1305
1306 function getShortDesc() {
1307 $handler = $this->getHandler();
1308 if ( $handler ) {
1309 return $handler->getShortDesc( $this );
1310 } else {
1311 return MediaHandler::getGeneralShortDesc( $this );
1312 }
1313 }
1314
1315 function getDimensionsString() {
1316 $handler = $this->getHandler();
1317 if ( $handler ) {
1318 return $handler->getDimensionsString( $this );
1319 } else {
1320 return '';
1321 }
1322 }
1323
1324 function getRedirected() {
1325 return $this->redirected;
1326 }
1327
1328 function getRedirectedTitle() {
1329 if ( $this->redirected ) {
1330 if ( !$this->redirectTitle )
1331 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
1332 return $this->redirectTitle;
1333 }
1334 }
1335
1336 function redirectedFrom( $from ) {
1337 $this->redirected = $from;
1338 }
1339
1340 function isMissing() {
1341 return false;
1342 }
1343 }
1344 /**
1345 * Aliases for backwards compatibility with 1.6
1346 */
1347 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1348 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1349 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1350 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );