MediaWiki master
rebuildFileCache.php
Go to the documentation of this file.
1<?php
33use Wikimedia\AtEase\AtEase;
35
36// @codeCoverageIgnoreStart
37require_once __DIR__ . '/Maintenance.php';
38// @codeCoverageIgnoreEnd
39
47 private $enabled = true;
48
49 public function __construct() {
50 parent::__construct();
51 $this->addDescription( 'Build the file cache' );
52 $this->addOption( 'start', 'Page_id to start from', false, true );
53 $this->addOption( 'end', 'Page_id to end on', false, true );
54 $this->addOption( 'overwrite', 'Refresh page cache' );
55 $this->addOption( 'all', 'Build the file cache for pages in all namespaces, not just content pages' );
56 $this->setBatchSize( 100 );
57 }
58
59 public function finalSetup( SettingsBuilder $settingsBuilder ) {
60 $this->enabled = $settingsBuilder->getConfig()->get( MainConfigNames::UseFileCache );
61 // Script will handle capturing output and saving it itself
62 $settingsBuilder->putConfigValue( MainConfigNames::UseFileCache, false );
63
64 // Avoid DB writes (like enotif/counters)
65 $this->getServiceContainer()->getReadOnlyMode()
66 ->setReason( 'Building cache' );
67
68 // Ensure no debug-specific logic ends up in the cache (must be after Setup.php)
69 MWDebug::deinit();
70
71 parent::finalSetup( $settingsBuilder );
72 }
73
74 public function execute() {
75 if ( !$this->enabled ) {
76 $this->fatalError( "Nothing to do -- \$wgUseFileCache is disabled." );
77 }
78
79 $start = $this->getOption( 'start', "0" );
80 if ( !ctype_digit( $start ) ) {
81 $this->fatalError( "Invalid value for start parameter." );
82 }
83 $start = intval( $start );
84
85 $end = $this->getOption( 'end', "0" );
86 if ( !ctype_digit( $end ) ) {
87 $this->fatalError( "Invalid value for end parameter." );
88 }
89 $end = intval( $end );
90
91 $this->output( "Building page file cache from page_id {$start}!\n" );
92
93 $dbr = $this->getReplicaDB();
94 $batchSize = $this->getBatchSize();
95 $overwrite = $this->hasOption( 'overwrite' );
96 $start = ( $start > 0 )
97 ? $start
98 : $dbr->newSelectQueryBuilder()
99 ->select( 'MIN(page_id)' )
100 ->from( 'page' )
101 ->caller( __METHOD__ )->fetchField();
102 $end = ( $end > 0 )
103 ? $end
104 : $dbr->newSelectQueryBuilder()
105 ->select( 'MAX(page_id)' )
106 ->from( 'page' )
107 ->caller( __METHOD__ )->fetchField();
108 if ( !$start ) {
109 $this->fatalError( "Nothing to do." );
110 }
111
112 $where = [];
113 if ( !$this->getOption( 'all' ) ) {
114 // If 'all' isn't passed as an option, just fall back to previous behaviour
115 // of using content namespaces
116 $where['page_namespace'] =
117 $this->getServiceContainer()->getNamespaceInfo()->getContentNamespaces();
118 }
119
120 // Mock request (hack, no real client)
121 $_SERVER['HTTP_ACCEPT_ENCODING'] = 'bgzip';
122
123 # Do remaining chunk
124 $end += $batchSize - 1;
125 $blockStart = $start;
126 $blockEnd = $start + $batchSize - 1;
127
128 $dbw = $this->getPrimaryDB();
129 // Go through each page and save the output
130 while ( $blockEnd <= $end ) {
131 // Get the pages
132 $res = $dbr->newSelectQueryBuilder()
133 ->select( [ 'page_namespace', 'page_title', 'page_id' ] )
134 ->from( 'page' )
135 ->useIndex( 'PRIMARY' )
136 ->where( $where )
137 ->andWhere( [
138 $dbr->expr( 'page_id', '>=', (int)$blockStart ),
139 $dbr->expr( 'page_id', '<=', (int)$blockEnd ),
140 ] )
141 ->orderBy( 'page_id', SelectQueryBuilder::SORT_ASC )
142 ->caller( __METHOD__ )->fetchResultSet();
143
144 $this->beginTransaction( $dbw, __METHOD__ ); // for any changes
145 foreach ( $res as $row ) {
146 $rebuilt = false;
147
148 $title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
149 if ( $title === null ) {
150 $this->output( "Page {$row->page_id} has bad title\n" );
151 continue; // broken title?
152 }
153
154 $context = new RequestContext();
155 $context->setTitle( $title );
156 $article = Article::newFromTitle( $title, $context );
157 $context->setWikiPage( $article->getPage() );
158
159 // Some extensions like FlaggedRevs while error out if this is unset
160 RequestContext::getMain()->setTitle( $title );
161
162 // If the article is cacheable, then load it
163 if ( $article->isFileCacheable( HTMLFileCache::MODE_REBUILD ) ) {
164 $viewCache = new HTMLFileCache( $title, 'view' );
165 $historyCache = new HTMLFileCache( $title, 'history' );
166 if ( $viewCache->isCacheGood() && $historyCache->isCacheGood() ) {
167 if ( $overwrite ) {
168 $rebuilt = true;
169 } else {
170 $this->output( "Page '$title' (id {$row->page_id}) already cached\n" );
171 continue; // done already!
172 }
173 }
174
175 AtEase::suppressWarnings(); // header notices
176
177 // 1. Cache ?action=view
178 // Be sure to reset the mocked request time (T24852)
179 $_SERVER['REQUEST_TIME_FLOAT'] = microtime( true );
180 ob_start();
181 $article->view();
182 $context->getOutput()->output();
183 $context->getOutput()->clearHTML();
184 $viewHtml = ob_get_clean();
185 $viewCache->saveToFileCache( $viewHtml );
186
187 // 2. Cache ?action=history
188 // Be sure to reset the mocked request time (T24852)
189 $_SERVER['REQUEST_TIME_FLOAT'] = microtime( true );
190 ob_start();
191 Action::factory( 'history', $article, $context )->show();
192 $context->getOutput()->output();
193 $context->getOutput()->clearHTML();
194 $historyHtml = ob_get_clean();
195 $historyCache->saveToFileCache( $historyHtml );
196
197 AtEase::restoreWarnings();
198
199 if ( $rebuilt ) {
200 $this->output( "Re-cached page '$title' (id {$row->page_id})..." );
201 } else {
202 $this->output( "Cached page '$title' (id {$row->page_id})..." );
203 }
204 $this->output( "[view: " . strlen( $viewHtml ) . " bytes; " .
205 "history: " . strlen( $historyHtml ) . " bytes]\n" );
206 } else {
207 $this->output( "Page '$title' (id {$row->page_id}) not cacheable\n" );
208 }
209 }
210 $this->commitTransaction( $dbw, __METHOD__ ); // commit any changes
211
212 $blockStart += $batchSize;
213 $blockEnd += $batchSize;
214 }
215 $this->output( "Done!\n" );
216 }
217}
218
219// @codeCoverageIgnoreStart
220$maintClass = RebuildFileCache::class;
221require_once RUN_MAINTENANCE_IF_MAIN;
222// @codeCoverageIgnoreEnd
Actions are things which can be done to pages (edit, delete, rollback, etc).
Definition Action.php:66
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:49
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.
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DB servers to catch up.
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.
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB handle.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Legacy class representing an editable page and handling UI for some page actions.
Definition Article.php:76
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:78
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.