/** * checkLastModified returns true if it has taken care of all * output to the client that is necessary for this request. * (that is, it has sent a cached version of the page) * * @return bool True if cached version send, false otherwise */ protected function tryFileCache() { static $called = false; if ($called) { wfDebug("Article::tryFileCache(): called twice!?\n"); return false; } $called = true; if ($this->isFileCacheable()) { $cache = new HTMLFileCache($this->getTitle(), 'view'); if ($cache->isCacheGood($this->mPage->getTouched())) { wfDebug("Article::tryFileCache(): about to load file\n"); $cache->loadFromFileCache($this->getContext()); return true; } else { wfDebug("Article::tryFileCache(): starting buffer\n"); ob_start(array(&$cache, 'saveToFileCache')); } } else { wfDebug("Article::tryFileCache(): not cacheable\n"); } return false; }
/** * Print the history page for an article. */ function onView() { $out = $this->getOutput(); $request = $this->getRequest(); /** * Allow client caching. */ if ($out->checkLastModified($this->page->getTouched())) { return; // Client cache fresh and headers sent, nothing more to do. } $this->preCacheMessages(); $config = $this->context->getConfig(); # Fill in the file cache if not set already if (HTMLFileCache::useFileCache($this->getContext())) { $cache = new HTMLFileCache($this->getTitle(), 'history'); if (!$cache->isCacheGood()) { ob_start([&$cache, 'saveToFileCache']); } } // Setup page variables. $out->setFeedAppendQuery('action=history'); $out->addModules('mediawiki.action.history'); $out->addModuleStyles(['mediawiki.action.history.styles', 'mediawiki.special.changeslist']); if ($config->get('UseMediaWikiUIEverywhere')) { $out = $this->getOutput(); $out->addModuleStyles(['mediawiki.ui.input', 'mediawiki.ui.checkbox']); } // Handle atom/RSS feeds. $feedType = $request->getVal('feed'); if ($feedType) { $this->feed($feedType); return; } $this->addHelpLink('//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Page_history', true); // Fail nicely if article doesn't exist. if (!$this->page->exists()) { global $wgSend404Code; if ($wgSend404Code) { $out->setStatusCode(404); } $out->addWikiMsg('nohistory'); # show deletion/move log if there is an entry LogEventsList::showLogExtract($out, ['delete', 'move'], $this->getTitle(), '', ['lim' => 10, 'conds' => ["log_action != 'revision'"], 'showIfEmpty' => false, 'msgKey' => ['moveddeleted-notice']]); return; } /** * Add date selector to quickly get to a certain time */ $year = $request->getInt('year'); $month = $request->getInt('month'); $tagFilter = $request->getVal('tagfilter'); $tagSelector = ChangeTags::buildTagFilterSelector($tagFilter); /** * Option to show only revisions that have been (partially) hidden via RevisionDelete */ if ($request->getBool('deleted')) { $conds = ['rev_deleted != 0']; } else { $conds = []; } if ($this->getUser()->isAllowed('deletedhistory')) { $checkDeleted = Xml::checkLabel($this->msg('history-show-deleted')->text(), 'deleted', 'mw-show-deleted-only', $request->getBool('deleted')) . "\n"; } else { $checkDeleted = ''; } // Add the general form $action = htmlspecialchars(wfScript()); $out->addHTML("<form action=\"{$action}\" method=\"get\" id=\"mw-history-searchform\">" . Xml::fieldset($this->msg('history-fieldset-title')->text(), false, ['id' => 'mw-history-search']) . Html::hidden('title', $this->getTitle()->getPrefixedDBkey()) . "\n" . Html::hidden('action', 'history') . "\n" . Xml::dateMenu($year == null ? MWTimestamp::getLocalInstance()->format('Y') : $year, $month) . ' ' . ($tagSelector ? implode(' ', $tagSelector) . ' ' : '') . $checkDeleted . Html::submitButton($this->msg('historyaction-submit')->text(), [], ['mw-ui-progressive']) . "\n" . '</fieldset></form>'); Hooks::run('PageHistoryBeforeList', [&$this->page, $this->getContext()]); // Create and output the list. $pager = new HistoryPager($this, $year, $month, $tagFilter, $conds); $out->addHTML($pager->getNavigationBar() . $pager->getBody() . $pager->getNavigationBar()); $out->preventClickjacking($pager->getPreventClickjacking()); }
private function main() { global $wgTitle; wfProfileIn(__METHOD__); $request = $this->context->getRequest(); // Send Ajax requests to the Ajax dispatcher. if ($this->config->get('UseAjax') && $request->getVal('action', 'view') == 'ajax') { // Set a dummy title, because $wgTitle == null might break things $title = Title::makeTitle(NS_MAIN, 'AJAX'); $this->context->setTitle($title); $wgTitle = $title; $dispatcher = new AjaxDispatcher($this->config); $dispatcher->performAction($this->context->getUser()); wfProfileOut(__METHOD__); return; } // Get title from request parameters, // is set on the fly by parseTitle the first time. $title = $this->getTitle(); $action = $this->getAction(); $wgTitle = $title; // If the user has forceHTTPS set to true, or if the user // is in a group requiring HTTPS, or if they have the HTTPS // preference set, redirect them to HTTPS. // Note: Do this after $wgTitle is setup, otherwise the hooks run from // isLoggedIn() will do all sorts of weird stuff. if ($request->getProtocol() == 'http' && ($request->getCookie('forceHTTPS', '') || $request->getCookie('forceHTTPS') || $this->context->getUser()->isLoggedIn() && $this->context->getUser()->requiresHTTPS())) { $oldUrl = $request->getFullRequestURL(); $redirUrl = preg_replace('#^http://#', 'https://', $oldUrl); // ATTENTION: This hook is likely to be removed soon due to overall design of the system. if (wfRunHooks('BeforeHttpsRedirect', array($this->context, &$redirUrl))) { if ($request->wasPosted()) { // This is weird and we'd hope it almost never happens. This // means that a POST came in via HTTP and policy requires us // redirecting to HTTPS. It's likely such a request is going // to fail due to post data being lost, but let's try anyway // and just log the instance. // // @todo FIXME: See if we could issue a 307 or 308 here, need // to see how clients (automated & browser) behave when we do wfDebugLog('RedirectedPosts', "Redirected from HTTP to HTTPS: {$oldUrl}"); } // Setup dummy Title, otherwise OutputPage::redirect will fail $title = Title::newFromText(NS_MAIN, 'REDIR'); $this->context->setTitle($title); $output = $this->context->getOutput(); // Since we only do this redir to change proto, always send a vary header $output->addVaryHeader('X-Forwarded-Proto'); $output->redirect($redirUrl); $output->output(); wfProfileOut(__METHOD__); return; } } if ($this->config->get('UseFileCache') && $title->getNamespace() >= 0) { wfProfileIn('main-try-filecache'); if (HTMLFileCache::useFileCache($this->context)) { // Try low-level file cache hit $cache = new HTMLFileCache($title, $action); if ($cache->isCacheGood()) { // Check incoming headers to see if client has this cached $timestamp = $cache->cacheTimestamp(); if (!$this->context->getOutput()->checkLastModified($timestamp)) { $cache->loadFromFileCache($this->context); } // Do any stats increment/watchlist stuff // Assume we're viewing the latest revision (this should always be the case with file cache) $this->context->getWikiPage()->doViewUpdates($this->context->getUser()); // Tell OutputPage that output is taken care of $this->context->getOutput()->disable(); wfProfileOut('main-try-filecache'); wfProfileOut(__METHOD__); return; } } wfProfileOut('main-try-filecache'); } // Actually do the work of the request and build up any output $this->performRequest(); // Either all DB and deferred updates should happen or none. // The later should not be cancelled due to client disconnect. ignore_user_abort(true); // Now commit any transactions, so that unreported errors after // output() don't roll back the whole DB transaction wfGetLBFactory()->commitMasterChanges(); // Output everything! $this->context->getOutput()->output(); wfProfileOut(__METHOD__); }
private function main() { global $wgTitle; $output = $this->context->getOutput(); $request = $this->context->getRequest(); // Send Ajax requests to the Ajax dispatcher. if ($this->config->get('UseAjax') && $request->getVal('action') === 'ajax') { // Set a dummy title, because $wgTitle == null might break things $title = Title::makeTitle(NS_SPECIAL, 'Badtitle/performing an AJAX call in ' . __METHOD__); $this->context->setTitle($title); $wgTitle = $title; $dispatcher = new AjaxDispatcher($this->config); $dispatcher->performAction($this->context->getUser()); return; } // Get title from request parameters, // is set on the fly by parseTitle the first time. $title = $this->getTitle(); $action = $this->getAction(); $wgTitle = $title; // Set DB query expectations for this HTTP request $trxLimits = $this->config->get('TrxProfilerLimits'); $trxProfiler = Profiler::instance()->getTransactionProfiler(); $trxProfiler->setLogger(LoggerFactory::getInstance('DBPerformance')); if ($request->hasSafeMethod()) { $trxProfiler->setExpectations($trxLimits['GET'], __METHOD__); } else { $trxProfiler->setExpectations($trxLimits['POST'], __METHOD__); } // If the user has forceHTTPS set to true, or if the user // is in a group requiring HTTPS, or if they have the HTTPS // preference set, redirect them to HTTPS. // Note: Do this after $wgTitle is setup, otherwise the hooks run from // isLoggedIn() will do all sorts of weird stuff. if ($request->getProtocol() == 'http' && preg_match('#^https://#', wfExpandUrl($request->getRequestURL(), PROTO_HTTPS)) && ($request->getSession()->shouldForceHTTPS() || $request->getCookie('forceHTTPS', '') || $request->getCookie('forceHTTPS') || $this->context->getUser()->isLoggedIn() && $this->context->getUser()->requiresHTTPS())) { $oldUrl = $request->getFullRequestURL(); $redirUrl = preg_replace('#^http://#', 'https://', $oldUrl); // ATTENTION: This hook is likely to be removed soon due to overall design of the system. if (Hooks::run('BeforeHttpsRedirect', [$this->context, &$redirUrl])) { if ($request->wasPosted()) { // This is weird and we'd hope it almost never happens. This // means that a POST came in via HTTP and policy requires us // redirecting to HTTPS. It's likely such a request is going // to fail due to post data being lost, but let's try anyway // and just log the instance. // @todo FIXME: See if we could issue a 307 or 308 here, need // to see how clients (automated & browser) behave when we do wfDebugLog('RedirectedPosts', "Redirected from HTTP to HTTPS: {$oldUrl}"); } // Setup dummy Title, otherwise OutputPage::redirect will fail $title = Title::newFromText('REDIR', NS_MAIN); $this->context->setTitle($title); // Since we only do this redir to change proto, always send a vary header $output->addVaryHeader('X-Forwarded-Proto'); $output->redirect($redirUrl); $output->output(); return; } } if ($title->canExist() && HTMLFileCache::useFileCache($this->context)) { // Try low-level file cache hit $cache = new HTMLFileCache($title, $action); if ($cache->isCacheGood()) { // Check incoming headers to see if client has this cached $timestamp = $cache->cacheTimestamp(); if (!$output->checkLastModified($timestamp)) { $cache->loadFromFileCache($this->context); } // Do any stats increment/watchlist stuff, assuming user is viewing the // latest revision (which should always be the case for file cache) $this->context->getWikiPage()->doViewUpdates($this->context->getUser()); // Tell OutputPage that output is taken care of $output->disable(); return; } } // Actually do the work of the request and build up any output $this->performRequest(); // GUI-ify and stash the page output in MediaWiki::doPreOutputCommit() while // ChronologyProtector synchronizes DB positions or slaves accross all datacenters. $buffer = null; $outputWork = function () use($output, &$buffer) { if ($buffer === null) { $buffer = $output->output(true); } return $buffer; }; // Now commit any transactions, so that unreported errors after // output() don't roll back the whole DB transaction and so that // we avoid having both success and error text in the response $this->doPreOutputCommit($outputWork); // Now send the actual output print $outputWork(); }
public function execute() { global $wgRequestTime; if (!$this->enabled) { $this->error("Nothing to do -- \$wgUseFileCache is disabled.", true); } $start = $this->getOption('start', "0"); if (!ctype_digit($start)) { $this->error("Invalid value for start parameter.", true); } $start = intval($start); $end = $this->getOption('end', "0"); if (!ctype_digit($end)) { $this->error("Invalid value for end parameter.", true); } $end = intval($end); $this->output("Building content page file cache from page {$start}!\n"); $dbr = $this->getDB(DB_REPLICA); $overwrite = $this->getOption('overwrite', false); $start = $start > 0 ? $start : $dbr->selectField('page', 'MIN(page_id)', false, __METHOD__); $end = $end > 0 ? $end : $dbr->selectField('page', 'MAX(page_id)', false, __METHOD__); if (!$start) { $this->error("Nothing to do.", true); } $_SERVER['HTTP_ACCEPT_ENCODING'] = 'bgzip'; // hack, no real client # Do remaining chunk $end += $this->mBatchSize - 1; $blockStart = $start; $blockEnd = $start + $this->mBatchSize - 1; $dbw = $this->getDB(DB_MASTER); // Go through each page and save the output while ($blockEnd <= $end) { // Get the pages $res = $dbr->select('page', ['page_namespace', 'page_title', 'page_id'], ['page_namespace' => MWNamespace::getContentNamespaces(), "page_id BETWEEN {$blockStart} AND {$blockEnd}"], __METHOD__, ['ORDER BY' => 'page_id ASC', 'USE INDEX' => 'PRIMARY']); $this->beginTransaction($dbw, __METHOD__); // for any changes foreach ($res as $row) { $rebuilt = false; $title = Title::makeTitleSafe($row->page_namespace, $row->page_title); if (null == $title) { $this->output("Page {$row->page_id} has bad title\n"); continue; // broken title? } $context = new RequestContext(); $context->setTitle($title); $article = Article::newFromTitle($title, $context); $context->setWikiPage($article->getPage()); // If the article is cacheable, then load it if ($article->isFileCacheable(HTMLFileCache::MODE_REBUILD)) { $viewCache = new HTMLFileCache($title, 'view'); $historyCache = new HTMLFileCache($title, 'history'); if ($viewCache->isCacheGood() && $historyCache->isCacheGood()) { if ($overwrite) { $rebuilt = true; } else { $this->output("Page '{$title}' (id {$row->page_id}) already cached\n"); continue; // done already! } } MediaWiki\suppressWarnings(); // header notices // Cache ?action=view $wgRequestTime = microtime(true); # bug 22852 ob_start(); $article->view(); $context->getOutput()->output(); $context->getOutput()->clearHTML(); $viewHtml = ob_get_clean(); $viewCache->saveToFileCache($viewHtml); // Cache ?action=history $wgRequestTime = microtime(true); # bug 22852 ob_start(); Action::factory('history', $article, $context)->show(); $context->getOutput()->output(); $context->getOutput()->clearHTML(); $historyHtml = ob_get_clean(); $historyCache->saveToFileCache($historyHtml); MediaWiki\restoreWarnings(); if ($rebuilt) { $this->output("Re-cached page '{$title}' (id {$row->page_id})..."); } else { $this->output("Cached page '{$title}' (id {$row->page_id})..."); } $this->output("[view: " . strlen($viewHtml) . " bytes; " . "history: " . strlen($historyHtml) . " bytes]\n"); } else { $this->output("Page '{$title}' (id {$row->page_id}) not cacheable\n"); } } $this->commitTransaction($dbw, __METHOD__); // commit any changes (just for sanity) $blockStart += $this->mBatchSize; $blockEnd += $this->mBatchSize; } $this->output("Done!\n"); }