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
66 var $lastError, $redirected, $redirectedTitle;
74 * Call this constructor from child classes
76 function __construct( $title, $repo ) {
77 $this->title
= $title;
81 function __get( $name ) {
82 $function = array( $this, 'get' . ucfirst( $name ) );
83 if ( !is_callable( $function ) ) {
86 $this->$name = call_user_func( $function );
92 * Normalize a file extension to the common form, and ensure it's clean.
93 * Extensions with non-alphanumeric characters will be discarded.
95 * @param $ext string (without the .)
98 static function normalizeExtension( $ext ) {
99 $lower = strtolower( $ext );
106 if( isset( $squish[$lower] ) ) {
107 return $squish[$lower];
108 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
116 * Checks if file extensions are compatible
118 * @param $old File Old file
119 * @param $new string New name
121 static function checkExtensionCompatibility( File
$old, $new ) {
122 $oldMime = $old->getMimeType();
123 $n = strrpos( $new, '.' );
124 $newExt = self
::normalizeExtension(
125 $n ?
substr( $new, $n +
1 ) : '' );
126 $mimeMagic = MimeMagic
::singleton();
127 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
131 * Upgrade the database row if there is one
132 * Called by ImagePage
135 function upgradeRow() {}
138 * Split an internet media type into its two components; if not
139 * a two-part name, set the minor type to 'unknown'.
141 * @param string $mime "text/html" etc
142 * @return array ("text", "html") etc
144 public static function splitMime( $mime ) {
145 if( strpos( $mime, '/' ) !== false ) {
146 return explode( '/', $mime, 2 );
148 return array( $mime, 'unknown' );
153 * Return the name of this file
155 public function getName() {
156 if ( !isset( $this->name
) ) {
157 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
163 * Get the file extension, e.g. "svg"
165 function getExtension() {
166 if ( !isset( $this->extension
) ) {
167 $n = strrpos( $this->getName(), '.' );
168 $this->extension
= self
::normalizeExtension(
169 $n ?
substr( $this->getName(), $n +
1 ) : '' );
171 return $this->extension
;
175 * Return the associated title object
178 public function getTitle() { return $this->title
; }
181 * Return the title used to find this file
183 public function getOriginalTitle() {
184 if ( $this->redirected
)
185 return $this->getRedirectedTitle();
190 * Return the URL of the file
192 public function getUrl() {
193 if ( !isset( $this->url
) ) {
194 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
200 * Return a fully-qualified URL to the file.
201 * Upload URL paths _may or may not_ be fully qualified, so
202 * we check. Local paths are assumed to belong on $wgServer.
206 public function getFullUrl() {
207 return wfExpandUrl( $this->getUrl() );
210 function getViewURL() {
211 if( $this->mustRender()) {
212 if( $this->canRender() ) {
213 return $this->createThumb( $this->getWidth() );
216 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
217 return $this->getURL(); #hm... return NULL?
220 return $this->getURL();
225 * Return the full filesystem path to the file. Note that this does
226 * not mean that a file actually exists under that location.
228 * This path depends on whether directory hashing is active or not,
229 * i.e. whether the files are all found in the same directory,
230 * or in hashed paths like /images/3/3c.
232 * May return false if the file is not locally accessible.
234 public function getPath() {
235 if ( !isset( $this->path
) ) {
236 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
242 * Alias for getPath()
244 public function getFullPath() {
245 return $this->getPath();
249 * Return the width of the image. Returns false if the width is unknown
253 * Overridden by LocalFile, UnregisteredLocalFile
255 public function getWidth( $page = 1 ) { return false; }
258 * Return the height of the image. Returns false if the height is unknown
262 * Overridden by LocalFile, UnregisteredLocalFile
264 public function getHeight( $page = 1 ) { return false; }
267 * Returns ID or name of user who uploaded the file
270 * @param $type string 'text' or 'id'
272 public function getUser( $type='text' ) { return null; }
275 * Get the duration of a media file in seconds
277 public function getLength() {
278 $handler = $this->getHandler();
280 return $handler->getLength( $this );
287 * Return true if the file is vectorized
289 public function isVectorized() {
290 $handler = $this->getHandler();
292 return $handler->isVectorized( $this );
300 * Get handler-specific metadata
301 * Overridden by LocalFile, UnregisteredLocalFile
304 public function getMetadata() { return false; }
307 * get versioned metadata
309 * @param $metadata Mixed Array or String of (serialized) metadata
310 * @param $version integer version number.
311 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
313 public function convertMetadataVersion($metadata, $version) {
314 $handler = $this->getHandler();
315 if ( !is_array( $metadata ) ) {
316 //just to make the return type consistant
317 $metadata = unserialize( $metadata );
320 return $handler->convertMetadataVersion( $metadata, $version );
327 * Return the bit depth of the file
328 * Overridden by LocalFile
331 public function getBitDepth() { return 0; }
334 * Return the size of the image file, in bytes
335 * Overridden by LocalFile, UnregisteredLocalFile
338 public function getSize() { return false; }
341 * Returns the mime type of the file.
342 * Overridden by LocalFile, UnregisteredLocalFile
345 function getMimeType() { return 'unknown/unknown'; }
348 * Return the type of the media in the file.
349 * Use the value returned by this function with the MEDIATYPE_xxx constants.
350 * Overridden by LocalFile,
353 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
356 * Checks if the output of transform() for this file is likely
357 * to be valid. If this is false, various user elements will
358 * display a placeholder instead.
360 * Currently, this checks if the file is an image format
361 * that can be converted to a format
362 * supported by all browsers (namely GIF, PNG and JPEG),
363 * or if it is an SVG image and SVG conversion is enabled.
365 function canRender() {
366 if ( !isset( $this->canRender
) ) {
367 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
369 return $this->canRender
;
373 * Accessor for __get()
375 protected function getCanRender() {
376 return $this->canRender();
380 * Return true if the file is of a type that can't be directly
381 * rendered by typical browsers and needs to be re-rasterized.
383 * This returns true for everything but the bitmap types
384 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
385 * also return true for any non-image formats.
389 function mustRender() {
390 return $this->getHandler() && $this->handler
->mustRender( $this );
394 * Alias for canRender()
396 function allowInlineDisplay() {
397 return $this->canRender();
401 * Determines if this media file is in a format that is unlikely to
402 * contain viruses or malicious content. It uses the global
403 * $wgTrustedMediaFormats list to determine if the file is safe.
405 * This is used to show a warning on the description page of non-safe files.
406 * It may also be used to disallow direct [[media:...]] links to such files.
408 * Note that this function will always return true if allowInlineDisplay()
409 * or isTrustedFile() is true for this file.
411 function isSafeFile() {
412 if ( !isset( $this->isSafeFile
) ) {
413 $this->isSafeFile
= $this->_getIsSafeFile();
415 return $this->isSafeFile
;
418 /** Accessor for __get() */
419 protected function getIsSafeFile() {
420 return $this->isSafeFile();
423 /** Uncached accessor */
424 protected function _getIsSafeFile() {
425 if ($this->allowInlineDisplay()) return true;
426 if ($this->isTrustedFile()) return true;
428 global $wgTrustedMediaFormats;
430 $type= $this->getMediaType();
431 $mime= $this->getMimeType();
432 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
434 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
435 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
437 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
438 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
443 /** Returns true if the file is flagged as trusted. Files flagged that way
444 * can be linked to directly, even if that is not allowed for this type of
447 * This is a dummy function right now and always returns false. It could be
448 * implemented to extract a flag from the database. The trusted flag could be
449 * set on upload, if the user has sufficient privileges, to bypass script-
450 * and html-filters. It may even be coupled with cryptographics signatures
453 function isTrustedFile() {
454 #this could be implemented to check a flag in the databas,
455 #look for signatures, etc
460 * Returns true if file exists in the repository.
462 * Overridden by LocalFile to avoid unnecessary stat calls.
464 * @return boolean Whether file exists in the repository.
466 public function exists() {
467 return $this->getPath() && file_exists( $this->path
);
471 * Returns true if file exists in the repository and can be included in a page.
472 * It would be unsafe to include private images, making public thumbnails inadvertently
474 * @return boolean Whether file exists in the repository and is includable.
476 public function isVisible() {
477 return $this->exists();
480 function getTransformScript() {
481 if ( !isset( $this->transformScript
) ) {
482 $this->transformScript
= false;
484 $script = $this->repo
->getThumbScriptUrl();
486 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
490 return $this->transformScript
;
494 * Get a ThumbnailImage which is the same size as the source
496 function getUnscaledThumb( $handlerParams = array() ) {
497 $hp =& $handlerParams;
498 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
499 $width = $this->getWidth( $page );
501 return $this->iconThumb();
503 $hp['width'] = $width;
504 return $this->transform( $hp );
508 * Return the file name of a thumbnail with the specified parameters
510 * @param $params Array: handler-specific parameters
513 function thumbName( $params ) {
514 return $this->generateThumbName( $this->getName(), $params );
518 * Generate a thumbnail file name from a name and specified parameters
520 * @param string $name
521 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
523 function generateThumbName( $name, $params ) {
524 if ( !$this->getHandler() ) {
527 $extension = $this->getExtension();
528 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
529 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
530 if ( $thumbExt != $extension ) {
531 $thumbName .= ".$thumbExt";
537 * Create a thumbnail of the image having the specified width/height.
538 * The thumbnail will not be created if the width is larger than the
539 * image's width. Let the browser do the scaling in this case.
540 * The thumbnail is stored on disk and is only computed if the thumbnail
541 * file does not exist OR if it is older than the image.
544 * Keeps aspect ratio of original image. If both width and height are
545 * specified, the generated image will be no bigger than width x height,
546 * and will also have correct aspect ratio.
548 * @param $width Integer: maximum width of the generated thumbnail
549 * @param $height Integer: maximum height of the image (optional)
551 public function createThumb( $width, $height = -1 ) {
552 $params = array( 'width' => $width );
553 if ( $height != -1 ) {
554 $params['height'] = $height;
556 $thumb = $this->transform( $params );
557 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
558 return $thumb->getUrl();
562 * As createThumb, but returns a ThumbnailImage object. This can
563 * provide access to the actual file, the real size of the thumb,
564 * and can produce a convenient \<img\> tag for you.
566 * For non-image formats, this may return a filetype-specific icon.
568 * @param $width Integer: maximum width of the generated thumbnail
569 * @param $height Integer: maximum height of the image (optional)
570 * @param $render Integer: Deprecated
572 * @return ThumbnailImage or null on failure
574 * @deprecated use transform()
576 public function getThumbnail( $width, $height=-1, $render = true ) {
577 wfDeprecated( __METHOD__
);
578 $params = array( 'width' => $width );
579 if ( $height != -1 ) {
580 $params['height'] = $height;
582 return $this->transform( $params, 0 );
586 * Transform a media file
588 * @param $params Array: an associative array of handler-specific parameters.
589 * Typical keys are width, height and page.
590 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
591 * @return MediaTransformOutput | false
593 function transform( $params, $flags = 0 ) {
594 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
596 wfProfileIn( __METHOD__
);
598 if ( !$this->canRender() ) {
599 // not a bitmap or renderable image, don't try.
600 $thumb = $this->iconThumb();
604 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
605 $descriptionUrl = $this->getDescriptionUrl();
606 if ( $descriptionUrl ) {
607 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
610 $script = $this->getTransformScript();
611 if ( $script && !($flags & self
::RENDER_NOW
) ) {
612 // Use a script to transform on client request, if possible
613 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
619 $normalisedParams = $params;
620 $this->handler
->normaliseParams( $this, $normalisedParams );
621 $thumbName = $this->thumbName( $normalisedParams );
622 $thumbPath = $this->getThumbPath( $thumbName );
623 $thumbUrl = $this->getThumbUrl( $thumbName );
625 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
626 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
630 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
631 $this->migrateThumbFile( $thumbName );
632 if ( file_exists( $thumbPath )) {
633 $thumbTime = filemtime( $thumbPath );
634 if ( $thumbTime !== FALSE &&
635 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
637 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
641 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
643 // Ignore errors if requested
646 } elseif ( $thumb->isError() ) {
647 $this->lastError
= $thumb->toText();
648 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
649 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
653 // Purge. Useful in the event of Core -> Squid connection failure or squid
654 // purge collisions from elsewhere during failure. Don't keep triggering for
655 // "thumbs" which have the main image URL though (bug 13776)
656 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
657 SquidUpdate
::purge( array( $thumbUrl ) );
661 wfProfileOut( __METHOD__
);
662 return is_object( $thumb ) ?
$thumb : false;
666 * Hook into transform() to allow migration of thumbnail files
668 * Overridden by LocalFile
670 function migrateThumbFile( $thumbName ) {}
673 * Get a MediaHandler instance for this file
674 * @return MediaHandler
676 function getHandler() {
677 if ( !isset( $this->handler
) ) {
678 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
680 return $this->handler
;
684 * Get a ThumbnailImage representing a file type icon
685 * @return ThumbnailImage
687 function iconThumb() {
688 global $wgStylePath, $wgStyleDirectory;
690 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
691 foreach( $try as $icon ) {
692 $path = '/common/images/icons/' . $icon;
693 $filepath = $wgStyleDirectory . $path;
694 if( file_exists( $filepath ) ) {
695 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
702 * Get last thumbnailing error.
705 function getLastError() {
706 return $this->lastError
;
710 * Get all thumbnail names previously generated for this file
712 * Overridden by LocalFile
714 function getThumbnails() { return array(); }
717 * Purge shared caches such as thumbnails and DB data caching
719 * Overridden by LocalFile
721 function purgeCache() {}
724 * Purge the file description page, but don't go after
725 * pages using the file. Use when modifying file history
726 * but not the current data.
728 function purgeDescription() {
729 $title = $this->getTitle();
731 $title->invalidateCache();
732 $title->purgeSquid();
737 * Purge metadata and all affected pages when the file is created,
738 * deleted, or majorly updated.
740 function purgeEverything() {
741 // Delete thumbnails and refresh file metadata cache
743 $this->purgeDescription();
745 // Purge cache of all pages using this file
746 $title = $this->getTitle();
748 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
754 * Return a fragment of the history of file.
757 * @param $limit integer Limit of rows to return
758 * @param $start timestamp Only revisions older than $start will be returned
759 * @param $end timestamp Only revisions newer than $end will be returned
760 * @param $inc bool Include the endpoints of the time range
762 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
767 * Return the history of this file, line by line. Starts with current version,
768 * then old versions. Should return an object similar to an image/oldimage
772 * Overridden in LocalFile
774 public function nextHistoryLine() {
779 * Reset the history pointer to the first element of the history.
780 * Always call this function after using nextHistoryLine() to free db resources
782 * Overridden in LocalFile.
784 public function resetHistory() {}
787 * Get the filename hash component of the directory including trailing slash,
789 * If the repository is not hashed, returns an empty string.
791 function getHashPath() {
792 if ( !isset( $this->hashPath
) ) {
793 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
795 return $this->hashPath
;
799 * Get the path of the file relative to the public zone root
802 return $this->getHashPath() . $this->getName();
806 * Get urlencoded relative path of the file
808 function getUrlRel() {
809 return $this->getHashPath() . rawurlencode( $this->getName() );
812 /** Get the relative path for an archive file */
813 function getArchiveRel( $suffix = false ) {
814 $path = 'archive/' . $this->getHashPath();
815 if ( $suffix === false ) {
816 $path = substr( $path, 0, -1 );
823 /** Get the path of the archive directory, or a particular file if $suffix is specified */
824 function getArchivePath( $suffix = false ) {
825 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
828 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
829 function getThumbPath( $suffix = false ) {
830 $path = $this->repo
->getZonePath('thumb') . '/' . $this->getRel();
831 if ( $suffix !== false ) {
832 $path .= '/' . $suffix;
837 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
838 function getArchiveUrl( $suffix = false ) {
839 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
840 if ( $suffix === false ) {
841 $path = substr( $path, 0, -1 );
843 $path .= rawurlencode( $suffix );
848 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
849 function getThumbUrl( $suffix = false ) {
850 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
851 if ( $suffix !== false ) {
852 $path .= '/' . rawurlencode( $suffix );
857 /** Get the virtual URL for an archive file or directory */
858 function getArchiveVirtualUrl( $suffix = false ) {
859 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
860 if ( $suffix === false ) {
861 $path = substr( $path, 0, -1 );
863 $path .= rawurlencode( $suffix );
868 /** Get the virtual URL for a thumbnail file or directory */
869 function getThumbVirtualUrl( $suffix = false ) {
870 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
871 if ( $suffix !== false ) {
872 $path .= '/' . rawurlencode( $suffix );
877 /** Get the virtual URL for the file itself */
878 function getVirtualUrl( $suffix = false ) {
879 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
880 if ( $suffix !== false ) {
881 $path .= '/' . rawurlencode( $suffix );
889 function isHashed() {
890 return $this->repo
->isHashed();
893 function readOnlyError() {
894 throw new MWException( get_class($this) . ': write operations are not supported' );
898 * Record a file upload in the upload log and the image table
900 * Overridden by LocalFile
902 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
903 $this->readOnlyError();
907 * Move or copy a file to its public location. If a file exists at the
908 * destination, move it to an archive. Returns a FileRepoStatus object with
909 * the archive name in the "value" member on success.
911 * The archive name should be passed through to recordUpload for database
914 * @param $srcPath String: local filesystem path to the source image
915 * @param $flags Integer: a bitwise combination of:
916 * File::DELETE_SOURCE Delete the source file, i.e. move
918 * @return FileRepoStatus object. On success, the value member contains the
919 * archive name, or an empty string if it was a new file.
922 * Overridden by LocalFile
924 function publish( $srcPath, $flags = 0 ) {
925 $this->readOnlyError();
929 * Get an array of Title objects which are articles which use this file
930 * Also adds their IDs to the link cache
932 * This is mostly copied from Title::getLinksTo()
934 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
936 function getLinksTo( $options = array() ) {
937 wfDeprecated( __METHOD__
);
938 wfProfileIn( __METHOD__
);
940 // Note: use local DB not repo DB, we want to know local links
941 if ( count( $options ) > 0 ) {
942 $db = wfGetDB( DB_MASTER
);
944 $db = wfGetDB( DB_SLAVE
);
946 $linkCache = LinkCache
::singleton();
948 $encName = $db->addQuotes( $this->getName() );
949 $res = $db->select( array( 'page', 'imagelinks'),
950 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
951 array( 'page_id=il_from', 'il_to' => $encName ),
956 if ( $db->numRows( $res ) ) {
957 foreach ( $res as $row ) {
958 $titleObj = Title
::newFromRow( $row );
960 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
961 $retVal[] = $titleObj;
965 wfProfileOut( __METHOD__
);
969 function formatMetadata() {
970 if ( !$this->getHandler() ) {
973 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
977 * Returns true if the file comes from the local file repository.
982 $repo = $this->getRepo();
983 return $repo && $repo->isLocal();
987 * Returns the name of the repository.
991 function getRepoName() {
992 return $this->repo ?
$this->repo
->getName() : 'unknown';
995 * Returns the repository
1002 * Returns true if the image is an old version
1010 * Is this file a "deleted" file in a private archive?
1013 function isDeleted( $field ) {
1018 * Return the deletion bitfield
1021 function getVisibility() {
1026 * Was this file ever deleted from the wiki?
1030 function wasDeleted() {
1031 $title = $this->getTitle();
1032 return $title && $title->isDeletedQuick();
1036 * Move file to the new title
1038 * Move current, old version and all thumbnails
1039 * to the new filename. Old file is deleted.
1041 * Cache purging is done; checks for validity
1042 * and logging are caller's responsibility
1044 * @param $target Title New file name
1045 * @return FileRepoStatus object.
1047 function move( $target ) {
1048 $this->readOnlyError();
1052 * Delete all versions of the file.
1054 * Moves the files into an archive directory (or deletes them)
1055 * and removes the database rows.
1057 * Cache purging is done; logging is caller's responsibility.
1059 * @param $reason String
1060 * @param $suppress Boolean: hide content from sysops?
1061 * @return true on success, false on some kind of failure
1063 * Overridden by LocalFile
1065 function delete( $reason, $suppress = false ) {
1066 $this->readOnlyError();
1070 * Restore all or specified deleted revisions to the given file.
1071 * Permissions and logging are left to the caller.
1073 * May throw database exceptions on error.
1075 * @param $versions set of record ids of deleted items to restore,
1076 * or empty to restore all revisions.
1077 * @param $unsuppress remove restrictions on content upon restoration?
1078 * @return the number of file revisions restored if successful,
1079 * or false on failure
1081 * Overridden by LocalFile
1083 function restore( $versions=array(), $unsuppress=false ) {
1084 $this->readOnlyError();
1088 * Returns 'true' if this file is a type which supports multiple pages,
1089 * e.g. DJVU or PDF. Note that this may be true even if the file in
1090 * question only has a single page.
1094 function isMultipage() {
1095 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1099 * Returns the number of pages of a multipage document, or false for
1100 * documents which aren't multipage documents
1102 function pageCount() {
1103 if ( !isset( $this->pageCount
) ) {
1104 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1105 $this->pageCount
= $this->handler
->pageCount( $this );
1107 $this->pageCount
= false;
1110 return $this->pageCount
;
1114 * Calculate the height of a thumbnail using the source and destination width
1116 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1117 // Exact integer multiply followed by division
1118 if ( $srcWidth == 0 ) {
1121 return round( $srcHeight * $dstWidth / $srcWidth );
1126 * Get an image size array like that returned by getImageSize(), or false if it
1127 * can't be determined.
1129 * @param $fileName String: The filename
1132 function getImageSize( $fileName ) {
1133 if ( !$this->getHandler() ) {
1136 return $this->handler
->getImageSize( $this, $fileName );
1140 * Get the URL of the image description page. May return false if it is
1141 * unknown or not applicable.
1143 function getDescriptionUrl() {
1144 return $this->repo
->getDescriptionUrl( $this->getName() );
1148 * Get the HTML text of the description page, if available
1150 function getDescriptionText() {
1151 global $wgMemc, $wgLang;
1152 if ( !$this->repo
->fetchDescription
) {
1155 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1157 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1158 wfDebug("Attempting to get the description from cache...");
1159 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1161 $obj = $wgMemc->get($key);
1163 wfDebug("success!\n");
1168 wfDebug( "Fetching shared description from $renderUrl\n" );
1169 $res = Http
::get( $renderUrl );
1170 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1171 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1180 * Get discription of file revision
1183 function getDescription() {
1188 * Get the 14-character timestamp of the file upload, or false if
1191 function getTimestamp() {
1192 $path = $this->getPath();
1193 if ( !file_exists( $path ) ) {
1196 return wfTimestamp( TS_MW
, filemtime( $path ) );
1200 * Get the SHA-1 base 36 hash of the file
1202 function getSha1() {
1203 return self
::sha1Base36( $this->getPath() );
1207 * Get the deletion archive key, <sha1>.<ext>
1209 function getStorageKey() {
1210 $hash = $this->getSha1();
1214 $ext = $this->getExtension();
1215 $dotExt = $ext === '' ?
'' : ".$ext";
1216 return $hash . $dotExt;
1220 * Determine if the current user is allowed to view a particular
1221 * field of this file, if it's marked as deleted.
1223 * @param $field Integer
1226 function userCan( $field ) {
1231 * Get an associative array containing information about a file in the local filesystem.
1233 * @param $path String: absolute local filesystem path
1234 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1235 * Set it to false to ignore the extension.
1237 static function getPropsFromPath( $path, $ext = true ) {
1238 wfProfileIn( __METHOD__
);
1239 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1241 'fileExists' => file_exists( $path ) && !is_dir( $path )
1244 if ( $info['fileExists'] ) {
1245 $magic = MimeMagic
::singleton();
1247 if ( $ext === true ) {
1248 $i = strrpos( $path, '.' );
1249 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1252 # mime type according to file contents
1253 $info['file-mime'] = $magic->guessMimeType( $path, false );
1255 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1257 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1258 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1261 $info['size'] = filesize( $path );
1263 # Height, width and metadata
1264 $handler = MediaHandler
::getHandler( $info['mime'] );
1266 $tempImage = (object)array();
1267 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1268 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1271 $info['metadata'] = '';
1273 $info['sha1'] = self
::sha1Base36( $path );
1275 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1277 $info['mime'] = null;
1278 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1279 $info['metadata'] = '';
1281 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1284 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1285 $info['width'] = $gis[0];
1286 $info['height'] = $gis[1];
1287 if ( isset( $gis['bits'] ) ) {
1288 $info['bits'] = $gis['bits'];
1294 $info['height'] = 0;
1297 wfProfileOut( __METHOD__
);
1302 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1303 * encoding, zero padded to 31 digits.
1305 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1308 * Returns false on failure
1310 static function sha1Base36( $path ) {
1311 wfSuppressWarnings();
1312 $hash = sha1_file( $path );
1313 wfRestoreWarnings();
1314 if ( $hash === false ) {
1317 return wfBaseConvert( $hash, 16, 36, 31 );
1321 function getLongDesc() {
1322 $handler = $this->getHandler();
1324 return $handler->getLongDesc( $this );
1326 return MediaHandler
::getGeneralLongDesc( $this );
1330 function getShortDesc() {
1331 $handler = $this->getHandler();
1333 return $handler->getShortDesc( $this );
1335 return MediaHandler
::getGeneralShortDesc( $this );
1339 function getDimensionsString() {
1340 $handler = $this->getHandler();
1342 return $handler->getDimensionsString( $this );
1348 function getRedirected() {
1349 return $this->redirected
;
1352 function getRedirectedTitle() {
1353 if ( $this->redirected
) {
1354 if ( !$this->redirectTitle
) {
1355 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1357 return $this->redirectTitle
;
1361 function redirectedFrom( $from ) {
1362 $this->redirected
= $from;
1365 function isMissing() {
1370 * Aliases for backwards compatibility with 1.6
1372 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1373 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1374 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1375 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);