162 $file->loadFromRow( $row );
179 $conds = [
'img_sha1' =>
$sha1 ];
184 $row =
$dbr->selectRow(
'image', self::selectFields(), $conds, __METHOD__ );
186 return self::newFromRow( $row,
$repo );
224 $this->metadata =
'';
225 $this->historyLine = 0;
226 $this->historyRes = null;
227 $this->dataLoaded =
false;
228 $this->extraDataLoaded =
false;
240 return $this->repo->getSharedCacheKey(
'file', sha1( $this->
getName() ) );
247 $this->dataLoaded =
false;
248 $this->extraDataLoaded =
false;
258 $cachedValues =
$cache->getWithSetCallback(
268 if ( $this->fileExists ) {
269 foreach ( $fields
as $field ) {
270 $cacheVal[$field] = $this->$field;
277 if ( isset( $cacheVal[$field] )
278 && strlen( $cacheVal[$field] ) > 100 * 1024
280 unset( $cacheVal[$field] );
284 if ( $this->fileExists ) {
287 $ttl = $cache::TTL_DAY;
292 [
'version' => self::VERSION ]
295 $this->fileExists = $cachedValues[
'fileExists'];
296 if ( $this->fileExists ) {
300 $this->dataLoaded =
true;
301 $this->extraDataLoaded =
true;
303 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
316 $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
317 function ()
use ( $key ) {
328 $props = $this->repo->getFileProps( $this->
getVirtualUrl() );
337 static $fields = [
'size',
'width',
'height',
'bits',
'media_type',
338 'major_mime',
'minor_mime',
'metadata',
'timestamp',
'sha1',
'user',
339 'user_text',
'description' ];
340 static $results = [];
342 if ( $prefix ==
'' ) {
346 if ( !isset( $results[$prefix] ) ) {
347 $prefixedFields = [];
348 foreach ( $fields
as $field ) {
349 $prefixedFields[] = $prefix . $field;
351 $results[$prefix] = $prefixedFields;
354 return $results[$prefix];
362 static $fields = [
'metadata' ];
363 static $results = [];
365 if ( $prefix ==
'' ) {
369 if ( !isset( $results[$prefix] ) ) {
370 $prefixedFields = [];
371 foreach ( $fields
as $field ) {
372 $prefixedFields[] = $prefix . $field;
374 $results[$prefix] = $prefixedFields;
377 return $results[$prefix];
385 $fname = get_class( $this ) .
'::' . __FUNCTION__;
387 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
388 $this->dataLoaded =
true;
389 $this->extraDataLoaded =
true;
392 ? $this->repo->getMasterDB()
393 : $this->repo->getSlaveDB();
401 $this->fileExists =
false;
410 $fname = get_class( $this ) .
'::' . __FUNCTION__;
412 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
413 $this->extraDataLoaded =
true;
425 throw new MWException(
"Could not find data for image '{$this->getName()}'." );
438 'img_name' => $this->
getName(),
439 'img_timestamp' =>
$dbr->timestamp( $this->getTimestamp() )
444 # File may have been uploaded over in the meantime; check the old versions
447 'oi_timestamp' =>
$dbr->timestamp( $this->getTimestamp() )
464 $array = (
array)$row;
465 $prefixLength = strlen( $prefix );
468 if ( substr(
key( $array ), 0, $prefixLength ) !== $prefix ) {
469 throw new MWException( __METHOD__ .
': incorrect $prefix parameter' );
493 $decoded[
'metadata'] = $this->repo->getSlaveDB()->decodeBlob( $decoded[
'metadata'] );
495 if ( empty( $decoded[
'major_mime'] ) ) {
496 $decoded[
'mime'] =
'unknown/unknown';
498 if ( !$decoded[
'minor_mime'] ) {
499 $decoded[
'minor_mime'] =
'unknown';
501 $decoded[
'mime'] = $decoded[
'major_mime'] .
'/' . $decoded[
'minor_mime'];
505 $decoded[
'sha1'] = rtrim( $decoded[
'sha1'],
"\0" );
511 foreach ( [
'size',
'width',
'height',
'bits' ]
as $field ) {
512 $decoded[$field] = +$decoded[$field];
525 $this->dataLoaded =
true;
526 $this->extraDataLoaded =
true;
528 $array = $this->
decodeRow( $row, $prefix );
534 $this->fileExists =
true;
543 if ( !$this->dataLoaded ) {
544 if (
$flags & self::READ_LATEST ) {
551 if ( (
$flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
568 if ( is_null( $this->media_type ) || $this->mime ==
'image/svg' ) {
583 $this->upgrading =
true;
586 $this->upgrading =
false;
611 # Don't destroy file info of missing files
612 if ( !$this->fileExists ) {
614 wfDebug( __METHOD__ .
": file does not exist, aborting\n" );
619 $dbw = $this->repo->getMasterDB();
620 list( $major, $minor ) = self::splitMime( $this->mime );
627 wfDebug( __METHOD__ .
': upgrading ' . $this->
getName() .
" to the current schema\n" );
629 $dbw->update(
'image',
631 'img_size' => $this->size,
632 'img_width' => $this->
width,
633 'img_height' => $this->height,
634 'img_bits' => $this->bits,
635 'img_media_type' => $this->media_type,
636 'img_major_mime' => $major,
637 'img_minor_mime' => $minor,
638 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
641 [
'img_name' => $this->
getName() ],
648 $this->upgraded =
true;
662 $this->dataLoaded =
true;
664 $fields[] =
'fileExists';
666 foreach ( $fields
as $field ) {
667 if ( isset( $info[$field] ) ) {
668 $this->$field = $info[$field];
673 if ( isset( $info[
'major_mime'] ) ) {
674 $this->mime =
"{$info['major_mime']}/{$info['minor_mime']}";
675 } elseif ( isset( $info[
'mime'] ) ) {
676 $this->mime = $info[
'mime'];
677 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
693 if ( $this->missing === null ) {
717 return $dim[
'width'];
744 return $dim[
'height'];
764 if (
$type ==
'text' ) {
779 $pageId = $this->
title->getArticleID();
781 if ( $pageId !== null ) {
782 $url = $this->repo->makeUrl( [
'curid' => $pageId ] );
783 if (
$url !==
false ) {
795 $this->
load( self::LOAD_ALL );
871 if ( $archiveName ) {
877 $backend = $this->repo->getBackend();
880 $iterator = $backend->getFileList( [
'dir' =>
$dir ] );
881 foreach ( $iterator
as $file ) {
927 Hooks::run(
'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
952 array_shift(
$urls );
955 if ( !empty(
$options[
'forThumbRefresh'] ) ) {
963 Hooks::run(
'LocalFilePurgeThumbnails', [ $this,
false ] );
990 [
'transformParams' => [
'width' => $size ] ]
1006 $fileListDebug = strtr(
1007 var_export(
$files,
true ),
1010 wfDebug( __METHOD__ .
": $fileListDebug\n" );
1014 # Check that the base file name is part of the thumb name
1015 # This is a basic sanity check to avoid erasing unrelated directories
1016 if ( strpos( $file, $this->
getName() ) !==
false
1017 || strpos( $file,
"-thumbnail" ) !==
false
1019 $purgeList[] =
"{$dir}/{$file}";
1023 # Delete the thumbnails
1024 $this->repo->quickPurgeBatch( $purgeList );
1025 # Clear out the thumbnail directory if empty
1026 $this->repo->quickCleanDir(
$dir );
1040 $dbr = $this->repo->getSlaveDB();
1043 $conds = $opts = $join_conds = [];
1044 $eq = $inc ?
'=' :
'';
1045 $conds[] =
"oi_name = " .
$dbr->addQuotes( $this->
title->getDBkey() );
1048 $conds[] =
"oi_timestamp <$eq " .
$dbr->addQuotes(
$dbr->timestamp( $start ) );
1052 $conds[] =
"oi_timestamp >$eq " .
$dbr->addQuotes(
$dbr->timestamp( $end ) );
1060 $order = ( !$start && $end !== null ) ?
'ASC' :
'DESC';
1061 $opts[
'ORDER BY'] =
"oi_timestamp $order";
1062 $opts[
'USE INDEX'] = [
'oldimage' =>
'oi_name_timestamp' ];
1065 &$conds, &$opts, &$join_conds ] );
1067 $res =
$dbr->select(
$tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1070 foreach (
$res as $row ) {
1071 $r[] = $this->repo->newFileFromRow( $row );
1074 if ( $order ==
'ASC' ) {
1075 $r = array_reverse( $r );
1091 # Polymorphic function name to distinguish foreign and local fetches
1092 $fname = get_class( $this ) .
'::' . __FUNCTION__;
1094 $dbr = $this->repo->getSlaveDB();
1096 if ( $this->historyLine == 0 ) {
1097 $this->historyRes =
$dbr->select(
'image',
1100 "'' AS oi_archive_name",
1104 [
'img_name' => $this->
title->getDBkey() ],
1108 if ( 0 ==
$dbr->numRows( $this->historyRes ) ) {
1109 $this->historyRes = null;
1113 } elseif ( $this->historyLine == 1 ) {
1114 $this->historyRes =
$dbr->select(
'oldimage',
'*',
1115 [
'oi_name' => $this->
title->getDBkey() ],
1117 [
'ORDER BY' =>
'oi_timestamp DESC' ]
1120 $this->historyLine++;
1122 return $dbr->fetchObject( $this->historyRes );
1129 $this->historyLine = 0;
1131 if ( !is_null( $this->historyRes ) ) {
1132 $this->historyRes = null;
1171 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1175 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1177 if ( $this->repo->isVirtualUrl( $srcPath )
1180 $props = $this->repo->getFileProps( $srcPath );
1183 $props = $mwProps->getPropsFromPath( $srcPath,
true );
1204 if (
$status->successCount >= 2 ) {
1213 $status->fatal(
'filenotfound', $srcPath );
1268 if ( is_null(
$user ) ) {
1273 $dbw = $this->repo->getMasterDB();
1275 # Imports or such might force a certain timestamp; otherwise we generate
1276 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1279 $allowTimeKludge =
true;
1281 $allowTimeKludge =
false;
1284 $props = $props ?: $this->repo->getFileProps( $this->
getVirtualUrl() );
1286 $props[
'user'] =
$user->getId();
1287 $props[
'user_text'] =
$user->getName();
1291 # Fail now if the file isn't there
1292 if ( !$this->fileExists ) {
1293 wfDebug( __METHOD__ .
": File " . $this->
getRel() .
" went missing!\n" );
1298 $dbw->startAtomic( __METHOD__ );
1300 # Test to see if the row exists using INSERT IGNORE
1301 # This avoids race conditions by locking the row until the commit, and also
1302 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1303 $dbw->insert(
'image',
1305 'img_name' => $this->
getName(),
1306 'img_size' => $this->size,
1307 'img_width' => intval( $this->
width ),
1308 'img_height' => intval( $this->height ),
1309 'img_bits' => $this->bits,
1310 'img_media_type' => $this->media_type,
1311 'img_major_mime' => $this->major_mime,
1312 'img_minor_mime' => $this->minor_mime,
1315 'img_user' =>
$user->getId(),
1316 'img_user_text' =>
$user->getName(),
1317 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1324 $reupload = ( $dbw->affectedRows() == 0 );
1326 if ( $allowTimeKludge ) {
1327 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1328 $ltimestamp = $dbw->selectField(
1331 [
'img_name' => $this->
getName() ],
1333 [
'LOCK IN SHARE MODE' ]
1336 # Avoid a timestamp that is not newer than the last version
1337 # TODO: the image/oldimage tables should be like page/revision with an ID field
1340 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1345 # (bug 34993) Note: $oldver can be empty here, if the previous
1346 # version of the file was broken. Allow registration of the new
1347 # version to continue anyway, because that's better than having
1348 # an image that's not fixable by user operations.
1349 # Collision, this is an update of a file
1350 # Insert previous contents into oldimage
1351 $dbw->insertSelect(
'oldimage',
'image',
1353 'oi_name' =>
'img_name',
1354 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1355 'oi_size' =>
'img_size',
1356 'oi_width' =>
'img_width',
1357 'oi_height' =>
'img_height',
1358 'oi_bits' =>
'img_bits',
1359 'oi_timestamp' =>
'img_timestamp',
1360 'oi_description' =>
'img_description',
1361 'oi_user' =>
'img_user',
1362 'oi_user_text' =>
'img_user_text',
1363 'oi_metadata' =>
'img_metadata',
1364 'oi_media_type' =>
'img_media_type',
1365 'oi_major_mime' =>
'img_major_mime',
1366 'oi_minor_mime' =>
'img_minor_mime',
1367 'oi_sha1' =>
'img_sha1'
1369 [
'img_name' => $this->
getName() ],
1373 # Update the current image row
1374 $dbw->update(
'image',
1376 'img_size' => $this->size,
1377 'img_width' => intval( $this->
width ),
1378 'img_height' => intval( $this->height ),
1379 'img_bits' => $this->bits,
1380 'img_media_type' => $this->media_type,
1381 'img_major_mime' => $this->major_mime,
1382 'img_minor_mime' => $this->minor_mime,
1385 'img_user' =>
$user->getId(),
1386 'img_user_text' =>
$user->getName(),
1387 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1390 [
'img_name' => $this->
getName() ],
1396 $descId = $descTitle->getArticleID();
1398 $wikiPage->setFile( $this );
1401 $logEntry =
new ManualLogEntry(
'upload', $reupload ?
'overwrite' :
'upload' );
1402 $logEntry->setTimestamp( $this->timestamp );
1403 $logEntry->setPerformer(
$user );
1405 $logEntry->setTarget( $descTitle );
1408 $logEntry->setParameters(
1410 'img_sha1' => $this->sha1,
1420 $logId = $logEntry->insert();
1422 if ( $descTitle->exists() ) {
1426 $editSummary = $formatter->getPlainActionText();
1435 if ( $nullRevision ) {
1436 $nullRevision->insertOn( $dbw );
1438 'NewRevisionFromEditComplete',
1439 [ $wikiPage, $nullRevision, $nullRevision->getParentId(),
$user ]
1441 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1443 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1446 $newPageContent = null;
1452 # Defer purges, page creation, and link updates in case they error out.
1453 # The most important thing is that files and the DB registry stay synced.
1454 $dbw->endAtomic( __METHOD__ );
1456 # Do some cache purges after final commit so that:
1457 # a) Changes are more likely to be seen post-purge
1458 # b) They won't cause rollback of the log publish/update above
1465 $logEntry, $logId, $descId, $tags
1467 # Update memcache after the commit
1470 $updateLogPage =
false;
1471 if ( $newPageContent ) {
1472 # New file page; create the description page.
1473 # There's already a log entry, so don't make a second RC entry
1474 # CDN and file cache for the description page are purged by doEditContent.
1475 $status = $wikiPage->doEditContent(
1483 if ( isset(
$status->value[
'revision'] ) ) {
1487 $logEntry->setAssociatedRevId(
$rev->getId() );
1491 if ( isset(
$status->value[
'revision'] ) ) {
1494 $updateLogPage =
$rev->getPage();
1497 # Existing file page: invalidate description page cache
1498 $wikiPage->getTitle()->invalidateCache();
1499 $wikiPage->getTitle()->purgeSquid();
1500 # Allow the new file version to be patrolled from the page footer
1504 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1505 # but setAssociatedRevId() wasn't called at that point yet...
1506 $logParams = $logEntry->getParameters();
1507 $logParams[
'associated_rev_id'] = $logEntry->getAssociatedRevId();
1509 if ( $updateLogPage ) {
1510 # Also log page, in case where we just created it above
1511 $update[
'log_page'] = $updateLogPage;
1513 $this->
getRepo()->getMasterDB()->update(
1516 [
'log_id' => $logId ],
1519 $this->
getRepo()->getMasterDB()->insert(
1522 'ls_field' =>
'associated_rev_id',
1523 'ls_value' => $logEntry->getAssociatedRevId(),
1524 'ls_log_id' => $logId,
1529 # Add change tags, if any
1531 $logEntry->setTags( $tags );
1534 # Uploads can be patrolled
1535 $logEntry->setIsPatrollable(
true );
1537 # Now that the log entry is up-to-date, make an RC entry.
1538 $logEntry->publish( $logId );
1540 # Run hook for other updates (typically more cache purging)
1541 Hooks::run(
'FileUpload', [ $this, $reupload, !$newPageContent ] );
1544 # Delete old thumbnails
1546 # Remove the old file from the CDN cache
1552 # Update backlink pages pointing to this title if created
1563 # This is a new file, so update the image count
1567 # Invalidate cache for all pages using this file
1608 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1618 $archiveRel =
'archive/' . $this->
getHashPath() . $archiveName;
1626 $dst = $wrapperBackend->getPathForSHA1(
$sha1 );
1633 $status->value = $archiveName;
1639 if (
$status->value ==
'new' ) {
1642 $status->value = $archiveName;
1669 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1673 wfDebugLog(
'imagemove',
"Got request to move {$this->name} to " . $target->getText() );
1677 $batch->addCurrent();
1678 $archiveNames = $batch->addOlds();
1682 wfDebugLog(
'imagemove',
"Finished moving {$this->name}" );
1690 $this->
getRepo()->getMasterDB(),
1692 function ()
use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1693 $oldTitleFile->purgeEverything();
1694 foreach ( $archiveNames
as $archiveName ) {
1695 $oldTitleFile->purgeOldThumbnails( $archiveName );
1697 $newTitleFile->purgeEverything();
1705 $this->
title = $target;
1707 unset( $this->
name );
1708 unset( $this->hashPath );
1727 function delete( $reason, $suppress =
false,
$user = null ) {
1728 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1737 $archiveNames =
$batch->addOlds();
1748 $this->
getRepo()->getMasterDB(),
1750 function ()
use ( $archiveNames ) {
1752 foreach ( $archiveNames
as $archiveName ) {
1762 foreach ( $archiveNames
as $archiveName ) {
1786 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1793 $batch->addOld( $archiveName );
1821 function restore( $versions = [], $unsuppress =
false ) {
1822 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1832 $batch->addIds( $versions );
1836 $cleanupStatus =
$batch->cleanup();
1837 $cleanupStatus->successCount = 0;
1838 $cleanupStatus->failCount = 0;
1839 $status->merge( $cleanupStatus );
1856 return $this->
title->getLocalURL();
1872 $content = $revision->getContent();
1878 return $pout->getText();
1888 if ( $audience == self::FOR_PUBLIC && $this->
isDeleted( self::DELETED_COMMENT ) ) {
1890 } elseif ( $audience == self::FOR_THIS_USER
1915 if ( $this->descriptionTouched === null ) {
1917 'page_namespace' => $this->
title->getNamespace(),
1918 'page_title' => $this->
title->getDBkey()
1920 $touched = $this->repo->getSlaveDB()->selectField(
'page',
'page_touched', $cond, __METHOD__ );
1921 $this->descriptionTouched = $touched ?
wfTimestamp(
TS_MW, $touched ) :
false;
1933 if ( $this->sha1 ==
'' && $this->fileExists ) {
1936 $this->sha1 = $this->repo->getFileSha1( $this->
getPath() );
1937 if ( !
wfReadOnly() && strval( $this->sha1 ) !=
'' ) {
1938 $dbw = $this->repo->getMasterDB();
1939 $dbw->update(
'image',
1940 [
'img_sha1' => $this->sha1 ],
1941 [
'img_name' => $this->
getName() ],
1959 return $this->extraDataLoaded
1960 && strlen(
serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1968 return $this->
getRepo()->getBackend()->lockFiles(
1978 return $this->
getRepo()->getBackend()->unlockFiles(
1993 if ( !$this->locked ) {
1994 $logger = LoggerFactory::getInstance(
'LocalFile' );
1996 $dbw = $this->repo->getMasterDB();
1997 $makesTransaction = !$dbw->trxLevel();
1998 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2004 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2005 $logger->warning(
"Failed to lock '{file}'", [
'file' => $this->
name ] );
2011 $dbw->onTransactionResolution(
2012 function ()
use ( $logger ) {
2015 $logger->error(
"Failed to unlock '{file}'", [
'file' => $this->
name ] );
2021 $this->lockedOwnTrx = $makesTransaction;
2038 if ( $this->locked ) {
2040 if ( !$this->locked ) {
2041 $dbw = $this->repo->getMasterDB();
2042 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2043 $this->lockedOwnTrx =
false;
2052 return $this->
getRepo()->newFatal(
'filereadonlyerror', $this->
getName(),
2064 # ------------------------------------------------------------------------------
2111 $this->status = $file->repo->newGood();
2115 $this->srcRels[
'.'] = $this->
file->getRel();
2122 $this->srcRels[$oldName] = $this->
file->getArchiveRel( $oldName );
2123 $this->archiveUrls[] = $this->
file->getArchiveUrl( $oldName );
2133 $dbw = $this->
file->repo->getMasterDB();
2134 $result = $dbw->select(
'oldimage',
2135 [
'oi_archive_name' ],
2136 [
'oi_name' => $this->
file->getName() ],
2141 $this->
addOld( $row->oi_archive_name );
2142 $archiveNames[] = $row->oi_archive_name;
2145 return $archiveNames;
2152 if ( !isset( $this->srcRels[
'.'] ) ) {
2154 $deleteCurrent =
false;
2157 unset( $oldRels[
'.'] );
2158 $deleteCurrent =
true;
2161 return [ $oldRels, $deleteCurrent ];
2171 if ( $deleteCurrent ) {
2175 if ( count( $oldRels ) ) {
2176 $dbw = $this->
file->repo->getMasterDB();
2177 $res = $dbw->select(
2179 [
'oi_archive_name',
'oi_sha1' ],
2180 [
'oi_archive_name' => array_keys( $oldRels ),
2181 'oi_name' => $this->
file->getName() ],
2185 foreach (
$res as $row ) {
2186 if ( rtrim( $row->oi_sha1,
"\0" ) ===
'' ) {
2188 $oldUrl = $this->
file->getArchiveVirtualUrl( $row->oi_archive_name );
2189 $props = $this->
file->repo->getFileProps( $oldUrl );
2191 if ( $props[
'fileExists'] ) {
2193 $dbw->update(
'oldimage',
2194 [
'oi_sha1' => $props[
'sha1'] ],
2195 [
'oi_name' => $this->
file->getName(),
'oi_archive_name' => $row->oi_archive_name ],
2197 $hashes[$row->oi_archive_name] = $props[
'sha1'];
2199 $hashes[$row->oi_archive_name] =
false;
2202 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2207 $missing = array_diff_key( $this->srcRels,
$hashes );
2209 foreach ( $missing
as $name => $rel ) {
2210 $this->status->error(
'filedelete-old-unregistered',
$name );
2215 $this->status->error(
'filedelete-missing', $this->srcRels[
$name] );
2225 $dbw = $this->
file->repo->getMasterDB();
2226 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2227 $encUserId = $dbw->addQuotes( $this->
user->getId() );
2228 $encReason = $dbw->addQuotes( $this->reason );
2229 $encGroup = $dbw->addQuotes(
'deleted' );
2230 $ext = $this->
file->getExtension();
2231 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2232 $encExt = $dbw->addQuotes( $dotExt );
2236 if ( $this->suppress ) {
2244 $bitfield =
'oi_deleted';
2247 if ( $deleteCurrent ) {
2252 'fa_storage_group' => $encGroup,
2253 'fa_storage_key' => $dbw->conditional(
2254 [
'img_sha1' =>
'' ],
2255 $dbw->addQuotes(
'' ),
2256 $dbw->buildConcat( [
"img_sha1", $encExt ] )
2258 'fa_deleted_user' => $encUserId,
2259 'fa_deleted_timestamp' => $encTimestamp,
2260 'fa_deleted_reason' => $encReason,
2261 'fa_deleted' => $this->suppress ? $bitfield : 0,
2263 'fa_name' =>
'img_name',
2264 'fa_archive_name' =>
'NULL',
2265 'fa_size' =>
'img_size',
2266 'fa_width' =>
'img_width',
2267 'fa_height' =>
'img_height',
2268 'fa_metadata' =>
'img_metadata',
2269 'fa_bits' =>
'img_bits',
2270 'fa_media_type' =>
'img_media_type',
2271 'fa_major_mime' =>
'img_major_mime',
2272 'fa_minor_mime' =>
'img_minor_mime',
2273 'fa_description' =>
'img_description',
2274 'fa_user' =>
'img_user',
2275 'fa_user_text' =>
'img_user_text',
2276 'fa_timestamp' =>
'img_timestamp',
2277 'fa_sha1' =>
'img_sha1'
2279 [
'img_name' => $this->
file->getName() ],
2284 if ( count( $oldRels ) ) {
2285 $res = $dbw->select(
2289 'oi_name' => $this->
file->getName(),
2290 'oi_archive_name' => array_keys( $oldRels )
2296 foreach (
$res as $row ) {
2299 'fa_storage_group' =>
'deleted',
2300 'fa_storage_key' => ( $row->oi_sha1 ===
'' )
2302 :
"{$row->oi_sha1}{$dotExt}",
2303 'fa_deleted_user' => $this->
user->getId(),
2304 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2307 'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2308 'fa_name' => $row->oi_name,
2309 'fa_archive_name' => $row->oi_archive_name,
2310 'fa_size' => $row->oi_size,
2311 'fa_width' => $row->oi_width,
2312 'fa_height' => $row->oi_height,
2313 'fa_metadata' => $row->oi_metadata,
2314 'fa_bits' => $row->oi_bits,
2315 'fa_media_type' => $row->oi_media_type,
2316 'fa_major_mime' => $row->oi_major_mime,
2317 'fa_minor_mime' => $row->oi_minor_mime,
2318 'fa_description' => $row->oi_description,
2319 'fa_user' => $row->oi_user,
2320 'fa_user_text' => $row->oi_user_text,
2321 'fa_timestamp' => $row->oi_timestamp,
2322 'fa_sha1' => $row->oi_sha1
2326 $dbw->insert(
'filearchive', $rowsInsert, __METHOD__ );
2331 $dbw = $this->
file->repo->getMasterDB();
2334 if ( count( $oldRels ) ) {
2335 $dbw->delete(
'oldimage',
2337 'oi_name' => $this->
file->getName(),
2338 'oi_archive_name' => array_keys( $oldRels )
2342 if ( $deleteCurrent ) {
2343 $dbw->delete(
'image', [
'img_name' => $this->
file->getName() ], __METHOD__ );
2352 $repo = $this->
file->getRepo();
2353 $this->
file->lock();
2357 $this->deletionBatch = [];
2358 $ext = $this->
file->getExtension();
2359 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2361 foreach ( $this->srcRels
as $name => $srcRel ) {
2365 $key = $hash . $dotExt;
2366 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2367 $this->deletionBatch[
$name] = [ $srcRel, $dstRel ];
2371 if ( !$repo->hasSha1Storage() ) {
2375 if ( !$checkStatus->isGood() ) {
2376 $this->status->merge( $checkStatus );
2379 $this->deletionBatch = $checkStatus->value;
2382 $status = $this->
file->repo->deleteBatch( $this->deletionBatch );
2384 $this->status->merge(
$status );
2388 if ( !$this->status->isOK() ) {
2390 $this->
file->unlock();
2401 $this->
file->unlock();
2415 list( $src, ) = $batchItem;
2416 $files[$src] = $this->
file->repo->getVirtualUrl(
'public' ) .
'/' . rawurlencode( $src );
2420 if ( in_array( null,
$result,
true ) ) {
2422 $this->
file->repo->getBackend()->getName() );
2426 if (
$result[$batchItem[0]] ) {
2427 $newBatch[] = $batchItem;
2435 # ------------------------------------------------------------------------------
2463 $this->cleanupBatch = $this->ids = [];
2473 $this->ids[] = $fa_id;
2481 $this->ids = array_merge( $this->ids,
$ids );
2503 $repo = $this->
file->getRepo();
2504 if ( !$this->all && !$this->ids ) {
2506 return $repo->newGood();
2509 $lockOwnsTrx = $this->
file->lock();
2511 $dbw = $this->
file->repo->getMasterDB();
2514 $exists = (bool)$dbw->selectField(
'image',
'1',
2515 [
'img_name' => $this->file->getName() ],
2520 $lockOwnsTrx ? [] : [
'LOCK IN SHARE MODE' ]
2525 $conditions = [
'fa_name' => $this->
file->getName() ];
2527 if ( !$this->all ) {
2536 [
'ORDER BY' =>
'fa_timestamp DESC' ]
2542 $insertCurrent =
false;
2548 $idsPresent[] = $row->fa_id;
2550 if ( $row->fa_name != $this->file->getName() ) {
2551 $status->error(
'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2556 if ( $row->fa_storage_key ==
'' ) {
2558 $status->error(
'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2563 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2564 $row->fa_storage_key;
2565 $deletedUrl = $repo->getVirtualUrl() .
'/deleted/' . $deletedRel;
2567 if ( isset( $row->fa_sha1 ) ) {
2568 $sha1 = $row->fa_sha1;
2575 if ( strlen( $sha1 ) == 32 && $sha1[0] ==
'0' ) {
2576 $sha1 = substr( $sha1, 1 );
2579 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime ==
'unknown'
2580 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime ==
'unknown'
2581 || is_null( $row->fa_media_type ) || $row->fa_media_type ==
'UNKNOWN'
2582 || is_null( $row->fa_metadata )
2589 'minor_mime' => $row->fa_minor_mime,
2590 'major_mime' => $row->fa_major_mime,
2591 'media_type' => $row->fa_media_type,
2592 'metadata' => $row->fa_metadata
2596 if ( $first && !$exists ) {
2598 $destRel = $this->
file->getRel();
2600 'img_name' => $row->fa_name,
2601 'img_size' => $row->fa_size,
2602 'img_width' => $row->fa_width,
2603 'img_height' => $row->fa_height,
2604 'img_metadata' => $props[
'metadata'],
2605 'img_bits' => $row->fa_bits,
2606 'img_media_type' => $props[
'media_type'],
2607 'img_major_mime' => $props[
'major_mime'],
2608 'img_minor_mime' => $props[
'minor_mime'],
2609 'img_description' => $row->fa_description,
2610 'img_user' => $row->fa_user,
2611 'img_user_text' => $row->fa_user_text,
2612 'img_timestamp' => $row->fa_timestamp,
2617 if ( !$this->unsuppress && $row->fa_deleted ) {
2618 $status->fatal(
'undeleterevdel' );
2619 $this->
file->unlock();
2623 $archiveName = $row->fa_archive_name;
2625 if ( $archiveName ==
'' ) {
2634 }
while ( isset( $archiveNames[$archiveName] ) );
2637 $archiveNames[$archiveName] =
true;
2638 $destRel = $this->
file->getArchiveRel( $archiveName );
2640 'oi_name' => $row->fa_name,
2641 'oi_archive_name' => $archiveName,
2642 'oi_size' => $row->fa_size,
2643 'oi_width' => $row->fa_width,
2644 'oi_height' => $row->fa_height,
2645 'oi_bits' => $row->fa_bits,
2646 'oi_description' => $row->fa_description,
2647 'oi_user' => $row->fa_user,
2648 'oi_user_text' => $row->fa_user_text,
2649 'oi_timestamp' => $row->fa_timestamp,
2650 'oi_metadata' => $props[
'metadata'],
2651 'oi_media_type' => $props[
'media_type'],
2652 'oi_major_mime' => $props[
'major_mime'],
2653 'oi_minor_mime' => $props[
'minor_mime'],
2654 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2655 'oi_sha1' => $sha1 ];
2658 $deleteIds[] = $row->fa_id;
2664 $storeBatch[] = [ $deletedUrl,
'public', $destRel ];
2665 $this->cleanupBatch[] = $row->fa_storage_key;
2674 $missingIds = array_diff( $this->ids, $idsPresent );
2676 foreach ( $missingIds
as $id ) {
2677 $status->error(
'undelete-missing-filearchive', $id );
2680 if ( !$repo->hasSha1Storage() ) {
2683 if ( !$checkStatus->isGood() ) {
2684 $status->merge( $checkStatus );
2687 $storeBatch = $checkStatus->value;
2692 $status->merge( $storeStatus );
2699 $this->
file->unlock();
2711 if ( $insertCurrent ) {
2712 $dbw->insert(
'image', $insertCurrent, __METHOD__ );
2715 if ( $insertBatch ) {
2716 $dbw->insert(
'oldimage', $insertBatch, __METHOD__ );
2720 $dbw->delete(
'filearchive',
2721 [
'fa_id' => $deleteIds ],
2726 if (
$status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
2728 wfDebug( __METHOD__ .
" restored {$status->successCount} items, creating a new current\n" );
2732 $this->
file->purgeEverything();
2734 wfDebug( __METHOD__ .
" restored {$status->successCount} as archived versions\n" );
2735 $this->
file->purgeDescription();
2739 $this->
file->unlock();
2750 $files = $filteredTriplets = [];
2751 foreach ( $triplets
as $file ) {
2752 $files[$file[0]] = $file[0];
2756 if ( in_array( null,
$result,
true ) ) {
2758 $this->
file->repo->getBackend()->getName() );
2761 foreach ( $triplets
as $file ) {
2763 $filteredTriplets[] =
$file;
2777 $repo = $this->
file->repo;
2780 $files[
$file] = $repo->getVirtualUrl(
'deleted' ) .
'/' .
2781 rawurlencode( $repo->getDeletedHashPath( $file ) .
$file );
2788 $newBatch[] =
$file;
2801 if ( !$this->cleanupBatch ) {
2802 return $this->
file->repo->newGood();
2807 $status = $this->
file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2822 foreach ( $storeStatus->success
as $i =>
$success ) {
2827 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2834 # ------------------------------------------------------------------------------
2865 $this->oldHash = $this->
file->repo->getHashPath( $this->
file->getName() );
2866 $this->newHash = $this->
file->repo->getHashPath( $this->target->getDBkey() );
2867 $this->oldName = $this->
file->getName();
2868 $this->newName = $this->
file->repo->getNameFromTitle( $this->target );
2869 $this->oldRel = $this->oldHash . $this->oldName;
2870 $this->newRel = $this->newHash . $this->newName;
2871 $this->db = $file->
getRepo()->getMasterDB();
2878 $this->cur = [ $this->oldRel, $this->newRel ];
2886 $archiveBase =
'archive';
2888 $this->oldCount = 0;
2891 $result = $this->db->select(
'oldimage',
2892 [
'oi_archive_name',
'oi_deleted' ],
2893 [
'oi_name' => $this->oldName ],
2895 [
'LOCK IN SHARE MODE' ]
2899 $archiveNames[] = $row->oi_archive_name;
2900 $oldName = $row->oi_archive_name;
2901 $bits = explode(
'!', $oldName, 2 );
2903 if ( count( $bits ) != 2 ) {
2904 wfDebug(
"Old file name missing !: '$oldName' \n" );
2910 if ( $this->oldName != $filename ) {
2911 wfDebug(
"Old file name doesn't match: '$oldName' \n" );
2923 "{$archiveBase}/{$this->oldHash}{$oldName}",
2924 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2928 return $archiveNames;
2936 $repo = $this->
file->repo;
2940 $this->
file->lock();
2945 if ( !$checkStatus->isGood() ) {
2946 $destFile->unlock();
2947 $this->
file->unlock();
2948 $status->merge( $checkStatus );
2951 $triplets = $checkStatus->value;
2955 if ( !$statusDb->isGood() ) {
2956 $destFile->unlock();
2957 $this->
file->unlock();
2958 $statusDb->setOK(
false );
2963 if ( !$repo->hasSha1Storage() ) {
2968 wfDebugLog(
'imagemove',
"Moved files for {$this->file->getName()}: " .
2969 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2970 if ( !$statusMove->isGood() ) {
2973 $destFile->unlock();
2974 $this->
file->unlock();
2975 wfDebugLog(
'imagemove',
"Error in moving files: "
2976 . $statusMove->getWikiText(
false,
false,
'en' ) );
2977 $statusMove->setOK(
false );
2981 $status->merge( $statusMove );
2987 wfDebugLog(
'imagemove',
"Renamed {$this->file->getName()} in database: " .
2988 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2990 $destFile->unlock();
2991 $this->
file->unlock();
3008 $repo = $this->
file->repo;
3015 [
'img_name' => $this->oldName ],
3019 $oldRowCount = $dbw->selectField(
3022 [
'oi_name' => $this->oldName ],
3027 if ( $hasCurrent ) {
3032 $status->successCount += $oldRowCount;
3036 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3038 $status->error(
'imageinvalidfilename' );
3054 [
'img_name' => $this->newName ],
3055 [
'img_name' => $this->oldName ],
3062 'oi_name' => $this->newName,
3063 'oi_archive_name = ' . $dbw->strreplace(
'oi_archive_name',
3064 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3066 [
'oi_name' => $this->oldName ],
3076 $moves = array_merge( [ $this->cur ], $this->olds );
3079 foreach ( $moves
as $move ) {
3081 $srcUrl = $this->
file->repo->getVirtualUrl() .
'/public/' . rawurlencode( $move[0] );
3082 $triplets[] = [ $srcUrl,
'public', $move[1] ];
3085 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3100 foreach ( $triplets
as $file ) {
3101 $files[$file[0]] = $file[0];
3105 if ( in_array( null,
$result,
true ) ) {
3107 $this->
file->repo->getBackend()->getName() );
3110 $filteredTriplets = [];
3111 foreach ( $triplets
as $file ) {
3113 $filteredTriplets[] =
$file;
3115 wfDebugLog(
'imagemove',
"File {$file[0]} does not exist" );
3130 foreach ( $triplets
as $triplet ) {
3132 $pairs[] = [ $triplet[1], $triplet[2] ];
3135 $this->
file->repo->cleanupBatch( $pairs );
3146 foreach ( $triplets
as $triplet ) {
3156 parent::__construct(
3164 $wgOut->setStatusCode( 429 );
static purgePatrolFooterCache($articleID)
Purge the cache used to check if it is worth showing the patrol footer For example, it is done during re-uploads when file patrol is used.
removeNonexistentFiles($batch)
Removes non-existent files from a deletion batch.
getArchiveThumbPath($archiveName, $suffix=false)
Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified.
static getMainWANInstance()
Get the main WAN cache object.
exists()
canRender inherited
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
invalidateCache()
Purge the file object/metadata cache.
the array() calling protocol came about after MediaWiki 1.4rc1.
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
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.
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
assertTitleDefined()
Assert that $this->title is set to a Title.
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...
addAll()
Add all revisions of the file.
cleanupTarget($triplets)
Cleanup a partially moved array of triplets by deleting the target files.
processing should stop and the error should be shown to the user * false
cleanupSource($triplets)
Cleanup a fully moved array of triplets by deleting the source files.
loadFromRow($row, $prefix= 'img_')
Load file metadata from a DB result row.
string $minor_mime
Minor MIME type.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getHistory($limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
restore($versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
static singleton()
Get an instance of this class.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
static newFatal($message)
Factory function for fatal errors.
static getCacheSetOptions(IDatabase $db1)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Set options of the Parser.
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
if(!isset($args[0])) $lang
__construct(File $file, $reason= '', $suppress=false, $user=null)
cleanup()
Delete unused files in the deleted zone.
getUser($type= 'text')
Returns ID or name of user who uploaded the file.
getThumbPath($suffix=false)
Get the path of the thumbnail directory, or a particular file if $suffix is specified.
recordUpload2($oldver, $comment, $pageText, $props=false, $timestamp=false, $user=null, $tags=[])
Record a file upload in the upload log and the image table.
addCurrent()
Add the current image to the batch.
getSize()
Returns the size of the image file, in bytes.
Handles purging appropriate CDN URLs given a title (or titles)
verifyDBUpdates()
Verify the database updates and return a new FileRepoStatus indicating how many rows would be updated...
Helper class for file undeletion.
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero. ...
string $major_mime
Major MIME type.
string $sha1
SHA-1 base 36 content hash.
isMissing()
splitMime inherited
getArchiveThumbUrl($archiveName, $suffix=false)
Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified.
static isVirtualUrl($url)
Determine if a string is an mwrepo:// URL.
isGood()
Returns whether the operation completed and didn't have any error or warnings.
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
getName()
Return the name of this file.
string $name
The name of a file from its title object.
static newFromKey($sha1, $repo, $timestamp=false)
Create a LocalFile from a SHA-1 key Do not call this except from inside a repo class.
getRepo()
Returns the repository.
unprefixRow($row, $prefix= 'img_')
array $cleanupBatch
List of file IDs to restore.
int $user
User ID of uploader.
setProps($info)
Set properties in this object to be equal to those given in the associative array $info...
when a variable name is used in a it is silently declared as a new local masking the global
static makeParamBlob($params)
Create a blob from a parameter array.
int $bits
Returned by getimagesize (loadFromXxx)
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target...
publish($src, $flags=0, array $options=[])
Move or copy a file to its public location.
const ATOMIC_SECTION_LOCK
bool $fileExists
Does the file exist on disk? (loadFromXxx)
wfLocalFile($title)
Get an object referring to a locally registered file.
doDBUpdates()
Do the database updates and return a new FileRepoStatus indicating how many rows where updated...
getHeight($page=1)
Return the height of the image.
getTitle()
Return the associated title object.
getHashPath()
Get the filename hash component of the directory including trailing slash, e.g.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
purgeEverything()
Purge metadata and all affected pages when the file is created, deleted, or majorly updated...
__destruct()
Clean up any dangling locks.
static queueRecursiveJobsForTable(Title $title, $table)
Queue a RefreshLinks job for any table.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
getBackend()
Get the file backend instance.
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 index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile.
Deferrable Update for closure/callback updates that should use auto-commit mode.
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
nextHistoryLine()
Returns the history of this file, line by line.
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
__construct(File $file, Title $target)
getPath()
Return the storage path to the 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...
removeNonexistentFiles($triplets)
Removes non-existent files from move batch.
int $historyRes
Result of the query for the file's history (nextHistoryLine)
bool $locked
True if the image row is locked.
getFileSha1($virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
deleteOld($archiveName, $reason, $suppress=false, $user=null)
Delete an old version of the file.
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
__construct(File $file, $unsuppress=false)
wfReadOnly()
Check whether the wiki is in read-only mode.
string $metadata
Handler-specific metadata.
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
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
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
publishTo($src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
File backend exception for checked exceptions (e.g.
An error page which can definitely be safely rendered using the OutputPage.
isDeleted($field)
Is this file a "deleted" file in a private archive? STUB.
isVectorized()
Return true if the file is vectorized.
Class to invalidate the HTML cache of all the pages linking to a given title.
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
getHandler()
Get a MediaHandler instance for this file.
getCacheKey()
Get the memcached key for the main data for this file, or false if there is no access to the shared c...
static factory(array $deltas)
static selectFields()
Fields in the filearchive table.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
getRel()
Get the path of the file relative to the public zone root.
static singleton()
Get a RepoGroup instance.
static isStoragePath($path)
Check if a given path is a "mwstore://" path.
bool $unsuppress
Whether to remove all settings for suppressed fields.
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
static newNullRevision($dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page's history.
static selectFields()
Fields in the image table.
string $user_text
User name of uploader.
__construct($title, $repo)
Constructor.
const CACHE_FIELD_MAX_LEN
__construct(Status $status)
purgeThumbList($dir, $files)
Delete a list of thumbnails visible at urls.
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.
upload($src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, $user=null, $tags=[])
getHashPath inherited
loadExtraFromDB()
Load lazy file metadata from the DB.
static newFromRow($row, $repo)
Create a LocalFile from a title Do not call this except from inside a repo class. ...
maybeUpgradeRow()
Upgrade a row if it needs it.
static getInitialPageText($comment= '', $license= '', $copyStatus= '', $source= '', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
quickImport($src, $dst, $options=null)
Import a file from the local file system into the repo.
Helper class for file movement.
bool $upgraded
Whether the row was upgraded on load.
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
selectField($table, $var, $cond= '', $fname=__METHOD__, $options=[])
A SELECT wrapper which returns a single field from a single result row.
static selectFields()
Fields in the oldimage table.
static newFromTitle($title, $repo, $unused=null)
Create a LocalFile from a title Do not call this except from inside a repo class. ...
loadFieldsWithTimestamp($dbr, $fname)
execute()
Run the transaction.
getVirtualUrl($suffix=false)
Get the public zone virtual URL for a current version source file.
bool $all
Add all revisions of 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...
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
static newGood($value=null)
Factory function for good results.
getThumbnails($archiveName=false)
getTransformScript inherited
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
array $ids
List of file IDs to restore.
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
getMetadata()
Get handler-specific metadata.
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
static getSha1Base36FromPath($path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding, zero padded to 31 digits.
string $mime
MIME type, determined by MimeMagic::guessMimeType.
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
Special handling for file pages.
execute()
Perform the move.
Helper class for file deletion.
array $deletionBatch
Items to be processed in the deletion batch.
purgeOldThumbnails($archiveName)
Delete cached transformed files for an archived version only.
getWidth($page=1)
Return the width of the image.
static singleton($wiki=false)
removeNonexistentFiles($triplets)
Removes non-existent files from a store batch.
getMessage($shortContext=false, $longContext=false, $lang=null)
Get a bullet list of the errors as a Message object.
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
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
removeNonexistentFromCleanup($batch)
Removes non-existent files from a cleanup batch.
Class for creating log entries manually, to inject them into the database.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file...
Class representing a non-directory file on the file system.
static getHashFromKey($key)
Gets the SHA1 hash from a storage key.
getCacheFields($prefix= 'img_')
cleanupFailedBatch($storeStatus, $storeBatch)
Cleanup a failed batch.
Job for asynchronous rendering of thumbnails.
bool $upgrading
Whether the row was scheduled to upgrade on load.
lock()
Start an atomic DB section and lock the image for update or increments a reference counter if the loc...
getDescriptionText($lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files...
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
string $url
The URL corresponding to one of the four basic zones.
int $deleted
Bitfield akin to rev_deleted.
move($target)
getLinksTo inherited
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
getUrl()
Return the URL of the file.
bool $missing
True if file is not present in file system.
getDescriptionUrl()
isMultipage inherited
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
getDescription($audience=self::FOR_PUBLIC, User $user=null)
Class to represent a local file in the wiki's own database.
MimeMagic helper wrapper.
addOlds()
Add the old versions of the image to the batch.
getThumbUrl($suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
getMoveTriplets()
Generate triplets for FileRepo::storeBatch().
string $timestamp
Upload timestamp.
getLazyCacheFields($prefix= 'img_')
loadFromDB($flags=0)
Load file metadata from the DB.
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 addCallableUpdate($callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
loadFromFile()
Load metadata from the file itself.
string $description
Description of current revision of the file.
load($flags=0)
Load file metadata from cache or DB, unless already loaded.
purgeCache($options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN...
Implements some public methods and some protected utility functions which are required by multiple ch...
bool $suppress
Whether to suppress all suppressable fields when deleting.
getArchiveUrl($suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
getMediaType()
Returns the type of the media in the file.
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
purgeThumbnails($options=[])
Delete cached transformed files for the current version only.
getMimeType()
Returns the MIME type of the file.
resetHistory()
Reset the history pointer to the first element of the history.
int $size
Size in bytes (loadFromXxx)
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
addOlds()
Add the old versions of the image to the batch.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
purgeDescription()
Purge the file description page, but don't go after pages using the file.
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
addIds($ids)
Add a whole lot of files by ID.
update($table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
execute()
Run the transaction, except the cleanup batch.
Allows to change the fields on the form that will be generated $name
addId($fa_id)
Add a file by ID.