bug 25517 Assignment in conditions should be avoided/ http://www.mediawiki.org/wiki...
[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 {
8 var $params = array();
9
10 /** Constructor */
11 function __construct() {}
12
13 /**
14 * Stores key/value pairs to circumvent global variables
15 * Note that keys are case-insensitive!
16 *
17 * @param $key String: key to store
18 * @param $value Mixed: value to put for the key
19 */
20 function setVal( $key, &$value ) {
21 $key = strtolower( $key );
22 $this->params[$key] =& $value;
23 }
24
25 /**
26 * Retrieves key/value pairs to circumvent global variables
27 * Note that keys are case-insensitive!
28 *
29 * @param $key String: key to get
30 * @param $default string default value, defaults to empty string
31 * @return $default Mixed: default value if if the key doesn't exist
32 */
33 function getVal( $key, $default = '' ) {
34 $key = strtolower( $key );
35 if( isset( $this->params[$key] ) ) {
36 return $this->params[$key];
37 }
38 return $default;
39 }
40
41 /**
42 * Initialization of ... everything
43 * Performs the request too
44 *
45 * @param $title Title ($wgTitle)
46 * @param $article Article
47 * @param $output OutputPage
48 * @param $user User
49 * @param $request WebRequest
50 */
51 function performRequestForTitle( &$title, &$article, &$output, &$user, $request ) {
52 wfProfileIn( __METHOD__ );
53
54 $output->setTitle( $title );
55
56 wfRunHooks( 'BeforeInitialize', array( &$title, &$article, &$output, &$user, $request, $this ) );
57
58 if( !$this->preliminaryChecks( $title, $output, $request ) ) {
59 wfProfileOut( __METHOD__ );
60 return;
61 }
62 // Call handleSpecialCases() to deal with all special requests...
63 if( !$this->handleSpecialCases( $title, $output, $request ) ) {
64 // ...otherwise treat it as an article view. The article
65 // may be a redirect to another article or URL.
66 $new_article = $this->initializeArticle( $title, $output, $request );
67 if( is_object( $new_article ) ) {
68 $article = $new_article;
69 $this->performAction( $output, $article, $title, $user, $request );
70 } elseif( is_string( $new_article ) ) {
71 $output->redirect( $new_article );
72 } else {
73 wfProfileOut( __METHOD__ );
74 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
75 }
76 }
77 wfProfileOut( __METHOD__ );
78 }
79
80 /**
81 * Check if the maximum lag of database slaves is higher that $maxLag, and
82 * if it's the case, output an error message
83 *
84 * @param $maxLag int: maximum lag allowed for the request, as supplied by
85 * the client
86 * @return bool true if the request can continue
87 */
88 function checkMaxLag( $maxLag ) {
89 list( $host, $lag ) = wfGetLB()->getMaxLag();
90 if( $lag > $maxLag ) {
91 wfMaxlagError( $host, $lag, $maxLag );
92 return false;
93 } else {
94 return true;
95 }
96 }
97
98 /**
99 * Checks some initial queries
100 * Note that $title here is *not* a Title object, but a string!
101 *
102 * @param $title String
103 * @param $action String
104 * @return Title object to be $wgTitle
105 */
106 function checkInitialQueries( $title, $action ) {
107 global $wgOut, $wgRequest, $wgContLang;
108 if( $wgRequest->getVal( 'printable' ) === 'yes' ) {
109 $wgOut->setPrintable();
110 }
111 $curid = $wgRequest->getInt( 'curid' );
112 if( $curid ) {
113 // URLs like this are generated by RC, because rc_title isn't always accurate
114 $ret = Title::newFromID( $curid );
115 } elseif( $title == '' && $action != 'delete' ) {
116 $ret = Title::newMainPage();
117 } else {
118 $ret = Title::newFromURL( $title );
119 // check variant links so that interwiki links don't have to worry
120 // about the possible different language variants
121 if( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 )
122 $wgContLang->findVariantLink( $title, $ret );
123 }
124 // For non-special titles, check for implicit titles
125 if( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
126 // We can have urls with just ?diff=,?oldid= or even just ?diff=
127 $oldid = $wgRequest->getInt( 'oldid' );
128 $oldid = $oldid ? $oldid : $wgRequest->getInt( 'diff' );
129 // Allow oldid to override a changed or missing title
130 if( $oldid ) {
131 $rev = Revision::newFromId( $oldid );
132 $ret = $rev ? $rev->getTitle() : $ret;
133 }
134 }
135 return $ret;
136 }
137
138 /**
139 * Checks for search query and anon-cannot-read case
140 *
141 * @param $title Title
142 * @param $output OutputPage
143 * @param $request WebRequest
144 * @return boolean true if successful
145 */
146 function preliminaryChecks( &$title, &$output, $request ) {
147 if( $request->getCheck( 'search' ) ) {
148 // Compatibility with old search URLs which didn't use Special:Search
149 // Just check for presence here, so blank requests still
150 // show the search page when using ugly URLs (bug 8054).
151
152 // Do this above the read whitelist check for security...
153 $title = SpecialPage::getTitleFor( 'Search' );
154 }
155 // If the user is not logged in, the Namespace:title of the article must be in
156 // the Read array in order for the user to see it. (We have to check here to
157 // catch special pages etc. We check again in Article::view())
158 if( !is_null( $title ) && !$title->userCanRead() ) {
159 global $wgDeferredUpdateList;
160 $output->loginToUse();
161 $this->finalCleanup( $wgDeferredUpdateList, $output );
162 $output->disable();
163 return false;
164 }
165 return true;
166 }
167
168 /**
169 * Initialize some special cases:
170 * - bad titles
171 * - local interwiki redirects
172 * - redirect loop
173 * - special pages
174 *
175 * @param $title Title
176 * @param $output OutputPage
177 * @param $request WebRequest
178 * @return bool true if the request is already executed
179 */
180 function handleSpecialCases( &$title, &$output, $request ) {
181 wfProfileIn( __METHOD__ );
182
183 $action = $this->getVal( 'Action' );
184
185 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
186 if( is_null($title) || ( ( $title->getDBkey() == '' ) && ( $title->getInterwiki() == '' ) ) ) {
187 $title = SpecialPage::getTitleFor( 'Badtitle' );
188 $output->setTitle( $title ); // bug 21456
189 // Die now before we mess up $wgArticle and the skin stops working
190 throw new ErrorPageError( 'badtitle', 'badtitletext' );
191
192 // Interwiki redirects
193 } else if( $title->getInterwiki() != '' ) {
194 $rdfrom = $request->getVal( 'rdfrom' );
195 if( $rdfrom ) {
196 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
197 } else {
198 $query = $request->getValues();
199 unset( $query['title'] );
200 $url = $title->getFullURL( $query );
201 }
202 /* Check for a redirect loop */
203 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
204 $output->redirect( $url );
205 } else {
206 $title = SpecialPage::getTitleFor( 'Badtitle' );
207 $output->setTitle( $title ); // bug 21456
208 wfProfileOut( __METHOD__ );
209 throw new ErrorPageError( 'badtitle', 'badtitletext' );
210 }
211 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
212 } else if ( $action == 'view' && !$request->wasPosted()
213 && ( !$request->getVal( 'title' ) || $title->getPrefixedDBKey() != $request->getText( 'title' ) )
214 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
215 {
216 $targetUrl = $title->getFullURL();
217 // Redirect to canonical url, make it a 301 to allow caching
218 if( $targetUrl == $request->getFullRequestURL() ) {
219 $message = "Redirect loop detected!\n\n" .
220 "This means the wiki got confused about what page was " .
221 "requested; this sometimes happens when moving a wiki " .
222 "to a new server or changing the server configuration.\n\n";
223
224 if( $this->getVal( 'UsePathInfo' ) ) {
225 $message .= "The wiki is trying to interpret the page " .
226 "title from the URL path portion (PATH_INFO), which " .
227 "sometimes fails depending on the web server. Try " .
228 "setting \"\$wgUsePathInfo = false;\" in your " .
229 "LocalSettings.php, or check that \$wgArticlePath " .
230 "is correct.";
231 } else {
232 $message .= "Your web server was detected as possibly not " .
233 "supporting URL path components (PATH_INFO) correctly; " .
234 "check your LocalSettings.php for a customized " .
235 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
236 "to true.";
237 }
238 wfHttpError( 500, "Internal error", $message );
239 wfProfileOut( __METHOD__ );
240 return false;
241 } else {
242 $output->setSquidMaxage( 1200 );
243 $output->redirect( $targetUrl, '301' );
244 }
245 // Special pages
246 } else if( NS_SPECIAL == $title->getNamespace() ) {
247 /* actions that need to be made when we have a special pages */
248 SpecialPage::executePath( $title );
249 } else {
250 /* No match to special cases */
251 wfProfileOut( __METHOD__ );
252 return false;
253 }
254 /* Did match a special case */
255 wfProfileOut( __METHOD__ );
256 return true;
257 }
258
259 /**
260 * Create an Article object of the appropriate class for the given page.
261 *
262 * @param $title Title
263 * @return Article object
264 */
265 static function articleFromTitle( &$title ) {
266 if( NS_MEDIA == $title->getNamespace() ) {
267 // FIXME: where should this go?
268 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
269 }
270
271 $article = null;
272 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
273 if( $article ) {
274 return $article;
275 }
276
277 switch( $title->getNamespace() ) {
278 case NS_FILE:
279 return new ImagePage( $title );
280 case NS_CATEGORY:
281 return new CategoryPage( $title );
282 default:
283 return new Article( $title );
284 }
285 }
286
287 /**
288 * Initialize the object to be known as $wgArticle for "standard" actions
289 * Create an Article object for the page, following redirects if needed.
290 *
291 * @param $title Title ($wgTitle)
292 * @param $output OutputPage ($wgOut)
293 * @param $request WebRequest ($wgRequest)
294 * @return mixed an Article, or a string to redirect to another URL
295 */
296 function initializeArticle( &$title, &$output, $request ) {
297 wfProfileIn( __METHOD__ );
298
299 $action = $this->getVal( 'action', 'view' );
300 $article = self::articleFromTitle( $title );
301 // NS_MEDIAWIKI has no redirects.
302 // It is also used for CSS/JS, so performance matters here...
303 if( $title->getNamespace() == NS_MEDIAWIKI ) {
304 wfProfileOut( __METHOD__ );
305 return $article;
306 }
307 // Namespace might change when using redirects
308 // Check for redirects ...
309 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
310 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
311 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
312 !$request->getVal( 'diff' ) && // ... and not when showing diff
313 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
314 // ... and the article is not a non-redirect image page with associated file
315 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
316 {
317 // Give extensions a change to ignore/handle redirects as needed
318 $ignoreRedirect = $target = false;
319
320 $dbr = wfGetDB( DB_SLAVE );
321 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
322
323 wfRunHooks( 'InitializeArticleMaybeRedirect',
324 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
325
326 // Follow redirects only for... redirects.
327 // If $target is set, then a hook wanted to redirect.
328 if( !$ignoreRedirect && ($target || $article->isRedirect()) ) {
329 // Is the target already set by an extension?
330 $target = $target ? $target : $article->followRedirect();
331 if( is_string( $target ) ) {
332 if( !$this->getVal( 'DisableHardRedirects' ) ) {
333 // we'll need to redirect
334 wfProfileOut( __METHOD__ );
335 return $target;
336 }
337 }
338 if( is_object($target) ) {
339 // Rewrite environment to redirected article
340 $rarticle = self::articleFromTitle( $target );
341 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
342 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
343 $rarticle->setRedirectedFrom( $title );
344 $article = $rarticle;
345 $title = $target;
346 $output->setTitle( $title );
347 }
348 }
349 } else {
350 $title = $article->getTitle();
351 }
352 }
353 wfProfileOut( __METHOD__ );
354 return $article;
355 }
356
357 /**
358 * Cleaning up request by doing:
359 ** deferred updates, DB transaction, and the output
360 *
361 * @param $deferredUpdates array of updates to do
362 * @param $output OutputPage
363 */
364 function finalCleanup( &$deferredUpdates, &$output ) {
365 wfProfileIn( __METHOD__ );
366 // Now commit any transactions, so that unreported errors after
367 // output() don't roll back the whole DB transaction
368 $factory = wfGetLBFactory();
369 $factory->commitMasterChanges();
370 // Output everything!
371 $output->output();
372 // Do any deferred jobs
373 $this->doUpdates( $deferredUpdates );
374 // Close the session so that jobs don't access the current session
375 session_write_close();
376 $this->doJobs();
377 wfProfileOut( __METHOD__ );
378 }
379
380 /**
381 * Deferred updates aren't really deferred anymore. It's important to report
382 * errors to the user, and that means doing this before OutputPage::output().
383 * Note that for page saves, the client will wait until the script exits
384 * anyway before following the redirect.
385 *
386 * @param $updates array of objects that hold an update to do
387 */
388 function doUpdates( &$updates ) {
389 wfProfileIn( __METHOD__ );
390 /* No need to get master connections in case of empty updates array */
391 if (!$updates) {
392 wfProfileOut( __METHOD__ );
393 return;
394 }
395
396 $dbw = wfGetDB( DB_MASTER );
397 foreach( $updates as $up ) {
398 $up->doUpdate();
399
400 // Commit after every update to prevent lock contention
401 if( $dbw->trxLevel() ) {
402 $dbw->commit();
403 }
404 }
405 wfProfileOut( __METHOD__ );
406 }
407
408 /**
409 * Do a job from the job queue
410 */
411 function doJobs() {
412 $jobRunRate = $this->getVal( 'JobRunRate' );
413
414 if( $jobRunRate <= 0 || wfReadOnly() ) {
415 return;
416 }
417 if( $jobRunRate < 1 ) {
418 $max = mt_getrandmax();
419 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
420 return;
421 }
422 $n = 1;
423 } else {
424 $n = intval( $jobRunRate );
425 }
426
427 while ( $n-- && false != ( $job = Job::pop() ) ) {
428 $output = $job->toString() . "\n";
429 $t = -wfTime();
430 $success = $job->run();
431 $t += wfTime();
432 $t = round( $t*1000 );
433 if( !$success ) {
434 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
435 } else {
436 $output .= "Success, Time: $t ms\n";
437 }
438 wfDebugLog( 'jobqueue', $output );
439 }
440 }
441
442 /**
443 * Ends this task peacefully
444 */
445 function restInPeace() {
446 MessageCache::logMessages();
447 wfLogProfilingData();
448 // Commit and close up!
449 $factory = wfGetLBFactory();
450 $factory->commitMasterChanges();
451 $factory->shutdown();
452 wfDebug( "Request ended normally\n" );
453 }
454
455 /**
456 * Perform one of the "standard" actions
457 *
458 * @param $output OutputPage
459 * @param $article Article
460 * @param $title Title
461 * @param $user User
462 * @param $request WebRequest
463 */
464 function performAction( &$output, &$article, &$title, &$user, &$request ) {
465 wfProfileIn( __METHOD__ );
466
467 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
468 wfProfileOut( __METHOD__ );
469 return;
470 }
471
472 $action = $this->getVal( 'Action' );
473 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
474 /* No such action; this will switch to the default case */
475 $action = 'nosuchaction';
476 }
477
478 // Workaround for bug #20966: inability of IE to provide an action dependent
479 // on which submit button is clicked.
480 if ( $action === 'historysubmit' ) {
481 if ( $request->getBool( 'revisiondelete' ) ) {
482 $action = 'revisiondelete';
483 } elseif ( $request->getBool( 'revisionmove' ) ) {
484 $action = 'revisionmove';
485 } else {
486 $action = 'view';
487 }
488 }
489
490 switch( $action ) {
491 case 'view':
492 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
493 $article->view();
494 break;
495 case 'raw': // includes JS/CSS
496 wfProfileIn( __METHOD__.'-raw' );
497 $raw = new RawPage( $article );
498 $raw->view();
499 wfProfileOut( __METHOD__.'-raw' );
500 break;
501 case 'watch':
502 case 'unwatch':
503 case 'delete':
504 case 'revert':
505 case 'rollback':
506 case 'protect':
507 case 'unprotect':
508 case 'info':
509 case 'markpatrolled':
510 case 'render':
511 case 'deletetrackback':
512 case 'purge':
513 $article->$action();
514 break;
515 case 'print':
516 $article->view();
517 break;
518 case 'dublincore':
519 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
520 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
521 } else {
522 $rdf = new DublinCoreRdf( $article );
523 $rdf->show();
524 }
525 break;
526 case 'creativecommons':
527 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
528 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
529 } else {
530 $rdf = new CreativeCommonsRdf( $article );
531 $rdf->show();
532 }
533 break;
534 case 'credits':
535 Credits::showPage( $article );
536 break;
537 case 'submit':
538 if( session_id() == '' ) {
539 /* Send a cookie so anons get talk message notifications */
540 wfSetupSession();
541 }
542 /* Continue... */
543 case 'edit':
544 case 'editredlink':
545 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
546 $internal = $request->getVal( 'internaledit' );
547 $external = $request->getVal( 'externaledit' );
548 $section = $request->getVal( 'section' );
549 $oldid = $request->getVal( 'oldid' );
550 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
551 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
552 $editor = new EditPage( $article );
553 $editor->submit();
554 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
555 $mode = $request->getVal( 'mode' );
556 $extedit = new ExternalEdit( $article, $mode );
557 $extedit->edit();
558 }
559 }
560 break;
561 case 'history':
562 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
563 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
564 }
565 $history = new HistoryPage( $article );
566 $history->history();
567 break;
568 case 'revisiondelete':
569 // For show/hide submission from history page
570 $special = SpecialPage::getPage( 'Revisiondelete' );
571 $special->execute( '' );
572 break;
573 case 'revisionmove':
574 // For revision move submission from history page
575 $special = SpecialPage::getPage( 'RevisionMove' );
576 $special->execute( '' );
577 break;
578 default:
579 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
580 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
581 }
582 }
583 wfProfileOut( __METHOD__ );
584
585 }
586
587 }