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