MediaWiki master
rebuildFileCache.php
Go to the documentation of this file.
1<?php
20
21// @codeCoverageIgnoreStart
22require_once __DIR__ . '/Maintenance.php';
23// @codeCoverageIgnoreEnd
24
32 private $enabled = true;
33
34 public function __construct() {
35 parent::__construct();
36 $this->addDescription( 'Build the file cache' );
37 $this->addOption( 'start', 'Page_id to start from', false, true );
38 $this->addOption( 'end', 'Page_id to end on', false, true );
39 $this->addOption( 'overwrite', 'Refresh page cache' );
40 $this->addOption( 'all', 'Build the file cache for pages in all namespaces, not just content pages' );
41 $this->setBatchSize( 100 );
42 }
43
44 public function finalSetup( SettingsBuilder $settingsBuilder ) {
45 $this->enabled = $settingsBuilder->getConfig()->get( MainConfigNames::UseFileCache );
46 // Script will handle capturing output and saving it itself
47 $settingsBuilder->putConfigValue( MainConfigNames::UseFileCache, false );
48
49 // Avoid DB writes (like enotif/counters)
50 $this->getServiceContainer()->getReadOnlyMode()
51 ->setReason( 'Building cache' );
52
53 // Ensure no debug-specific logic ends up in the cache (must be after Setup.php)
54 MWDebug::deinit();
55
56 parent::finalSetup( $settingsBuilder );
57 }
58
59 public function execute() {
60 if ( !$this->enabled ) {
61 $this->fatalError( "Nothing to do -- \$wgUseFileCache is disabled." );
62 }
63
64 $start = $this->getOption( 'start', "0" );
65 if ( !ctype_digit( $start ) ) {
66 $this->fatalError( "Invalid value for start parameter." );
67 }
68 $start = intval( $start );
69
70 $end = $this->getOption( 'end', "0" );
71 if ( !ctype_digit( $end ) ) {
72 $this->fatalError( "Invalid value for end parameter." );
73 }
74 $end = intval( $end );
75
76 $this->output( "Building page file cache from page_id {$start}!\n" );
77
78 $dbr = $this->getReplicaDB();
79 $batchSize = $this->getBatchSize();
80 $overwrite = $this->hasOption( 'overwrite' );
81 $start = ( $start > 0 )
82 ? $start
83 : $dbr->newSelectQueryBuilder()
84 ->select( 'MIN(page_id)' )
85 ->from( 'page' )
86 ->caller( __METHOD__ )->fetchField();
87 $end = ( $end > 0 )
88 ? $end
89 : $dbr->newSelectQueryBuilder()
90 ->select( 'MAX(page_id)' )
91 ->from( 'page' )
92 ->caller( __METHOD__ )->fetchField();
93 if ( !$start ) {
94 $this->fatalError( "Nothing to do." );
95 }
96
97 $where = [];
98 if ( !$this->getOption( 'all' ) ) {
99 // If 'all' isn't passed as an option, just fall back to previous behaviour
100 // of using content namespaces
101 $where['page_namespace'] =
102 $this->getServiceContainer()->getNamespaceInfo()->getContentNamespaces();
103 }
104
105 // Mock request (hack, no real client)
106 $_SERVER['HTTP_ACCEPT_ENCODING'] = 'bgzip';
107
108 # Do remaining chunk
109 $end += $batchSize - 1;
110 $blockStart = $start;
111 $blockEnd = $start + $batchSize - 1;
112
113 $dbw = $this->getPrimaryDB();
114 // Go through each page and save the output
115 while ( $blockEnd <= $end ) {
116 // Get the pages
117 $res = $dbr->newSelectQueryBuilder()
118 ->select( [ 'page_namespace', 'page_title', 'page_id' ] )
119 ->from( 'page' )
120 ->useIndex( 'PRIMARY' )
121 ->where( $where )
122 ->andWhere( [
123 $dbr->expr( 'page_id', '>=', (int)$blockStart ),
124 $dbr->expr( 'page_id', '<=', (int)$blockEnd ),
125 ] )
126 ->orderBy( 'page_id', SelectQueryBuilder::SORT_ASC )
127 ->caller( __METHOD__ )->fetchResultSet();
128
129 $this->beginTransactionRound( __METHOD__ ); // for any changes
130 foreach ( $res as $row ) {
131 $rebuilt = false;
132
133 $title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
134 if ( $title === null ) {
135 $this->output( "Page {$row->page_id} has bad title\n" );
136 continue; // broken title?
137 }
138
139 $context = new RequestContext();
140 $context->setTitle( $title );
141 $article = Article::newFromTitle( $title, $context );
142 $context->setWikiPage( $article->getPage() );
143
144 // Some extensions like FlaggedRevs while error out if this is unset
145 RequestContext::getMain()->setTitle( $title );
146
147 // If the article is cacheable, then load it
148 if ( $article->isFileCacheable( HTMLFileCache::MODE_REBUILD ) ) {
149 $viewCache = new HTMLFileCache( $title, 'view' );
150 $historyCache = new HTMLFileCache( $title, 'history' );
151 if ( $viewCache->isCacheGood() && $historyCache->isCacheGood() ) {
152 if ( $overwrite ) {
153 $rebuilt = true;
154 } else {
155 $this->output( "Page '$title' (id {$row->page_id}) already cached\n" );
156 continue; // done already!
157 }
158 }
159
160 // 1. Cache ?action=view
161 // Be sure to reset the mocked request time (T24852)
162 $_SERVER['REQUEST_TIME_FLOAT'] = microtime( true );
163 ob_start();
164 $article->view();
165 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- causes "header already sent" notices
166 @$context->getOutput()->output();
167 $context->getOutput()->clearHTML();
168 $viewHtml = ob_get_clean();
169 $viewCache->saveToFileCache( $viewHtml );
170
171 // 2. Cache ?action=history
172 // Be sure to reset the mocked request time (T24852)
173 $_SERVER['REQUEST_TIME_FLOAT'] = microtime( true );
174 ob_start();
175 Action::factory( 'history', $article, $context )->show();
176 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- causes "header already sent" notices
177 @$context->getOutput()->output();
178 $context->getOutput()->clearHTML();
179 $historyHtml = ob_get_clean();
180 $historyCache->saveToFileCache( $historyHtml );
181
182 if ( $rebuilt ) {
183 $this->output( "Re-cached page '$title' (id {$row->page_id})..." );
184 } else {
185 $this->output( "Cached page '$title' (id {$row->page_id})..." );
186 }
187 $this->output( "[view: " . strlen( $viewHtml ) . " bytes; " .
188 "history: " . strlen( $historyHtml ) . " bytes]\n" );
189 } else {
190 $this->output( "Page '$title' (id {$row->page_id}) not cacheable\n" );
191 }
192 }
193 $this->commitTransactionRound( __METHOD__ ); // commit any changes
194
195 $blockStart += $batchSize;
196 $blockEnd += $batchSize;
197 }
198 $this->output( "Done!\n" );
199 }
200}
201
202// @codeCoverageIgnoreStart
203$maintClass = RebuildFileCache::class;
204require_once RUN_MAINTENANCE_IF_MAIN;
205// @codeCoverageIgnoreEnd
Actions are things which can be done to pages (edit, delete, rollback, etc).
Definition Action.php:53
Page view caching in the file system.
Group all the pieces relevant to the context of a request into one instance.
Debug toolbar.
Definition MWDebug.php:35
A class containing constants representing the names of configuration variables.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getBatchSize()
Returns batch size.
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
commitTransactionRound( $fname)
Commit a transactional batch of DB operations and wait for replica DB servers to catch up.
getReplicaDB(string|false $virtualDomain=false)
beginTransactionRound( $fname)
Start a transactional batch of DB operations.
getServiceContainer()
Returns the main service container.
getPrimaryDB(string|false $virtualDomain=false)
addDescription( $text)
Set the description text.
Legacy class representing an editable page and handling UI for some page actions.
Definition Article.php:64
Builder class for constructing a Config object from a set of sources during bootstrap.
getConfig()
Returns the config loaded so far.
putConfigValue(string $key, $value)
Puts a value into a config variable.
Represents a title within MediaWiki.
Definition Title.php:69
Maintenance script that builds the file cache.
execute()
Do the actual work.
finalSetup(SettingsBuilder $settingsBuilder)
Handle some last-minute setup here.
__construct()
Default constructor.
Build SELECT queries with a fluent interface.