898ac64a8a59fa0b58f614bb14a1a0e836dd9713
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 * Return the bit depth of the file
308 * Overridden by LocalFile
311 public function getBitDepth() { return 0; }
314 * Return the size of the image file, in bytes
315 * Overridden by LocalFile, UnregisteredLocalFile
318 public function getSize() { return false; }
321 * Returns the mime type of the file.
322 * Overridden by LocalFile, UnregisteredLocalFile
325 function getMimeType() { return 'unknown/unknown'; }
328 * Return the type of the media in the file.
329 * Use the value returned by this function with the MEDIATYPE_xxx constants.
330 * Overridden by LocalFile,
333 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
336 * Checks if the output of transform() for this file is likely
337 * to be valid. If this is false, various user elements will
338 * display a placeholder instead.
340 * Currently, this checks if the file is an image format
341 * that can be converted to a format
342 * supported by all browsers (namely GIF, PNG and JPEG),
343 * or if it is an SVG image and SVG conversion is enabled.
345 function canRender() {
346 if ( !isset( $this->canRender
) ) {
347 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
349 return $this->canRender
;
353 * Accessor for __get()
355 protected function getCanRender() {
356 return $this->canRender();
360 * Return true if the file is of a type that can't be directly
361 * rendered by typical browsers and needs to be re-rasterized.
363 * This returns true for everything but the bitmap types
364 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
365 * also return true for any non-image formats.
369 function mustRender() {
370 return $this->getHandler() && $this->handler
->mustRender( $this );
374 * Alias for canRender()
376 function allowInlineDisplay() {
377 return $this->canRender();
381 * Determines if this media file is in a format that is unlikely to
382 * contain viruses or malicious content. It uses the global
383 * $wgTrustedMediaFormats list to determine if the file is safe.
385 * This is used to show a warning on the description page of non-safe files.
386 * It may also be used to disallow direct [[media:...]] links to such files.
388 * Note that this function will always return true if allowInlineDisplay()
389 * or isTrustedFile() is true for this file.
391 function isSafeFile() {
392 if ( !isset( $this->isSafeFile
) ) {
393 $this->isSafeFile
= $this->_getIsSafeFile();
395 return $this->isSafeFile
;
398 /** Accessor for __get() */
399 protected function getIsSafeFile() {
400 return $this->isSafeFile();
403 /** Uncached accessor */
404 protected function _getIsSafeFile() {
405 if ($this->allowInlineDisplay()) return true;
406 if ($this->isTrustedFile()) return true;
408 global $wgTrustedMediaFormats;
410 $type= $this->getMediaType();
411 $mime= $this->getMimeType();
412 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
414 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
415 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
417 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
418 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
423 /** Returns true if the file is flagged as trusted. Files flagged that way
424 * can be linked to directly, even if that is not allowed for this type of
427 * This is a dummy function right now and always returns false. It could be
428 * implemented to extract a flag from the database. The trusted flag could be
429 * set on upload, if the user has sufficient privileges, to bypass script-
430 * and html-filters. It may even be coupled with cryptographics signatures
433 function isTrustedFile() {
434 #this could be implemented to check a flag in the databas,
435 #look for signatures, etc
440 * Returns true if file exists in the repository.
442 * Overridden by LocalFile to avoid unnecessary stat calls.
444 * @return boolean Whether file exists in the repository.
446 public function exists() {
447 return $this->getPath() && file_exists( $this->path
);
451 * Returns true if file exists in the repository and can be included in a page.
452 * It would be unsafe to include private images, making public thumbnails inadvertently
454 * @return boolean Whether file exists in the repository and is includable.
457 function isVisible() {
458 return $this->exists();
461 function getTransformScript() {
462 if ( !isset( $this->transformScript
) ) {
463 $this->transformScript
= false;
465 $script = $this->repo
->getThumbScriptUrl();
467 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
471 return $this->transformScript
;
475 * Get a ThumbnailImage which is the same size as the source
477 function getUnscaledThumb( $handlerParams = array() ) {
478 $hp =& $handlerParams;
479 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
480 $width = $this->getWidth( $page );
482 return $this->iconThumb();
484 $hp['width'] = $width;
485 return $this->transform( $hp );
489 * Return the file name of a thumbnail with the specified parameters
491 * @param $params Array: handler-specific parameters
494 function thumbName( $params ) {
495 return $this->generateThumbName( $this->getName(), $params );
499 * Generate a thumbnail file name from a name and specified parameters
501 * @param string $name
502 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
504 function generateThumbName( $name, $params ) {
505 if ( !$this->getHandler() ) {
508 $extension = $this->getExtension();
509 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
510 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
511 if ( $thumbExt != $extension ) {
512 $thumbName .= ".$thumbExt";
518 * Create a thumbnail of the image having the specified width/height.
519 * The thumbnail will not be created if the width is larger than the
520 * image's width. Let the browser do the scaling in this case.
521 * The thumbnail is stored on disk and is only computed if the thumbnail
522 * file does not exist OR if it is older than the image.
525 * Keeps aspect ratio of original image. If both width and height are
526 * specified, the generated image will be no bigger than width x height,
527 * and will also have correct aspect ratio.
529 * @param $width Integer: maximum width of the generated thumbnail
530 * @param $height Integer: maximum height of the image (optional)
532 public function createThumb( $width, $height = -1 ) {
533 $params = array( 'width' => $width );
534 if ( $height != -1 ) {
535 $params['height'] = $height;
537 $thumb = $this->transform( $params );
538 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
539 return $thumb->getUrl();
543 * As createThumb, but returns a ThumbnailImage object. This can
544 * provide access to the actual file, the real size of the thumb,
545 * and can produce a convenient \<img\> tag for you.
547 * For non-image formats, this may return a filetype-specific icon.
549 * @param $width Integer: maximum width of the generated thumbnail
550 * @param $height Integer: maximum height of the image (optional)
551 * @param $render Integer: Deprecated
553 * @return ThumbnailImage or null on failure
555 * @deprecated use transform()
557 public function getThumbnail( $width, $height=-1, $render = true ) {
558 wfDeprecated( __METHOD__
);
559 $params = array( 'width' => $width );
560 if ( $height != -1 ) {
561 $params['height'] = $height;
563 return $this->transform( $params, 0 );
567 * Transform a media file
569 * @param $params Array: an associative array of handler-specific parameters.
570 * Typical keys are width, height and page.
571 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
572 * @return MediaTransformOutput | false
574 function transform( $params, $flags = 0 ) {
575 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
577 wfProfileIn( __METHOD__
);
579 if ( !$this->canRender() ) {
580 // not a bitmap or renderable image, don't try.
581 $thumb = $this->iconThumb();
585 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
586 $descriptionUrl = $this->getDescriptionUrl();
587 if ( $descriptionUrl ) {
588 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
591 $script = $this->getTransformScript();
592 if ( $script && !($flags & self
::RENDER_NOW
) ) {
593 // Use a script to transform on client request, if possible
594 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
600 $normalisedParams = $params;
601 $this->handler
->normaliseParams( $this, $normalisedParams );
602 $thumbName = $this->thumbName( $normalisedParams );
603 $thumbPath = $this->getThumbPath( $thumbName );
604 $thumbUrl = $this->getThumbUrl( $thumbName );
606 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
607 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
611 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
612 $this->migrateThumbFile( $thumbName );
613 if ( file_exists( $thumbPath )) {
614 $thumbTime = filemtime( $thumbPath );
615 if ( $thumbTime !== FALSE &&
616 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
618 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
622 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
624 // Ignore errors if requested
627 } elseif ( $thumb->isError() ) {
628 $this->lastError
= $thumb->toText();
629 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
630 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
634 // Purge. Useful in the event of Core -> Squid connection failure or squid
635 // purge collisions from elsewhere during failure. Don't keep triggering for
636 // "thumbs" which have the main image URL though (bug 13776)
637 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
638 SquidUpdate
::purge( array( $thumbUrl ) );
642 wfProfileOut( __METHOD__
);
643 return is_object( $thumb ) ?
$thumb : false;
647 * Hook into transform() to allow migration of thumbnail files
649 * Overridden by LocalFile
651 function migrateThumbFile( $thumbName ) {}
654 * Get a MediaHandler instance for this file
655 * @return MediaHandler
657 function getHandler() {
658 if ( !isset( $this->handler
) ) {
659 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
661 return $this->handler
;
665 * Get a ThumbnailImage representing a file type icon
666 * @return ThumbnailImage
668 function iconThumb() {
669 global $wgStylePath, $wgStyleDirectory;
671 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
672 foreach( $try as $icon ) {
673 $path = '/common/images/icons/' . $icon;
674 $filepath = $wgStyleDirectory . $path;
675 if( file_exists( $filepath ) ) {
676 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
683 * Get last thumbnailing error.
686 function getLastError() {
687 return $this->lastError
;
691 * Get all thumbnail names previously generated for this file
693 * Overridden by LocalFile
695 function getThumbnails() { return array(); }
698 * Purge shared caches such as thumbnails and DB data caching
700 * Overridden by LocalFile
702 function purgeCache() {}
705 * Purge the file description page, but don't go after
706 * pages using the file. Use when modifying file history
707 * but not the current data.
709 function purgeDescription() {
710 $title = $this->getTitle();
712 $title->invalidateCache();
713 $title->purgeSquid();
718 * Purge metadata and all affected pages when the file is created,
719 * deleted, or majorly updated.
721 function purgeEverything() {
722 // Delete thumbnails and refresh file metadata cache
724 $this->purgeDescription();
726 // Purge cache of all pages using this file
727 $title = $this->getTitle();
729 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
735 * Return a fragment of the history of file.
738 * @param $limit integer Limit of rows to return
739 * @param $start timestamp Only revisions older than $start will be returned
740 * @param $end timestamp Only revisions newer than $end will be returned
741 * @param $inc bool Include the endpoints of the time range
743 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
748 * Return the history of this file, line by line. Starts with current version,
749 * then old versions. Should return an object similar to an image/oldimage
753 * Overridden in LocalFile
755 public function nextHistoryLine() {
760 * Reset the history pointer to the first element of the history.
761 * Always call this function after using nextHistoryLine() to free db resources
763 * Overridden in LocalFile.
765 public function resetHistory() {}
768 * Get the filename hash component of the directory including trailing slash,
770 * If the repository is not hashed, returns an empty string.
772 function getHashPath() {
773 if ( !isset( $this->hashPath
) ) {
774 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
776 return $this->hashPath
;
780 * Get the path of the file relative to the public zone root
783 return $this->getHashPath() . $this->getName();
787 * Get urlencoded relative path of the file
789 function getUrlRel() {
790 return $this->getHashPath() . rawurlencode( $this->getName() );
793 /** Get the relative path for an archive file */
794 function getArchiveRel( $suffix = false ) {
795 $path = 'archive/' . $this->getHashPath();
796 if ( $suffix === false ) {
797 $path = substr( $path, 0, -1 );
804 /** Get the path of the archive directory, or a particular file if $suffix is specified */
805 function getArchivePath( $suffix = false ) {
806 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
809 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
810 function getThumbPath( $suffix = false ) {
811 $path = $this->repo
->getZonePath('thumb') . '/' . $this->getRel();
812 if ( $suffix !== false ) {
813 $path .= '/' . $suffix;
818 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
819 function getArchiveUrl( $suffix = false ) {
820 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
821 if ( $suffix === false ) {
822 $path = substr( $path, 0, -1 );
824 $path .= rawurlencode( $suffix );
829 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
830 function getThumbUrl( $suffix = false ) {
831 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
832 if ( $suffix !== false ) {
833 $path .= '/' . rawurlencode( $suffix );
838 /** Get the virtual URL for an archive file or directory */
839 function getArchiveVirtualUrl( $suffix = false ) {
840 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
841 if ( $suffix === false ) {
842 $path = substr( $path, 0, -1 );
844 $path .= rawurlencode( $suffix );
849 /** Get the virtual URL for a thumbnail file or directory */
850 function getThumbVirtualUrl( $suffix = false ) {
851 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
852 if ( $suffix !== false ) {
853 $path .= '/' . rawurlencode( $suffix );
858 /** Get the virtual URL for the file itself */
859 function getVirtualUrl( $suffix = false ) {
860 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
861 if ( $suffix !== false ) {
862 $path .= '/' . rawurlencode( $suffix );
870 function isHashed() {
871 return $this->repo
->isHashed();
874 function readOnlyError() {
875 throw new MWException( get_class($this) . ': write operations are not supported' );
879 * Record a file upload in the upload log and the image table
881 * Overridden by LocalFile
883 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
884 $this->readOnlyError();
888 * Move or copy a file to its public location. If a file exists at the
889 * destination, move it to an archive. Returns a FileRepoStatus object with
890 * the archive name in the "value" member on success.
892 * The archive name should be passed through to recordUpload for database
895 * @param $srcPath String: local filesystem path to the source image
896 * @param $flags Integer: a bitwise combination of:
897 * File::DELETE_SOURCE Delete the source file, i.e. move
899 * @return FileRepoStatus object. On success, the value member contains the
900 * archive name, or an empty string if it was a new file.
903 * Overridden by LocalFile
905 function publish( $srcPath, $flags = 0 ) {
906 $this->readOnlyError();
910 * Get an array of Title objects which are articles which use this file
911 * Also adds their IDs to the link cache
913 * This is mostly copied from Title::getLinksTo()
915 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
917 function getLinksTo( $options = array() ) {
918 wfDeprecated( __METHOD__
);
919 wfProfileIn( __METHOD__
);
921 // Note: use local DB not repo DB, we want to know local links
922 if ( count( $options ) > 0 ) {
923 $db = wfGetDB( DB_MASTER
);
925 $db = wfGetDB( DB_SLAVE
);
927 $linkCache = LinkCache
::singleton();
929 $encName = $db->addQuotes( $this->getName() );
930 $res = $db->select( array( 'page', 'imagelinks'),
931 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
932 array( 'page_id=il_from', 'il_to' => $encName ),
937 if ( $db->numRows( $res ) ) {
938 foreach ( $res as $row ) {
939 $titleObj = Title
::newFromRow( $row );
941 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
942 $retVal[] = $titleObj;
946 wfProfileOut( __METHOD__
);
950 function formatMetadata() {
951 if ( !$this->getHandler() ) {
954 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
958 * Returns true if the file comes from the local file repository.
963 $repo = $this->getRepo();
964 return $repo && $repo->isLocal();
968 * Returns the name of the repository.
972 function getRepoName() {
973 return $this->repo ?
$this->repo
->getName() : 'unknown';
976 * Returns the repository
983 * Returns true if the image is an old version
991 * Is this file a "deleted" file in a private archive?
994 function isDeleted( $field ) {
999 * Return the deletion bitfield
1002 function getVisibility() {
1007 * Was this file ever deleted from the wiki?
1011 function wasDeleted() {
1012 $title = $this->getTitle();
1013 return $title && $title->isDeletedQuick();
1017 * Move file to the new title
1019 * Move current, old version and all thumbnails
1020 * to the new filename. Old file is deleted.
1022 * Cache purging is done; checks for validity
1023 * and logging are caller's responsibility
1025 * @param $target Title New file name
1026 * @return FileRepoStatus object.
1028 function move( $target ) {
1029 $this->readOnlyError();
1033 * Delete all versions of the file.
1035 * Moves the files into an archive directory (or deletes them)
1036 * and removes the database rows.
1038 * Cache purging is done; logging is caller's responsibility.
1040 * @param $reason String
1041 * @param $suppress Boolean: hide content from sysops?
1042 * @return true on success, false on some kind of failure
1044 * Overridden by LocalFile
1046 function delete( $reason, $suppress = false ) {
1047 $this->readOnlyError();
1051 * Restore all or specified deleted revisions to the given file.
1052 * Permissions and logging are left to the caller.
1054 * May throw database exceptions on error.
1056 * @param $versions set of record ids of deleted items to restore,
1057 * or empty to restore all revisions.
1058 * @param $unsuppress remove restrictions on content upon restoration?
1059 * @return the number of file revisions restored if successful,
1060 * or false on failure
1062 * Overridden by LocalFile
1064 function restore( $versions=array(), $unsuppress=false ) {
1065 $this->readOnlyError();
1069 * Returns 'true' if this file is a type which supports multiple pages,
1070 * e.g. DJVU or PDF. Note that this may be true even if the file in
1071 * question only has a single page.
1075 function isMultipage() {
1076 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1080 * Returns the number of pages of a multipage document, or false for
1081 * documents which aren't multipage documents
1083 function pageCount() {
1084 if ( !isset( $this->pageCount
) ) {
1085 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1086 $this->pageCount
= $this->handler
->pageCount( $this );
1088 $this->pageCount
= false;
1091 return $this->pageCount
;
1095 * Calculate the height of a thumbnail using the source and destination width
1097 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1098 // Exact integer multiply followed by division
1099 if ( $srcWidth == 0 ) {
1102 return round( $srcHeight * $dstWidth / $srcWidth );
1107 * Get an image size array like that returned by getImageSize(), or false if it
1108 * can't be determined.
1110 * @param $fileName String: The filename
1113 function getImageSize( $fileName ) {
1114 if ( !$this->getHandler() ) {
1117 return $this->handler
->getImageSize( $this, $fileName );
1121 * Get the URL of the image description page. May return false if it is
1122 * unknown or not applicable.
1124 function getDescriptionUrl() {
1125 return $this->repo
->getDescriptionUrl( $this->getName() );
1129 * Get the HTML text of the description page, if available
1131 function getDescriptionText() {
1132 global $wgMemc, $wgLang;
1133 if ( !$this->repo
->fetchDescription
) {
1136 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1138 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1139 wfDebug("Attempting to get the description from cache...");
1140 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1142 $obj = $wgMemc->get($key);
1144 wfDebug("success!\n");
1149 wfDebug( "Fetching shared description from $renderUrl\n" );
1150 $res = Http
::get( $renderUrl );
1151 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1152 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1161 * Get discription of file revision
1164 function getDescription() {
1169 * Get the 14-character timestamp of the file upload, or false if
1172 function getTimestamp() {
1173 $path = $this->getPath();
1174 if ( !file_exists( $path ) ) {
1177 return wfTimestamp( TS_MW
, filemtime( $path ) );
1181 * Get the SHA-1 base 36 hash of the file
1183 function getSha1() {
1184 return self
::sha1Base36( $this->getPath() );
1188 * Get the deletion archive key, <sha1>.<ext>
1190 function getStorageKey() {
1191 $hash = $this->getSha1();
1195 $ext = $this->getExtension();
1196 $dotExt = $ext === '' ?
'' : ".$ext";
1197 return $hash . $dotExt;
1201 * Determine if the current user is allowed to view a particular
1202 * field of this file, if it's marked as deleted.
1204 * @param $field Integer
1207 function userCan( $field ) {
1212 * Get an associative array containing information about a file in the local filesystem.
1214 * @param $path String: absolute local filesystem path
1215 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1216 * Set it to false to ignore the extension.
1218 static function getPropsFromPath( $path, $ext = true ) {
1219 wfProfileIn( __METHOD__
);
1220 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1222 'fileExists' => file_exists( $path ) && !is_dir( $path )
1225 if ( $info['fileExists'] ) {
1226 $magic = MimeMagic
::singleton();
1228 if ( $ext === true ) {
1229 $i = strrpos( $path, '.' );
1230 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1233 # mime type according to file contents
1234 $info['file-mime'] = $magic->guessMimeType( $path, false );
1236 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1238 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1239 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1242 $info['size'] = filesize( $path );
1244 # Height, width and metadata
1245 $handler = MediaHandler
::getHandler( $info['mime'] );
1247 $tempImage = (object)array();
1248 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1249 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1252 $info['metadata'] = '';
1254 $info['sha1'] = self
::sha1Base36( $path );
1256 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1258 $info['mime'] = null;
1259 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1260 $info['metadata'] = '';
1262 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1265 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1266 $info['width'] = $gis[0];
1267 $info['height'] = $gis[1];
1268 if ( isset( $gis['bits'] ) ) {
1269 $info['bits'] = $gis['bits'];
1275 $info['height'] = 0;
1278 wfProfileOut( __METHOD__
);
1283 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1284 * encoding, zero padded to 31 digits.
1286 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1289 * Returns false on failure
1291 static function sha1Base36( $path ) {
1292 wfSuppressWarnings();
1293 $hash = sha1_file( $path );
1294 wfRestoreWarnings();
1295 if ( $hash === false ) {
1298 return wfBaseConvert( $hash, 16, 36, 31 );
1302 function getLongDesc() {
1303 $handler = $this->getHandler();
1305 return $handler->getLongDesc( $this );
1307 return MediaHandler
::getGeneralLongDesc( $this );
1311 function getShortDesc() {
1312 $handler = $this->getHandler();
1314 return $handler->getShortDesc( $this );
1316 return MediaHandler
::getGeneralShortDesc( $this );
1320 function getDimensionsString() {
1321 $handler = $this->getHandler();
1323 return $handler->getDimensionsString( $this );
1329 function getRedirected() {
1330 return $this->redirected
;
1333 function getRedirectedTitle() {
1334 if ( $this->redirected
) {
1335 if ( !$this->redirectTitle
)
1336 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1337 return $this->redirectTitle
;
1341 function redirectedFrom( $from ) {
1342 $this->redirected
= $from;
1345 function isMissing() {
1350 * Aliases for backwards compatibility with 1.6
1352 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1353 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1354 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1355 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);