Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 111
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
RebuildFileCache
0.00% covered (danger)
0.00%
0 / 108
0.00% covered (danger)
0.00%
0 / 3
342
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 finalSetup
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 95
0.00% covered (danger)
0.00%
0 / 1
272
1<?php
2/**
3 * Build file cache for content pages
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Maintenance
22 */
23
24use MediaWiki\Context\RequestContext;
25use MediaWiki\Debug\MWDebug;
26use MediaWiki\MainConfigNames;
27use MediaWiki\Settings\SettingsBuilder;
28use MediaWiki\Title\Title;
29use Wikimedia\AtEase\AtEase;
30use Wikimedia\Rdbms\SelectQueryBuilder;
31
32require_once __DIR__ . '/Maintenance.php';
33
34/**
35 * Maintenance script that builds the file cache.
36 *
37 * @ingroup Maintenance
38 */
39class RebuildFileCache extends Maintenance {
40    private $enabled = true;
41
42    public function __construct() {
43        parent::__construct();
44        $this->addDescription( 'Build the file cache' );
45        $this->addOption( 'start', 'Page_id to start from', false, true );
46        $this->addOption( 'end', 'Page_id to end on', false, true );
47        $this->addOption( 'overwrite', 'Refresh page cache' );
48        $this->addOption( 'all', 'Build the file cache for pages in all namespaces, not just content pages' );
49        $this->setBatchSize( 100 );
50    }
51
52    public function finalSetup( SettingsBuilder $settingsBuilder ) {
53        $this->enabled = $settingsBuilder->getConfig()->get( MainConfigNames::UseFileCache );
54        // Script will handle capturing output and saving it itself
55        $settingsBuilder->putConfigValue( MainConfigNames::UseFileCache, false );
56
57        // Avoid DB writes (like enotif/counters)
58        $this->getServiceContainer()->getReadOnlyMode()
59            ->setReason( 'Building cache' );
60
61        // Ensure no debug-specific logic ends up in the cache (must be after Setup.php)
62        MWDebug::deinit();
63
64        parent::finalSetup( $settingsBuilder );
65    }
66
67    public function execute() {
68        if ( !$this->enabled ) {
69            $this->fatalError( "Nothing to do -- \$wgUseFileCache is disabled." );
70        }
71
72        $start = $this->getOption( 'start', "0" );
73        if ( !ctype_digit( $start ) ) {
74            $this->fatalError( "Invalid value for start parameter." );
75        }
76        $start = intval( $start );
77
78        $end = $this->getOption( 'end', "0" );
79        if ( !ctype_digit( $end ) ) {
80            $this->fatalError( "Invalid value for end parameter." );
81        }
82        $end = intval( $end );
83
84        $this->output( "Building page file cache from page_id {$start}!\n" );
85
86        $dbr = $this->getReplicaDB();
87        $batchSize = $this->getBatchSize();
88        $overwrite = $this->hasOption( 'overwrite' );
89        $start = ( $start > 0 )
90            ? $start
91            : $dbr->newSelectQueryBuilder()
92                ->select( 'MIN(page_id)' )
93                ->from( 'page' )
94                ->caller( __METHOD__ )->fetchField();
95        $end = ( $end > 0 )
96            ? $end
97            : $dbr->newSelectQueryBuilder()
98                ->select( 'MAX(page_id)' )
99                ->from( 'page' )
100                ->caller( __METHOD__ )->fetchField();
101        if ( !$start ) {
102            $this->fatalError( "Nothing to do." );
103        }
104
105        $where = [];
106        if ( !$this->getOption( 'all' ) ) {
107            // If 'all' isn't passed as an option, just fall back to previous behaviour
108            // of using content namespaces
109            $where['page_namespace'] =
110                $this->getServiceContainer()->getNamespaceInfo()->getContentNamespaces();
111        }
112
113        // Mock request (hack, no real client)
114        $_SERVER['HTTP_ACCEPT_ENCODING'] = 'bgzip';
115
116        # Do remaining chunk
117        $end += $batchSize - 1;
118        $blockStart = $start;
119        $blockEnd = $start + $batchSize - 1;
120
121        $dbw = $this->getPrimaryDB();
122        // Go through each page and save the output
123        while ( $blockEnd <= $end ) {
124            // Get the pages
125            $res = $dbr->newSelectQueryBuilder()
126                ->select( [ 'page_namespace', 'page_title', 'page_id' ] )
127                ->from( 'page' )
128                ->useIndex( 'PRIMARY' )
129                ->where( $where )
130                ->andWhere( [
131                    $dbr->expr( 'page_id', '>=', (int)$blockStart ),
132                    $dbr->expr( 'page_id', '<=', (int)$blockEnd ),
133                ] )
134                ->orderBy( 'page_id', SelectQueryBuilder::SORT_ASC )
135                ->caller( __METHOD__ )->fetchResultSet();
136
137            $this->beginTransaction( $dbw, __METHOD__ ); // for any changes
138            foreach ( $res as $row ) {
139                $rebuilt = false;
140
141                $title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
142                if ( $title === null ) {
143                    $this->output( "Page {$row->page_id} has bad title\n" );
144                    continue; // broken title?
145                }
146
147                $context = new RequestContext();
148                $context->setTitle( $title );
149                $article = Article::newFromTitle( $title, $context );
150                $context->setWikiPage( $article->getPage() );
151
152                // Some extensions like FlaggedRevs while error out if this is unset
153                RequestContext::getMain()->setTitle( $title );
154
155                // If the article is cacheable, then load it
156                if ( $article->isFileCacheable( HTMLFileCache::MODE_REBUILD ) ) {
157                    $viewCache = new HTMLFileCache( $title, 'view' );
158                    $historyCache = new HTMLFileCache( $title, 'history' );
159                    if ( $viewCache->isCacheGood() && $historyCache->isCacheGood() ) {
160                        if ( $overwrite ) {
161                            $rebuilt = true;
162                        } else {
163                            $this->output( "Page '$title' (id {$row->page_id}) already cached\n" );
164                            continue; // done already!
165                        }
166                    }
167
168                    AtEase::suppressWarnings(); // header notices
169
170                    // 1. Cache ?action=view
171                    // Be sure to reset the mocked request time (T24852)
172                    $_SERVER['REQUEST_TIME_FLOAT'] = microtime( true );
173                    ob_start();
174                    $article->view();
175                    $context->getOutput()->output();
176                    $context->getOutput()->clearHTML();
177                    $viewHtml = ob_get_clean();
178                    $viewCache->saveToFileCache( $viewHtml );
179
180                    // 2. Cache ?action=history
181                    // Be sure to reset the mocked request time (T24852)
182                    $_SERVER['REQUEST_TIME_FLOAT'] = microtime( true );
183                    ob_start();
184                    Action::factory( 'history', $article, $context )->show();
185                    $context->getOutput()->output();
186                    $context->getOutput()->clearHTML();
187                    $historyHtml = ob_get_clean();
188                    $historyCache->saveToFileCache( $historyHtml );
189
190                    AtEase::restoreWarnings();
191
192                    if ( $rebuilt ) {
193                        $this->output( "Re-cached page '$title' (id {$row->page_id})..." );
194                    } else {
195                        $this->output( "Cached page '$title' (id {$row->page_id})..." );
196                    }
197                    $this->output( "[view: " . strlen( $viewHtml ) . " bytes; " .
198                        "history: " . strlen( $historyHtml ) . " bytes]\n" );
199                } else {
200                    $this->output( "Page '$title' (id {$row->page_id}) not cacheable\n" );
201                }
202            }
203            $this->commitTransaction( $dbw, __METHOD__ ); // commit any changes
204
205            $blockStart += $batchSize;
206            $blockEnd += $batchSize;
207        }
208        $this->output( "Done!\n" );
209    }
210}
211
212$maintClass = RebuildFileCache::class;
213require_once RUN_MAINTENANCE_IF_MAIN;