10 * Implements some public methods and some protected utility functions which
11 * are required by multiple child classes. Contains stub functionality for
12 * unimplemented public methods.
14 * Stub functions which should be overridden are marked with STUB. Some more
15 * concrete functions are also typically overridden by child classes.
17 * Note that only the repo object knows what its file class is called. You should
18 * never name a file class explictly outside of the repo class. Instead use the
19 * repo's factory functions to generate file objects, for example:
21 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
23 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
29 const DELETED_FILE
= 1;
30 const DELETED_COMMENT
= 2;
31 const DELETED_USER
= 4;
32 const DELETED_RESTRICTED
= 8;
35 const DELETE_SOURCE
= 1;
38 * Some member variables can be lazy-initialised using __get(). The
39 * initialisation function for these variables is always a function named
40 * like getVar(), where Var is the variable name with upper-case first
43 * The following variables are initialised in this way in this base class:
44 * name, extension, handler, path, canRender, isSafeFile,
45 * transformScript, hashPath, pageCount, url
47 * Code within this class should generally use the accessor function
48 * directly, since __get() isn't re-entrant and therefore causes bugs that
49 * depend on initialisation order.
53 * The following member variables are not lazy-initialised
55 var $repo, $title, $lastError, $redirected, $redirectedTitle;
58 * Call this constructor from child classes
60 function __construct( $title, $repo ) {
61 $this->title
= $title;
65 function __get( $name ) {
66 $function = array( $this, 'get' . ucfirst( $name ) );
67 if ( !is_callable( $function ) ) {
70 $this->$name = call_user_func( $function );
76 * Normalize a file extension to the common form, and ensure it's clean.
77 * Extensions with non-alphanumeric characters will be discarded.
79 * @param $ext string (without the .)
82 static function normalizeExtension( $ext ) {
83 $lower = strtolower( $ext );
90 if( isset( $squish[$lower] ) ) {
91 return $squish[$lower];
92 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
100 * Checks if file extensions are compatible
102 * @param $old File Old file
103 * @param $new string New name
105 static function checkExtensionCompatibility( File
$old, $new ) {
106 $oldMime = $old->getMimeType();
107 $n = strrpos( $new, '.' );
108 $newExt = self
::normalizeExtension(
109 $n ?
substr( $new, $n +
1 ) : '' );
110 $mimeMagic = MimeMagic
::singleton();
111 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
115 * Upgrade the database row if there is one
116 * Called by ImagePage
119 function upgradeRow() {}
122 * Split an internet media type into its two components; if not
123 * a two-part name, set the minor type to 'unknown'.
125 * @param $mime "text/html" etc
126 * @return array ("text", "html") etc
128 static function splitMime( $mime ) {
129 if( strpos( $mime, '/' ) !== false ) {
130 return explode( '/', $mime, 2 );
132 return array( $mime, 'unknown' );
137 * Return the name of this file
139 public function getName() {
140 if ( !isset( $this->name
) ) {
141 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
147 * Get the file extension, e.g. "svg"
149 function getExtension() {
150 if ( !isset( $this->extension
) ) {
151 $n = strrpos( $this->getName(), '.' );
152 $this->extension
= self
::normalizeExtension(
153 $n ?
substr( $this->getName(), $n +
1 ) : '' );
155 return $this->extension
;
159 * Return the associated title object
162 public function getTitle() { return $this->title
; }
165 * Return the title used to find this file
167 public function getOriginalTitle() {
168 if ( $this->redirected
)
169 return $this->getRedirectedTitle();
174 * Return the URL of the file
176 public function getUrl() {
177 if ( !isset( $this->url
) ) {
178 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
184 * Return a fully-qualified URL to the file.
185 * Upload URL paths _may or may not_ be fully qualified, so
186 * we check. Local paths are assumed to belong on $wgServer.
190 public function getFullUrl() {
191 return wfExpandUrl( $this->getUrl() );
194 function getViewURL() {
195 if( $this->mustRender()) {
196 if( $this->canRender() ) {
197 return $this->createThumb( $this->getWidth() );
200 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
201 return $this->getURL(); #hm... return NULL?
204 return $this->getURL();
209 * Return the full filesystem path to the file. Note that this does
210 * not mean that a file actually exists under that location.
212 * This path depends on whether directory hashing is active or not,
213 * i.e. whether the files are all found in the same directory,
214 * or in hashed paths like /images/3/3c.
216 * May return false if the file is not locally accessible.
218 public function getPath() {
219 if ( !isset( $this->path
) ) {
220 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
226 * Alias for getPath()
228 public function getFullPath() {
229 return $this->getPath();
233 * Return the width of the image. Returns false if the width is unknown
237 * Overridden by LocalFile, UnregisteredLocalFile
239 public function getWidth( $page = 1 ) { return false; }
242 * Return the height of the image. Returns false if the height is unknown
246 * Overridden by LocalFile, UnregisteredLocalFile
248 public function getHeight( $page = 1 ) { return false; }
251 * Returns ID or name of user who uploaded the file
254 * @param $type string 'text' or 'id'
256 public function getUser( $type='text' ) { return null; }
259 * Get the duration of a media file in seconds
261 public function getLength() {
262 $handler = $this->getHandler();
264 return $handler->getLength( $this );
271 * Return true if the file is vectorized
273 public function isVectorized() {
274 $handler = $this->getHandler();
276 return $handler->isVectorized( $this );
284 * Get handler-specific metadata
285 * Overridden by LocalFile, UnregisteredLocalFile
288 public function getMetadata() { return false; }
291 * Return the bit depth of the file
292 * Overridden by LocalFile
295 public function getBitDepth() { return 0; }
298 * Return the size of the image file, in bytes
299 * Overridden by LocalFile, UnregisteredLocalFile
302 public function getSize() { return false; }
305 * Returns the mime type of the file.
306 * Overridden by LocalFile, UnregisteredLocalFile
309 function getMimeType() { return 'unknown/unknown'; }
312 * Return the type of the media in the file.
313 * Use the value returned by this function with the MEDIATYPE_xxx constants.
314 * Overridden by LocalFile,
317 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
320 * Checks if the output of transform() for this file is likely
321 * to be valid. If this is false, various user elements will
322 * display a placeholder instead.
324 * Currently, this checks if the file is an image format
325 * that can be converted to a format
326 * supported by all browsers (namely GIF, PNG and JPEG),
327 * or if it is an SVG image and SVG conversion is enabled.
329 function canRender() {
330 if ( !isset( $this->canRender
) ) {
331 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
333 return $this->canRender
;
337 * Accessor for __get()
339 protected function getCanRender() {
340 return $this->canRender();
344 * Return true if the file is of a type that can't be directly
345 * rendered by typical browsers and needs to be re-rasterized.
347 * This returns true for everything but the bitmap types
348 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
349 * also return true for any non-image formats.
353 function mustRender() {
354 return $this->getHandler() && $this->handler
->mustRender( $this );
358 * Alias for canRender()
360 function allowInlineDisplay() {
361 return $this->canRender();
365 * Determines if this media file is in a format that is unlikely to
366 * contain viruses or malicious content. It uses the global
367 * $wgTrustedMediaFormats list to determine if the file is safe.
369 * This is used to show a warning on the description page of non-safe files.
370 * It may also be used to disallow direct [[media:...]] links to such files.
372 * Note that this function will always return true if allowInlineDisplay()
373 * or isTrustedFile() is true for this file.
375 function isSafeFile() {
376 if ( !isset( $this->isSafeFile
) ) {
377 $this->isSafeFile
= $this->_getIsSafeFile();
379 return $this->isSafeFile
;
382 /** Accessor for __get() */
383 protected function getIsSafeFile() {
384 return $this->isSafeFile();
387 /** Uncached accessor */
388 protected function _getIsSafeFile() {
389 if ($this->allowInlineDisplay()) return true;
390 if ($this->isTrustedFile()) return true;
392 global $wgTrustedMediaFormats;
394 $type= $this->getMediaType();
395 $mime= $this->getMimeType();
396 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
398 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
399 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
401 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
402 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
407 /** Returns true if the file is flagged as trusted. Files flagged that way
408 * can be linked to directly, even if that is not allowed for this type of
411 * This is a dummy function right now and always returns false. It could be
412 * implemented to extract a flag from the database. The trusted flag could be
413 * set on upload, if the user has sufficient privileges, to bypass script-
414 * and html-filters. It may even be coupled with cryptographics signatures
417 function isTrustedFile() {
418 #this could be implemented to check a flag in the databas,
419 #look for signatures, etc
424 * Returns true if file exists in the repository.
426 * Overridden by LocalFile to avoid unnecessary stat calls.
428 * @return boolean Whether file exists in the repository.
430 public function exists() {
431 return $this->getPath() && file_exists( $this->path
);
435 * Returns true if file exists in the repository and can be included in a page.
436 * It would be unsafe to include private images, making public thumbnails inadvertently
438 * @return boolean Whether file exists in the repository and is includable.
441 function isVisible() {
442 return $this->exists();
445 function getTransformScript() {
446 if ( !isset( $this->transformScript
) ) {
447 $this->transformScript
= false;
449 $script = $this->repo
->getThumbScriptUrl();
451 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
455 return $this->transformScript
;
459 * Get a ThumbnailImage which is the same size as the source
461 function getUnscaledThumb( $handlerParams = array() ) {
462 $hp =& $handlerParams;
463 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
464 $width = $this->getWidth( $page );
466 return $this->iconThumb();
468 $hp['width'] = $width;
469 return $this->transform( $hp );
473 * Return the file name of a thumbnail with the specified parameters
475 * @param $params Array: handler-specific parameters
478 function thumbName( $params ) {
479 if ( !$this->getHandler() ) {
482 $extension = $this->getExtension();
483 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
484 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
485 if ( $thumbExt != $extension ) {
486 $thumbName .= ".$thumbExt";
492 * Create a thumbnail of the image having the specified width/height.
493 * The thumbnail will not be created if the width is larger than the
494 * image's width. Let the browser do the scaling in this case.
495 * The thumbnail is stored on disk and is only computed if the thumbnail
496 * file does not exist OR if it is older than the image.
499 * Keeps aspect ratio of original image. If both width and height are
500 * specified, the generated image will be no bigger than width x height,
501 * and will also have correct aspect ratio.
503 * @param $width Integer: maximum width of the generated thumbnail
504 * @param $height Integer: maximum height of the image (optional)
506 public function createThumb( $width, $height = -1 ) {
507 $params = array( 'width' => $width );
508 if ( $height != -1 ) {
509 $params['height'] = $height;
511 $thumb = $this->transform( $params );
512 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
513 return $thumb->getUrl();
517 * As createThumb, but returns a ThumbnailImage object. This can
518 * provide access to the actual file, the real size of the thumb,
519 * and can produce a convenient \<img\> tag for you.
521 * For non-image formats, this may return a filetype-specific icon.
523 * @param $width Integer: maximum width of the generated thumbnail
524 * @param $height Integer: maximum height of the image (optional)
525 * @param $render Integer: Deprecated
527 * @return ThumbnailImage or null on failure
529 * @deprecated use transform()
531 public function getThumbnail( $width, $height=-1, $render = true ) {
532 wfDeprecated( __METHOD__
);
533 $params = array( 'width' => $width );
534 if ( $height != -1 ) {
535 $params['height'] = $height;
537 return $this->transform( $params, 0 );
541 * Transform a media file
543 * @param $params Array: an associative array of handler-specific parameters.
544 * Typical keys are width, height and page.
545 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
546 * @return MediaTransformOutput | false
548 function transform( $params, $flags = 0 ) {
549 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
551 wfProfileIn( __METHOD__
);
553 if ( !$this->canRender() ) {
554 // not a bitmap or renderable image, don't try.
555 $thumb = $this->iconThumb();
559 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
560 $descriptionUrl = $this->getDescriptionUrl();
561 if ( $descriptionUrl ) {
562 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
565 $script = $this->getTransformScript();
566 if ( $script && !($flags & self
::RENDER_NOW
) ) {
567 // Use a script to transform on client request, if possible
568 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
574 $normalisedParams = $params;
575 $this->handler
->normaliseParams( $this, $normalisedParams );
576 $thumbName = $this->thumbName( $normalisedParams );
577 $thumbPath = $this->getThumbPath( $thumbName );
578 $thumbUrl = $this->getThumbUrl( $thumbName );
580 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
581 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
585 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
586 $this->migrateThumbFile( $thumbName );
587 if ( file_exists( $thumbPath )) {
588 $thumbTime = filemtime( $thumbPath );
589 if ( $thumbTime !== FALSE &&
590 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
592 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
596 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
598 // Ignore errors if requested
601 } elseif ( $thumb->isError() ) {
602 $this->lastError
= $thumb->toText();
603 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
604 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
608 // Purge. Useful in the event of Core -> Squid connection failure or squid
609 // purge collisions from elsewhere during failure. Don't keep triggering for
610 // "thumbs" which have the main image URL though (bug 13776)
611 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
612 SquidUpdate
::purge( array( $thumbUrl ) );
616 wfProfileOut( __METHOD__
);
617 return is_object( $thumb ) ?
$thumb : false;
621 * Hook into transform() to allow migration of thumbnail files
623 * Overridden by LocalFile
625 function migrateThumbFile( $thumbName ) {}
628 * Get a MediaHandler instance for this file
630 function getHandler() {
631 if ( !isset( $this->handler
) ) {
632 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
634 return $this->handler
;
638 * Get a ThumbnailImage representing a file type icon
639 * @return ThumbnailImage
641 function iconThumb() {
642 global $wgStylePath, $wgStyleDirectory;
644 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
645 foreach( $try as $icon ) {
646 $path = '/common/images/icons/' . $icon;
647 $filepath = $wgStyleDirectory . $path;
648 if( file_exists( $filepath ) ) {
649 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
656 * Get last thumbnailing error.
659 function getLastError() {
660 return $this->lastError
;
664 * Get all thumbnail names previously generated for this file
666 * Overridden by LocalFile
668 function getThumbnails() { return array(); }
671 * Purge shared caches such as thumbnails and DB data caching
673 * Overridden by LocalFile
675 function purgeCache() {}
678 * Purge the file description page, but don't go after
679 * pages using the file. Use when modifying file history
680 * but not the current data.
682 function purgeDescription() {
683 $title = $this->getTitle();
685 $title->invalidateCache();
686 $title->purgeSquid();
691 * Purge metadata and all affected pages when the file is created,
692 * deleted, or majorly updated.
694 function purgeEverything() {
695 // Delete thumbnails and refresh file metadata cache
697 $this->purgeDescription();
699 // Purge cache of all pages using this file
700 $title = $this->getTitle();
702 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
708 * Return a fragment of the history of file.
711 * @param $limit integer Limit of rows to return
712 * @param $start timestamp Only revisions older than $start will be returned
713 * @param $end timestamp Only revisions newer than $end will be returned
714 * @param $inc bool Include the endpoints of the time range
716 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
721 * Return the history of this file, line by line. Starts with current version,
722 * then old versions. Should return an object similar to an image/oldimage
726 * Overridden in LocalFile
728 public function nextHistoryLine() {
733 * Reset the history pointer to the first element of the history.
734 * Always call this function after using nextHistoryLine() to free db resources
736 * Overridden in LocalFile.
738 public function resetHistory() {}
741 * Get the filename hash component of the directory including trailing slash,
743 * If the repository is not hashed, returns an empty string.
745 function getHashPath() {
746 if ( !isset( $this->hashPath
) ) {
747 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
749 return $this->hashPath
;
753 * Get the path of the file relative to the public zone root
756 return $this->getHashPath() . $this->getName();
760 * Get urlencoded relative path of the file
762 function getUrlRel() {
763 return $this->getHashPath() . rawurlencode( $this->getName() );
766 /** Get the relative path for an archive file */
767 function getArchiveRel( $suffix = false ) {
768 $path = 'archive/' . $this->getHashPath();
769 if ( $suffix === false ) {
770 $path = substr( $path, 0, -1 );
777 /** Get the path of the archive directory, or a particular file if $suffix is specified */
778 function getArchivePath( $suffix = false ) {
779 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
782 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
783 function getThumbPath( $suffix = false ) {
784 $path = $this->repo
->getZonePath('thumb') . '/' . $this->getRel();
785 if ( $suffix !== false ) {
786 $path .= '/' . $suffix;
791 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
792 function getArchiveUrl( $suffix = false ) {
793 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
794 if ( $suffix === false ) {
795 $path = substr( $path, 0, -1 );
797 $path .= rawurlencode( $suffix );
802 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
803 function getThumbUrl( $suffix = false ) {
804 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
805 if ( $suffix !== false ) {
806 $path .= '/' . rawurlencode( $suffix );
811 /** Get the virtual URL for an archive file or directory */
812 function getArchiveVirtualUrl( $suffix = false ) {
813 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
814 if ( $suffix === false ) {
815 $path = substr( $path, 0, -1 );
817 $path .= rawurlencode( $suffix );
822 /** Get the virtual URL for a thumbnail file or directory */
823 function getThumbVirtualUrl( $suffix = false ) {
824 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
825 if ( $suffix !== false ) {
826 $path .= '/' . rawurlencode( $suffix );
831 /** Get the virtual URL for the file itself */
832 function getVirtualUrl( $suffix = false ) {
833 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
834 if ( $suffix !== false ) {
835 $path .= '/' . rawurlencode( $suffix );
843 function isHashed() {
844 return $this->repo
->isHashed();
847 function readOnlyError() {
848 throw new MWException( get_class($this) . ': write operations are not supported' );
852 * Record a file upload in the upload log and the image table
854 * Overridden by LocalFile
856 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
857 $this->readOnlyError();
861 * Move or copy a file to its public location. If a file exists at the
862 * destination, move it to an archive. Returns a FileRepoStatus object with
863 * the archive name in the "value" member on success.
865 * The archive name should be passed through to recordUpload for database
868 * @param $srcPath String: local filesystem path to the source image
869 * @param $flags Integer: a bitwise combination of:
870 * File::DELETE_SOURCE Delete the source file, i.e. move
872 * @return FileRepoStatus object. On success, the value member contains the
873 * archive name, or an empty string if it was a new file.
876 * Overridden by LocalFile
878 function publish( $srcPath, $flags = 0 ) {
879 $this->readOnlyError();
883 * Get an array of Title objects which are articles which use this file
884 * Also adds their IDs to the link cache
886 * This is mostly copied from Title::getLinksTo()
888 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
890 function getLinksTo( $options = array() ) {
891 wfDeprecated( __METHOD__
);
892 wfProfileIn( __METHOD__
);
894 // Note: use local DB not repo DB, we want to know local links
895 if ( count( $options ) > 0 ) {
896 $db = wfGetDB( DB_MASTER
);
898 $db = wfGetDB( DB_SLAVE
);
900 $linkCache = LinkCache
::singleton();
902 $encName = $db->addQuotes( $this->getName() );
903 $res = $db->select( array( 'page', 'imagelinks'),
904 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
905 array( 'page_id=il_from', 'il_to' => $encName ),
910 if ( $db->numRows( $res ) ) {
911 foreach ( $res as $row ) {
912 $titleObj = Title
::newFromRow( $row );
914 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
915 $retVal[] = $titleObj;
919 wfProfileOut( __METHOD__
);
923 function formatMetadata() {
924 if ( !$this->getHandler() ) {
927 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
931 * Returns true if the file comes from the local file repository.
936 $repo = $this->getRepo();
937 return $repo && $repo->isLocal();
941 * Returns the name of the repository.
945 function getRepoName() {
946 return $this->repo ?
$this->repo
->getName() : 'unknown';
949 * Returns the repository
956 * Returns true if the image is an old version
964 * Is this file a "deleted" file in a private archive?
967 function isDeleted( $field ) {
972 * Return the deletion bitfield
975 function getVisibility() {
980 * Was this file ever deleted from the wiki?
984 function wasDeleted() {
985 $title = $this->getTitle();
986 return $title && $title->isDeletedQuick();
990 * Move file to the new title
992 * Move current, old version and all thumbnails
993 * to the new filename. Old file is deleted.
995 * Cache purging is done; checks for validity
996 * and logging are caller's responsibility
998 * @param $target Title New file name
999 * @return FileRepoStatus object.
1001 function move( $target ) {
1002 $this->readOnlyError();
1006 * Delete all versions of the file.
1008 * Moves the files into an archive directory (or deletes them)
1009 * and removes the database rows.
1011 * Cache purging is done; logging is caller's responsibility.
1013 * @param $reason String
1014 * @param $suppress Boolean: hide content from sysops?
1015 * @return true on success, false on some kind of failure
1017 * Overridden by LocalFile
1019 function delete( $reason, $suppress = false ) {
1020 $this->readOnlyError();
1024 * Restore all or specified deleted revisions to the given file.
1025 * Permissions and logging are left to the caller.
1027 * May throw database exceptions on error.
1029 * @param $versions set of record ids of deleted items to restore,
1030 * or empty to restore all revisions.
1031 * @param $unsuppress remove restrictions on content upon restoration?
1032 * @return the number of file revisions restored if successful,
1033 * or false on failure
1035 * Overridden by LocalFile
1037 function restore( $versions=array(), $unsuppress=false ) {
1038 $this->readOnlyError();
1042 * Returns 'true' if this file is a type which supports multiple pages,
1043 * e.g. DJVU or PDF. Note that this may be true even if the file in
1044 * question only has a single page.
1048 function isMultipage() {
1049 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1053 * Returns the number of pages of a multipage document, or false for
1054 * documents which aren't multipage documents
1056 function pageCount() {
1057 if ( !isset( $this->pageCount
) ) {
1058 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1059 $this->pageCount
= $this->handler
->pageCount( $this );
1061 $this->pageCount
= false;
1064 return $this->pageCount
;
1068 * Calculate the height of a thumbnail using the source and destination width
1070 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1071 // Exact integer multiply followed by division
1072 if ( $srcWidth == 0 ) {
1075 return round( $srcHeight * $dstWidth / $srcWidth );
1080 * Get an image size array like that returned by getImageSize(), or false if it
1081 * can't be determined.
1083 * @param $fileName String: The filename
1086 function getImageSize( $fileName ) {
1087 if ( !$this->getHandler() ) {
1090 return $this->handler
->getImageSize( $this, $fileName );
1094 * Get the URL of the image description page. May return false if it is
1095 * unknown or not applicable.
1097 function getDescriptionUrl() {
1098 return $this->repo
->getDescriptionUrl( $this->getName() );
1102 * Get the HTML text of the description page, if available
1103 * For local files ImagePage does not use it, because it skips the parser cache.
1105 function getDescriptionText() {
1106 if( $this->isLocal() ) {
1108 $revision = Revision
::newFromTitle( $this->title
);
1109 if ( !$revision ) return false;
1110 $text = $revision->getText();
1111 if ( !$text ) return false;
1112 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1113 return $pout->getText();
1116 global $wgMemc, $wgLang;
1117 if ( !$this->repo
->fetchDescription
) {
1120 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1122 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1123 wfDebug("Attempting to get the description from cache...");
1124 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1126 $obj = $wgMemc->get($key);
1128 wfDebug("success!\n");
1133 wfDebug( "Fetching shared description from $renderUrl\n" );
1134 $res = Http
::get( $renderUrl );
1135 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1136 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1145 * Get discription of file revision
1148 function getDescription() {
1153 * Get the 14-character timestamp of the file upload, or false if
1156 function getTimestamp() {
1157 $path = $this->getPath();
1158 if ( !file_exists( $path ) ) {
1161 return wfTimestamp( TS_MW
, filemtime( $path ) );
1165 * Get the SHA-1 base 36 hash of the file
1167 function getSha1() {
1168 return self
::sha1Base36( $this->getPath() );
1172 * Get the deletion archive key, <sha1>.<ext>
1174 function getStorageKey() {
1175 $hash = $this->getSha1();
1179 $ext = $this->getExtension();
1180 $dotExt = $ext === '' ?
'' : ".$ext";
1181 return $hash . $dotExt;
1185 * Determine if the current user is allowed to view a particular
1186 * field of this file, if it's marked as deleted.
1188 * @param $field Integer
1191 function userCan( $field ) {
1196 * Get an associative array containing information about a file in the local filesystem.
1198 * @param $path String: absolute local filesystem path
1199 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1200 * Set it to false to ignore the extension.
1202 static function getPropsFromPath( $path, $ext = true ) {
1203 wfProfileIn( __METHOD__
);
1204 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1206 'fileExists' => file_exists( $path ) && !is_dir( $path )
1209 if ( $info['fileExists'] ) {
1210 $magic = MimeMagic
::singleton();
1212 if ( $ext === true ) {
1213 $i = strrpos( $path, '.' );
1214 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1217 # mime type according to file contents
1218 $info['file-mime'] = $magic->guessMimeType( $path, false );
1220 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1222 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1223 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1226 $info['size'] = filesize( $path );
1228 # Height, width and metadata
1229 $handler = MediaHandler
::getHandler( $info['mime'] );
1231 $tempImage = (object)array();
1232 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1233 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1236 $info['metadata'] = '';
1238 $info['sha1'] = self
::sha1Base36( $path );
1240 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1242 $info['mime'] = null;
1243 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1244 $info['metadata'] = '';
1246 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1249 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1250 $info['width'] = $gis[0];
1251 $info['height'] = $gis[1];
1252 if ( isset( $gis['bits'] ) ) {
1253 $info['bits'] = $gis['bits'];
1259 $info['height'] = 0;
1262 wfProfileOut( __METHOD__
);
1267 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1268 * encoding, zero padded to 31 digits.
1270 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1273 * Returns false on failure
1275 static function sha1Base36( $path ) {
1276 wfSuppressWarnings();
1277 $hash = sha1_file( $path );
1278 wfRestoreWarnings();
1279 if ( $hash === false ) {
1282 return wfBaseConvert( $hash, 16, 36, 31 );
1286 function getLongDesc() {
1287 $handler = $this->getHandler();
1289 return $handler->getLongDesc( $this );
1291 return MediaHandler
::getGeneralLongDesc( $this );
1295 function getShortDesc() {
1296 $handler = $this->getHandler();
1298 return $handler->getShortDesc( $this );
1300 return MediaHandler
::getGeneralShortDesc( $this );
1304 function getDimensionsString() {
1305 $handler = $this->getHandler();
1307 return $handler->getDimensionsString( $this );
1313 function getRedirected() {
1314 return $this->redirected
;
1317 function getRedirectedTitle() {
1318 if ( $this->redirected
) {
1319 if ( !$this->redirectTitle
)
1320 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1321 return $this->redirectTitle
;
1325 function redirectedFrom( $from ) {
1326 $this->redirected
= $from;
1329 function isMissing() {
1334 * Aliases for backwards compatibility with 1.6
1336 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1337 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1338 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1339 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);