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