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