62 private const VERSION = 13;
64 private const CACHE_FIELD_MAX_LEN = 1000;
67 private const MDS_EMPTY =
'empty';
70 private const MDS_LEGACY =
'legacy';
73 private const MDS_PHP =
'php';
76 private const MDS_JSON =
'json';
79 private const MAX_PAGE_RENDER_JOBS = 50;
140 private $historyLine = 0;
143 private $historyRes =
null;
158 private $description;
161 private $descriptionTouched;
173 private $lockedOwnTrx;
179 private $metadataStorageHelper;
182 private const LOAD_ALL = 16;
184 private const ATOMIC_SECTION_LOCK =
'LocalFile::lockingTransaction';
218 $file->loadFromRow( $row );
237 $conds = [
'img_sha1' =>
$sha1 ];
239 $conds[
'img_timestamp'] =
$dbr->timestamp( $timestamp );
242 $fileQuery = static::getQueryInfo();
243 $row =
$dbr->selectRow(
244 $fileQuery[
'tables'], $fileQuery[
'fields'], $conds, __METHOD__, [], $fileQuery[
'joins']
247 return static::newFromRow( $row,
$repo );
273 $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin(
'img_description' );
277 'image_actor' =>
'actor'
278 ] + $commentQuery[
'tables'],
292 'img_user' =>
'image_actor.actor_user',
293 'img_user_text' =>
'image_actor.actor_name',
294 ] + $commentQuery[
'fields'],
296 'image_actor' => [
'JOIN',
'actor_id=img_actor' ]
297 ] + $commentQuery[
'joins'],
300 if ( in_array(
'omit-nonlazy', $options,
true ) ) {
304 if ( !in_array(
'omit-lazy', $options,
true ) ) {
307 $ret[
'fields'][] =
'img_metadata';
342 return $this->repo->getSharedCacheKey(
'file', sha1( $this->
getName() ) );
348 private function loadFromCache() {
349 $this->dataLoaded =
false;
350 $this->extraDataLoaded =
false;
359 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
360 $cachedValues = $cache->getWithSetCallback(
363 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
364 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
371 if ( $this->fileExists ) {
372 foreach ( $fields as $field ) {
373 $cacheVal[$field] = $this->$field;
377 $cacheVal[
'user'] = $this->user->getId();
378 $cacheVal[
'user_text'] = $this->user->getName();
382 if ( $this->metadataBlobs ) {
383 $cacheVal[
'metadata'] = array_diff_key(
384 $this->metadataArray, $this->metadataBlobs );
395 if ( isset( $cacheVal[$field] )
396 && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
398 unset( $cacheVal[$field] );
399 if ( $field ===
'metadata' ) {
400 unset( $cacheVal[
'metadataBlobs'] );
405 if ( $this->fileExists ) {
406 $ttl = $cache->adaptiveTTL( (
int)
wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
408 $ttl = $cache::TTL_DAY;
413 [
'version' => self::VERSION ]
416 $this->fileExists = $cachedValues[
'fileExists'];
417 if ( $this->fileExists ) {
421 $this->dataLoaded =
true;
422 $this->extraDataLoaded =
true;
424 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
437 $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
438 static function () use ( $key ) {
439 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
465 if ( $prefix !==
'' ) {
466 throw new InvalidArgumentException(
467 __METHOD__ .
' with a non-empty prefix is no longer supported.'
475 return [
'size',
'width',
'height',
'bits',
'media_type',
476 'major_mime',
'minor_mime',
'timestamp',
'sha1',
'description' ];
487 if ( $prefix !==
'' ) {
488 throw new InvalidArgumentException(
489 __METHOD__ .
' with a non-empty prefix is no longer supported.'
494 return [
'metadata' ];
503 $fname = static::class .
'::' . __FUNCTION__;
505 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
506 $this->dataLoaded =
true;
507 $this->extraDataLoaded =
true;
509 $dbr = ( $flags & self::READ_LATEST )
510 ? $this->repo->getPrimaryDB()
511 : $this->repo->getReplicaDB();
513 $fileQuery = static::getQueryInfo();
514 $row =
$dbr->selectRow(
515 $fileQuery[
'tables'],
516 $fileQuery[
'fields'],
517 [
'img_name' => $this->
getName() ],
526 $this->fileExists =
false;
536 if ( !$this->title ) {
540 $fname = static::class .
'::' . __FUNCTION__;
542 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
543 $this->extraDataLoaded =
true;
545 $db = $this->repo->getReplicaDB();
546 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
548 $db = $this->repo->getPrimaryDB();
549 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
553 if ( isset( $fieldMap[
'metadata'] ) ) {
557 throw new MWException(
"Could not find data for image '{$this->getName()}'." );
566 private function loadExtraFieldsWithTimestamp(
$dbr, $fname ) {
570 $row =
$dbr->selectRow(
571 $fileQuery[
'tables'],
572 $fileQuery[
'fields'],
574 'img_name' => $this->
getName(),
575 'img_timestamp' =>
$dbr->timestamp( $this->getTimestamp() ),
584 # File may have been uploaded over in the meantime; check the old versions
586 $row =
$dbr->selectRow(
587 $fileQuery[
'tables'],
588 $fileQuery[
'fields'],
591 'oi_timestamp' =>
$dbr->timestamp( $this->getTimestamp() ),
612 $array = (array)$row;
613 $prefixLength = strlen( $prefix );
616 if ( substr( array_key_first( $array ), 0, $prefixLength ) !== $prefix ) {
617 throw new MWException( __METHOD__ .
': incorrect $prefix parameter' );
621 foreach ( $array as
$name => $value ) {
622 $decoded[substr(
$name, $prefixLength )] = $value;
644 $this->dataLoaded =
true;
648 $this->name = $unprefixed[
'name'];
649 $this->media_type = $unprefixed[
'media_type'];
651 $services = MediaWikiServices::getInstance();
652 $this->description = $services->getCommentStore()
653 ->getComment(
"{$prefix}description", $row )->text;
655 $this->user = $services->getUserFactory()->newFromAnyId(
656 $unprefixed[
'user'] ??
null,
657 $unprefixed[
'user_text'] ??
null,
658 $unprefixed[
'actor'] ??
null
661 $this->timestamp =
wfTimestamp( TS_MW, $unprefixed[
'timestamp'] );
664 $this->repo->getReplicaDB(), $unprefixed[
'metadata'] );
666 if ( empty( $unprefixed[
'major_mime'] ) ) {
667 $this->major_mime =
'unknown';
668 $this->minor_mime =
'unknown';
669 $this->mime =
'unknown/unknown';
671 if ( !$unprefixed[
'minor_mime'] ) {
672 $unprefixed[
'minor_mime'] =
'unknown';
674 $this->major_mime = $unprefixed[
'major_mime'];
675 $this->minor_mime = $unprefixed[
'minor_mime'];
676 $this->mime = $unprefixed[
'major_mime'] .
'/' . $unprefixed[
'minor_mime'];
680 $this->sha1 = rtrim( $unprefixed[
'sha1'],
"\0" );
686 $this->size = +$unprefixed[
'size'];
687 $this->width = +$unprefixed[
'width'];
688 $this->height = +$unprefixed[
'height'];
689 $this->bits = +$unprefixed[
'bits'];
692 $extraFields = array_diff(
693 array_keys( $unprefixed ),
695 'name',
'media_type',
'description_text',
'description_data',
696 'description_cid',
'user',
'user_text',
'actor',
'timestamp',
697 'metadata',
'major_mime',
'minor_mime',
'sha1',
'size',
'width',
701 if ( $extraFields ) {
703 'Passing extra fields (' .
704 implode(
', ', $extraFields )
705 .
') to ' . __METHOD__ .
' was deprecated in MediaWiki 1.37. ' .
706 'Property assignment will be removed in a later version.',
708 foreach ( $extraFields as $field ) {
709 $this->$field = $unprefixed[$field];
713 $this->fileExists =
true;
721 public function load( $flags = 0 ) {
722 if ( !$this->dataLoaded ) {
723 if ( $flags & self::READ_LATEST ) {
726 $this->loadFromCache();
730 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
741 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() || $this->upgrading ) {
746 $reserialize =
false;
747 if ( $this->media_type ===
null || $this->mime ==
'image/svg' ) {
756 && $this->repo->isMetadataUpdateEnabled()
759 } elseif ( $this->repo->isJsonMetadataEnabled()
760 && $this->repo->isMetadataReserializeEnabled()
762 if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
764 } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
765 $this->metadataSerializationFormat !== self::MDS_JSON ) {
772 if ( $upgrade || $reserialize ) {
773 $this->upgrading =
true;
776 $this->upgrading =
false;
794 return $this->upgraded;
802 $dbw = $this->repo->getPrimaryDB();
806 $freshnessCondition = [
'img_timestamp' => $dbw->timestamp( $this->
getTimestamp() ) ];
810 # Don't destroy file info of missing files
811 if ( !$this->fileExists ) {
812 wfDebug( __METHOD__ .
": file does not exist, aborting" );
819 wfDebug( __METHOD__ .
': upgrading ' . $this->
getName() .
" to the current schema" );
821 $dbw->update(
'image',
823 'img_size' => $this->size,
824 'img_width' => $this->width,
825 'img_height' => $this->height,
826 'img_bits' => $this->bits,
827 'img_media_type' => $this->media_type,
828 'img_major_mime' => $major,
829 'img_minor_mime' => $minor,
831 'img_sha1' => $this->sha1,
834 [
'img_name' => $this->
getName() ],
842 $this->upgraded =
true;
850 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
853 $dbw = $this->repo->getPrimaryDB();
858 'img_name' => $this->name,
859 'img_timestamp' => $dbw->timestamp( $this->timestamp ),
863 $this->upgraded =
true;
878 $this->dataLoaded =
true;
880 $fields[] =
'fileExists';
882 foreach ( $fields as $field ) {
883 if ( isset( $info[$field] ) ) {
884 $this->$field = $info[$field];
889 if ( isset( $info[
'user'] ) &&
890 isset( $info[
'user_text'] ) &&
891 $info[
'user_text'] !==
''
897 if ( isset( $info[
'major_mime'] ) ) {
898 $this->mime =
"{$info['major_mime']}/{$info['minor_mime']}";
899 } elseif ( isset( $info[
'mime'] ) ) {
900 $this->mime = $info[
'mime'];
901 [ $this->major_mime, $this->minor_mime ] =
self::splitMime( $this->mime );
904 if ( isset( $info[
'metadata'] ) ) {
905 if ( is_string( $info[
'metadata'] ) ) {
907 } elseif ( is_array( $info[
'metadata'] ) ) {
908 $this->metadataArray = $info[
'metadata'];
909 if ( isset( $info[
'metadataBlobs'] ) ) {
910 $this->metadataBlobs = $info[
'metadataBlobs'];
911 $this->unloadedMetadataBlobs = array_diff_key(
912 $this->metadataBlobs,
916 $this->metadataBlobs = [];
917 $this->unloadedMetadataBlobs = [];
920 $logger = LoggerFactory::getInstance(
'LocalFile' );
921 $logger->warning( __METHOD__ .
' given invalid metadata of type ' .
922 gettype( $info[
'metadata'] ) );
923 $this->metadataArray = [];
925 $this->extraDataLoaded =
true;
945 if ( $this->missing ===
null ) {
950 return $this->missing;
975 return $dim[
'width'];
1008 return $dim[
'height'];
1027 if ( !$this->title ) {
1031 $pageId = $this->title->getArticleID();
1034 $url = $this->repo->makeUrl( [
'curid' => $pageId ] );
1035 if (
$url !==
false ) {
1052 } elseif ( array_keys( $data ) === [
'_error' ] ) {
1054 return $data[
'_error'];
1067 $this->
load( self::LOAD_ALL );
1068 if ( $this->unloadedMetadataBlobs ) {
1070 array_unique( array_merge(
1071 array_keys( $this->metadataArray ),
1072 array_keys( $this->unloadedMetadataBlobs )
1080 $this->load( self::LOAD_ALL );
1083 foreach ( $itemNames as $itemName ) {
1084 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1085 $result[$itemName] = $this->metadataArray[$itemName];
1086 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1087 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1092 $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
1093 foreach ( $addresses as $itemName => $address ) {
1094 unset( $this->unloadedMetadataBlobs[$itemName] );
1095 $value = $resultFromBlob[$itemName] ??
null;
1096 if ( $value !==
null ) {
1097 $result[$itemName] = $value;
1098 $this->metadataArray[$itemName] = $value;
1117 $this->load( self::LOAD_ALL );
1118 if ( !$this->metadataArray && !$this->metadataBlobs ) {
1120 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1121 $s = $this->getJsonMetadata();
1123 $s = serialize( $this->getMetadataArray() );
1125 if ( !is_string( $s ) ) {
1126 throw new MWException(
'Could not serialize image metadata value for DB' );
1137 private function getJsonMetadata() {
1140 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1144 if ( $this->metadataBlobs ) {
1145 $envelope[
'blobs'] = $this->metadataBlobs;
1148 [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
1151 $this->metadataBlobs += $blobAddresses;
1162 private function isMetadataOversize() {
1163 if ( !$this->repo->isSplitMetadataEnabled() ) {
1166 $threshold = $this->repo->getSplitMetadataThreshold();
1167 $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1168 foreach ( $directItems as $value ) {
1169 if ( strlen( $this->metadataStorageHelper->jsonEncode( $value ) ) > $threshold ) {
1185 $this->loadMetadataFromString( $db->
decodeBlob( $metadataBlob ) );
1196 $this->extraDataLoaded =
true;
1197 $this->metadataArray = [];
1198 $this->metadataBlobs = [];
1199 $this->unloadedMetadataBlobs = [];
1200 $metadataString = (string)$metadataString;
1201 if ( $metadataString ===
'' ) {
1202 $this->metadataSerializationFormat = self::MDS_EMPTY;
1205 if ( $metadataString[0] ===
'{' ) {
1206 $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
1209 $this->metadataArray = [
'_error' => $metadataString ];
1210 $this->metadataSerializationFormat = self::MDS_LEGACY;
1212 $this->metadataSerializationFormat = self::MDS_JSON;
1213 if ( isset( $envelope[
'data'] ) ) {
1214 $this->metadataArray = $envelope[
'data'];
1216 if ( isset( $envelope[
'blobs'] ) ) {
1217 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope[
'blobs'];
1222 $data = @unserialize( $metadataString );
1223 if ( !is_array( $data ) ) {
1225 $data = [
'_error' => $metadataString ];
1226 $this->metadataSerializationFormat = self::MDS_LEGACY;
1228 $this->metadataSerializationFormat = self::MDS_PHP;
1230 $this->metadataArray = $data;
1241 return (
int)$this->bits;
1275 return $this->media_type;
1292 return $this->fileExists;
1317 if ( $archiveName ) {
1318 $dir = $this->getArchiveThumbPath( $archiveName );
1320 $dir = $this->getThumbPath();
1323 $backend = $this->repo->getBackend();
1326 $iterator = $backend->getFileList( [
'dir' => $dir,
'forWrite' =>
true ] );
1327 if ( $iterator !==
null ) {
1328 foreach ( $iterator as
$file ) {
1341 private function purgeMetadataCache() {
1342 $this->invalidateCache();
1355 $this->maybeUpgradeRow();
1356 $this->purgeMetadataCache();
1359 $this->purgeThumbnails( $options );
1362 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1365 !empty( $options[
'forThumbRefresh'] )
1366 ? $hcu::PURGE_PRESEND
1367 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1378 $thumbs = $this->getThumbnails( $archiveName );
1381 $dir = array_shift( $thumbs );
1382 $this->purgeThumbList( $dir, $thumbs );
1385 foreach ( $thumbs as $thumb ) {
1386 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1390 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1393 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1394 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1404 $thumbs = $this->getThumbnails();
1407 $dir = array_shift( $thumbs );
1408 $this->purgeThumbList( $dir, $thumbs );
1412 foreach ( $thumbs as $thumb ) {
1413 $urls[] = $this->getThumbUrl( $thumb );
1417 if ( !empty( $options[
'forThumbRefresh'] ) ) {
1418 $handler = $this->getHandler();
1420 $handler->filterThumbnailPurgeList( $thumbs, $options );
1425 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this,
false, $urls );
1428 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1431 !empty( $options[
'forThumbRefresh'] )
1432 ? $hcu::PURGE_PRESEND
1433 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1444 $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1445 ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1449 $sizes = $uploadThumbnailRenderMap;
1452 foreach ( $sizes as $size ) {
1453 if ( $this->isMultipage() ) {
1456 $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1458 for ( $page = 1; $page <= $pageLimit; $page++ ) {
1461 [
'transformParams' => [
1467 } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1470 [
'transformParams' => [
'width' => $size ] ]
1476 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1487 $fileListDebug = strtr(
1488 var_export( $files,
true ),
1491 wfDebug( __METHOD__ .
": $fileListDebug" );
1493 if ( $this->repo->supportsSha1URLs() ) {
1494 $reference = $this->getSha1();
1496 $reference = $this->getName();
1500 foreach ( $files as
$file ) {
1501 # Check that the reference (filename or sha1) is part of the thumb name
1502 # This is a basic check to avoid erasing unrelated directories
1503 if ( str_contains(
$file, $reference )
1504 || str_contains(
$file,
"-thumbnail" )
1506 $purgeList[] =
"{$dir}/{$file}";
1510 # Delete the thumbnails
1511 $this->repo->quickPurgeBatch( $purgeList );
1512 # Clear out the thumbnail directory if empty
1513 $this->repo->quickCleanDir( $dir );
1527 public function getHistory( $limit =
null, $start =
null, $end =
null, $inc =
true ) {
1528 if ( !$this->exists() ) {
1532 $dbr = $this->repo->getReplicaDB();
1535 $tables = $oldFileQuery[
'tables'];
1536 $fields = $oldFileQuery[
'fields'];
1537 $join_conds = $oldFileQuery[
'joins'];
1538 $conds = $opts = [];
1539 $eq = $inc ?
'=' :
'';
1540 $conds[] =
"oi_name = " .
$dbr->addQuotes( $this->title->getDBkey() );
1543 $conds[] =
"oi_timestamp <$eq " .
$dbr->addQuotes(
$dbr->timestamp( $start ) );
1547 $conds[] =
"oi_timestamp >$eq " .
$dbr->addQuotes(
$dbr->timestamp( $end ) );
1551 $opts[
'LIMIT'] = $limit;
1555 $order = ( !$start && $end !== null ) ?
'ASC' :
'DESC';
1556 $opts[
'ORDER BY'] =
"oi_timestamp $order";
1557 $opts[
'USE INDEX'] = [
'oldimage' =>
'oi_name_timestamp' ];
1559 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1560 $conds, $opts, $join_conds );
1562 $res =
$dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1565 foreach (
$res as $row ) {
1566 $r[] = $this->repo->newFileFromRow( $row );
1569 if ( $order ==
'ASC' ) {
1570 $r = array_reverse( $r );
1587 if ( !$this->exists() ) {
1591 # Polymorphic function name to distinguish foreign and local fetches
1592 $fname = static::class .
'::' . __FUNCTION__;
1594 $dbr = $this->repo->getReplicaDB();
1596 if ( $this->historyLine == 0 ) {
1597 $fileQuery = self::getQueryInfo();
1598 $this->historyRes =
$dbr->select( $fileQuery[
'tables'],
1599 $fileQuery[
'fields'] + [
1600 'oi_archive_name' =>
$dbr->addQuotes(
'' ),
1603 [
'img_name' => $this->title->getDBkey() ],
1609 if ( $this->historyRes->numRows() == 0 ) {
1610 $this->historyRes =
null;
1614 } elseif ( $this->historyLine == 1 ) {
1616 $this->historyRes =
$dbr->select(
1617 $fileQuery[
'tables'],
1618 $fileQuery[
'fields'],
1619 [
'oi_name' => $this->title->getDBkey() ],
1621 [
'ORDER BY' =>
'oi_timestamp DESC' ],
1625 $this->historyLine++;
1627 return $this->historyRes->fetchObject();
1635 $this->historyLine = 0;
1637 if ( $this->historyRes !==
null ) {
1638 $this->historyRes =
null;
1675 public function upload( $src, $comment, $pageText, $flags = 0, $props =
false,
1676 $timestamp =
false,
Authority $uploader =
null, $tags = [],
1677 $createNullRevision =
true, $revert =
false
1679 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
1680 return $this->readOnlyFatalStatus();
1681 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1684 return $this->readOnlyFatalStatus();
1687 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1692 $props = $this->repo->getFileProps( $srcPath );
1694 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1695 $props = $mwProps->getPropsFromPath( $srcPath,
true );
1702 if ( is_string( $props[
'metadata'] ) ) {
1707 $metadata = @unserialize( $props[
'metadata'] );
1709 $metadata = $props[
'metadata'];
1712 if ( is_array( $metadata ) ) {
1713 $options[
'headers'] = $handler->getContentHeaders( $metadata );
1716 $options[
'headers'] = [];
1720 $comment = trim( $comment );
1722 $status = $this->publish( $src, $flags, $options );
1724 if ( $status->successCount >= 2 ) {
1731 $oldver = $status->value;
1733 $uploadStatus = $this->recordUpload3(
1741 $createNullRevision,
1744 if ( !$uploadStatus->isOK() ) {
1745 if ( $uploadStatus->hasMessage(
'filenotfound' ) ) {
1747 $status->fatal(
'filenotfound', $srcPath );
1749 $status->merge( $uploadStatus );
1781 bool $createNullRevision =
true,
1782 bool $revert =
false
1784 $dbw = $this->repo->getPrimaryDB();
1786 # Imports or such might force a certain timestamp; otherwise we generate
1787 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1788 if ( $timestamp ===
false ) {
1789 $timestamp = $dbw->timestamp();
1790 $allowTimeKludge =
true;
1792 $allowTimeKludge =
false;
1795 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1796 $props[
'description'] = $comment;
1797 $props[
'timestamp'] =
wfTimestamp( TS_MW, $timestamp );
1798 $this->setProps( $props );
1800 # Fail now if the file isn't there
1801 if ( !$this->fileExists ) {
1802 wfDebug( __METHOD__ .
": File " . $this->getRel() .
" went missing!" );
1807 $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1809 $dbw->startAtomic( __METHOD__ );
1811 $actorId = $actorNormalizaton->acquireActorId( $performer->
getUser(), $dbw );
1812 $this->user = $performer->
getUser();
1814 # Test to see if the row exists using INSERT IGNORE
1815 # This avoids race conditions by locking the row until the commit, and also
1816 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1817 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1818 $commentFields = $commentStore->insert( $dbw,
'img_description', $comment );
1819 $actorFields = [
'img_actor' => $actorId ];
1820 $dbw->insert(
'image',
1822 'img_name' => $this->getName(),
1823 'img_size' => $this->size,
1824 'img_width' => intval( $this->width ),
1825 'img_height' => intval( $this->height ),
1826 'img_bits' => $this->bits,
1827 'img_media_type' => $this->media_type,
1828 'img_major_mime' => $this->major_mime,
1829 'img_minor_mime' => $this->minor_mime,
1830 'img_timestamp' => $dbw->timestamp( $timestamp ),
1831 'img_metadata' => $this->getMetadataForDb( $dbw ),
1832 'img_sha1' => $this->sha1
1833 ] + $commentFields + $actorFields,
1837 $reupload = ( $dbw->affectedRows() == 0 );
1840 $row = $dbw->selectRow(
1842 [
'img_timestamp',
'img_sha1' ],
1843 [
'img_name' => $this->getName() ],
1845 [
'LOCK IN SHARE MODE' ]
1848 if ( $row && $row->img_sha1 === $this->sha1 ) {
1849 $dbw->endAtomic( __METHOD__ );
1850 wfDebug( __METHOD__ .
": File " . $this->getRel() .
" already exists!" );
1855 if ( $allowTimeKludge ) {
1856 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1857 $lUnixtime = $row ? (int)
wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1858 # Avoid a timestamp that is not newer than the last version
1859 # TODO: the image/oldimage tables should be like page/revision with an ID field
1860 if ( $lUnixtime && (
int)
wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1862 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1863 $this->timestamp =
wfTimestamp( TS_MW, $timestamp );
1867 $tables = [
'image' ];
1869 'oi_name' =>
'img_name',
1870 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1871 'oi_size' =>
'img_size',
1872 'oi_width' =>
'img_width',
1873 'oi_height' =>
'img_height',
1874 'oi_bits' =>
'img_bits',
1875 'oi_description_id' =>
'img_description_id',
1876 'oi_timestamp' =>
'img_timestamp',
1877 'oi_metadata' =>
'img_metadata',
1878 'oi_media_type' =>
'img_media_type',
1879 'oi_major_mime' =>
'img_major_mime',
1880 'oi_minor_mime' =>
'img_minor_mime',
1881 'oi_sha1' =>
'img_sha1',
1882 'oi_actor' =>
'img_actor',
1886 # (T36993) Note: $oldver can be empty here, if the previous
1887 # version of the file was broken. Allow registration of the new
1888 # version to continue anyway, because that's better than having
1889 # an image that's not fixable by user operations.
1890 # Collision, this is an update of a file
1891 # Insert previous contents into oldimage
1892 $dbw->insertSelect(
'oldimage', $tables, $fields,
1893 [
'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1895 # Update the current image row
1896 $dbw->update(
'image',
1898 'img_size' => $this->size,
1899 'img_width' => intval( $this->width ),
1900 'img_height' => intval( $this->height ),
1901 'img_bits' => $this->bits,
1902 'img_media_type' => $this->media_type,
1903 'img_major_mime' => $this->major_mime,
1904 'img_minor_mime' => $this->minor_mime,
1905 'img_timestamp' => $dbw->timestamp( $timestamp ),
1906 'img_metadata' => $this->getMetadataForDb( $dbw ),
1907 'img_sha1' => $this->sha1
1908 ] + $commentFields + $actorFields,
1909 [
'img_name' => $this->getName() ],
1915 $descId = $descTitle->getArticleID();
1916 $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
1918 throw new MWException(
'Cannot instance WikiFilePage for ' . $this->getName()
1919 .
', got instance of ' . get_class( $wikiPage ) );
1921 $wikiPage->setFile( $this );
1925 $logAction =
'revert';
1926 } elseif ( $reupload ) {
1927 $logAction =
'overwrite';
1929 $logAction =
'upload';
1933 $logEntry->setTimestamp( $this->timestamp );
1934 $logEntry->setPerformer( $performer->
getUser() );
1935 $logEntry->setComment( $comment );
1936 $logEntry->setTarget( $descTitle );
1939 $logEntry->setParameters(
1941 'img_sha1' => $this->sha1,
1942 'img_timestamp' => $timestamp,
1951 $logId = $logEntry->insert();
1953 if ( $descTitle->exists() ) {
1954 if ( $createNullRevision ) {
1955 $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1959 $editSummary = $formatter->getPlainActionText();
1960 $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1961 $nullRevRecord =
$revStore->newNullRevision(
1969 if ( $nullRevRecord ) {
1970 $inserted =
$revStore->insertRevisionOn( $nullRevRecord, $dbw );
1972 $this->getHookRunner()->onRevisionFromEditComplete(
1975 $inserted->getParentId(),
1980 $wikiPage->updateRevisionOn( $dbw, $inserted );
1982 $logEntry->setAssociatedRevId( $inserted->getId() );
1986 $newPageContent =
null;
1995 $dbw->endAtomic( __METHOD__ );
1996 $fname = __METHOD__;
1998 # Do some cache purges after final commit so that:
1999 # a) Changes are more likely to be seen post-purge
2000 # b) They won't cause rollback of the log publish/update above
2005 $reupload, $wikiPage, $newPageContent, $comment, $performer,
2006 $logEntry, $logId, $descId, $tags, $fname
2008 # Update memcache after the commit
2009 $this->invalidateCache();
2011 $updateLogPage =
false;
2012 if ( $newPageContent ) {
2013 # New file page; create the description page.
2014 # There's already a log entry, so don't make a second RC entry
2015 # CDN and file cache for the description page are purged by doUserEditContent.
2016 $status = $wikiPage->doUserEditContent(
2023 $revRecord = $status->getNewRevision();
2026 $logEntry->setAssociatedRevId( $revRecord->getId() );
2030 $updateLogPage = $revRecord->getPageId();
2033 # Existing file page: invalidate description page cache
2034 $title = $wikiPage->getTitle();
2035 $title->invalidateCache();
2036 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2037 $hcu->purgeTitleUrls(
$title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2038 # Allow the new file version to be patrolled from the page footer
2042 # Update associated rev id. This should be done by $logEntry->insert() earlier,
2043 # but setAssociatedRevId() wasn't called at that point yet...
2044 $logParams = $logEntry->getParameters();
2045 $logParams[
'associated_rev_id'] = $logEntry->getAssociatedRevId();
2047 if ( $updateLogPage ) {
2048 # Also log page, in case where we just created it above
2049 $update[
'log_page'] = $updateLogPage;
2051 $this->getRepo()->getPrimaryDB()->update(
2054 [
'log_id' => $logId ],
2057 $this->getRepo()->getPrimaryDB()->insert(
2060 'ls_field' =>
'associated_rev_id',
2061 'ls_value' => (
string)$logEntry->getAssociatedRevId(),
2062 'ls_log_id' => $logId,
2067 # Add change tags, if any
2069 $logEntry->addTags( $tags );
2072 # Uploads can be patrolled
2073 $logEntry->setIsPatrollable(
true );
2075 # Now that the log entry is up-to-date, make an RC entry.
2076 $logEntry->publish( $logId );
2078 # Run hook for other updates (typically more cache purging)
2079 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2082 # Delete old thumbnails
2083 $this->purgeThumbnails();
2084 # Remove the old file from the CDN cache
2085 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2086 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2088 # Update backlink pages pointing to this title if created
2089 $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2090 LinksUpdate::queueRecursiveJobsForTable(
2094 $performer->
getUser()->getName(),
2095 $blcFactory->getBacklinkCache( $this->getTitle() )
2099 $this->prerenderThumbnails();
2103 # Invalidate cache for all pages using this file
2107 [
'causeAction' =>
'file-upload',
'causeAgent' => $performer->
getUser()->getName() ]
2115 $dbw->onTransactionCommitOrIdle(
static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2123 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2145 public function publish( $src, $flags = 0, array $options = [] ) {
2146 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2165 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2166 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
2168 $repo = $this->getRepo();
2169 if ( $repo->getReadOnlyReason() !==
false ) {
2170 return $this->readOnlyFatalStatus();
2173 $status = $this->acquireFileLock();
2174 if ( !$status->isOK() ) {
2178 if ( $this->isOld() ) {
2179 $archiveRel = $dstRel;
2180 $archiveName = basename( $archiveRel );
2182 $archiveName =
wfTimestamp( TS_MW ) .
'!' . $this->getName();
2183 $archiveRel = $this->getArchiveRel( $archiveName );
2186 if ( $repo->hasSha1Storage() ) {
2188 ? $repo->getFileSha1( $srcPath )
2191 $wrapperBackend = $repo->getBackend();
2192 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2193 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2194 $status = $repo->quickImport( $src, $dst );
2199 if ( $this->exists() ) {
2200 $status->value = $archiveName;
2204 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2206 if ( $status->value ==
'new' ) {
2207 $status->value =
'';
2209 $status->value = $archiveName;
2213 $this->releaseFileLock();
2236 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2237 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2238 return $this->readOnlyFatalStatus();
2241 wfDebugLog(
'imagemove',
"Got request to move {$this->name} to " . $target->getText() );
2244 $status = $batch->addCurrent();
2245 if ( !$status->isOK() ) {
2248 $archiveNames = $batch->addOlds();
2249 $status = $batch->execute();
2251 wfDebugLog(
'imagemove',
"Finished moving {$this->name}" );
2254 $oldTitleFile = $localRepo->newFile( $this->title );
2255 $newTitleFile = $localRepo->newFile( $target );
2258 $this->getRepo()->getPrimaryDB(),
2260 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2261 $oldTitleFile->purgeEverything();
2262 foreach ( $archiveNames as $archiveName ) {
2264 '@phan-var OldLocalFile $oldTitleFile';
2265 $oldTitleFile->purgeOldThumbnails( $archiveName );
2267 $newTitleFile->purgeEverything();
2270 DeferredUpdates::PRESEND
2273 if ( $status->isOK() ) {
2275 $this->title = $target;
2278 $this->hashPath =
null;
2301 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2302 return $this->readOnlyFatalStatus();
2307 $batch->addCurrent();
2309 $archiveNames = $batch->addOlds();
2310 $status = $batch->execute();
2312 if ( $status->isOK() ) {
2319 $this->getRepo()->getPrimaryDB(),
2321 function () use ( $archiveNames ) {
2322 $this->purgeEverything();
2323 foreach ( $archiveNames as $archiveName ) {
2324 $this->purgeOldThumbnails( $archiveName );
2328 DeferredUpdates::PRESEND
2333 foreach ( $archiveNames as $archiveName ) {
2334 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2337 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2338 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2362 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2363 return $this->readOnlyFatalStatus();
2368 $batch->addOld( $archiveName );
2369 $status = $batch->execute();
2371 $this->purgeOldThumbnails( $archiveName );
2372 if ( $status->isOK() ) {
2373 $this->purgeDescription();
2376 $url = $this->getArchiveUrl( $archiveName );
2377 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2378 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2395 public function restore( $versions = [], $unsuppress =
false ) {
2396 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2397 return $this->readOnlyFatalStatus();
2405 $batch->addIds( $versions );
2407 $status = $batch->execute();
2408 if ( $status->isGood() ) {
2409 $cleanupStatus = $batch->cleanup();
2410 $cleanupStatus->successCount = 0;
2411 $cleanupStatus->failCount = 0;
2412 $status->merge( $cleanupStatus );
2430 return $this->title ? $this->title->getLocalURL() :
false;
2443 if ( !$this->title ) {
2447 $services = MediaWikiServices::getInstance();
2448 $page = $services->getPageStore()->getPageByReference( $this->
getTitle() );
2462 $parseStatus = $services->getParserOutputAccess()
2463 ->getParserOutput( $page, $parserOptions );
2465 if ( !$parseStatus->isGood() ) {
2469 return $parseStatus->getValue()->getText();
2481 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2483 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2498 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2500 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2503 return $this->description;
2514 return $this->timestamp;
2522 if ( !$this->exists() ) {
2529 if ( $this->descriptionTouched ===
null ) {
2531 'page_namespace' => $this->title->getNamespace(),
2532 'page_title' => $this->title->getDBkey()
2534 $touched = $this->repo->getReplicaDB()->selectField(
'page',
'page_touched', $cond, __METHOD__ );
2535 $this->descriptionTouched = $touched ?
wfTimestamp( TS_MW, $touched ) :
false;
2538 return $this->descriptionTouched;
2557 return $this->extraDataLoaded
2558 && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2570 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2582 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2598 if ( !$this->locked ) {
2599 $logger = LoggerFactory::getInstance(
'LocalFile' );
2601 $dbw = $this->repo->getPrimaryDB();
2602 $makesTransaction = !$dbw->trxLevel();
2603 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2607 $status = $this->acquireFileLock( 10 );
2608 if ( !$status->isGood() ) {
2609 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2610 $logger->warning(
"Failed to lock '{file}'", [
'file' => $this->name ] );
2616 $dbw->onTransactionResolution(
2617 function () use ( $logger ) {
2618 $status = $this->releaseFileLock();
2619 if ( !$status->isGood() ) {
2620 $logger->error(
"Failed to unlock '{file}'", [
'file' => $this->name ] );
2626 $this->lockedOwnTrx = $makesTransaction;
2631 return $this->lockedOwnTrx;
2645 if ( $this->locked ) {
2647 if ( !$this->locked ) {
2648 $dbw = $this->repo->getPrimaryDB();
2649 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2650 $this->lockedOwnTrx =
false;
2659 return $this->getRepo()->newFatal(
'filereadonlyerror', $this->getName(),
2660 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Deferrable Update for closure/callback updates that should use auto-commit mode.
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add an update to the pending update queue that invokes the specified callback when run.
Class representing a non-directory file on the file system.
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
File backend exception for checked exceptions (e.g.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Implements some public methods and some protected utility functions which are required by multiple ch...
string $url
The URL corresponding to one of the four basic zones.
static splitMime(?string $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
getName()
Return the name of this file.
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
assertTitleDefined()
Assert that $this->title is set to a Title.
FileRepo LocalRepo ForeignAPIRepo false $repo
Some member variables can be lazy-initialised using __get().
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Title string false $title
string $path
The storage path corresponding to one of the zones.
getHandler()
Get a MediaHandler instance for this file.
string null $name
The name of a file from its title object.
static newForBacklinks(PageReference $page, $table, $params=[])
Base class for language-specific code.
Helper class for file deletion.
Helper class for file movement.
Helper class for file undeletion.
Local file in the wiki's own database.
exists()
canRender inherited
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
maybeUpgradeRow()
Upgrade a row if it needs it.
static newFromKey( $sha1, $repo, $timestamp=false)
Create a LocalFile from a SHA-1 key Do not call this except from inside a repo class.
array $metadataArray
Unserialized metadata.
getMediaType()
Returns the type of the media in the file.
string[] $unloadedMetadataBlobs
Map of metadata item name to blob address for items that exist but have not yet been loaded into $thi...
deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress=false)
Delete an old version of the file.
move( $target)
getLinksTo inherited
lock()
Start an atomic DB section and lock the image for update or increments a reference counter if the loc...
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
getCacheKey()
Get the memcached key for the main data for this file, or false if there is no access to the shared c...
getWidth( $page=1)
Return the width of the image @stable to override.
__destruct()
Clean up any dangling locks.
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
reserializeMetadata()
Write the metadata back to the database with the current serialization format.
isMissing()
splitMime inherited
getDescriptionUrl()
isMultipage inherited
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
releaseFileLock()
Release a lock acquired with acquireFileLock().
getUploader(int $audience=self::FOR_PUBLIC, Authority $performer=null)
loadMetadataFromDbFieldValue(IDatabase $db, $metadataBlob)
Unserialize a metadata blob which came from the database and store it in $this.
loadFromDB( $flags=0)
Load file metadata from the DB.
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
loadMetadataFromString( $metadataString)
Unserialize a metadata string which came from some non-DB source, or is the return value of IDatabase...
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
deleteFile( $reason, UserIdentity $user, $suppress=false)
Delete all versions of the file.
acquireFileLock( $timeout=0)
Acquire an exclusive lock on the file, indicating an intention to write to the file backend.
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
loadFromFile( $path=null)
Load metadata from the file itself.
getBitDepth()
@stable to override
string null $metadataSerializationFormat
One of the MDS_* constants, giving the format of the metadata as stored in the DB,...
int $size
Size in bytes (loadFromXxx)
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
getThumbnails( $archiveName=false)
getTransformScript inherited
static newFromTitle( $title, $repo, $unused=null)
Create a LocalFile from a title Do not call this except from inside a repo class.
getMetadataForDb(IDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
getLazyCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache, only when they're not too...
getSize()
Returns the size of the image file, in bytes @stable to override.
invalidateCache()
Purge the file object/metadata cache.
getMimeType()
Returns the MIME type of the file.
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
string $sha1
SHA-1 base 36 content hash.
getDescription( $audience=self::FOR_PUBLIC, Authority $performer=null)
getHeight( $page=1)
Return the height of the image @stable to override.
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
resetHistory()
Reset the history pointer to the first element of the history.
unprefixRow( $row, $prefix='img_')
static newFromRow( $row, $repo)
Create a LocalFile from a title Do not call this except from inside a repo class.
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
int $bits
Returned by getimagesize (loadFromXxx)
getMetadataItems(array $itemNames)
Get multiple elements of the unserialized handler-specific metadata.
getDescriptionText(Language $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files,...
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
loadExtraFromDB()
Load lazy file metadata from the DB.
nextHistoryLine()
Returns the history of this file, line by line.
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
int $deleted
Bitfield akin to rev_deleted.
getMetadata()
Get handler-specific metadata as a serialized string.
getMetadataArray()
Get unserialized handler-specific metadata.
__construct( $title, $repo)
Do not call this except from inside a repo class.
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
bool $fileExists
Does the file exist on disk? (loadFromXxx)
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, Authority $uploader=null, $tags=[], $createNullRevision=true, $revert=false)
getHashPath inherited
recordUpload3(string $oldver, string $comment, string $pageText, Authority $performer, $props=false, $timestamp=false, $tags=[], bool $createNullRevision=true, bool $revert=false)
Record a file upload in the upload log and the image table (version 3)
string[] $metadataBlobs
Map of metadata item name to blob address.
static makeParamBlob( $params)
Create a blob from a parameter array.
MimeMagic helper wrapper.
Class for creating new log entries and inserting them into the database.
A class containing constants representing the names of configuration variables.
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new oldlocalfile object.
static newFromUserAndLang(UserIdentity $user, Language $lang)
Get a ParserOptions object from a given user and language.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
static getMain()
Get the RequestContext object associated with the main request.
static factory(array $deltas)
static newFatal( $message,... $parameters)
Factory function for fatal errors.
static newGood( $value=null)
Factory function for good results.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Job for asynchronous rendering of thumbnails, e.g.
Special handling for representing file pages.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!isset( $args[0])) $lang