MediaWiki REL1_27
RawAction.php
Go to the documentation of this file.
1<?php
30
38 public function getName() {
39 return 'raw';
40 }
41
42 public function requiresWrite() {
43 return false;
44 }
45
46 public function requiresUnblock() {
47 return false;
48 }
49
50 function onView() {
51 $this->getOutput()->disable();
52 $request = $this->getRequest();
53 $response = $request->response();
54 $config = $this->context->getConfig();
55
56 if ( !$request->checkUrlExtension() ) {
57 return;
58 }
59
60 if ( $this->getOutput()->checkLastModified( $this->page->getTouched() ) ) {
61 return; // Client cache fresh and headers sent, nothing more to do.
62 }
63
64 $gen = $request->getVal( 'gen' );
65 if ( $gen == 'css' || $gen == 'js' ) {
66 $this->gen = true;
67 }
68
69 $contentType = $this->getContentType();
70
71 $maxage = $request->getInt( 'maxage', $config->get( 'SquidMaxage' ) );
72 $smaxage = $request->getIntOrNull( 'smaxage' );
73 if ( $smaxage === null ) {
74 if ( $contentType == 'text/css' || $contentType == 'text/javascript' ) {
75 // CSS/JS raw content has its own CDN max age configuration.
76 // Note: Title::getCdnUrls() includes action=raw for css/js pages,
77 // so if using the canonical url, this will get HTCP purges.
78 $smaxage = intval( $config->get( 'ForcedRawSMaxage' ) );
79 } else {
80 // No CDN cache for anything else
81 $smaxage = 0;
82 }
83 }
84
85 // Set standard Vary headers so cache varies on cookies and such (T125283)
86 $response->header( $this->getOutput()->getVaryHeader() );
87 if ( $config->get( 'UseKeyHeader' ) ) {
88 $response->header( $this->getOutput()->getKeyHeader() );
89 }
90
91 // Output may contain user-specific data;
92 // vary generated content for open sessions on private wikis
93 $privateCache = !User::isEveryoneAllowed( 'read' ) &&
94 ( $smaxage == 0 || MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() );
95 // Don't accidentally cache cookies if user is logged in (T55032)
96 $privateCache = $privateCache || $this->getUser()->isLoggedIn();
97 $mode = $privateCache ? 'private' : 'public';
98 $response->header(
99 'Cache-Control: ' . $mode . ', s-maxage=' . $smaxage . ', max-age=' . $maxage
100 );
101
102 // In the event of user JS, don't allow loading a user JS/CSS/Json
103 // subpage that has no registered user associated with, as
104 // someone could register the account and take control of the
105 // JS/CSS/Json page.
106 $title = $this->getTitle();
107 if ( $title->isCssJsSubpage() && $contentType !== 'text/x-wiki' ) {
108 // not using getRootText() as we want this to work
109 // even if subpages are disabled.
110 $rootPage = strtok( $title->getText(), '/' );
111 $userFromTitle = User::newFromName( $rootPage, 'usable' );
112 if ( !$userFromTitle || $userFromTitle->getId() === 0 ) {
113 $log = LoggerFactory::getInstance( "security" );
114 $log->warning(
115 "Unsafe JS/CSS/Json load - {user} loaded {title} with {ctype}",
116 [
117 'user' => $this->getUser()->getName(),
118 'title' => $title->getPrefixedDBKey(),
119 'ctype' => $contentType,
120 ]
121 );
122 $msg = wfMessage( 'unregistered-user-config' );
123 throw new HttpError( 403, $msg );
124 }
125 }
126
127 // Don't allow loading non-protected pages as javascript.
128 // In future we may further restrict this to only CONTENT_MODEL_JAVASCRIPT
129 // in NS_MEDIAWIKI or NS_USER, as well as including other config types,
130 // but for now be more permissive. Allowing protected pages outside of
131 // NS_USER and NS_MEDIAWIKI in particular should be considered a temporary
132 // allowance.
133 if (
134 $contentType === 'text/javascript' &&
135 !$title->isJsSubpage() &&
136 !$title->inNamespace( NS_MEDIAWIKI ) &&
137 !in_array( 'sysop', $title->getRestrictions( 'edit' ) ) &&
138 !in_array( 'editprotected', $title->getRestrictions( 'edit' ) )
139 ) {
140
141 $log = LoggerFactory::getInstance( "security" );
142 $log->info( "Blocked loading unprotected JS {title} for {user}",
143 [
144 'user' => $this->getUser()->getName(),
145 'title' => $title->getPrefixedDBKey(),
146 ]
147 );
148 throw new HttpError( 403, wfMessage( 'unprotected-js' ) );
149 }
150
151 $response->header( 'Content-type: ' . $contentType . '; charset=UTF-8' );
152
153 $text = $this->getRawText();
154
155 // Don't return a 404 response for CSS or JavaScript;
156 // 404s aren't generally cached and it would create
157 // extra hits when user CSS/JS are on and the user doesn't
158 // have the pages.
159 if ( $text === false && $contentType == 'text/x-wiki' ) {
160 $response->statusHeader( 404 );
161 }
162
163 // Avoid PHP 7.1 warning of passing $this by reference
164 $rawAction = $this;
165 if ( !Hooks::run( 'RawPageViewBeforeOutput', [ &$rawAction, &$text ] ) ) {
166 wfDebug( __METHOD__ . ": RawPageViewBeforeOutput hook broke raw page output.\n" );
167 }
168
169 echo $text;
170 }
171
178 public function getRawText() {
180
181 $text = false;
182 $title = $this->getTitle();
183 $request = $this->getRequest();
184
185 // If it's a MediaWiki message we can just hit the message cache
186 if ( $request->getBool( 'usemsgcache' ) && $title->getNamespace() == NS_MEDIAWIKI ) {
187 // The first "true" is to use the database, the second is to use
188 // the content langue and the last one is to specify the message
189 // key already contains the language in it ("/de", etc.).
190 $text = MessageCache::singleton()->get( $title->getDBkey(), true, true, true );
191 // If the message doesn't exist, return a blank
192 if ( $text === false ) {
193 $text = '';
194 }
195 } else {
196 // Get it from the DB
198 if ( $rev ) {
199 $lastmod = wfTimestamp( TS_RFC2822, $rev->getTimestamp() );
200 $request->response()->header( "Last-modified: $lastmod" );
201
202 // Public-only due to cache headers
203 $content = $rev->getContent();
204
205 if ( $content === null ) {
206 // revision not found (or suppressed)
207 $text = false;
208 } elseif ( !$content instanceof TextContent ) {
209 // non-text content
210 wfHttpError( 415, "Unsupported Media Type", "The requested page uses the content model `"
211 . $content->getModel() . "` which is not supported via this interface." );
212 die();
213 } else {
214 // want a section?
215 $section = $request->getIntOrNull( 'section' );
216 if ( $section !== null ) {
217 $content = $content->getSection( $section );
218 }
219
220 if ( $content === null || $content === false ) {
221 // section not found (or section not supported, e.g. for JS and CSS)
222 $text = false;
223 } else {
224 $text = $content->getNativeData();
225 }
226 }
227 }
228 }
229
230 if ( $text !== false && $text !== '' && $request->getVal( 'templates' ) === 'expand' ) {
231 $text = $wgParser->preprocess(
232 $text,
233 $title,
235 );
236 }
237
238 return $text;
239 }
240
246 public function getOldId() {
247 $oldid = $this->getRequest()->getInt( 'oldid' );
248 switch ( $this->getRequest()->getText( 'direction' ) ) {
249 case 'next':
250 # output next revision, or nothing if there isn't one
251 $nextid = 0;
252 if ( $oldid ) {
253 $nextid = $this->getTitle()->getNextRevisionID( $oldid );
254 }
255 $oldid = $nextid ?: -1;
256 break;
257 case 'prev':
258 # output previous revision, or nothing if there isn't one
259 if ( !$oldid ) {
260 # get the current revision so we can get the penultimate one
261 $oldid = $this->page->getLatest();
262 }
263 $previd = $this->getTitle()->getPreviousRevisionID( $oldid );
264 $oldid = $previd ?: -1;
265 break;
266 case 'cur':
267 $oldid = 0;
268 break;
269 }
270
271 return $oldid;
272 }
273
279 public function getContentType() {
280 $ctype = $this->getRequest()->getVal( 'ctype' );
281
282 if ( $ctype == '' ) {
283 $gen = $this->getRequest()->getVal( 'gen' );
284 if ( $gen == 'js' ) {
285 $ctype = 'text/javascript';
286 } elseif ( $gen == 'css' ) {
287 $ctype = 'text/css';
288 }
289 }
290
291 $allowedCTypes = [ 'text/x-wiki', 'text/javascript', 'text/css', 'application/x-zope-edit' ];
292 if ( $ctype == '' || !in_array( $ctype, $allowedCTypes ) ) {
293 $ctype = 'text/x-wiki';
294 }
295
296 return $ctype;
297 }
298}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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.
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgParser
Definition Setup.php:809
getTitle()
Shortcut to get the Title object from the page.
Definition Action.php:246
getContext()
Get the IContextSource in use here.
Definition Action.php:178
getOutput()
Get the OutputPage being used for this instance.
Definition Action.php:207
getUser()
Shortcut to get the User being used for this instance.
Definition Action.php:217
getRequest()
Get the WebRequest being used for this instance.
Definition Action.php:197
getConfig()
Get the Config object.
An action which just does something, without showing a form first.
Show an error that looks like an HTTP server error.
Definition HttpError.php:30
PSR-3 logger instance factory.
static singleton()
Get the signleton instance of this class.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
A simple method to retrieve the plain source of an article, using "action=raw" in the GET request str...
Definition RawAction.php:37
getContentType()
Get the content type to use for the response.
getRawText()
Get the text that should be returned, or false if the page or revision was not found.
getName()
Return the name of the action this object responds to.
Definition RawAction.php:38
requiresWrite()
Whether this action requires the wiki not to be locked.
Definition RawAction.php:42
onView()
Show something on GET request.
Definition RawAction.php:50
requiresUnblock()
Whether this action can still be executed by a blocked user.
Definition RawAction.php:46
getOldId()
Get the ID of the revision that should used to get the text.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition Revision.php:117
Content object implementation for representing flat text.
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
const NS_MEDIAWIKI
Definition Defines.php:78
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition hooks.txt:1040
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:944
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2530
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk page
Definition hooks.txt:2388
this hook is for auditing only $response
Definition hooks.txt:765
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition hooks.txt:2727
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1597
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37