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