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