3 * Raw page text accessor
5 * Copyright © 2004 Gabriel Wicke <wicke@wikidev.net>
8 * Based on HistoryAction and SpecialExport
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
25 * @author Gabriel Wicke <wicke@wikidev.net>
29 use MediaWiki\Content\TextContent
;
30 use MediaWiki\Context\IContextSource
;
31 use MediaWiki\Logger\LoggerFactory
;
32 use MediaWiki\MainConfigNames
;
33 use MediaWiki\Parser\Parser
;
34 use MediaWiki\Permissions\PermissionManager
;
35 use MediaWiki\Permissions\RestrictionStore
;
36 use MediaWiki\Revision\RevisionLookup
;
37 use MediaWiki\Revision\SlotRecord
;
38 use MediaWiki\Session\SessionManager
;
39 use MediaWiki\User\UserFactory
;
40 use MediaWiki\User\UserRigorOptions
;
43 * A simple method to retrieve the plain source of an article,
44 * using "action=raw" in the GET request string.
48 class RawAction
extends FormlessAction
{
50 private Parser
$parser;
51 private PermissionManager
$permissionManager;
52 private RevisionLookup
$revisionLookup;
53 private RestrictionStore
$restrictionStore;
54 private UserFactory
$userFactory;
57 * @param Article $article
58 * @param IContextSource $context
59 * @param Parser $parser
60 * @param PermissionManager $permissionManager
61 * @param RevisionLookup $revisionLookup
62 * @param RestrictionStore $restrictionStore
63 * @param UserFactory $userFactory
65 public function __construct(
67 IContextSource
$context,
69 PermissionManager
$permissionManager,
70 RevisionLookup
$revisionLookup,
71 RestrictionStore
$restrictionStore,
72 UserFactory
$userFactory
74 parent
::__construct( $article, $context );
75 $this->parser
= $parser;
76 $this->permissionManager
= $permissionManager;
77 $this->revisionLookup
= $revisionLookup;
78 $this->restrictionStore
= $restrictionStore;
79 $this->userFactory
= $userFactory;
83 public function getName() {
87 public function requiresWrite() {
91 public function requiresUnblock() {
96 * @suppress SecurityCheck-XSS Non html mime type
99 public function onView() {
100 $this->getOutput()->disable();
101 $request = $this->getRequest();
102 $response = $request->response();
103 $config = $this->context
->getConfig();
105 if ( $this->getOutput()->checkLastModified(
106 $this->getWikiPage()->getTouched()
108 // Client cache fresh and headers sent, nothing more to do.
112 $contentType = $this->getContentType();
114 $maxage = $request->getInt( 'maxage', $config->get( MainConfigNames
::CdnMaxAge
) );
115 $smaxage = $request->getIntOrNull( 'smaxage' );
116 if ( $smaxage === null ) {
118 $contentType === 'text/css' ||
119 $contentType === 'application/json' ||
120 $contentType === 'text/javascript'
122 // CSS/JSON/JS raw content has its own CDN max age configuration.
123 // Note: HTMLCacheUpdater::getUrls() includes action=raw for css/json/js
124 // pages, so if using the canonical url, this will get HTCP purges.
125 $smaxage = intval( $config->get( MainConfigNames
::ForcedRawSMaxage
) );
127 // No CDN cache for anything else
132 // Set standard Vary headers so cache varies on cookies and such (T125283)
133 $response->header( $this->getOutput()->getVaryHeader() );
135 // Output may contain user-specific data;
136 // vary generated content for open sessions on private wikis
137 $privateCache = !$this->permissionManager
->isEveryoneAllowed( 'read' ) &&
138 ( $smaxage === 0 || SessionManager
::getGlobalSession()->isPersistent() );
139 // Don't accidentally cache cookies if the user is registered (T55032)
140 $privateCache = $privateCache ||
$this->getUser()->isRegistered();
141 $mode = $privateCache ?
'private' : 'public';
143 'Cache-Control: ' . $mode . ', s-maxage=' . $smaxage . ', max-age=' . $maxage
146 // In the event of user JS, don't allow loading a user JS/CSS/Json
147 // subpage that has no registered user associated with, as
148 // someone could register the account and take control of the
150 $title = $this->getTitle();
151 if ( $title->isUserConfigPage() && $contentType !== 'text/x-wiki' ) {
152 // not using getRootText() as we want this to work
153 // even if subpages are disabled.
154 $rootPage = strtok( $title->getText(), '/' );
155 $userFromTitle = $this->userFactory
->newFromName( $rootPage, UserRigorOptions
::RIGOR_USABLE
);
156 if ( !$userFromTitle ||
!$userFromTitle->isRegistered() ) {
157 $elevated = $this->getAuthority()->isAllowed( 'editinterface' );
158 $elevatedText = $elevated ?
'by elevated ' : '';
159 $log = LoggerFactory
::getInstance( "security" );
161 "Unsafe JS/CSS/Json {$elevatedText}load - {user} loaded {title} with {ctype}",
163 'user' => $this->getUser()->getName(),
164 'title' => $title->getPrefixedDBkey(),
165 'ctype' => $contentType,
166 'elevated' => $elevated
169 throw new HttpError( 403, wfMessage( 'unregistered-user-config' ) );
173 // Don't allow loading non-protected pages as javascript.
174 // In the future, we may further restrict this to only CONTENT_MODEL_JAVASCRIPT
175 // in NS_MEDIAWIKI or NS_USER, as well as including other config types,
176 // but for now be more permissive. Allowing protected pages outside
177 // NS_USER and NS_MEDIAWIKI in particular should be considered a temporary
179 $pageRestrictions = $this->restrictionStore
->getRestrictions( $title, 'edit' );
181 $contentType === 'text/javascript' &&
182 !$title->isUserJsConfigPage() &&
183 !$title->inNamespace( NS_MEDIAWIKI
) &&
184 !in_array( 'sysop', $pageRestrictions ) &&
185 !in_array( 'editprotected', $pageRestrictions )
188 $log = LoggerFactory
::getInstance( "security" );
189 $log->info( "Blocked loading unprotected JS {title} for {user}",
191 'user' => $this->getUser()->getName(),
192 'title' => $title->getPrefixedDBkey(),
195 throw new HttpError( 403, wfMessage( 'unprotected-js' ) );
198 $response->header( 'Content-type: ' . $contentType . '; charset=UTF-8' );
200 $text = $this->getRawText();
202 // Don't return a 404 response for CSS or JavaScript;
203 // 404s aren't generally cached, and it would create
204 // extra hits when user CSS/JS are on and the user doesn't
206 if ( $text === false && $contentType === 'text/x-wiki' ) {
207 $response->statusHeader( 404 );
210 if ( !$this->getHookRunner()->onRawPageViewBeforeOutput( $this, $text ) ) {
211 wfDebug( __METHOD__
. ": RawPageViewBeforeOutput hook broke raw page output." );
220 * Get the text that should be returned, or false if the page or revision
223 * @return string|false
225 public function getRawText() {
227 $title = $this->getTitle();
228 $request = $this->getRequest();
230 // Get it from the DB
231 $rev = $this->revisionLookup
->getRevisionByTitle( $title, $this->getOldId() );
233 $lastMod = wfTimestamp( TS_RFC2822
, $rev->getTimestamp() );
234 $request->response()->header( "Last-modified: $lastMod" );
236 // Public-only due to cache headers
237 // Fetch specific slot if defined
238 $slot = $this->getRequest()->getText( 'slot' );
240 if ( $rev->hasSlot( $slot ) ) {
241 $content = $rev->getContent( $slot );
246 $content = $rev->getContent( SlotRecord
::MAIN
);
249 if ( $content === null ) {
250 // revision or slot was not found (or suppressed)
251 } elseif ( !$content instanceof TextContent
&& !method_exists( $content, 'getText' ) ) {
255 "Unsupported Media Type", "The requested page uses the content model `"
256 . $content->getModel() . "` which is not supported via this interface."
261 $section = $request->getIntOrNull( 'section' );
262 if ( $section !== null ) {
263 $content = $content->getSection( $section );
266 if ( $content !== null && $content !== false ) {
267 // section found (and section supported, e.g. not for JS, JSON, and CSS)
268 $text = $content->getText();
273 if ( $text !== false && $text !== '' && $request->getRawVal( 'templates' ) === 'expand' ) {
274 $text = $this->parser
->preprocess(
277 ParserOptions
::newFromContext( $this->getContext() )
285 * Get the ID of the revision that should be used to get the text.
289 public function getOldId() {
290 $oldId = $this->getRequest()->getInt( 'oldid' );
291 $rl = $this->revisionLookup
;
292 switch ( $this->getRequest()->getText( 'direction' ) ) {
294 # output next revision, or nothing if there isn't one
297 $oldRev = $rl->getRevisionById( $oldId );
299 $nextRev = $rl->getNextRevision( $oldRev );
302 $oldId = $nextRev ?
$nextRev->getId() : -1;
305 # output previous revision, or nothing if there isn't one
308 # get the current revision so we can get the penultimate one
309 $oldId = $this->getWikiPage()->getLatest();
311 $oldRev = $rl->getRevisionById( $oldId );
313 $prevRev = $rl->getPreviousRevision( $oldRev );
315 $oldId = $prevRev ?
$prevRev->getId() : -1;
322 // @phan-suppress-next-line PhanTypeMismatchReturnNullable RevisionRecord::getId does not return null here
327 * Get the content type to be used for the response
331 public function getContentType() {
332 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
333 $ctype = $this->getRequest()->getRawVal( 'ctype' );
335 if ( $ctype == '' ) {
336 // Legacy compatibility
337 $gen = $this->getRequest()->getRawVal( 'gen' );
338 if ( $gen == 'js' ) {
339 $ctype = 'text/javascript';
340 } elseif ( $gen == 'css' ) {
345 static $allowedCTypes = [
349 // FIXME: Should we still allow Zope editing? External editing feature was dropped
350 'application/x-zope-edit',
353 if ( $ctype == '' ||
!in_array( $ctype, $allowedCTypes ) ) {
354 $ctype = 'text/x-wiki';