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