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