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