Swap else if for elseif
[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
9 /**
10 * TODO: fold $output, etc, into this
11 * @var RequestContext
12 */
13 private $context;
14
15 public function request( WebRequest $x = null ){
16 $this->context->setRequest( $x );
17 return $this->context->getRequest();
18 }
19
20 public function output( OutputPage $x = null ){
21 $this->context->setOutput( $x );
22 return $this->context->getOutput();
23 }
24
25 public function __construct( RequestContext $context ){
26 $this->context = $context;
27 $this->context->setTitle( $this->parseTitle() );
28 }
29
30 /**
31 * Parse $request to get the Title object
32 *
33 * @return Title object to be $wgTitle
34 */
35 private function parseTitle() {
36 global $wgContLang;
37
38 $request = $this->context->getRequest();
39 $curid = $request->getInt( 'curid' );
40 $title = $request->getVal( 'title' );
41
42 if ( $request->getCheck( 'search' ) ) {
43 // Compatibility with old search URLs which didn't use Special:Search
44 // Just check for presence here, so blank requests still
45 // show the search page when using ugly URLs (bug 8054).
46 $ret = SpecialPage::getTitleFor( 'Search' );
47 } elseif ( $curid ) {
48 // URLs like this are generated by RC, because rc_title isn't always accurate
49 $ret = Title::newFromID( $curid );
50 } elseif ( $title == '' && $this->getAction() != 'delete' ) {
51 $ret = Title::newMainPage();
52 } else {
53 $ret = Title::newFromURL( $title );
54 // check variant links so that interwiki links don't have to worry
55 // about the possible different language variants
56 if ( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 ){
57 $wgContLang->findVariantLink( $title, $ret );
58 }
59 }
60 // For non-special titles, check for implicit titles
61 if ( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
62 // We can have urls with just ?diff=,?oldid= or even just ?diff=
63 $oldid = $request->getInt( 'oldid' );
64 $oldid = $oldid ? $oldid : $request->getInt( 'diff' );
65 // Allow oldid to override a changed or missing title
66 if ( $oldid ) {
67 $rev = Revision::newFromId( $oldid );
68 $ret = $rev ? $rev->getTitle() : $ret;
69 }
70 }
71
72 if( $ret === null || ( $ret->getDBkey() == '' && $ret->getInterwiki() == '' ) ){
73 $ret = new BadTitle;
74 }
75 return $ret;
76 }
77
78 /**
79 * Get the Title object that we'll be acting on, as specified in the WebRequest
80 * @return Title
81 */
82 public function getTitle(){
83 if( $this->context->getTitle() === null ){
84 $this->context->setTitle( $this->parseTitle() );
85 }
86 return $this->context->getTitle();
87 }
88
89 /**
90 * Performs the request.
91 * - bad titles
92 * - read restriction
93 * - local interwiki redirects
94 * - redirect loop
95 * - special pages
96 * - normal pages
97 *
98 * @return Article object
99 */
100 public function performRequest() {
101 global $wgServer, $wgUsePathInfo;
102
103 wfProfileIn( __METHOD__ );
104
105 $request = $this->context->getRequest();
106 $title = $this->context->getTitle();
107 $output = $this->context->getOutput();
108 $user = $this->context->getUser();
109
110 if ( $request->getVal( 'printable' ) === 'yes' ) {
111 $output->setPrintable();
112 }
113
114 wfRunHooks( 'BeforeInitialize', array(
115 &$title,
116 null,
117 &$output,
118 &$user,
119 $request,
120 $this
121 ) );
122
123 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
124 if ( $title instanceof BadTitle ) {
125 throw new ErrorPageError( 'badtitle', 'badtitletext' );
126 // If the user is not logged in, the Namespace:title of the article must be in
127 // the Read array in order for the user to see it. (We have to check here to
128 // catch special pages etc. We check again in Article::view())
129 } elseif ( !$title->userCanRead() ) {
130 $output->loginToUse();
131 // Interwiki redirects
132 } elseif ( $title->getInterwiki() != '' ) {
133 $rdfrom = $request->getVal( 'rdfrom' );
134 if ( $rdfrom ) {
135 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
136 } else {
137 $query = $request->getValues();
138 unset( $query['title'] );
139 $url = $title->getFullURL( $query );
140 }
141 // Check for a redirect loop
142 if ( !preg_match( '/^' . preg_quote( $wgServer, '/' ) . '/', $url ) && $title->isLocal() ) {
143 // 301 so google et al report the target as the actual url.
144 $output->redirect( $url, 301 );
145 } else {
146 $this->context->setTitle( new BadTitle );
147 wfProfileOut( __METHOD__ );
148 throw new ErrorPageError( 'badtitle', 'badtitletext' );
149 }
150 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
151 } elseif ( $request->getVal( 'action', 'view' ) == 'view' && !$request->wasPosted()
152 && ( $request->getVal( 'title' ) === null || $title->getPrefixedDBKey() != $request->getVal( 'title' ) )
153 && !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
154 {
155 if ( $title->getNamespace() == NS_SPECIAL ) {
156 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
157 if ( $name ) {
158 $title = SpecialPage::getTitleFor( $name, $subpage );
159 }
160 }
161 $targetUrl = $title->getFullURL();
162 // Redirect to canonical url, make it a 301 to allow caching
163 if ( $targetUrl == $request->getFullRequestURL() ) {
164 $message = "Redirect loop detected!\n\n" .
165 "This means the wiki got confused about what page was " .
166 "requested; this sometimes happens when moving a wiki " .
167 "to a new server or changing the server configuration.\n\n";
168
169 if ( $wgUsePathInfo ) {
170 $message .= "The wiki is trying to interpret the page " .
171 "title from the URL path portion (PATH_INFO), which " .
172 "sometimes fails depending on the web server. Try " .
173 "setting \"\$wgUsePathInfo = false;\" in your " .
174 "LocalSettings.php, or check that \$wgArticlePath " .
175 "is correct.";
176 } else {
177 $message .= "Your web server was detected as possibly not " .
178 "supporting URL path components (PATH_INFO) correctly; " .
179 "check your LocalSettings.php for a customized " .
180 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
181 "to true.";
182 }
183 wfHttpError( 500, "Internal error", $message );
184 } else {
185 $output->setSquidMaxage( 1200 );
186 $output->redirect( $targetUrl, '301' );
187 }
188 // Special pages
189 } elseif ( NS_SPECIAL == $title->getNamespace() ) {
190 // actions that need to be made when we have a special pages
191 SpecialPageFactory::executePath( $title, $this->context );
192 } else {
193 // ...otherwise treat it as an article view. The article
194 // may be a redirect to another article or URL.
195 $article = $this->initializeArticle();
196 if ( is_object( $article ) ) {
197 $this->performAction( $article );
198 wfProfileOut( __METHOD__ );
199 return $article;
200 } elseif ( is_string( $article ) ) {
201 $output->redirect( $article );
202 } else {
203 wfProfileOut( __METHOD__ );
204 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
205 }
206 }
207 wfProfileOut( __METHOD__ );
208 }
209
210 /**
211 * Create an Article object of the appropriate class for the given page.
212 *
213 * @deprecated in 1.19; use Article::newFromTitle() instead
214 * @param $title Title
215 * @param $context RequestContext
216 * @return Article object
217 */
218 public static function articleFromTitle( $title, RequestContext $context ) {
219 return Article::newFromTitle( $title, $context );
220 }
221
222 /**
223 * Returns the action that will be executed, not necesserly the one passed
224 * passed through the "action" parameter. Actions disabled in
225 * $wgDisabledActions will be replaced by "nosuchaction"
226 *
227 * @return String: action
228 */
229 public function getAction() {
230 global $wgDisabledActions;
231
232 $request = $this->context->getRequest();
233 $action = $request->getVal( 'action', 'view' );
234
235 // Check for disabled actions
236 if ( in_array( $action, $wgDisabledActions ) ) {
237 return 'nosuchaction';
238 }
239
240 // Workaround for bug #20966: inability of IE to provide an action dependent
241 // on which submit button is clicked.
242 if ( $action === 'historysubmit' ) {
243 if ( $request->getBool( 'revisiondelete' ) ) {
244 return 'revisiondelete';
245 } else {
246 return 'view';
247 }
248 } elseif ( $action == 'editredlink' ) {
249 return 'edit';
250 }
251
252 return $action;
253 }
254
255 /**
256 * Initialize the main Article object for "standard" actions (view, etc)
257 * Create an Article object for the page, following redirects if needed.
258 *
259 * @return mixed an Article, or a string to redirect to another URL
260 */
261 private function initializeArticle() {
262 global $wgDisableHardRedirects;
263
264 wfProfileIn( __METHOD__ );
265
266 $request = $this->context->getRequest();
267 $title = $this->context->getTitle();
268
269 $action = $request->getVal( 'action', 'view' );
270 $article = Article::newFromTitle( $title, $this->context );
271 // NS_MEDIAWIKI has no redirects.
272 // It is also used for CSS/JS, so performance matters here...
273 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
274 wfProfileOut( __METHOD__ );
275 return $article;
276 }
277 // Namespace might change when using redirects
278 // Check for redirects ...
279 $file = ( $title->getNamespace() == NS_FILE ) ? $article->getFile() : null;
280 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
281 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
282 !$request->getVal( 'diff' ) && // ... and not when showing diff
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
290 wfRunHooks( 'InitializeArticleMaybeRedirect',
291 array( &$title, &$request, &$ignoreRedirect, &$target, &$article ) );
292
293 // Follow redirects only for... redirects.
294 // If $target is set, then a hook wanted to redirect.
295 if ( !$ignoreRedirect && ( $target || $article->isRedirect() ) ) {
296 // Is the target already set by an extension?
297 $target = $target ? $target : $article->followRedirect();
298 if ( is_string( $target ) ) {
299 if ( !$wgDisableHardRedirects ) {
300 // we'll need to redirect
301 wfProfileOut( __METHOD__ );
302 return $target;
303 }
304 }
305 if ( is_object( $target ) ) {
306 // Rewrite environment to redirected article
307 $rarticle = Article::newFromTitle( $target, $this->context );
308 $rarticle->loadPageData();
309 if ( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
310 $rarticle->setRedirectedFrom( $title );
311 $article = $rarticle;
312 $this->context->setTitle( $target );
313 }
314 }
315 } else {
316 $this->context->setTitle( $article->getTitle() );
317 }
318 }
319 wfProfileOut( __METHOD__ );
320 return $article;
321 }
322
323 /**
324 * Cleaning up request by doing deferred updates, DB transaction, and the output
325 */
326 public function finalCleanup() {
327 wfProfileIn( __METHOD__ );
328 // Now commit any transactions, so that unreported errors after
329 // output() don't roll back the whole DB transaction
330 $factory = wfGetLBFactory();
331 $factory->commitMasterChanges();
332 // Output everything!
333 $this->context->getOutput()->output();
334 // Do any deferred jobs
335 wfDoUpdates( 'commit' );
336
337 $this->doJobs();
338 wfProfileOut( __METHOD__ );
339 }
340
341 /**
342 * Do a job from the job queue
343 */
344 private function doJobs() {
345 global $wgJobRunRate;
346
347 if ( $wgJobRunRate <= 0 || wfReadOnly() ) {
348 return;
349 }
350 if ( $wgJobRunRate < 1 ) {
351 $max = mt_getrandmax();
352 if ( mt_rand( 0, $max ) > $max * $wgJobRunRate ) {
353 return;
354 }
355 $n = 1;
356 } else {
357 $n = intval( $wgJobRunRate );
358 }
359
360 // Close the session so that jobs don't access the current session
361 $this->shutdownLBFactory();
362 session_write_close();
363
364 while ( $n-- && false != ( $job = Job::pop() ) ) {
365 $output = $job->toString() . "\n";
366 $t = -wfTime();
367 $success = $job->run();
368 $t += wfTime();
369 $t = round( $t * 1000 );
370 if ( !$success ) {
371 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
372 } else {
373 $output .= "Success, Time: $t ms\n";
374 }
375 wfDebugLog( 'jobqueue', $output );
376 }
377 }
378
379 /**
380 * Ends this task peacefully
381 */
382 public function restInPeace() {
383 MessageCache::logMessages();
384 wfLogProfilingData();
385 $this->shutdownLBFactory();
386 wfDebug( "Request ended normally\n" );
387 }
388
389 /**
390 * Commit pending master changes, shutdown the current loadbalancer
391 * factory and destroys the factory instance.
392 */
393 private function shutdownLBFactory() {
394 // Commit and close up!
395 $factory = LBFactory::singleton();
396 $factory->commitMasterChanges();
397 $factory->shutdown();
398 LBFactory::destroyInstance();
399 }
400
401 /**
402 * Perform one of the "standard" actions
403 *
404 * @param $article Article
405 */
406 private function performAction( $article ) {
407 global $wgSquidMaxage, $wgUseExternalEditor;
408
409 wfProfileIn( __METHOD__ );
410
411 $request = $this->context->getRequest();
412 $output = $this->context->getOutput();
413 $title = $this->context->getTitle();
414 $user = $this->context->getUser();
415
416 if ( !wfRunHooks( 'MediaWikiPerformAction', array(
417 $output, $article, $title,
418 $user, $request, $this ) ) )
419 {
420 wfProfileOut( __METHOD__ );
421 return;
422 }
423
424 $act = $this->getAction();
425
426 $action = Action::factory( $act, $article );
427 if( $action instanceof Action ){
428 $action->show();
429 wfProfileOut( __METHOD__ );
430 return;
431 }
432
433 switch( $act ) {
434 case 'view':
435 $output->setSquidMaxage( $wgSquidMaxage );
436 $article->view();
437 break;
438 case 'raw': // includes JS/CSS
439 wfProfileIn( __METHOD__ . '-raw' );
440 $raw = new RawPage( $article );
441 $raw->view();
442 wfProfileOut( __METHOD__ . '-raw' );
443 break;
444 case 'delete':
445 case 'revert':
446 case 'rollback':
447 case 'protect':
448 case 'unprotect':
449 case 'info':
450 case 'render':
451 $article->$act();
452 break;
453 case 'submit':
454 if ( session_id() == '' ) {
455 // Send a cookie so anons get talk message notifications
456 wfSetupSession();
457 }
458 // Continue...
459 case 'edit':
460 if ( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
461 $internal = $request->getVal( 'internaledit' );
462 $external = $request->getVal( 'externaledit' );
463 $section = $request->getVal( 'section' );
464 $oldid = $request->getVal( 'oldid' );
465 if ( !$wgUseExternalEditor || $act == 'submit' || $internal ||
466 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
467 $editor = new EditPage( $article );
468 $editor->submit();
469 } elseif ( $wgUseExternalEditor && ( $external || $user->getOption( 'externaleditor' ) ) ) {
470 $mode = $request->getVal( 'mode' );
471 $extedit = new ExternalEdit( $article, $mode );
472 $extedit->edit();
473 }
474 }
475 break;
476 case 'history':
477 if ( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
478 $output->setSquidMaxage( $wgSquidMaxage );
479 }
480 $history = new HistoryPage( $article );
481 $history->history();
482 break;
483 default:
484 if ( wfRunHooks( 'UnknownAction', array( $act, $article ) ) ) {
485 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
486 }
487 }
488 wfProfileOut( __METHOD__ );
489 }
490 }