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