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