MediaWiki master
RawAction.php
Go to the documentation of this file.
1<?php
15namespace MediaWiki\Actions;
16
32use Wikimedia\Timestamp\TimestampFormat as TS;
33
41
42 public function __construct(
43 Article $article,
45 private readonly Parser $parser,
46 private readonly PermissionManager $permissionManager,
47 private readonly RevisionLookup $revisionLookup,
48 private readonly RestrictionStore $restrictionStore,
49 private readonly UserFactory $userFactory,
50 ) {
51 parent::__construct( $article, $context );
52 }
53
55 public function getName() {
56 return 'raw';
57 }
58
60 public function requiresWrite() {
61 return false;
62 }
63
65 public function requiresUnblock() {
66 return false;
67 }
68
73 public function onView() {
74 $this->getOutput()->disable();
75 ContentSecurityPolicy::sendRestrictiveHeader();
76 $request = $this->getRequest();
77 $response = $request->response();
78 $config = $this->context->getConfig();
79
80 if ( $this->getOutput()->checkLastModified(
81 $this->getWikiPage()->getTouched()
82 ) ) {
83 // Client cache fresh and headers sent, nothing more to do.
84 return null;
85 }
86
87 $contentType = $this->getContentType();
88
89 $maxage = $request->getInt( 'maxage', $config->get( MainConfigNames::CdnMaxAge ) );
90 $smaxage = $request->getIntOrNull( 'smaxage' );
91 if ( $smaxage === null ) {
92 if (
93 $contentType === 'text/css' ||
94 $contentType === 'application/json' ||
95 $contentType === 'text/javascript'
96 ) {
97 // CSS/JSON/JS raw content has its own CDN max age configuration.
98 // Note: HTMLCacheUpdater::getUrls() includes action=raw for css/json/js
99 // pages, so if using the canonical url, this will get HTCP purges.
100 $smaxage = intval( $config->get( MainConfigNames::ForcedRawSMaxage ) );
101 } else {
102 // No CDN cache for anything else
103 $smaxage = 0;
104 }
105 }
106
107 // Set standard Vary headers so cache varies on cookies and such (T125283)
108 $response->header( $this->getOutput()->getVaryHeader() );
109
110 // Output may contain user-specific data;
111 // vary generated content for open sessions on private wikis
112 $privateCache = !$this->permissionManager->isEveryoneAllowed( 'read' ) &&
113 ( $smaxage === 0 || $request->getSession()->isPersistent() );
114 // Don't accidentally cache cookies if the user is registered (T55032)
115 $privateCache = $privateCache || $this->getUser()->isRegistered();
116 $mode = $privateCache ? 'private' : 'public';
117 $response->header(
118 'Cache-Control: ' . $mode . ', s-maxage=' . $smaxage . ', max-age=' . $maxage
119 );
120
121 // In the event of user JS, don't allow loading a user JS/CSS/Json
122 // subpage that has no registered user associated with, as
123 // someone could register the account and take control of the
124 // JS/CSS/Json page.
125 $title = $this->getTitle();
126 if ( $title->isUserConfigPage() && $contentType !== 'text/x-wiki' ) {
127 // not using getRootText() as we want this to work
128 // even if subpages are disabled.
129 $rootPage = strtok( $title->getText(), '/' );
130 $userFromTitle = $this->userFactory->newFromName( $rootPage, UserRigorOptions::RIGOR_USABLE );
131 if ( !$userFromTitle || !$userFromTitle->isRegistered() ) {
132 $elevated = $this->getAuthority()->isAllowed( 'editinterface' );
133 $elevatedText = $elevated ? 'by elevated ' : '';
134 $log = LoggerFactory::getInstance( "security" );
135 $log->warning(
136 "Unsafe JS/CSS/Json {$elevatedText}load - {user} loaded {title} with {ctype}",
137 [
138 'user' => $this->getUser()->getName(),
139 'title' => $title->getPrefixedDBkey(),
140 'ctype' => $contentType,
141 'elevated' => $elevated
142 ]
143 );
144 throw new HttpError( 403, wfMessage( 'unregistered-user-config' ) );
145 }
146 }
147
148 // Don't allow loading non-protected pages as javascript.
149 // In the future, we may further restrict this to only CONTENT_MODEL_JAVASCRIPT
150 // in NS_MEDIAWIKI or NS_USER, as well as including other config types,
151 // but for now be more permissive. Allowing protected pages outside
152 // NS_USER and NS_MEDIAWIKI in particular should be considered a temporary
153 // allowance.
154 $pageRestrictions = $this->restrictionStore->getRestrictions( $title, 'edit' );
155 if (
156 $contentType === 'text/javascript' &&
157 !$title->isUserJsConfigPage() &&
158 !$title->inNamespace( NS_MEDIAWIKI ) &&
159 !in_array( 'sysop', $pageRestrictions ) &&
160 !in_array( 'editprotected', $pageRestrictions )
161 ) {
162
163 $log = LoggerFactory::getInstance( "security" );
164 $log->info( "Blocked loading unprotected JS {title} for {user}",
165 [
166 'user' => $this->getUser()->getName(),
167 'title' => $title->getPrefixedDBkey(),
168 ]
169 );
170 throw new HttpError( 403, wfMessage( 'unprotected-js' ) );
171 }
172
173 $response->header( 'Content-type: ' . $contentType . '; charset=UTF-8' );
174
175 $text = $this->getRawText();
176
177 // Don't return a 404 response for CSS or JavaScript;
178 // 404s aren't generally cached, and it would create
179 // extra hits when user CSS/JS are on and the user doesn't
180 // have the pages.
181 if ( $text === false && $contentType === 'text/x-wiki' ) {
182 $response->statusHeader( 404 );
183 }
184
185 if ( !$this->getHookRunner()->onRawPageViewBeforeOutput( $this, $text ) ) {
186 wfDebug( __METHOD__ . ": RawPageViewBeforeOutput hook broke raw page output." );
187 }
188
189 echo $text;
190
191 return null;
192 }
193
200 public function getRawText() {
201 $text = false;
202 $title = $this->getTitle();
203 $request = $this->getRequest();
204
205 // Get it from the DB
206 $rev = $this->revisionLookup->getRevisionByTitle( $title, $this->getOldId() );
207 if ( $rev ) {
208 $lastMod = wfTimestamp( TS::RFC2822, $rev->getTimestamp() );
209 $request->response()->header( "Last-modified: $lastMod" );
210
211 // Public-only due to cache headers
212 // Fetch specific slot if defined
213 $slot = $this->getRequest()->getText( 'slot' );
214 if ( $slot ) {
215 if ( $rev->hasSlot( $slot ) ) {
216 $content = $rev->getContent( $slot );
217 } else {
218 $content = null;
219 }
220 } else {
221 $content = $rev->getContent( SlotRecord::MAIN );
222 }
223
224 if ( $content === null ) {
225 // revision or slot was not found (or suppressed)
226 } elseif ( !$content instanceof TextContent && !method_exists( $content, 'getText' ) ) {
227 // non-text content
229 415,
230 "Unsupported Media Type", "The requested page uses the content model `"
231 . $content->getModel() . "` which is not supported via this interface."
232 );
233 die();
234 } else {
235 // want a section?
236 $section = $request->getIntOrNull( 'section' );
237 if ( $section !== null ) {
238 $content = $content->getSection( $section );
239 }
240
241 if ( $content !== null && $content !== false ) {
242 // section found (and section supported, e.g. not for JS, JSON, and CSS)
243 $text = $content->getText();
244 }
245 }
246 }
247
248 if ( $text !== false && $text !== '' && $request->getRawVal( 'templates' ) === 'expand' ) {
249 $text = $this->parser->preprocess(
250 $text,
251 $title,
253 );
254 }
255
256 return $text;
257 }
258
264 public function getOldId() {
265 $oldId = $this->getRequest()->getInt( 'oldid' );
266 $rl = $this->revisionLookup;
267 switch ( $this->getRequest()->getText( 'direction' ) ) {
268 case 'next':
269 # output next revision, or nothing if there isn't one
270 $nextRev = null;
271 if ( $oldId ) {
272 $oldRev = $rl->getRevisionById( $oldId );
273 if ( $oldRev ) {
274 $nextRev = $rl->getNextRevision( $oldRev );
275 }
276 }
277 $oldId = $nextRev ? $nextRev->getId() : -1;
278 break;
279 case 'prev':
280 # output previous revision, or nothing if there isn't one
281 $prevRev = null;
282 if ( !$oldId ) {
283 # get the current revision so we can get the penultimate one
284 $oldId = $this->getWikiPage()->getLatest();
285 }
286 $oldRev = $rl->getRevisionById( $oldId );
287 if ( $oldRev ) {
288 $prevRev = $rl->getPreviousRevision( $oldRev );
289 }
290 $oldId = $prevRev ? $prevRev->getId() : -1;
291 break;
292 case 'cur':
293 $oldId = 0;
294 break;
295 }
296
297 // @phan-suppress-next-line PhanTypeMismatchReturnNullable RevisionRecord::getId does not return null here
298 return $oldId;
299 }
300
306 public function getContentType() {
307 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
308 $ctype = $this->getRequest()->getRawVal( 'ctype' );
309
310 if ( $ctype == '' ) {
311 // Legacy compatibility
312 $gen = $this->getRequest()->getRawVal( 'gen' );
313 if ( $gen == 'js' ) {
314 $ctype = 'text/javascript';
315 } elseif ( $gen == 'css' ) {
316 $ctype = 'text/css';
317 }
318 }
319
320 static $allowedCTypes = [
321 'text/x-wiki',
322 'text/javascript',
323 'text/css',
324 // FIXME: Should we still allow Zope editing? External editing feature was dropped
325 'application/x-zope-edit',
326 'application/json'
327 ];
328 if ( $ctype == '' || !in_array( $ctype, $allowedCTypes ) ) {
329 $ctype = 'text/x-wiki';
330 }
331
332 return $ctype;
333 }
334}
335
337class_alias( RawAction::class, 'RawAction' );
const NS_MEDIAWIKI
Definition Defines.php:59
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
getContext()
Get the IContextSource in use here.
Definition Action.php:119
getWikiPage()
Get a WikiPage object.
Definition Action.php:192
IContextSource null $context
IContextSource if specified; otherwise we'll use the Context from the Page.
Definition Action.php:66
getUser()
Shortcut to get the User being used for this instance.
Definition Action.php:153
getTitle()
Shortcut to get the Title object from the page.
Definition Action.php:213
getRequest()
Get the WebRequest being used for this instance.
Definition Action.php:133
getOutput()
Get the OutputPage being used for this instance.
Definition Action.php:143
getAuthority()
Shortcut to get the Authority executing this instance.
Definition Action.php:163
An action which just does something, without showing a form first.
A simple method to retrieve the plain source of an article, using "action=raw" in the GET request str...
Definition RawAction.php:40
requiresUnblock()
Whether this action can still be executed by a blocked user.Implementations of this methods must alwa...
Definition RawAction.php:65
getOldId()
Get the ID of the revision that should be used to get the text.
getName()
Return the name of the action this object responds to.1.17string Lowercase name
Definition RawAction.php:55
getContentType()
Get the content type to be used for the response.
getRawText()
Get the text that should be returned, or false if the page or revision was not found.
__construct(Article $article, IContextSource $context, private readonly Parser $parser, private readonly PermissionManager $permissionManager, private readonly RevisionLookup $revisionLookup, private readonly RestrictionStore $restrictionStore, private readonly UserFactory $userFactory,)
Definition RawAction.php:42
requiresWrite()
Indicates whether this action page write access to the wiki.Subclasses must override this method to r...
Definition RawAction.php:60
Content object implementation for representing flat text.
Show an error that looks like an HTTP server error.
Definition HttpError.php:23
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
const CdnMaxAge
Name constant for the CdnMaxAge setting, for use with Config::get()
const ForcedRawSMaxage
Name constant for the ForcedRawSMaxage setting, for use with Config::get()
Legacy class representing an editable page and handling UI for some page actions.
Definition Article.php:64
Set options of the Parser.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:135
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
Handle sending Content-Security-Policy headers.
Value object representing a content slot associated with a page revision.
Create User objects.
Interface for objects which can provide a MediaWiki context on request.
Service for looking up page revisions.
Shared interface for rigor levels when dealing with User methods.