164 $file->loadFromRow( $row );
181 $conds = [
'img_sha1' =>
$sha1 ];
186 $row =
$dbr->selectRow(
'image', self::selectFields(), $conds, __METHOD__ );
226 $this->metadata =
'';
227 $this->historyLine = 0;
228 $this->historyRes =
null;
229 $this->dataLoaded =
false;
230 $this->extraDataLoaded =
false;
242 return $this->repo->getSharedCacheKey(
'file', sha1( $this->
getName() ) );
258 $this->dataLoaded =
false;
259 $this->extraDataLoaded =
false;
268 $cache = ObjectCache::getMainWANInstance();
269 $cachedValues =
$cache->getWithSetCallback(
273 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
279 if ( $this->fileExists ) {
280 foreach ( $fields
as $field ) {
281 $cacheVal[$field] = $this->$field;
288 if ( isset( $cacheVal[$field] )
289 && strlen( $cacheVal[$field] ) > 100 * 1024
291 unset( $cacheVal[$field] );
295 if ( $this->fileExists ) {
298 $ttl = $cache::TTL_DAY;
306 $this->fileExists = $cachedValues[
'fileExists'];
307 if ( $this->fileExists ) {
311 $this->dataLoaded =
true;
312 $this->extraDataLoaded =
true;
314 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
327 $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
328 function ()
use ( $key ) {
329 ObjectCache::getMainWANInstance()->delete( $key );
339 $props = $this->repo->getFileProps( $this->
getVirtualUrl() );
348 static $fields = [
'size',
'width',
'height',
'bits',
'media_type',
349 'major_mime',
'minor_mime',
'metadata',
'timestamp',
'sha1',
'user',
350 'user_text',
'description' ];
351 static $results = [];
353 if ( $prefix ==
'' ) {
357 if ( !isset( $results[$prefix] ) ) {
358 $prefixedFields = [];
359 foreach ( $fields
as $field ) {
360 $prefixedFields[] = $prefix . $field;
362 $results[$prefix] = $prefixedFields;
365 return $results[$prefix];
373 static $fields = [
'metadata' ];
374 static $results = [];
376 if ( $prefix ==
'' ) {
380 if ( !isset( $results[$prefix] ) ) {
381 $prefixedFields = [];
382 foreach ( $fields
as $field ) {
383 $prefixedFields[] = $prefix . $field;
385 $results[$prefix] = $prefixedFields;
388 return $results[$prefix];
396 $fname = static::class .
'::' . __FUNCTION__;
398 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
399 $this->dataLoaded =
true;
400 $this->extraDataLoaded =
true;
403 ? $this->repo->getMasterDB()
404 : $this->repo->getReplicaDB();
412 $this->fileExists =
false;
421 $fname = static::class .
'::' . __FUNCTION__;
423 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
424 $this->extraDataLoaded =
true;
436 throw new MWException(
"Could not find data for image '{$this->getName()}'." );
449 'img_name' => $this->
getName(),
450 'img_timestamp' =>
$dbr->timestamp( $this->getTimestamp() )
455 # File may have been uploaded over in the meantime; check the old versions
458 'oi_timestamp' =>
$dbr->timestamp( $this->getTimestamp() )
475 $array = (
array)$row;
476 $prefixLength = strlen( $prefix );
479 if ( substr(
key( $array ), 0, $prefixLength ) !== $prefix ) {
480 throw new MWException( __METHOD__ .
': incorrect $prefix parameter' );
502 $decoded[
'timestamp'] =
wfTimestamp( TS_MW, $decoded[
'timestamp'] );
504 $decoded[
'metadata'] = $this->repo->getReplicaDB()->decodeBlob( $decoded[
'metadata'] );
506 if ( empty( $decoded[
'major_mime'] ) ) {
507 $decoded[
'mime'] =
'unknown/unknown';
509 if ( !$decoded[
'minor_mime'] ) {
510 $decoded[
'minor_mime'] =
'unknown';
512 $decoded[
'mime'] = $decoded[
'major_mime'] .
'/' . $decoded[
'minor_mime'];
516 $decoded[
'sha1'] = rtrim( $decoded[
'sha1'],
"\0" );
522 foreach ( [
'size',
'width',
'height',
'bits' ]
as $field ) {
523 $decoded[$field] = +$decoded[$field];
536 $this->dataLoaded =
true;
537 $this->extraDataLoaded =
true;
539 $array = $this->
decodeRow( $row, $prefix );
545 $this->fileExists =
true;
554 if ( !$this->dataLoaded ) {
555 if (
$flags & self::READ_LATEST ) {
562 if ( (
$flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
579 if ( is_null( $this->media_type ) || $this->mime ==
'image/svg' ) {
594 $this->upgrading =
true;
596 DeferredUpdates::addCallableUpdate(
function() {
597 $this->upgrading =
false;
622 # Don't destroy file info of missing files
623 if ( !$this->fileExists ) {
625 wfDebug( __METHOD__ .
": file does not exist, aborting\n" );
630 $dbw = $this->repo->getMasterDB();
638 wfDebug( __METHOD__ .
': upgrading ' . $this->
getName() .
" to the current schema\n" );
640 $dbw->update(
'image',
642 'img_size' => $this->size,
643 'img_width' => $this->
width,
644 'img_height' => $this->height,
645 'img_bits' => $this->bits,
646 'img_media_type' => $this->media_type,
647 'img_major_mime' => $major,
648 'img_minor_mime' => $minor,
649 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
650 'img_sha1' => $this->sha1,
652 [
'img_name' => $this->getName() ],
659 $this->upgraded =
true;
673 $this->dataLoaded =
true;
675 $fields[] =
'fileExists';
677 foreach ( $fields
as $field ) {
678 if ( isset( $info[$field] ) ) {
679 $this->$field = $info[$field];
684 if ( isset( $info[
'major_mime'] ) ) {
685 $this->mime =
"{$info['major_mime']}/{$info['minor_mime']}";
686 } elseif ( isset( $info[
'mime'] ) ) {
687 $this->mime = $info[
'mime'];
704 if ( $this->missing ===
null ) {
728 return $dim[
'width'];
755 return $dim[
'height'];
775 if (
$type ==
'text' ) {
790 $pageId = $this->
title->getArticleID();
792 if ( $pageId !==
null ) {
793 $url = $this->repo->makeUrl( [
'curid' => $pageId ] );
794 if (
$url !==
false ) {
806 $this->
load( self::LOAD_ALL );
882 if ( $archiveName ) {
888 $backend = $this->repo->getBackend();
891 $iterator = $backend->getFileList( [
'dir' => $dir ] );
892 foreach ( $iterator
as $file ) {
923 DeferredUpdates::addUpdate(
925 DeferredUpdates::PRESEND
938 Hooks::run(
'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
941 $dir = array_shift( $files );
946 foreach ( $files
as $file ) {
960 foreach ( $files
as $file ) {
963 array_shift(
$urls );
966 if ( !empty(
$options[
'forThumbRefresh'] ) ) {
974 Hooks::run(
'LocalFilePurgeThumbnails', [ $this,
false ] );
977 $dir = array_shift( $files );
1001 [
'transformParams' => [
'width' => $size ] ]
1017 $fileListDebug = strtr(
1018 var_export( $files,
true ),
1021 wfDebug( __METHOD__ .
": $fileListDebug\n" );
1024 foreach ( $files
as $file ) {
1025 # Check that the base file name is part of the thumb name
1026 # This is a basic sanity check to avoid erasing unrelated directories
1027 if ( strpos( $file, $this->
getName() ) !==
false
1028 || strpos( $file,
"-thumbnail" ) !==
false
1030 $purgeList[] =
"{$dir}/{$file}";
1034 # Delete the thumbnails
1035 $this->repo->quickPurgeBatch( $purgeList );
1036 # Clear out the thumbnail directory if empty
1037 $this->repo->quickCleanDir( $dir );
1051 $dbr = $this->repo->getReplicaDB();
1054 $conds = $opts = $join_conds = [];
1055 $eq = $inc ?
'=' :
'';
1056 $conds[] =
"oi_name = " .
$dbr->addQuotes( $this->
title->getDBkey() );
1059 $conds[] =
"oi_timestamp <$eq " .
$dbr->addQuotes(
$dbr->timestamp( $start ) );
1063 $conds[] =
"oi_timestamp >$eq " .
$dbr->addQuotes(
$dbr->timestamp( $end ) );
1071 $order = ( !$start && $end !== null ) ?
'ASC' :
'DESC';
1072 $opts[
'ORDER BY'] =
"oi_timestamp $order";
1073 $opts[
'USE INDEX'] = [
'oldimage' =>
'oi_name_timestamp' ];
1077 Hooks::run(
'LocalFile::getHistory', [ &$localFile, &
$tables, &$fields,
1078 &$conds, &$opts, &$join_conds ] );
1080 $res =
$dbr->select(
$tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1083 foreach (
$res as $row ) {
1084 $r[] = $this->repo->newFileFromRow( $row );
1087 if ( $order ==
'ASC' ) {
1088 $r = array_reverse( $r );
1104 # Polymorphic function name to distinguish foreign and local fetches
1105 $fname = static::class .
'::' . __FUNCTION__;
1107 $dbr = $this->repo->getReplicaDB();
1109 if ( $this->historyLine == 0 ) {
1110 $this->historyRes =
$dbr->select(
'image',
1113 "'' AS oi_archive_name",
1117 [
'img_name' => $this->
title->getDBkey() ],
1121 if ( 0 ==
$dbr->numRows( $this->historyRes ) ) {
1122 $this->historyRes =
null;
1126 } elseif ( $this->historyLine == 1 ) {
1127 $this->historyRes =
$dbr->select(
'oldimage',
'*',
1128 [
'oi_name' => $this->
title->getDBkey() ],
1130 [
'ORDER BY' =>
'oi_timestamp DESC' ]
1133 $this->historyLine++;
1135 return $dbr->fetchObject( $this->historyRes );
1142 $this->historyLine = 0;
1144 if ( !is_null( $this->historyRes ) ) {
1145 $this->historyRes =
null;
1184 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1188 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1190 if ( $this->repo->isVirtualUrl( $srcPath )
1193 $props = $this->repo->getFileProps( $srcPath );
1196 $props = $mwProps->getPropsFromPath( $srcPath,
true );
1209 $comment = trim( $comment );
1213 $comment =
$wgContLang->truncate( $comment, 255 );
1217 if (
$status->successCount >= 2 ) {
1226 $status->fatal(
'filenotfound', $srcPath );
1279 $oldver, $comment, $pageText, $props =
false,
$timestamp =
false,
$user =
null, $tags = []
1281 if ( is_null(
$user ) ) {
1286 $dbw = $this->repo->getMasterDB();
1288 # Imports or such might force a certain timestamp; otherwise we generate
1289 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1292 $allowTimeKludge =
true;
1294 $allowTimeKludge =
false;
1297 $props = $props ?: $this->repo->getFileProps( $this->
getVirtualUrl() );
1298 $props[
'description'] = $comment;
1299 $props[
'user'] =
$user->getId();
1300 $props[
'user_text'] =
$user->getName();
1304 # Fail now if the file isn't there
1305 if ( !$this->fileExists ) {
1306 wfDebug( __METHOD__ .
": File " . $this->
getRel() .
" went missing!\n" );
1311 $dbw->startAtomic( __METHOD__ );
1313 # Test to see if the row exists using INSERT IGNORE
1314 # This avoids race conditions by locking the row until the commit, and also
1315 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1316 $dbw->insert(
'image',
1318 'img_name' => $this->
getName(),
1319 'img_size' => $this->size,
1320 'img_width' => intval( $this->
width ),
1321 'img_height' => intval( $this->height ),
1322 'img_bits' => $this->bits,
1323 'img_media_type' => $this->media_type,
1324 'img_major_mime' => $this->major_mime,
1325 'img_minor_mime' => $this->minor_mime,
1327 'img_description' => $comment,
1328 'img_user' =>
$user->getId(),
1329 'img_user_text' =>
$user->getName(),
1330 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1331 'img_sha1' => $this->sha1
1337 $reupload = ( $dbw->affectedRows() == 0 );
1339 if ( $allowTimeKludge ) {
1340 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1341 $ltimestamp = $dbw->selectField(
1344 [
'img_name' => $this->
getName() ],
1346 [
'LOCK IN SHARE MODE' ]
1348 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX, $ltimestamp ) :
false;
1349 # Avoid a timestamp that is not newer than the last version
1350 # TODO: the image/oldimage tables should be like page/revision with an ID field
1353 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1358 # (T36993) Note: $oldver can be empty here, if the previous
1359 # version of the file was broken. Allow registration of the new
1360 # version to continue anyway, because that's better than having
1361 # an image that's not fixable by user operations.
1362 # Collision, this is an update of a file
1363 # Insert previous contents into oldimage
1364 $dbw->insertSelect(
'oldimage',
'image',
1366 'oi_name' =>
'img_name',
1367 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1368 'oi_size' =>
'img_size',
1369 'oi_width' =>
'img_width',
1370 'oi_height' =>
'img_height',
1371 'oi_bits' =>
'img_bits',
1372 'oi_timestamp' =>
'img_timestamp',
1373 'oi_description' =>
'img_description',
1374 'oi_user' =>
'img_user',
1375 'oi_user_text' =>
'img_user_text',
1376 'oi_metadata' =>
'img_metadata',
1377 'oi_media_type' =>
'img_media_type',
1378 'oi_major_mime' =>
'img_major_mime',
1379 'oi_minor_mime' =>
'img_minor_mime',
1380 'oi_sha1' =>
'img_sha1'
1382 [
'img_name' => $this->getName() ],
1386 # Update the current image row
1387 $dbw->update(
'image',
1389 'img_size' => $this->size,
1390 'img_width' => intval( $this->
width ),
1391 'img_height' => intval( $this->height ),
1392 'img_bits' => $this->bits,
1393 'img_media_type' => $this->media_type,
1394 'img_major_mime' => $this->major_mime,
1395 'img_minor_mime' => $this->minor_mime,
1397 'img_description' => $comment,
1398 'img_user' =>
$user->getId(),
1399 'img_user_text' =>
$user->getName(),
1400 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1401 'img_sha1' => $this->sha1
1403 [
'img_name' => $this->getName() ],
1409 $descId = $descTitle->getArticleID();
1411 $wikiPage->setFile( $this );
1414 $logEntry =
new ManualLogEntry(
'upload', $reupload ?
'overwrite' :
'upload' );
1416 $logEntry->setPerformer(
$user );
1417 $logEntry->setComment( $comment );
1418 $logEntry->setTarget( $descTitle );
1421 $logEntry->setParameters(
1423 'img_sha1' => $this->sha1,
1433 $logId = $logEntry->insert();
1435 if ( $descTitle->exists() ) {
1439 $editSummary = $formatter->getPlainActionText();
1448 if ( $nullRevision ) {
1449 $nullRevision->insertOn( $dbw );
1451 'NewRevisionFromEditComplete',
1452 [ $wikiPage, $nullRevision, $nullRevision->getParentId(),
$user ]
1454 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1456 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1459 $newPageContent =
null;
1465 # Defer purges, page creation, and link updates in case they error out.
1466 # The most important thing is that files and the DB registry stay synced.
1467 $dbw->endAtomic( __METHOD__ );
1469 # Do some cache purges after final commit so that:
1470 # a) Changes are more likely to be seen post-purge
1471 # b) They won't cause rollback of the log publish/update above
1472 DeferredUpdates::addUpdate(
1477 $reupload, $wikiPage, $newPageContent, $comment,
$user,
1478 $logEntry, $logId, $descId, $tags
1480 # Update memcache after the commit
1483 $updateLogPage =
false;
1484 if ( $newPageContent ) {
1485 # New file page; create the description page.
1486 # There's already a log entry, so don't make a second RC entry
1487 # CDN and file cache for the description page are purged by doEditContent.
1488 $status = $wikiPage->doEditContent(
1496 if ( isset(
$status->value[
'revision'] ) ) {
1500 $logEntry->setAssociatedRevId(
$rev->getId() );
1504 if ( isset(
$status->value[
'revision'] ) ) {
1507 $updateLogPage =
$rev->getPage();
1510 # Existing file page: invalidate description page cache
1511 $wikiPage->getTitle()->invalidateCache();
1512 $wikiPage->getTitle()->purgeSquid();
1513 # Allow the new file version to be patrolled from the page footer
1517 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1518 # but setAssociatedRevId() wasn't called at that point yet...
1519 $logParams = $logEntry->getParameters();
1520 $logParams[
'associated_rev_id'] = $logEntry->getAssociatedRevId();
1522 if ( $updateLogPage ) {
1523 # Also log page, in case where we just created it above
1524 $update[
'log_page'] = $updateLogPage;
1526 $this->
getRepo()->getMasterDB()->update(
1529 [
'log_id' => $logId ],
1532 $this->
getRepo()->getMasterDB()->insert(
1535 'ls_field' =>
'associated_rev_id',
1536 'ls_value' => $logEntry->getAssociatedRevId(),
1537 'ls_log_id' => $logId,
1542 # Add change tags, if any
1544 $logEntry->setTags( $tags );
1547 # Uploads can be patrolled
1548 $logEntry->setIsPatrollable(
true );
1550 # Now that the log entry is up-to-date, make an RC entry.
1551 $logEntry->publish( $logId );
1553 # Run hook for other updates (typically more cache purging)
1554 Hooks::run(
'FileUpload', [ $this, $reupload, !$newPageContent ] );
1557 # Delete old thumbnails
1559 # Remove the old file from the CDN cache
1560 DeferredUpdates::addUpdate(
1562 DeferredUpdates::PRESEND
1565 # Update backlink pages pointing to this title if created
1572 DeferredUpdates::PRESEND
1576 # This is a new file, so update the image count
1580 # Invalidate cache for all pages using this file
1621 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1631 $archiveRel =
'archive/' . $this->
getHashPath() . $archiveName;
1639 $dst = $wrapperBackend->getPathForSHA1(
$sha1 );
1646 $status->value = $archiveName;
1652 if (
$status->value ==
'new' ) {
1655 $status->value = $archiveName;
1682 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1686 wfDebugLog(
'imagemove',
"Got request to move {$this->name} to " . $target->getText() );
1691 $archiveNames =
$batch->addOlds();
1695 wfDebugLog(
'imagemove',
"Finished moving {$this->name}" );
1701 DeferredUpdates::addUpdate(
1703 $this->
getRepo()->getMasterDB(),
1705 function ()
use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1706 $oldTitleFile->purgeEverything();
1707 foreach ( $archiveNames
as $archiveName ) {
1708 $oldTitleFile->purgeOldThumbnails( $archiveName );
1710 $newTitleFile->purgeEverything();
1713 DeferredUpdates::PRESEND
1718 $this->
title = $target;
1720 unset( $this->
name );
1721 unset( $this->hashPath );
1740 function delete( $reason, $suppress =
false,
$user = null ) {
1741 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1750 $archiveNames =
$batch->addOlds();
1759 DeferredUpdates::addUpdate(
1761 $this->
getRepo()->getMasterDB(),
1763 function ()
use ( $archiveNames ) {
1765 foreach ( $archiveNames
as $archiveName ) {
1770 DeferredUpdates::PRESEND
1775 foreach ( $archiveNames
as $archiveName ) {
1778 DeferredUpdates::addUpdate(
new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
1799 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1806 $batch->addOld( $archiveName );
1815 DeferredUpdates::addUpdate(
1817 DeferredUpdates::PRESEND
1834 function restore( $versions = [], $unsuppress =
false ) {
1835 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1845 $batch->addIds( $versions );
1849 $cleanupStatus =
$batch->cleanup();
1850 $cleanupStatus->successCount = 0;
1851 $cleanupStatus->failCount = 0;
1852 $status->merge( $cleanupStatus );
1869 return $this->
title->getLocalURL();
1885 $content = $revision->getContent();
1891 return $pout->getText();
1901 if ( $audience == self::FOR_PUBLIC && $this->
isDeleted( self::DELETED_COMMENT ) ) {
1903 } elseif ( $audience == self::FOR_THIS_USER
1928 if ( $this->descriptionTouched ===
null ) {
1930 'page_namespace' => $this->
title->getNamespace(),
1931 'page_title' => $this->
title->getDBkey()
1933 $touched = $this->repo->getReplicaDB()->selectField(
'page',
'page_touched', $cond, __METHOD__ );
1934 $this->descriptionTouched = $touched ?
wfTimestamp( TS_MW, $touched ) :
false;
1946 if ( $this->sha1 ==
'' && $this->fileExists ) {
1949 $this->sha1 = $this->repo->getFileSha1( $this->
getPath() );
1950 if ( !
wfReadOnly() && strval( $this->sha1 ) !=
'' ) {
1951 $dbw = $this->repo->getMasterDB();
1952 $dbw->update(
'image',
1953 [
'img_sha1' => $this->sha1 ],
1954 [
'img_name' => $this->
getName() ],
1972 return $this->extraDataLoaded
1981 return $this->
getRepo()->getBackend()->lockFiles(
1982 [ $this->
getPath() ], LockManager::LOCK_EX, 10
1991 return $this->
getRepo()->getBackend()->unlockFiles(
1992 [ $this->
getPath() ], LockManager::LOCK_EX
2006 if ( !$this->locked ) {
2007 $logger = LoggerFactory::getInstance(
'LocalFile' );
2009 $dbw = $this->repo->getMasterDB();
2010 $makesTransaction = !$dbw->trxLevel();
2011 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2017 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2018 $logger->warning(
"Failed to lock '{file}'", [
'file' => $this->
name ] );
2024 $dbw->onTransactionResolution(
2025 function ()
use ( $logger ) {
2028 $logger->error(
"Failed to unlock '{file}'", [
'file' => $this->
name ] );
2034 $this->lockedOwnTrx = $makesTransaction;
2051 if ( $this->locked ) {
2053 if ( !$this->locked ) {
2054 $dbw = $this->repo->getMasterDB();
2055 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2056 $this->lockedOwnTrx =
false;
2065 return $this->
getRepo()->newFatal(
'filereadonlyerror', $this->
getName(),
2077# ------------------------------------------------------------------------------
2124 $this->status =
$file->repo->newGood();
2128 $this->srcRels[
'.'] = $this->
file->getRel();
2135 $this->srcRels[$oldName] = $this->
file->getArchiveRel( $oldName );
2136 $this->archiveUrls[] = $this->
file->getArchiveUrl( $oldName );
2146 $dbw = $this->
file->repo->getMasterDB();
2147 $result = $dbw->select(
'oldimage',
2148 [
'oi_archive_name' ],
2149 [
'oi_name' => $this->
file->getName() ],
2154 $this->
addOld( $row->oi_archive_name );
2155 $archiveNames[] = $row->oi_archive_name;
2158 return $archiveNames;
2165 if ( !isset( $this->srcRels[
'.'] ) ) {
2167 $deleteCurrent =
false;
2170 unset( $oldRels[
'.'] );
2171 $deleteCurrent =
true;
2174 return [ $oldRels, $deleteCurrent ];
2184 if ( $deleteCurrent ) {
2188 if ( count( $oldRels ) ) {
2189 $dbw = $this->
file->repo->getMasterDB();
2190 $res = $dbw->select(
2192 [
'oi_archive_name',
'oi_sha1' ],
2193 [
'oi_archive_name' => array_keys( $oldRels ),
2194 'oi_name' => $this->
file->getName() ],
2198 foreach (
$res as $row ) {
2199 if ( rtrim( $row->oi_sha1,
"\0" ) ===
'' ) {
2201 $oldUrl = $this->
file->getArchiveVirtualUrl( $row->oi_archive_name );
2202 $props = $this->
file->repo->getFileProps( $oldUrl );
2204 if ( $props[
'fileExists'] ) {
2206 $dbw->update(
'oldimage',
2207 [
'oi_sha1' => $props[
'sha1'] ],
2208 [
'oi_name' => $this->
file->getName(),
'oi_archive_name' => $row->oi_archive_name ],
2210 $hashes[$row->oi_archive_name] = $props[
'sha1'];
2212 $hashes[$row->oi_archive_name] =
false;
2215 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2220 $missing = array_diff_key( $this->srcRels,
$hashes );
2222 foreach ( $missing
as $name => $rel ) {
2223 $this->status->error(
'filedelete-old-unregistered',
$name );
2228 $this->status->error(
'filedelete-missing', $this->srcRels[
$name] );
2238 $dbw = $this->
file->repo->getMasterDB();
2239 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2240 $encUserId = $dbw->addQuotes( $this->
user->getId() );
2241 $encReason = $dbw->addQuotes( $this->reason );
2242 $encGroup = $dbw->addQuotes(
'deleted' );
2243 $ext = $this->
file->getExtension();
2244 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2245 $encExt = $dbw->addQuotes( $dotExt );
2249 if ( $this->suppress ) {
2252 $bitfield =
'oi_deleted';
2255 if ( $deleteCurrent ) {
2260 'fa_storage_group' => $encGroup,
2261 'fa_storage_key' => $dbw->conditional(
2262 [
'img_sha1' =>
'' ],
2263 $dbw->addQuotes(
'' ),
2264 $dbw->buildConcat( [
"img_sha1", $encExt ] )
2266 'fa_deleted_user' => $encUserId,
2267 'fa_deleted_timestamp' => $encTimestamp,
2268 'fa_deleted_reason' => $encReason,
2269 'fa_deleted' => $this->suppress ? $bitfield : 0,
2270 'fa_name' =>
'img_name',
2271 'fa_archive_name' =>
'NULL',
2272 'fa_size' =>
'img_size',
2273 'fa_width' =>
'img_width',
2274 'fa_height' =>
'img_height',
2275 'fa_metadata' =>
'img_metadata',
2276 'fa_bits' =>
'img_bits',
2277 'fa_media_type' =>
'img_media_type',
2278 'fa_major_mime' =>
'img_major_mime',
2279 'fa_minor_mime' =>
'img_minor_mime',
2280 'fa_description' =>
'img_description',
2281 'fa_user' =>
'img_user',
2282 'fa_user_text' =>
'img_user_text',
2283 'fa_timestamp' =>
'img_timestamp',
2284 'fa_sha1' =>
'img_sha1'
2286 [
'img_name' => $this->
file->getName() ],
2291 if ( count( $oldRels ) ) {
2292 $res = $dbw->select(
2296 'oi_name' => $this->
file->getName(),
2297 'oi_archive_name' => array_keys( $oldRels )
2303 foreach (
$res as $row ) {
2306 'fa_storage_group' =>
'deleted',
2307 'fa_storage_key' => ( $row->oi_sha1 ===
'' )
2309 :
"{$row->oi_sha1}{$dotExt}",
2310 'fa_deleted_user' => $this->
user->getId(),
2311 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2314 'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2315 'fa_name' => $row->oi_name,
2316 'fa_archive_name' => $row->oi_archive_name,
2317 'fa_size' => $row->oi_size,
2318 'fa_width' => $row->oi_width,
2319 'fa_height' => $row->oi_height,
2320 'fa_metadata' => $row->oi_metadata,
2321 'fa_bits' => $row->oi_bits,
2322 'fa_media_type' => $row->oi_media_type,
2323 'fa_major_mime' => $row->oi_major_mime,
2324 'fa_minor_mime' => $row->oi_minor_mime,
2325 'fa_description' => $row->oi_description,
2326 'fa_user' => $row->oi_user,
2327 'fa_user_text' => $row->oi_user_text,
2328 'fa_timestamp' => $row->oi_timestamp,
2329 'fa_sha1' => $row->oi_sha1
2333 $dbw->insert(
'filearchive', $rowsInsert, __METHOD__ );
2338 $dbw = $this->
file->repo->getMasterDB();
2341 if ( count( $oldRels ) ) {
2342 $dbw->delete(
'oldimage',
2344 'oi_name' => $this->
file->getName(),
2345 'oi_archive_name' => array_keys( $oldRels )
2349 if ( $deleteCurrent ) {
2350 $dbw->delete(
'image', [
'img_name' => $this->
file->getName() ], __METHOD__ );
2359 $repo = $this->
file->getRepo();
2360 $this->
file->lock();
2364 $this->deletionBatch = [];
2365 $ext = $this->
file->getExtension();
2366 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2368 foreach ( $this->srcRels
as $name => $srcRel ) {
2372 $key = $hash . $dotExt;
2373 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2374 $this->deletionBatch[
$name] = [ $srcRel, $dstRel ];
2378 if ( !$repo->hasSha1Storage() ) {
2382 if ( !$checkStatus->isGood() ) {
2383 $this->status->merge( $checkStatus );
2386 $this->deletionBatch = $checkStatus->value;
2389 $status = $this->
file->repo->deleteBatch( $this->deletionBatch );
2391 $this->status->merge(
$status );
2395 if ( !$this->status->isOK() ) {
2397 $this->
file->unlock();
2408 $this->
file->unlock();
2419 $files = $newBatch = [];
2422 list( $src, ) = $batchItem;
2423 $files[$src] = $this->
file->repo->getVirtualUrl(
'public' ) .
'/' . rawurlencode( $src );
2426 $result = $this->
file->repo->fileExistsBatch( $files );
2427 if ( in_array(
null,
$result,
true ) ) {
2428 return Status::newFatal(
'backend-fail-internal',
2429 $this->
file->repo->getBackend()->getName() );
2433 if (
$result[$batchItem[0]] ) {
2434 $newBatch[] = $batchItem;
2438 return Status::newGood( $newBatch );
2442# ------------------------------------------------------------------------------
2470 $this->cleanupBatch = $this->ids = [];
2480 $this->ids[] = $fa_id;
2488 $this->ids = array_merge( $this->ids,
$ids );
2510 $repo = $this->
file->getRepo();
2511 if ( !$this->all && !$this->ids ) {
2513 return $repo->newGood();
2516 $lockOwnsTrx = $this->
file->lock();
2518 $dbw = $this->
file->repo->getMasterDB();
2521 $exists = (bool)$dbw->selectField(
'image',
'1',
2522 [
'img_name' => $this->file->getName() ],
2527 $lockOwnsTrx ? [] : [
'LOCK IN SHARE MODE' ]
2532 $conditions = [
'fa_name' => $this->
file->getName() ];
2534 if ( !$this->all ) {
2543 [
'ORDER BY' =>
'fa_timestamp DESC' ]
2549 $insertCurrent =
false;
2555 $idsPresent[] = $row->fa_id;
2557 if ( $row->fa_name != $this->file->getName() ) {
2558 $status->error(
'undelete-filename-mismatch',
$wgLang->timeanddate( $row->fa_timestamp ) );
2563 if ( $row->fa_storage_key ==
'' ) {
2565 $status->error(
'undelete-bad-store-key',
$wgLang->timeanddate( $row->fa_timestamp ) );
2570 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2571 $row->fa_storage_key;
2572 $deletedUrl = $repo->getVirtualUrl() .
'/deleted/' . $deletedRel;
2574 if ( isset( $row->fa_sha1 ) ) {
2575 $sha1 = $row->fa_sha1;
2582 if ( strlen( $sha1 ) == 32 && $sha1[0] ==
'0' ) {
2583 $sha1 = substr( $sha1, 1 );
2586 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime ==
'unknown'
2587 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime ==
'unknown'
2588 || is_null( $row->fa_media_type ) || $row->fa_media_type ==
'UNKNOWN'
2589 || is_null( $row->fa_metadata )
2596 'minor_mime' => $row->fa_minor_mime,
2597 'major_mime' => $row->fa_major_mime,
2598 'media_type' => $row->fa_media_type,
2599 'metadata' => $row->fa_metadata
2603 if ( $first && !$exists ) {
2605 $destRel = $this->
file->getRel();
2607 'img_name' => $row->fa_name,
2608 'img_size' => $row->fa_size,
2609 'img_width' => $row->fa_width,
2610 'img_height' => $row->fa_height,
2611 'img_metadata' => $props[
'metadata'],
2612 'img_bits' => $row->fa_bits,
2613 'img_media_type' => $props[
'media_type'],
2614 'img_major_mime' => $props[
'major_mime'],
2615 'img_minor_mime' => $props[
'minor_mime'],
2616 'img_description' => $row->fa_description,
2617 'img_user' => $row->fa_user,
2618 'img_user_text' => $row->fa_user_text,
2619 'img_timestamp' => $row->fa_timestamp,
2624 if ( !$this->unsuppress && $row->fa_deleted ) {
2625 $status->fatal(
'undeleterevdel' );
2626 $this->
file->unlock();
2630 $archiveName = $row->fa_archive_name;
2632 if ( $archiveName ==
'' ) {
2636 $timestamp =
wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2639 $archiveName =
wfTimestamp( TS_MW, $timestamp ) .
'!' . $row->fa_name;
2641 }
while ( isset( $archiveNames[$archiveName] ) );
2644 $archiveNames[$archiveName] =
true;
2645 $destRel = $this->
file->getArchiveRel( $archiveName );
2647 'oi_name' => $row->fa_name,
2648 'oi_archive_name' => $archiveName,
2649 'oi_size' => $row->fa_size,
2650 'oi_width' => $row->fa_width,
2651 'oi_height' => $row->fa_height,
2652 'oi_bits' => $row->fa_bits,
2653 'oi_description' => $row->fa_description,
2654 'oi_user' => $row->fa_user,
2655 'oi_user_text' => $row->fa_user_text,
2656 'oi_timestamp' => $row->fa_timestamp,
2657 'oi_metadata' => $props[
'metadata'],
2658 'oi_media_type' => $props[
'media_type'],
2659 'oi_major_mime' => $props[
'major_mime'],
2660 'oi_minor_mime' => $props[
'minor_mime'],
2661 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2662 'oi_sha1' => $sha1 ];
2665 $deleteIds[] = $row->fa_id;
2671 $storeBatch[] = [ $deletedUrl,
'public', $destRel ];
2672 $this->cleanupBatch[] = $row->fa_storage_key;
2681 $missingIds = array_diff( $this->ids, $idsPresent );
2683 foreach ( $missingIds
as $id ) {
2684 $status->error(
'undelete-missing-filearchive', $id );
2687 if ( !$repo->hasSha1Storage() ) {
2690 if ( !$checkStatus->isGood() ) {
2691 $status->merge( $checkStatus );
2694 $storeBatch = $checkStatus->value;
2699 $status->merge( $storeStatus );
2706 $this->
file->unlock();
2718 if ( $insertCurrent ) {
2719 $dbw->insert(
'image', $insertCurrent, __METHOD__ );
2722 if ( $insertBatch ) {
2723 $dbw->insert(
'oldimage', $insertBatch, __METHOD__ );
2727 $dbw->delete(
'filearchive',
2728 [
'fa_id' => $deleteIds ],
2733 if (
$status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
2735 wfDebug( __METHOD__ .
" restored {$status->successCount} items, creating a new current\n" );
2739 $this->
file->purgeEverything();
2741 wfDebug( __METHOD__ .
" restored {$status->successCount} as archived versions\n" );
2742 $this->
file->purgeDescription();
2746 $this->
file->unlock();
2757 $files = $filteredTriplets = [];
2758 foreach ( $triplets
as $file ) {
2762 $result = $this->
file->repo->fileExistsBatch( $files );
2763 if ( in_array(
null,
$result,
true ) ) {
2764 return Status::newFatal(
'backend-fail-internal',
2765 $this->
file->repo->getBackend()->getName() );
2768 foreach ( $triplets
as $file ) {
2770 $filteredTriplets[] =
$file;
2774 return Status::newGood( $filteredTriplets );
2783 $files = $newBatch = [];
2784 $repo = $this->
file->repo;
2787 $files[
$file] = $repo->getVirtualUrl(
'deleted' ) .
'/' .
2788 rawurlencode( $repo->getDeletedHashPath(
$file ) .
$file );
2791 $result = $repo->fileExistsBatch( $files );
2795 $newBatch[] =
$file;
2808 if ( !$this->cleanupBatch ) {
2809 return $this->
file->repo->newGood();
2814 $status = $this->
file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2829 foreach ( $storeStatus->success
as $i =>
$success ) {
2834 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2841# ------------------------------------------------------------------------------
2872 $this->oldHash = $this->
file->repo->getHashPath( $this->
file->getName() );
2873 $this->newHash = $this->
file->repo->getHashPath( $this->target->getDBkey() );
2874 $this->oldName = $this->
file->getName();
2875 $this->newName = $this->
file->repo->getNameFromTitle( $this->target );
2876 $this->oldRel = $this->oldHash . $this->oldName;
2877 $this->newRel = $this->newHash . $this->newName;
2885 $this->cur = [ $this->oldRel, $this->newRel ];
2893 $archiveBase =
'archive';
2895 $this->oldCount = 0;
2898 $result = $this->db->select(
'oldimage',
2899 [
'oi_archive_name',
'oi_deleted' ],
2900 [
'oi_name' => $this->oldName ],
2902 [
'LOCK IN SHARE MODE' ]
2906 $archiveNames[] = $row->oi_archive_name;
2907 $oldName = $row->oi_archive_name;
2908 $bits = explode(
'!', $oldName, 2 );
2910 if ( count( $bits ) != 2 ) {
2911 wfDebug(
"Old file name missing !: '$oldName' \n" );
2915 list( $timestamp, $filename ) = $bits;
2917 if ( $this->oldName != $filename ) {
2918 wfDebug(
"Old file name doesn't match: '$oldName' \n" );
2930 "{$archiveBase}/{$this->oldHash}{$oldName}",
2931 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2935 return $archiveNames;
2943 $repo = $this->
file->repo;
2947 $this->
file->lock();
2952 if ( !$checkStatus->isGood() ) {
2953 $destFile->unlock();
2954 $this->
file->unlock();
2955 $status->merge( $checkStatus );
2958 $triplets = $checkStatus->value;
2962 if ( !$statusDb->isGood() ) {
2963 $destFile->unlock();
2964 $this->
file->unlock();
2965 $statusDb->setOK(
false );
2970 if ( !$repo->hasSha1Storage() ) {
2975 wfDebugLog(
'imagemove',
"Moved files for {$this->file->getName()}: " .
2976 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2977 if ( !$statusMove->isGood() ) {
2980 $destFile->unlock();
2981 $this->
file->unlock();
2982 wfDebugLog(
'imagemove',
"Error in moving files: "
2983 . $statusMove->getWikiText(
false,
false,
'en' ) );
2984 $statusMove->setOK(
false );
2988 $status->merge( $statusMove );
2994 wfDebugLog(
'imagemove',
"Renamed {$this->file->getName()} in database: " .
2995 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2997 $destFile->unlock();
2998 $this->
file->unlock();
3015 $repo = $this->
file->repo;
3022 [
'img_name' => $this->oldName ],
3026 $oldRowCount = $dbw->selectField(
3029 [
'oi_name' => $this->oldName ],
3034 if ( $hasCurrent ) {
3039 $status->successCount += $oldRowCount;
3043 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3045 $status->error(
'imageinvalidfilename' );
3061 [
'img_name' => $this->newName ],
3062 [
'img_name' => $this->oldName ],
3069 'oi_name' => $this->newName,
3070 'oi_archive_name = ' . $dbw->strreplace(
'oi_archive_name',
3071 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3073 [
'oi_name' => $this->oldName ],
3083 $moves = array_merge( [ $this->cur ], $this->olds );
3086 foreach ( $moves
as $move ) {
3088 $srcUrl = $this->
file->repo->getVirtualUrl() .
'/public/' . rawurlencode( $move[0] );
3089 $triplets[] = [ $srcUrl,
'public', $move[1] ];
3092 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3107 foreach ( $triplets
as $file ) {
3111 $result = $this->
file->repo->fileExistsBatch( $files );
3112 if ( in_array(
null,
$result,
true ) ) {
3113 return Status::newFatal(
'backend-fail-internal',
3114 $this->
file->repo->getBackend()->getName() );
3117 $filteredTriplets = [];
3118 foreach ( $triplets
as $file ) {
3120 $filteredTriplets[] =
$file;
3122 wfDebugLog(
'imagemove',
"File {$file[0]} does not exist" );
3126 return Status::newGood( $filteredTriplets );
3137 foreach ( $triplets
as $triplet ) {
3139 $pairs[] = [ $triplet[1], $triplet[2] ];
3142 $this->
file->repo->cleanupBatch( $pairs );
3153 foreach ( $triplets
as $triplet ) {
3154 $files[] = $triplet[0];
3157 $this->
file->repo->cleanupBatch( $files );
3163 parent::__construct(
3171 $wgOut->setStatusCode( 429 );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfLocalFile( $title)
Get an object referring to a locally registered file.
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.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
static selectFields()
Fields in the filearchive table.
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.
Handles purging appropriate CDN URLs given a title (or titles)
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
An error page which can definitely be safely rendered using the OutputPage.
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.
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
publish( $src, $dstRel, $archiveRel, $flags=0, array $options=[])
Copy or move a file either from a storage path, virtual URL, or file system path, into this repositor...
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
getBackend()
Get the file backend instance.
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.
isVectorized()
Return true if the file is vectorized.
purgeDescription()
Purge the file description page, but don't go after pages using the file.
getPath()
Return the storage path to the file.
getThumbPath( $suffix=false)
Get the path of the thumbnail directory, or a particular file if $suffix is specified.
getRel()
Get the path of the file relative to the public zone root.
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
getName()
Return the name of this file.
getThumbUrl( $suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
getRepo()
Returns the repository.
assertTitleDefined()
Assert that $this->title is set to a Title.
getArchiveThumbPath( $archiveName, $suffix=false)
Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified.
getTitle()
Return the associated title object.
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile.
string $name
The name of a file from its title object.
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
purgeEverything()
Purge metadata and all affected pages when the file is created, deleted, or majorly updated.
static splitMime( $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
getUrl()
Return the URL of the file.
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
userCan( $field, User $user=null)
Determine if the current user is allowed to view a particular field of this file, if it's marked as d...
getHandler()
Get a MediaHandler instance for this file.
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
getArchiveThumbUrl( $archiveName, $suffix=false)
Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified.
getHashPath()
Get the filename hash component of the directory including trailing slash, e.g.
Class to invalidate the HTML cache of all the pages linking to a given title.
static singleton( $wiki=false)
Internationalisation code.
static queueRecursiveJobsForTable(Title $title, $table)
Queue a RefreshLinks job for any table.
Helper class for file deletion.
addOlds()
Add the old versions of the image to the batch.
removeNonexistentFiles( $batch)
Removes non-existent files from a deletion batch.
array $deletionBatch
Items to be processed in the deletion batch.
__construct(File $file, $reason='', $suppress=false, $user=null)
bool $suppress
Whether to suppress all suppressable fields when deleting.
execute()
Run the transaction.
__construct(Status $status)
report()
Output a report about the exception and takes care of formatting.
Helper class for file movement.
cleanupTarget( $triplets)
Cleanup a partially moved array of triplets by deleting the target files.
addOlds()
Add the old versions of the image to the batch.
doDBUpdates()
Do the database updates and return a new Status indicating how many rows where updated.
getMoveTriplets()
Generate triplets for FileRepo::storeBatch().
__construct(File $file, Title $target)
execute()
Perform the move.
verifyDBUpdates()
Verify the database updates and return a new Status indicating how many rows would be updated.
removeNonexistentFiles( $triplets)
Removes non-existent files from move batch.
addCurrent()
Add the current image to the batch.
cleanupSource( $triplets)
Cleanup a fully moved array of triplets by deleting the source files.
Helper class for file undeletion.
execute()
Run the transaction, except the cleanup batch.
addIds( $ids)
Add a whole lot of files by ID.
addAll()
Add all revisions of the file.
bool $unsuppress
Whether to remove all settings for suppressed fields.
removeNonexistentFromCleanup( $batch)
Removes non-existent files from a cleanup batch.
array $ids
List of file IDs to restore.
addId( $fa_id)
Add a file by ID.
cleanup()
Delete unused files in the deleted zone.
removeNonexistentFiles( $triplets)
Removes non-existent files from a store batch.
cleanupFailedBatch( $storeStatus, $storeBatch)
Cleanup a failed batch.
bool $all
Add all revisions of the file.
array $cleanupBatch
List of file IDs to restore.
__construct(File $file, $unsuppress=false)
Class to represent a 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.
string $major_mime
Major MIME type.
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.
getMediaType()
Returns the type of the media in the file.
recordUpload( $oldver, $desc, $license='', $copyStatus='', $source='', $watch=false, $timestamp=false, User $user=null)
Record a file upload in the upload log and the image table.
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.
__destruct()
Clean up any dangling locks.
string $mime
MIME type, determined by MimeMagic::guessMimeType.
isMissing()
splitMime inherited
deleteOld( $archiveName, $reason, $suppress=false, $user=null)
Delete an old version of the file.
getDescriptionUrl()
isMultipage inherited
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
getMutableCacheKeys(WANObjectCache $cache)
static selectFields()
Fields in the image table.
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
loadFromDB( $flags=0)
Load file metadata from the DB.
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
bool $upgrading
Whether the row was scheduled to upgrade on load.
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
loadFromFile()
Load metadata from the file itself.
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
int $size
Size in bytes (loadFromXxx)
string $minor_mime
Minor MIME type.
int $user
User ID of uploader.
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
getThumbnails( $archiveName=false)
getTransformScript inherited
bool $upgraded
Whether the row was upgraded on load.
static newFromTitle( $title, $repo, $unused=null)
Create a LocalFile from a title Do not call this except from inside a repo class.
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
loadFieldsWithTimestamp( $dbr, $fname)
string $timestamp
Upload timestamp.
const ATOMIC_SECTION_LOCK
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.
int $historyRes
Result of the query for the file's history (nextHistoryLine)
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
getUser( $type='text')
Returns ID or name of user who uploaded the file.
decodeRow( $row, $prefix='img_')
Decode a row from the database (either object or array) to an array with timestamps and MIME types de...
string $description
Description of current revision of the file.
const CACHE_FIELD_MAX_LEN
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
getLazyCacheFields( $prefix='img_')
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.
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
string $sha1
SHA-1 base 36 content hash.
getHeight( $page=1)
Return the height of the image.
bool $locked
True if the image row is locked.
getDescriptionText( $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files,...
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
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.
string $user_text
User name of uploader.
string $metadata
Handler-specific metadata.
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
getCacheFields( $prefix='img_')
int $bits
Returned by getimagesize (loadFromXxx)
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, $user=null, $tags=[])
getHashPath inherited
bool $missing
True if file is not present in file system.
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
loadExtraFromDB()
Load lazy file metadata from the DB.
recordUpload2( $oldver, $comment, $pageText, $props=false, $timestamp=false, $user=null, $tags=[])
Record a file upload in the upload log and the image table.
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.
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
getMetadata()
Get handler-specific metadata.
__construct( $title, $repo)
Constructor.
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
bool $fileExists
Does the file exist on disk? (loadFromXxx)
static getHashFromKey( $key)
Gets the SHA1 hash from a storage key.
static makeParamBlob( $params)
Create a blob from a parameter array.
MimeMagic helper wrapper.
Class for creating log entries manually, to inject them into the database.
setTimestamp( $timestamp)
Set the timestamp of when the logged action took place.
static singleton()
Get an instance of this class.
static selectFields()
Fields in the oldimage table.
Set options of the Parser.
static singleton()
Get a RepoGroup instance.
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
static newNullRevision( $dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page's history.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
static factory(array $deltas)
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
isGood()
Returns whether the operation completed and didn't have any error or warnings.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Job for asynchronous rendering of thumbnails.
Represents a title within MediaWiki.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Multi-datacenter aware caching interface.
Special handling for file pages.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
when a variable name is used in a it is silently declared as a new local masking the global
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
the array() calling protocol came about after MediaWiki 1.4rc1.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers please use GetContentModels hook to make them known to core if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
it s the revision text itself In either if gzip is the revision text is gzipped $flags
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Allows to change the fields on the form that will be generated $name
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
processing should stop and the error should be shown to the user * false
returning false will NOT prevent logging $e
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
MediaWiki has optional support for a high distributed memory object caching system For general information on but for a larger site with heavy load
if(!isset( $args[0])) $lang