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