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;
69 * Call this constructor from child classes
71 function __construct( $title, $repo ) {
72 $this->title
= $title;
76 function __get( $name ) {
77 $function = array( $this, 'get' . ucfirst( $name ) );
78 if ( !is_callable( $function ) ) {
81 $this->$name = call_user_func( $function );
87 * Normalize a file extension to the common form, and ensure it's clean.
88 * Extensions with non-alphanumeric characters will be discarded.
90 * @param $ext string (without the .)
93 static function normalizeExtension( $ext ) {
94 $lower = strtolower( $ext );
101 if( isset( $squish[$lower] ) ) {
102 return $squish[$lower];
103 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
111 * Checks if file extensions are compatible
113 * @param $old File Old file
114 * @param $new string New name
116 static function checkExtensionCompatibility( File
$old, $new ) {
117 $oldMime = $old->getMimeType();
118 $n = strrpos( $new, '.' );
119 $newExt = self
::normalizeExtension(
120 $n ?
substr( $new, $n +
1 ) : '' );
121 $mimeMagic = MimeMagic
::singleton();
122 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
126 * Upgrade the database row if there is one
127 * Called by ImagePage
130 function upgradeRow() {}
133 * Split an internet media type into its two components; if not
134 * a two-part name, set the minor type to 'unknown'.
136 * @param $mime "text/html" etc
137 * @return array ("text", "html") etc
139 static function splitMime( $mime ) {
140 if( strpos( $mime, '/' ) !== false ) {
141 return explode( '/', $mime, 2 );
143 return array( $mime, 'unknown' );
148 * Return the name of this file
150 public function getName() {
151 if ( !isset( $this->name
) ) {
152 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
158 * Get the file extension, e.g. "svg"
160 function getExtension() {
161 if ( !isset( $this->extension
) ) {
162 $n = strrpos( $this->getName(), '.' );
163 $this->extension
= self
::normalizeExtension(
164 $n ?
substr( $this->getName(), $n +
1 ) : '' );
166 return $this->extension
;
170 * Return the associated title object
173 public function getTitle() { return $this->title
; }
176 * Return the title used to find this file
178 public function getOriginalTitle() {
179 if ( $this->redirected
)
180 return $this->getRedirectedTitle();
185 * Return the URL of the file
187 public function getUrl() {
188 if ( !isset( $this->url
) ) {
189 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
195 * Return a fully-qualified URL to the file.
196 * Upload URL paths _may or may not_ be fully qualified, so
197 * we check. Local paths are assumed to belong on $wgServer.
201 public function getFullUrl() {
202 return wfExpandUrl( $this->getUrl() );
205 function getViewURL() {
206 if( $this->mustRender()) {
207 if( $this->canRender() ) {
208 return $this->createThumb( $this->getWidth() );
211 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
212 return $this->getURL(); #hm... return NULL?
215 return $this->getURL();
220 * Return the full filesystem path to the file. Note that this does
221 * not mean that a file actually exists under that location.
223 * This path depends on whether directory hashing is active or not,
224 * i.e. whether the files are all found in the same directory,
225 * or in hashed paths like /images/3/3c.
227 * May return false if the file is not locally accessible.
229 public function getPath() {
230 if ( !isset( $this->path
) ) {
231 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
237 * Alias for getPath()
239 public function getFullPath() {
240 return $this->getPath();
244 * Return the width of the image. Returns false if the width is unknown
248 * Overridden by LocalFile, UnregisteredLocalFile
250 public function getWidth( $page = 1 ) { return false; }
253 * Return the height of the image. Returns false if the height is unknown
257 * Overridden by LocalFile, UnregisteredLocalFile
259 public function getHeight( $page = 1 ) { return false; }
262 * Returns ID or name of user who uploaded the file
265 * @param $type string 'text' or 'id'
267 public function getUser( $type='text' ) { return null; }
270 * Get the duration of a media file in seconds
272 public function getLength() {
273 $handler = $this->getHandler();
275 return $handler->getLength( $this );
282 * Return true if the file is vectorized
284 public function isVectorized() {
285 $handler = $this->getHandler();
287 return $handler->isVectorized( $this );
295 * Get handler-specific metadata
296 * Overridden by LocalFile, UnregisteredLocalFile
299 public function getMetadata() { return false; }
302 * Return the bit depth of the file
303 * Overridden by LocalFile
306 public function getBitDepth() { return 0; }
309 * Return the size of the image file, in bytes
310 * Overridden by LocalFile, UnregisteredLocalFile
313 public function getSize() { return false; }
316 * Returns the mime type of the file.
317 * Overridden by LocalFile, UnregisteredLocalFile
320 function getMimeType() { return 'unknown/unknown'; }
323 * Return the type of the media in the file.
324 * Use the value returned by this function with the MEDIATYPE_xxx constants.
325 * Overridden by LocalFile,
328 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
331 * Checks if the output of transform() for this file is likely
332 * to be valid. If this is false, various user elements will
333 * display a placeholder instead.
335 * Currently, this checks if the file is an image format
336 * that can be converted to a format
337 * supported by all browsers (namely GIF, PNG and JPEG),
338 * or if it is an SVG image and SVG conversion is enabled.
340 function canRender() {
341 if ( !isset( $this->canRender
) ) {
342 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
344 return $this->canRender
;
348 * Accessor for __get()
350 protected function getCanRender() {
351 return $this->canRender();
355 * Return true if the file is of a type that can't be directly
356 * rendered by typical browsers and needs to be re-rasterized.
358 * This returns true for everything but the bitmap types
359 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
360 * also return true for any non-image formats.
364 function mustRender() {
365 return $this->getHandler() && $this->handler
->mustRender( $this );
369 * Alias for canRender()
371 function allowInlineDisplay() {
372 return $this->canRender();
376 * Determines if this media file is in a format that is unlikely to
377 * contain viruses or malicious content. It uses the global
378 * $wgTrustedMediaFormats list to determine if the file is safe.
380 * This is used to show a warning on the description page of non-safe files.
381 * It may also be used to disallow direct [[media:...]] links to such files.
383 * Note that this function will always return true if allowInlineDisplay()
384 * or isTrustedFile() is true for this file.
386 function isSafeFile() {
387 if ( !isset( $this->isSafeFile
) ) {
388 $this->isSafeFile
= $this->_getIsSafeFile();
390 return $this->isSafeFile
;
393 /** Accessor for __get() */
394 protected function getIsSafeFile() {
395 return $this->isSafeFile();
398 /** Uncached accessor */
399 protected function _getIsSafeFile() {
400 if ($this->allowInlineDisplay()) return true;
401 if ($this->isTrustedFile()) return true;
403 global $wgTrustedMediaFormats;
405 $type= $this->getMediaType();
406 $mime= $this->getMimeType();
407 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
409 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
410 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
412 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
413 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
418 /** Returns true if the file is flagged as trusted. Files flagged that way
419 * can be linked to directly, even if that is not allowed for this type of
422 * This is a dummy function right now and always returns false. It could be
423 * implemented to extract a flag from the database. The trusted flag could be
424 * set on upload, if the user has sufficient privileges, to bypass script-
425 * and html-filters. It may even be coupled with cryptographics signatures
428 function isTrustedFile() {
429 #this could be implemented to check a flag in the databas,
430 #look for signatures, etc
435 * Returns true if file exists in the repository.
437 * Overridden by LocalFile to avoid unnecessary stat calls.
439 * @return boolean Whether file exists in the repository.
441 public function exists() {
442 return $this->getPath() && file_exists( $this->path
);
446 * Returns true if file exists in the repository and can be included in a page.
447 * It would be unsafe to include private images, making public thumbnails inadvertently
449 * @return boolean Whether file exists in the repository and is includable.
452 function isVisible() {
453 return $this->exists();
456 function getTransformScript() {
457 if ( !isset( $this->transformScript
) ) {
458 $this->transformScript
= false;
460 $script = $this->repo
->getThumbScriptUrl();
462 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
466 return $this->transformScript
;
470 * Get a ThumbnailImage which is the same size as the source
472 function getUnscaledThumb( $handlerParams = array() ) {
473 $hp =& $handlerParams;
474 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
475 $width = $this->getWidth( $page );
477 return $this->iconThumb();
479 $hp['width'] = $width;
480 return $this->transform( $hp );
484 * Return the file name of a thumbnail with the specified parameters
486 * @param $params Array: handler-specific parameters
489 function thumbName( $params ) {
490 return $this->generateThumbName( $this->getName(), $params );
494 * Generate a thumbnail file name from a name and specified parameters
496 * @param string $name
497 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
499 function generateThumbName( $name, $params ) {
500 if ( !$this->getHandler() ) {
503 $extension = $this->getExtension();
504 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
505 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
506 if ( $thumbExt != $extension ) {
507 $thumbName .= ".$thumbExt";
513 * Create a thumbnail of the image having the specified width/height.
514 * The thumbnail will not be created if the width is larger than the
515 * image's width. Let the browser do the scaling in this case.
516 * The thumbnail is stored on disk and is only computed if the thumbnail
517 * file does not exist OR if it is older than the image.
520 * Keeps aspect ratio of original image. If both width and height are
521 * specified, the generated image will be no bigger than width x height,
522 * and will also have correct aspect ratio.
524 * @param $width Integer: maximum width of the generated thumbnail
525 * @param $height Integer: maximum height of the image (optional)
527 public function createThumb( $width, $height = -1 ) {
528 $params = array( 'width' => $width );
529 if ( $height != -1 ) {
530 $params['height'] = $height;
532 $thumb = $this->transform( $params );
533 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
534 return $thumb->getUrl();
538 * As createThumb, but returns a ThumbnailImage object. This can
539 * provide access to the actual file, the real size of the thumb,
540 * and can produce a convenient \<img\> tag for you.
542 * For non-image formats, this may return a filetype-specific icon.
544 * @param $width Integer: maximum width of the generated thumbnail
545 * @param $height Integer: maximum height of the image (optional)
546 * @param $render Integer: Deprecated
548 * @return ThumbnailImage or null on failure
550 * @deprecated use transform()
552 public function getThumbnail( $width, $height=-1, $render = true ) {
553 wfDeprecated( __METHOD__
);
554 $params = array( 'width' => $width );
555 if ( $height != -1 ) {
556 $params['height'] = $height;
558 return $this->transform( $params, 0 );
562 * Transform a media file
564 * @param $params Array: an associative array of handler-specific parameters.
565 * Typical keys are width, height and page.
566 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
567 * @return MediaTransformOutput | false
569 function transform( $params, $flags = 0 ) {
570 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
572 wfProfileIn( __METHOD__
);
574 if ( !$this->canRender() ) {
575 // not a bitmap or renderable image, don't try.
576 $thumb = $this->iconThumb();
580 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
581 $descriptionUrl = $this->getDescriptionUrl();
582 if ( $descriptionUrl ) {
583 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
586 $script = $this->getTransformScript();
587 if ( $script && !($flags & self
::RENDER_NOW
) ) {
588 // Use a script to transform on client request, if possible
589 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
595 $normalisedParams = $params;
596 $this->handler
->normaliseParams( $this, $normalisedParams );
597 $thumbName = $this->thumbName( $normalisedParams );
598 $thumbPath = $this->getThumbPath( $thumbName );
599 $thumbUrl = $this->getThumbUrl( $thumbName );
601 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
602 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
606 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
607 $this->migrateThumbFile( $thumbName );
608 if ( file_exists( $thumbPath )) {
609 $thumbTime = filemtime( $thumbPath );
610 if ( $thumbTime !== FALSE &&
611 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
613 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
617 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
619 // Ignore errors if requested
622 } elseif ( $thumb->isError() ) {
623 $this->lastError
= $thumb->toText();
624 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
625 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
629 // Purge. Useful in the event of Core -> Squid connection failure or squid
630 // purge collisions from elsewhere during failure. Don't keep triggering for
631 // "thumbs" which have the main image URL though (bug 13776)
632 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
633 SquidUpdate
::purge( array( $thumbUrl ) );
637 wfProfileOut( __METHOD__
);
638 return is_object( $thumb ) ?
$thumb : false;
642 * Hook into transform() to allow migration of thumbnail files
644 * Overridden by LocalFile
646 function migrateThumbFile( $thumbName ) {}
649 * Get a MediaHandler instance for this file
650 * @return MediaHandler
652 function getHandler() {
653 if ( !isset( $this->handler
) ) {
654 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
656 return $this->handler
;
660 * Get a ThumbnailImage representing a file type icon
661 * @return ThumbnailImage
663 function iconThumb() {
664 global $wgStylePath, $wgStyleDirectory;
666 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
667 foreach( $try as $icon ) {
668 $path = '/common/images/icons/' . $icon;
669 $filepath = $wgStyleDirectory . $path;
670 if( file_exists( $filepath ) ) {
671 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
678 * Get last thumbnailing error.
681 function getLastError() {
682 return $this->lastError
;
686 * Get all thumbnail names previously generated for this file
688 * Overridden by LocalFile
690 function getThumbnails() { return array(); }
693 * Purge shared caches such as thumbnails and DB data caching
695 * Overridden by LocalFile
697 function purgeCache() {}
700 * Purge the file description page, but don't go after
701 * pages using the file. Use when modifying file history
702 * but not the current data.
704 function purgeDescription() {
705 $title = $this->getTitle();
707 $title->invalidateCache();
708 $title->purgeSquid();
713 * Purge metadata and all affected pages when the file is created,
714 * deleted, or majorly updated.
716 function purgeEverything() {
717 // Delete thumbnails and refresh file metadata cache
719 $this->purgeDescription();
721 // Purge cache of all pages using this file
722 $title = $this->getTitle();
724 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
730 * Return a fragment of the history of file.
733 * @param $limit integer Limit of rows to return
734 * @param $start timestamp Only revisions older than $start will be returned
735 * @param $end timestamp Only revisions newer than $end will be returned
736 * @param $inc bool Include the endpoints of the time range
738 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
743 * Return the history of this file, line by line. Starts with current version,
744 * then old versions. Should return an object similar to an image/oldimage
748 * Overridden in LocalFile
750 public function nextHistoryLine() {
755 * Reset the history pointer to the first element of the history.
756 * Always call this function after using nextHistoryLine() to free db resources
758 * Overridden in LocalFile.
760 public function resetHistory() {}
763 * Get the filename hash component of the directory including trailing slash,
765 * If the repository is not hashed, returns an empty string.
767 function getHashPath() {
768 if ( !isset( $this->hashPath
) ) {
769 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
771 return $this->hashPath
;
775 * Get the path of the file relative to the public zone root
778 return $this->getHashPath() . $this->getName();
782 * Get urlencoded relative path of the file
784 function getUrlRel() {
785 return $this->getHashPath() . rawurlencode( $this->getName() );
788 /** Get the relative path for an archive file */
789 function getArchiveRel( $suffix = false ) {
790 $path = 'archive/' . $this->getHashPath();
791 if ( $suffix === false ) {
792 $path = substr( $path, 0, -1 );
799 /** Get the path of the archive directory, or a particular file if $suffix is specified */
800 function getArchivePath( $suffix = false ) {
801 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
804 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
805 function getThumbPath( $suffix = false ) {
806 $path = $this->repo
->getZonePath('thumb') . '/' . $this->getRel();
807 if ( $suffix !== false ) {
808 $path .= '/' . $suffix;
813 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
814 function getArchiveUrl( $suffix = false ) {
815 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
816 if ( $suffix === false ) {
817 $path = substr( $path, 0, -1 );
819 $path .= rawurlencode( $suffix );
824 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
825 function getThumbUrl( $suffix = false ) {
826 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
827 if ( $suffix !== false ) {
828 $path .= '/' . rawurlencode( $suffix );
833 /** Get the virtual URL for an archive file or directory */
834 function getArchiveVirtualUrl( $suffix = false ) {
835 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
836 if ( $suffix === false ) {
837 $path = substr( $path, 0, -1 );
839 $path .= rawurlencode( $suffix );
844 /** Get the virtual URL for a thumbnail file or directory */
845 function getThumbVirtualUrl( $suffix = false ) {
846 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
847 if ( $suffix !== false ) {
848 $path .= '/' . rawurlencode( $suffix );
853 /** Get the virtual URL for the file itself */
854 function getVirtualUrl( $suffix = false ) {
855 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
856 if ( $suffix !== false ) {
857 $path .= '/' . rawurlencode( $suffix );
865 function isHashed() {
866 return $this->repo
->isHashed();
869 function readOnlyError() {
870 throw new MWException( get_class($this) . ': write operations are not supported' );
874 * Record a file upload in the upload log and the image table
876 * Overridden by LocalFile
878 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
879 $this->readOnlyError();
883 * Move or copy a file to its public location. If a file exists at the
884 * destination, move it to an archive. Returns a FileRepoStatus object with
885 * the archive name in the "value" member on success.
887 * The archive name should be passed through to recordUpload for database
890 * @param $srcPath String: local filesystem path to the source image
891 * @param $flags Integer: a bitwise combination of:
892 * File::DELETE_SOURCE Delete the source file, i.e. move
894 * @return FileRepoStatus object. On success, the value member contains the
895 * archive name, or an empty string if it was a new file.
898 * Overridden by LocalFile
900 function publish( $srcPath, $flags = 0 ) {
901 $this->readOnlyError();
905 * Get an array of Title objects which are articles which use this file
906 * Also adds their IDs to the link cache
908 * This is mostly copied from Title::getLinksTo()
910 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
912 function getLinksTo( $options = array() ) {
913 wfDeprecated( __METHOD__
);
914 wfProfileIn( __METHOD__
);
916 // Note: use local DB not repo DB, we want to know local links
917 if ( count( $options ) > 0 ) {
918 $db = wfGetDB( DB_MASTER
);
920 $db = wfGetDB( DB_SLAVE
);
922 $linkCache = LinkCache
::singleton();
924 $encName = $db->addQuotes( $this->getName() );
925 $res = $db->select( array( 'page', 'imagelinks'),
926 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
927 array( 'page_id=il_from', 'il_to' => $encName ),
932 if ( $db->numRows( $res ) ) {
933 foreach ( $res as $row ) {
934 $titleObj = Title
::newFromRow( $row );
936 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
937 $retVal[] = $titleObj;
941 wfProfileOut( __METHOD__
);
945 function formatMetadata() {
946 if ( !$this->getHandler() ) {
949 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
953 * Returns true if the file comes from the local file repository.
958 $repo = $this->getRepo();
959 return $repo && $repo->isLocal();
963 * Returns the name of the repository.
967 function getRepoName() {
968 return $this->repo ?
$this->repo
->getName() : 'unknown';
971 * Returns the repository
978 * Returns true if the image is an old version
986 * Is this file a "deleted" file in a private archive?
989 function isDeleted( $field ) {
994 * Return the deletion bitfield
997 function getVisibility() {
1002 * Was this file ever deleted from the wiki?
1006 function wasDeleted() {
1007 $title = $this->getTitle();
1008 return $title && $title->isDeletedQuick();
1012 * Move file to the new title
1014 * Move current, old version and all thumbnails
1015 * to the new filename. Old file is deleted.
1017 * Cache purging is done; checks for validity
1018 * and logging are caller's responsibility
1020 * @param $target Title New file name
1021 * @return FileRepoStatus object.
1023 function move( $target ) {
1024 $this->readOnlyError();
1028 * Delete all versions of the file.
1030 * Moves the files into an archive directory (or deletes them)
1031 * and removes the database rows.
1033 * Cache purging is done; logging is caller's responsibility.
1035 * @param $reason String
1036 * @param $suppress Boolean: hide content from sysops?
1037 * @return true on success, false on some kind of failure
1039 * Overridden by LocalFile
1041 function delete( $reason, $suppress = false ) {
1042 $this->readOnlyError();
1046 * Restore all or specified deleted revisions to the given file.
1047 * Permissions and logging are left to the caller.
1049 * May throw database exceptions on error.
1051 * @param $versions set of record ids of deleted items to restore,
1052 * or empty to restore all revisions.
1053 * @param $unsuppress remove restrictions on content upon restoration?
1054 * @return the number of file revisions restored if successful,
1055 * or false on failure
1057 * Overridden by LocalFile
1059 function restore( $versions=array(), $unsuppress=false ) {
1060 $this->readOnlyError();
1064 * Returns 'true' if this file is a type which supports multiple pages,
1065 * e.g. DJVU or PDF. Note that this may be true even if the file in
1066 * question only has a single page.
1070 function isMultipage() {
1071 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1075 * Returns the number of pages of a multipage document, or false for
1076 * documents which aren't multipage documents
1078 function pageCount() {
1079 if ( !isset( $this->pageCount
) ) {
1080 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1081 $this->pageCount
= $this->handler
->pageCount( $this );
1083 $this->pageCount
= false;
1086 return $this->pageCount
;
1090 * Calculate the height of a thumbnail using the source and destination width
1092 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1093 // Exact integer multiply followed by division
1094 if ( $srcWidth == 0 ) {
1097 return round( $srcHeight * $dstWidth / $srcWidth );
1102 * Get an image size array like that returned by getImageSize(), or false if it
1103 * can't be determined.
1105 * @param $fileName String: The filename
1108 function getImageSize( $fileName ) {
1109 if ( !$this->getHandler() ) {
1112 return $this->handler
->getImageSize( $this, $fileName );
1116 * Get the URL of the image description page. May return false if it is
1117 * unknown or not applicable.
1119 function getDescriptionUrl() {
1120 return $this->repo
->getDescriptionUrl( $this->getName() );
1124 * Get the HTML text of the description page, if available
1126 function getDescriptionText() {
1127 global $wgMemc, $wgLang;
1128 if ( !$this->repo
->fetchDescription
) {
1131 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1133 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1134 wfDebug("Attempting to get the description from cache...");
1135 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1137 $obj = $wgMemc->get($key);
1139 wfDebug("success!\n");
1144 wfDebug( "Fetching shared description from $renderUrl\n" );
1145 $res = Http
::get( $renderUrl );
1146 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1147 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1156 * Get discription of file revision
1159 function getDescription() {
1164 * Get the 14-character timestamp of the file upload, or false if
1167 function getTimestamp() {
1168 $path = $this->getPath();
1169 if ( !file_exists( $path ) ) {
1172 return wfTimestamp( TS_MW
, filemtime( $path ) );
1176 * Get the SHA-1 base 36 hash of the file
1178 function getSha1() {
1179 return self
::sha1Base36( $this->getPath() );
1183 * Get the deletion archive key, <sha1>.<ext>
1185 function getStorageKey() {
1186 $hash = $this->getSha1();
1190 $ext = $this->getExtension();
1191 $dotExt = $ext === '' ?
'' : ".$ext";
1192 return $hash . $dotExt;
1196 * Determine if the current user is allowed to view a particular
1197 * field of this file, if it's marked as deleted.
1199 * @param $field Integer
1202 function userCan( $field ) {
1207 * Get an associative array containing information about a file in the local filesystem.
1209 * @param $path String: absolute local filesystem path
1210 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1211 * Set it to false to ignore the extension.
1213 static function getPropsFromPath( $path, $ext = true ) {
1214 wfProfileIn( __METHOD__
);
1215 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1217 'fileExists' => file_exists( $path ) && !is_dir( $path )
1220 if ( $info['fileExists'] ) {
1221 $magic = MimeMagic
::singleton();
1223 if ( $ext === true ) {
1224 $i = strrpos( $path, '.' );
1225 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1228 # mime type according to file contents
1229 $info['file-mime'] = $magic->guessMimeType( $path, false );
1231 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1233 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1234 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1237 $info['size'] = filesize( $path );
1239 # Height, width and metadata
1240 $handler = MediaHandler
::getHandler( $info['mime'] );
1242 $tempImage = (object)array();
1243 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1244 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1247 $info['metadata'] = '';
1249 $info['sha1'] = self
::sha1Base36( $path );
1251 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1253 $info['mime'] = null;
1254 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1255 $info['metadata'] = '';
1257 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1260 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1261 $info['width'] = $gis[0];
1262 $info['height'] = $gis[1];
1263 if ( isset( $gis['bits'] ) ) {
1264 $info['bits'] = $gis['bits'];
1270 $info['height'] = 0;
1273 wfProfileOut( __METHOD__
);
1278 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1279 * encoding, zero padded to 31 digits.
1281 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1284 * Returns false on failure
1286 static function sha1Base36( $path ) {
1287 wfSuppressWarnings();
1288 $hash = sha1_file( $path );
1289 wfRestoreWarnings();
1290 if ( $hash === false ) {
1293 return wfBaseConvert( $hash, 16, 36, 31 );
1297 function getLongDesc() {
1298 $handler = $this->getHandler();
1300 return $handler->getLongDesc( $this );
1302 return MediaHandler
::getGeneralLongDesc( $this );
1306 function getShortDesc() {
1307 $handler = $this->getHandler();
1309 return $handler->getShortDesc( $this );
1311 return MediaHandler
::getGeneralShortDesc( $this );
1315 function getDimensionsString() {
1316 $handler = $this->getHandler();
1318 return $handler->getDimensionsString( $this );
1324 function getRedirected() {
1325 return $this->redirected
;
1328 function getRedirectedTitle() {
1329 if ( $this->redirected
) {
1330 if ( !$this->redirectTitle
)
1331 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1332 return $this->redirectTitle
;
1336 function redirectedFrom( $from ) {
1337 $this->redirected
= $from;
1340 function isMissing() {
1345 * Aliases for backwards compatibility with 1.6
1347 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1348 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1349 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1350 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);