162 $file->loadFromRow( $row );
179 $conds = [
'img_sha1' =>
$sha1 ];
185 $row =
$dbr->selectRow(
186 $fileQuery[
'tables'], $fileQuery[
'fields'], $conds, __METHOD__, [], $fileQuery[
'joins']
209 throw new BadMethodCallException(
210 'Cannot use ' . __METHOD__
211 .
' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
227 'img_actor' =>
'NULL',
230 ] + MediaWikiServices::getInstance()->getCommentStore()->getFields(
'img_description' );
245 $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin(
'img_description' );
246 $actorQuery = ActorMigration::newMigration()->getJoin(
'img_user' );
248 'tables' => [
'image' ] + $commentQuery[
'tables'] + $actorQuery[
'tables'],
261 ] + $commentQuery[
'fields'] + $actorQuery[
'fields'],
262 'joins' => $commentQuery[
'joins'] + $actorQuery[
'joins'],
265 if ( in_array(
'omit-nonlazy',
$options,
true ) ) {
269 if ( !in_array(
'omit-lazy',
$options,
true ) ) {
271 $ret[
'fields'][] =
'img_metadata';
285 $this->metadata =
'';
286 $this->historyLine = 0;
287 $this->historyRes =
null;
288 $this->dataLoaded =
false;
289 $this->extraDataLoaded =
false;
301 return $this->repo->getSharedCacheKey(
'file', sha1( $this->
getName() ) );
317 $this->dataLoaded =
false;
318 $this->extraDataLoaded =
false;
327 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
328 $cachedValues =
$cache->getWithSetCallback(
332 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
338 if ( $this->fileExists ) {
339 foreach ( $fields
as $field ) {
340 $cacheVal[$field] = $this->$field;
343 $cacheVal[
'user'] = $this->
user ? $this->
user->getId() : 0;
344 $cacheVal[
'user_text'] = $this->
user ? $this->
user->getName() :
'';
345 $cacheVal[
'actor'] = $this->
user ? $this->
user->getActorId() :
null;
351 if ( isset( $cacheVal[$field] )
352 && strlen( $cacheVal[$field] ) > 100 * 1024
354 unset( $cacheVal[$field] );
358 if ( $this->fileExists ) {
361 $ttl = $cache::TTL_DAY;
369 $this->fileExists = $cachedValues[
'fileExists'];
370 if ( $this->fileExists ) {
374 $this->dataLoaded =
true;
375 $this->extraDataLoaded =
true;
377 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
390 $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
391 function ()
use ( $key ) {
392 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
402 $props = $this->repo->getFileProps( $this->
getVirtualUrl() );
413 if ( $prefix !==
'' ) {
414 throw new InvalidArgumentException(
415 __METHOD__ .
' with a non-empty prefix is no longer supported.'
423 return [
'size',
'width',
'height',
'bits',
'media_type',
424 'major_mime',
'minor_mime',
'metadata',
'timestamp',
'sha1',
'description' ];
435 if ( $prefix !==
'' ) {
436 throw new InvalidArgumentException(
437 __METHOD__ .
' with a non-empty prefix is no longer supported.'
442 return [
'metadata' ];
450 $fname = static::class .
'::' . __FUNCTION__;
452 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
453 $this->dataLoaded =
true;
454 $this->extraDataLoaded =
true;
456 $dbr = ( $flags & self::READ_LATEST )
457 ? $this->repo->getMasterDB()
458 : $this->repo->getReplicaDB();
460 $fileQuery = static::getQueryInfo();
461 $row =
$dbr->selectRow(
462 $fileQuery[
'tables'],
463 $fileQuery[
'fields'],
464 [
'img_name' => $this->
getName() ],
473 $this->fileExists =
false;
482 $fname = static::class .
'::' . __FUNCTION__;
484 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
485 $this->extraDataLoaded =
true;
497 throw new MWException(
"Could not find data for image '{$this->getName()}'." );
510 $row =
$dbr->selectRow(
511 $fileQuery[
'tables'],
512 $fileQuery[
'fields'],
514 'img_name' => $this->
getName(),
515 'img_timestamp' =>
$dbr->timestamp( $this->getTimestamp() ),
524 # File may have been uploaded over in the meantime; check the old versions
526 $row =
$dbr->selectRow(
527 $fileQuery[
'tables'],
528 $fileQuery[
'fields'],
531 'oi_timestamp' =>
$dbr->timestamp( $this->getTimestamp() ),
542 if ( isset( $fieldMap[
'metadata'] ) ) {
543 $fieldMap[
'metadata'] = $this->repo->getReplicaDB()->decodeBlob( $fieldMap[
'metadata'] );
556 $array = (
array)$row;
557 $prefixLength = strlen( $prefix );
560 if ( substr(
key( $array ), 0, $prefixLength ) !== $prefix ) {
561 throw new MWException( __METHOD__ .
': incorrect $prefix parameter' );
583 $decoded[
'description'] = MediaWikiServices::getInstance()->getCommentStore()
584 ->getComment(
'description', (
object)$decoded )->text;
587 $decoded[
'user'] ??
null,
588 $decoded[
'user_text'] ??
null,
589 $decoded[
'actor'] ??
null
591 unset( $decoded[
'user_text'], $decoded[
'actor'] );
593 $decoded[
'timestamp'] =
wfTimestamp( TS_MW, $decoded[
'timestamp'] );
595 $decoded[
'metadata'] = $this->repo->getReplicaDB()->decodeBlob( $decoded[
'metadata'] );
597 if ( empty( $decoded[
'major_mime'] ) ) {
598 $decoded[
'mime'] =
'unknown/unknown';
600 if ( !$decoded[
'minor_mime'] ) {
601 $decoded[
'minor_mime'] =
'unknown';
603 $decoded[
'mime'] = $decoded[
'major_mime'] .
'/' . $decoded[
'minor_mime'];
607 $decoded[
'sha1'] = rtrim( $decoded[
'sha1'],
"\0" );
613 foreach ( [
'size',
'width',
'height',
'bits' ]
as $field ) {
614 $decoded[$field] = +$decoded[$field];
627 $this->dataLoaded =
true;
628 $this->extraDataLoaded =
true;
630 $array = $this->
decodeRow( $row, $prefix );
636 $this->fileExists =
true;
644 if ( !$this->dataLoaded ) {
645 if ( $flags & self::READ_LATEST ) {
652 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
669 if ( is_null( $this->media_type ) || $this->mime ==
'image/svg' ) {
684 $this->upgrading =
true;
686 DeferredUpdates::addCallableUpdate(
function () {
687 $this->upgrading =
false;
712 # Don't destroy file info of missing files
713 if ( !$this->fileExists ) {
715 wfDebug( __METHOD__ .
": file does not exist, aborting\n" );
720 $dbw = $this->repo->getMasterDB();
728 wfDebug( __METHOD__ .
': upgrading ' . $this->
getName() .
" to the current schema\n" );
730 $dbw->update(
'image',
732 'img_size' => $this->size,
733 'img_width' => $this->
width,
734 'img_height' => $this->height,
735 'img_bits' => $this->bits,
736 'img_media_type' => $this->media_type,
737 'img_major_mime' => $major,
738 'img_minor_mime' => $minor,
739 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
740 'img_sha1' => $this->sha1,
742 [
'img_name' => $this->getName() ],
749 $this->upgraded =
true;
763 $this->dataLoaded =
true;
765 $fields[] =
'fileExists';
767 foreach ( $fields
as $field ) {
768 if ( isset( $info[$field] ) ) {
769 $this->$field = $info[$field];
773 if ( isset( $info[
'user'] ) || isset( $info[
'user_text'] ) || isset( $info[
'actor'] ) ) {
775 $info[
'user'] ??
null,
776 $info[
'user_text'] ??
null,
777 $info[
'actor'] ??
null
782 if ( isset( $info[
'major_mime'] ) ) {
783 $this->mime =
"{$info['major_mime']}/{$info['minor_mime']}";
784 } elseif ( isset( $info[
'mime'] ) ) {
785 $this->mime = $info[
'mime'];
805 if ( $this->missing ===
null ) {
834 return $dim[
'width'];
866 return $dim[
'height'];
887 if (
$type ===
'object' ) {
889 } elseif (
$type ===
'text' ) {
890 return $this->
user->getName();
891 } elseif (
$type ===
'id' ) {
892 return $this->
user->getId();
906 $pageId = $this->
title->getArticleID();
908 if ( $pageId !==
null ) {
909 $url = $this->repo->makeUrl( [
'curid' => $pageId ] );
910 if (
$url !==
false ) {
922 $this->
load( self::LOAD_ALL );
998 if ( $archiveName ) {
1004 $backend = $this->repo->getBackend();
1007 $iterator = $backend->getFileList( [
'dir' => $dir ] );
1008 foreach ( $iterator
as $file ) {
1040 DeferredUpdates::addUpdate(
1042 DeferredUpdates::PRESEND
1055 Hooks::run(
'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1058 $dir = array_shift( $files );
1080 array_shift(
$urls );
1083 if ( !empty(
$options[
'forThumbRefresh'] ) ) {
1091 Hooks::run(
'LocalFilePurgeThumbnails', [ $this,
false ] );
1094 $dir = array_shift( $files );
1118 [
'transformParams' => [
'width' => $size ] ]
1124 JobQueueGroup::singleton()->lazyPush( $jobs );
1134 $fileListDebug = strtr(
1135 var_export( $files,
true ),
1138 wfDebug( __METHOD__ .
": $fileListDebug\n" );
1142 if ( $this->repo->supportsSha1URLs() ) {
1143 $reference = $this->
getSha1();
1145 $reference = $this->
getName();
1148 # Check that the reference (filename or sha1) is part of the thumb name
1149 # This is a basic sanity check to avoid erasing unrelated directories
1150 if ( strpos(
$file, $reference ) !==
false
1151 || strpos(
$file,
"-thumbnail" ) !==
false
1153 $purgeList[] =
"{$dir}/{$file}";
1157 # Delete the thumbnails
1158 $this->repo->quickPurgeBatch( $purgeList );
1159 # Clear out the thumbnail directory if empty
1160 $this->repo->quickCleanDir( $dir );
1173 function getHistory( $limit =
null, $start =
null, $end =
null, $inc =
true ) {
1174 $dbr = $this->repo->getReplicaDB();
1177 $tables = $oldFileQuery[
'tables'];
1178 $fields = $oldFileQuery[
'fields'];
1179 $join_conds = $oldFileQuery[
'joins'];
1180 $conds = $opts = [];
1181 $eq = $inc ?
'=' :
'';
1182 $conds[] =
"oi_name = " .
$dbr->addQuotes( $this->
title->getDBkey() );
1185 $conds[] =
"oi_timestamp <$eq " .
$dbr->addQuotes(
$dbr->timestamp( $start ) );
1189 $conds[] =
"oi_timestamp >$eq " .
$dbr->addQuotes(
$dbr->timestamp( $end ) );
1193 $opts[
'LIMIT'] = $limit;
1197 $order = ( !$start && $end !==
null ) ?
'ASC' :
'DESC';
1198 $opts[
'ORDER BY'] =
"oi_timestamp $order";
1199 $opts[
'USE INDEX'] = [
'oldimage' =>
'oi_name_timestamp' ];
1203 Hooks::run(
'LocalFile::getHistory', [ &$localFile, &
$tables, &$fields,
1204 &$conds, &$opts, &$join_conds ] );
1206 $res =
$dbr->select(
$tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1209 foreach (
$res as $row ) {
1210 $r[] = $this->repo->newFileFromRow( $row );
1213 if ( $order ==
'ASC' ) {
1214 $r = array_reverse( $r );
1230 # Polymorphic function name to distinguish foreign and local fetches
1231 $fname = static::class .
'::' . __FUNCTION__;
1233 $dbr = $this->repo->getReplicaDB();
1235 if ( $this->historyLine == 0 ) {
1237 $this->historyRes =
$dbr->select( $fileQuery[
'tables'],
1238 $fileQuery[
'fields'] + [
1239 'oi_archive_name' =>
$dbr->addQuotes(
'' ),
1242 [
'img_name' => $this->title->getDBkey() ],
1248 if (
$dbr->numRows( $this->historyRes ) == 0 ) {
1249 $this->historyRes =
null;
1253 } elseif ( $this->historyLine == 1 ) {
1255 $this->historyRes =
$dbr->select(
1256 $fileQuery[
'tables'],
1257 $fileQuery[
'fields'],
1258 [
'oi_name' => $this->
title->getDBkey() ],
1260 [
'ORDER BY' =>
'oi_timestamp DESC' ],
1264 $this->historyLine++;
1266 return $dbr->fetchObject( $this->historyRes );
1273 $this->historyLine = 0;
1275 if ( !is_null( $this->historyRes ) ) {
1276 $this->historyRes =
null;
1313 function upload( $src, $comment, $pageText, $flags = 0, $props =
false,
1315 $createNullRevision =
true,
$revert =
false
1317 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1319 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1325 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1330 $props = $this->repo->getFileProps( $srcPath );
1332 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1333 $props = $mwProps->getPropsFromPath( $srcPath,
true );
1340 $metadata = Wikimedia\quietCall(
'unserialize', $props[
'metadata'] );
1352 $comment = trim( $comment );
1357 if (
$status->successCount >= 2 ) {
1373 $createNullRevision,
1376 if ( !$uploadStatus->isOK() ) {
1377 if ( $uploadStatus->hasMessage(
'filenotfound' ) ) {
1379 $status->fatal(
'filenotfound', $srcPath );
1381 $status->merge( $uploadStatus );
1437 $oldver, $comment, $pageText, $props =
false,
$timestamp =
false,
$user =
null, $tags = [],
1438 $createNullRevision =
true,
$revert =
false
1442 if ( is_null(
$user ) ) {
1447 $dbw = $this->repo->getMasterDB();
1449 # Imports or such might force a certain timestamp; otherwise we generate
1450 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1453 $allowTimeKludge =
true;
1455 $allowTimeKludge =
false;
1458 $props = $props ?: $this->repo->getFileProps( $this->
getVirtualUrl() );
1459 $props[
'description'] = $comment;
1466 # Fail now if the file isn't there
1467 if ( !$this->fileExists ) {
1468 wfDebug( __METHOD__ .
": File " . $this->
getRel() .
" went missing!\n" );
1470 return Status::newFatal(
'filenotfound', $this->
getRel() );
1473 $dbw->startAtomic( __METHOD__ );
1475 # Test to see if the row exists using INSERT IGNORE
1476 # This avoids race conditions by locking the row until the commit, and also
1477 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1478 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1479 $commentFields = $commentStore->insert( $dbw,
'img_description', $comment );
1480 $actorMigration = ActorMigration::newMigration();
1481 $actorFields = $actorMigration->getInsertValues( $dbw,
'img_user',
$user );
1482 $dbw->insert(
'image',
1484 'img_name' => $this->
getName(),
1485 'img_size' => $this->size,
1486 'img_width' => intval( $this->
width ),
1487 'img_height' => intval( $this->height ),
1488 'img_bits' => $this->bits,
1489 'img_media_type' => $this->media_type,
1490 'img_major_mime' => $this->major_mime,
1491 'img_minor_mime' => $this->minor_mime,
1493 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1494 'img_sha1' => $this->sha1
1495 ] + $commentFields + $actorFields,
1499 $reupload = ( $dbw->affectedRows() == 0 );
1502 $row = $dbw->selectRow(
1504 [
'img_timestamp',
'img_sha1' ],
1505 [
'img_name' => $this->
getName() ],
1507 [
'LOCK IN SHARE MODE' ]
1510 if ( $row && $row->img_sha1 === $this->sha1 ) {
1511 $dbw->endAtomic( __METHOD__ );
1512 wfDebug( __METHOD__ .
": File " . $this->
getRel() .
" already exists!\n" );
1517 if ( $allowTimeKludge ) {
1518 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1519 $lUnixtime = $row ?
wfTimestamp( TS_UNIX, $row->img_timestamp ) :
false;
1520 # Avoid a timestamp that is not newer than the last version
1521 # TODO: the image/oldimage tables should be like page/revision with an ID field
1524 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1531 'oi_name' =>
'img_name',
1532 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1533 'oi_size' =>
'img_size',
1534 'oi_width' =>
'img_width',
1535 'oi_height' =>
'img_height',
1536 'oi_bits' =>
'img_bits',
1537 'oi_description_id' =>
'img_description_id',
1538 'oi_timestamp' =>
'img_timestamp',
1539 'oi_metadata' =>
'img_metadata',
1540 'oi_media_type' =>
'img_media_type',
1541 'oi_major_mime' =>
'img_major_mime',
1542 'oi_minor_mime' =>
'img_minor_mime',
1543 'oi_sha1' =>
'img_sha1',
1548 $fields[
'oi_user'] =
'img_user';
1549 $fields[
'oi_user_text'] =
'img_user_text';
1552 $fields[
'oi_actor'] =
'img_actor';
1561 $res = $dbw->select(
1563 [
'img_name',
'img_user',
'img_user_text' ],
1564 [
'img_name' => $this->
getName(),
'img_actor' => 0 ],
1567 foreach (
$res as $row ) {
1568 $actorId =
User::newFromAnyId( $row->img_user, $row->img_user_text,
null )->getActorId( $dbw );
1571 [
'img_actor' => $actorId ],
1572 [
'img_name' => $row->img_name,
'img_actor' => 0 ],
1578 # (T36993) Note: $oldver can be empty here, if the previous
1579 # version of the file was broken. Allow registration of the new
1580 # version to continue anyway, because that's better than having
1581 # an image that's not fixable by user operations.
1582 # Collision, this is an update of a file
1583 # Insert previous contents into oldimage
1584 $dbw->insertSelect(
'oldimage',
$tables, $fields,
1585 [
'img_name' => $this->
getName() ], __METHOD__, [], [], $joins );
1587 # Update the current image row
1588 $dbw->update(
'image',
1590 'img_size' => $this->size,
1591 'img_width' => intval( $this->
width ),
1592 'img_height' => intval( $this->height ),
1593 'img_bits' => $this->bits,
1594 'img_media_type' => $this->media_type,
1595 'img_major_mime' => $this->major_mime,
1596 'img_minor_mime' => $this->minor_mime,
1598 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1599 'img_sha1' => $this->sha1
1600 ] + $commentFields + $actorFields,
1601 [
'img_name' => $this->getName() ],
1607 $descId = $descTitle->getArticleID();
1609 $wikiPage->setFile( $this );
1613 $logAction =
'revert';
1614 } elseif ( $reupload ===
true ) {
1615 $logAction =
'overwrite';
1617 $logAction =
'upload';
1621 $logEntry->setTimestamp( $this->timestamp );
1622 $logEntry->setPerformer(
$user );
1623 $logEntry->setComment( $comment );
1624 $logEntry->setTarget( $descTitle );
1627 $logEntry->setParameters(
1629 'img_sha1' => $this->sha1,
1639 $logId = $logEntry->insert();
1641 if ( $descTitle->exists() ) {
1644 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1645 $editSummary = $formatter->getPlainActionText();
1654 if ( $nullRevision ) {
1655 $nullRevision->insertOn( $dbw );
1657 'NewRevisionFromEditComplete',
1658 [ $wikiPage, $nullRevision, $nullRevision->getParentId(),
$user ]
1660 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1662 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1665 $newPageContent =
null;
1668 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1671 # Defer purges, page creation, and link updates in case they error out.
1672 # The most important thing is that files and the DB registry stay synced.
1673 $dbw->endAtomic( __METHOD__ );
1676 # Do some cache purges after final commit so that:
1677 # a) Changes are more likely to be seen post-purge
1678 # b) They won't cause rollback of the log publish/update above
1679 DeferredUpdates::addUpdate(
1684 $reupload, $wikiPage, $newPageContent, $comment,
$user,
1685 $logEntry, $logId, $descId, $tags,
$fname
1687 # Update memcache after the commit
1690 $updateLogPage =
false;
1691 if ( $newPageContent ) {
1692 # New file page; create the description page.
1693 # There's already a log entry, so don't make a second RC entry
1694 # CDN and file cache for the description page are purged by doEditContent.
1695 $status = $wikiPage->doEditContent(
1703 if ( isset(
$status->value[
'revision'] ) ) {
1707 $logEntry->setAssociatedRevId(
$rev->getId() );
1711 if ( isset(
$status->value[
'revision'] ) ) {
1714 $updateLogPage =
$rev->getPage();
1717 # Existing file page: invalidate description page cache
1718 $wikiPage->getTitle()->invalidateCache();
1719 $wikiPage->getTitle()->purgeSquid();
1720 # Allow the new file version to be patrolled from the page footer
1724 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1725 # but setAssociatedRevId() wasn't called at that point yet...
1726 $logParams = $logEntry->getParameters();
1727 $logParams[
'associated_rev_id'] = $logEntry->getAssociatedRevId();
1729 if ( $updateLogPage ) {
1730 # Also log page, in case where we just created it above
1731 $update[
'log_page'] = $updateLogPage;
1733 $this->
getRepo()->getMasterDB()->update(
1736 [
'log_id' => $logId ],
1739 $this->
getRepo()->getMasterDB()->insert(
1742 'ls_field' =>
'associated_rev_id',
1743 'ls_value' => $logEntry->getAssociatedRevId(),
1744 'ls_log_id' => $logId,
1749 # Add change tags, if any
1751 $logEntry->setTags( $tags );
1754 # Uploads can be patrolled
1755 $logEntry->setIsPatrollable(
true );
1757 # Now that the log entry is up-to-date, make an RC entry.
1758 $logEntry->publish( $logId );
1760 # Run hook for other updates (typically more cache purging)
1761 Hooks::run(
'FileUpload', [ $this, $reupload, !$newPageContent ] );
1764 # Delete old thumbnails
1766 # Remove the old file from the CDN cache
1767 DeferredUpdates::addUpdate(
1769 DeferredUpdates::PRESEND
1772 # Update backlink pages pointing to this title if created
1773 LinksUpdate::queueRecursiveJobsForTable(
1784 DeferredUpdates::PRESEND
1788 # This is a new file, so update the image count
1789 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
'images' => 1 ] ) );
1792 # Invalidate cache for all pages using this file
1793 DeferredUpdates::addUpdate(
1797 return Status::newGood();
1835 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1844 if ( $this->
isOld() ) {
1845 $archiveRel = $dstRel;
1846 $archiveName = basename( $archiveRel );
1858 $dst = $wrapperBackend->getPathForSHA1(
$sha1 );
1865 $status->value = $archiveName;
1871 if (
$status->value ==
'new' ) {
1874 $status->value = $archiveName;
1900 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1904 wfDebugLog(
'imagemove',
"Got request to move {$this->name} to " . $target->getText() );
1909 $archiveNames =
$batch->addOlds();
1913 wfDebugLog(
'imagemove',
"Finished moving {$this->name}" );
1919 DeferredUpdates::addUpdate(
1921 $this->
getRepo()->getMasterDB(),
1923 function ()
use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1924 $oldTitleFile->purgeEverything();
1925 foreach ( $archiveNames
as $archiveName ) {
1926 $oldTitleFile->purgeOldThumbnails( $archiveName );
1928 $newTitleFile->purgeEverything();
1931 DeferredUpdates::PRESEND
1936 $this->
title = $target;
1938 unset( $this->
name );
1939 unset( $this->hashPath );
1958 function delete( $reason, $suppress =
false,
$user =
null ) {
1959 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1968 $archiveNames =
$batch->addOlds();
1973 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
'images' => -1 ] ) );
1977 DeferredUpdates::addUpdate(
1979 $this->
getRepo()->getMasterDB(),
1981 function ()
use ( $archiveNames ) {
1983 foreach ( $archiveNames
as $archiveName ) {
1988 DeferredUpdates::PRESEND
1993 foreach ( $archiveNames
as $archiveName ) {
1996 DeferredUpdates::addUpdate(
new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
2017 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
2024 $batch->addOld( $archiveName );
2033 DeferredUpdates::addUpdate(
2035 DeferredUpdates::PRESEND
2052 function restore( $versions = [], $unsuppress =
false ) {
2053 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
2063 $batch->addIds( $versions );
2067 $cleanupStatus =
$batch->cleanup();
2068 $cleanupStatus->successCount = 0;
2069 $cleanupStatus->failCount = 0;
2070 $status->merge( $cleanupStatus );
2087 return $this->
title->getLocalURL();
2099 $store = MediaWikiServices::getInstance()->getRevisionStore();
2100 $revision = $store->getRevisionByTitle( $this->
title, 0, Revision::READ_NORMAL );
2105 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2106 $rendered = $renderer->getRenderedRevision( $revision,
new ParserOptions(
null,
$lang ) );
2113 $pout = $rendered->getRevisionParserOutput();
2114 return $pout->getText();
2124 if ( $audience == self::FOR_PUBLIC && $this->
isDeleted( self::DELETED_COMMENT ) ) {
2126 } elseif ( $audience == self::FOR_THIS_USER
2151 if ( $this->descriptionTouched ===
null ) {
2153 'page_namespace' => $this->
title->getNamespace(),
2154 'page_title' => $this->
title->getDBkey()
2156 $touched = $this->repo->getReplicaDB()->selectField(
'page',
'page_touched', $cond, __METHOD__ );
2157 $this->descriptionTouched = $touched ?
wfTimestamp( TS_MW, $touched ) :
false;
2169 if ( $this->sha1 ==
'' && $this->fileExists ) {
2172 $this->sha1 = $this->repo->getFileSha1( $this->
getPath() );
2173 if ( !
wfReadOnly() && strval( $this->sha1 ) !=
'' ) {
2174 $dbw = $this->repo->getMasterDB();
2175 $dbw->update(
'image',
2176 [
'img_sha1' => $this->sha1 ],
2177 [
'img_name' => $this->
getName() ],
2195 return $this->extraDataLoaded
2204 return Status::wrap( $this->
getRepo()->getBackend()->lockFiles(
2205 [ $this->
getPath() ], LockManager::LOCK_EX, 10
2214 return Status::wrap( $this->
getRepo()->getBackend()->unlockFiles(
2215 [ $this->
getPath() ], LockManager::LOCK_EX
2229 if ( !$this->locked ) {
2230 $logger = LoggerFactory::getInstance(
'LocalFile' );
2232 $dbw = $this->repo->getMasterDB();
2233 $makesTransaction = !$dbw->trxLevel();
2234 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2240 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2241 $logger->warning(
"Failed to lock '{file}'", [
'file' => $this->
name ] );
2247 $dbw->onTransactionResolution(
2248 function ()
use ( $logger ) {
2251 $logger->error(
"Failed to unlock '{file}'", [
'file' => $this->
name ] );
2257 $this->lockedOwnTrx = $makesTransaction;
2274 if ( $this->locked ) {
2276 if ( !$this->locked ) {
2277 $dbw = $this->repo->getMasterDB();
2278 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2279 $this->lockedOwnTrx =
false;
2288 return $this->
getRepo()->newFatal(
'filereadonlyerror', $this->
getName(),
2300# ------------------------------------------------------------------------------
2345 $this->
user = $wgUser;
2347 $this->status =
$file->repo->newGood();
2351 $this->srcRels[
'.'] = $this->
file->getRel();
2358 $this->srcRels[$oldName] = $this->
file->getArchiveRel( $oldName );
2359 $this->archiveUrls[] = $this->
file->getArchiveUrl( $oldName );
2369 $dbw = $this->
file->repo->getMasterDB();
2370 $result = $dbw->select(
'oldimage',
2371 [
'oi_archive_name' ],
2372 [
'oi_name' => $this->
file->getName() ],
2377 $this->
addOld( $row->oi_archive_name );
2378 $archiveNames[] = $row->oi_archive_name;
2381 return $archiveNames;
2388 if ( !isset( $this->srcRels[
'.'] ) ) {
2390 $deleteCurrent =
false;
2393 unset( $oldRels[
'.'] );
2394 $deleteCurrent =
true;
2397 return [ $oldRels, $deleteCurrent ];
2407 if ( $deleteCurrent ) {
2411 if ( count( $oldRels ) ) {
2412 $dbw = $this->
file->repo->getMasterDB();
2413 $res = $dbw->select(
2415 [
'oi_archive_name',
'oi_sha1' ],
2416 [
'oi_archive_name' => array_keys( $oldRels ),
2417 'oi_name' => $this->
file->getName() ],
2421 foreach (
$res as $row ) {
2422 if ( rtrim( $row->oi_sha1,
"\0" ) ===
'' ) {
2424 $oldUrl = $this->
file->getArchiveVirtualUrl( $row->oi_archive_name );
2425 $props = $this->
file->repo->getFileProps( $oldUrl );
2427 if ( $props[
'fileExists'] ) {
2429 $dbw->update(
'oldimage',
2430 [
'oi_sha1' => $props[
'sha1'] ],
2431 [
'oi_name' => $this->
file->getName(),
'oi_archive_name' => $row->oi_archive_name ],
2433 $hashes[$row->oi_archive_name] = $props[
'sha1'];
2435 $hashes[$row->oi_archive_name] =
false;
2438 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2443 $missing = array_diff_key( $this->srcRels,
$hashes );
2445 foreach ( $missing
as $name => $rel ) {
2446 $this->status->error(
'filedelete-old-unregistered',
$name );
2451 $this->status->error(
'filedelete-missing', $this->srcRels[
$name] );
2463 $dbw = $this->
file->repo->getMasterDB();
2465 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2466 $actorMigration = ActorMigration::newMigration();
2468 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2469 $encUserId = $dbw->addQuotes( $this->
user->getId() );
2470 $encGroup = $dbw->addQuotes(
'deleted' );
2471 $ext = $this->
file->getExtension();
2472 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2473 $encExt = $dbw->addQuotes( $dotExt );
2477 if ( $this->suppress ) {
2480 $bitfield =
'oi_deleted';
2483 if ( $deleteCurrent ) {
2486 'fa_storage_group' => $encGroup,
2487 'fa_storage_key' => $dbw->conditional(
2488 [
'img_sha1' =>
'' ],
2489 $dbw->addQuotes(
'' ),
2490 $dbw->buildConcat( [
"img_sha1", $encExt ] )
2492 'fa_deleted_user' => $encUserId,
2493 'fa_deleted_timestamp' => $encTimestamp,
2494 'fa_deleted' => $this->suppress ? $bitfield : 0,
2495 'fa_name' =>
'img_name',
2496 'fa_archive_name' =>
'NULL',
2497 'fa_size' =>
'img_size',
2498 'fa_width' =>
'img_width',
2499 'fa_height' =>
'img_height',
2500 'fa_metadata' =>
'img_metadata',
2501 'fa_bits' =>
'img_bits',
2502 'fa_media_type' =>
'img_media_type',
2503 'fa_major_mime' =>
'img_major_mime',
2504 'fa_minor_mime' =>
'img_minor_mime',
2505 'fa_description_id' =>
'img_description_id',
2506 'fa_timestamp' =>
'img_timestamp',
2507 'fa_sha1' =>
'img_sha1'
2511 $fields += array_map(
2512 [ $dbw,
'addQuotes' ],
2513 $commentStore->insert( $dbw,
'fa_deleted_reason', $this->reason )
2517 $fields[
'fa_user'] =
'img_user';
2518 $fields[
'fa_user_text'] =
'img_user_text';
2521 $fields[
'fa_actor'] =
'img_actor';
2530 $res = $dbw->select(
2532 [
'img_name',
'img_user',
'img_user_text' ],
2533 [
'img_name' => $this->
file->getName(),
'img_actor' => 0 ],
2536 foreach (
$res as $row ) {
2537 $actorId =
User::newFromAnyId( $row->img_user, $row->img_user_text,
null )->getActorId( $dbw );
2540 [
'img_actor' => $actorId ],
2541 [
'img_name' => $row->img_name,
'img_actor' => 0 ],
2547 $dbw->insertSelect(
'filearchive',
$tables, $fields,
2548 [
'img_name' => $this->
file->getName() ], __METHOD__, [], [], $joins );
2551 if ( count( $oldRels ) ) {
2553 $res = $dbw->select(
2554 $fileQuery[
'tables'],
2555 $fileQuery[
'fields'],
2557 'oi_name' => $this->
file->getName(),
2558 'oi_archive_name' => array_keys( $oldRels )
2565 if (
$res->numRows() ) {
2566 $reason = $commentStore->createComment( $dbw, $this->reason );
2567 foreach (
$res as $row ) {
2568 $comment = $commentStore->getComment(
'oi_description', $row );
2572 'fa_storage_group' =>
'deleted',
2573 'fa_storage_key' => ( $row->oi_sha1 ===
'' )
2575 :
"{$row->oi_sha1}{$dotExt}",
2576 'fa_deleted_user' => $this->
user->getId(),
2577 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2579 'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2580 'fa_name' => $row->oi_name,
2581 'fa_archive_name' => $row->oi_archive_name,
2582 'fa_size' => $row->oi_size,
2583 'fa_width' => $row->oi_width,
2584 'fa_height' => $row->oi_height,
2585 'fa_metadata' => $row->oi_metadata,
2586 'fa_bits' => $row->oi_bits,
2587 'fa_media_type' => $row->oi_media_type,
2588 'fa_major_mime' => $row->oi_major_mime,
2589 'fa_minor_mime' => $row->oi_minor_mime,
2590 'fa_timestamp' => $row->oi_timestamp,
2591 'fa_sha1' => $row->oi_sha1
2592 ] + $commentStore->insert( $dbw,
'fa_deleted_reason',
$reason )
2593 + $commentStore->insert( $dbw,
'fa_description', $comment )
2594 + $actorMigration->getInsertValues( $dbw,
'fa_user',
$user );
2598 $dbw->insert(
'filearchive', $rowsInsert, __METHOD__ );
2603 $dbw = $this->
file->repo->getMasterDB();
2606 if ( count( $oldRels ) ) {
2607 $dbw->delete(
'oldimage',
2609 'oi_name' => $this->
file->getName(),
2610 'oi_archive_name' => array_keys( $oldRels )
2614 if ( $deleteCurrent ) {
2615 $dbw->delete(
'image', [
'img_name' => $this->
file->getName() ], __METHOD__ );
2624 $repo = $this->
file->getRepo();
2625 $this->
file->lock();
2629 $this->deletionBatch = [];
2630 $ext = $this->
file->getExtension();
2631 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2633 foreach ( $this->srcRels
as $name => $srcRel ) {
2637 $key = $hash . $dotExt;
2638 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2639 $this->deletionBatch[
$name] = [ $srcRel, $dstRel ];
2643 if ( !$repo->hasSha1Storage() ) {
2647 if ( !$checkStatus->isGood() ) {
2648 $this->status->merge( $checkStatus );
2651 $this->deletionBatch = $checkStatus->value;
2654 $status = $this->
file->repo->deleteBatch( $this->deletionBatch );
2656 $this->status->merge(
$status );
2660 if ( !$this->status->isOK() ) {
2662 $this->
file->unlock();
2673 $this->
file->unlock();
2684 $files = $newBatch = [];
2687 list( $src, ) = $batchItem;
2688 $files[$src] = $this->
file->repo->getVirtualUrl(
'public' ) .
'/' . rawurlencode( $src );
2691 $result = $this->
file->repo->fileExistsBatch( $files );
2692 if ( in_array(
null,
$result,
true ) ) {
2693 return Status::newFatal(
'backend-fail-internal',
2694 $this->
file->repo->getBackend()->getName() );
2698 if (
$result[$batchItem[0]] ) {
2699 $newBatch[] = $batchItem;
2703 return Status::newGood( $newBatch );
2707# ------------------------------------------------------------------------------
2735 $this->cleanupBatch = [];
2745 $this->ids[] = $fa_id;
2753 $this->ids = array_merge( $this->ids,
$ids );
2775 $repo = $this->
file->getRepo();
2776 if ( !$this->all && !$this->ids ) {
2778 return $repo->newGood();
2781 $lockOwnsTrx = $this->
file->lock();
2783 $dbw = $this->
file->repo->getMasterDB();
2785 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2786 $actorMigration = ActorMigration::newMigration();
2790 $exists = (bool)$dbw->selectField(
'image',
'1',
2791 [
'img_name' => $this->file->getName() ],
2796 $lockOwnsTrx ? [] : [
'LOCK IN SHARE MODE' ]
2801 $conditions = [
'fa_name' => $this->
file->getName() ];
2803 if ( !$this->all ) {
2809 $arFileQuery[
'tables'],
2810 $arFileQuery[
'fields'],
2813 [
'ORDER BY' =>
'fa_timestamp DESC' ],
2814 $arFileQuery[
'joins']
2820 $insertCurrent =
false;
2826 $idsPresent[] = $row->fa_id;
2828 if ( $row->fa_name != $this->file->getName() ) {
2829 $status->error(
'undelete-filename-mismatch',
$wgLang->timeanddate( $row->fa_timestamp ) );
2834 if ( $row->fa_storage_key ==
'' ) {
2836 $status->error(
'undelete-bad-store-key',
$wgLang->timeanddate( $row->fa_timestamp ) );
2841 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2842 $row->fa_storage_key;
2843 $deletedUrl = $repo->getVirtualUrl() .
'/deleted/' . $deletedRel;
2845 if ( isset( $row->fa_sha1 ) ) {
2846 $sha1 = $row->fa_sha1;
2853 if ( strlen( $sha1 ) == 32 && $sha1[0] ==
'0' ) {
2854 $sha1 = substr( $sha1, 1 );
2857 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime ==
'unknown'
2858 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime ==
'unknown'
2859 || is_null( $row->fa_media_type ) || $row->fa_media_type ==
'UNKNOWN'
2860 || is_null( $row->fa_metadata )
2867 'minor_mime' => $row->fa_minor_mime,
2868 'major_mime' => $row->fa_major_mime,
2869 'media_type' => $row->fa_media_type,
2870 'metadata' => $row->fa_metadata
2874 $comment = $commentStore->getComment(
'fa_description', $row );
2876 if ( $first && !$exists ) {
2878 $destRel = $this->
file->getRel();
2879 $commentFields = $commentStore->insert( $dbw,
'img_description', $comment );
2880 $actorFields = $actorMigration->getInsertValues( $dbw,
'img_user',
$user );
2882 'img_name' => $row->fa_name,
2883 'img_size' => $row->fa_size,
2884 'img_width' => $row->fa_width,
2885 'img_height' => $row->fa_height,
2886 'img_metadata' => $props[
'metadata'],
2887 'img_bits' => $row->fa_bits,
2888 'img_media_type' => $props[
'media_type'],
2889 'img_major_mime' => $props[
'major_mime'],
2890 'img_minor_mime' => $props[
'minor_mime'],
2891 'img_timestamp' => $row->fa_timestamp,
2893 ] + $commentFields + $actorFields;
2896 if ( !$this->unsuppress && $row->fa_deleted ) {
2897 $status->fatal(
'undeleterevdel' );
2898 $this->
file->unlock();
2902 $archiveName = $row->fa_archive_name;
2904 if ( $archiveName ==
'' ) {
2908 $timestamp =
wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2911 $archiveName =
wfTimestamp( TS_MW, $timestamp ) .
'!' . $row->fa_name;
2913 }
while ( isset( $archiveNames[$archiveName] ) );
2916 $archiveNames[$archiveName] =
true;
2917 $destRel = $this->
file->getArchiveRel( $archiveName );
2919 'oi_name' => $row->fa_name,
2920 'oi_archive_name' => $archiveName,
2921 'oi_size' => $row->fa_size,
2922 'oi_width' => $row->fa_width,
2923 'oi_height' => $row->fa_height,
2924 'oi_bits' => $row->fa_bits,
2925 'oi_timestamp' => $row->fa_timestamp,
2926 'oi_metadata' => $props[
'metadata'],
2927 'oi_media_type' => $props[
'media_type'],
2928 'oi_major_mime' => $props[
'major_mime'],
2929 'oi_minor_mime' => $props[
'minor_mime'],
2930 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2932 ] + $commentStore->insert( $dbw,
'oi_description', $comment )
2933 + $actorMigration->getInsertValues( $dbw,
'oi_user',
$user );
2936 $deleteIds[] = $row->fa_id;
2942 $storeBatch[] = [ $deletedUrl,
'public', $destRel ];
2943 $this->cleanupBatch[] = $row->fa_storage_key;
2952 $missingIds = array_diff( $this->ids, $idsPresent );
2954 foreach ( $missingIds
as $id ) {
2955 $status->error(
'undelete-missing-filearchive', $id );
2958 if ( !$repo->hasSha1Storage() ) {
2961 if ( !$checkStatus->isGood() ) {
2962 $status->merge( $checkStatus );
2965 $storeBatch = $checkStatus->value;
2970 $status->merge( $storeStatus );
2977 $this->
file->unlock();
2989 if ( $insertCurrent ) {
2990 $dbw->insert(
'image', $insertCurrent, __METHOD__ );
2993 if ( $insertBatch ) {
2994 $dbw->insert(
'oldimage', $insertBatch, __METHOD__ );
2998 $dbw->delete(
'filearchive',
2999 [
'fa_id' => $deleteIds ],
3004 if (
$status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
3006 wfDebug( __METHOD__ .
" restored {$status->successCount} items, creating a new current\n" );
3008 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
'images' => 1 ] ) );
3010 $this->
file->purgeEverything();
3012 wfDebug( __METHOD__ .
" restored {$status->successCount} as archived versions\n" );
3013 $this->
file->purgeDescription();
3017 $this->
file->unlock();
3028 $files = $filteredTriplets = [];
3029 foreach ( $triplets
as $file ) {
3033 $result = $this->
file->repo->fileExistsBatch( $files );
3034 if ( in_array(
null,
$result,
true ) ) {
3035 return Status::newFatal(
'backend-fail-internal',
3036 $this->
file->repo->getBackend()->getName() );
3039 foreach ( $triplets
as $file ) {
3041 $filteredTriplets[] =
$file;
3045 return Status::newGood( $filteredTriplets );
3054 $files = $newBatch = [];
3055 $repo = $this->
file->repo;
3058 $files[
$file] = $repo->getVirtualUrl(
'deleted' ) .
'/' .
3059 rawurlencode( $repo->getDeletedHashPath(
$file ) .
$file );
3062 $result = $repo->fileExistsBatch( $files );
3066 $newBatch[] =
$file;
3079 if ( !$this->cleanupBatch ) {
3080 return $this->
file->repo->newGood();
3085 $status = $this->
file->repo->cleanupDeletedBatch( $this->cleanupBatch );
3100 foreach ( $storeStatus->success
as $i =>
$success ) {
3105 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3112# ------------------------------------------------------------------------------
3143 $this->oldHash = $this->
file->repo->getHashPath( $this->
file->getName() );
3144 $this->newHash = $this->
file->repo->getHashPath( $this->target->getDBkey() );
3145 $this->oldName = $this->
file->getName();
3146 $this->newName = $this->
file->repo->getNameFromTitle( $this->target );
3147 $this->oldRel = $this->oldHash . $this->oldName;
3148 $this->newRel = $this->newHash . $this->newName;
3156 $this->cur = [ $this->oldRel, $this->newRel ];
3164 $archiveBase =
'archive';
3166 $this->oldCount = 0;
3169 $result = $this->db->select(
'oldimage',
3170 [
'oi_archive_name',
'oi_deleted' ],
3171 [
'oi_name' => $this->oldName ],
3173 [
'LOCK IN SHARE MODE' ]
3177 $archiveNames[] = $row->oi_archive_name;
3178 $oldName = $row->oi_archive_name;
3179 $bits = explode(
'!', $oldName, 2 );
3181 if ( count( $bits ) != 2 ) {
3182 wfDebug(
"Old file name missing !: '$oldName' \n" );
3186 list( $timestamp, $filename ) = $bits;
3188 if ( $this->oldName != $filename ) {
3189 wfDebug(
"Old file name doesn't match: '$oldName' \n" );
3201 "{$archiveBase}/{$this->oldHash}{$oldName}",
3202 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3206 return $archiveNames;
3214 $repo = $this->
file->repo;
3218 $this->
file->lock();
3223 if ( !$checkStatus->isGood() ) {
3224 $destFile->unlock();
3225 $this->
file->unlock();
3226 $status->merge( $checkStatus );
3229 $triplets = $checkStatus->value;
3233 if ( !$statusDb->isGood() ) {
3234 $destFile->unlock();
3235 $this->
file->unlock();
3236 $statusDb->setOK(
false );
3241 if ( !$repo->hasSha1Storage() ) {
3246 wfDebugLog(
'imagemove',
"Moved files for {$this->file->getName()}: " .
3247 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3248 if ( !$statusMove->isGood() ) {
3251 $destFile->unlock();
3252 $this->
file->unlock();
3253 wfDebugLog(
'imagemove',
"Error in moving files: "
3254 . $statusMove->getWikiText(
false,
false,
'en' ) );
3255 $statusMove->setOK(
false );
3259 $status->merge( $statusMove );
3265 wfDebugLog(
'imagemove',
"Renamed {$this->file->getName()} in database: " .
3266 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3268 $destFile->unlock();
3269 $this->
file->unlock();
3286 $repo = $this->
file->repo;
3292 [
'img_name' => $this->oldName ],
3295 $oldRowCount = $dbw->lockForUpdate(
3297 [
'oi_name' => $this->oldName ],
3301 if ( $hasCurrent ) {
3306 $status->successCount += $oldRowCount;
3310 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3312 $status->error(
'imageinvalidfilename' );
3328 [
'img_name' => $this->newName ],
3329 [
'img_name' => $this->oldName ],
3337 'oi_name' => $this->newName,
3338 'oi_archive_name = ' . $dbw->strreplace(
'oi_archive_name',
3339 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3341 [
'oi_name' => $this->oldName ],
3351 $moves = array_merge( [ $this->cur ], $this->olds );
3354 foreach ( $moves
as $move ) {
3356 $srcUrl = $this->
file->repo->getVirtualUrl() .
'/public/' . rawurlencode( $move[0] );
3357 $triplets[] = [ $srcUrl,
'public', $move[1] ];
3360 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3375 foreach ( $triplets
as $file ) {
3379 $result = $this->
file->repo->fileExistsBatch( $files );
3380 if ( in_array(
null,
$result,
true ) ) {
3381 return Status::newFatal(
'backend-fail-internal',
3382 $this->
file->repo->getBackend()->getName() );
3385 $filteredTriplets = [];
3386 foreach ( $triplets
as $file ) {
3388 $filteredTriplets[] =
$file;
3390 wfDebugLog(
'imagemove',
"File {$file[0]} does not exist" );
3394 return Status::newGood( $filteredTriplets );
3405 foreach ( $triplets
as $triplet ) {
3407 $pairs[] = [ $triplet[1], $triplet[2] ];
3410 $this->
file->repo->cleanupBatch( $pairs );
3421 foreach ( $triplets
as $triplet ) {
3422 $files[] = $triplet[0];
3425 $this->
file->repo->cleanupBatch( $files );
3431 parent::__construct(
3439 $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.
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
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.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new archivedfile object.
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)
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.
isOld()
Returns true if the image is an old version STUB.
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.
getArchiveRel( $suffix=false)
Get the path of an archived file relative to the public zone root.
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.
Class to invalidate the HTML cache of all the pages linking to a given title.
Internationalisation code.
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.
string[] $ids
List of file IDs to restore.
bool $unsuppress
Whether to remove all settings for suppressed fields.
removeNonexistentFromCleanup( $batch)
Removes non-existent files from a cleanup batch.
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.
string[] $cleanupBatch
List of file IDs to restore.
cleanupFailedBatch( $storeStatus, $storeBatch)
Cleanup a failed batch.
bool $all
Add all revisions of the file.
__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...
recordUpload2( $oldver, $comment, $pageText, $props=false, $timestamp=false, $user=null, $tags=[], $createNullRevision=true, $revert=false)
Record a file upload in the upload log and the image table.
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 MimeAnalyzer::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.
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
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.
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.
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 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_')
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.
loadExtraFieldsWithTimestamp( $dbr, $fname)
invalidateCache()
Purge the file object/metadata cache.
getMimeType()
Returns the MIME type of the file.
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, $user=null, $tags=[], $createNullRevision=true, $revert=false)
getHashPath inherited
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.
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 $metadata
Handler-specific metadata.
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)
bool $missing
True if file is not present in file system.
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.
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)
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)
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 new log entries and inserting them into the database.
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new oldlocalfile object.
Set options of the Parser.
static singleton()
Get a RepoGroup instance.
static newNullRevision( $dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page's history.
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Job for asynchronous rendering of thumbnails.
Represents a title within MediaWiki.
getPrefixedText()
Get the prefixed title with spaces.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Watch an article.
getName()
Get the user name, or the IP of an anonymous user.
getId()
Get the user's ID.
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
getActorId(IDatabase $dbw=null)
Get the user's actor ID.
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 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.
const SCHEMA_COMPAT_WRITE_BOTH
const SCHEMA_COMPAT_READ_NEW
const SCHEMA_COMPAT_WRITE_OLD
const SCHEMA_COMPAT_WRITE_NEW
returning false will NOT prevent logging a wrapping ErrorException create2 Corresponds to logging log_action database field and which is displayed in the UI & $revert
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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 since 1.28! 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
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
this hook is for auditing only 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 or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Allows to change the fields on the form that will be generated $name
and how to run hooks for an and one after Each event has a name
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function 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
return true to allow those checks to and false if checking is done & $user
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
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
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(!is_readable( $file)) $ext
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
if(!isset( $args[0])) $lang