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