Debian Codegraph @

includes/actions/RawAction.php

raw symbols SCIP
1 <?php
2 /**
3 * Raw page text accessor
4 *
5 * Copyright © 2004 Gabriel Wicke <[email protected]>
6 * http://wikidev.net/
7 *
8 * Based on HistoryAction and SpecialExport
9 *
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.
14 *
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.
19 *
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
24 *
25 * @author Gabriel Wicke <[email protected]>
26 * @file
27 */
28
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\Parser\ParserOptions;
35 use MediaWiki\Permissions\PermissionManager;
36 use MediaWiki\Permissions\RestrictionStore;
37 use MediaWiki\Revision\RevisionLookup;
38 use MediaWiki\Revision\SlotRecord;
39 use MediaWiki\Session\SessionManager;
40 use MediaWiki\User\UserFactory;
41 use MediaWiki\User\UserRigorOptions;
42
43 /**
44 * A simple method to retrieve the plain source of an article,
45 * using "action=raw" in the GET request string.
46 *
47 * @ingroup Actions
48 */
49 class RawAction extends FormlessAction {
50
51 private Parser $parser;
52 private PermissionManager $permissionManager;
53 private RevisionLookup $revisionLookup;
54 private RestrictionStore $restrictionStore;
55 private UserFactory $userFactory;
56
57 /**
58 * @param Article $article
59 * @param IContextSource $context
60 * @param Parser $parser
61 * @param PermissionManager $permissionManager
62 * @param RevisionLookup $revisionLookup
63 * @param RestrictionStore $restrictionStore
64 * @param UserFactory $userFactory
65 */
66 public function __construct(
67 Article $article,
68 IContextSource $context,
69 Parser $parser,
70 PermissionManager $permissionManager,
71 RevisionLookup $revisionLookup,
72 RestrictionStore $restrictionStore,
73 UserFactory $userFactory
74 ) {
75 parent::__construct( $article, $context );
76 $this->parser = $parser;
77 $this->permissionManager = $permissionManager;
78 $this->revisionLookup = $revisionLookup;
79 $this->restrictionStore = $restrictionStore;
80 $this->userFactory = $userFactory;
81 }
82
83 /** @inheritDoc */
84 public function getName() {
85 return 'raw';
86 }
87
88 public function requiresWrite() {
89 return false;
90 }
91
92 public function requiresUnblock() {
93 return false;
94 }
95
96 /**
97 * @suppress SecurityCheck-XSS Non html mime type
98 * @return string|null
99 */
100 public function onView() {
101 $this->getOutput()->disable();
102 $request = $this->getRequest();
103 $response = $request->response();
104 $config = $this->context->getConfig();
105
106 if ( $this->getOutput()->checkLastModified(
107 $this->getWikiPage()->getTouched()
108 ) ) {
109 // Client cache fresh and headers sent, nothing more to do.
110 return null;
111 }
112
113 $contentType = $this->getContentType();
114
115 $maxage = $request->getInt( 'maxage', $config->get( MainConfigNames::CdnMaxAge ) );
116 $smaxage = $request->getIntOrNull( 'smaxage' );
117 if ( $smaxage === null ) {
118 if (
119 $contentType === 'text/css' ||
120 $contentType === 'application/json' ||
121 $contentType === 'text/javascript'
122 ) {
123 // CSS/JSON/JS raw content has its own CDN max age configuration.
124 // Note: HTMLCacheUpdater::getUrls() includes action=raw for css/json/js
125 // pages, so if using the canonical url, this will get HTCP purges.
126 $smaxage = intval( $config->get( MainConfigNames::ForcedRawSMaxage ) );
127 } else {
128 // No CDN cache for anything else
129 $smaxage = 0;
130 }
131 }
132
133 // Set standard Vary headers so cache varies on cookies and such (T125283)
134 $response->header( $this->getOutput()->getVaryHeader() );
135
136 // Output may contain user-specific data;
137 // vary generated content for open sessions on private wikis
138 $privateCache = !$this->permissionManager->isEveryoneAllowed( 'read' ) &&
139 ( $smaxage === 0 || SessionManager::getGlobalSession()->isPersistent() );
140 // Don't accidentally cache cookies if the user is registered (T55032)
141 $privateCache = $privateCache || $this->getUser()->isRegistered();
142 $mode = $privateCache ? 'private' : 'public';
143 $response->header(
144 'Cache-Control: ' . $mode . ', s-maxage=' . $smaxage . ', max-age=' . $maxage
145 );
146
147 // In the event of user JS, don't allow loading a user JS/CSS/Json
148 // subpage that has no registered user associated with, as
149 // someone could register the account and take control of the
150 // JS/CSS/Json page.
151 $title = $this->getTitle();
152 if ( $title->isUserConfigPage() && $contentType !== 'text/x-wiki' ) {
153 // not using getRootText() as we want this to work
154 // even if subpages are disabled.
155 $rootPage = strtok( $title->getText(), '/' );
156 $userFromTitle = $this->userFactory->newFromName( $rootPage, UserRigorOptions::RIGOR_USABLE );
157 if ( !$userFromTitle || !$userFromTitle->isRegistered() ) {
158 $elevated = $this->getAuthority()->isAllowed( 'editinterface' );
159 $elevatedText = $elevated ? 'by elevated ' : '';
160 $log = LoggerFactory::getInstance( "security" );
161 $log->warning(
162 "Unsafe JS/CSS/Json {$elevatedText}load - {user} loaded {title} with {ctype}",
163 [
164 'user' => $this->getUser()->getName(),
165 'title' => $title->getPrefixedDBkey(),
166 'ctype' => $contentType,
167 'elevated' => $elevated
168 ]
169 );
170 throw new HttpError( 403, wfMessage( 'unregistered-user-config' ) );
171 }
172 }
173
174 // Don't allow loading non-protected pages as javascript.
175 // In the future, we may further restrict this to only CONTENT_MODEL_JAVASCRIPT
176 // in NS_MEDIAWIKI or NS_USER, as well as including other config types,
177 // but for now be more permissive. Allowing protected pages outside
178 // NS_USER and NS_MEDIAWIKI in particular should be considered a temporary
179 // allowance.
180 $pageRestrictions = $this->restrictionStore->getRestrictions( $title, 'edit' );
181 if (
182 $contentType === 'text/javascript' &&
183 !$title->isUserJsConfigPage() &&
184 !$title->inNamespace( NS_MEDIAWIKI ) &&
185 !in_array( 'sysop', $pageRestrictions ) &&
186 !in_array( 'editprotected', $pageRestrictions )
187 ) {
188
189 $log = LoggerFactory::getInstance( "security" );
190 $log->info( "Blocked loading unprotected JS {title} for {user}",
191 [
192 'user' => $this->getUser()->getName(),
193 'title' => $title->getPrefixedDBkey(),
194 ]
195 );
196 throw new HttpError( 403, wfMessage( 'unprotected-js' ) );
197 }
198
199 // Content-Type: text/javascript should only work when the following are true:
200 // page is in User subpage or Mediawiki namespace
201 // page title ends in .js or .vue
202 // page content type is CONTENT_MODEL_JAVASCRIPT or CONTENT_MODEL_VUE
203 // currntly only logging to determine how many pages would be impacted by this change
204 if ( $contentType === 'text/javascript' ) {
205 if ( !( $title->isSiteJsConfigPage() || $title->isUserJsConfigPage() ) ) {
206 $log = LoggerFactory::getInstance( "security" );
207 $log->info( "Did not block loading unprotected JS {title} for {user} with more restrictions",
208 [
209 'user' => $this->getUser()->getName(),
210 'title' => $title->getPrefixedDBkey(),
211 ]
212 );
213 }
214 }
215
216 $response->header( 'Content-type: ' . $contentType . '; charset=UTF-8' );
217
218 $text = $this->getRawText();
219
220 // Don't return a 404 response for CSS or JavaScript;
221 // 404s aren't generally cached, and it would create
222 // extra hits when user CSS/JS are on and the user doesn't
223 // have the pages.
224 if ( $text === false && $contentType === 'text/x-wiki' ) {
225 $response->statusHeader( 404 );
226 }
227
228 if ( !$this->getHookRunner()->onRawPageViewBeforeOutput( $this, $text ) ) {
229 wfDebug( __METHOD__ . ": RawPageViewBeforeOutput hook broke raw page output." );
230 }
231
232 echo $text;
233
234 return null;
235 }
236
237 /**
238 * Get the text that should be returned, or false if the page or revision
239 * was not found.
240 *
241 * @return string|false
242 */
243 public function getRawText() {
244 $text = false;
245 $title = $this->getTitle();
246 $request = $this->getRequest();
247
248 // Get it from the DB
249 $rev = $this->revisionLookup->getRevisionByTitle( $title, $this->getOldId() );
250 if ( $rev ) {
251 $lastMod = wfTimestamp( TS_RFC2822, $rev->getTimestamp() );
252 $request->response()->header( "Last-modified: $lastMod" );
253
254 // Public-only due to cache headers
255 // Fetch specific slot if defined
256 $slot = $this->getRequest()->getText( 'slot' );
257 if ( $slot ) {
258 if ( $rev->hasSlot( $slot ) ) {
259 $content = $rev->getContent( $slot );
260 } else {
261 $content = null;
262 }
263 } else {
264 $content = $rev->getContent( SlotRecord::MAIN );
265 }
266
267 if ( $content === null ) {
268 // revision or slot was not found (or suppressed)
269 } elseif ( !$content instanceof TextContent && !method_exists( $content, 'getText' ) ) {
270 // non-text content
271 wfHttpError(
272 415,
273 "Unsupported Media Type", "The requested page uses the content model `"
274 . $content->getModel() . "` which is not supported via this interface."
275 );
276 die();
277 } else {
278 // want a section?
279 $section = $request->getIntOrNull( 'section' );
280 if ( $section !== null ) {
281 $content = $content->getSection( $section );
282 }
283
284 if ( $content !== null && $content !== false ) {
285 // section found (and section supported, e.g. not for JS, JSON, and CSS)
286 $text = $content->getText();
287 }
288 }
289 }
290
291 if ( $text !== false && $text !== '' && $request->getRawVal( 'templates' ) === 'expand' ) {
292 $text = $this->parser->preprocess(
293 $text,
294 $title,
295 ParserOptions::newFromContext( $this->getContext() )
296 );
297 }
298
299 return $text;
300 }
301
302 /**
303 * Get the ID of the revision that should be used to get the text.
304 *
305 * @return int
306 */
307 public function getOldId() {
308 $oldId = $this->getRequest()->getInt( 'oldid' );
309 $rl = $this->revisionLookup;
310 switch ( $this->getRequest()->getText( 'direction' ) ) {
311 case 'next':
312 # output next revision, or nothing if there isn't one
313 $nextRev = null;
314 if ( $oldId ) {
315 $oldRev = $rl->getRevisionById( $oldId );
316 if ( $oldRev ) {
317 $nextRev = $rl->getNextRevision( $oldRev );
318 }
319 }
320 $oldId = $nextRev ? $nextRev->getId() : -1;
321 break;
322 case 'prev':
323 # output previous revision, or nothing if there isn't one
324 $prevRev = null;
325 if ( !$oldId ) {
326 # get the current revision so we can get the penultimate one
327 $oldId = $this->getWikiPage()->getLatest();
328 }
329 $oldRev = $rl->getRevisionById( $oldId );
330 if ( $oldRev ) {
331 $prevRev = $rl->getPreviousRevision( $oldRev );
332 }
333 $oldId = $prevRev ? $prevRev->getId() : -1;
334 break;
335 case 'cur':
336 $oldId = 0;
337 break;
338 }
339
340 // @phan-suppress-next-line PhanTypeMismatchReturnNullable RevisionRecord::getId does not return null here
341 return $oldId;
342 }
343
344 /**
345 * Get the content type to be used for the response
346 *
347 * @return string
348 */
349 public function getContentType() {
350 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
351 $ctype = $this->getRequest()->getRawVal( 'ctype' );
352
353 if ( $ctype == '' ) {
354 // Legacy compatibility
355 $gen = $this->getRequest()->getRawVal( 'gen' );
356 if ( $gen == 'js' ) {
357 $ctype = 'text/javascript';
358 } elseif ( $gen == 'css' ) {
359 $ctype = 'text/css';
360 }
361 }
362
363 static $allowedCTypes = [
364 'text/x-wiki',
365 'text/javascript',
366 'text/css',
367 // FIXME: Should we still allow Zope editing? External editing feature was dropped
368 'application/x-zope-edit',
369 'application/json'
370 ];
371 if ( $ctype == '' || !in_array( $ctype, $allowedCTypes ) ) {
372 $ctype = 'text/x-wiki';
373 }
374
375 return $ctype;
376 }
377 }