68 private const VERSION = 13;
70 private const CACHE_FIELD_MAX_LEN = 1000;
73 private const MDS_EMPTY =
'empty';
76 private const MDS_LEGACY =
'legacy';
79 private const MDS_PHP =
'php';
82 private const MDS_JSON =
'json';
85 private const MAX_PAGE_RENDER_JOBS = 50;
109 protected $metadataArray = [];
120 protected $metadataBlobs = [];
128 protected $unloadedMetadataBlobs = [];
134 protected $dataLoaded =
false;
137 protected $extraDataLoaded =
false;
143 protected $repoClass = LocalRepo::class;
146 private $historyLine = 0;
149 private $historyRes =
null;
164 private $description;
167 private $descriptionTouched;
179 private $lockedOwnTrx;
185 private $metadataStorageHelper;
188 private const LOAD_ALL = 16;
190 private const ATOMIC_SECTION_LOCK =
'LocalFile::lockingTransaction';
224 $file->loadFromRow( $row );
240 public static function newFromKey( $sha1, $repo, $timestamp =
false ) {
241 $dbr =
$repo->getReplicaDB();
242 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
244 $queryBuilder->where( [
'img_sha1' => $sha1 ] );
247 $queryBuilder->andWhere( [
'img_timestamp' => $dbr->
timestamp( $timestamp ) ] );
250 $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
252 return static::newFromRow( $row,
$repo );
279 $dbr = MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->getReplicaDatabase();
280 $queryInfo = FileSelectQueryBuilder::newForFile( $dbr, $options )->getQueryInfo();
283 'tables' => $queryInfo[
'tables'],
284 'fields' => $queryInfo[
'fields'],
285 'joins' => $queryInfo[
'join_conds'],
318 return $this->repo->getSharedCacheKey(
'file', sha1( $this->
getName() ) );
324 private function loadFromCache() {
325 $this->dataLoaded =
false;
326 $this->extraDataLoaded =
false;
328 $key = $this->getCacheKey();
330 $this->loadFromDB( self::READ_NORMAL );
335 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
336 $cachedValues = $cache->getWithSetCallback(
339 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
340 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
346 $cacheVal[
'fileExists'] = $this->fileExists;
347 if ( $this->fileExists ) {
348 foreach ( $fields as $field ) {
349 $cacheVal[$field] = $this->$field;
353 $cacheVal[
'user'] = $this->user->getId();
354 $cacheVal[
'user_text'] = $this->user->getName();
358 if ( $this->metadataBlobs ) {
359 $cacheVal[
'metadata'] = array_diff_key(
360 $this->metadataArray, $this->metadataBlobs );
362 $cacheVal[
'metadataBlobs'] = $this->metadataBlobs;
364 $cacheVal[
'metadata'] = $this->metadataArray;
371 if ( isset( $cacheVal[$field] )
372 && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
374 unset( $cacheVal[$field] );
375 if ( $field ===
'metadata' ) {
376 unset( $cacheVal[
'metadataBlobs'] );
381 if ( $this->fileExists ) {
382 $ttl = $cache->adaptiveTTL( (
int)
wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
384 $ttl = $cache::TTL_DAY;
389 [
'version' => self::VERSION ]
392 $this->fileExists = $cachedValues[
'fileExists'];
393 if ( $this->fileExists ) {
397 $this->dataLoaded =
true;
398 $this->extraDataLoaded =
true;
400 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
413 $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
414 static function () use ( $key ) {
415 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
441 if ( $prefix !==
'' ) {
442 throw new InvalidArgumentException(
443 __METHOD__ .
' with a non-empty prefix is no longer supported.'
451 return [
'size',
'width',
'height',
'bits',
'media_type',
452 'major_mime',
'minor_mime',
'timestamp',
'sha1',
'description' ];
463 if ( $prefix !==
'' ) {
464 throw new InvalidArgumentException(
465 __METHOD__ .
' with a non-empty prefix is no longer supported.'
470 return [
'metadata' ];
479 $fname = static::class .
'::' . __FUNCTION__;
481 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
482 $this->dataLoaded =
true;
483 $this->extraDataLoaded =
true;
485 $dbr = ( $flags & self::READ_LATEST )
486 ? $this->repo->getPrimaryDB()
487 : $this->repo->getReplicaDB();
488 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
490 $queryBuilder->where( [
'img_name' => $this->
getName() ] );
491 $row = $queryBuilder->caller( $fname )->fetchRow();
496 $this->fileExists =
false;
506 if ( !$this->title ) {
510 $fname = static::class .
'::' . __FUNCTION__;
512 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
513 $this->extraDataLoaded =
true;
515 $db = $this->repo->getReplicaDB();
516 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
518 $db = $this->repo->getPrimaryDB();
519 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
523 if ( isset( $fieldMap[
'metadata'] ) ) {
527 throw new MWException(
"Could not find data for image '{$this->getName()}'." );
536 private function loadExtraFieldsWithTimestamp(
IReadableDatabase $dbr, $fname ) {
539 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr, [
'omit-nonlazy' ] );
540 $queryBuilder->where( [
'img_name' => $this->getName() ] )
541 ->andWhere( [
'img_timestamp' => $dbr->
timestamp( $this->getTimestamp() ) ] );
542 $row = $queryBuilder->caller( $fname )->fetchRow();
544 $fieldMap = $this->unprefixRow( $row,
'img_' );
546 # File may have been uploaded over in the meantime; check the old versions
547 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr, [
'omit-nonlazy' ] );
548 $row = $queryBuilder->where( [
'oi_name' => $this->
getName() ] )
549 ->andWhere( [
'oi_timestamp' => $dbr->
timestamp( $this->getTimestamp() ) ] )
550 ->caller( __METHOD__ )->fetchRow();
566 $array = (array)$row;
567 $prefixLength = strlen( $prefix );
570 if ( substr( array_key_first( $array ), 0, $prefixLength ) !== $prefix ) {
571 throw new MWException( __METHOD__ .
': incorrect $prefix parameter' );
575 foreach ( $array as
$name => $value ) {
576 $decoded[substr(
$name, $prefixLength )] = $value;
598 $this->dataLoaded =
true;
602 $this->name = $unprefixed[
'name'];
603 $this->media_type = $unprefixed[
'media_type'];
605 $services = MediaWikiServices::getInstance();
606 $this->description = $services->getCommentStore()
607 ->getComment(
"{$prefix}description", $row )->text;
609 $this->user = $services->getUserFactory()->newFromAnyId(
610 $unprefixed[
'user'] ??
null,
611 $unprefixed[
'user_text'] ??
null,
612 $unprefixed[
'actor'] ??
null
615 $this->timestamp =
wfTimestamp( TS_MW, $unprefixed[
'timestamp'] );
618 $this->repo->getReplicaDB(), $unprefixed[
'metadata'] );
620 if ( empty( $unprefixed[
'major_mime'] ) ) {
621 $this->major_mime =
'unknown';
622 $this->minor_mime =
'unknown';
623 $this->mime =
'unknown/unknown';
625 if ( !$unprefixed[
'minor_mime'] ) {
626 $unprefixed[
'minor_mime'] =
'unknown';
628 $this->major_mime = $unprefixed[
'major_mime'];
629 $this->minor_mime = $unprefixed[
'minor_mime'];
630 $this->mime = $unprefixed[
'major_mime'] .
'/' . $unprefixed[
'minor_mime'];
634 $this->sha1 = rtrim( $unprefixed[
'sha1'],
"\0" );
640 $this->size = +$unprefixed[
'size'];
641 $this->width = +$unprefixed[
'width'];
642 $this->height = +$unprefixed[
'height'];
643 $this->bits = +$unprefixed[
'bits'];
646 $extraFields = array_diff(
647 array_keys( $unprefixed ),
649 'name',
'media_type',
'description_text',
'description_data',
650 'description_cid',
'user',
'user_text',
'actor',
'timestamp',
651 'metadata',
'major_mime',
'minor_mime',
'sha1',
'size',
'width',
655 if ( $extraFields ) {
657 'Passing extra fields (' .
658 implode(
', ', $extraFields )
659 .
') to ' . __METHOD__ .
' was deprecated in MediaWiki 1.37. ' .
660 'Property assignment will be removed in a later version.',
662 foreach ( $extraFields as $field ) {
663 $this->$field = $unprefixed[$field];
667 $this->fileExists =
true;
675 public function load( $flags = 0 ) {
676 if ( !$this->dataLoaded ) {
677 if ( $flags & self::READ_LATEST ) {
680 $this->loadFromCache();
684 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
695 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() || $this->upgrading ) {
700 $reserialize =
false;
701 if ( $this->media_type ===
null || $this->mime ==
'image/svg' ) {
710 && $this->repo->isMetadataUpdateEnabled()
713 } elseif ( $this->repo->isJsonMetadataEnabled()
714 && $this->repo->isMetadataReserializeEnabled()
716 if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
718 } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
719 $this->metadataSerializationFormat !== self::MDS_JSON ) {
726 if ( $upgrade || $reserialize ) {
727 $this->upgrading =
true;
729 DeferredUpdates::addCallableUpdate(
function () use ( $upgrade ) {
730 $this->upgrading =
false;
748 return $this->upgraded;
756 $dbw = $this->repo->getPrimaryDB();
760 $freshnessCondition = [
'img_timestamp' => $dbw->timestamp( $this->
getTimestamp() ) ];
764 # Don't destroy file info of missing files
765 if ( !$this->fileExists ) {
766 wfDebug( __METHOD__ .
": file does not exist, aborting" );
771 [ $major, $minor ] = self::splitMime( $this->mime );
773 wfDebug( __METHOD__ .
': upgrading ' . $this->
getName() .
" to the current schema" );
775 $dbw->newUpdateQueryBuilder()
778 'img_size' => $this->size,
779 'img_width' => $this->width,
780 'img_height' => $this->height,
781 'img_bits' => $this->bits,
782 'img_media_type' => $this->media_type,
783 'img_major_mime' => $major,
784 'img_minor_mime' => $minor,
786 'img_sha1' => $this->sha1,
788 ->where( [
'img_name' => $this->
getName() ] )
789 ->andWhere( $freshnessCondition )
790 ->caller( __METHOD__ )->execute();
794 $this->upgraded =
true;
802 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
805 $dbw = $this->repo->getPrimaryDB();
806 $dbw->newUpdateQueryBuilder()
810 'img_name' => $this->name,
811 'img_timestamp' => $dbw->timestamp( $this->timestamp ),
813 ->caller( __METHOD__ )->execute();
814 $this->upgraded =
true;
829 $this->dataLoaded =
true;
831 $fields[] =
'fileExists';
833 foreach ( $fields as $field ) {
834 if ( isset( $info[$field] ) ) {
835 $this->$field = $info[$field];
840 if ( isset( $info[
'user'] ) &&
841 isset( $info[
'user_text'] ) &&
842 $info[
'user_text'] !==
''
848 if ( isset( $info[
'major_mime'] ) ) {
849 $this->mime =
"{$info['major_mime']}/{$info['minor_mime']}";
850 } elseif ( isset( $info[
'mime'] ) ) {
851 $this->mime = $info[
'mime'];
852 [ $this->major_mime, $this->minor_mime ] = self::splitMime( $this->mime );
855 if ( isset( $info[
'metadata'] ) ) {
856 if ( is_string( $info[
'metadata'] ) ) {
858 } elseif ( is_array( $info[
'metadata'] ) ) {
859 $this->metadataArray = $info[
'metadata'];
860 if ( isset( $info[
'metadataBlobs'] ) ) {
861 $this->metadataBlobs = $info[
'metadataBlobs'];
862 $this->unloadedMetadataBlobs = array_diff_key(
863 $this->metadataBlobs,
867 $this->metadataBlobs = [];
868 $this->unloadedMetadataBlobs = [];
871 $logger = LoggerFactory::getInstance(
'LocalFile' );
872 $logger->warning( __METHOD__ .
' given invalid metadata of type ' .
873 gettype( $info[
'metadata'] ) );
874 $this->metadataArray = [];
876 $this->extraDataLoaded =
true;
896 if ( $this->missing ===
null ) {
897 $fileExists = $this->repo->fileExists( $this->
getVirtualUrl() );
898 $this->missing = !$fileExists;
901 return $this->missing;
926 return $dim[
'width'];
959 return $dim[
'height'];
966 return $this->height;
978 if ( !$this->title ) {
982 $pageId = $this->title->getArticleID();
985 $url = $this->repo->makeUrl( [
'curid' => $pageId ] );
986 if (
$url !==
false ) {
1003 } elseif ( array_keys( $data ) === [
'_error' ] ) {
1005 return $data[
'_error'];
1018 $this->
load( self::LOAD_ALL );
1019 if ( $this->unloadedMetadataBlobs ) {
1021 array_unique( array_merge(
1022 array_keys( $this->metadataArray ),
1023 array_keys( $this->unloadedMetadataBlobs )
1027 return $this->metadataArray;
1031 $this->load( self::LOAD_ALL );
1034 foreach ( $itemNames as $itemName ) {
1035 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1036 $result[$itemName] = $this->metadataArray[$itemName];
1037 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1038 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1043 $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
1044 foreach ( $addresses as $itemName => $address ) {
1045 unset( $this->unloadedMetadataBlobs[$itemName] );
1046 $value = $resultFromBlob[$itemName] ??
null;
1047 if ( $value !==
null ) {
1048 $result[$itemName] = $value;
1049 $this->metadataArray[$itemName] = $value;
1068 $this->load( self::LOAD_ALL );
1069 if ( !$this->metadataArray && !$this->metadataBlobs ) {
1071 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1072 $s = $this->getJsonMetadata();
1074 $s = serialize( $this->getMetadataArray() );
1076 if ( !is_string( $s ) ) {
1077 throw new MWException(
'Could not serialize image metadata value for DB' );
1088 private function getJsonMetadata() {
1091 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1095 if ( $this->metadataBlobs ) {
1096 $envelope[
'blobs'] = $this->metadataBlobs;
1099 [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
1102 $this->metadataBlobs += $blobAddresses;
1113 private function isMetadataOversize() {
1114 if ( !$this->repo->isSplitMetadataEnabled() ) {
1117 $threshold = $this->repo->getSplitMetadataThreshold();
1118 $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1119 foreach ( $directItems as $value ) {
1120 if ( strlen( $this->metadataStorageHelper->jsonEncode( $value ) ) > $threshold ) {
1136 $this->loadMetadataFromString( $db->
decodeBlob( $metadataBlob ) );
1147 $this->extraDataLoaded =
true;
1148 $this->metadataArray = [];
1149 $this->metadataBlobs = [];
1150 $this->unloadedMetadataBlobs = [];
1151 $metadataString = (string)$metadataString;
1152 if ( $metadataString ===
'' ) {
1153 $this->metadataSerializationFormat = self::MDS_EMPTY;
1156 if ( $metadataString[0] ===
'{' ) {
1157 $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
1160 $this->metadataArray = [
'_error' => $metadataString ];
1161 $this->metadataSerializationFormat = self::MDS_LEGACY;
1163 $this->metadataSerializationFormat = self::MDS_JSON;
1164 if ( isset( $envelope[
'data'] ) ) {
1165 $this->metadataArray = $envelope[
'data'];
1167 if ( isset( $envelope[
'blobs'] ) ) {
1168 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope[
'blobs'];
1173 $data = @unserialize( $metadataString );
1174 if ( !is_array( $data ) ) {
1176 $data = [
'_error' => $metadataString ];
1177 $this->metadataSerializationFormat = self::MDS_LEGACY;
1179 $this->metadataSerializationFormat = self::MDS_PHP;
1181 $this->metadataArray = $data;
1192 return (
int)$this->bits;
1226 return $this->media_type;
1243 return $this->fileExists;
1268 if ( $archiveName ) {
1269 $dir = $this->getArchiveThumbPath( $archiveName );
1271 $dir = $this->getThumbPath();
1274 $backend = $this->repo->getBackend();
1277 $iterator = $backend->getFileList( [
'dir' => $dir,
'forWrite' =>
true ] );
1278 if ( $iterator !==
null ) {
1279 foreach ( $iterator as
$file ) {
1292 private function purgeMetadataCache() {
1293 $this->invalidateCache();
1306 $this->maybeUpgradeRow();
1307 $this->purgeMetadataCache();
1310 $this->purgeThumbnails( $options );
1313 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1316 !empty( $options[
'forThumbRefresh'] )
1317 ? $hcu::PURGE_PRESEND
1318 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1329 $thumbs = $this->getThumbnails( $archiveName );
1332 $dir = array_shift( $thumbs );
1333 $this->purgeThumbList( $dir, $thumbs );
1336 foreach ( $thumbs as $thumb ) {
1337 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1341 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1344 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1345 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1355 $thumbs = $this->getThumbnails();
1358 $dir = array_shift( $thumbs );
1359 $this->purgeThumbList( $dir, $thumbs );
1363 foreach ( $thumbs as $thumb ) {
1364 $urls[] = $this->getThumbUrl( $thumb );
1368 if ( !empty( $options[
'forThumbRefresh'] ) ) {
1369 $handler = $this->getHandler();
1371 $handler->filterThumbnailPurgeList( $thumbs, $options );
1376 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this,
false, $urls );
1379 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1382 !empty( $options[
'forThumbRefresh'] )
1383 ? $hcu::PURGE_PRESEND
1384 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1395 $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1396 ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1400 $sizes = $uploadThumbnailRenderMap;
1403 foreach ( $sizes as $size ) {
1404 if ( $this->isMultipage() ) {
1407 $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1412 'transformParams' => [
'width' => $size,
'page' => 1 ],
1413 'enqueueNextPage' =>
true,
1414 'pageLimit' => $pageLimit
1417 } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1420 [
'transformParams' => [
'width' => $size ] ]
1426 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1437 $fileListDebug = strtr(
1438 var_export( $files,
true ),
1441 wfDebug( __METHOD__ .
": $fileListDebug" );
1443 if ( $this->repo->supportsSha1URLs() ) {
1444 $reference = $this->getSha1();
1446 $reference = $this->getName();
1450 foreach ( $files as
$file ) {
1451 # Check that the reference (filename or sha1) is part of the thumb name
1452 # This is a basic check to avoid erasing unrelated directories
1453 if ( str_contains(
$file, $reference )
1454 || str_contains(
$file,
"-thumbnail" )
1456 $purgeList[] =
"{$dir}/{$file}";
1460 # Delete the thumbnails
1461 $this->repo->quickPurgeBatch( $purgeList );
1462 # Clear out the thumbnail directory if empty
1463 $this->repo->quickCleanDir( $dir );
1477 public function getHistory( $limit =
null, $start =
null, $end =
null, $inc =
true ) {
1478 if ( !$this->exists() ) {
1482 $dbr = $this->repo->getReplicaDB();
1483 $oldFileQuery = OldLocalFile::getQueryInfo();
1485 $tables = $oldFileQuery[
'tables'];
1486 $fields = $oldFileQuery[
'fields'];
1487 $join_conds = $oldFileQuery[
'joins'];
1488 $conds = $opts = [];
1489 $eq = $inc ?
'=' :
'';
1490 $conds[] =
"oi_name = " . $dbr->
addQuotes( $this->title->getDBkey() );
1501 $opts[
'LIMIT'] = $limit;
1505 $order = ( !$start && $end !== null ) ?
'ASC' :
'DESC';
1506 $opts[
'ORDER BY'] =
"oi_timestamp $order";
1507 $opts[
'USE INDEX'] = [
'oldimage' =>
'oi_name_timestamp' ];
1509 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1510 $conds, $opts, $join_conds );
1512 $res = $dbr->
select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1515 foreach ( $res as $row ) {
1516 $r[] = $this->repo->newFileFromRow( $row );
1519 if ( $order ==
'ASC' ) {
1520 $r = array_reverse( $r );
1537 if ( !$this->exists() ) {
1541 # Polymorphic function name to distinguish foreign and local fetches
1542 $fname = static::class .
'::' . __FUNCTION__;
1544 $dbr = $this->repo->getReplicaDB();
1546 if ( $this->historyLine == 0 ) {
1547 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
1549 $queryBuilder->fields( [
'oi_archive_name' => $dbr->
addQuotes(
'' ),
'oi_deleted' =>
'0' ] )
1550 ->where( [
'img_name' => $this->title->getDBkey() ] );
1551 $this->historyRes = $queryBuilder->caller( $fname )->fetchResultSet();
1553 if ( $this->historyRes->numRows() == 0 ) {
1554 $this->historyRes =
null;
1558 } elseif ( $this->historyLine == 1 ) {
1559 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
1561 $this->historyRes = $queryBuilder->where( [
'oi_name' => $this->title->getDBkey() ] )
1562 ->orderBy(
'oi_timestamp', SelectQueryBuilder::SORT_DESC )
1563 ->caller( $fname )->fetchResultSet();
1565 $this->historyLine++;
1567 return $this->historyRes->fetchObject();
1575 $this->historyLine = 0;
1577 if ( $this->historyRes !==
null ) {
1578 $this->historyRes =
null;
1615 public function upload( $src, $comment, $pageText, $flags = 0, $props =
false,
1616 $timestamp =
false,
Authority $uploader =
null, $tags = [],
1617 $createNullRevision =
true, $revert =
false
1619 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
1620 return $this->readOnlyFatalStatus();
1621 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1624 return $this->readOnlyFatalStatus();
1627 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1632 $props = $this->repo->getFileProps( $srcPath );
1634 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1635 $props = $mwProps->getPropsFromPath( $srcPath,
true );
1642 if ( is_string( $props[
'metadata'] ) ) {
1647 $metadata = @unserialize( $props[
'metadata'] );
1649 $metadata = $props[
'metadata'];
1652 if ( is_array( $metadata ) ) {
1653 $options[
'headers'] = $handler->getContentHeaders( $metadata );
1656 $options[
'headers'] = [];
1660 $comment = trim( $comment );
1662 $status = $this->publish( $src, $flags, $options );
1664 if ( $status->successCount >= 2 ) {
1671 $oldver = $status->value;
1673 $uploadStatus = $this->recordUpload3(
1677 $uploader ?? RequestContext::getMain()->
getAuthority(),
1681 $createNullRevision,
1684 if ( !$uploadStatus->isOK() ) {
1685 if ( $uploadStatus->hasMessage(
'filenotfound' ) ) {
1687 $status->fatal(
'filenotfound', $srcPath );
1689 $status->merge( $uploadStatus );
1721 bool $createNullRevision =
true,
1722 bool $revert =
false
1724 $dbw = $this->repo->getPrimaryDB();
1726 # Imports or such might force a certain timestamp; otherwise we generate
1727 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1728 if ( $timestamp ===
false ) {
1729 $timestamp = $dbw->timestamp();
1730 $allowTimeKludge =
true;
1732 $allowTimeKludge =
false;
1735 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1736 $props[
'description'] = $comment;
1737 $props[
'timestamp'] =
wfTimestamp( TS_MW, $timestamp );
1738 $this->setProps( $props );
1740 # Fail now if the file isn't there
1741 if ( !$this->fileExists ) {
1742 wfDebug( __METHOD__ .
": File " . $this->getRel() .
" went missing!" );
1744 return Status::newFatal(
'filenotfound', $this->getRel() );
1747 $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1749 $dbw->startAtomic( __METHOD__ );
1751 $actorId = $actorNormalizaton->acquireActorId( $performer->
getUser(), $dbw );
1752 $this->user = $performer->
getUser();
1754 # Test to see if the row exists using INSERT IGNORE
1755 # This avoids race conditions by locking the row until the commit, and also
1756 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1757 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1758 $commentFields = $commentStore->insert( $dbw,
'img_description', $comment );
1759 $actorFields = [
'img_actor' => $actorId ];
1760 $dbw->newInsertQueryBuilder()
1761 ->insertInto(
'image' )
1764 'img_name' => $this->getName(),
1765 'img_size' => $this->size,
1766 'img_width' => intval( $this->width ),
1767 'img_height' => intval( $this->height ),
1768 'img_bits' => $this->bits,
1769 'img_media_type' => $this->media_type,
1770 'img_major_mime' => $this->major_mime,
1771 'img_minor_mime' => $this->minor_mime,
1772 'img_timestamp' => $dbw->timestamp( $timestamp ),
1773 'img_metadata' => $this->getMetadataForDb( $dbw ),
1774 'img_sha1' => $this->sha1
1775 ] + $commentFields + $actorFields )
1776 ->caller( __METHOD__ )->execute();
1777 $reupload = ( $dbw->affectedRows() == 0 );
1780 $row = $dbw->newSelectQueryBuilder()
1781 ->select( [
'img_timestamp',
'img_sha1' ] )
1783 ->where( [
'img_name' => $this->getName() ] )
1784 ->caller( __METHOD__ )->fetchRow();
1786 if ( $row && $row->img_sha1 === $this->sha1 ) {
1787 $dbw->endAtomic( __METHOD__ );
1788 wfDebug( __METHOD__ .
": File " . $this->getRel() .
" already exists!" );
1789 $title = Title::newFromText( $this->getName(),
NS_FILE );
1790 return Status::newFatal(
'fileexists-no-change', $title->getPrefixedText() );
1793 if ( $allowTimeKludge ) {
1794 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1795 $lUnixtime = $row ? (int)
wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1796 # Avoid a timestamp that is not newer than the last version
1797 # TODO: the image/oldimage tables should be like page/revision with an ID field
1798 if ( $lUnixtime && (
int)
wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1800 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1801 $this->timestamp =
wfTimestamp( TS_MW, $timestamp );
1805 $tables = [
'image' ];
1807 'oi_name' =>
'img_name',
1808 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1809 'oi_size' =>
'img_size',
1810 'oi_width' =>
'img_width',
1811 'oi_height' =>
'img_height',
1812 'oi_bits' =>
'img_bits',
1813 'oi_description_id' =>
'img_description_id',
1814 'oi_timestamp' =>
'img_timestamp',
1815 'oi_metadata' =>
'img_metadata',
1816 'oi_media_type' =>
'img_media_type',
1817 'oi_major_mime' =>
'img_major_mime',
1818 'oi_minor_mime' =>
'img_minor_mime',
1819 'oi_sha1' =>
'img_sha1',
1820 'oi_actor' =>
'img_actor',
1824 # (T36993) Note: $oldver can be empty here, if the previous
1825 # version of the file was broken. Allow registration of the new
1826 # version to continue anyway, because that's better than having
1827 # an image that's not fixable by user operations.
1828 # Collision, this is an update of a file
1829 # Insert previous contents into oldimage
1830 $dbw->insertSelect(
'oldimage', $tables, $fields,
1831 [
'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1833 # Update the current image row
1834 $dbw->newUpdateQueryBuilder()
1837 'img_size' => $this->size,
1838 'img_width' => intval( $this->width ),
1839 'img_height' => intval( $this->height ),
1840 'img_bits' => $this->bits,
1841 'img_media_type' => $this->media_type,
1842 'img_major_mime' => $this->major_mime,
1843 'img_minor_mime' => $this->minor_mime,
1844 'img_timestamp' => $dbw->timestamp( $timestamp ),
1845 'img_metadata' => $this->getMetadataForDb( $dbw ),
1846 'img_sha1' => $this->sha1
1847 ] + $commentFields + $actorFields )
1848 ->where( [
'img_name' => $this->getName() ] )
1849 ->caller( __METHOD__ )->execute();
1853 $descId = $descTitle->getArticleID();
1854 $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
1856 throw new MWException(
'Cannot instance WikiFilePage for ' . $this->getName()
1857 .
', got instance of ' . get_class( $wikiPage ) );
1859 $wikiPage->setFile( $this );
1863 $logAction =
'revert';
1864 } elseif ( $reupload ) {
1865 $logAction =
'overwrite';
1867 $logAction =
'upload';
1871 $logEntry->setTimestamp( $this->timestamp );
1872 $logEntry->setPerformer( $performer->
getUser() );
1873 $logEntry->setComment( $comment );
1874 $logEntry->setTarget( $descTitle );
1877 $logEntry->setParameters(
1879 'img_sha1' => $this->sha1,
1880 'img_timestamp' => $timestamp,
1889 $logId = $logEntry->insert();
1891 if ( $descTitle->exists() ) {
1892 if ( $createNullRevision ) {
1893 $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1896 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1897 $editSummary = $formatter->getPlainActionText();
1898 $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1899 $nullRevRecord = $revStore->newNullRevision(
1907 if ( $nullRevRecord ) {
1908 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1910 $this->getHookRunner()->onRevisionFromEditComplete(
1913 $inserted->getParentId(),
1918 $wikiPage->updateRevisionOn( $dbw, $inserted );
1920 $logEntry->setAssociatedRevId( $inserted->getId() );
1924 $newPageContent =
null;
1933 $dbw->endAtomic( __METHOD__ );
1934 $fname = __METHOD__;
1936 # Do some cache purges after final commit so that:
1937 # a) Changes are more likely to be seen post-purge
1938 # b) They won't cause rollback of the log publish/update above
1943 $reupload, $wikiPage, $newPageContent, $comment, $performer,
1944 $logEntry, $logId, $descId, $tags, $fname
1946 # Update memcache after the commit
1947 $this->invalidateCache();
1949 $updateLogPage =
false;
1950 if ( $newPageContent ) {
1951 # New file page; create the description page.
1952 # There's already a log entry, so don't make a second RC entry
1953 # CDN and file cache for the description page are purged by doUserEditContent.
1954 $status = $wikiPage->doUserEditContent(
1961 $revRecord = $status->getNewRevision();
1964 $logEntry->setAssociatedRevId( $revRecord->getId() );
1968 $updateLogPage = $revRecord->getPageId();
1971 # Existing file page: invalidate description page cache
1972 $title = $wikiPage->getTitle();
1973 $title->invalidateCache();
1974 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1975 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1976 # Allow the new file version to be patrolled from the page footer
1980 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1981 # but setAssociatedRevId() wasn't called at that point yet...
1982 $logParams = $logEntry->getParameters();
1983 $logParams[
'associated_rev_id'] = $logEntry->getAssociatedRevId();
1985 if ( $updateLogPage ) {
1986 # Also log page, in case where we just created it above
1987 $update[
'log_page'] = $updateLogPage;
1989 $this->getRepo()->getPrimaryDB()->newUpdateQueryBuilder()
1990 ->update(
'logging' )
1992 ->where( [
'log_id' => $logId ] )
1993 ->caller( $fname )->execute();
1995 $this->getRepo()->getPrimaryDB()->insert(
1998 'ls_field' =>
'associated_rev_id',
1999 'ls_value' => (
string)$logEntry->getAssociatedRevId(),
2000 'ls_log_id' => $logId,
2005 # Add change tags, if any
2007 $logEntry->addTags( $tags );
2010 # Uploads can be patrolled
2011 $logEntry->setIsPatrollable(
true );
2013 # Now that the log entry is up-to-date, make an RC entry.
2014 $logEntry->publish( $logId );
2016 # Run hook for other updates (typically more cache purging)
2017 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2020 # Delete old thumbnails
2021 $this->purgeThumbnails();
2022 # Remove the old file from the CDN cache
2023 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2024 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2026 # Update backlink pages pointing to this title if created
2027 $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2028 LinksUpdate::queueRecursiveJobsForTable(
2032 $performer->
getUser()->getName(),
2033 $blcFactory->getBacklinkCache( $this->getTitle() )
2037 $this->prerenderThumbnails();
2041 # Invalidate cache for all pages using this file
2045 [
'causeAction' =>
'file-upload',
'causeAgent' => $performer->
getUser()->getName() ]
2053 $dbw->onTransactionCommitOrIdle(
static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2054 DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2058 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
'images' => 1 ] ) );
2061 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2064 return Status::newGood();
2083 public function publish( $src, $flags = 0, array $options = [] ) {
2084 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2103 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2104 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
2106 $repo = $this->getRepo();
2107 if ( $repo->getReadOnlyReason() !==
false ) {
2108 return $this->readOnlyFatalStatus();
2111 $status = $this->acquireFileLock();
2112 if ( !$status->isOK() ) {
2116 if ( $this->isOld() ) {
2117 $archiveRel = $dstRel;
2118 $archiveName = basename( $archiveRel );
2120 $archiveName =
wfTimestamp( TS_MW ) .
'!' . $this->getName();
2121 $archiveRel = $this->getArchiveRel( $archiveName );
2124 if ( $repo->hasSha1Storage() ) {
2126 ? $repo->getFileSha1( $srcPath )
2129 $wrapperBackend = $repo->getBackend();
2130 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2131 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2132 $status = $repo->quickImport( $src, $dst );
2137 if ( $this->exists() ) {
2138 $status->value = $archiveName;
2142 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2144 if ( $status->value ==
'new' ) {
2145 $status->value =
'';
2147 $status->value = $archiveName;
2151 $this->releaseFileLock();
2174 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2175 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2176 return $this->readOnlyFatalStatus();
2179 wfDebugLog(
'imagemove',
"Got request to move {$this->name} to " . $target->getText() );
2182 $status = $batch->addCurrent();
2183 if ( !$status->isOK() ) {
2186 $archiveNames = $batch->addOlds();
2187 $status = $batch->execute();
2189 wfDebugLog(
'imagemove',
"Finished moving {$this->name}" );
2192 $oldTitleFile = $localRepo->newFile( $this->title );
2193 $newTitleFile = $localRepo->newFile( $target );
2194 DeferredUpdates::addUpdate(
2196 $this->getRepo()->getPrimaryDB(),
2198 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2199 $oldTitleFile->purgeEverything();
2200 foreach ( $archiveNames as $archiveName ) {
2202 '@phan-var OldLocalFile $oldTitleFile';
2203 $oldTitleFile->purgeOldThumbnails( $archiveName );
2205 $newTitleFile->purgeEverything();
2208 DeferredUpdates::PRESEND
2211 if ( $status->isOK() ) {
2213 $this->title = $target;
2216 $this->hashPath =
null;
2239 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2240 return $this->readOnlyFatalStatus();
2245 $batch->addCurrent();
2247 $archiveNames = $batch->addOlds();
2248 $status = $batch->execute();
2250 if ( $status->isOK() ) {
2251 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
'images' => -1 ] ) );
2255 DeferredUpdates::addUpdate(
2257 $this->getRepo()->getPrimaryDB(),
2259 function () use ( $archiveNames ) {
2260 $this->purgeEverything();
2261 foreach ( $archiveNames as $archiveName ) {
2262 $this->purgeOldThumbnails( $archiveName );
2266 DeferredUpdates::PRESEND
2271 foreach ( $archiveNames as $archiveName ) {
2272 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2275 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2276 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2300 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2301 return $this->readOnlyFatalStatus();
2306 $batch->addOld( $archiveName );
2307 $status = $batch->execute();
2309 $this->purgeOldThumbnails( $archiveName );
2310 if ( $status->isOK() ) {
2311 $this->purgeDescription();
2314 $url = $this->getArchiveUrl( $archiveName );
2315 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2316 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2333 public function restore( $versions = [], $unsuppress =
false ) {
2334 if ( $this->getRepo()->getReadOnlyReason() !==
false ) {
2335 return $this->readOnlyFatalStatus();
2343 $batch->addIds( $versions );
2345 $status = $batch->execute();
2346 if ( $status->isGood() ) {
2347 $cleanupStatus = $batch->cleanup();
2348 $cleanupStatus->successCount = 0;
2349 $cleanupStatus->failCount = 0;
2350 $status->merge( $cleanupStatus );
2368 return $this->title ? $this->title->getLocalURL() :
false;
2381 if ( !$this->title ) {
2385 $services = MediaWikiServices::getInstance();
2386 $page = $services->getPageStore()->getPageByReference( $this->
getTitle() );
2392 $parserOptions = ParserOptions::newFromUserAndLang(
2393 RequestContext::getMain()->
getUser(),
2397 $parserOptions = ParserOptions::newFromContext( RequestContext::getMain() );
2400 $parseStatus = $services->getParserOutputAccess()
2401 ->getParserOutput( $page, $parserOptions );
2403 if ( !$parseStatus->isGood() ) {
2407 return $parseStatus->getValue()->getText();
2419 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2421 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2436 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2438 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2441 return $this->description;
2452 return $this->timestamp;
2460 if ( !$this->exists() ) {
2467 if ( $this->descriptionTouched ===
null ) {
2468 $touched = $this->repo->getReplicaDB()->newSelectQueryBuilder()
2469 ->select(
'page_touched' )
2471 ->where( [
'page_namespace' => $this->title->getNamespace() ] )
2472 ->andWhere( [
'page_title' => $this->title->getDBkey() ] )
2473 ->caller( __METHOD__ )->fetchField();
2474 $this->descriptionTouched = $touched ?
wfTimestamp( TS_MW, $touched ) :
false;
2477 return $this->descriptionTouched;
2496 return $this->extraDataLoaded
2497 && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2509 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2510 [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2521 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2522 [ $this->getPath() ], LockManager::LOCK_EX
2537 if ( !$this->locked ) {
2538 $logger = LoggerFactory::getInstance(
'LocalFile' );
2540 $dbw = $this->repo->getPrimaryDB();
2541 $makesTransaction = !$dbw->trxLevel();
2542 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2546 $status = $this->acquireFileLock( 10 );
2547 if ( !$status->isGood() ) {
2548 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2549 $logger->warning(
"Failed to lock '{file}'", [
'file' => $this->name ] );
2555 $dbw->onTransactionResolution(
2556 function () use ( $logger ) {
2557 $status = $this->releaseFileLock();
2558 if ( !$status->isGood() ) {
2559 $logger->error(
"Failed to unlock '{file}'", [
'file' => $this->name ] );
2565 $this->lockedOwnTrx = $makesTransaction;
2570 return $this->lockedOwnTrx;
2584 if ( $this->locked ) {
2586 if ( !$this->locked ) {
2587 $dbw = $this->repo->getPrimaryDB();
2588 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2589 $this->lockedOwnTrx =
false;
2598 return $this->getRepo()->newFatal(
'filereadonlyerror', $this->getName(),
2599 $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,...
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
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.
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
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.
loadMetadataFromDbFieldValue(IReadableDatabase $db, $metadataBlob)
Unserialize a metadata blob which came from the database and store it in $this.
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.
__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)
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 IReadable...
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.
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.
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.
getMetadataForDb(IReadableDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
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.
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.
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.
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.