Start unpicking r85288 (magic __get() accessor for RequestContext). Instead, bring...
[lhc/web/wiklou.git] / includes / Wiki.php
1 <?php
2 /**
3 * MediaWiki is the to-be base class for this whole project
4 *
5 * @internal documentation reviewed 15 Mar 2010
6 */
7 class MediaWiki extends ContextSource {
8
9 public function request( WebRequest $x = null ){
10 return wfSetVar( $this->getRequest(), $x );
11 }
12
13 public function output( OutputPage $x = null ){
14 return wfSetVar( $this->getOutput(), $x );
15 }
16
17 public function __construct( RequestContext $context ){
18 $this->setContext( $context );
19 $this->getContext()->setTitle( $this->parseTitle() );
20 }
21
22 /**
23 * Parse $request to get the Title object
24 *
25 * @return Title object to be $wgTitle
26 */
27 private function parseTitle() {
28 global $wgContLang;
29
30 $curid = $this->getRequest()->getInt( 'curid' );
31 $title = $this->getRequest()->getVal( 'title' );
32
33 if ( $this->getRequest()->getCheck( 'search' ) ) {
34 // Compatibility with old search URLs which didn't use Special:Search
35 // Just check for presence here, so blank requests still
36 // show the search page when using ugly URLs (bug 8054).
37 $ret = SpecialPage::getTitleFor( 'Search' );
38 } elseif ( $curid ) {
39 // URLs like this are generated by RC, because rc_title isn't always accurate
40 $ret = Title::newFromID( $curid );
41 } elseif ( $title == '' && $this->getAction() != 'delete' ) {
42 $ret = Title::newMainPage();
43 } else {
44 $ret = Title::newFromURL( $title );
45 // check variant links so that interwiki links don't have to worry
46 // about the possible different language variants
47 if ( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 ){
48 $wgContLang->findVariantLink( $title, $ret );
49 }
50 }
51 // For non-special titles, check for implicit titles
52 if ( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
53 // We can have urls with just ?diff=,?oldid= or even just ?diff=
54 $oldid = $this->getRequest()->getInt( 'oldid' );
55 $oldid = $oldid ? $oldid : $this->getRequest()->getInt( 'diff' );
56 // Allow oldid to override a changed or missing title
57 if ( $oldid ) {
58 $rev = Revision::newFromId( $oldid );
59 $ret = $rev ? $rev->getTitle() : $ret;
60 }
61 }
62
63 if( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ){
64 $ret = new BadTitle;
65 }
66 return $ret;
67 }
68
69 /**
70 * Get the Title object that we'll be acting on, as specified in the WebRequest
71 * @return Title
72 */
73 public function getTitle(){
74 if( $this->getContext()->getTitle() === null ){
75 $this->getContext()->setTitle( $this->parseTitle() );
76 }
77 return $this->getContext()->getTitle();
78 }
79
80 /**
81 * Performs the request.
82 * - bad titles
83 * - read restriction
84 * - local interwiki redirects
85 * - redirect loop
86 * - special pages
87 * - normal pages
88 *
89 * @return Article object
90 */
91 public function performRequest() {
92 global $wgServer, $wgUsePathInfo;
93
94 wfProfileIn( __METHOD__ );
95
96 if ( $this->getRequest()->getVal( 'printable' ) === 'yes' ) {
97 $this->getOutput()->setPrintable();
98 }
99
100 wfRunHooks( 'BeforeInitialize', array(
101 $this->getTitle(),
102 null,
103 $this->getOutput(),
104 $this->getUser(),
105 $this->getRequest(),
106 $this
107 ) );
108
109 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
110 if ( $this->getTitle() instanceof BadTitle ) {
111 throw new ErrorPageError( 'badtitle', 'badtitletext' );
112 // If the user is not logged in, the Namespace:title of the article must be in
113 // the Read array in order for the user to see it. (We have to check here to
114 // catch special pages etc. We check again in Article::view())
115 } else if ( !$this->getTitle()->userCanRead() ) {
116 $this->getOutput()->loginToUse();
117 // Interwiki redirects
118 } else if ( $this->getTitle()->getInterwiki() != '' ) {
119 $rdfrom = $this->getRequest()->getVal( 'rdfrom' );
120 if ( $rdfrom ) {
121 $url = $this->getTitle()->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
122 } else {
123 $query = $this->getRequest()->getValues();
124 unset( $query['title'] );
125 $url = $this->getTitle()->getFullURL( $query );
126 }
127 // Check for a redirect loop
128 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url ) && $this->getTitle()->isLocal() ) {
129 // 301 so google et al report the target as the actual url.
130 $this->getOutput()->redirect( $url, 301 );
131 } else {
132 $this->getContext()->setTitle( new BadTitle );
133 wfProfileOut( __METHOD__ );
134 throw new ErrorPageError( 'badtitle', 'badtitletext' );
135 }
136 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
137 } else if ( $this->getRequest()->getVal( 'action', 'view' ) == 'view' && !$this->getRequest()->wasPosted()
138 && ( $this->getRequest()->getVal( 'title' ) === null || $this->getTitle()->getPrefixedDBKey() != $this->getRequest()->getVal( 'title' ) )
139 && !count( array_diff( array_keys( $this->getRequest()->getValues() ), array( 'action', 'title' ) ) ) )
140 {
141 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
142 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $this->getTitle()->getDBkey() );
143 if ( $name ) {
144 $this->getContext()->setTitle( SpecialPage::getTitleFor( $name, $subpage ) );
145 }
146 }
147 $targetUrl = $this->getTitle()->getFullURL();
148 // Redirect to canonical url, make it a 301 to allow caching
149 if ( $targetUrl == $this->getRequest()->getFullRequestURL() ) {
150 $message = "Redirect loop detected!\n\n" .
151 "This means the wiki got confused about what page was " .
152 "requested; this sometimes happens when moving a wiki " .
153 "to a new server or changing the server configuration.\n\n";
154
155 if ( $wgUsePathInfo ) {
156 $message .= "The wiki is trying to interpret the page " .
157 "title from the URL path portion (PATH_INFO), which " .
158 "sometimes fails depending on the web server. Try " .
159 "setting \"\$wgUsePathInfo = false;\" in your " .
160 "LocalSettings.php, or check that \$wgArticlePath " .
161 "is correct.";
162 } else {
163 $message .= "Your web server was detected as possibly not " .
164 "supporting URL path components (PATH_INFO) correctly; " .
165 "check your LocalSettings.php for a customized " .
166 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
167 "to true.";
168 }
169 wfHttpError( 500, "Internal error", $message );
170 } else {
171 $this->getOutput()->setSquidMaxage( 1200 );
172 $this->getOutput()->redirect( $targetUrl, '301' );
173 }
174 // Special pages
175 } else if ( NS_SPECIAL == $this->getTitle()->getNamespace() ) {
176 // actions that need to be made when we have a special pages
177 SpecialPageFactory::executePath( $this->getTitle(), $this->getContext() );
178 } else {
179 // ...otherwise treat it as an article view. The article
180 // may be a redirect to another article or URL.
181 $article = $this->initializeArticle();
182 if ( is_object( $article ) ) {
183 $this->performAction( $article );
184 wfProfileOut( __METHOD__ );
185 return $article;
186 } elseif ( is_string( $article ) ) {
187 $this->getOutput()->redirect( $article );
188 } else {
189 wfProfileOut( __METHOD__ );
190 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
191 }
192 }
193 wfProfileOut( __METHOD__ );
194 }
195
196 /**
197 * Create an Article object of the appropriate class for the given page.
198 *
199 * @deprecated in 1.19; use Article::newFromTitle() instead
200 * @param $title Title
201 * @param $context RequestContext
202 * @return Article object
203 */
204 public static function articleFromTitle( $title, RequestContext $context ) {
205 return Article::newFromTitle( $title, $context );
206 }
207
208 /**
209 * Returns the action that will be executed, not necesserly the one passed
210 * passed through the "action" parameter. Actions disabled in
211 * $wgDisabledActions will be replaced by "nosuchaction"
212 *
213 * @return String: action
214 */
215 public function getAction() {
216 global $wgDisabledActions;
217
218 $action = $this->getRequest()->getVal( 'action', 'view' );
219
220 // Check for disabled actions
221 if ( in_array( $action, $wgDisabledActions ) ) {
222 return 'nosuchaction';
223 }
224
225 // Workaround for bug #20966: inability of IE to provide an action dependent
226 // on which submit button is clicked.
227 if ( $action === 'historysubmit' ) {
228 if ( $this->getRequest()->getBool( 'revisiondelete' ) ) {
229 return 'revisiondelete';
230 } else {
231 return 'view';
232 }
233 } elseif ( $action == 'editredlink' ) {
234 return 'edit';
235 }
236
237 return $action;
238 }
239
240 /**
241 * Initialize the main Article object for "standard" actions (view, etc)
242 * Create an Article object for the page, following redirects if needed.
243 *
244 * @return mixed an Article, or a string to redirect to another URL
245 */
246 private function initializeArticle() {
247 global $wgDisableHardRedirects;
248
249 wfProfileIn( __METHOD__ );
250
251 $action = $this->getRequest()->getVal( 'action', 'view' );
252 $article = Article::newFromTitle( $this->getTitle(), $this->getContext() );
253 // NS_MEDIAWIKI has no redirects.
254 // It is also used for CSS/JS, so performance matters here...
255 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI ) {
256 wfProfileOut( __METHOD__ );
257 return $article;
258 }
259 // Namespace might change when using redirects
260 // Check for redirects ...
261 $file = ( $this->getTitle()->getNamespace() == NS_FILE ) ? $article->getFile() : null;
262 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
263 && !$this->getRequest()->getVal( 'oldid' ) && // ... and are not old revisions
264 !$this->getRequest()->getVal( 'diff' ) && // ... and not when showing diff
265 $this->getRequest()->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
266 // ... and the article is not a non-redirect image page with associated file
267 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
268 {
269 // Give extensions a change to ignore/handle redirects as needed
270 $ignoreRedirect = $target = false;
271
272 wfRunHooks( 'InitializeArticleMaybeRedirect',
273 array( $this->getTitle(), $this->getRequest(), &$ignoreRedirect, &$target, &$article ) );
274
275 // Follow redirects only for... redirects.
276 // If $target is set, then a hook wanted to redirect.
277 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
278 // Is the target already set by an extension?
279 $target = $target ? $target : $article->followRedirect();
280 if ( is_string( $target ) ) {
281 if ( !$wgDisableHardRedirects ) {
282 // we'll need to redirect
283 wfProfileOut( __METHOD__ );
284 return $target;
285 }
286 }
287 if ( is_object( $target ) ) {
288 // Rewrite environment to redirected article
289 $rarticle = Article::newFromTitle( $target, $this->getContext() );
290 $rarticle->loadPageData();
291 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
292 $rarticle->setRedirectedFrom( $this->getTitle() );
293 $article = $rarticle;
294 $this->getContext()->setTitle( $target );
295 }
296 }
297 } else {
298 $this->getContext()->setTitle( $article->getTitle() );
299 }
300 }
301 wfProfileOut( __METHOD__ );
302 return $article;
303 }
304
305 /**
306 * Cleaning up request by doing deferred updates, DB transaction, and the output
307 */
308 public function finalCleanup() {
309 wfProfileIn( __METHOD__ );
310 // Now commit any transactions, so that unreported errors after
311 // output() don't roll back the whole DB transaction
312 $factory = wfGetLBFactory();
313 $factory->commitMasterChanges();
314 // Output everything!
315 $this->getOutput()->output();
316 // Do any deferred jobs
317 wfDoUpdates( 'commit' );
318
319 $this->doJobs();
320 wfProfileOut( __METHOD__ );
321 }
322
323 /**
324 * Do a job from the job queue
325 */
326 private function doJobs() {
327 global $wgJobRunRate;
328
329 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
330 return;
331 }
332 if ( $wgJobRunRate < 1 ) {
333 $max = mt_getrandmax();
334 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
335 return;
336 }
337 $n = 1;
338 } else {
339 $n = intval( $wgJobRunRate );
340 }
341
342 // Close the session so that jobs don't access the current session
343 $this->shutdownLBFactory();
344 session_write_close();
345
346 while ( $n-- && false != ( $job = Job::pop() ) ) {
347 $output = $job->toString() . "\n";
348 $t = -wfTime();
349 $success = $job->run();
350 $t += wfTime();
351 $t = round( $t * 1000 );
352 if ( !$success ) {
353 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
354 } else {
355 $output .= "Success, Time: $t ms\n";
356 }
357 wfDebugLog( 'jobqueue', $output );
358 }
359 }
360
361 /**
362 * Ends this task peacefully
363 */
364 public function restInPeace() {
365 MessageCache::logMessages();
366 wfLogProfilingData();
367 $this->shutdownLBFactory();
368 wfDebug( "Request ended normally\n" );
369 }
370
371 /**
372 * Commit pending master changes, shutdown the current loadbalancer
373 * factory and destroys the factory instance.
374 */
375 private function shutdownLBFactory() {
376 // Commit and close up!
377 $factory = LBFactory::singleton();
378 $factory->commitMasterChanges();
379 $factory->shutdown();
380 LBFactory::destroyInstance();
381 }
382
383 /**
384 * Perform one of the "standard" actions
385 *
386 * @param $article Article
387 */
388 private function performAction( $article ) {
389 global $wgSquidMaxage, $wgUseExternalEditor;
390
391 wfProfileIn( __METHOD__ );
392
393 if ( !wfRunHooks( 'MediaWikiPerformAction', array(
394 $this->getOutput(), $article, $this->getTitle(),
395 $this->getUser(), $this->getRequest(), $this ) ) )
396 {
397 wfProfileOut( __METHOD__ );
398 return;
399 }
400
401 $act = $this->getAction();
402
403 $action = Action::factory( $act, $article );
404 if( $action instanceof Action ){
405 $action->show();
406 wfProfileOut( __METHOD__ );
407 return;
408 }
409
410 switch( $act ) {
411 case 'view':
412 $this->getOutput()->setSquidMaxage( $wgSquidMaxage );
413 $article->view();
414 break;
415 case 'raw': // includes JS/CSS
416 wfProfileIn( __METHOD__ . '-raw' );
417 $raw = new RawPage( $article );
418 $raw->view();
419 wfProfileOut( __METHOD__ . '-raw' );
420 break;
421 case 'delete':
422 case 'revert':
423 case 'rollback':
424 case 'protect':
425 case 'unprotect':
426 case 'info':
427 case 'markpatrolled':
428 case 'render':
429 case 'deletetrackback':
430 $article->$act();
431 break;
432 case 'submit':
433 if ( session_id() == '' ) {
434 // Send a cookie so anons get talk message notifications
435 wfSetupSession();
436 }
437 // Continue...
438 case 'edit':
439 if ( wfRunHooks( 'CustomEditor', array( $article, $this->getUser() ) ) ) {
440 $internal = $this->getRequest()->getVal( 'internaledit' );
441 $external = $this->getRequest()->getVal( 'externaledit' );
442 $section = $this->getRequest()->getVal( 'section' );
443 $oldid = $this->getRequest()->getVal( 'oldid' );
444 if ( !$wgUseExternalEditor || $act == 'submit' || $internal ||
445 $section || $oldid || ( !$this->getUser()->getOption( 'externaleditor' ) && !$external ) ) {
446 $editor = new EditPage( $article );
447 $editor->submit();
448 } elseif ( $wgUseExternalEditor && ( $external || $this->getUser()->getOption( 'externaleditor' ) ) ) {
449 $mode = $this->getRequest()->getVal( 'mode' );
450 $extedit = new ExternalEdit( $article, $mode );
451 $extedit->edit();
452 }
453 }
454 break;
455 case 'history':
456 if ( $this->getRequest()->getFullRequestURL() == $this->getTitle()->getInternalURL( 'action=history' ) ) {
457 $this->getOutput()->setSquidMaxage( $wgSquidMaxage );
458 }
459 $history = new HistoryPage( $article );
460 $history->history();
461 break;
462 case 'revisiondelete':
463 // For show/hide submission from history page
464 $special = SpecialPageFactory::getPage( 'Revisiondelete' );
465 $special->execute( '' );
466 break;
467 default:
468 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
469 $this->getOutput()->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
470 }
471 }
472 wfProfileOut( __METHOD__ );
473 }
474 }