4 * Implements some public methods and some protected utility functions which
5 * are required by multiple child classes. Contains stub functionality for
6 * unimplemented public methods.
8 * Stub functions which should be overridden are marked with STUB. Some more
9 * concrete functions are also typically overridden by child classes.
11 * Note that only the repo object knows what its file class is called. You should
12 * never name a file class explictly outside of the repo class. Instead use the
13 * repo's factory functions to generate file objects, for example:
15 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
17 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
23 const DELETED_FILE
= 1;
24 const DELETED_COMMENT
= 2;
25 const DELETED_USER
= 4;
26 const DELETED_RESTRICTED
= 8;
29 const DELETE_SOURCE
= 1;
32 * Some member variables can be lazy-initialised using __get(). The
33 * initialisation function for these variables is always a function named
34 * like getVar(), where Var is the variable name with upper-case first
37 * The following variables are initialised in this way in this base class:
38 * name, extension, handler, path, canRender, isSafeFile,
39 * transformScript, hashPath, pageCount, url
41 * Code within this class should generally use the accessor function
42 * directly, since __get() isn't re-entrant and therefore causes bugs that
43 * depend on initialisation order.
47 * The following member variables are not lazy-initialised
49 var $repo, $title, $lastError, $redirected, $redirectedTitle;
52 * Call this constructor from child classes
54 function __construct( $title, $repo ) {
55 $this->title
= $title;
59 function __get( $name ) {
60 $function = array( $this, 'get' . ucfirst( $name ) );
61 if ( !is_callable( $function ) ) {
64 $this->$name = call_user_func( $function );
70 * Normalize a file extension to the common form, and ensure it's clean.
71 * Extensions with non-alphanumeric characters will be discarded.
73 * @param $ext string (without the .)
76 static function normalizeExtension( $ext ) {
77 $lower = strtolower( $ext );
84 if( isset( $squish[$lower] ) ) {
85 return $squish[$lower];
86 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
94 * Checks if file extensions are compatible
96 * @param $old File Old file
97 * @param $new string New name
99 static function checkExtensionCompatibility( File
$old, $new ) {
100 $oldMime = $old->getMimeType();
101 $n = strrpos( $new, '.' );
102 $newExt = self
::normalizeExtension(
103 $n ?
substr( $new, $n +
1 ) : '' );
104 $mimeMagic = MimeMagic
::singleton();
105 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
109 * Upgrade the database row if there is one
110 * Called by ImagePage
113 function upgradeRow() {}
116 * Split an internet media type into its two components; if not
117 * a two-part name, set the minor type to 'unknown'.
119 * @param $mime "text/html" etc
120 * @return array ("text", "html") etc
122 static function splitMime( $mime ) {
123 if( strpos( $mime, '/' ) !== false ) {
124 return explode( '/', $mime, 2 );
126 return array( $mime, 'unknown' );
131 * Return the name of this file
133 public function getName() {
134 if ( !isset( $this->name
) ) {
135 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
141 * Get the file extension, e.g. "svg"
143 function getExtension() {
144 if ( !isset( $this->extension
) ) {
145 $n = strrpos( $this->getName(), '.' );
146 $this->extension
= self
::normalizeExtension(
147 $n ?
substr( $this->getName(), $n +
1 ) : '' );
149 return $this->extension
;
153 * Return the associated title object
155 public function getTitle() { return $this->title
; }
158 * Return the title used to find this file
160 public function getOriginalTitle() {
161 if ( $this->redirected
)
162 return $this->getRedirectedTitle();
167 * Return the URL of the file
169 public function getUrl() {
170 if ( !isset( $this->url
) ) {
171 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
177 * Return a fully-qualified URL to the file.
178 * Upload URL paths _may or may not_ be fully qualified, so
179 * we check. Local paths are assumed to belong on $wgServer.
183 public function getFullUrl() {
184 return wfExpandUrl( $this->getUrl() );
187 function getViewURL() {
188 if( $this->mustRender()) {
189 if( $this->canRender() ) {
190 return $this->createThumb( $this->getWidth() );
193 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
194 return $this->getURL(); #hm... return NULL?
197 return $this->getURL();
202 * Return the full filesystem path to the file. Note that this does
203 * not mean that a file actually exists under that location.
205 * This path depends on whether directory hashing is active or not,
206 * i.e. whether the files are all found in the same directory,
207 * or in hashed paths like /images/3/3c.
209 * May return false if the file is not locally accessible.
211 public function getPath() {
212 if ( !isset( $this->path
) ) {
213 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
219 * Alias for getPath()
221 public function getFullPath() {
222 return $this->getPath();
226 * Return the width of the image. Returns false if the width is unknown
230 * Overridden by LocalFile, UnregisteredLocalFile
232 public function getWidth( $page = 1 ) { return false; }
235 * Return the height of the image. Returns false if the height is unknown
239 * Overridden by LocalFile, UnregisteredLocalFile
241 public function getHeight( $page = 1 ) { return false; }
244 * Returns ID or name of user who uploaded the file
247 * @param $type string 'text' or 'id'
249 public function getUser( $type='text' ) { return null; }
252 * Get the duration of a media file in seconds
254 public function getLength() {
255 $handler = $this->getHandler();
257 return $handler->getLength( $this );
264 * Get handler-specific metadata
265 * Overridden by LocalFile, UnregisteredLocalFile
268 public function getMetadata() { return false; }
271 * Return the bit depth of the file
272 * Overridden by LocalFile
275 public function getBitDepth() { return 0; }
278 * Return the size of the image file, in bytes
279 * Overridden by LocalFile, UnregisteredLocalFile
282 public function getSize() { return false; }
285 * Returns the mime type of the file.
286 * Overridden by LocalFile, UnregisteredLocalFile
289 function getMimeType() { return 'unknown/unknown'; }
292 * Return the type of the media in the file.
293 * Use the value returned by this function with the MEDIATYPE_xxx constants.
294 * Overridden by LocalFile,
297 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
300 * Checks if the output of transform() for this file is likely
301 * to be valid. If this is false, various user elements will
302 * display a placeholder instead.
304 * Currently, this checks if the file is an image format
305 * that can be converted to a format
306 * supported by all browsers (namely GIF, PNG and JPEG),
307 * or if it is an SVG image and SVG conversion is enabled.
309 function canRender() {
310 if ( !isset( $this->canRender
) ) {
311 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
313 return $this->canRender
;
317 * Accessor for __get()
319 protected function getCanRender() {
320 return $this->canRender();
324 * Return true if the file is of a type that can't be directly
325 * rendered by typical browsers and needs to be re-rasterized.
327 * This returns true for everything but the bitmap types
328 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
329 * also return true for any non-image formats.
333 function mustRender() {
334 return $this->getHandler() && $this->handler
->mustRender( $this );
338 * Alias for canRender()
340 function allowInlineDisplay() {
341 return $this->canRender();
345 * Determines if this media file is in a format that is unlikely to
346 * contain viruses or malicious content. It uses the global
347 * $wgTrustedMediaFormats list to determine if the file is safe.
349 * This is used to show a warning on the description page of non-safe files.
350 * It may also be used to disallow direct [[media:...]] links to such files.
352 * Note that this function will always return true if allowInlineDisplay()
353 * or isTrustedFile() is true for this file.
355 function isSafeFile() {
356 if ( !isset( $this->isSafeFile
) ) {
357 $this->isSafeFile
= $this->_getIsSafeFile();
359 return $this->isSafeFile
;
362 /** Accessor for __get() */
363 protected function getIsSafeFile() {
364 return $this->isSafeFile();
367 /** Uncached accessor */
368 protected function _getIsSafeFile() {
369 if ($this->allowInlineDisplay()) return true;
370 if ($this->isTrustedFile()) return true;
372 global $wgTrustedMediaFormats;
374 $type= $this->getMediaType();
375 $mime= $this->getMimeType();
376 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
378 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
379 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
381 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
382 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
387 /** Returns true if the file is flagged as trusted. Files flagged that way
388 * can be linked to directly, even if that is not allowed for this type of
391 * This is a dummy function right now and always returns false. It could be
392 * implemented to extract a flag from the database. The trusted flag could be
393 * set on upload, if the user has sufficient privileges, to bypass script-
394 * and html-filters. It may even be coupled with cryptographics signatures
397 function isTrustedFile() {
398 #this could be implemented to check a flag in the databas,
399 #look for signatures, etc
404 * Returns true if file exists in the repository.
406 * Overridden by LocalFile to avoid unnecessary stat calls.
408 * @return boolean Whether file exists in the repository.
410 public function exists() {
411 return $this->getPath() && file_exists( $this->path
);
415 * Returns true if file exists in the repository and can be included in a page.
416 * It would be unsafe to include private images, making public thumbnails inadvertently
418 * @return boolean Whether file exists in the repository and is includable.
421 function isVisible() {
422 return $this->exists();
425 function getTransformScript() {
426 if ( !isset( $this->transformScript
) ) {
427 $this->transformScript
= false;
429 $script = $this->repo
->getThumbScriptUrl();
431 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
435 return $this->transformScript
;
439 * Get a ThumbnailImage which is the same size as the source
441 function getUnscaledThumb( $handlerParams = array() ) {
442 $hp =& $handlerParams;
443 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
444 $width = $this->getWidth( $page );
446 return $this->iconThumb();
448 $hp['width'] = $width;
449 return $this->transform( $hp );
453 * Return the file name of a thumbnail with the specified parameters
455 * @param $params Array: handler-specific parameters
458 function thumbName( $params ) {
459 if ( !$this->getHandler() ) {
462 $extension = $this->getExtension();
463 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
464 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
465 if ( $thumbExt != $extension ) {
466 $thumbName .= ".$thumbExt";
472 * Create a thumbnail of the image having the specified width/height.
473 * The thumbnail will not be created if the width is larger than the
474 * image's width. Let the browser do the scaling in this case.
475 * The thumbnail is stored on disk and is only computed if the thumbnail
476 * file does not exist OR if it is older than the image.
479 * Keeps aspect ratio of original image. If both width and height are
480 * specified, the generated image will be no bigger than width x height,
481 * and will also have correct aspect ratio.
483 * @param $width Integer: maximum width of the generated thumbnail
484 * @param $height Integer: maximum height of the image (optional)
486 public function createThumb( $width, $height = -1 ) {
487 $params = array( 'width' => $width );
488 if ( $height != -1 ) {
489 $params['height'] = $height;
491 $thumb = $this->transform( $params );
492 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
493 return $thumb->getUrl();
497 * As createThumb, but returns a ThumbnailImage object. This can
498 * provide access to the actual file, the real size of the thumb,
499 * and can produce a convenient \<img\> tag for you.
501 * For non-image formats, this may return a filetype-specific icon.
503 * @param $width Integer: maximum width of the generated thumbnail
504 * @param $height Integer: maximum height of the image (optional)
505 * @param $render Integer: Deprecated
507 * @return ThumbnailImage or null on failure
509 * @deprecated use transform()
511 public function getThumbnail( $width, $height=-1, $render = true ) {
512 $params = array( 'width' => $width );
513 if ( $height != -1 ) {
514 $params['height'] = $height;
516 return $this->transform( $params, 0 );
520 * Transform a media file
522 * @param $params Array: an associative array of handler-specific parameters.
523 * Typical keys are width, height and page.
524 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
525 * @return MediaTransformOutput
527 function transform( $params, $flags = 0 ) {
528 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
530 wfProfileIn( __METHOD__
);
532 if ( !$this->canRender() ) {
533 // not a bitmap or renderable image, don't try.
534 $thumb = $this->iconThumb();
538 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
539 $descriptionUrl = $this->getDescriptionUrl();
540 if ( $descriptionUrl ) {
541 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
544 $script = $this->getTransformScript();
545 if ( $script && !($flags & self
::RENDER_NOW
) ) {
546 // Use a script to transform on client request, if possible
547 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
553 $normalisedParams = $params;
554 $this->handler
->normaliseParams( $this, $normalisedParams );
555 $thumbName = $this->thumbName( $normalisedParams );
556 $thumbPath = $this->getThumbPath( $thumbName );
557 $thumbUrl = $this->getThumbUrl( $thumbName );
559 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
560 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
564 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
565 $this->migrateThumbFile( $thumbName );
566 if ( file_exists( $thumbPath )) {
567 $thumbTime = filemtime( $thumbPath );
568 if ( $thumbTime !== FALSE &&
569 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
571 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
575 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
577 // Ignore errors if requested
580 } elseif ( $thumb->isError() ) {
581 $this->lastError
= $thumb->toText();
582 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
583 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
587 // Purge. Useful in the event of Core -> Squid connection failure or squid
588 // purge collisions from elsewhere during failure. Don't keep triggering for
589 // "thumbs" which have the main image URL though (bug 13776)
590 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
591 SquidUpdate
::purge( array( $thumbUrl ) );
595 wfProfileOut( __METHOD__
);
596 return is_object( $thumb ) ?
$thumb : false;
600 * Hook into transform() to allow migration of thumbnail files
602 * Overridden by LocalFile
604 function migrateThumbFile( $thumbName ) {}
607 * Get a MediaHandler instance for this file
609 function getHandler() {
610 if ( !isset( $this->handler
) ) {
611 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
613 return $this->handler
;
617 * Get a ThumbnailImage representing a file type icon
618 * @return ThumbnailImage
620 function iconThumb() {
621 global $wgStylePath, $wgStyleDirectory;
623 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
624 foreach( $try as $icon ) {
625 $path = '/common/images/icons/' . $icon;
626 $filepath = $wgStyleDirectory . $path;
627 if( file_exists( $filepath ) ) {
628 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
635 * Get last thumbnailing error.
638 function getLastError() {
639 return $this->lastError
;
643 * Get all thumbnail names previously generated for this file
645 * Overridden by LocalFile
647 function getThumbnails() { return array(); }
650 * Purge shared caches such as thumbnails and DB data caching
652 * Overridden by LocalFile
654 function purgeCache() {}
657 * Purge the file description page, but don't go after
658 * pages using the file. Use when modifying file history
659 * but not the current data.
661 function purgeDescription() {
662 $title = $this->getTitle();
664 $title->invalidateCache();
665 $title->purgeSquid();
670 * Purge metadata and all affected pages when the file is created,
671 * deleted, or majorly updated.
673 function purgeEverything() {
674 // Delete thumbnails and refresh file metadata cache
676 $this->purgeDescription();
678 // Purge cache of all pages using this file
679 $title = $this->getTitle();
681 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
687 * Return a fragment of the history of file.
690 * @param $limit integer Limit of rows to return
691 * @param $start timestamp Only revisions older than $start will be returned
692 * @param $end timestamp Only revisions newer than $end will be returned
693 * @param $inc bool Include the endpoints of the time range
695 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
700 * Return the history of this file, line by line. Starts with current version,
701 * then old versions. Should return an object similar to an image/oldimage
705 * Overridden in LocalFile
707 public function nextHistoryLine() {
712 * Reset the history pointer to the first element of the history.
713 * Always call this function after using nextHistoryLine() to free db resources
715 * Overridden in LocalFile.
717 public function resetHistory() {}
720 * Get the filename hash component of the directory including trailing slash,
722 * If the repository is not hashed, returns an empty string.
724 function getHashPath() {
725 if ( !isset( $this->hashPath
) ) {
726 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
728 return $this->hashPath
;
732 * Get the path of the file relative to the public zone root
735 return $this->getHashPath() . $this->getName();
739 * Get urlencoded relative path of the file
741 function getUrlRel() {
742 return $this->getHashPath() . rawurlencode( $this->getName() );
745 /** Get the relative path for an archive file */
746 function getArchiveRel( $suffix = false ) {
747 $path = 'archive/' . $this->getHashPath();
748 if ( $suffix === false ) {
749 $path = substr( $path, 0, -1 );
756 /** Get the path of the archive directory, or a particular file if $suffix is specified */
757 function getArchivePath( $suffix = false ) {
758 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
761 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
762 function getThumbPath( $suffix = false ) {
763 $path = $this->repo
->getZonePath('thumb') . '/' . $this->getRel();
764 if ( $suffix !== false ) {
765 $path .= '/' . $suffix;
770 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
771 function getArchiveUrl( $suffix = false ) {
772 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
773 if ( $suffix === false ) {
774 $path = substr( $path, 0, -1 );
776 $path .= rawurlencode( $suffix );
781 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
782 function getThumbUrl( $suffix = false ) {
783 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
784 if ( $suffix !== false ) {
785 $path .= '/' . rawurlencode( $suffix );
790 /** Get the virtual URL for an archive file or directory */
791 function getArchiveVirtualUrl( $suffix = false ) {
792 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
793 if ( $suffix === false ) {
794 $path = substr( $path, 0, -1 );
796 $path .= rawurlencode( $suffix );
801 /** Get the virtual URL for a thumbnail file or directory */
802 function getThumbVirtualUrl( $suffix = false ) {
803 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
804 if ( $suffix !== false ) {
805 $path .= '/' . rawurlencode( $suffix );
810 /** Get the virtual URL for the file itself */
811 function getVirtualUrl( $suffix = false ) {
812 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
813 if ( $suffix !== false ) {
814 $path .= '/' . rawurlencode( $suffix );
822 function isHashed() {
823 return $this->repo
->isHashed();
826 function readOnlyError() {
827 throw new MWException( get_class($this) . ': write operations are not supported' );
831 * Record a file upload in the upload log and the image table
833 * Overridden by LocalFile
835 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
836 $this->readOnlyError();
840 * Move or copy a file to its public location. If a file exists at the
841 * destination, move it to an archive. Returns a FileRepoStatus object with
842 * the archive name in the "value" member on success.
844 * The archive name should be passed through to recordUpload for database
847 * @param $srcPath String: local filesystem path to the source image
848 * @param $flags Integer: a bitwise combination of:
849 * File::DELETE_SOURCE Delete the source file, i.e. move
851 * @return FileRepoStatus object. On success, the value member contains the
852 * archive name, or an empty string if it was a new file.
855 * Overridden by LocalFile
857 function publish( $srcPath, $flags = 0 ) {
858 $this->readOnlyError();
862 * Get an array of Title objects which are articles which use this file
863 * Also adds their IDs to the link cache
865 * This is mostly copied from Title::getLinksTo()
867 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
869 function getLinksTo( $options = array() ) {
870 wfProfileIn( __METHOD__
);
872 // Note: use local DB not repo DB, we want to know local links
873 if ( count( $options ) > 0 ) {
874 $db = wfGetDB( DB_MASTER
);
876 $db = wfGetDB( DB_SLAVE
);
878 $linkCache = LinkCache
::singleton();
880 $encName = $db->addQuotes( $this->getName() );
881 $res = $db->select( array( 'page', 'imagelinks'),
882 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
883 array( 'page_id' => 'il_from', 'il_to' => $encName ),
888 if ( $db->numRows( $res ) ) {
889 while ( $row = $db->fetchObject( $res ) ) {
890 if ( $titleObj = Title
::newFromRow( $row ) ) {
891 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
892 $retVal[] = $titleObj;
896 wfProfileOut( __METHOD__
);
900 function formatMetadata() {
901 if ( !$this->getHandler() ) {
904 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
908 * Returns true if the file comes from the local file repository.
913 $repo = $this->getRepo();
914 return $repo && $repo->isLocal();
918 * Returns the name of the repository.
922 function getRepoName() {
923 return $this->repo ?
$this->repo
->getName() : 'unknown';
926 * Returns the repository
933 * Returns true if the image is an old version
941 * Is this file a "deleted" file in a private archive?
944 function isDeleted( $field ) {
949 * Return the deletion bitfield
952 function getVisibility() {
957 * Was this file ever deleted from the wiki?
961 function wasDeleted() {
962 $title = $this->getTitle();
963 return $title && $title->isDeletedQuick();
967 * Move file to the new title
969 * Move current, old version and all thumbnails
970 * to the new filename. Old file is deleted.
972 * Cache purging is done; checks for validity
973 * and logging are caller's responsibility
975 * @param $target Title New file name
976 * @return FileRepoStatus object.
978 function move( $target ) {
979 $this->readOnlyError();
983 * Delete all versions of the file.
985 * Moves the files into an archive directory (or deletes them)
986 * and removes the database rows.
988 * Cache purging is done; logging is caller's responsibility.
990 * @param $reason String
991 * @param $suppress Boolean: hide content from sysops?
992 * @return true on success, false on some kind of failure
994 * Overridden by LocalFile
996 function delete( $reason, $suppress = false ) {
997 $this->readOnlyError();
1001 * Restore all or specified deleted revisions to the given file.
1002 * Permissions and logging are left to the caller.
1004 * May throw database exceptions on error.
1006 * @param $versions set of record ids of deleted items to restore,
1007 * or empty to restore all revisions.
1008 * @param $unsuppress remove restrictions on content upon restoration?
1009 * @return the number of file revisions restored if successful,
1010 * or false on failure
1012 * Overridden by LocalFile
1014 function restore( $versions=array(), $unsuppress=false ) {
1015 $this->readOnlyError();
1019 * Returns 'true' if this file is a type which supports multiple pages,
1020 * e.g. DJVU or PDF. Note that this may be true even if the file in
1021 * question only has a single page.
1025 function isMultipage() {
1026 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1030 * Returns the number of pages of a multipage document, or NULL for
1031 * documents which aren't multipage documents
1033 function pageCount() {
1034 if ( !isset( $this->pageCount
) ) {
1035 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1036 $this->pageCount
= $this->handler
->pageCount( $this );
1038 $this->pageCount
= false;
1041 return $this->pageCount
;
1045 * Calculate the height of a thumbnail using the source and destination width
1047 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1048 // Exact integer multiply followed by division
1049 if ( $srcWidth == 0 ) {
1052 return round( $srcHeight * $dstWidth / $srcWidth );
1057 * Get an image size array like that returned by getImageSize(), or false if it
1058 * can't be determined.
1060 * @param $fileName String: The filename
1063 function getImageSize( $fileName ) {
1064 if ( !$this->getHandler() ) {
1067 return $this->handler
->getImageSize( $this, $fileName );
1071 * Get the URL of the image description page. May return false if it is
1072 * unknown or not applicable.
1074 function getDescriptionUrl() {
1075 return $this->repo
->getDescriptionUrl( $this->getName() );
1079 * Get the HTML text of the description page, if available
1080 * For local files ImagePage does not use it, because it skips the parser cache.
1082 function getDescriptionText() {
1083 if( $this->isLocal() ) {
1085 $revision = Revision
::newFromTitle( $this->title
);
1086 if ( !$revision ) return false;
1087 $text = $revision->getText();
1088 if ( !$text ) return false;
1089 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1090 return $pout->getText();
1093 global $wgMemc, $wgLang;
1094 if ( !$this->repo
->fetchDescription
) {
1097 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1099 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1100 wfDebug("Attempting to get the description from cache...");
1101 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1103 $obj = $wgMemc->get($key);
1105 wfDebug("success!\n");
1110 wfDebug( "Fetching shared description from $renderUrl\n" );
1111 $res = Http
::get( $renderUrl );
1112 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1113 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1122 * Get discription of file revision
1125 function getDescription() {
1130 * Get the 14-character timestamp of the file upload, or false if
1133 function getTimestamp() {
1134 $path = $this->getPath();
1135 if ( !file_exists( $path ) ) {
1138 return wfTimestamp( TS_MW
, filemtime( $path ) );
1142 * Get the SHA-1 base 36 hash of the file
1144 function getSha1() {
1145 return self
::sha1Base36( $this->getPath() );
1149 * Get the deletion archive key, <sha1>.<ext>
1151 function getStorageKey() {
1152 $hash = $this->getSha1();
1156 $ext = $this->getExtension();
1157 $dotExt = $ext === '' ?
'' : ".$ext";
1158 return $hash . $dotExt;
1162 * Determine if the current user is allowed to view a particular
1163 * field of this file, if it's marked as deleted.
1165 * @param $field Integer
1168 function userCan( $field ) {
1173 * Get an associative array containing information about a file in the local filesystem.
1175 * @param $path String: absolute local filesystem path
1176 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1177 * Set it to false to ignore the extension.
1179 static function getPropsFromPath( $path, $ext = true ) {
1180 wfProfileIn( __METHOD__
);
1181 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1183 'fileExists' => file_exists( $path ) && !is_dir( $path )
1186 if ( $info['fileExists'] ) {
1187 $magic = MimeMagic
::singleton();
1189 if ( $ext === true ) {
1190 $i = strrpos( $path, '.' );
1191 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1194 $info['file-mime'] = $magic->guessMimeType( $path, false ); # mime type according to file contents
1195 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext ); # logical mime type
1197 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1198 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1201 $info['size'] = filesize( $path );
1203 # Height, width and metadata
1204 $handler = MediaHandler
::getHandler( $info['mime'] );
1206 $tempImage = (object)array();
1207 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1208 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1211 $info['metadata'] = '';
1213 $info['sha1'] = self
::sha1Base36( $path );
1215 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1217 $info['mime'] = null;
1218 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1219 $info['metadata'] = '';
1221 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1224 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1225 $info['width'] = $gis[0];
1226 $info['height'] = $gis[1];
1227 if ( isset( $gis['bits'] ) ) {
1228 $info['bits'] = $gis['bits'];
1234 $info['height'] = 0;
1237 wfProfileOut( __METHOD__
);
1242 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1243 * encoding, zero padded to 31 digits.
1245 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1248 * Returns false on failure
1250 static function sha1Base36( $path ) {
1251 wfSuppressWarnings();
1252 $hash = sha1_file( $path );
1253 wfRestoreWarnings();
1254 if ( $hash === false ) {
1257 return wfBaseConvert( $hash, 16, 36, 31 );
1261 function getLongDesc() {
1262 $handler = $this->getHandler();
1264 return $handler->getLongDesc( $this );
1266 return MediaHandler
::getGeneralLongDesc( $this );
1270 function getShortDesc() {
1271 $handler = $this->getHandler();
1273 return $handler->getShortDesc( $this );
1275 return MediaHandler
::getGeneralShortDesc( $this );
1279 function getDimensionsString() {
1280 $handler = $this->getHandler();
1282 return $handler->getDimensionsString( $this );
1288 function getRedirected() {
1289 return $this->redirected
;
1292 function getRedirectedTitle() {
1293 if ( $this->redirected
) {
1294 if ( !$this->redirectTitle
)
1295 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1296 return $this->redirectTitle
;
1300 function redirectedFrom( $from ) {
1301 $this->redirected
= $from;
1304 function isMissing() {
1309 * Aliases for backwards compatibility with 1.6
1311 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1312 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1313 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1314 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);