160 $title = Title::makeTitle(
NS_FILE, $row->img_name );
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__ .
' when $wgActorTableSchemaMigrationStage > MIGRATION_WRITE_BOTH'
229 ] + CommentStore::getStore()->getFields(
'img_description' );
244 $commentQuery = CommentStore::getStore()->getJoin(
'img_description' );
245 $actorQuery = ActorMigration::newMigration()->getJoin(
'img_user' );
247 'tables' => [
'image' ] + $commentQuery[
'tables'] + $actorQuery[
'tables'],
260 ] + $commentQuery[
'fields'] + $actorQuery[
'fields'],
261 'joins' => $commentQuery[
'joins'] + $actorQuery[
'joins'],
264 if ( in_array(
'omit-nonlazy',
$options,
true ) ) {
268 if ( !in_array(
'omit-lazy',
$options,
true ) ) {
270 $ret[
'fields'][] =
'img_metadata';
282 parent::__construct( $title,
$repo );
284 $this->metadata =
'';
285 $this->historyLine = 0;
286 $this->historyRes =
null;
287 $this->dataLoaded =
false;
288 $this->extraDataLoaded =
false;
300 return $this->repo->getSharedCacheKey(
'file', sha1( $this->
getName() ) );
316 $this->dataLoaded =
false;
317 $this->extraDataLoaded =
false;
326 $cache = ObjectCache::getMainWANInstance();
327 $cachedValues =
$cache->getWithSetCallback(
330 function ( $oldValue, &$ttl, array &$setOpts ) use (
$cache ) {
331 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
337 if ( $this->fileExists ) {
338 foreach ( $fields as $field ) {
339 $cacheVal[$field] = $this->$field;
342 $cacheVal[
'user'] = $this->user ? $this->user->getId() : 0;
343 $cacheVal[
'user_text'] = $this->user ? $this->user->getName() :
'';
344 $cacheVal[
'actor'] = $this->user ? $this->user->getActorId() :
null;
350 if ( isset( $cacheVal[$field] )
351 && strlen( $cacheVal[$field] ) > 100 * 1024
353 unset( $cacheVal[$field] );
357 if ( $this->fileExists ) {
360 $ttl = $cache::TTL_DAY;
368 $this->fileExists = $cachedValues[
'fileExists'];
369 if ( $this->fileExists ) {
373 $this->dataLoaded =
true;
374 $this->extraDataLoaded =
true;
376 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
389 $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
390 function () use ( $key ) {
391 ObjectCache::getMainWANInstance()->delete( $key );
401 $props = $this->repo->getFileProps( $this->
getVirtualUrl() );
412 if ( $prefix !==
'' ) {
413 throw new InvalidArgumentException(
414 __METHOD__ .
' with a non-empty prefix is no longer supported.'
422 return [
'size',
'width',
'height',
'bits',
'media_type',
423 'major_mime',
'minor_mime',
'metadata',
'timestamp',
'sha1',
'description' ];
434 if ( $prefix !==
'' ) {
435 throw new InvalidArgumentException(
436 __METHOD__ .
' with a non-empty prefix is no longer supported.'
441 return [
'metadata' ];
449 $fname = static::class .
'::' . __FUNCTION__;
451 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
452 $this->dataLoaded =
true;
453 $this->extraDataLoaded =
true;
455 $dbr = ( $flags & self::READ_LATEST )
456 ? $this->repo->getMasterDB()
457 : $this->repo->getReplicaDB();
459 $fileQuery = static::getQueryInfo();
460 $row =
$dbr->selectRow(
461 $fileQuery[
'tables'],
462 $fileQuery[
'fields'],
463 [
'img_name' => $this->
getName() ],
472 $this->fileExists =
false;
481 $fname = static::class .
'::' . __FUNCTION__;
483 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
484 $this->extraDataLoaded =
true;
492 foreach ( $fieldMap as $name =>
$value ) {
496 throw new MWException(
"Could not find data for image '{$this->getName()}'." );
509 $row =
$dbr->selectRow(
510 $fileQuery[
'tables'],
511 $fileQuery[
'fields'],
513 'img_name' => $this->
getName(),
514 'img_timestamp' =>
$dbr->timestamp( $this->getTimestamp() ),
523 # File may have been uploaded over in the meantime; check the old versions
525 $row =
$dbr->selectRow(
526 $fileQuery[
'tables'],
527 $fileQuery[
'fields'],
530 'oi_timestamp' =>
$dbr->timestamp( $this->getTimestamp() ),
541 if ( isset( $fieldMap[
'metadata'] ) ) {
542 $fieldMap[
'metadata'] = $this->repo->getReplicaDB()->decodeBlob( $fieldMap[
'metadata'] );
555 $array = (
array)$row;
556 $prefixLength = strlen( $prefix );
559 if ( substr(
key( $array ), 0, $prefixLength ) !== $prefix ) {
560 throw new MWException( __METHOD__ .
': incorrect $prefix parameter' );
564 foreach ( $array as $name =>
$value ) {
565 $decoded[substr( $name, $prefixLength )] =
$value;
582 $decoded[
'description'] = CommentStore::getStore()
583 ->getComment(
'description', (
object)$decoded )->text;
586 isset( $decoded[
'user'] ) ? $decoded[
'user'] :
null,
587 isset( $decoded[
'user_text'] ) ? $decoded[
'user_text'] :
null,
588 isset( $decoded[
'actor'] ) ? $decoded[
'actor'] : null
590 unset( $decoded[
'user_text'], $decoded[
'actor'] );
592 $decoded[
'timestamp'] =
wfTimestamp( TS_MW, $decoded[
'timestamp'] );
594 $decoded[
'metadata'] = $this->repo->getReplicaDB()->decodeBlob( $decoded[
'metadata'] );
596 if ( empty( $decoded[
'major_mime'] ) ) {
597 $decoded[
'mime'] =
'unknown/unknown';
599 if ( !$decoded[
'minor_mime'] ) {
600 $decoded[
'minor_mime'] =
'unknown';
602 $decoded[
'mime'] = $decoded[
'major_mime'] .
'/' . $decoded[
'minor_mime'];
606 $decoded[
'sha1'] = rtrim( $decoded[
'sha1'],
"\0" );
612 foreach ( [
'size',
'width',
'height',
'bits' ] as $field ) {
613 $decoded[$field] = +$decoded[$field];
626 $this->dataLoaded =
true;
627 $this->extraDataLoaded =
true;
629 $array = $this->
decodeRow( $row, $prefix );
631 foreach ( $array as $name =>
$value ) {
635 $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 isset( $info[
'user'] ) ? $info[
'user'] :
null,
776 isset( $info[
'user_text'] ) ? $info[
'user_text'] :
null,
777 isset( $info[
'actor'] ) ? $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'];
802 if ( $this->missing ===
null ) {
831 return $dim[
'width'];
863 return $dim[
'height'];
884 if (
$type ===
'object' ) {
886 } elseif (
$type ===
'text' ) {
888 } elseif (
$type ===
'id' ) {
889 return $this->user->getId();
903 $pageId = $this->title->getArticleID();
905 if ( $pageId !==
null ) {
906 $url = $this->repo->makeUrl( [
'curid' => $pageId ] );
907 if (
$url !==
false ) {
919 $this->
load( self::LOAD_ALL );
995 if ( $archiveName ) {
1001 $backend = $this->repo->getBackend();
1004 $iterator = $backend->getFileList( [
'dir' => $dir ] );
1005 foreach ( $iterator as $file ) {
1036 DeferredUpdates::addUpdate(
1038 DeferredUpdates::PRESEND
1051 Hooks::run(
'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1054 $dir = array_shift( $files );
1059 foreach ( $files as $file ) {
1073 foreach ( $files as $file ) {
1076 array_shift(
$urls );
1079 if ( !empty(
$options[
'forThumbRefresh'] ) ) {
1087 Hooks::run(
'LocalFilePurgeThumbnails', [ $this,
false ] );
1090 $dir = array_shift( $files );
1110 foreach ( $sizes as
$size ) {
1114 [
'transformParams' => [
'width' => $size ] ]
1130 $fileListDebug = strtr(
1131 var_export( $files,
true ),
1134 wfDebug( __METHOD__ .
": $fileListDebug\n" );
1137 foreach ( $files as $file ) {
1138 if ( $this->repo->supportsSha1URLs() ) {
1139 $reference = $this->
getSha1();
1141 $reference = $this->
getName();
1144 # Check that the reference (filename or sha1) is part of the thumb name
1145 # This is a basic sanity check to avoid erasing unrelated directories
1146 if ( strpos( $file, $reference ) !==
false
1147 || strpos( $file,
"-thumbnail" ) !==
false
1149 $purgeList[] =
"{$dir}/{$file}";
1153 # Delete the thumbnails
1154 $this->repo->quickPurgeBatch( $purgeList );
1155 # Clear out the thumbnail directory if empty
1156 $this->repo->quickCleanDir( $dir );
1169 function getHistory( $limit =
null, $start =
null, $end =
null, $inc =
true ) {
1170 $dbr = $this->repo->getReplicaDB();
1173 $tables = $oldFileQuery[
'tables'];
1174 $fields = $oldFileQuery[
'fields'];
1175 $join_conds = $oldFileQuery[
'joins'];
1176 $conds = $opts = [];
1177 $eq = $inc ?
'=' :
'';
1178 $conds[] =
"oi_name = " .
$dbr->addQuotes( $this->title->getDBkey() );
1181 $conds[] =
"oi_timestamp <$eq " .
$dbr->addQuotes(
$dbr->timestamp( $start ) );
1185 $conds[] =
"oi_timestamp >$eq " .
$dbr->addQuotes(
$dbr->timestamp( $end ) );
1189 $opts[
'LIMIT'] = $limit;
1193 $order = ( !$start && $end !== null ) ?
'ASC' :
'DESC';
1194 $opts[
'ORDER BY'] =
"oi_timestamp $order";
1195 $opts[
'USE INDEX'] = [
'oldimage' =>
'oi_name_timestamp' ];
1199 Hooks::run(
'LocalFile::getHistory', [ &$localFile, &
$tables, &$fields,
1200 &$conds, &$opts, &$join_conds ] );
1202 $res =
$dbr->select(
$tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1205 foreach (
$res as $row ) {
1206 $r[] = $this->repo->newFileFromRow( $row );
1209 if ( $order ==
'ASC' ) {
1210 $r = array_reverse( $r );
1226 # Polymorphic function name to distinguish foreign and local fetches
1227 $fname = static::class .
'::' . __FUNCTION__;
1229 $dbr = $this->repo->getReplicaDB();
1231 if ( $this->historyLine == 0 ) {
1233 $this->historyRes =
$dbr->select( $fileQuery[
'tables'],
1234 $fileQuery[
'fields'] + [
1235 'oi_archive_name' =>
$dbr->addQuotes(
'' ),
1238 [
'img_name' => $this->title->getDBkey() ],
1244 if ( 0 ==
$dbr->numRows( $this->historyRes ) ) {
1245 $this->historyRes =
null;
1249 } elseif ( $this->historyLine == 1 ) {
1251 $this->historyRes =
$dbr->select(
1252 $fileQuery[
'tables'],
1253 $fileQuery[
'fields'],
1254 [
'oi_name' => $this->title->getDBkey() ],
1256 [
'ORDER BY' =>
'oi_timestamp DESC' ],
1260 $this->historyLine++;
1262 return $dbr->fetchObject( $this->historyRes );
1269 $this->historyLine = 0;
1271 if ( !is_null( $this->historyRes ) ) {
1272 $this->historyRes =
null;
1306 function upload( $src, $comment, $pageText, $flags = 0, $props =
false,
1309 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1311 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1317 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1319 if ( $this->repo->isVirtualUrl( $srcPath )
1322 $props = $this->repo->getFileProps( $srcPath );
1325 $props = $mwProps->getPropsFromPath( $srcPath,
true );
1332 $metadata = Wikimedia\quietCall(
'unserialize', $props[
'metadata'] );
1344 $comment = trim( $comment );
1349 if (
$status->successCount >= 2 ) {
1366 if ( !$uploadStatus->isOK() ) {
1367 if ( $uploadStatus->hasMessage(
'filenotfound' ) ) {
1369 $status->fatal(
'filenotfound', $srcPath );
1371 $status->merge( $uploadStatus );
1407 $user->addWatch( $this->
getTitle() );
1425 $oldver, $comment, $pageText, $props =
false,
$timestamp =
false, $user =
null, $tags = []
1429 if ( is_null( $user ) ) {
1434 $dbw = $this->repo->getMasterDB();
1436 # Imports or such might force a certain timestamp; otherwise we generate
1437 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1440 $allowTimeKludge =
true;
1442 $allowTimeKludge =
false;
1445 $props = $props ?: $this->repo->getFileProps( $this->
getVirtualUrl() );
1446 $props[
'description'] = $comment;
1447 $props[
'user'] = $user->getId();
1448 $props[
'user_text'] = $user->getName();
1449 $props[
'actor'] = $user->getActorId( $dbw );
1453 # Fail now if the file isn't there
1454 if ( !$this->fileExists ) {
1455 wfDebug( __METHOD__ .
": File " . $this->
getRel() .
" went missing!\n" );
1457 return Status::newFatal(
'filenotfound', $this->
getRel() );
1460 $dbw->startAtomic( __METHOD__ );
1462 # Test to see if the row exists using INSERT IGNORE
1463 # This avoids race conditions by locking the row until the commit, and also
1464 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1465 $commentStore = CommentStore::getStore();
1466 list( $commentFields, $commentCallback ) =
1467 $commentStore->insertWithTempTable( $dbw,
'img_description', $comment );
1468 $actorMigration = ActorMigration::newMigration();
1469 $actorFields = $actorMigration->getInsertValues( $dbw,
'img_user', $user );
1470 $dbw->insert(
'image',
1472 'img_name' => $this->
getName(),
1473 'img_size' => $this->size,
1474 'img_width' => intval( $this->
width ),
1475 'img_height' => intval( $this->height ),
1476 'img_bits' => $this->bits,
1477 'img_media_type' => $this->media_type,
1478 'img_major_mime' => $this->major_mime,
1479 'img_minor_mime' => $this->minor_mime,
1481 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1482 'img_sha1' => $this->sha1
1483 ] + $commentFields + $actorFields,
1487 $reupload = ( $dbw->affectedRows() == 0 );
1490 $row = $dbw->selectRow(
1492 [
'img_timestamp',
'img_sha1' ],
1493 [
'img_name' => $this->
getName() ],
1495 [
'LOCK IN SHARE MODE' ]
1498 if ( $row && $row->img_sha1 === $this->sha1 ) {
1499 $dbw->endAtomic( __METHOD__ );
1500 wfDebug( __METHOD__ .
": File " . $this->
getRel() .
" already exists!\n" );
1502 return Status::newFatal(
'fileexists-no-change', $title->getPrefixedText() );
1505 if ( $allowTimeKludge ) {
1506 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1507 $lUnixtime = $row ?
wfTimestamp( TS_UNIX, $row->img_timestamp ) :
false;
1508 # Avoid a timestamp that is not newer than the last version
1509 # TODO: the image/oldimage tables should be like page/revision with an ID field
1512 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1519 'oi_name' =>
'img_name',
1520 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1521 'oi_size' =>
'img_size',
1522 'oi_width' =>
'img_width',
1523 'oi_height' =>
'img_height',
1524 'oi_bits' =>
'img_bits',
1525 'oi_timestamp' =>
'img_timestamp',
1526 'oi_metadata' =>
'img_metadata',
1527 'oi_media_type' =>
'img_media_type',
1528 'oi_major_mime' =>
'img_major_mime',
1529 'oi_minor_mime' =>
'img_minor_mime',
1530 'oi_sha1' =>
'img_sha1',
1535 $fields[
'oi_description'] =
'img_description';
1538 $tables[] =
'image_comment_temp';
1539 $fields[
'oi_description_id'] =
'imgcomment_description_id';
1540 $joins[
'image_comment_temp'] = [
1542 [
'imgcomment_name = img_name' ]
1552 $res = $dbw->select(
1553 [
'image',
'image_comment_temp' ],
1554 [
'img_name',
'img_description' ],
1555 [
'img_name' => $this->
getName(),
'imgcomment_name' =>
null ],
1558 [
'image_comment_temp' => [
'LEFT JOIN', [
'imgcomment_name = img_name' ] ] ]
1560 foreach (
$res as $row ) {
1561 list( , $callback ) = $commentStore->insertWithTempTable(
1562 $dbw,
'img_description', $row->img_description
1564 $callback( $row->img_name );
1569 $fields[
'oi_user'] =
'img_user';
1570 $fields[
'oi_user_text'] =
'img_user_text';
1573 $fields[
'oi_actor'] =
'img_actor';
1582 $res = $dbw->select(
1584 [
'img_name',
'img_user',
'img_user_text' ],
1585 [
'img_name' => $this->
getName(),
'img_actor' => 0 ],
1588 foreach (
$res as $row ) {
1589 $actorId =
User::newFromAnyId( $row->img_user, $row->img_user_text,
null )->getActorId( $dbw );
1592 [
'img_actor' => $actorId ],
1593 [
'img_name' => $row->img_name,
'img_actor' => 0 ],
1599 # (T36993) Note: $oldver can be empty here, if the previous
1600 # version of the file was broken. Allow registration of the new
1601 # version to continue anyway, because that's better than having
1602 # an image that's not fixable by user operations.
1603 # Collision, this is an update of a file
1604 # Insert previous contents into oldimage
1605 $dbw->insertSelect(
'oldimage',
$tables, $fields,
1606 [
'img_name' => $this->
getName() ], __METHOD__, [], [], $joins );
1608 # Update the current image row
1609 $dbw->update(
'image',
1611 'img_size' => $this->size,
1612 'img_width' => intval( $this->
width ),
1613 'img_height' => intval( $this->height ),
1614 'img_bits' => $this->bits,
1615 'img_media_type' => $this->media_type,
1616 'img_major_mime' => $this->major_mime,
1617 'img_minor_mime' => $this->minor_mime,
1619 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1620 'img_sha1' => $this->sha1
1621 ] + $commentFields + $actorFields,
1622 [
'img_name' => $this->getName() ],
1627 $dbw->delete(
'image_comment_temp', [
'imgcomment_name' => $this->
getName() ], __METHOD__ );
1630 $commentCallback( $this->
getName() );
1633 $descId = $descTitle->getArticleID();
1635 $wikiPage->setFile( $this );
1638 $logEntry =
new ManualLogEntry(
'upload', $reupload ?
'overwrite' :
'upload' );
1640 $logEntry->setPerformer( $user );
1641 $logEntry->setComment( $comment );
1642 $logEntry->setTarget( $descTitle );
1645 $logEntry->setParameters(
1647 'img_sha1' => $this->sha1,
1657 $logId = $logEntry->insert();
1659 if ( $descTitle->exists() ) {
1663 $editSummary = $formatter->getPlainActionText();
1665 $nullRevision = Revision::newNullRevision(
1672 if ( $nullRevision ) {
1673 $nullRevision->insertOn( $dbw );
1675 'NewRevisionFromEditComplete',
1676 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1678 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1680 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1683 $newPageContent =
null;
1686 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1689 # Defer purges, page creation, and link updates in case they error out.
1690 # The most important thing is that files and the DB registry stay synced.
1691 $dbw->endAtomic( __METHOD__ );
1693 # Do some cache purges after final commit so that:
1694 # a) Changes are more likely to be seen post-purge
1695 # b) They won't cause rollback of the log publish/update above
1696 DeferredUpdates::addUpdate(
1701 $reupload, $wikiPage, $newPageContent, $comment, $user,
1702 $logEntry, $logId, $descId, $tags
1704 # Update memcache after the commit
1707 $updateLogPage =
false;
1708 if ( $newPageContent ) {
1709 # New file page; create the description page.
1710 # There's already a log entry, so don't make a second RC entry
1711 # CDN and file cache for the description page are purged by doEditContent.
1712 $status = $wikiPage->doEditContent(
1720 if ( isset(
$status->value[
'revision'] ) ) {
1724 $logEntry->setAssociatedRevId(
$rev->getId() );
1728 if ( isset(
$status->value[
'revision'] ) ) {
1731 $updateLogPage =
$rev->getPage();
1734 # Existing file page: invalidate description page cache
1735 $wikiPage->getTitle()->invalidateCache();
1736 $wikiPage->getTitle()->purgeSquid();
1737 # Allow the new file version to be patrolled from the page footer
1741 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1742 # but setAssociatedRevId() wasn't called at that point yet...
1743 $logParams = $logEntry->getParameters();
1744 $logParams[
'associated_rev_id'] = $logEntry->getAssociatedRevId();
1746 if ( $updateLogPage ) {
1747 # Also log page, in case where we just created it above
1748 $update[
'log_page'] = $updateLogPage;
1750 $this->
getRepo()->getMasterDB()->update(
1753 [
'log_id' => $logId ],
1756 $this->
getRepo()->getMasterDB()->insert(
1759 'ls_field' =>
'associated_rev_id',
1760 'ls_value' => $logEntry->getAssociatedRevId(),
1761 'ls_log_id' => $logId,
1766 # Add change tags, if any
1768 $logEntry->setTags( $tags );
1771 # Uploads can be patrolled
1772 $logEntry->setIsPatrollable(
true );
1774 # Now that the log entry is up-to-date, make an RC entry.
1775 $logEntry->publish( $logId );
1777 # Run hook for other updates (typically more cache purging)
1778 Hooks::run(
'FileUpload', [ $this, $reupload, !$newPageContent ] );
1781 # Delete old thumbnails
1783 # Remove the old file from the CDN cache
1784 DeferredUpdates::addUpdate(
1786 DeferredUpdates::PRESEND
1789 # Update backlink pages pointing to this title if created
1801 DeferredUpdates::PRESEND
1805 # This is a new file, so update the image count
1809 # Invalidate cache for all pages using this file
1810 DeferredUpdates::addUpdate(
1814 return Status::newGood();
1852 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1862 $archiveRel =
'archive/' . $this->
getHashPath() . $archiveName;
1870 $dst = $wrapperBackend->getPathForSHA1(
$sha1 );
1877 $status->value = $archiveName;
1883 if (
$status->value ==
'new' ) {
1886 $status->value = $archiveName;
1913 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1917 wfDebugLog(
'imagemove',
"Got request to move {$this->name} to " . $target->getText() );
1922 $archiveNames =
$batch->addOlds();
1926 wfDebugLog(
'imagemove',
"Finished moving {$this->name}" );
1932 DeferredUpdates::addUpdate(
1934 $this->
getRepo()->getMasterDB(),
1936 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1937 $oldTitleFile->purgeEverything();
1938 foreach ( $archiveNames as $archiveName ) {
1939 $oldTitleFile->purgeOldThumbnails( $archiveName );
1941 $newTitleFile->purgeEverything();
1944 DeferredUpdates::PRESEND
1949 $this->title = $target;
1951 unset( $this->
name );
1952 unset( $this->hashPath );
1971 function delete( $reason, $suppress =
false, $user = null ) {
1972 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1981 $archiveNames =
$batch->addOlds();
1990 DeferredUpdates::addUpdate(
1992 $this->
getRepo()->getMasterDB(),
1994 function () use ( $archiveNames ) {
1996 foreach ( $archiveNames as $archiveName ) {
2001 DeferredUpdates::PRESEND
2006 foreach ( $archiveNames as $archiveName ) {
2009 DeferredUpdates::addUpdate(
new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
2029 function deleteOld( $archiveName, $reason, $suppress =
false, $user =
null ) {
2030 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
2037 $batch->addOld( $archiveName );
2046 DeferredUpdates::addUpdate(
2048 DeferredUpdates::PRESEND
2065 function restore( $versions = [], $unsuppress =
false ) {
2066 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
2076 $batch->addIds( $versions );
2080 $cleanupStatus =
$batch->cleanup();
2081 $cleanupStatus->successCount = 0;
2082 $cleanupStatus->failCount = 0;
2083 $status->merge( $cleanupStatus );
2100 return $this->title->getLocalURL();
2112 $revision = Revision::newFromTitle( $this->title,
false, Revision::READ_NORMAL );
2116 $content = $revision->getContent();
2120 $pout = $content->getParserOutput( $this->title,
null,
new ParserOptions(
null,
$lang ) );
2122 return $pout->getText();
2132 if ( $audience == self::FOR_PUBLIC && $this->
isDeleted( self::DELETED_COMMENT ) ) {
2134 } elseif ( $audience == self::FOR_THIS_USER
2135 && !$this->
userCan( self::DELETED_COMMENT, $user )
2159 if ( $this->descriptionTouched ===
null ) {
2161 'page_namespace' => $this->title->getNamespace(),
2162 'page_title' => $this->title->getDBkey()
2164 $touched = $this->repo->getReplicaDB()->selectField(
'page',
'page_touched', $cond, __METHOD__ );
2165 $this->descriptionTouched = $touched ?
wfTimestamp( TS_MW, $touched ) :
false;
2177 if ( $this->sha1 ==
'' && $this->fileExists ) {
2180 $this->sha1 = $this->repo->getFileSha1( $this->
getPath() );
2181 if ( !
wfReadOnly() && strval( $this->sha1 ) !=
'' ) {
2182 $dbw = $this->repo->getMasterDB();
2183 $dbw->update(
'image',
2184 [
'img_sha1' => $this->sha1 ],
2185 [
'img_name' => $this->
getName() ],
2203 return $this->extraDataLoaded
2212 return $this->
getRepo()->getBackend()->lockFiles(
2213 [ $this->
getPath() ], LockManager::LOCK_EX, 10
2222 return $this->
getRepo()->getBackend()->unlockFiles(
2223 [ $this->
getPath() ], LockManager::LOCK_EX
2237 if ( !$this->locked ) {
2238 $logger = LoggerFactory::getInstance(
'LocalFile' );
2240 $dbw = $this->repo->getMasterDB();
2241 $makesTransaction = !$dbw->trxLevel();
2242 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2248 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2249 $logger->warning(
"Failed to lock '{file}'", [
'file' => $this->
name ] );
2255 $dbw->onTransactionResolution(
2256 function () use ( $logger ) {
2259 $logger->error(
"Failed to unlock '{file}'", [
'file' => $this->
name ] );
2265 $this->lockedOwnTrx = $makesTransaction;
2282 if ( $this->locked ) {
2284 if ( !$this->locked ) {
2285 $dbw = $this->repo->getMasterDB();
2286 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2287 $this->lockedOwnTrx =
false;
2296 return $this->
getRepo()->newFatal(
'filereadonlyerror', $this->
getName(),
2308# ------------------------------------------------------------------------------
2346 $this->file =
$file;
2350 $this->user =
$user;
2355 $this->status = $file->repo->newGood();
2359 $this->srcRels[
'.'] = $this->file->getRel();
2366 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2367 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2377 $dbw = $this->file->repo->getMasterDB();
2378 $result = $dbw->select(
'oldimage',
2379 [
'oi_archive_name' ],
2380 [
'oi_name' => $this->file->getName() ],
2384 foreach ( $result as $row ) {
2385 $this->
addOld( $row->oi_archive_name );
2386 $archiveNames[] = $row->oi_archive_name;
2389 return $archiveNames;
2396 if ( !isset( $this->srcRels[
'.'] ) ) {
2398 $deleteCurrent =
false;
2401 unset( $oldRels[
'.'] );
2402 $deleteCurrent =
true;
2405 return [ $oldRels, $deleteCurrent ];
2415 if ( $deleteCurrent ) {
2416 $hashes[
'.'] = $this->file->getSha1();
2419 if ( count( $oldRels ) ) {
2420 $dbw = $this->file->repo->getMasterDB();
2421 $res = $dbw->select(
2423 [
'oi_archive_name',
'oi_sha1' ],
2424 [
'oi_archive_name' => array_keys( $oldRels ),
2425 'oi_name' => $this->file->getName() ],
2429 foreach (
$res as $row ) {
2430 if ( rtrim( $row->oi_sha1,
"\0" ) ===
'' ) {
2432 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2433 $props = $this->file->repo->getFileProps( $oldUrl );
2435 if ( $props[
'fileExists'] ) {
2437 $dbw->update(
'oldimage',
2438 [
'oi_sha1' => $props[
'sha1'] ],
2439 [
'oi_name' => $this->file->getName(),
'oi_archive_name' => $row->oi_archive_name ],
2441 $hashes[$row->oi_archive_name] = $props[
'sha1'];
2443 $hashes[$row->oi_archive_name] =
false;
2446 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2451 $missing = array_diff_key( $this->srcRels,
$hashes );
2453 foreach ( $missing as $name => $rel ) {
2454 $this->status->error(
'filedelete-old-unregistered', $name );
2457 foreach (
$hashes as $name => $hash ) {
2459 $this->status->error(
'filedelete-missing', $this->srcRels[$name] );
2471 $dbw = $this->file->repo->getMasterDB();
2473 $commentStore = CommentStore::getStore();
2474 $actorMigration = ActorMigration::newMigration();
2476 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2477 $encUserId = $dbw->addQuotes( $this->user->getId() );
2478 $encGroup = $dbw->addQuotes(
'deleted' );
2479 $ext = $this->file->getExtension();
2480 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2481 $encExt = $dbw->addQuotes( $dotExt );
2485 if ( $this->suppress ) {
2486 $bitfield = Revision::SUPPRESSED_ALL;
2488 $bitfield =
'oi_deleted';
2491 if ( $deleteCurrent ) {
2494 'fa_storage_group' => $encGroup,
2495 'fa_storage_key' => $dbw->conditional(
2496 [
'img_sha1' =>
'' ],
2497 $dbw->addQuotes(
'' ),
2498 $dbw->buildConcat( [
"img_sha1", $encExt ] )
2500 'fa_deleted_user' => $encUserId,
2501 'fa_deleted_timestamp' => $encTimestamp,
2502 'fa_deleted' => $this->suppress ? $bitfield : 0,
2503 'fa_name' =>
'img_name',
2504 'fa_archive_name' =>
'NULL',
2505 'fa_size' =>
'img_size',
2506 'fa_width' =>
'img_width',
2507 'fa_height' =>
'img_height',
2508 'fa_metadata' =>
'img_metadata',
2509 'fa_bits' =>
'img_bits',
2510 'fa_media_type' =>
'img_media_type',
2511 'fa_major_mime' =>
'img_major_mime',
2512 'fa_minor_mime' =>
'img_minor_mime',
2513 'fa_timestamp' =>
'img_timestamp',
2514 'fa_sha1' =>
'img_sha1'
2518 $fields += array_map(
2519 [ $dbw,
'addQuotes' ],
2520 $commentStore->insert( $dbw,
'fa_deleted_reason', $this->reason )
2524 $fields[
'fa_description'] =
'img_description';
2527 $tables[] =
'image_comment_temp';
2528 $fields[
'fa_description_id'] =
'imgcomment_description_id';
2529 $joins[
'image_comment_temp'] = [
2531 [
'imgcomment_name = img_name' ]
2541 $res = $dbw->select(
2542 [
'image',
'image_comment_temp' ],
2543 [
'img_name',
'img_description' ],
2544 [
'img_name' => $this->file->getName(),
'imgcomment_name' =>
null ],
2547 [
'image_comment_temp' => [
'LEFT JOIN', [
'imgcomment_name = img_name' ] ] ]
2549 foreach (
$res as $row ) {
2550 list( , $callback ) = $commentStore->insertWithTempTable(
2551 $dbw,
'img_description', $row->img_description
2553 $callback( $row->img_name );
2558 $fields[
'fa_user'] =
'img_user';
2559 $fields[
'fa_user_text'] =
'img_user_text';
2562 $fields[
'fa_actor'] =
'img_actor';
2571 $res = $dbw->select(
2573 [
'img_name',
'img_user',
'img_user_text' ],
2574 [
'img_name' => $this->file->getName(),
'img_actor' => 0 ],
2577 foreach (
$res as $row ) {
2578 $actorId =
User::newFromAnyId( $row->img_user, $row->img_user_text,
null )->getActorId( $dbw );
2581 [
'img_actor' => $actorId ],
2582 [
'img_name' => $row->img_name,
'img_actor' => 0 ],
2588 $dbw->insertSelect(
'filearchive',
$tables, $fields,
2589 [
'img_name' => $this->file->getName() ], __METHOD__, [], [], $joins );
2592 if ( count( $oldRels ) ) {
2594 $res = $dbw->select(
2595 $fileQuery[
'tables'],
2596 $fileQuery[
'fields'],
2598 'oi_name' => $this->file->getName(),
2599 'oi_archive_name' => array_keys( $oldRels )
2606 if (
$res->numRows() ) {
2607 $reason = $commentStore->createComment( $dbw, $this->reason );
2608 foreach (
$res as $row ) {
2609 $comment = $commentStore->getComment(
'oi_description', $row );
2613 'fa_storage_group' =>
'deleted',
2614 'fa_storage_key' => ( $row->oi_sha1 ===
'' )
2616 :
"{$row->oi_sha1}{$dotExt}",
2617 'fa_deleted_user' => $this->user->getId(),
2618 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2620 'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2621 'fa_name' => $row->oi_name,
2622 'fa_archive_name' => $row->oi_archive_name,
2623 'fa_size' => $row->oi_size,
2624 'fa_width' => $row->oi_width,
2625 'fa_height' => $row->oi_height,
2626 'fa_metadata' => $row->oi_metadata,
2627 'fa_bits' => $row->oi_bits,
2628 'fa_media_type' => $row->oi_media_type,
2629 'fa_major_mime' => $row->oi_major_mime,
2630 'fa_minor_mime' => $row->oi_minor_mime,
2631 'fa_timestamp' => $row->oi_timestamp,
2632 'fa_sha1' => $row->oi_sha1
2633 ] + $commentStore->insert( $dbw,
'fa_deleted_reason',
$reason )
2634 + $commentStore->insert( $dbw,
'fa_description', $comment )
2635 + $actorMigration->getInsertValues( $dbw,
'fa_user', $user );
2639 $dbw->insert(
'filearchive', $rowsInsert, __METHOD__ );
2646 $dbw = $this->file->repo->getMasterDB();
2649 if ( count( $oldRels ) ) {
2650 $dbw->delete(
'oldimage',
2652 'oi_name' => $this->file->getName(),
2653 'oi_archive_name' => array_keys( $oldRels )
2657 if ( $deleteCurrent ) {
2658 $dbw->delete(
'image', [
'img_name' => $this->file->getName() ], __METHOD__ );
2661 'image_comment_temp', [
'imgcomment_name' => $this->file->getName() ], __METHOD__
2672 $repo = $this->file->getRepo();
2673 $this->file->lock();
2677 $this->deletionBatch = [];
2678 $ext = $this->file->getExtension();
2679 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2681 foreach ( $this->srcRels as $name => $srcRel ) {
2683 if ( isset(
$hashes[$name] ) ) {
2685 $key = $hash . $dotExt;
2686 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2687 $this->deletionBatch[
$name] = [ $srcRel, $dstRel ];
2691 if ( !$repo->hasSha1Storage() ) {
2695 if ( !$checkStatus->isGood() ) {
2696 $this->status->merge( $checkStatus );
2699 $this->deletionBatch = $checkStatus->value;
2702 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2708 if ( !$this->status->isOK() ) {
2710 $this->file->unlock();
2721 $this->file->unlock();
2732 $files = $newBatch = [];
2734 foreach (
$batch as $batchItem ) {
2735 list( $src, ) = $batchItem;
2736 $files[$src] = $this->file->repo->getVirtualUrl(
'public' ) .
'/' . rawurlencode( $src );
2739 $result = $this->file->repo->fileExistsBatch( $files );
2740 if ( in_array(
null, $result,
true ) ) {
2741 return Status::newFatal(
'backend-fail-internal',
2742 $this->file->repo->getBackend()->getName() );
2745 foreach (
$batch as $batchItem ) {
2746 if ( $result[$batchItem[0]] ) {
2747 $newBatch[] = $batchItem;
2751 return Status::newGood( $newBatch );
2755# ------------------------------------------------------------------------------
2782 $this->file =
$file;
2783 $this->cleanupBatch = [];
2793 $this->ids[] = $fa_id;
2801 $this->ids = array_merge( $this->ids,
$ids );
2823 $repo = $this->file->getRepo();
2824 if ( !$this->all && !$this->ids ) {
2826 return $repo->newGood();
2829 $lockOwnsTrx = $this->file->lock();
2831 $dbw = $this->file->repo->getMasterDB();
2833 $commentStore = CommentStore::getStore();
2834 $actorMigration = ActorMigration::newMigration();
2836 $status = $this->file->repo->newGood();
2838 $exists = (bool)$dbw->selectField(
'image',
'1',
2839 [
'img_name' => $this->file->getName() ],
2844 $lockOwnsTrx ? [] : [
'LOCK IN SHARE MODE' ]
2849 $conditions = [
'fa_name' => $this->file->getName() ];
2851 if ( !$this->all ) {
2856 $result = $dbw->select(
2857 $arFileQuery[
'tables'],
2858 $arFileQuery[
'fields'],
2861 [
'ORDER BY' =>
'fa_timestamp DESC' ],
2862 $arFileQuery[
'joins']
2868 $insertCurrent =
false;
2873 foreach ( $result as $row ) {
2874 $idsPresent[] = $row->fa_id;
2876 if ( $row->fa_name != $this->file->getName() ) {
2877 $status->error(
'undelete-filename-mismatch',
$wgLang->timeanddate( $row->fa_timestamp ) );
2882 if ( $row->fa_storage_key ==
'' ) {
2884 $status->error(
'undelete-bad-store-key',
$wgLang->timeanddate( $row->fa_timestamp ) );
2889 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2890 $row->fa_storage_key;
2891 $deletedUrl = $repo->getVirtualUrl() .
'/deleted/' . $deletedRel;
2893 if ( isset( $row->fa_sha1 ) ) {
2894 $sha1 = $row->fa_sha1;
2901 if ( strlen( $sha1 ) == 32 && $sha1[0] ==
'0' ) {
2902 $sha1 = substr( $sha1, 1 );
2905 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime ==
'unknown'
2906 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime ==
'unknown'
2907 || is_null( $row->fa_media_type ) || $row->fa_media_type ==
'UNKNOWN'
2908 || is_null( $row->fa_metadata )
2915 'minor_mime' => $row->fa_minor_mime,
2916 'major_mime' => $row->fa_major_mime,
2917 'media_type' => $row->fa_media_type,
2918 'metadata' => $row->fa_metadata
2922 $comment = $commentStore->getComment(
'fa_description', $row );
2924 if ( $first && !$exists ) {
2926 $destRel = $this->file->getRel();
2927 list( $commentFields, $commentCallback ) =
2928 $commentStore->insertWithTempTable( $dbw,
'img_description', $comment );
2929 $actorFields = $actorMigration->getInsertValues( $dbw,
'img_user', $user );
2931 'img_name' => $row->fa_name,
2932 'img_size' => $row->fa_size,
2933 'img_width' => $row->fa_width,
2934 'img_height' => $row->fa_height,
2935 'img_metadata' => $props[
'metadata'],
2936 'img_bits' => $row->fa_bits,
2937 'img_media_type' => $props[
'media_type'],
2938 'img_major_mime' => $props[
'major_mime'],
2939 'img_minor_mime' => $props[
'minor_mime'],
2940 'img_timestamp' => $row->fa_timestamp,
2942 ] + $commentFields + $actorFields;
2945 if ( !$this->unsuppress && $row->fa_deleted ) {
2946 $status->fatal(
'undeleterevdel' );
2947 $this->file->unlock();
2951 $archiveName = $row->fa_archive_name;
2953 if ( $archiveName ==
'' ) {
2957 $timestamp =
wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2960 $archiveName =
wfTimestamp( TS_MW, $timestamp ) .
'!' . $row->fa_name;
2962 }
while ( isset( $archiveNames[$archiveName] ) );
2965 $archiveNames[$archiveName] =
true;
2966 $destRel = $this->file->getArchiveRel( $archiveName );
2968 'oi_name' => $row->fa_name,
2969 'oi_archive_name' => $archiveName,
2970 'oi_size' => $row->fa_size,
2971 'oi_width' => $row->fa_width,
2972 'oi_height' => $row->fa_height,
2973 'oi_bits' => $row->fa_bits,
2974 'oi_timestamp' => $row->fa_timestamp,
2975 'oi_metadata' => $props[
'metadata'],
2976 'oi_media_type' => $props[
'media_type'],
2977 'oi_major_mime' => $props[
'major_mime'],
2978 'oi_minor_mime' => $props[
'minor_mime'],
2979 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2981 ] + $commentStore->insert( $dbw,
'oi_description', $comment )
2982 + $actorMigration->getInsertValues( $dbw,
'oi_user', $user );
2985 $deleteIds[] = $row->fa_id;
2991 $storeBatch[] = [ $deletedUrl,
'public', $destRel ];
2992 $this->cleanupBatch[] = $row->fa_storage_key;
3001 $missingIds = array_diff( $this->ids, $idsPresent );
3003 foreach ( $missingIds as $id ) {
3004 $status->error(
'undelete-missing-filearchive', $id );
3007 if ( !$repo->hasSha1Storage() ) {
3010 if ( !$checkStatus->isGood() ) {
3011 $status->merge( $checkStatus );
3014 $storeBatch = $checkStatus->value;
3019 $status->merge( $storeStatus );
3026 $this->file->unlock();
3038 if ( $insertCurrent ) {
3039 $dbw->insert(
'image', $insertCurrent, __METHOD__ );
3040 $commentCallback( $insertCurrent[
'img_name'] );
3043 if ( $insertBatch ) {
3044 $dbw->insert(
'oldimage', $insertBatch, __METHOD__ );
3048 $dbw->delete(
'filearchive',
3049 [
'fa_id' => $deleteIds ],
3054 if (
$status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
3056 wfDebug( __METHOD__ .
" restored {$status->successCount} items, creating a new current\n" );
3060 $this->file->purgeEverything();
3062 wfDebug( __METHOD__ .
" restored {$status->successCount} as archived versions\n" );
3063 $this->file->purgeDescription();
3067 $this->file->unlock();
3078 $files = $filteredTriplets = [];
3079 foreach ( $triplets as $file ) {
3080 $files[$file[0]] = $file[0];
3083 $result = $this->file->repo->fileExistsBatch( $files );
3084 if ( in_array(
null, $result,
true ) ) {
3085 return Status::newFatal(
'backend-fail-internal',
3086 $this->file->repo->getBackend()->getName() );
3089 foreach ( $triplets as $file ) {
3090 if ( $result[$file[0]] ) {
3091 $filteredTriplets[] =
$file;
3095 return Status::newGood( $filteredTriplets );
3104 $files = $newBatch = [];
3105 $repo = $this->file->repo;
3107 foreach (
$batch as $file ) {
3108 $files[
$file] = $repo->getVirtualUrl(
'deleted' ) .
'/' .
3109 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3112 $result = $repo->fileExistsBatch( $files );
3114 foreach (
$batch as $file ) {
3115 if ( $result[$file] ) {
3116 $newBatch[] =
$file;
3129 if ( !$this->cleanupBatch ) {
3130 return $this->file->repo->newGood();
3135 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
3150 foreach ( $storeStatus->success as $i =>
$success ) {
3155 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3162# ------------------------------------------------------------------------------
3191 $this->file =
$file;
3193 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
3194 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
3195 $this->oldName = $this->file->getName();
3196 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
3197 $this->oldRel = $this->oldHash . $this->oldName;
3198 $this->newRel = $this->newHash . $this->newName;
3199 $this->db = $file->getRepo()->getMasterDB();
3206 $this->cur = [ $this->oldRel, $this->newRel ];
3214 $archiveBase =
'archive';
3216 $this->oldCount = 0;
3219 $result = $this->db->select(
'oldimage',
3220 [
'oi_archive_name',
'oi_deleted' ],
3221 [
'oi_name' => $this->oldName ],
3223 [
'LOCK IN SHARE MODE' ]
3226 foreach ( $result as $row ) {
3227 $archiveNames[] = $row->oi_archive_name;
3228 $oldName = $row->oi_archive_name;
3229 $bits = explode(
'!', $oldName, 2 );
3231 if ( count( $bits ) != 2 ) {
3232 wfDebug(
"Old file name missing !: '$oldName' \n" );
3236 list( $timestamp, $filename ) = $bits;
3238 if ( $this->oldName != $filename ) {
3239 wfDebug(
"Old file name doesn't match: '$oldName' \n" );
3251 "{$archiveBase}/{$this->oldHash}{$oldName}",
3252 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3256 return $archiveNames;
3264 $repo = $this->file->repo;
3268 $this->file->lock();
3273 if ( !$checkStatus->isGood() ) {
3274 $destFile->unlock();
3275 $this->file->unlock();
3276 $status->merge( $checkStatus );
3279 $triplets = $checkStatus->value;
3283 if ( !$statusDb->isGood() ) {
3284 $destFile->unlock();
3285 $this->file->unlock();
3286 $statusDb->setOK(
false );
3291 if ( !$repo->hasSha1Storage() ) {
3296 wfDebugLog(
'imagemove',
"Moved files for {$this->file->getName()}: " .
3297 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3298 if ( !$statusMove->isGood() ) {
3301 $destFile->unlock();
3302 $this->file->unlock();
3303 wfDebugLog(
'imagemove',
"Error in moving files: "
3304 . $statusMove->getWikiText(
false,
false,
'en' ) );
3305 $statusMove->setOK(
false );
3309 $status->merge( $statusMove );
3315 wfDebugLog(
'imagemove',
"Renamed {$this->file->getName()} in database: " .
3316 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3318 $destFile->unlock();
3319 $this->file->unlock();
3336 $repo = $this->file->repo;
3343 [
'img_name' => $this->oldName ],
3347 $oldRowCount = $dbw->selectRowCount(
3350 [
'oi_name' => $this->oldName ],
3355 if ( $hasCurrent ) {
3360 $status->successCount += $oldRowCount;
3364 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3366 $status->error(
'imageinvalidfilename' );
3384 [
'img_name' => $this->newName ],
3385 [
'img_name' => $this->oldName ],
3390 'image_comment_temp',
3391 [
'imgcomment_name' => $this->newName ],
3392 [
'imgcomment_name' => $this->oldName ],
3401 'oi_name' => $this->newName,
3402 'oi_archive_name = ' . $dbw->strreplace(
'oi_archive_name',
3403 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3405 [
'oi_name' => $this->oldName ],
3415 $moves = array_merge( [ $this->cur ], $this->olds );
3418 foreach ( $moves as $move ) {
3420 $srcUrl = $this->file->repo->getVirtualUrl() .
'/public/' . rawurlencode( $move[0] );
3421 $triplets[] = [ $srcUrl,
'public', $move[1] ];
3424 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3439 foreach ( $triplets as $file ) {
3440 $files[$file[0]] = $file[0];
3443 $result = $this->file->repo->fileExistsBatch( $files );
3444 if ( in_array(
null, $result,
true ) ) {
3445 return Status::newFatal(
'backend-fail-internal',
3446 $this->file->repo->getBackend()->getName() );
3449 $filteredTriplets = [];
3450 foreach ( $triplets as $file ) {
3451 if ( $result[$file[0]] ) {
3452 $filteredTriplets[] =
$file;
3454 wfDebugLog(
'imagemove',
"File {$file[0]} does not exist" );
3458 return Status::newGood( $filteredTriplets );
3469 foreach ( $triplets as $triplet ) {
3471 $pairs[] = [ $triplet[1], $triplet[2] ];
3474 $this->file->repo->cleanupBatch( $pairs );
3485 foreach ( $triplets as $triplet ) {
3486 $files[] = $triplet[0];
3489 $this->file->repo->cleanupBatch( $files );
3495 parent::__construct(
3503 $wgOut->setStatusCode( 429 );
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
int $wgCommentTableSchemaMigrationStage
Comment table schema migration stage.
$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.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to publish
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.
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.
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( $domain=false)
Internationalisation code.
static queueRecursiveJobsForTable(Title $title, $table, $action='unknown', $userName='unknown')
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.
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...
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.
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.
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 $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)
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)
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 log entries manually, to inject them into the database.
setTimestamp( $timestamp)
Set the timestamp of when the logged action took place.
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 newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
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.
merge( $other, $overwriteValue=false)
Merge another status object into this one.
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,...
getName()
Get the user name, or the IP of an anonymous user.
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or 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
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
the array() calling protocol came about after MediaWiki 1.4rc1.
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). '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
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
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
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
> 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. '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) name
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
const MIGRATION_WRITE_BOTH
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(!isset( $args[0])) $lang