10 * Implements some public methods and some protected utility functions which
11 * are required by multiple child classes. Contains stub functionality for
12 * unimplemented public methods.
14 * Stub functions which should be overridden are marked with STUB. Some more
15 * concrete functions are also typically overridden by child classes.
17 * Note that only the repo object knows what its file class is called. You should
18 * never name a file class explictly outside of the repo class. Instead use the
19 * repo's factory functions to generate file objects, for example:
21 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
23 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
29 const DELETED_FILE
= 1;
30 const DELETED_COMMENT
= 2;
31 const DELETED_USER
= 4;
32 const DELETED_RESTRICTED
= 8;
35 const DELETE_SOURCE
= 1;
38 * Some member variables can be lazy-initialised using __get(). The
39 * initialisation function for these variables is always a function named
40 * like getVar(), where Var is the variable name with upper-case first
43 * The following variables are initialised in this way in this base class:
44 * name, extension, handler, path, canRender, isSafeFile,
45 * transformScript, hashPath, pageCount, url
47 * Code within this class should generally use the accessor function
48 * directly, since __get() isn't re-entrant and therefore causes bugs that
49 * depend on initialisation order.
53 * The following member variables are not lazy-initialised
55 var $repo, $title, $lastError, $redirected, $redirectedTitle;
58 * Call this constructor from child classes
60 function __construct( $title, $repo ) {
61 $this->title
= $title;
65 function __get( $name ) {
66 $function = array( $this, 'get' . ucfirst( $name ) );
67 if ( !is_callable( $function ) ) {
70 $this->$name = call_user_func( $function );
76 * Normalize a file extension to the common form, and ensure it's clean.
77 * Extensions with non-alphanumeric characters will be discarded.
79 * @param $ext string (without the .)
82 static function normalizeExtension( $ext ) {
83 $lower = strtolower( $ext );
90 if( isset( $squish[$lower] ) ) {
91 return $squish[$lower];
92 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
100 * Checks if file extensions are compatible
102 * @param $old File Old file
103 * @param $new string New name
105 static function checkExtensionCompatibility( File
$old, $new ) {
106 $oldMime = $old->getMimeType();
107 $n = strrpos( $new, '.' );
108 $newExt = self
::normalizeExtension(
109 $n ?
substr( $new, $n +
1 ) : '' );
110 $mimeMagic = MimeMagic
::singleton();
111 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
115 * Upgrade the database row if there is one
116 * Called by ImagePage
119 function upgradeRow() {}
122 * Split an internet media type into its two components; if not
123 * a two-part name, set the minor type to 'unknown'.
125 * @param $mime "text/html" etc
126 * @return array ("text", "html") etc
128 static function splitMime( $mime ) {
129 if( strpos( $mime, '/' ) !== false ) {
130 return explode( '/', $mime, 2 );
132 return array( $mime, 'unknown' );
137 * Return the name of this file
139 public function getName() {
140 if ( !isset( $this->name
) ) {
141 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
147 * Get the file extension, e.g. "svg"
149 function getExtension() {
150 if ( !isset( $this->extension
) ) {
151 $n = strrpos( $this->getName(), '.' );
152 $this->extension
= self
::normalizeExtension(
153 $n ?
substr( $this->getName(), $n +
1 ) : '' );
155 return $this->extension
;
159 * Return the associated title object
162 public function getTitle() { return $this->title
; }
165 * Return the title used to find this file
167 public function getOriginalTitle() {
168 if ( $this->redirected
)
169 return $this->getRedirectedTitle();
174 * Return the URL of the file
176 public function getUrl() {
177 if ( !isset( $this->url
) ) {
178 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
184 * Return a fully-qualified URL to the file.
185 * Upload URL paths _may or may not_ be fully qualified, so
186 * we check. Local paths are assumed to belong on $wgServer.
190 public function getFullUrl() {
191 return wfExpandUrl( $this->getUrl() );
194 function getViewURL() {
195 if( $this->mustRender()) {
196 if( $this->canRender() ) {
197 return $this->createThumb( $this->getWidth() );
200 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
201 return $this->getURL(); #hm... return NULL?
204 return $this->getURL();
209 * Return the full filesystem path to the file. Note that this does
210 * not mean that a file actually exists under that location.
212 * This path depends on whether directory hashing is active or not,
213 * i.e. whether the files are all found in the same directory,
214 * or in hashed paths like /images/3/3c.
216 * May return false if the file is not locally accessible.
218 public function getPath() {
219 if ( !isset( $this->path
) ) {
220 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
226 * Alias for getPath()
228 public function getFullPath() {
229 return $this->getPath();
233 * Return the width of the image. Returns false if the width is unknown
237 * Overridden by LocalFile, UnregisteredLocalFile
239 public function getWidth( $page = 1 ) { return false; }
242 * Return the height of the image. Returns false if the height is unknown
246 * Overridden by LocalFile, UnregisteredLocalFile
248 public function getHeight( $page = 1 ) { return false; }
251 * Returns ID or name of user who uploaded the file
254 * @param $type string 'text' or 'id'
256 public function getUser( $type='text' ) { return null; }
259 * Get the duration of a media file in seconds
261 public function getLength() {
262 $handler = $this->getHandler();
264 return $handler->getLength( $this );
271 * Return true if the file is vectorized
273 public function isVectorized() {
274 $handler = $this->getHandler();
276 return $handler->isVectorized( $this );
284 * Get handler-specific metadata
285 * Overridden by LocalFile, UnregisteredLocalFile
288 public function getMetadata() { return false; }
291 * Return the bit depth of the file
292 * Overridden by LocalFile
295 public function getBitDepth() { return 0; }
298 * Return the size of the image file, in bytes
299 * Overridden by LocalFile, UnregisteredLocalFile
302 public function getSize() { return false; }
305 * Returns the mime type of the file.
306 * Overridden by LocalFile, UnregisteredLocalFile
309 function getMimeType() { return 'unknown/unknown'; }
312 * Return the type of the media in the file.
313 * Use the value returned by this function with the MEDIATYPE_xxx constants.
314 * Overridden by LocalFile,
317 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
320 * Checks if the output of transform() for this file is likely
321 * to be valid. If this is false, various user elements will
322 * display a placeholder instead.
324 * Currently, this checks if the file is an image format
325 * that can be converted to a format
326 * supported by all browsers (namely GIF, PNG and JPEG),
327 * or if it is an SVG image and SVG conversion is enabled.
329 function canRender() {
330 if ( !isset( $this->canRender
) ) {
331 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
333 return $this->canRender
;
337 * Accessor for __get()
339 protected function getCanRender() {
340 return $this->canRender();
344 * Return true if the file is of a type that can't be directly
345 * rendered by typical browsers and needs to be re-rasterized.
347 * This returns true for everything but the bitmap types
348 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
349 * also return true for any non-image formats.
353 function mustRender() {
354 return $this->getHandler() && $this->handler
->mustRender( $this );
358 * Alias for canRender()
360 function allowInlineDisplay() {
361 return $this->canRender();
365 * Determines if this media file is in a format that is unlikely to
366 * contain viruses or malicious content. It uses the global
367 * $wgTrustedMediaFormats list to determine if the file is safe.
369 * This is used to show a warning on the description page of non-safe files.
370 * It may also be used to disallow direct [[media:...]] links to such files.
372 * Note that this function will always return true if allowInlineDisplay()
373 * or isTrustedFile() is true for this file.
375 function isSafeFile() {
376 if ( !isset( $this->isSafeFile
) ) {
377 $this->isSafeFile
= $this->_getIsSafeFile();
379 return $this->isSafeFile
;
382 /** Accessor for __get() */
383 protected function getIsSafeFile() {
384 return $this->isSafeFile();
387 /** Uncached accessor */
388 protected function _getIsSafeFile() {
389 if ($this->allowInlineDisplay()) return true;
390 if ($this->isTrustedFile()) return true;
392 global $wgTrustedMediaFormats;
394 $type= $this->getMediaType();
395 $mime= $this->getMimeType();
396 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
398 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
399 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
401 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
402 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
407 /** Returns true if the file is flagged as trusted. Files flagged that way
408 * can be linked to directly, even if that is not allowed for this type of
411 * This is a dummy function right now and always returns false. It could be
412 * implemented to extract a flag from the database. The trusted flag could be
413 * set on upload, if the user has sufficient privileges, to bypass script-
414 * and html-filters. It may even be coupled with cryptographics signatures
417 function isTrustedFile() {
418 #this could be implemented to check a flag in the databas,
419 #look for signatures, etc
424 * Returns true if file exists in the repository.
426 * Overridden by LocalFile to avoid unnecessary stat calls.
428 * @return boolean Whether file exists in the repository.
430 public function exists() {
431 return $this->getPath() && file_exists( $this->path
);
435 * Returns true if file exists in the repository and can be included in a page.
436 * It would be unsafe to include private images, making public thumbnails inadvertently
438 * @return boolean Whether file exists in the repository and is includable.
441 function isVisible() {
442 return $this->exists();
445 function getTransformScript() {
446 if ( !isset( $this->transformScript
) ) {
447 $this->transformScript
= false;
449 $script = $this->repo
->getThumbScriptUrl();
451 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
455 return $this->transformScript
;
459 * Get a ThumbnailImage which is the same size as the source
461 function getUnscaledThumb( $handlerParams = array() ) {
462 $hp =& $handlerParams;
463 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
464 $width = $this->getWidth( $page );
466 return $this->iconThumb();
468 $hp['width'] = $width;
469 return $this->transform( $hp );
473 * Return the file name of a thumbnail with the specified parameters
475 * @param $params Array: handler-specific parameters
478 function thumbName( $params ) {
479 return $this->generateThumbName( $this->getName(), $params );
483 * Generate a thumbnail file name from a name and specified parameters
485 * @param string $name
486 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
488 function generateThumbName( $name, $params ) {
489 if ( !$this->getHandler() ) {
492 $extension = $this->getExtension();
493 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
494 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
495 if ( $thumbExt != $extension ) {
496 $thumbName .= ".$thumbExt";
502 * Create a thumbnail of the image having the specified width/height.
503 * The thumbnail will not be created if the width is larger than the
504 * image's width. Let the browser do the scaling in this case.
505 * The thumbnail is stored on disk and is only computed if the thumbnail
506 * file does not exist OR if it is older than the image.
509 * Keeps aspect ratio of original image. If both width and height are
510 * specified, the generated image will be no bigger than width x height,
511 * and will also have correct aspect ratio.
513 * @param $width Integer: maximum width of the generated thumbnail
514 * @param $height Integer: maximum height of the image (optional)
516 public function createThumb( $width, $height = -1 ) {
517 $params = array( 'width' => $width );
518 if ( $height != -1 ) {
519 $params['height'] = $height;
521 $thumb = $this->transform( $params );
522 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
523 return $thumb->getUrl();
527 * As createThumb, but returns a ThumbnailImage object. This can
528 * provide access to the actual file, the real size of the thumb,
529 * and can produce a convenient \<img\> tag for you.
531 * For non-image formats, this may return a filetype-specific icon.
533 * @param $width Integer: maximum width of the generated thumbnail
534 * @param $height Integer: maximum height of the image (optional)
535 * @param $render Integer: Deprecated
537 * @return ThumbnailImage or null on failure
539 * @deprecated use transform()
541 public function getThumbnail( $width, $height=-1, $render = true ) {
542 wfDeprecated( __METHOD__
);
543 $params = array( 'width' => $width );
544 if ( $height != -1 ) {
545 $params['height'] = $height;
547 return $this->transform( $params, 0 );
551 * Transform a media file
553 * @param $params Array: an associative array of handler-specific parameters.
554 * Typical keys are width, height and page.
555 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
556 * @return MediaTransformOutput | false
558 function transform( $params, $flags = 0 ) {
559 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
561 wfProfileIn( __METHOD__
);
563 if ( !$this->canRender() ) {
564 // not a bitmap or renderable image, don't try.
565 $thumb = $this->iconThumb();
569 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
570 $descriptionUrl = $this->getDescriptionUrl();
571 if ( $descriptionUrl ) {
572 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
575 $script = $this->getTransformScript();
576 if ( $script && !($flags & self
::RENDER_NOW
) ) {
577 // Use a script to transform on client request, if possible
578 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
584 $normalisedParams = $params;
585 $this->handler
->normaliseParams( $this, $normalisedParams );
586 $thumbName = $this->thumbName( $normalisedParams );
587 $thumbPath = $this->getThumbPath( $thumbName );
588 $thumbUrl = $this->getThumbUrl( $thumbName );
590 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
591 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
595 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
596 $this->migrateThumbFile( $thumbName );
597 if ( file_exists( $thumbPath )) {
598 $thumbTime = filemtime( $thumbPath );
599 if ( $thumbTime !== FALSE &&
600 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
602 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
606 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
608 // Ignore errors if requested
611 } elseif ( $thumb->isError() ) {
612 $this->lastError
= $thumb->toText();
613 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
614 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
618 // Purge. Useful in the event of Core -> Squid connection failure or squid
619 // purge collisions from elsewhere during failure. Don't keep triggering for
620 // "thumbs" which have the main image URL though (bug 13776)
621 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
622 SquidUpdate
::purge( array( $thumbUrl ) );
626 wfProfileOut( __METHOD__
);
627 return is_object( $thumb ) ?
$thumb : false;
631 * Hook into transform() to allow migration of thumbnail files
633 * Overridden by LocalFile
635 function migrateThumbFile( $thumbName ) {}
638 * Get a MediaHandler instance for this file
639 * @return MediaHandler
641 function getHandler() {
642 if ( !isset( $this->handler
) ) {
643 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
645 return $this->handler
;
649 * Get a ThumbnailImage representing a file type icon
650 * @return ThumbnailImage
652 function iconThumb() {
653 global $wgStylePath, $wgStyleDirectory;
655 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
656 foreach( $try as $icon ) {
657 $path = '/common/images/icons/' . $icon;
658 $filepath = $wgStyleDirectory . $path;
659 if( file_exists( $filepath ) ) {
660 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
667 * Get last thumbnailing error.
670 function getLastError() {
671 return $this->lastError
;
675 * Get all thumbnail names previously generated for this file
677 * Overridden by LocalFile
679 function getThumbnails() { return array(); }
682 * Purge shared caches such as thumbnails and DB data caching
684 * Overridden by LocalFile
686 function purgeCache() {}
689 * Purge the file description page, but don't go after
690 * pages using the file. Use when modifying file history
691 * but not the current data.
693 function purgeDescription() {
694 $title = $this->getTitle();
696 $title->invalidateCache();
697 $title->purgeSquid();
702 * Purge metadata and all affected pages when the file is created,
703 * deleted, or majorly updated.
705 function purgeEverything() {
706 // Delete thumbnails and refresh file metadata cache
708 $this->purgeDescription();
710 // Purge cache of all pages using this file
711 $title = $this->getTitle();
713 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
719 * Return a fragment of the history of file.
722 * @param $limit integer Limit of rows to return
723 * @param $start timestamp Only revisions older than $start will be returned
724 * @param $end timestamp Only revisions newer than $end will be returned
725 * @param $inc bool Include the endpoints of the time range
727 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
732 * Return the history of this file, line by line. Starts with current version,
733 * then old versions. Should return an object similar to an image/oldimage
737 * Overridden in LocalFile
739 public function nextHistoryLine() {
744 * Reset the history pointer to the first element of the history.
745 * Always call this function after using nextHistoryLine() to free db resources
747 * Overridden in LocalFile.
749 public function resetHistory() {}
752 * Get the filename hash component of the directory including trailing slash,
754 * If the repository is not hashed, returns an empty string.
756 function getHashPath() {
757 if ( !isset( $this->hashPath
) ) {
758 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
760 return $this->hashPath
;
764 * Get the path of the file relative to the public zone root
767 return $this->getHashPath() . $this->getName();
771 * Get urlencoded relative path of the file
773 function getUrlRel() {
774 return $this->getHashPath() . rawurlencode( $this->getName() );
777 /** Get the relative path for an archive file */
778 function getArchiveRel( $suffix = false ) {
779 $path = 'archive/' . $this->getHashPath();
780 if ( $suffix === false ) {
781 $path = substr( $path, 0, -1 );
788 /** Get the path of the archive directory, or a particular file if $suffix is specified */
789 function getArchivePath( $suffix = false ) {
790 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
793 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
794 function getThumbPath( $suffix = false ) {
795 $path = $this->repo
->getZonePath('thumb') . '/' . $this->getRel();
796 if ( $suffix !== false ) {
797 $path .= '/' . $suffix;
802 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
803 function getArchiveUrl( $suffix = false ) {
804 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
805 if ( $suffix === false ) {
806 $path = substr( $path, 0, -1 );
808 $path .= rawurlencode( $suffix );
813 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
814 function getThumbUrl( $suffix = false ) {
815 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
816 if ( $suffix !== false ) {
817 $path .= '/' . rawurlencode( $suffix );
822 /** Get the virtual URL for an archive file or directory */
823 function getArchiveVirtualUrl( $suffix = false ) {
824 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
825 if ( $suffix === false ) {
826 $path = substr( $path, 0, -1 );
828 $path .= rawurlencode( $suffix );
833 /** Get the virtual URL for a thumbnail file or directory */
834 function getThumbVirtualUrl( $suffix = false ) {
835 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
836 if ( $suffix !== false ) {
837 $path .= '/' . rawurlencode( $suffix );
842 /** Get the virtual URL for the file itself */
843 function getVirtualUrl( $suffix = false ) {
844 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
845 if ( $suffix !== false ) {
846 $path .= '/' . rawurlencode( $suffix );
854 function isHashed() {
855 return $this->repo
->isHashed();
858 function readOnlyError() {
859 throw new MWException( get_class($this) . ': write operations are not supported' );
863 * Record a file upload in the upload log and the image table
865 * Overridden by LocalFile
867 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
868 $this->readOnlyError();
872 * Move or copy a file to its public location. If a file exists at the
873 * destination, move it to an archive. Returns a FileRepoStatus object with
874 * the archive name in the "value" member on success.
876 * The archive name should be passed through to recordUpload for database
879 * @param $srcPath String: local filesystem path to the source image
880 * @param $flags Integer: a bitwise combination of:
881 * File::DELETE_SOURCE Delete the source file, i.e. move
883 * @return FileRepoStatus object. On success, the value member contains the
884 * archive name, or an empty string if it was a new file.
887 * Overridden by LocalFile
889 function publish( $srcPath, $flags = 0 ) {
890 $this->readOnlyError();
894 * Get an array of Title objects which are articles which use this file
895 * Also adds their IDs to the link cache
897 * This is mostly copied from Title::getLinksTo()
899 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
901 function getLinksTo( $options = array() ) {
902 wfDeprecated( __METHOD__
);
903 wfProfileIn( __METHOD__
);
905 // Note: use local DB not repo DB, we want to know local links
906 if ( count( $options ) > 0 ) {
907 $db = wfGetDB( DB_MASTER
);
909 $db = wfGetDB( DB_SLAVE
);
911 $linkCache = LinkCache
::singleton();
913 $encName = $db->addQuotes( $this->getName() );
914 $res = $db->select( array( 'page', 'imagelinks'),
915 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
916 array( 'page_id=il_from', 'il_to' => $encName ),
921 if ( $db->numRows( $res ) ) {
922 foreach ( $res as $row ) {
923 $titleObj = Title
::newFromRow( $row );
925 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
926 $retVal[] = $titleObj;
930 wfProfileOut( __METHOD__
);
934 function formatMetadata() {
935 if ( !$this->getHandler() ) {
938 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
942 * Returns true if the file comes from the local file repository.
947 $repo = $this->getRepo();
948 return $repo && $repo->isLocal();
952 * Returns the name of the repository.
956 function getRepoName() {
957 return $this->repo ?
$this->repo
->getName() : 'unknown';
960 * Returns the repository
967 * Returns true if the image is an old version
975 * Is this file a "deleted" file in a private archive?
978 function isDeleted( $field ) {
983 * Return the deletion bitfield
986 function getVisibility() {
991 * Was this file ever deleted from the wiki?
995 function wasDeleted() {
996 $title = $this->getTitle();
997 return $title && $title->isDeletedQuick();
1001 * Move file to the new title
1003 * Move current, old version and all thumbnails
1004 * to the new filename. Old file is deleted.
1006 * Cache purging is done; checks for validity
1007 * and logging are caller's responsibility
1009 * @param $target Title New file name
1010 * @return FileRepoStatus object.
1012 function move( $target ) {
1013 $this->readOnlyError();
1017 * Delete all versions of the file.
1019 * Moves the files into an archive directory (or deletes them)
1020 * and removes the database rows.
1022 * Cache purging is done; logging is caller's responsibility.
1024 * @param $reason String
1025 * @param $suppress Boolean: hide content from sysops?
1026 * @return true on success, false on some kind of failure
1028 * Overridden by LocalFile
1030 function delete( $reason, $suppress = false ) {
1031 $this->readOnlyError();
1035 * Restore all or specified deleted revisions to the given file.
1036 * Permissions and logging are left to the caller.
1038 * May throw database exceptions on error.
1040 * @param $versions set of record ids of deleted items to restore,
1041 * or empty to restore all revisions.
1042 * @param $unsuppress remove restrictions on content upon restoration?
1043 * @return the number of file revisions restored if successful,
1044 * or false on failure
1046 * Overridden by LocalFile
1048 function restore( $versions=array(), $unsuppress=false ) {
1049 $this->readOnlyError();
1053 * Returns 'true' if this file is a type which supports multiple pages,
1054 * e.g. DJVU or PDF. Note that this may be true even if the file in
1055 * question only has a single page.
1059 function isMultipage() {
1060 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1064 * Returns the number of pages of a multipage document, or false for
1065 * documents which aren't multipage documents
1067 function pageCount() {
1068 if ( !isset( $this->pageCount
) ) {
1069 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1070 $this->pageCount
= $this->handler
->pageCount( $this );
1072 $this->pageCount
= false;
1075 return $this->pageCount
;
1079 * Calculate the height of a thumbnail using the source and destination width
1081 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1082 // Exact integer multiply followed by division
1083 if ( $srcWidth == 0 ) {
1086 return round( $srcHeight * $dstWidth / $srcWidth );
1091 * Get an image size array like that returned by getImageSize(), or false if it
1092 * can't be determined.
1094 * @param $fileName String: The filename
1097 function getImageSize( $fileName ) {
1098 if ( !$this->getHandler() ) {
1101 return $this->handler
->getImageSize( $this, $fileName );
1105 * Get the URL of the image description page. May return false if it is
1106 * unknown or not applicable.
1108 function getDescriptionUrl() {
1109 return $this->repo
->getDescriptionUrl( $this->getName() );
1113 * Get the HTML text of the description page, if available
1114 * For local files ImagePage does not use it, because it skips the parser cache.
1116 function getDescriptionText() {
1117 if( $this->isLocal() ) {
1119 $revision = Revision
::newFromTitle( $this->title
);
1120 if ( !$revision ) return false;
1121 $text = $revision->getText();
1122 if ( !$text ) return false;
1123 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1124 return $pout->getText();
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
);