MediaWiki REL1_30
File.php
Go to the documentation of this file.
1<?php
9
51abstract class File implements IDBAccessObject {
52 // Bitfield values akin to the Revision deletion constants
53 const DELETED_FILE = 1;
54 const DELETED_COMMENT = 2;
55 const DELETED_USER = 4;
57
59 const RENDER_NOW = 1;
64 const RENDER_FORCE = 2;
65
66 const DELETE_SOURCE = 1;
67
68 // Audience options for File::getDescription()
69 const FOR_PUBLIC = 1;
70 const FOR_THIS_USER = 2;
71 const RAW = 3;
72
73 // Options for File::thumbName()
74 const THUMB_FULL_NAME = 1;
75
96 public $repo;
97
99 protected $title;
100
102 protected $lastError;
103
105 protected $redirected;
106
109
111 protected $fsFile;
112
114 protected $handler;
115
117 protected $url;
118
120 protected $extension;
121
123 protected $name;
124
126 protected $path;
127
129 protected $hashPath;
130
134 protected $pageCount;
135
138
140 protected $redirectTitle;
141
143 protected $canRender;
144
148 protected $isSafeFile;
149
151 protected $repoClass = 'FileRepo';
152
155
166 function __construct( $title, $repo ) {
167 // Some subclasses do not use $title, but set name/title some other way
168 if ( $title !== false ) {
169 $title = self::normalizeTitle( $title, 'exception' );
170 }
171 $this->title = $title;
172 $this->repo = $repo;
173 }
174
184 static function normalizeTitle( $title, $exception = false ) {
185 $ret = $title;
186 if ( $ret instanceof Title ) {
187 # Normalize NS_MEDIA -> NS_FILE
188 if ( $ret->getNamespace() == NS_MEDIA ) {
189 $ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
190 # Sanity check the title namespace
191 } elseif ( $ret->getNamespace() !== NS_FILE ) {
192 $ret = null;
193 }
194 } else {
195 # Convert strings to Title objects
196 $ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
197 }
198 if ( !$ret && $exception !== false ) {
199 throw new MWException( "`$title` is not a valid file title." );
200 }
201
202 return $ret;
203 }
204
205 function __get( $name ) {
206 $function = [ $this, 'get' . ucfirst( $name ) ];
207 if ( !is_callable( $function ) ) {
208 return null;
209 } else {
210 $this->$name = call_user_func( $function );
211
212 return $this->$name;
213 }
214 }
215
224 static function normalizeExtension( $extension ) {
225 $lower = strtolower( $extension );
226 $squish = [
227 'htm' => 'html',
228 'jpeg' => 'jpg',
229 'mpeg' => 'mpg',
230 'tiff' => 'tif',
231 'ogv' => 'ogg' ];
232 if ( isset( $squish[$lower] ) ) {
233 return $squish[$lower];
234 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
235 return $lower;
236 } else {
237 return '';
238 }
239 }
240
249 static function checkExtensionCompatibility( File $old, $new ) {
250 $oldMime = $old->getMimeType();
251 $n = strrpos( $new, '.' );
252 $newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
254
255 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
256 }
257
263 function upgradeRow() {
264 }
265
273 public static function splitMime( $mime ) {
274 if ( strpos( $mime, '/' ) !== false ) {
275 return explode( '/', $mime, 2 );
276 } else {
277 return [ $mime, 'unknown' ];
278 }
279 }
280
288 public static function compare( File $a, File $b ) {
289 return strcmp( $a->getName(), $b->getName() );
290 }
291
297 public function getName() {
298 if ( !isset( $this->name ) ) {
299 $this->assertRepoDefined();
300 $this->name = $this->repo->getNameFromTitle( $this->title );
301 }
302
303 return $this->name;
304 }
305
311 function getExtension() {
312 if ( !isset( $this->extension ) ) {
313 $n = strrpos( $this->getName(), '.' );
314 $this->extension = self::normalizeExtension(
315 $n ? substr( $this->getName(), $n + 1 ) : '' );
316 }
317
318 return $this->extension;
319 }
320
326 public function getTitle() {
327 return $this->title;
328 }
329
335 public function getOriginalTitle() {
336 if ( $this->redirected ) {
337 return $this->getRedirectedTitle();
338 }
339
340 return $this->title;
341 }
342
348 public function getUrl() {
349 if ( !isset( $this->url ) ) {
350 $this->assertRepoDefined();
351 $ext = $this->getExtension();
352 $this->url = $this->repo->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
353 }
354
355 return $this->url;
356 }
357
364 public function getDescriptionShortUrl() {
365 return null;
366 }
367
375 public function getFullUrl() {
376 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE );
377 }
378
382 public function getCanonicalUrl() {
383 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL );
384 }
385
389 function getViewURL() {
390 if ( $this->mustRender() ) {
391 if ( $this->canRender() ) {
392 return $this->createThumb( $this->getWidth() );
393 } else {
394 wfDebug( __METHOD__ . ': supposed to render ' . $this->getName() .
395 ' (' . $this->getMimeType() . "), but can't!\n" );
396
397 return $this->getUrl(); # hm... return NULL?
398 }
399 } else {
400 return $this->getUrl();
401 }
402 }
403
417 public function getPath() {
418 if ( !isset( $this->path ) ) {
419 $this->assertRepoDefined();
420 $this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
421 }
422
423 return $this->path;
424 }
425
433 public function getLocalRefPath() {
434 $this->assertRepoDefined();
435 if ( !isset( $this->fsFile ) ) {
436 $starttime = microtime( true );
437 $this->fsFile = $this->repo->getLocalReference( $this->getPath() );
438
439 $statTiming = microtime( true ) - $starttime;
440 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
441 'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
442
443 if ( !$this->fsFile ) {
444 $this->fsFile = false; // null => false; cache negative hits
445 }
446 }
447
448 return ( $this->fsFile )
449 ? $this->fsFile->getPath()
450 : false;
451 }
452
463 public function getWidth( $page = 1 ) {
464 return false;
465 }
466
477 public function getHeight( $page = 1 ) {
478 return false;
479 }
480
490 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
492
493 $imageWidth = $this->getWidth( $page );
494
495 if ( $imageWidth === false ) {
496 return false;
497 }
498
499 if ( $desiredWidth > $imageWidth ) {
500 return false;
501 }
502
503 if ( !$wgThumbnailBuckets ) {
504 return false;
505 }
506
507 $sortedBuckets = $wgThumbnailBuckets;
508
509 sort( $sortedBuckets );
510
511 foreach ( $sortedBuckets as $bucket ) {
512 if ( $bucket >= $imageWidth ) {
513 return false;
514 }
515
516 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
517 return $bucket;
518 }
519 }
520
521 // Image is bigger than any available bucket
522 return false;
523 }
524
532 public function getUser( $type = 'text' ) {
533 return null;
534 }
535
541 public function getLength() {
542 $handler = $this->getHandler();
543 if ( $handler ) {
544 return $handler->getLength( $this );
545 } else {
546 return 0;
547 }
548 }
549
555 public function isVectorized() {
556 $handler = $this->getHandler();
557 if ( $handler ) {
558 return $handler->isVectorized( $this );
559 } else {
560 return false;
561 }
562 }
563
575 public function getAvailableLanguages() {
576 $handler = $this->getHandler();
577 if ( $handler ) {
578 return $handler->getAvailableLanguages( $this );
579 } else {
580 return [];
581 }
582 }
583
591 public function getDefaultRenderLanguage() {
592 $handler = $this->getHandler();
593 if ( $handler ) {
594 return $handler->getDefaultRenderLanguage( $this );
595 } else {
596 return null;
597 }
598 }
599
611 $handler = $this->getHandler();
612 if ( !$handler ) {
613 // We cannot handle image whatsoever, thus
614 // one would not expect it to be animated
615 // so true.
616 return true;
617 } else {
618 if ( $this->allowInlineDisplay()
619 && $handler->isAnimatedImage( $this )
620 && !$handler->canAnimateThumbnail( $this )
621 ) {
622 // Image is animated, but thumbnail isn't.
623 // This is unexpected to the user.
624 return false;
625 } else {
626 // Image is not animated, so one would
627 // not expect thumb to be
628 return true;
629 }
630 }
631 }
632
639 public function getMetadata() {
640 return false;
641 }
642
649 public function getCommonMetaArray() {
650 $handler = $this->getHandler();
651
652 if ( !$handler ) {
653 return false;
654 }
655
656 return $handler->getCommonMetaArray( $this );
657 }
658
667 public function convertMetadataVersion( $metadata, $version ) {
668 $handler = $this->getHandler();
669 if ( !is_array( $metadata ) ) {
670 // Just to make the return type consistent
671 $metadata = unserialize( $metadata );
672 }
673 if ( $handler ) {
674 return $handler->convertMetadataVersion( $metadata, $version );
675 } else {
676 return $metadata;
677 }
678 }
679
686 public function getBitDepth() {
687 return 0;
688 }
689
696 public function getSize() {
697 return false;
698 }
699
707 function getMimeType() {
708 return 'unknown/unknown';
709 }
710
718 function getMediaType() {
719 return MEDIATYPE_UNKNOWN;
720 }
721
734 function canRender() {
735 if ( !isset( $this->canRender ) ) {
736 $this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
737 }
738
739 return $this->canRender;
740 }
741
746 protected function getCanRender() {
747 return $this->canRender();
748 }
749
760 function mustRender() {
761 return $this->getHandler() && $this->handler->mustRender( $this );
762 }
763
770 return $this->canRender();
771 }
772
786 function isSafeFile() {
787 if ( !isset( $this->isSafeFile ) ) {
788 $this->isSafeFile = $this->getIsSafeFileUncached();
789 }
790
791 return $this->isSafeFile;
792 }
793
799 protected function getIsSafeFile() {
800 return $this->isSafeFile();
801 }
802
808 protected function getIsSafeFileUncached() {
810
811 if ( $this->allowInlineDisplay() ) {
812 return true;
813 }
814 if ( $this->isTrustedFile() ) {
815 return true;
816 }
817
818 $type = $this->getMediaType();
819 $mime = $this->getMimeType();
820 # wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
821
822 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
823 return false; # unknown type, not trusted
824 }
825 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
826 return true;
827 }
828
829 if ( $mime === "unknown/unknown" ) {
830 return false; # unknown type, not trusted
831 }
832 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
833 return true;
834 }
835
836 return false;
837 }
838
852 function isTrustedFile() {
853 # this could be implemented to check a flag in the database,
854 # look for signatures, etc
855 return false;
856 }
857
867 public function load( $flags = 0 ) {
868 }
869
877 public function exists() {
878 return $this->getPath() && $this->repo->fileExists( $this->path );
879 }
880
887 public function isVisible() {
888 return $this->exists();
889 }
890
895 if ( !isset( $this->transformScript ) ) {
896 $this->transformScript = false;
897 if ( $this->repo ) {
898 $script = $this->repo->getThumbScriptUrl();
899 if ( $script ) {
900 $this->transformScript = wfAppendQuery( $script, [ 'f' => $this->getName() ] );
901 }
902 }
903 }
904
906 }
907
916 $hp =& $handlerParams;
917 $page = isset( $hp['page'] ) ? $hp['page'] : false;
918 $width = $this->getWidth( $page );
919 if ( !$width ) {
920 return $this->iconThumb();
921 }
922 $hp['width'] = $width;
923 // be sure to ignore any height specification as well (T64258)
924 unset( $hp['height'] );
925
926 return $this->transform( $hp );
927 }
928
938 public function thumbName( $params, $flags = 0 ) {
939 $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
940 ? $this->repo->nameForThumb( $this->getName() )
941 : $this->getName();
942
943 return $this->generateThumbName( $name, $params );
944 }
945
953 public function generateThumbName( $name, $params ) {
954 if ( !$this->getHandler() ) {
955 return null;
956 }
957 $extension = $this->getExtension();
958 list( $thumbExt, ) = $this->getHandler()->getThumbType(
959 $extension, $this->getMimeType(), $params );
960 $thumbName = $this->getHandler()->makeParamString( $params );
961
962 if ( $this->repo->supportsSha1URLs() ) {
963 $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
964 } else {
965 $thumbName .= '-' . $name;
966
967 if ( $thumbExt != $extension ) {
968 $thumbName .= ".$thumbExt";
969 }
970 }
971
972 return $thumbName;
973 }
974
992 public function createThumb( $width, $height = -1 ) {
993 $params = [ 'width' => $width ];
994 if ( $height != -1 ) {
995 $params['height'] = $height;
996 }
997 $thumb = $this->transform( $params );
998 if ( !$thumb || $thumb->isError() ) {
999 return '';
1000 }
1001
1002 return $thumb->getUrl();
1003 }
1004
1014 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
1015 global $wgIgnoreImageErrors;
1016
1017 $handler = $this->getHandler();
1018 if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1019 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1020 } else {
1021 return new MediaTransformError( 'thumbnail_error',
1022 $params['width'], 0, wfMessage( 'thumbnail-dest-create' ) );
1023 }
1024 }
1025
1034 function transform( $params, $flags = 0 ) {
1035 global $wgThumbnailEpoch;
1036
1037 do {
1038 if ( !$this->canRender() ) {
1039 $thumb = $this->iconThumb();
1040 break; // not a bitmap or renderable image, don't try
1041 }
1042
1043 // Get the descriptionUrl to embed it as comment into the thumbnail. T21791.
1044 $descriptionUrl = $this->getDescriptionUrl();
1045 if ( $descriptionUrl ) {
1046 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
1047 }
1048
1049 $handler = $this->getHandler();
1050 $script = $this->getTransformScript();
1051 if ( $script && !( $flags & self::RENDER_NOW ) ) {
1052 // Use a script to transform on client request, if possible
1053 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1054 if ( $thumb ) {
1055 break;
1056 }
1057 }
1058
1059 $normalisedParams = $params;
1060 $handler->normaliseParams( $this, $normalisedParams );
1061
1062 $thumbName = $this->thumbName( $normalisedParams );
1063 $thumbUrl = $this->getThumbUrl( $thumbName );
1064 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1065
1066 if ( $this->repo ) {
1067 // Defer rendering if a 404 handler is set up...
1068 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
1069 // XXX: Pass in the storage path even though we are not rendering anything
1070 // and the path is supposed to be an FS path. This is due to getScalerType()
1071 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1072 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1073 break;
1074 }
1075 // Check if an up-to-date thumbnail already exists...
1076 wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
1077 if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
1078 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
1079 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1080 // XXX: Pass in the storage path even though we are not rendering anything
1081 // and the path is supposed to be an FS path. This is due to getScalerType()
1082 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1083 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1084 $thumb->setStoragePath( $thumbPath );
1085 break;
1086 }
1087 } elseif ( $flags & self::RENDER_FORCE ) {
1088 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
1089 }
1090
1091 // If the backend is ready-only, don't keep generating thumbnails
1092 // only to return transformation errors, just return the error now.
1093 if ( $this->repo->getReadOnlyReason() !== false ) {
1094 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1095 break;
1096 }
1097 }
1098
1099 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1100
1101 if ( !$tmpFile ) {
1102 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1103 } else {
1104 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1105 }
1106 } while ( false );
1107
1108 return is_object( $thumb ) ? $thumb : false;
1109 }
1110
1118 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1119 global $wgIgnoreImageErrors;
1120
1121 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1122
1123 $handler = $this->getHandler();
1124
1125 $normalisedParams = $transformParams;
1126 $handler->normaliseParams( $this, $normalisedParams );
1127
1128 $thumbName = $this->thumbName( $normalisedParams );
1129 $thumbUrl = $this->getThumbUrl( $thumbName );
1130 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1131
1132 $tmpThumbPath = $tmpFile->getPath();
1133
1134 if ( $handler->supportsBucketing() ) {
1135 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1136 }
1137
1138 $starttime = microtime( true );
1139
1140 // Actually render the thumbnail...
1141 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1142 $tmpFile->bind( $thumb ); // keep alive with $thumb
1143
1144 $statTiming = microtime( true ) - $starttime;
1145 $stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
1146
1147 if ( !$thumb ) { // bad params?
1148 $thumb = false;
1149 } elseif ( $thumb->isError() ) { // transform error
1151 $this->lastError = $thumb->toText();
1152 // Ignore errors if requested
1153 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1154 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1155 }
1156 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
1157 // Copy the thumbnail from the file system into storage...
1158
1159 $starttime = microtime( true );
1160
1161 $disposition = $this->getThumbDisposition( $thumbName );
1162 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1163 if ( $status->isOK() ) {
1164 $thumb->setStoragePath( $thumbPath );
1165 } else {
1166 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1167 }
1168
1169 $statTiming = microtime( true ) - $starttime;
1170 $stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
1171
1172 // Give extensions a chance to do something with this thumbnail...
1173 Hooks::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
1174 }
1175
1176 return $thumb;
1177 }
1178
1185 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1186 if ( !$this->repo
1187 || !isset( $params['physicalWidth'] )
1188 || !isset( $params['physicalHeight'] )
1189 ) {
1190 return false;
1191 }
1192
1193 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1194
1195 if ( !$bucket || $bucket == $params['physicalWidth'] ) {
1196 return false;
1197 }
1198
1199 $bucketPath = $this->getBucketThumbPath( $bucket );
1200
1201 if ( $this->repo->fileExists( $bucketPath ) ) {
1202 return false;
1203 }
1204
1205 $starttime = microtime( true );
1206
1207 $params['physicalWidth'] = $bucket;
1208 $params['width'] = $bucket;
1209
1210 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1211
1212 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1213
1214 if ( !$tmpFile ) {
1215 return false;
1216 }
1217
1218 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1219
1220 $buckettime = microtime( true ) - $starttime;
1221
1222 if ( !$thumb || $thumb->isError() ) {
1223 return false;
1224 }
1225
1226 $this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
1227 // For the caching to work, we need to make the tmp file survive as long as
1228 // this object exists
1229 $tmpFile->bind( $this );
1230
1231 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
1232 'media.thumbnail.generate.bucket', 1000 * $buckettime );
1233
1234 return true;
1235 }
1236
1242 public function getThumbnailSource( $params ) {
1243 if ( $this->repo
1244 && $this->getHandler()->supportsBucketing()
1245 && isset( $params['physicalWidth'] )
1246 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1247 ) {
1248 if ( $this->getWidth() != 0 ) {
1249 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1250 } else {
1251 $bucketHeight = 0;
1252 }
1253
1254 // Try to avoid reading from storage if the file was generated by this script
1255 if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
1256 $tmpPath = $this->tmpBucketedThumbCache[$bucket];
1257
1258 if ( file_exists( $tmpPath ) ) {
1259 return [
1260 'path' => $tmpPath,
1261 'width' => $bucket,
1262 'height' => $bucketHeight
1263 ];
1264 }
1265 }
1266
1267 $bucketPath = $this->getBucketThumbPath( $bucket );
1268
1269 if ( $this->repo->fileExists( $bucketPath ) ) {
1270 $fsFile = $this->repo->getLocalReference( $bucketPath );
1271
1272 if ( $fsFile ) {
1273 return [
1274 'path' => $fsFile->getPath(),
1275 'width' => $bucket,
1276 'height' => $bucketHeight
1277 ];
1278 }
1279 }
1280 }
1281
1282 // Thumbnailing a very large file could result in network saturation if
1283 // everyone does it at once.
1284 if ( $this->getSize() >= 1e7 ) { // 10MB
1285 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1286 [
1287 'doWork' => function () {
1288 return $this->getLocalRefPath();
1289 }
1290 ]
1291 );
1292 $srcPath = $work->execute();
1293 } else {
1294 $srcPath = $this->getLocalRefPath();
1295 }
1296
1297 // Original file
1298 return [
1299 'path' => $srcPath,
1300 'width' => $this->getWidth(),
1301 'height' => $this->getHeight()
1302 ];
1303 }
1304
1310 protected function getBucketThumbPath( $bucket ) {
1311 $thumbName = $this->getBucketThumbName( $bucket );
1312 return $this->getThumbPath( $thumbName );
1313 }
1314
1320 protected function getBucketThumbName( $bucket ) {
1321 return $this->thumbName( [ 'physicalWidth' => $bucket ] );
1322 }
1323
1329 protected function makeTransformTmpFile( $thumbPath ) {
1330 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
1331 return TempFSFile::factory( 'transform_', $thumbExt, wfTempDir() );
1332 }
1333
1339 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1340 $fileName = $this->name; // file name to suggest
1341 $thumbExt = FileBackend::extensionFromPath( $thumbName );
1342 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1343 $fileName .= ".$thumbExt";
1344 }
1345
1346 return FileBackend::makeContentDisposition( $dispositionType, $fileName );
1347 }
1348
1355 function migrateThumbFile( $thumbName ) {
1356 }
1357
1364 function getHandler() {
1365 if ( !isset( $this->handler ) ) {
1366 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
1367 }
1368
1369 return $this->handler;
1370 }
1371
1377 function iconThumb() {
1378 global $wgResourceBasePath, $IP;
1379 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1380 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1381
1382 $try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
1383 foreach ( $try as $icon ) {
1384 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1385 $params = [ 'width' => 120, 'height' => 120 ];
1386
1387 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1388 }
1389 }
1390
1391 return null;
1392 }
1393
1399 function getLastError() {
1400 return $this->lastError;
1401 }
1402
1409 function getThumbnails() {
1410 return [];
1411 }
1412
1420 function purgeCache( $options = [] ) {
1421 }
1422
1428 function purgeDescription() {
1429 $title = $this->getTitle();
1430 if ( $title ) {
1431 $title->invalidateCache();
1432 $title->purgeSquid();
1433 }
1434 }
1435
1440 function purgeEverything() {
1441 // Delete thumbnails and refresh file metadata cache
1442 $this->purgeCache();
1443 $this->purgeDescription();
1444
1445 // Purge cache of all pages using this file
1446 $title = $this->getTitle();
1447 if ( $title ) {
1448 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
1449 }
1450 }
1451
1463 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1464 return [];
1465 }
1466
1476 public function nextHistoryLine() {
1477 return false;
1478 }
1479
1486 public function resetHistory() {
1487 }
1488
1496 function getHashPath() {
1497 if ( !isset( $this->hashPath ) ) {
1498 $this->assertRepoDefined();
1499 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1500 }
1501
1502 return $this->hashPath;
1503 }
1504
1511 function getRel() {
1512 return $this->getHashPath() . $this->getName();
1513 }
1514
1522 function getArchiveRel( $suffix = false ) {
1523 $path = 'archive/' . $this->getHashPath();
1524 if ( $suffix === false ) {
1525 $path = substr( $path, 0, -1 );
1526 } else {
1527 $path .= $suffix;
1528 }
1529
1530 return $path;
1531 }
1532
1540 function getThumbRel( $suffix = false ) {
1541 $path = $this->getRel();
1542 if ( $suffix !== false ) {
1543 $path .= '/' . $suffix;
1544 }
1545
1546 return $path;
1547 }
1548
1555 function getUrlRel() {
1556 return $this->getHashPath() . rawurlencode( $this->getName() );
1557 }
1558
1567 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1568 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1569 if ( $suffix === false ) {
1570 $path = substr( $path, 0, -1 );
1571 } else {
1572 $path .= $suffix;
1573 }
1574
1575 return $path;
1576 }
1577
1584 function getArchivePath( $suffix = false ) {
1585 $this->assertRepoDefined();
1586
1587 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1588 }
1589
1597 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1598 $this->assertRepoDefined();
1599
1600 return $this->repo->getZonePath( 'thumb' ) . '/' .
1601 $this->getArchiveThumbRel( $archiveName, $suffix );
1602 }
1603
1610 function getThumbPath( $suffix = false ) {
1611 $this->assertRepoDefined();
1612
1613 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1614 }
1615
1622 function getTranscodedPath( $suffix = false ) {
1623 $this->assertRepoDefined();
1624
1625 return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1626 }
1627
1634 function getArchiveUrl( $suffix = false ) {
1635 $this->assertRepoDefined();
1636 $ext = $this->getExtension();
1637 $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1638 if ( $suffix === false ) {
1639 $path = substr( $path, 0, -1 );
1640 } else {
1641 $path .= rawurlencode( $suffix );
1642 }
1643
1644 return $path;
1645 }
1646
1654 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1655 $this->assertRepoDefined();
1656 $ext = $this->getExtension();
1657 $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1658 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1659 if ( $suffix === false ) {
1660 $path = substr( $path, 0, -1 );
1661 } else {
1662 $path .= rawurlencode( $suffix );
1663 }
1664
1665 return $path;
1666 }
1667
1675 function getZoneUrl( $zone, $suffix = false ) {
1676 $this->assertRepoDefined();
1677 $ext = $this->getExtension();
1678 $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1679 if ( $suffix !== false ) {
1680 $path .= '/' . rawurlencode( $suffix );
1681 }
1682
1683 return $path;
1684 }
1685
1692 function getThumbUrl( $suffix = false ) {
1693 return $this->getZoneUrl( 'thumb', $suffix );
1694 }
1695
1702 function getTranscodedUrl( $suffix = false ) {
1703 return $this->getZoneUrl( 'transcoded', $suffix );
1704 }
1705
1712 function getVirtualUrl( $suffix = false ) {
1713 $this->assertRepoDefined();
1714 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1715 if ( $suffix !== false ) {
1716 $path .= '/' . rawurlencode( $suffix );
1717 }
1718
1719 return $path;
1720 }
1721
1728 function getArchiveVirtualUrl( $suffix = false ) {
1729 $this->assertRepoDefined();
1730 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1731 if ( $suffix === false ) {
1732 $path = substr( $path, 0, -1 );
1733 } else {
1734 $path .= rawurlencode( $suffix );
1735 }
1736
1737 return $path;
1738 }
1739
1746 function getThumbVirtualUrl( $suffix = false ) {
1747 $this->assertRepoDefined();
1748 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1749 if ( $suffix !== false ) {
1750 $path .= '/' . rawurlencode( $suffix );
1751 }
1752
1753 return $path;
1754 }
1755
1759 function isHashed() {
1760 $this->assertRepoDefined();
1761
1762 return (bool)$this->repo->getHashLevels();
1763 }
1764
1768 function readOnlyError() {
1769 throw new MWException( static::class . ': write operations are not supported' );
1770 }
1771
1787 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1788 $watch = false, $timestamp = false, User $user = null
1789 ) {
1790 $this->readOnlyError();
1791 }
1792
1814 function publish( $src, $flags = 0, array $options = [] ) {
1815 $this->readOnlyError();
1816 }
1817
1822 function formatMetadata( $context = false ) {
1823 if ( !$this->getHandler() ) {
1824 return false;
1825 }
1826
1827 return $this->getHandler()->formatMetadata( $this, $context );
1828 }
1829
1835 function isLocal() {
1836 return $this->repo && $this->repo->isLocal();
1837 }
1838
1844 function getRepoName() {
1845 return $this->repo ? $this->repo->getName() : 'unknown';
1846 }
1847
1853 function getRepo() {
1854 return $this->repo;
1855 }
1856
1863 function isOld() {
1864 return false;
1865 }
1866
1874 function isDeleted( $field ) {
1875 return false;
1876 }
1877
1883 function getVisibility() {
1884 return 0;
1885 }
1886
1892 function wasDeleted() {
1893 $title = $this->getTitle();
1894
1895 return $title && $title->isDeletedQuick();
1896 }
1897
1910 function move( $target ) {
1911 $this->readOnlyError();
1912 }
1913
1929 function delete( $reason, $suppress = false, $user = null ) {
1930 $this->readOnlyError();
1931 }
1932
1947 function restore( $versions = [], $unsuppress = false ) {
1948 $this->readOnlyError();
1949 }
1950
1958 function isMultipage() {
1959 return $this->getHandler() && $this->handler->isMultiPage( $this );
1960 }
1961
1968 function pageCount() {
1969 if ( !isset( $this->pageCount ) ) {
1970 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1971 $this->pageCount = $this->handler->pageCount( $this );
1972 } else {
1973 $this->pageCount = false;
1974 }
1975 }
1976
1977 return $this->pageCount;
1978 }
1979
1989 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1990 // Exact integer multiply followed by division
1991 if ( $srcWidth == 0 ) {
1992 return 0;
1993 } else {
1994 return (int)round( $srcHeight * $dstWidth / $srcWidth );
1995 }
1996 }
1997
2008 function getImageSize( $filePath ) {
2009 if ( !$this->getHandler() ) {
2010 return false;
2011 }
2012
2013 return $this->getHandler()->getImageSize( $this, $filePath );
2014 }
2015
2023 if ( $this->repo ) {
2024 return $this->repo->getDescriptionUrl( $this->getName() );
2025 } else {
2026 return false;
2027 }
2028 }
2029
2036 function getDescriptionText( $lang = false ) {
2037 global $wgLang;
2038
2039 if ( !$this->repo || !$this->repo->fetchDescription ) {
2040 return false;
2041 }
2042
2043 $lang = $lang ?: $wgLang;
2044
2045 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2046 if ( $renderUrl ) {
2047 $cache = ObjectCache::getMainWANInstance();
2048 $key = $this->repo->getLocalCacheKey(
2049 'RemoteFileDescription',
2050 'url',
2051 $lang->getCode(),
2052 $this->getName()
2053 );
2054
2055 return $cache->getWithSetCallback(
2056 $key,
2057 $this->repo->descriptionCacheExpiry ?: $cache::TTL_UNCACHEABLE,
2058 function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl ) {
2059 wfDebug( "Fetching shared description from $renderUrl\n" );
2060 $res = Http::get( $renderUrl, [], __METHOD__ );
2061 if ( !$res ) {
2062 $ttl = WANObjectCache::TTL_UNCACHEABLE;
2063 }
2064
2065 return $res;
2066 }
2067 );
2068 }
2069
2070 return false;
2071 }
2072
2085 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2086 return null;
2087 }
2088
2094 function getTimestamp() {
2095 $this->assertRepoDefined();
2096
2097 return $this->repo->getFileTimestamp( $this->getPath() );
2098 }
2099
2107 public function getDescriptionTouched() {
2108 return false;
2109 }
2110
2116 function getSha1() {
2117 $this->assertRepoDefined();
2118
2119 return $this->repo->getFileSha1( $this->getPath() );
2120 }
2121
2127 function getStorageKey() {
2128 $hash = $this->getSha1();
2129 if ( !$hash ) {
2130 return false;
2131 }
2132 $ext = $this->getExtension();
2133 $dotExt = $ext === '' ? '' : ".$ext";
2134
2135 return $hash . $dotExt;
2136 }
2137
2146 function userCan( $field, User $user = null ) {
2147 return true;
2148 }
2149
2153 function getStreamHeaders() {
2154 wfDeprecated( __METHOD__, '1.30' );
2155 return $this->getContentHeaders();
2156 }
2157
2163 $handler = $this->getHandler();
2164 if ( $handler ) {
2165 $metadata = $this->getMetadata();
2166
2167 if ( is_string( $metadata ) ) {
2168 $metadata = MediaWiki\quietCall( 'unserialize', $metadata );
2169 }
2170
2171 if ( !is_array( $metadata ) ) {
2172 $metadata = [];
2173 }
2174
2175 return $handler->getContentHeaders( $metadata );
2176 }
2177
2178 return [];
2179 }
2180
2184 function getLongDesc() {
2185 $handler = $this->getHandler();
2186 if ( $handler ) {
2187 return $handler->getLongDesc( $this );
2188 } else {
2189 return MediaHandler::getGeneralLongDesc( $this );
2190 }
2191 }
2192
2196 function getShortDesc() {
2197 $handler = $this->getHandler();
2198 if ( $handler ) {
2199 return $handler->getShortDesc( $this );
2200 } else {
2201 return MediaHandler::getGeneralShortDesc( $this );
2202 }
2203 }
2204
2209 $handler = $this->getHandler();
2210 if ( $handler ) {
2211 return $handler->getDimensionsString( $this );
2212 } else {
2213 return '';
2214 }
2215 }
2216
2220 function getRedirected() {
2221 return $this->redirected;
2222 }
2223
2228 if ( $this->redirected ) {
2229 if ( !$this->redirectTitle ) {
2230 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
2231 }
2232
2233 return $this->redirectTitle;
2234 }
2235
2236 return null;
2237 }
2238
2243 function redirectedFrom( $from ) {
2244 $this->redirected = $from;
2245 }
2246
2250 function isMissing() {
2251 return false;
2252 }
2253
2258 public function isCacheable() {
2259 return true;
2260 }
2261
2266 protected function assertRepoDefined() {
2267 if ( !( $this->repo instanceof $this->repoClass ) ) {
2268 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2269 }
2270 }
2271
2276 protected function assertTitleDefined() {
2277 if ( !( $this->title instanceof Title ) ) {
2278 throw new MWException( "A Title object is not set for this File.\n" );
2279 }
2280 }
2281
2286 public function isExpensiveToThumbnail() {
2287 $handler = $this->getHandler();
2288 return $handler ? $handler->isExpensiveToThumbnail( $this ) : false;
2289 }
2290
2296 public function isTransformedLocally() {
2297 return true;
2298 }
2299}
unserialize( $serialized)
$wgIgnoreImageErrors
If set, inline scaled images will still produce "<img>" tags ready for output instead of showing an e...
$wgThumbnailBuckets
When defined, is an array of image widths used as buckets for thumbnail generation.
$wgThumbnailMinimumBucketDistance
When using thumbnail buckets as defined above, this sets the minimum distance to the bucket above the...
$wgResourceBasePath
The default 'remoteBasePath' value for instances of ResourceLoaderFileModule.
$wgThumbnailEpoch
If rendered thumbnail files are older than this timestamp, they will be rerendered on demand as if th...
$wgTrustedMediaFormats
list of trusted media-types and MIME types.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTempDir()
Tries to get the system directory for temporary files.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$starttime
Definition api.php:40
Class representing a non-directory file on the file system.
Definition FSFile.php:29
getPath()
Returns the file system path.
Definition FSFile.php:50
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
static makeContentDisposition( $type, $filename='')
Build a Content-Disposition header value per RFC 6266.
Base class for file repositories.
Definition FileRepo.php:37
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:51
getStorageKey()
Get the deletion archive key, "<sha1>.<ext>".
Definition File.php:2127
string $url
The URL corresponding to one of the four basic zones.
Definition File.php:117
getVisibility()
Return the deletion bitfield STUB.
Definition File.php:1883
isVectorized()
Return true if the file is vectorized.
Definition File.php:555
recordUpload( $oldver, $desc, $license='', $copyStatus='', $source='', $watch=false, $timestamp=false, User $user=null)
Record a file upload in the upload log and the image table STUB Overridden by LocalFile.
Definition File.php:1787
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition File.php:1947
isExpensiveToThumbnail()
True if creating thumbnails from the file is large or otherwise resource-intensive.
Definition File.php:2286
isLocal()
Returns true if the file comes from the local file repository.
Definition File.php:1835
getThumbRel( $suffix=false)
Get the path, relative to the thumbnail zone root, of the thumbnail directory or a particular file if...
Definition File.php:1540
getLastError()
Get last thumbnailing error.
Definition File.php:1399
getShortDesc()
Definition File.php:2196
generateAndSaveThumb( $tmpFile, $transformParams, $flags)
Generates a thumbnail according to the given parameters and saves it to storage.
Definition File.php:1118
MediaHandler $handler
Definition File.php:114
purgeDescription()
Purge the file description page, but don't go after pages using the file.
Definition File.php:1428
__construct( $title, $repo)
Call this constructor from child classes.
Definition File.php:166
getIsSafeFileUncached()
Uncached accessor.
Definition File.php:808
getArchivePath( $suffix=false)
Get the path of the archived file.
Definition File.php:1584
getBucketThumbName( $bucket)
Returns the name of the thumb for a given bucket.
Definition File.php:1320
FSFile bool $fsFile
False if undefined.
Definition File.php:111
const RENDER_NOW
Force rendering in the current process.
Definition File.php:59
getPath()
Return the storage path to the file.
Definition File.php:417
getThumbPath( $suffix=false)
Get the path of the thumbnail directory, or a particular file if $suffix is specified.
Definition File.php:1610
getThumbVirtualUrl( $suffix=false)
Get the virtual URL for a thumbnail file or directory.
Definition File.php:1746
getIsSafeFile()
Accessor for __get()
Definition File.php:799
redirectedFrom( $from)
Definition File.php:2243
getDescriptionTouched()
Returns the timestamp (in TS_MW format) of the last change of the description page.
Definition File.php:2107
transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags)
Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
Definition File.php:1014
array $tmpBucketedThumbCache
Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width.
Definition File.php:154
getMimeType()
Returns the MIME type of the file.
Definition File.php:707
getSize()
Return the size of the image file, in bytes Overridden by LocalFile, UnregisteredLocalFile STUB.
Definition File.php:696
string $extension
File extension.
Definition File.php:120
pageCount()
Returns the number of pages of a multipage document, or false for documents which aren't multipage do...
Definition File.php:1968
getMediaType()
Return the type of the media in the file.
Definition File.php:718
string $redirected
Main part of the title, with underscores (Title::getDBkey)
Definition File.php:105
getTranscodedUrl( $suffix=false)
Get the URL of the transcoded directory, or a particular file if $suffix is specified.
Definition File.php:1702
bool $isSafeFile
Whether this media file is in a format that is unlikely to contain viruses or malicious content.
Definition File.php:148
getRel()
Get the path of the file relative to the public zone root.
Definition File.php:1511
getLength()
Get the duration of a media file in seconds.
Definition File.php:541
static normalizeTitle( $title, $exception=false)
Given a string or Title object return either a valid Title object with namespace NS_FILE or null.
Definition File.php:184
getTimestamp()
Get the 14-character timestamp of the file upload.
Definition File.php:2094
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition File.php:2266
getName()
Return the name of this file.
Definition File.php:297
resetHistory()
Reset the history pointer to the first element of the history.
Definition File.php:1486
canAnimateThumbIfAppropriate()
Will the thumbnail be animated if one would expect it to be.
Definition File.php:610
getWidth( $page=1)
Return the width of the image.
Definition File.php:463
getLocalRefPath()
Get an FS copy or original of this file and return the path.
Definition File.php:433
exists()
Returns true if file exists in the repository.
Definition File.php:877
const DELETE_SOURCE
Definition File.php:66
getThumbUrl( $suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
Definition File.php:1692
Title $redirectedTitle
Definition File.php:108
allowInlineDisplay()
Alias for canRender()
Definition File.php:769
string false $pageCount
Number of pages of a multipage document, or false for documents which aren't multipage documents.
Definition File.php:134
mustRender()
Return true if the file is of a type that can't be directly rendered by typical browsers and needs to...
Definition File.php:760
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition File.php:1712
isTrustedFile()
Returns true if the file is flagged as trusted.
Definition File.php:852
getHistory( $limit=null, $start=null, $end=null, $inc=true)
Return a fragment of the history of file.
Definition File.php:1463
isCacheable()
Check if this file object is small and can be cached.
Definition File.php:2258
getTransformScript()
Definition File.php:894
isMissing()
Definition File.php:2250
isVisible()
Returns true if file exists in the repository and can be included in a page.
Definition File.php:887
iconThumb()
Get a ThumbnailImage representing a file type icon.
Definition File.php:1377
getRepo()
Returns the repository.
Definition File.php:1853
getZoneUrl( $zone, $suffix=false)
Get the URL of the zone directory, or a particular file if $suffix is specified.
Definition File.php:1675
getDimensionsString()
Definition File.php:2208
const DELETED_COMMENT
Definition File.php:54
upgradeRow()
Upgrade the database row if there is one Called by ImagePage STUB.
Definition File.php:263
convertMetadataVersion( $metadata, $version)
get versioned metadata
Definition File.php:667
const FOR_PUBLIC
Definition File.php:69
getCanRender()
Accessor for __get()
Definition File.php:746
getArchiveVirtualUrl( $suffix=false)
Get the public zone virtual URL for an archived version source file.
Definition File.php:1728
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition File.php:2276
getArchiveThumbPath( $archiveName, $suffix=false)
Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified.
Definition File.php:1597
getHeight( $page=1)
Return the height of the image.
Definition File.php:477
getThumbnailSource( $params)
Returns the most appropriate source image for the thumbnail, given a target thumbnail size.
Definition File.php:1242
getArchiveThumbRel( $archiveName, $suffix=false)
Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory or a speci...
Definition File.php:1567
getUser( $type='text')
Returns ID or name of user who uploaded the file STUB.
Definition File.php:532
makeTransformTmpFile( $thumbPath)
Creates a temp FS file with the same extension and the thumbnail.
Definition File.php:1329
getBitDepth()
Return the bit depth of the file Overridden by LocalFile STUB.
Definition File.php:686
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
Definition File.php:1814
isOld()
Returns true if the image is an old version STUB.
Definition File.php:1863
getContentHeaders()
Definition File.php:2162
getTitle()
Return the associated title object.
Definition File.php:326
getDescriptionShortUrl()
Get short description URL for a files based on the page ID.
Definition File.php:364
const DELETED_RESTRICTED
Definition File.php:56
canRender()
Checks if the output of transform() for this file is likely to be valid.
Definition File.php:734
getAvailableLanguages()
Gives a (possibly empty) list of languages to render the file in.
Definition File.php:575
getCommonMetaArray()
Like getMetadata but returns a handler independent array of common values.
Definition File.php:649
getOriginalTitle()
Return the title used to find this file.
Definition File.php:335
getRepoName()
Returns the name of the repository.
Definition File.php:1844
getDefaultRenderLanguage()
In files that support multiple language, what is the default language to use if none specified.
Definition File.php:591
readOnlyError()
Definition File.php:1768
migrateThumbFile( $thumbName)
Hook into transform() to allow migration of thumbnail files STUB Overridden by LocalFile.
Definition File.php:1355
static compare(File $a, File $b)
Callback for usort() to do file sorts by name.
Definition File.php:288
getCanonicalUrl()
Definition File.php:382
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition File.php:1958
isSafeFile()
Determines if this media file is in a format that is unlikely to contain viruses or malicious content...
Definition File.php:786
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile.
Definition File.php:1409
createThumb( $width, $height=-1)
Create a thumbnail of the image having the specified width/height.
Definition File.php:992
string $name
The name of a file from its title object.
Definition File.php:123
const RAW
Definition File.php:71
getTranscodedPath( $suffix=false)
Get the path of the transcoded directory, or a particular file if $suffix is specified.
Definition File.php:1622
load( $flags=0)
Load any lazy-loaded file object fields from source.
Definition File.php:867
getExtension()
Get the file extension, e.g.
Definition File.php:311
isHashed()
Definition File.php:1759
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition File.php:96
transform( $params, $flags=0)
Transform a media file.
Definition File.php:1034
getImageSize( $filePath)
Get an image size array like that returned by getImageSize(), or false if it can't be determined.
Definition File.php:2008
getStreamHeaders()
Definition File.php:2153
nextHistoryLine()
Return the history of this file, line by line.
Definition File.php:1476
purgeEverything()
Purge metadata and all affected pages when the file is created, deleted, or majorly updated.
Definition File.php:1440
const DELETED_FILE
Definition File.php:53
getRedirected()
Definition File.php:2220
getDescriptionText( $lang=false)
Get the HTML text of the description page, if available.
Definition File.php:2036
string $path
The storage path corresponding to one of the zones.
Definition File.php:126
static normalizeExtension( $extension)
Normalize a file extension to the common form, making it lowercase and checking some synonyms,...
Definition File.php:224
static splitMime( $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
Definition File.php:273
getUrl()
Return the URL of the file.
Definition File.php:348
Title string bool $title
Definition File.php:99
wasDeleted()
Was this file ever deleted from the wiki?
Definition File.php:1892
string $transformScript
URL of transformscript (for example thumb.php)
Definition File.php:137
string $repoClass
Required Repository class type.
Definition File.php:151
thumbName( $params, $flags=0)
Return the file name of a thumbnail with the specified parameters.
Definition File.php:938
const DELETED_USER
Definition File.php:55
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
Definition File.php:1634
getSha1()
Get the SHA-1 base 36 hash of the file.
Definition File.php:2116
getViewURL()
Definition File.php:389
formatMetadata( $context=false)
Definition File.php:1822
userCan( $field, User $user=null)
Determine if the current user is allowed to view a particular field of this file, if it's marked as d...
Definition File.php:2146
const THUMB_FULL_NAME
Definition File.php:74
Title $redirectTitle
Definition File.php:140
isTransformedLocally()
Whether the thumbnails created on the same server as this code is running.
Definition File.php:2296
getLongDesc()
Definition File.php:2184
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1364
getDescriptionUrl()
Get the URL of the image description page.
Definition File.php:2022
string $hashPath
Relative path including trailing slash.
Definition File.php:129
getBucketThumbPath( $bucket)
Returns the repo path of the thumb for a given bucket.
Definition File.php:1310
purgeCache( $options=[])
Purge shared caches such as thumbnails and DB data caching STUB Overridden by LocalFile.
Definition File.php:1420
getThumbnailBucket( $desiredWidth, $page=1)
Return the smallest bucket from $wgThumbnailBuckets which is at least $wgThumbnailMinimumBucketDistan...
Definition File.php:490
getUnscaledThumb( $handlerParams=[])
Get a ThumbnailImage which is the same size as the source.
Definition File.php:915
getArchiveRel( $suffix=false)
Get the path of an archived file relative to the public zone root.
Definition File.php:1522
getUrlRel()
Get urlencoded path of the file relative to the public zone root.
Definition File.php:1555
getThumbDisposition( $thumbName, $dispositionType='inline')
Definition File.php:1339
const FOR_THIS_USER
Definition File.php:70
move( $target)
Move file to the new title.
Definition File.php:1910
generateBucketsIfNeeded( $params, $flags=0)
Generates chained bucketed thumbnails if needed.
Definition File.php:1185
getRedirectedTitle()
Definition File.php:2227
__get( $name)
Definition File.php:205
static scaleHeight( $srcWidth, $srcHeight, $dstWidth)
Calculate the height of a thumbnail using the source and destination width.
Definition File.php:1989
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
Definition File.php:1874
getArchiveThumbUrl( $archiveName, $suffix=false)
Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified.
Definition File.php:1654
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
Get description of file revision STUB.
Definition File.php:2085
getMetadata()
Get handler-specific metadata Overridden by LocalFile, UnregisteredLocalFile STUB.
Definition File.php:639
generateThumbName( $name, $params)
Generate a thumbnail file name from a name and specified parameters.
Definition File.php:953
bool $canRender
Whether the output of transform() for this file is likely to be valid.
Definition File.php:143
getFullUrl()
Return a fully-qualified URL to the file.
Definition File.php:375
const RENDER_FORCE
Force rendering even if thumbnail already exist and using RENDER_NOW I.e.
Definition File.php:64
static checkExtensionCompatibility(File $old, $new)
Checks if file extensions are compatible.
Definition File.php:249
getHashPath()
Get the filename hash component of the directory including trailing slash, e.g.
Definition File.php:1496
string $lastError
Text of last error.
Definition File.php:102
A foreign repository with a remote MediaWiki with an API thingy.
Class to invalidate the HTML cache of all the pages linking to a given title.
A repository that stores files in the local filesystem and registers them in the wiki's own database.
Definition LocalRepo.php:35
MediaWiki exception.
Base media handler class.
normaliseParams( $image, &$params)
Changes the parameter array as necessary, ready for transformation.
canAnimateThumbnail( $file)
If the material is animated, we can animate the thumbnail.
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
static getGeneralLongDesc( $file)
Used instead of getLongDesc if there is no handler registered for file.
getDefaultRenderLanguage(File $file)
On file types that support renderings in multiple languages, which language is used by default if uns...
getLength( $file)
If its an audio file, return the length of the file.
getTransform( $image, $dstPath, $dstUrl, $params)
Get a MediaTransformOutput object representing the transformed output.
getDimensionsString( $file)
Shown in file history box on image description page.
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Get a MediaTransformOutput object representing the transformed output.
isAnimatedImage( $file)
The material is an image, and is animated.
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
convertMetadataVersion( $metadata, $version=1)
Convert metadata version.
static getGeneralShortDesc( $file)
Used instead of getShortDesc if there is no handler registered for file.
getLongDesc( $file)
Long description.
getScriptedTransform( $image, $script, $params)
Get a MediaTransformOutput object representing an alternate of the transformed output which will call...
isExpensiveToThumbnail( $file)
True if creating thumbnails from the file is large or otherwise resource-intensive.
getAvailableLanguages(File $file)
Get list of languages file can be viewed in.
getShortDesc( $file)
Short description.
getContentHeaders( $metadata)
Get useful response headers for GET/HEAD requests for a file with the given metadata.
Basic media transform error class.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static singleton()
Get an instance of this class.
Definition MimeMagic.php:33
Convenience class for dealing with PoolCounters using callbacks.
execute( $skipcache=false)
Get the result of the work (whatever it is), or the result of the error() function.
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
Media transform output for images.
Represents a title within MediaWiki.
Definition Title.php:39
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:51
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition design.txt:56
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array change it to the message you want to define you are encouraged to submit patches to MediaWiki s core to add new MIME types to mime types $mimeMagic
Definition hooks.txt:2265
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:1971
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2780
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves set to a MediaTransformOutput the error message to be returned in an array you should do so by altering $wgNamespaceProtection and $wgNamespaceContentModels outside the handler
Definition hooks.txt:928
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition hooks.txt:2805
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:1975
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1049
see documentation in includes Linker php for Linker::makeImageLink & $handlerParams
Definition hooks.txt:1776
$IP
Definition update.php:3
const PROTO_CANONICAL
Definition Defines.php:224
const NS_FILE
Definition Defines.php:71
const NS_MEDIA
Definition Defines.php:53
const PROTO_RELATIVE
Definition Defines.php:222
Interface for database access objects.
$cache
Definition mcc.php:33
const MEDIATYPE_UNKNOWN
Definition defines.php:26
$source
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition postgres.txt:36
if( $ext=='php'|| $ext=='php5') $mime
Definition router.php:59
$params
if(!isset( $args[0])) $lang