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