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