24use \MediaWiki\Logger\LoggerFactory;
162 $file->loadFromRow( $row );
179 $conds = [
'img_sha1' =>
$sha1 ];
184 $row =
$dbr->selectRow(
'image', self::selectFields(), $conds, __METHOD__ );
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;
257 $cache = ObjectCache::getMainWANInstance();
258 $cachedValues =
$cache->getWithSetCallback(
262 $setOpts += Database::getCacheSetOptions( $this->repo->getSlaveDB() );
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;
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 ) {
318 ObjectCache::getMainWANInstance()->delete( $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;
585 DeferredUpdates::addCallableUpdate(
function() {
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();
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 ),
639 'img_sha1' => $this->sha1,
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'];
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 ) {
912 DeferredUpdates::addUpdate(
914 DeferredUpdates::PRESEND
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' ];
1066 Hooks::run(
'LocalFile::getHistory', [ &$localFile, &
$tables, &$fields,
1067 &$conds, &$opts, &$join_conds ] );
1069 $res =
$dbr->select(
$tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1072 foreach (
$res as $row ) {
1073 $r[] = $this->repo->newFileFromRow( $row );
1076 if ( $order ==
'ASC' ) {
1077 $r = array_reverse( $r );
1093 # Polymorphic function name to distinguish foreign and local fetches
1094 $fname = get_class( $this ) .
'::' . __FUNCTION__;
1096 $dbr = $this->repo->getSlaveDB();
1098 if ( $this->historyLine == 0 ) {
1099 $this->historyRes =
$dbr->select(
'image',
1102 "'' AS oi_archive_name",
1106 [
'img_name' => $this->
title->getDBkey() ],
1110 if ( 0 ==
$dbr->numRows( $this->historyRes ) ) {
1111 $this->historyRes =
null;
1115 } elseif ( $this->historyLine == 1 ) {
1116 $this->historyRes =
$dbr->select(
'oldimage',
'*',
1117 [
'oi_name' => $this->
title->getDBkey() ],
1119 [
'ORDER BY' =>
'oi_timestamp DESC' ]
1122 $this->historyLine++;
1124 return $dbr->fetchObject( $this->historyRes );
1131 $this->historyLine = 0;
1133 if ( !is_null( $this->historyRes ) ) {
1134 $this->historyRes =
null;
1173 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1177 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1179 if ( $this->repo->isVirtualUrl( $srcPath )
1182 $props = $this->repo->getFileProps( $srcPath );
1185 $props = $mwProps->getPropsFromPath( $srcPath,
true );
1206 if (
$status->successCount >= 2 ) {
1215 $status->fatal(
'filenotfound', $srcPath );
1270 if ( is_null(
$user ) ) {
1275 $dbw = $this->repo->getMasterDB();
1277 # Imports or such might force a certain timestamp; otherwise we generate
1278 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1281 $allowTimeKludge =
true;
1283 $allowTimeKludge =
false;
1286 $props = $props ?: $this->repo->getFileProps( $this->
getVirtualUrl() );
1288 $props[
'user'] =
$user->getId();
1289 $props[
'user_text'] =
$user->getName();
1293 # Fail now if the file isn't there
1294 if ( !$this->fileExists ) {
1295 wfDebug( __METHOD__ .
": File " . $this->
getRel() .
" went missing!\n" );
1300 $dbw->startAtomic( __METHOD__ );
1302 # Test to see if the row exists using INSERT IGNORE
1303 # This avoids race conditions by locking the row until the commit, and also
1304 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1305 $dbw->insert(
'image',
1307 'img_name' => $this->
getName(),
1308 'img_size' => $this->size,
1309 'img_width' => intval( $this->
width ),
1310 'img_height' => intval( $this->height ),
1311 'img_bits' => $this->bits,
1312 'img_media_type' => $this->media_type,
1313 'img_major_mime' => $this->major_mime,
1314 'img_minor_mime' => $this->minor_mime,
1317 'img_user' =>
$user->getId(),
1318 'img_user_text' =>
$user->getName(),
1319 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1320 'img_sha1' => $this->sha1
1326 $reupload = ( $dbw->affectedRows() == 0 );
1328 if ( $allowTimeKludge ) {
1329 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1330 $ltimestamp = $dbw->selectField(
1333 [
'img_name' => $this->
getName() ],
1335 [
'LOCK IN SHARE MODE' ]
1338 # Avoid a timestamp that is not newer than the last version
1339 # TODO: the image/oldimage tables should be like page/revision with an ID field
1342 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1347 # (bug 34993) Note: $oldver can be empty here, if the previous
1348 # version of the file was broken. Allow registration of the new
1349 # version to continue anyway, because that's better than having
1350 # an image that's not fixable by user operations.
1351 # Collision, this is an update of a file
1352 # Insert previous contents into oldimage
1353 $dbw->insertSelect(
'oldimage',
'image',
1355 'oi_name' =>
'img_name',
1356 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1357 'oi_size' =>
'img_size',
1358 'oi_width' =>
'img_width',
1359 'oi_height' =>
'img_height',
1360 'oi_bits' =>
'img_bits',
1361 'oi_timestamp' =>
'img_timestamp',
1362 'oi_description' =>
'img_description',
1363 'oi_user' =>
'img_user',
1364 'oi_user_text' =>
'img_user_text',
1365 'oi_metadata' =>
'img_metadata',
1366 'oi_media_type' =>
'img_media_type',
1367 'oi_major_mime' =>
'img_major_mime',
1368 'oi_minor_mime' =>
'img_minor_mime',
1369 'oi_sha1' =>
'img_sha1'
1371 [
'img_name' => $this->getName() ],
1375 # Update the current image row
1376 $dbw->update(
'image',
1378 'img_size' => $this->size,
1379 'img_width' => intval( $this->
width ),
1380 'img_height' => intval( $this->height ),
1381 'img_bits' => $this->bits,
1382 'img_media_type' => $this->media_type,
1383 'img_major_mime' => $this->major_mime,
1384 'img_minor_mime' => $this->minor_mime,
1387 'img_user' =>
$user->getId(),
1388 'img_user_text' =>
$user->getName(),
1389 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1390 'img_sha1' => $this->sha1
1392 [
'img_name' => $this->getName() ],
1398 $descId = $descTitle->getArticleID();
1400 $wikiPage->setFile( $this );
1403 $logEntry =
new ManualLogEntry(
'upload', $reupload ?
'overwrite' :
'upload' );
1405 $logEntry->setPerformer(
$user );
1407 $logEntry->setTarget( $descTitle );
1410 $logEntry->setParameters(
1412 'img_sha1' => $this->sha1,
1422 $logId = $logEntry->insert();
1424 if ( $descTitle->exists() ) {
1428 $editSummary = $formatter->getPlainActionText();
1437 if ( $nullRevision ) {
1438 $nullRevision->insertOn( $dbw );
1440 'NewRevisionFromEditComplete',
1441 [ $wikiPage, $nullRevision, $nullRevision->getParentId(),
$user ]
1443 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1445 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1448 $newPageContent =
null;
1454 # Defer purges, page creation, and link updates in case they error out.
1455 # The most important thing is that files and the DB registry stay synced.
1456 $dbw->endAtomic( __METHOD__ );
1458 # Do some cache purges after final commit so that:
1459 # a) Changes are more likely to be seen post-purge
1460 # b) They won't cause rollback of the log publish/update above
1461 DeferredUpdates::addUpdate(
1467 $logEntry, $logId, $descId, $tags
1469 # Update memcache after the commit
1472 $updateLogPage =
false;
1473 if ( $newPageContent ) {
1474 # New file page; create the description page.
1475 # There's already a log entry, so don't make a second RC entry
1476 # CDN and file cache for the description page are purged by doEditContent.
1477 $status = $wikiPage->doEditContent(
1485 if ( isset(
$status->value[
'revision'] ) ) {
1489 $logEntry->setAssociatedRevId(
$rev->getId() );
1493 if ( isset(
$status->value[
'revision'] ) ) {
1496 $updateLogPage =
$rev->getPage();
1499 # Existing file page: invalidate description page cache
1500 $wikiPage->getTitle()->invalidateCache();
1501 $wikiPage->getTitle()->purgeSquid();
1502 # Allow the new file version to be patrolled from the page footer
1506 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1507 # but setAssociatedRevId() wasn't called at that point yet...
1508 $logParams = $logEntry->getParameters();
1509 $logParams[
'associated_rev_id'] = $logEntry->getAssociatedRevId();
1511 if ( $updateLogPage ) {
1512 # Also log page, in case where we just created it above
1513 $update[
'log_page'] = $updateLogPage;
1515 $this->
getRepo()->getMasterDB()->update(
1518 [
'log_id' => $logId ],
1521 $this->
getRepo()->getMasterDB()->insert(
1524 'ls_field' =>
'associated_rev_id',
1525 'ls_value' => $logEntry->getAssociatedRevId(),
1526 'ls_log_id' => $logId,
1531 # Add change tags, if any
1533 $logEntry->setTags( $tags );
1536 # Uploads can be patrolled
1537 $logEntry->setIsPatrollable(
true );
1539 # Now that the log entry is up-to-date, make an RC entry.
1540 $logEntry->publish( $logId );
1542 # Run hook for other updates (typically more cache purging)
1543 Hooks::run(
'FileUpload', [ $this, $reupload, !$newPageContent ] );
1546 # Delete old thumbnails
1548 # Remove the old file from the CDN cache
1549 DeferredUpdates::addUpdate(
1551 DeferredUpdates::PRESEND
1554 # Update backlink pages pointing to this title if created
1561 DeferredUpdates::PRESEND
1565 # This is a new file, so update the image count
1569 # Invalidate cache for all pages using this file
1610 $srcPath = ( $src instanceof
FSFile ) ? $src->getPath() : $src;
1620 $archiveRel =
'archive/' . $this->
getHashPath() . $archiveName;
1628 $dst = $wrapperBackend->getPathForSHA1(
$sha1 );
1635 $status->value = $archiveName;
1641 if (
$status->value ==
'new' ) {
1644 $status->value = $archiveName;
1671 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1675 wfDebugLog(
'imagemove',
"Got request to move {$this->name} to " . $target->getText() );
1680 $archiveNames =
$batch->addOlds();
1684 wfDebugLog(
'imagemove',
"Finished moving {$this->name}" );
1690 DeferredUpdates::addUpdate(
1692 $this->
getRepo()->getMasterDB(),
1694 function ()
use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1695 $oldTitleFile->purgeEverything();
1696 foreach ( $archiveNames
as $archiveName ) {
1697 $oldTitleFile->purgeOldThumbnails( $archiveName );
1699 $newTitleFile->purgeEverything();
1702 DeferredUpdates::PRESEND
1707 $this->
title = $target;
1709 unset( $this->
name );
1710 unset( $this->hashPath );
1729 function delete( $reason, $suppress =
false,
$user = null ) {
1730 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1739 $archiveNames =
$batch->addOlds();
1748 DeferredUpdates::addUpdate(
1750 $this->
getRepo()->getMasterDB(),
1752 function ()
use ( $archiveNames ) {
1754 foreach ( $archiveNames
as $archiveName ) {
1759 DeferredUpdates::PRESEND
1764 foreach ( $archiveNames
as $archiveName ) {
1767 DeferredUpdates::addUpdate(
new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
1788 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1795 $batch->addOld( $archiveName );
1804 DeferredUpdates::addUpdate(
1806 DeferredUpdates::PRESEND
1823 function restore( $versions = [], $unsuppress =
false ) {
1824 if ( $this->
getRepo()->getReadOnlyReason() !==
false ) {
1834 $batch->addIds( $versions );
1838 $cleanupStatus =
$batch->cleanup();
1839 $cleanupStatus->successCount = 0;
1840 $cleanupStatus->failCount = 0;
1841 $status->merge( $cleanupStatus );
1858 return $this->
title->getLocalURL();
1874 $content = $revision->getContent();
1880 return $pout->getText();
1890 if ( $audience == self::FOR_PUBLIC && $this->
isDeleted( self::DELETED_COMMENT ) ) {
1892 } elseif ( $audience == self::FOR_THIS_USER
1917 if ( $this->descriptionTouched ===
null ) {
1919 'page_namespace' => $this->
title->getNamespace(),
1920 'page_title' => $this->
title->getDBkey()
1922 $touched = $this->repo->getSlaveDB()->selectField(
'page',
'page_touched', $cond, __METHOD__ );
1923 $this->descriptionTouched = $touched ?
wfTimestamp(
TS_MW, $touched ) :
false;
1935 if ( $this->sha1 ==
'' && $this->fileExists ) {
1938 $this->sha1 = $this->repo->getFileSha1( $this->
getPath() );
1939 if ( !
wfReadOnly() && strval( $this->sha1 ) !=
'' ) {
1940 $dbw = $this->repo->getMasterDB();
1941 $dbw->update(
'image',
1942 [
'img_sha1' => $this->sha1 ],
1943 [
'img_name' => $this->
getName() ],
1961 return $this->extraDataLoaded
1970 return $this->
getRepo()->getBackend()->lockFiles(
1980 return $this->
getRepo()->getBackend()->unlockFiles(
1995 if ( !$this->locked ) {
1996 $logger = LoggerFactory::getInstance(
'LocalFile' );
1998 $dbw = $this->repo->getMasterDB();
1999 $makesTransaction = !$dbw->trxLevel();
2000 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2006 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2007 $logger->warning(
"Failed to lock '{file}'", [
'file' => $this->
name ] );
2013 $dbw->onTransactionResolution(
2014 function ()
use ( $logger ) {
2017 $logger->error(
"Failed to unlock '{file}'", [
'file' => $this->
name ] );
2023 $this->lockedOwnTrx = $makesTransaction;
2040 if ( $this->locked ) {
2042 if ( !$this->locked ) {
2043 $dbw = $this->repo->getMasterDB();
2044 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2045 $this->lockedOwnTrx =
false;
2054 return $this->
getRepo()->newFatal(
'filereadonlyerror', $this->
getName(),
2066# ------------------------------------------------------------------------------
2113 $this->status =
$file->repo->newGood();
2117 $this->srcRels[
'.'] = $this->
file->getRel();
2124 $this->srcRels[$oldName] = $this->
file->getArchiveRel( $oldName );
2125 $this->archiveUrls[] = $this->
file->getArchiveUrl( $oldName );
2135 $dbw = $this->
file->repo->getMasterDB();
2136 $result = $dbw->select(
'oldimage',
2137 [
'oi_archive_name' ],
2138 [
'oi_name' => $this->
file->getName() ],
2143 $this->
addOld( $row->oi_archive_name );
2144 $archiveNames[] = $row->oi_archive_name;
2147 return $archiveNames;
2154 if ( !isset( $this->srcRels[
'.'] ) ) {
2156 $deleteCurrent =
false;
2159 unset( $oldRels[
'.'] );
2160 $deleteCurrent =
true;
2163 return [ $oldRels, $deleteCurrent ];
2173 if ( $deleteCurrent ) {
2177 if ( count( $oldRels ) ) {
2178 $dbw = $this->
file->repo->getMasterDB();
2179 $res = $dbw->select(
2181 [
'oi_archive_name',
'oi_sha1' ],
2182 [
'oi_archive_name' => array_keys( $oldRels ),
2183 'oi_name' => $this->
file->getName() ],
2187 foreach (
$res as $row ) {
2188 if ( rtrim( $row->oi_sha1,
"\0" ) ===
'' ) {
2190 $oldUrl = $this->
file->getArchiveVirtualUrl( $row->oi_archive_name );
2191 $props = $this->
file->repo->getFileProps( $oldUrl );
2193 if ( $props[
'fileExists'] ) {
2195 $dbw->update(
'oldimage',
2196 [
'oi_sha1' => $props[
'sha1'] ],
2197 [
'oi_name' => $this->
file->getName(),
'oi_archive_name' => $row->oi_archive_name ],
2199 $hashes[$row->oi_archive_name] = $props[
'sha1'];
2201 $hashes[$row->oi_archive_name] =
false;
2204 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2209 $missing = array_diff_key( $this->srcRels,
$hashes );
2211 foreach ( $missing
as $name => $rel ) {
2212 $this->status->error(
'filedelete-old-unregistered',
$name );
2217 $this->status->error(
'filedelete-missing', $this->srcRels[
$name] );
2227 $dbw = $this->
file->repo->getMasterDB();
2228 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2229 $encUserId = $dbw->addQuotes( $this->
user->getId() );
2230 $encReason = $dbw->addQuotes( $this->reason );
2231 $encGroup = $dbw->addQuotes(
'deleted' );
2232 $ext = $this->
file->getExtension();
2233 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2234 $encExt = $dbw->addQuotes( $dotExt );
2238 if ( $this->suppress ) {
2246 $bitfield =
'oi_deleted';
2249 if ( $deleteCurrent ) {
2254 'fa_storage_group' => $encGroup,
2255 'fa_storage_key' => $dbw->conditional(
2256 [
'img_sha1' =>
'' ],
2257 $dbw->addQuotes(
'' ),
2258 $dbw->buildConcat( [
"img_sha1", $encExt ] )
2260 'fa_deleted_user' => $encUserId,
2261 'fa_deleted_timestamp' => $encTimestamp,
2262 'fa_deleted_reason' => $encReason,
2263 'fa_deleted' => $this->suppress ? $bitfield : 0,
2265 'fa_name' =>
'img_name',
2266 'fa_archive_name' =>
'NULL',
2267 'fa_size' =>
'img_size',
2268 'fa_width' =>
'img_width',
2269 'fa_height' =>
'img_height',
2270 'fa_metadata' =>
'img_metadata',
2271 'fa_bits' =>
'img_bits',
2272 'fa_media_type' =>
'img_media_type',
2273 'fa_major_mime' =>
'img_major_mime',
2274 'fa_minor_mime' =>
'img_minor_mime',
2275 'fa_description' =>
'img_description',
2276 'fa_user' =>
'img_user',
2277 'fa_user_text' =>
'img_user_text',
2278 'fa_timestamp' =>
'img_timestamp',
2279 'fa_sha1' =>
'img_sha1'
2281 [
'img_name' => $this->
file->getName() ],
2286 if ( count( $oldRels ) ) {
2287 $res = $dbw->select(
2291 'oi_name' => $this->
file->getName(),
2292 'oi_archive_name' => array_keys( $oldRels )
2298 foreach (
$res as $row ) {
2301 'fa_storage_group' =>
'deleted',
2302 'fa_storage_key' => ( $row->oi_sha1 ===
'' )
2304 :
"{$row->oi_sha1}{$dotExt}",
2305 'fa_deleted_user' => $this->
user->getId(),
2306 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2309 'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2310 'fa_name' => $row->oi_name,
2311 'fa_archive_name' => $row->oi_archive_name,
2312 'fa_size' => $row->oi_size,
2313 'fa_width' => $row->oi_width,
2314 'fa_height' => $row->oi_height,
2315 'fa_metadata' => $row->oi_metadata,
2316 'fa_bits' => $row->oi_bits,
2317 'fa_media_type' => $row->oi_media_type,
2318 'fa_major_mime' => $row->oi_major_mime,
2319 'fa_minor_mime' => $row->oi_minor_mime,
2320 'fa_description' => $row->oi_description,
2321 'fa_user' => $row->oi_user,
2322 'fa_user_text' => $row->oi_user_text,
2323 'fa_timestamp' => $row->oi_timestamp,
2324 'fa_sha1' => $row->oi_sha1
2328 $dbw->insert(
'filearchive', $rowsInsert, __METHOD__ );
2333 $dbw = $this->
file->repo->getMasterDB();
2336 if ( count( $oldRels ) ) {
2337 $dbw->delete(
'oldimage',
2339 'oi_name' => $this->
file->getName(),
2340 'oi_archive_name' => array_keys( $oldRels )
2344 if ( $deleteCurrent ) {
2345 $dbw->delete(
'image', [
'img_name' => $this->
file->getName() ], __METHOD__ );
2354 $repo = $this->
file->getRepo();
2355 $this->
file->lock();
2359 $this->deletionBatch = [];
2360 $ext = $this->
file->getExtension();
2361 $dotExt =
$ext ===
'' ?
'' :
".$ext";
2363 foreach ( $this->srcRels
as $name => $srcRel ) {
2367 $key = $hash . $dotExt;
2368 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2369 $this->deletionBatch[
$name] = [ $srcRel, $dstRel ];
2373 if ( !$repo->hasSha1Storage() ) {
2377 if ( !$checkStatus->isGood() ) {
2378 $this->status->merge( $checkStatus );
2381 $this->deletionBatch = $checkStatus->value;
2384 $status = $this->
file->repo->deleteBatch( $this->deletionBatch );
2386 $this->status->merge(
$status );
2390 if ( !$this->status->isOK() ) {
2392 $this->
file->unlock();
2403 $this->
file->unlock();
2417 list( $src, ) = $batchItem;
2418 $files[$src] = $this->
file->repo->getVirtualUrl(
'public' ) .
'/' . rawurlencode( $src );
2422 if ( in_array(
null,
$result,
true ) ) {
2423 return Status::newFatal(
'backend-fail-internal',
2424 $this->
file->repo->getBackend()->getName() );
2428 if (
$result[$batchItem[0]] ) {
2429 $newBatch[] = $batchItem;
2433 return Status::newGood( $newBatch );
2437# ------------------------------------------------------------------------------
2465 $this->cleanupBatch = $this->ids = [];
2475 $this->ids[] = $fa_id;
2483 $this->ids = array_merge( $this->ids,
$ids );
2505 $repo = $this->
file->getRepo();
2506 if ( !$this->all && !$this->ids ) {
2508 return $repo->newGood();
2511 $lockOwnsTrx = $this->
file->lock();
2513 $dbw = $this->
file->repo->getMasterDB();
2516 $exists = (bool)$dbw->selectField(
'image',
'1',
2517 [
'img_name' => $this->file->getName() ],
2522 $lockOwnsTrx ? [] : [
'LOCK IN SHARE MODE' ]
2527 $conditions = [
'fa_name' => $this->
file->getName() ];
2529 if ( !$this->all ) {
2538 [
'ORDER BY' =>
'fa_timestamp DESC' ]
2544 $insertCurrent =
false;
2550 $idsPresent[] = $row->fa_id;
2552 if ( $row->fa_name != $this->file->getName() ) {
2553 $status->error(
'undelete-filename-mismatch',
$wgLang->timeanddate( $row->fa_timestamp ) );
2558 if ( $row->fa_storage_key ==
'' ) {
2560 $status->error(
'undelete-bad-store-key',
$wgLang->timeanddate( $row->fa_timestamp ) );
2565 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2566 $row->fa_storage_key;
2567 $deletedUrl = $repo->getVirtualUrl() .
'/deleted/' . $deletedRel;
2569 if ( isset( $row->fa_sha1 ) ) {
2570 $sha1 = $row->fa_sha1;
2577 if ( strlen( $sha1 ) == 32 && $sha1[0] ==
'0' ) {
2578 $sha1 = substr( $sha1, 1 );
2581 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime ==
'unknown'
2582 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime ==
'unknown'
2583 || is_null( $row->fa_media_type ) || $row->fa_media_type ==
'UNKNOWN'
2584 || is_null( $row->fa_metadata )
2591 'minor_mime' => $row->fa_minor_mime,
2592 'major_mime' => $row->fa_major_mime,
2593 'media_type' => $row->fa_media_type,
2594 'metadata' => $row->fa_metadata
2598 if ( $first && !$exists ) {
2600 $destRel = $this->
file->getRel();
2602 'img_name' => $row->fa_name,
2603 'img_size' => $row->fa_size,
2604 'img_width' => $row->fa_width,
2605 'img_height' => $row->fa_height,
2606 'img_metadata' => $props[
'metadata'],
2607 'img_bits' => $row->fa_bits,
2608 'img_media_type' => $props[
'media_type'],
2609 'img_major_mime' => $props[
'major_mime'],
2610 'img_minor_mime' => $props[
'minor_mime'],
2611 'img_description' => $row->fa_description,
2612 'img_user' => $row->fa_user,
2613 'img_user_text' => $row->fa_user_text,
2614 'img_timestamp' => $row->fa_timestamp,
2619 if ( !$this->unsuppress && $row->fa_deleted ) {
2620 $status->fatal(
'undeleterevdel' );
2621 $this->
file->unlock();
2625 $archiveName = $row->fa_archive_name;
2627 if ( $archiveName ==
'' ) {
2636 }
while ( isset( $archiveNames[$archiveName] ) );
2639 $archiveNames[$archiveName] =
true;
2640 $destRel = $this->
file->getArchiveRel( $archiveName );
2642 'oi_name' => $row->fa_name,
2643 'oi_archive_name' => $archiveName,
2644 'oi_size' => $row->fa_size,
2645 'oi_width' => $row->fa_width,
2646 'oi_height' => $row->fa_height,
2647 'oi_bits' => $row->fa_bits,
2648 'oi_description' => $row->fa_description,
2649 'oi_user' => $row->fa_user,
2650 'oi_user_text' => $row->fa_user_text,
2651 'oi_timestamp' => $row->fa_timestamp,
2652 'oi_metadata' => $props[
'metadata'],
2653 'oi_media_type' => $props[
'media_type'],
2654 'oi_major_mime' => $props[
'major_mime'],
2655 'oi_minor_mime' => $props[
'minor_mime'],
2656 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2657 'oi_sha1' => $sha1 ];
2660 $deleteIds[] = $row->fa_id;
2666 $storeBatch[] = [ $deletedUrl,
'public', $destRel ];
2667 $this->cleanupBatch[] = $row->fa_storage_key;
2676 $missingIds = array_diff( $this->ids, $idsPresent );
2678 foreach ( $missingIds
as $id ) {
2679 $status->error(
'undelete-missing-filearchive', $id );
2682 if ( !$repo->hasSha1Storage() ) {
2685 if ( !$checkStatus->isGood() ) {
2686 $status->merge( $checkStatus );
2689 $storeBatch = $checkStatus->value;
2694 $status->merge( $storeStatus );
2701 $this->
file->unlock();
2713 if ( $insertCurrent ) {
2714 $dbw->insert(
'image', $insertCurrent, __METHOD__ );
2717 if ( $insertBatch ) {
2718 $dbw->insert(
'oldimage', $insertBatch, __METHOD__ );
2722 $dbw->delete(
'filearchive',
2723 [
'fa_id' => $deleteIds ],
2728 if (
$status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
2730 wfDebug( __METHOD__ .
" restored {$status->successCount} items, creating a new current\n" );
2734 $this->
file->purgeEverything();
2736 wfDebug( __METHOD__ .
" restored {$status->successCount} as archived versions\n" );
2737 $this->
file->purgeDescription();
2741 $this->
file->unlock();
2752 $files = $filteredTriplets = [];
2753 foreach ( $triplets
as $file ) {
2758 if ( in_array(
null,
$result,
true ) ) {
2759 return Status::newFatal(
'backend-fail-internal',
2760 $this->
file->repo->getBackend()->getName() );
2763 foreach ( $triplets
as $file ) {
2765 $filteredTriplets[] =
$file;
2769 return Status::newGood( $filteredTriplets );
2779 $repo = $this->
file->repo;
2782 $files[
$file] = $repo->getVirtualUrl(
'deleted' ) .
'/' .
2783 rawurlencode( $repo->getDeletedHashPath(
$file ) .
$file );
2790 $newBatch[] =
$file;
2803 if ( !$this->cleanupBatch ) {
2804 return $this->
file->repo->newGood();
2809 $status = $this->
file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2824 foreach ( $storeStatus->success
as $i =>
$success ) {
2829 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2836# ------------------------------------------------------------------------------
2867 $this->oldHash = $this->
file->repo->getHashPath( $this->
file->getName() );
2868 $this->newHash = $this->
file->repo->getHashPath( $this->target->getDBkey() );
2869 $this->oldName = $this->
file->getName();
2870 $this->newName = $this->
file->repo->getNameFromTitle( $this->target );
2871 $this->oldRel = $this->oldHash . $this->oldName;
2872 $this->newRel = $this->newHash . $this->newName;
2880 $this->cur = [ $this->oldRel, $this->newRel ];
2888 $archiveBase =
'archive';
2890 $this->oldCount = 0;
2893 $result = $this->db->select(
'oldimage',
2894 [
'oi_archive_name',
'oi_deleted' ],
2895 [
'oi_name' => $this->oldName ],
2897 [
'LOCK IN SHARE MODE' ]
2901 $archiveNames[] = $row->oi_archive_name;
2902 $oldName = $row->oi_archive_name;
2903 $bits = explode(
'!', $oldName, 2 );
2905 if ( count( $bits ) != 2 ) {
2906 wfDebug(
"Old file name missing !: '$oldName' \n" );
2912 if ( $this->oldName != $filename ) {
2913 wfDebug(
"Old file name doesn't match: '$oldName' \n" );
2925 "{$archiveBase}/{$this->oldHash}{$oldName}",
2926 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2930 return $archiveNames;
2938 $repo = $this->
file->repo;
2942 $this->
file->lock();
2947 if ( !$checkStatus->isGood() ) {
2948 $destFile->unlock();
2949 $this->
file->unlock();
2950 $status->merge( $checkStatus );
2953 $triplets = $checkStatus->value;
2957 if ( !$statusDb->isGood() ) {
2958 $destFile->unlock();
2959 $this->
file->unlock();
2960 $statusDb->setOK(
false );
2965 if ( !$repo->hasSha1Storage() ) {
2970 wfDebugLog(
'imagemove',
"Moved files for {$this->file->getName()}: " .
2971 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2972 if ( !$statusMove->isGood() ) {
2975 $destFile->unlock();
2976 $this->
file->unlock();
2977 wfDebugLog(
'imagemove',
"Error in moving files: "
2978 . $statusMove->getWikiText(
false,
false,
'en' ) );
2979 $statusMove->setOK(
false );
2983 $status->merge( $statusMove );
2989 wfDebugLog(
'imagemove',
"Renamed {$this->file->getName()} in database: " .
2990 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2992 $destFile->unlock();
2993 $this->
file->unlock();
3010 $repo = $this->
file->repo;
3017 [
'img_name' => $this->oldName ],
3021 $oldRowCount = $dbw->selectField(
3024 [
'oi_name' => $this->oldName ],
3029 if ( $hasCurrent ) {
3034 $status->successCount += $oldRowCount;
3038 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3040 $status->error(
'imageinvalidfilename' );
3056 [
'img_name' => $this->newName ],
3057 [
'img_name' => $this->oldName ],
3064 'oi_name' => $this->newName,
3065 'oi_archive_name = ' . $dbw->strreplace(
'oi_archive_name',
3066 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3068 [
'oi_name' => $this->oldName ],
3078 $moves = array_merge( [ $this->cur ], $this->olds );
3081 foreach ( $moves
as $move ) {
3083 $srcUrl = $this->
file->repo->getVirtualUrl() .
'/public/' . rawurlencode( $move[0] );
3084 $triplets[] = [ $srcUrl,
'public', $move[1] ];
3087 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3102 foreach ( $triplets
as $file ) {
3107 if ( in_array(
null,
$result,
true ) ) {
3108 return Status::newFatal(
'backend-fail-internal',
3109 $this->
file->repo->getBackend()->getName() );
3112 $filteredTriplets = [];
3113 foreach ( $triplets
as $file ) {
3115 $filteredTriplets[] =
$file;
3117 wfDebugLog(
'imagemove',
"File {$file[0]} does not exist" );
3121 return Status::newGood( $filteredTriplets );
3132 foreach ( $triplets
as $triplet ) {
3134 $pairs[] = [ $triplet[1], $triplet[2] ];
3137 $this->
file->repo->cleanupBatch( $pairs );
3148 foreach ( $triplets
as $triplet ) {
3158 parent::__construct(
3166 $wgOut->setStatusCode( 429 );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfLocalFile( $title)
Get an object referring to a locally registered file.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
static selectFields()
Fields in the filearchive table.
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Deferrable Update for closure/callback updates that should use auto-commit mode.
Handles purging appropriate CDN URLs given a title (or titles)
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
An error page which can definitely be safely rendered using the OutputPage.
Class representing a non-directory file on the file system.
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
File backend exception for checked exceptions (e.g.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Generic operation result class for FileRepo-related operations.
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
publish( $src, $dstRel, $archiveRel, $flags=0, array $options=[])
Copy or move a file either from a storage path, virtual URL, or file system path, into this repositor...
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
getBackend()
Get the file backend instance.
Implements some public methods and some protected utility functions which are required by multiple ch...
string $url
The URL corresponding to one of the four basic zones.
isVectorized()
Return true if the file is vectorized.
purgeDescription()
Purge the file description page, but don't go after pages using the file.
getPath()
Return the storage path to the file.
getThumbPath( $suffix=false)
Get the path of the thumbnail directory, or a particular file if $suffix is specified.
getRel()
Get the path of the file relative to the public zone root.
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
getName()
Return the name of this file.
getThumbUrl( $suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
getRepo()
Returns the repository.
assertTitleDefined()
Assert that $this->title is set to a Title.
getArchiveThumbPath( $archiveName, $suffix=false)
Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified.
getTitle()
Return the associated title object.
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile.
string $name
The name of a file from its title object.
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
purgeEverything()
Purge metadata and all affected pages when the file is created, deleted, or majorly updated.
static splitMime( $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
getUrl()
Return the URL of the file.
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
userCan( $field, User $user=null)
Determine if the current user is allowed to view a particular field of this file, if it's marked as d...
getHandler()
Get a MediaHandler instance for this file.
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
getArchiveThumbUrl( $archiveName, $suffix=false)
Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified.
getHashPath()
Get the filename hash component of the directory including trailing slash, e.g.
Class to invalidate the HTML cache of all the pages linking to a given title.
static singleton( $wiki=false)
Internationalisation code.
static queueRecursiveJobsForTable(Title $title, $table)
Queue a RefreshLinks job for any table.
Helper class for file deletion.
addOlds()
Add the old versions of the image to the batch.
removeNonexistentFiles( $batch)
Removes non-existent files from a deletion batch.
array $deletionBatch
Items to be processed in the deletion batch.
__construct(File $file, $reason='', $suppress=false, $user=null)
bool $suppress
Whether to suppress all suppressable fields when deleting.
execute()
Run the transaction.
__construct(Status $status)
report()
Output a report about the exception and takes care of formatting.
Helper class for file movement.
cleanupTarget( $triplets)
Cleanup a partially moved array of triplets by deleting the target files.
addOlds()
Add the old versions of the image to the batch.
doDBUpdates()
Do the database updates and return a new FileRepoStatus 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 FileRepoStatus indicating how many rows would be updated...
removeNonexistentFiles( $triplets)
Removes non-existent files from move batch.
addCurrent()
Add the current image to the batch.
cleanupSource( $triplets)
Cleanup a fully moved array of triplets by deleting the source files.
Helper class for file undeletion.
execute()
Run the transaction, except the cleanup batch.
addIds( $ids)
Add a whole lot of files by ID.
addAll()
Add all revisions of the file.
bool $unsuppress
Whether to remove all settings for suppressed fields.
removeNonexistentFromCleanup( $batch)
Removes non-existent files from a cleanup batch.
array $ids
List of file IDs to restore.
addId( $fa_id)
Add a file by ID.
cleanup()
Delete unused files in the deleted zone.
removeNonexistentFiles( $triplets)
Removes non-existent files from a store batch.
cleanupFailedBatch( $storeStatus, $storeBatch)
Cleanup a failed batch.
bool $all
Add all revisions of the file.
array $cleanupBatch
List of file IDs to restore.
__construct(File $file, $unsuppress=false)
Class to represent a local file in the wiki's own database.
exists()
canRender inherited
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
string $major_mime
Major MIME type.
maybeUpgradeRow()
Upgrade a row if it needs it.
static newFromKey( $sha1, $repo, $timestamp=false)
Create a LocalFile from a SHA-1 key Do not call this except from inside a repo class.
getMediaType()
Returns the type of the media in the file.
recordUpload( $oldver, $desc, $license='', $copyStatus='', $source='', $watch=false, $timestamp=false, User $user=null)
Record a file upload in the upload log and the image table.
move( $target)
getLinksTo inherited
lock()
Start an atomic DB section and lock the image for update or increments a reference counter if the loc...
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
getCacheKey()
Get the memcached key for the main data for this file, or false if there is no access to the shared c...
getWidth( $page=1)
Return the width of the image.
__destruct()
Clean up any dangling locks.
string $mime
MIME type, determined by MimeMagic::guessMimeType.
isMissing()
splitMime inherited
deleteOld( $archiveName, $reason, $suppress=false, $user=null)
Delete an old version of the file.
getDescriptionUrl()
isMultipage inherited
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
static selectFields()
Fields in the image table.
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
loadFromDB( $flags=0)
Load file metadata from the DB.
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
bool $upgrading
Whether the row was scheduled to upgrade on load.
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
loadFromFile()
Load metadata from the file itself.
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
int $size
Size in bytes (loadFromXxx)
string $minor_mime
Minor MIME type.
int $user
User ID of uploader.
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
getThumbnails( $archiveName=false)
getTransformScript inherited
bool $upgraded
Whether the row was upgraded on load.
static newFromTitle( $title, $repo, $unused=null)
Create a LocalFile from a title Do not call this except from inside a repo class.
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
loadFieldsWithTimestamp( $dbr, $fname)
string $timestamp
Upload timestamp.
const ATOMIC_SECTION_LOCK
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
int $historyRes
Result of the query for the file's history (nextHistoryLine)
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
getUser( $type='text')
Returns ID or name of user who uploaded the file.
decodeRow( $row, $prefix='img_')
Decode a row from the database (either object or array) to an array with timestamps and MIME types de...
string $description
Description of current revision of the file.
const CACHE_FIELD_MAX_LEN
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
getLazyCacheFields( $prefix='img_')
getSize()
Returns the size of the image file, in bytes.
invalidateCache()
Purge the file object/metadata cache.
getMimeType()
Returns the MIME type of the file.
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
string $sha1
SHA-1 base 36 content hash.
getHeight( $page=1)
Return the height of the image.
bool $locked
True if the image row is locked.
getDescriptionText( $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files,...
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
resetHistory()
Reset the history pointer to the first element of the history.
unprefixRow( $row, $prefix='img_')
static newFromRow( $row, $repo)
Create a LocalFile from a title Do not call this except from inside a repo class.
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
string $user_text
User name of uploader.
string $metadata
Handler-specific metadata.
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
getCacheFields( $prefix='img_')
int $bits
Returned by getimagesize (loadFromXxx)
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, $user=null, $tags=[])
getHashPath inherited
bool $missing
True if file is not present in file system.
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
loadExtraFromDB()
Load lazy file metadata from the DB.
recordUpload2( $oldver, $comment, $pageText, $props=false, $timestamp=false, $user=null, $tags=[])
Record a file upload in the upload log and the image table.
nextHistoryLine()
Returns the history of this file, line by line.
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
int $deleted
Bitfield akin to rev_deleted.
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
getMetadata()
Get handler-specific metadata.
__construct( $title, $repo)
Constructor.
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
bool $fileExists
Does the file exist on disk? (loadFromXxx)
static getHashFromKey( $key)
Gets the SHA1 hash from a storage key.
static makeParamBlob( $params)
Create a blob from a parameter array.
MimeMagic helper wrapper.
Class for creating log entries manually, to inject them into the database.
setTimestamp( $timestamp)
Set the timestamp of when the logged action took place.
static singleton()
Get an instance of this class.
static selectFields()
Fields in the oldimage table.
Set options of the Parser.
static singleton()
Get a RepoGroup instance.
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
static newNullRevision( $dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page's history.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
static factory(array $deltas)
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
isGood()
Returns whether the operation completed and didn't have any error or warnings.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Job for asynchronous rendering of thumbnails.
Represents a title within MediaWiki.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Special handling for file pages.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
when a variable name is used in a it is silently declared as a new local masking the global
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
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
the array() calling protocol came about after MediaWiki 1.4rc1.
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' 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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
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
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
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
it s the revision text itself In either if gzip is the revision text is gzipped $flags
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
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
Allows to change the fields on the form that will be generated $name
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' 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
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
if(count( $args)==0) $dir
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
Basic database interface for live and lazy-loaded relation database handles.
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[])
A SELECT wrapper which returns a single field from a single result row.
MediaWiki has optional support for a high distributed memory object caching system For general information on but for a larger site with heavy load
if(!isset( $args[0])) $lang
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)