* Using $wgContLang->ucfirst() instead of $wgLang->ucfirst() in loadFromFile() and...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**#@+
27 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 /**#@-*/
40
41 /**
42 * Constructor and clear the article
43 * @param mixed &$title
44 */
45 function Article( &$title ) {
46 $this->mTitle =& $title;
47 $this->clear();
48 }
49
50 /**
51 * get the title object of the article
52 * @public
53 */
54 function getTitle() {
55 return $this->mTitle;
56 }
57
58 /**
59 * Clear the object
60 * @private
61 */
62 function clear() {
63 $this->mDataLoaded = false;
64 $this->mContentLoaded = false;
65
66 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
67 $this->mRedirectedFrom = $this->mUserText =
68 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
69 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
70 $this->mTouched = '19700101000000';
71 $this->mForUpdate = false;
72 $this->mIsRedirect = false;
73 $this->mRevIdFetched = 0;
74 }
75
76 /**
77 * Note that getContent/loadContent may follow redirects if
78 * not told otherwise, and so may cause a change to mTitle.
79 *
80 * @param $noredir
81 * @return Return the text of this revision
82 */
83 function getContent( $noredir ) {
84 global $wgRequest, $wgUser, $wgOut;
85
86 # Get variables from query string :P
87 $action = $wgRequest->getText( 'action', 'view' );
88 $section = $wgRequest->getText( 'section' );
89 $preload = $wgRequest->getText( 'preload' );
90
91 $fname = 'Article::getContent';
92 wfProfileIn( $fname );
93
94 if ( 0 == $this->getID() ) {
95 if ( 'edit' == $action ) {
96 wfProfileOut( $fname );
97
98 # If requested, preload some text.
99 $text=$this->getPreloadedText($preload);
100
101 # We used to put MediaWiki:Newarticletext here if
102 # $text was empty at this point.
103 # This is now shown above the edit box instead.
104 return $text;
105 }
106 wfProfileOut( $fname );
107 $wgOut->setRobotpolicy( 'noindex,nofollow' );
108
109 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
110 return "<div class='noarticletext'>$ret</div>";
111 } else {
112 $this->loadContent( $noredir );
113 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
114 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
115 $wgUser->isIP($this->mTitle->getText()) &&
116 $action=='view'
117 ) {
118 wfProfileOut( $fname );
119 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
120 } else {
121 if($action=='edit') {
122 if($section!='') {
123 if($section=='new') {
124 wfProfileOut( $fname );
125 $text=$this->getPreloadedText($preload);
126 return $text;
127 }
128
129 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
130 # comments to be stripped as well)
131 $rv=$this->getSection($this->mContent,$section);
132 wfProfileOut( $fname );
133 return $rv;
134 }
135 }
136 wfProfileOut( $fname );
137 return $this->mContent;
138 }
139 }
140 }
141
142 /**
143 This function accepts a title string as parameter
144 ($preload). If this string is non-empty, it attempts
145 to fetch the current revision text.
146 */
147 function getPreloadedText($preload) {
148 if($preload) {
149 $preloadTitle=Title::newFromText($preload);
150 if(isset($preloadTitle) && $preloadTitle->userCanRead()) {
151 $rev=Revision::newFromTitle($preloadTitle);
152 if($rev) {
153 return $rev->getText();
154 }
155 }
156 }
157 return '';
158 }
159
160 /**
161 * This function returns the text of a section, specified by a number ($section).
162 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
163 * the first section before any such heading (section 0).
164 *
165 * If a section contains subsections, these are also returned.
166 *
167 * @param string $text text to look in
168 * @param integer $section section number
169 * @return string text of the requested section
170 */
171 function getSection($text,$section) {
172
173 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
174 # comments to be stripped as well)
175 $striparray=array();
176 $parser=new Parser();
177 $parser->mOutputType=OT_WIKI;
178 $parser->mOptions = new ParserOptions();
179 $striptext=$parser->strip($text, $striparray, true);
180
181 # now that we can be sure that no pseudo-sections are in the source,
182 # split it up by section
183 $secs =
184 preg_split(
185 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
186 $striptext, -1,
187 PREG_SPLIT_DELIM_CAPTURE);
188 if($section==0) {
189 $rv=$secs[0];
190 } else {
191 $headline=$secs[$section*2-1];
192 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
193 $hlevel=$matches[1];
194
195 # translate wiki heading into level
196 if(strpos($hlevel,'=')!==false) {
197 $hlevel=strlen($hlevel);
198 }
199
200 $rv=$headline. $secs[$section*2];
201 $count=$section+1;
202
203 $break=false;
204 while(!empty($secs[$count*2-1]) && !$break) {
205
206 $subheadline=$secs[$count*2-1];
207 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
208 $subhlevel=$matches[1];
209 if(strpos($subhlevel,'=')!==false) {
210 $subhlevel=strlen($subhlevel);
211 }
212 if($subhlevel > $hlevel) {
213 $rv.=$subheadline.$secs[$count*2];
214 }
215 if($subhlevel <= $hlevel) {
216 $break=true;
217 }
218 $count++;
219
220 }
221 }
222 # reinsert stripped tags
223 $rv=$parser->unstrip($rv,$striparray);
224 $rv=$parser->unstripNoWiki($rv,$striparray);
225 $rv=trim($rv);
226 return $rv;
227
228 }
229
230 /**
231 * Return an array of the columns of the "cur"-table
232 */
233 function getContentFields() {
234 return $wgArticleContentFields = array(
235 'old_text','old_flags',
236 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
237 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
238 }
239
240 /**
241 * Return the oldid of the article that is to be shown.
242 * For requests with a "direction", this is not the oldid of the
243 * query
244 */
245 function getOldID() {
246 global $wgRequest, $wgOut;
247 static $lastid;
248
249 if ( isset( $lastid ) ) {
250 return $lastid;
251 }
252 # Query variables :P
253 $oldid = $wgRequest->getVal( 'oldid' );
254 if ( isset( $oldid ) ) {
255 $oldid = intval( $oldid );
256 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
257 $nextid = $this->mTitle->getNextRevisionID( $oldid );
258 if ( $nextid ) {
259 $oldid = $nextid;
260 } else {
261 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
262 }
263 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
264 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
265 if ( $previd ) {
266 $oldid = $previd;
267 } else {
268 # TODO
269 }
270 }
271 $lastid = $oldid;
272 }
273 return @$oldid; # "@" to be able to return "unset" without PHP complaining
274 }
275
276
277 /**
278 * Load the revision (including cur_text) into this object
279 */
280 function loadContent( $noredir = false ) {
281 global $wgOut, $wgRequest;
282
283 if ( $this->mContentLoaded ) return;
284
285 # Query variables :P
286 $oldid = $this->getOldID();
287 $redirect = $wgRequest->getVal( 'redirect' );
288
289 $fname = 'Article::loadContent';
290
291 # Pre-fill content with error message so that if something
292 # fails we'll have something telling us what we intended.
293
294 $t = $this->mTitle->getPrefixedText();
295
296 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
297 || $wgRequest->getCheck( 'rdfrom' );
298 $this->mOldId = $oldid;
299 $this->fetchContent( $oldid, $noredir, true );
300 }
301
302
303 /**
304 * Fetch a page record with the given conditions
305 * @param Database $dbr
306 * @param array $conditions
307 * @access private
308 */
309 function pageData( &$dbr, $conditions ) {
310 return $dbr->selectRow( 'page',
311 array(
312 'page_id',
313 'page_namespace',
314 'page_title',
315 'page_restrictions',
316 'page_counter',
317 'page_is_redirect',
318 'page_is_new',
319 'page_random',
320 'page_touched',
321 'page_latest',
322 'page_len' ),
323 $conditions,
324 'Article::pageData' );
325 }
326
327 function pageDataFromTitle( &$dbr, $title ) {
328 return $this->pageData( $dbr, array(
329 'page_namespace' => $title->getNamespace(),
330 'page_title' => $title->getDBkey() ) );
331 }
332
333 function pageDataFromId( &$dbr, $id ) {
334 return $this->pageData( $dbr, array(
335 'page_id' => intval( $id ) ) );
336 }
337
338 /**
339 * Set the general counter, title etc data loaded from
340 * some source.
341 *
342 * @param object $data
343 * @access private
344 */
345 function loadPageData( $data ) {
346 $this->mTitle->loadRestrictions( $data->page_restrictions );
347 $this->mTitle->mRestrictionsLoaded = true;
348
349 $this->mCounter = $data->page_counter;
350 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
351 $this->mIsRedirect = $data->page_is_redirect;
352 $this->mLatest = $data->page_latest;
353
354 $this->mDataLoaded = true;
355 }
356
357 /**
358 * Get text of an article from database
359 * @param int $oldid 0 for whatever the latest revision is
360 * @param bool $noredir Set to false to follow redirects
361 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
362 * @return string
363 */
364 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
365 if ( $this->mContentLoaded ) {
366 return $this->mContent;
367 }
368 $dbr =& $this->getDB();
369 $fname = 'Article::fetchContent';
370
371 # Pre-fill content with error message so that if something
372 # fails we'll have something telling us what we intended.
373 $t = $this->mTitle->getPrefixedText();
374 if( $oldid ) {
375 $t .= ',oldid='.$oldid;
376 }
377 if( isset( $redirect ) ) {
378 $redirect = ($redirect == 'no') ? 'no' : 'yes';
379 $t .= ',redirect='.$redirect;
380 }
381 $this->mContent = wfMsg( 'missingarticle', $t );
382
383 if( $oldid ) {
384 $revision = Revision::newFromId( $oldid );
385 if( is_null( $revision ) ) {
386 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
387 return false;
388 }
389 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
390 if( !$data ) {
391 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
392 return false;
393 }
394 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
395 $this->loadPageData( $data );
396 } else {
397 if( !$this->mDataLoaded ) {
398 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
399 if( !$data ) {
400 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
401 return false;
402 }
403 $this->loadPageData( $data );
404 }
405 $revision = Revision::newFromId( $this->mLatest );
406 if( is_null( $revision ) ) {
407 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
408 return false;
409 }
410 }
411
412 # If we got a redirect, follow it (unless we've been told
413 # not to by either the function parameter or the query
414 if ( !$oldid && !$noredir ) {
415 $rt = Title::newFromRedirect( $revision->getText() );
416 # process if title object is valid and not special:userlogout
417 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
418 # Gotta hand redirects to special pages differently:
419 # Fill the HTTP response "Location" header and ignore
420 # the rest of the page we're on.
421 global $wgDisableHardRedirects;
422 if( $globalTitle && !$wgDisableHardRedirects ) {
423 global $wgOut;
424 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
425 $source = $this->mTitle->getFullURL( 'redirect=no' );
426 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
427 return false;
428 }
429 if ( $rt->getNamespace() == NS_SPECIAL ) {
430 $wgOut->redirect( $rt->getFullURL() );
431 return false;
432 }
433 }
434 $redirData = $this->pageDataFromTitle( $dbr, $rt );
435 if( $redirData ) {
436 $redirRev = Revision::newFromId( $redirData->page_latest );
437 if( !is_null( $redirRev ) ) {
438 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
439 $this->mTitle = $rt;
440 $data = $redirData;
441 $this->loadPageData( $data );
442 $revision = $redirRev;
443 }
444 }
445 }
446 }
447
448 # if the title's different from expected, update...
449 if( $globalTitle ) {
450 global $wgTitle;
451 if( !$this->mTitle->equals( $wgTitle ) ) {
452 $wgTitle = $this->mTitle;
453 }
454 }
455
456 # Back to the business at hand...
457 $this->mContent = $revision->getText();
458
459 $this->mUser = $revision->getUser();
460 $this->mUserText = $revision->getUserText();
461 $this->mComment = $revision->getComment();
462 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
463
464 $this->mRevIdFetched = $revision->getID();
465 $this->mContentLoaded = true;
466 $this->mRevision =& $revision;
467
468 return $this->mContent;
469 }
470
471 /**
472 * Gets the article text without using so many damn globals
473 * Returns false on error
474 *
475 * @param integer $oldid
476 */
477 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
478 return $this->fetchContent( $oldid, $noredir, false );
479 }
480
481 /**
482 * Read/write accessor to select FOR UPDATE
483 */
484 function forUpdate( $x = NULL ) {
485 return wfSetVar( $this->mForUpdate, $x );
486 }
487
488 /**
489 * Get the database which should be used for reads
490 */
491 function &getDB() {
492 $ret =& wfGetDB( DB_MASTER );
493 return $ret;
494 #if ( $this->mForUpdate ) {
495 $ret =& wfGetDB( DB_MASTER );
496 #} else {
497 # $ret =& wfGetDB( DB_SLAVE );
498 #}
499 return $ret;
500 }
501
502 /**
503 * Get options for all SELECT statements
504 * Can pass an option array, to which the class-wide options will be appended
505 */
506 function getSelectOptions( $options = '' ) {
507 if ( $this->mForUpdate ) {
508 if ( is_array( $options ) ) {
509 $options[] = 'FOR UPDATE';
510 } else {
511 $options = 'FOR UPDATE';
512 }
513 }
514 return $options;
515 }
516
517 /**
518 * Return the Article ID
519 */
520 function getID() {
521 if( $this->mTitle ) {
522 return $this->mTitle->getArticleID();
523 } else {
524 return 0;
525 }
526 }
527
528 /**
529 * Returns true if this article exists in the database.
530 * @return bool
531 */
532 function exists() {
533 return $this->getId() != 0;
534 }
535
536 /**
537 * Get the view count for this article
538 */
539 function getCount() {
540 if ( -1 == $this->mCounter ) {
541 $id = $this->getID();
542 $dbr =& $this->getDB();
543 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
544 'Article::getCount', $this->getSelectOptions() );
545 }
546 return $this->mCounter;
547 }
548
549 /**
550 * Would the given text make this article a "good" article (i.e.,
551 * suitable for including in the article count)?
552 * @param string $text Text to analyze
553 * @return integer 1 if it can be counted else 0
554 */
555 function isCountable( $text ) {
556 global $wgUseCommaCount;
557
558 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
559 if ( $this->isRedirect( $text ) ) { return 0; }
560 $token = ($wgUseCommaCount ? ',' : '[[' );
561 if ( false === strstr( $text, $token ) ) { return 0; }
562 return 1;
563 }
564
565 /**
566 * Tests if the article text represents a redirect
567 */
568 function isRedirect( $text = false ) {
569 if ( $text === false ) {
570 $this->loadContent();
571 $titleObj = Title::newFromRedirect( $this->fetchContent() );
572 } else {
573 $titleObj = Title::newFromRedirect( $text );
574 }
575 return $titleObj !== NULL;
576 }
577
578 /**
579 * Returns true if the currently-referenced revision is the current edit
580 * to this page (and it exists).
581 * @return bool
582 */
583 function isCurrent() {
584 return $this->exists() &&
585 isset( $this->mRevision ) &&
586 $this->mRevision->isCurrent();
587 }
588
589 /**
590 * Loads everything except the text
591 * This isn't necessary for all uses, so it's only done if needed.
592 * @private
593 */
594 function loadLastEdit() {
595 global $wgOut;
596
597 if ( -1 != $this->mUser )
598 return;
599
600 # New or non-existent articles have no user information
601 $id = $this->getID();
602 if ( 0 == $id ) return;
603
604 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
605 if( !is_null( $this->mLastRevision ) ) {
606 $this->mUser = $this->mLastRevision->getUser();
607 $this->mUserText = $this->mLastRevision->getUserText();
608 $this->mTimestamp = $this->mLastRevision->getTimestamp();
609 $this->mComment = $this->mLastRevision->getComment();
610 $this->mMinorEdit = $this->mLastRevision->isMinor();
611 }
612 }
613
614 function getTimestamp() {
615 $this->loadLastEdit();
616 return wfTimestamp(TS_MW, $this->mTimestamp);
617 }
618
619 function getUser() {
620 $this->loadLastEdit();
621 return $this->mUser;
622 }
623
624 function getUserText() {
625 $this->loadLastEdit();
626 return $this->mUserText;
627 }
628
629 function getComment() {
630 $this->loadLastEdit();
631 return $this->mComment;
632 }
633
634 function getMinorEdit() {
635 $this->loadLastEdit();
636 return $this->mMinorEdit;
637 }
638
639 function getRevIdFetched() {
640 $this->loadLastEdit();
641 return $this->mRevIdFetched;
642 }
643
644 function getContributors($limit = 0, $offset = 0) {
645 $fname = 'Article::getContributors';
646
647 # XXX: this is expensive; cache this info somewhere.
648
649 $title = $this->mTitle;
650 $contribs = array();
651 $dbr =& $this->getDB();
652 $revTable = $dbr->tableName( 'revision' );
653 $userTable = $dbr->tableName( 'user' );
654 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
655 $ns = $title->getNamespace();
656 $user = $this->getUser();
657 $pageId = $this->getId();
658
659 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
660 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
661 WHERE rev_page = $pageId
662 AND rev_user != $user
663 GROUP BY rev_user, rev_user_text, user_real_name
664 ORDER BY timestamp DESC";
665
666 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
667 $sql .= ' '. $this->getSelectOptions();
668
669 $res = $dbr->query($sql, $fname);
670
671 while ( $line = $dbr->fetchObject( $res ) ) {
672 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
673 }
674
675 $dbr->freeResult($res);
676 return $contribs;
677 }
678
679 /**
680 * This is the default action of the script: just view the page of
681 * the given title.
682 */
683 function view() {
684 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
685 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
686 global $wgEnotif, $wgParser, $wgParserCache, $wgUseTrackbacks;
687 $sk = $wgUser->getSkin();
688
689 $fname = 'Article::view';
690 wfProfileIn( $fname );
691 # Get variables from query string
692 $oldid = $this->getOldID();
693 $diff = $wgRequest->getVal( 'diff' );
694 $rcid = $wgRequest->getVal( 'rcid' );
695 $rdfrom = $wgRequest->getVal( 'rdfrom' );
696
697 $wgOut->setArticleFlag( true );
698 $wgOut->setRobotpolicy( 'index,follow' );
699 # If we got diff and oldid in the query, we want to see a
700 # diff page instead of the article.
701
702 if ( !is_null( $diff ) ) {
703 require_once( 'DifferenceEngine.php' );
704 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
705
706 $de = new DifferenceEngine( $oldid, $diff, $rcid );
707 // DifferenceEngine directly fetched the revision:
708 $this->mRevIdFetched = $de->mNewid;
709 $de->showDiffPage();
710
711 if( $diff == 0 ) {
712 # Run view updates for current revision only
713 $this->viewUpdates();
714 }
715 wfProfileOut( $fname );
716 return;
717 }
718
719 if ( empty( $oldid ) && $this->checkTouched() ) {
720 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
721
722 if( $wgOut->checkLastModified( $this->mTouched ) ){
723 wfProfileOut( $fname );
724 return;
725 } else if ( $this->tryFileCache() ) {
726 # tell wgOut that output is taken care of
727 $wgOut->disable();
728 $this->viewUpdates();
729 wfProfileOut( $fname );
730 return;
731 }
732 }
733 # Should the parser cache be used?
734 $pcache = $wgEnableParserCache &&
735 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
736 $this->exists() &&
737 empty( $oldid );
738 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
739
740 $outputDone = false;
741 if ( $pcache ) {
742 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
743 $outputDone = true;
744 }
745 }
746 if ( !$outputDone ) {
747 $text = $this->getContent( false ); # May change mTitle by following a redirect
748
749 # Another whitelist check in case oldid or redirects are altering the title
750 if ( !$this->mTitle->userCanRead() ) {
751 $wgOut->loginToUse();
752 $wgOut->output();
753 exit;
754 }
755
756 # We're looking at an old revision
757
758 if ( !empty( $oldid ) ) {
759 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
760 $wgOut->setRobotpolicy( 'noindex,follow' );
761 }
762 if ( '' != $this->mRedirectedFrom ) {
763 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
764 $sk = $wgUser->getSkin();
765 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '', 'redirect=no' );
766 $s = wfMsg( 'redirectedfrom', $redir );
767 $wgOut->setSubtitle( $s );
768 # Can't cache redirects
769 $pcache = false;
770 }
771 } elseif ( !empty( $rdfrom ) ) {
772 global $wgRedirectSources;
773 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
774 $sk = $wgUser->getSkin();
775 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
776 $s = wfMsg( 'redirectedfrom', $redir );
777 $wgOut->setSubtitle( $s );
778 }
779 }
780
781 # wrap user css and user js in pre and don't parse
782 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
783 if (
784 $this->mTitle->getNamespace() == NS_USER &&
785 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
786 ) {
787 $wgOut->addWikiText( wfMsg('clearyourcache'));
788 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
789 } else if ( $rt = Title::newFromRedirect( $text ) ) {
790 # Display redirect
791 $imageUrl = $wgStylePath.'/common/images/redirect.png';
792 $targetUrl = $rt->escapeLocalURL();
793 $titleText = htmlspecialchars( $rt->getPrefixedText() );
794 $link = $sk->makeLinkObj( $rt );
795
796 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
797 '<span class="redirectText">'.$link.'</span>' );
798
799 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
800 $catlinks = $parseout->getCategoryLinks();
801 $wgOut->addCategoryLinks($catlinks);
802 $skin = $wgUser->getSkin();
803 } else if ( $pcache ) {
804 # Display content and save to parser cache
805 $wgOut->addPrimaryWikiText( $text, $this );
806 } else {
807 # Display content, don't attempt to save to parser cache
808
809 # Don't show section-edit links on old revisions... this way lies madness.
810 if( !$this->isCurrent() ) {
811 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
812 }
813 $wgOut->addWikiText( $text );
814
815 if( !$this->isCurrent() ) {
816 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
817 }
818 }
819 }
820 /* title may have been set from the cache */
821 $t = $wgOut->getPageTitle();
822 if( empty( $t ) ) {
823 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
824 }
825
826 # If we have been passed an &rcid= parameter, we want to give the user a
827 # chance to mark this new article as patrolled.
828 if ( $wgUseRCPatrol
829 && !is_null($rcid)
830 && $rcid != 0
831 && $wgUser->isLoggedIn()
832 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
833 {
834 $wgOut->addHTML(
835 "<div class='patrollink'>" .
836 wfMsg ( 'markaspatrolledlink',
837 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
838 ) .
839 '</div>'
840 );
841 }
842
843 # Trackbacks
844 if ($wgUseTrackbacks)
845 $this->addTrackbacks();
846
847 # Put link titles into the link cache
848 $wgOut->transformBuffer();
849
850 # Add link titles as META keywords
851 $wgOut->addMetaTags() ;
852
853 $this->viewUpdates();
854 wfProfileOut( $fname );
855 }
856
857 function addTrackbacks() {
858 global $wgOut, $wgUser;
859
860 $dbr =& wfGetDB(DB_SLAVE);
861 $tbs = $dbr->select(
862 /* FROM */ 'trackbacks',
863 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
864 /* WHERE */ array('tb_page' => $this->getID())
865 );
866
867 if (!$dbr->numrows($tbs))
868 return;
869
870 $tbtext = "";
871 while ($o = $dbr->fetchObject($tbs)) {
872 $rmvtxt = "";
873 if ($wgUser->isSysop()) {
874 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
875 . $o->tb_id . "&token=" . $wgUser->editToken());
876 $rmvtxt = wfMsg('trackbackremove', $delurl);
877 }
878 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
879 $o->tb_title,
880 $o->tb_url,
881 $o->tb_ex,
882 $o->tb_name,
883 $rmvtxt);
884 }
885 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
886 }
887
888 function deletetrackback() {
889 global $wgUser, $wgRequest, $wgOut, $wgTitle;
890
891 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
892 $wgOut->addWikitext(wfMsg('sessionfailure'));
893 return;
894 }
895
896 if ((!$wgUser->isAllowed('delete'))) {
897 $wgOut->sysopRequired();
898 return;
899 }
900
901 if (wfReadOnly()) {
902 $wgOut->readOnlyPage();
903 return;
904 }
905
906 $db =& wfGetDB(DB_MASTER);
907 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
908 $wgTitle->invalidateCache();
909 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
910 }
911
912 function render() {
913 global $wgOut;
914
915 $wgOut->setArticleBodyOnly(true);
916 $this->view();
917 }
918
919 /**
920 * Insert a new empty page record for this article.
921 * This *must* be followed up by creating a revision
922 * and running $this->updateToLatest( $rev_id );
923 * or else the record will be left in a funky state.
924 * Best if all done inside a transaction.
925 *
926 * @param Database $dbw
927 * @param string $restrictions
928 * @return int The newly created page_id key
929 * @access private
930 */
931 function insertOn( &$dbw, $restrictions = '' ) {
932 $fname = 'Article::insertOn';
933 wfProfileIn( $fname );
934
935 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
936 $dbw->insert( 'page', array(
937 'page_id' => $page_id,
938 'page_namespace' => $this->mTitle->getNamespace(),
939 'page_title' => $this->mTitle->getDBkey(),
940 'page_counter' => 0,
941 'page_restrictions' => $restrictions,
942 'page_is_redirect' => 0, # Will set this shortly...
943 'page_is_new' => 1,
944 'page_random' => wfRandom(),
945 'page_touched' => $dbw->timestamp(),
946 'page_latest' => 0, # Fill this in shortly...
947 ), $fname );
948 $newid = $dbw->insertId();
949
950 $this->mTitle->resetArticleId( $newid );
951
952 wfProfileOut( $fname );
953 return $newid;
954 }
955
956 /**
957 * Update the page record to point to a newly saved revision.
958 *
959 * @param Database $dbw
960 * @param Revision $revision -- for ID number, and text used to set
961 length and redirect status fields
962 * @param int $lastRevision -- if given, will not overwrite the page field
963 * when different from the currently set value.
964 * Giving 0 indicates the new page flag should
965 * be set on.
966 * @return bool true on success, false on failure
967 * @access private
968 */
969 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
970 $fname = 'Article::updateToRevision';
971 wfProfileIn( $fname );
972
973 $conditions = array( 'page_id' => $this->getId() );
974 if( !is_null( $lastRevision ) ) {
975 # An extra check against threads stepping on each other
976 $conditions['page_latest'] = $lastRevision;
977 }
978
979 $text = $revision->getText();
980 $dbw->update( 'page',
981 array( /* SET */
982 'page_latest' => $revision->getId(),
983 'page_touched' => $dbw->timestamp(),
984 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
985 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
986 'page_len' => strlen( $text ),
987 ),
988 $conditions,
989 $fname );
990
991 wfProfileOut( $fname );
992 return ( $dbw->affectedRows() != 0 );
993 }
994
995 /**
996 * If the given revision is newer than the currently set page_latest,
997 * update the page record. Otherwise, do nothing.
998 *
999 * @param Database $dbw
1000 * @param Revision $revision
1001 */
1002 function updateIfNewerOn( &$dbw, $revision ) {
1003 $fname = 'Article::updateIfNewerOn';
1004 wfProfileIn( $fname );
1005
1006 $row = $dbw->selectRow(
1007 array( 'revision', 'page' ),
1008 array( 'rev_id', 'rev_timestamp' ),
1009 array(
1010 'page_id' => $this->getId(),
1011 'page_latest=rev_id' ),
1012 $fname );
1013 if( $row ) {
1014 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1015 wfProfileOut( $fname );
1016 return false;
1017 }
1018 $prev = $row->rev_id;
1019 } else {
1020 # No or missing previous revision; mark the page as new
1021 $prev = 0;
1022 }
1023
1024 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1025 wfProfileOut( $fname );
1026 return $ret;
1027 }
1028
1029 /**
1030 * Theoretically we could defer these whole insert and update
1031 * functions for after display, but that's taking a big leap
1032 * of faith, and we want to be able to report database
1033 * errors at some point.
1034 * @private
1035 */
1036 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1037 global $wgOut, $wgUser;
1038 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1039
1040 $fname = 'Article::insertNewArticle';
1041 wfProfileIn( $fname );
1042
1043 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1044 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1045 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1046 wfProfileOut( $fname );
1047 return false;
1048 }
1049
1050 $this->mGoodAdjustment = $this->isCountable( $text );
1051 $this->mTotalAdjustment = 1;
1052
1053 $ns = $this->mTitle->getNamespace();
1054 $ttl = $this->mTitle->getDBkey();
1055
1056 # If this is a comment, add the summary as headline
1057 if($comment && $summary!="") {
1058 $text="== {$summary} ==\n\n".$text;
1059 }
1060 $text = $this->preSaveTransform( $text );
1061 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
1062 $now = wfTimestampNow();
1063
1064 $dbw =& wfGetDB( DB_MASTER );
1065
1066 # Add the page record; stake our claim on this title!
1067 $newid = $this->insertOn( $dbw );
1068
1069 # Save the revision text...
1070 $revision = new Revision( array(
1071 'page' => $newid,
1072 'comment' => $summary,
1073 'minor_edit' => $isminor,
1074 'text' => $text
1075 ) );
1076 $revisionId = $revision->insertOn( $dbw );
1077
1078 $this->mTitle->resetArticleID( $newid );
1079
1080 # Update the page record with revision data
1081 $this->updateRevisionOn( $dbw, $revision, 0 );
1082
1083 Article::onArticleCreate( $this->mTitle );
1084 if(!$suppressRC) {
1085 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1086 '', strlen( $text ), $revisionId );
1087 }
1088
1089 if ($watchthis) {
1090 if(!$this->mTitle->userIsWatching()) $this->watch();
1091 } else {
1092 if ( $this->mTitle->userIsWatching() ) {
1093 $this->unwatch();
1094 }
1095 }
1096
1097 # The talk page isn't in the regular link tables, so we need to update manually:
1098 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1099 $dbw->update( 'page',
1100 array( 'page_touched' => $dbw->timestamp($now) ),
1101 array( 'page_namespace' => $talkns,
1102 'page_title' => $ttl ),
1103 $fname );
1104
1105 # standard deferred updates
1106 $this->editUpdates( $text, $summary, $isminor, $now );
1107
1108 $oldid = 0; # new article
1109 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1110
1111 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1112 $summary, $isminor,
1113 $watchthis, NULL ) );
1114 wfProfileOut( $fname );
1115 }
1116
1117 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1118 $this->replaceSection( $section, $text, $summary, $edittime );
1119 }
1120
1121 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1122 $fname = 'Article::replaceSection';
1123 wfProfileIn( $fname );
1124
1125 if ($section != '') {
1126 if( is_null( $edittime ) ) {
1127 $rev = Revision::newFromTitle( $this->mTitle );
1128 } else {
1129 $dbw =& wfGetDB( DB_MASTER );
1130 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1131 }
1132 $oldtext = $rev->getText();
1133
1134 if($section=='new') {
1135 if($summary) $subject="== {$summary} ==\n\n";
1136 $text=$oldtext."\n\n".$subject.$text;
1137 } else {
1138
1139 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1140 # comments to be stripped as well)
1141 $striparray=array();
1142 $parser=new Parser();
1143 $parser->mOutputType=OT_WIKI;
1144 $parser->mOptions = new ParserOptions();
1145 $oldtext=$parser->strip($oldtext, $striparray, true);
1146
1147 # now that we can be sure that no pseudo-sections are in the source,
1148 # split it up
1149 # Unfortunately we can't simply do a preg_replace because that might
1150 # replace the wrong section, so we have to use the section counter instead
1151 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1152 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1153 $secs[$section*2]=$text."\n\n"; // replace with edited
1154
1155 # section 0 is top (intro) section
1156 if($section!=0) {
1157
1158 # headline of old section - we need to go through this section
1159 # to determine if there are any subsections that now need to
1160 # be erased, as the mother section has been replaced with
1161 # the text of all subsections.
1162 $headline=$secs[$section*2-1];
1163 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1164 $hlevel=$matches[1];
1165
1166 # determine headline level for wikimarkup headings
1167 if(strpos($hlevel,'=')!==false) {
1168 $hlevel=strlen($hlevel);
1169 }
1170
1171 $secs[$section*2-1]=''; // erase old headline
1172 $count=$section+1;
1173 $break=false;
1174 while(!empty($secs[$count*2-1]) && !$break) {
1175
1176 $subheadline=$secs[$count*2-1];
1177 preg_match(
1178 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1179 $subhlevel=$matches[1];
1180 if(strpos($subhlevel,'=')!==false) {
1181 $subhlevel=strlen($subhlevel);
1182 }
1183 if($subhlevel > $hlevel) {
1184 // erase old subsections
1185 $secs[$count*2-1]='';
1186 $secs[$count*2]='';
1187 }
1188 if($subhlevel <= $hlevel) {
1189 $break=true;
1190 }
1191 $count++;
1192
1193 }
1194
1195 }
1196 $text=join('',$secs);
1197 # reinsert the stuff that we stripped out earlier
1198 $text=$parser->unstrip($text,$striparray);
1199 $text=$parser->unstripNoWiki($text,$striparray);
1200 }
1201
1202 }
1203 wfProfileOut( $fname );
1204 return $text;
1205 }
1206
1207 /**
1208 * Change an existing article. Puts the previous version back into the old table, updates RC
1209 * and all necessary caches, mostly via the deferred update array.
1210 *
1211 * It is possible to call this function from a command-line script, but note that you should
1212 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1213 */
1214 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1215 global $wgOut, $wgUser;
1216 global $wgDBtransactions, $wgMwRedir;
1217 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList, $wgUseFileCache;
1218
1219 $fname = 'Article::updateArticle';
1220 wfProfileIn( $fname );
1221 $good = true;
1222
1223 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1224 &$summary, &$minor,
1225 &$watchthis, &$sectionanchor ) ) ) {
1226 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1227 wfProfileOut( $fname );
1228 return false;
1229 }
1230
1231 $isminor = ( $minor && $wgUser->isLoggedIn() );
1232 if ( $this->isRedirect( $text ) ) {
1233 # Remove all content but redirect
1234 # This could be done by reconstructing the redirect from a title given by
1235 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1236 # wants to see
1237 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1238 $redir = 1;
1239 $text = $m[1] . "\n";
1240 }
1241 }
1242 else { $redir = 0; }
1243
1244 $text = $this->preSaveTransform( $text );
1245 $dbw =& wfGetDB( DB_MASTER );
1246 $now = wfTimestampNow();
1247
1248 # Update article, but only if changed.
1249
1250 # It's important that we either rollback or complete, otherwise an attacker could
1251 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1252 # could conceivably have the same effect, especially if cur is locked for long periods.
1253 if( !$wgDBtransactions ) {
1254 $userAbort = ignore_user_abort( true );
1255 }
1256
1257 $oldtext = $this->getContent( true );
1258 $oldsize = strlen( $oldtext );
1259 $newsize = strlen( $text );
1260 $lastRevision = 0;
1261
1262 if ( 0 != strcmp( $text, $oldtext ) ) {
1263 $this->mGoodAdjustment = $this->isCountable( $text )
1264 - $this->isCountable( $oldtext );
1265 $this->mTotalAdjustment = 0;
1266 $now = wfTimestampNow();
1267
1268 $lastRevision = $dbw->selectField(
1269 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1270
1271 $revision = new Revision( array(
1272 'page' => $this->getId(),
1273 'comment' => $summary,
1274 'minor_edit' => $isminor,
1275 'text' => $text
1276 ) );
1277
1278 $dbw->immediateCommit();
1279 $dbw->begin();
1280 $revisionId = $revision->insertOn( $dbw );
1281
1282 # Update page
1283 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1284
1285 if( !$ok ) {
1286 /* Belated edit conflict! Run away!! */
1287 $good = false;
1288 $dbw->rollback();
1289 } else {
1290 # Update recentchanges and purge cache and whatnot
1291 $bot = (int)($wgUser->isBot() || $forceBot);
1292 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1293 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1294 $revisionId );
1295 Article::onArticleEdit( $this->mTitle );
1296 $dbw->commit();
1297 }
1298 }
1299
1300 if( !$wgDBtransactions ) {
1301 ignore_user_abort( $userAbort );
1302 }
1303
1304 if ( $good ) {
1305 if ($watchthis) {
1306 if (!$this->mTitle->userIsWatching()) {
1307 $dbw->immediateCommit();
1308 $dbw->begin();
1309 $this->watch();
1310 $dbw->commit();
1311 }
1312 } else {
1313 if ( $this->mTitle->userIsWatching() ) {
1314 $dbw->immediateCommit();
1315 $dbw->begin();
1316 $this->unwatch();
1317 $dbw->commit();
1318 }
1319 }
1320 # standard deferred updates
1321 $this->editUpdates( $text, $summary, $minor, $now );
1322
1323
1324 $urls = array();
1325 # Template namespace
1326 # Purge all articles linking here
1327 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1328 $titles = $this->mTitle->getLinksTo();
1329 Title::touchArray( $titles );
1330 if ( $wgUseSquid ) {
1331 foreach ( $titles as $title ) {
1332 $urls[] = $title->getInternalURL();
1333 }
1334 }
1335 }
1336
1337 # Squid updates
1338 if ( $wgUseSquid ) {
1339 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1340 $u = new SquidUpdate( $urls );
1341 array_push( $wgPostCommitUpdateList, $u );
1342 }
1343
1344 # File cache
1345 if ( $wgUseFileCache ) {
1346 $cm = new CacheManager($this->mTitle);
1347 @unlink($cm->fileCacheName());
1348 }
1349
1350 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1351 }
1352 wfRunHooks( 'ArticleSaveComplete',
1353 array( &$this, &$wgUser, $text,
1354 $summary, $minor,
1355 $watchthis, $sectionanchor ) );
1356 wfProfileOut( $fname );
1357 return $good;
1358 }
1359
1360 /**
1361 * After we've either updated or inserted the article, update
1362 * the link tables and redirect to the new page.
1363 */
1364 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1365 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1366 global $wgUseEnotif;
1367
1368 $fname = 'Article::showArticle';
1369 wfProfileIn( $fname );
1370
1371 $wgLinkCache = new LinkCache();
1372
1373 if ( !$wgUseDumbLinkUpdate ) {
1374 # Preload links to reduce lock time
1375 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1376 $wgLinkCache->preFill( $this->mTitle );
1377 $wgLinkCache->clear();
1378 }
1379 }
1380
1381 # Parse the text and replace links with placeholders
1382 $wgOut = new OutputPage();
1383
1384 # Pass the current title along in case we're creating a wiki page
1385 # which is different than the currently displayed one (e.g. image
1386 # pages created on file uploads); otherwise, link updates will
1387 # go wrong.
1388 $wgOut->addWikiTextWithTitle( $text, $this->mTitle );
1389
1390 if ( !$wgUseDumbLinkUpdate ) {
1391 # Move the current links back to the second register
1392 $wgLinkCache->swapRegisters();
1393
1394 # Get old version of link table to allow incremental link updates
1395 # Lock this data now since it is needed for an update
1396 $wgLinkCache->forUpdate( true );
1397 $wgLinkCache->preFill( $this->mTitle );
1398
1399 # Swap this old version back into its rightful place
1400 $wgLinkCache->swapRegisters();
1401 }
1402
1403 if( $this->isRedirect( $text ) )
1404 $r = 'redirect=no';
1405 else
1406 $r = '';
1407 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1408
1409 if ( $wgUseEnotif ) {
1410 # this would be better as an extension hook
1411 include_once( "UserMailer.php" );
1412 $wgEnotif = new EmailNotification ();
1413 $wgEnotif->notifyOnPageChange( $this->mTitle, $now, $summary, $me2, $oldid );
1414 }
1415 wfProfileOut( $fname );
1416 }
1417
1418 /**
1419 * Mark this particular edit as patrolled
1420 */
1421 function markpatrolled() {
1422 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1423 $wgOut->setRobotpolicy( 'noindex,follow' );
1424
1425 if ( !$wgUseRCPatrol )
1426 {
1427 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1428 return;
1429 }
1430 if ( $wgUser->isAnon() )
1431 {
1432 $wgOut->loginToUse();
1433 return;
1434 }
1435 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1436 {
1437 $wgOut->sysopRequired();
1438 return;
1439 }
1440 $rcid = $wgRequest->getVal( 'rcid' );
1441 if ( !is_null ( $rcid ) )
1442 {
1443 RecentChange::markPatrolled( $rcid );
1444 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1445 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1446
1447 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1448 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1449 }
1450 else
1451 {
1452 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1453 }
1454 }
1455
1456 /**
1457 * Validate function
1458 */
1459 function validate() {
1460 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1461
1462 if ( !$wgUseValidation ) # Are we using article validation at all?
1463 {
1464 $wgOut->setStatusCode( 404 );
1465 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1466 return ;
1467 }
1468
1469 $wgOut->setRobotpolicy( 'noindex,follow' );
1470 $revision = $wgRequest->getVal( 'revision' );
1471
1472 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1473
1474 $v = new Validation ;
1475 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1476 $t = $v->showList ( $this ) ;
1477 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1478 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1479 else
1480 $t = $v->validatePageForm ( $this , $revision ) ;
1481
1482 $wgOut->addHTML ( $t ) ;
1483 }
1484
1485 /**
1486 * Add this page to $wgUser's watchlist
1487 */
1488
1489 function watch() {
1490
1491 global $wgUser, $wgOut;
1492
1493 if ( $wgUser->isAnon() ) {
1494 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1495 return;
1496 }
1497 if ( wfReadOnly() ) {
1498 $wgOut->readOnlyPage();
1499 return;
1500 }
1501
1502 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1503
1504 $wgUser->addWatch( $this->mTitle );
1505 $wgUser->saveSettings();
1506
1507 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1508
1509 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1510 $wgOut->setRobotpolicy( 'noindex,follow' );
1511
1512 $link = $this->mTitle->getPrefixedText();
1513 $text = wfMsg( 'addedwatchtext', $link );
1514 $wgOut->addWikiText( $text );
1515 }
1516
1517 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1518 }
1519
1520 /**
1521 * Stop watching a page
1522 */
1523
1524 function unwatch() {
1525
1526 global $wgUser, $wgOut;
1527
1528 if ( $wgUser->isAnon() ) {
1529 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1530 return;
1531 }
1532 if ( wfReadOnly() ) {
1533 $wgOut->readOnlyPage();
1534 return;
1535 }
1536
1537 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1538
1539 $wgUser->removeWatch( $this->mTitle );
1540 $wgUser->saveSettings();
1541
1542 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1543
1544 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1545 $wgOut->setRobotpolicy( 'noindex,follow' );
1546
1547 $link = $this->mTitle->getPrefixedText();
1548 $text = wfMsg( 'removedwatchtext', $link );
1549 $wgOut->addWikiText( $text );
1550 }
1551
1552 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1553 }
1554
1555 /**
1556 * protect a page
1557 */
1558 function protect( $limit = 'sysop' ) {
1559 global $wgUser, $wgOut, $wgRequest;
1560
1561 if ( ! $wgUser->isAllowed('protect') ) {
1562 $wgOut->sysopRequired();
1563 return;
1564 }
1565 if ( wfReadOnly() ) {
1566 $wgOut->readOnlyPage();
1567 return;
1568 }
1569 $id = $this->mTitle->getArticleID();
1570 if ( 0 == $id ) {
1571 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1572 return;
1573 }
1574
1575 $confirm = $wgRequest->wasPosted() &&
1576 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1577 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1578 $reason = $wgRequest->getText( 'wpReasonProtect' );
1579
1580 if ( $confirm ) {
1581 $dbw =& wfGetDB( DB_MASTER );
1582 $dbw->update( 'page',
1583 array( /* SET */
1584 'page_touched' => $dbw->timestamp(),
1585 'page_restrictions' => (string)$limit
1586 ), array( /* WHERE */
1587 'page_id' => $id
1588 ), 'Article::protect'
1589 );
1590
1591 $restrictions = "move=" . $limit;
1592 if( !$moveonly ) {
1593 $restrictions .= ":edit=" . $limit;
1594 }
1595 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1596
1597 $dbw =& wfGetDB( DB_MASTER );
1598 $dbw->update( 'page',
1599 array( /* SET */
1600 'page_touched' => $dbw->timestamp(),
1601 'page_restrictions' => $restrictions
1602 ), array( /* WHERE */
1603 'page_id' => $id
1604 ), 'Article::protect'
1605 );
1606
1607 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1608
1609 $log = new LogPage( 'protect' );
1610 if ( $limit === '' ) {
1611 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1612 } else {
1613 $log->addEntry( 'protect', $this->mTitle, $reason );
1614 }
1615 $wgOut->redirect( $this->mTitle->getFullURL() );
1616 }
1617 return;
1618 } else {
1619 return $this->confirmProtect( '', '', $limit );
1620 }
1621 }
1622
1623 /**
1624 * Output protection confirmation dialog
1625 */
1626 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1627 global $wgOut, $wgUser;
1628
1629 wfDebug( "Article::confirmProtect\n" );
1630
1631 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1632 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1633
1634 $check = '';
1635 $protcom = '';
1636 $moveonly = '';
1637
1638 if ( $limit === '' ) {
1639 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1640 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1641 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1642 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1643 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1644 } else {
1645 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1646 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1647 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1648 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1649 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1650 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1651 }
1652
1653 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1654 $token = htmlspecialchars( $wgUser->editToken() );
1655
1656 $wgOut->addHTML( "
1657 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1658 <table border='0'>
1659 <tr>
1660 <td align='right'>
1661 <label for='wpReasonProtect'>{$protcom}:</label>
1662 </td>
1663 <td align='left'>
1664 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1665 </td>
1666 </tr>" );
1667 if($moveonly != '') {
1668 $wgOut->AddHTML( "
1669 <tr>
1670 <td align='right'>
1671 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1672 </td>
1673 <td align='left'>
1674 <label for='wpMoveOnly'>{$moveonly}</label>
1675 </td>
1676 </tr> " );
1677 }
1678 $wgOut->addHTML( "
1679 <tr>
1680 <td>&nbsp;</td>
1681 <td>
1682 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1683 </td>
1684 </tr>
1685 </table>
1686 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1687 </form>" );
1688
1689 $wgOut->returnToMain( false );
1690 }
1691
1692 /**
1693 * Unprotect the pages
1694 */
1695 function unprotect() {
1696 return $this->protect( '' );
1697 }
1698
1699 /*
1700 * UI entry point for page deletion
1701 */
1702 function delete() {
1703 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1704 $fname = 'Article::delete';
1705 $confirm = $wgRequest->wasPosted() &&
1706 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1707 $reason = $wgRequest->getText( 'wpReason' );
1708
1709 # This code desperately needs to be totally rewritten
1710
1711 # Check permissions
1712 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1713 $wgOut->sysopRequired();
1714 return;
1715 }
1716 if( wfReadOnly() ) {
1717 $wgOut->readOnlyPage();
1718 return;
1719 }
1720
1721 # Better double-check that it hasn't been deleted yet!
1722 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1723 if( !$this->mTitle->exists() ) {
1724 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1725 return;
1726 }
1727
1728 if( $confirm ) {
1729 $this->doDelete( $reason );
1730 return;
1731 }
1732
1733 # determine whether this page has earlier revisions
1734 # and insert a warning if it does
1735 # we select the text because it might be useful below
1736 $dbr =& $this->getDB();
1737 $ns = $this->mTitle->getNamespace();
1738 $title = $this->mTitle->getDBkey();
1739 $revisions = $dbr->select( array( 'page', 'revision' ),
1740 array( 'rev_id', 'rev_user_text' ),
1741 array(
1742 'page_namespace' => $ns,
1743 'page_title' => $title,
1744 'rev_page = page_id'
1745 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1746 );
1747
1748 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1749 $skin=$wgUser->getSkin();
1750 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1751 $wgOut->addHTML( $skin->historyLink() .'</b>');
1752 }
1753
1754 # Fetch cur_text
1755 $rev = Revision::newFromTitle( $this->mTitle );
1756
1757 # Fetch name(s) of contributors
1758 $rev_name = '';
1759 $all_same_user = true;
1760 while( $row = $dbr->fetchObject( $revisions ) ) {
1761 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1762 $all_same_user = false;
1763 } else {
1764 $rev_name = $row->rev_user_text;
1765 }
1766 }
1767
1768 if( !is_null( $rev ) ) {
1769 # if this is a mini-text, we can paste part of it into the deletion reason
1770 $text = $rev->getText();
1771
1772 #if this is empty, an earlier revision may contain "useful" text
1773 $blanked = false;
1774 if( $text == '' ) {
1775 $prev = $rev->getPrevious();
1776 if( $prev ) {
1777 $text = $prev->getText();
1778 $blanked = true;
1779 }
1780 }
1781
1782 $length = strlen( $text );
1783
1784 # this should not happen, since it is not possible to store an empty, new
1785 # page. Let's insert a standard text in case it does, though
1786 if( $length == 0 && $reason === '' ) {
1787 $reason = wfMsgForContent( 'exblank' );
1788 }
1789
1790 if( $length < 500 && $reason === '' ) {
1791 # comment field=255, let's grep the first 150 to have some user
1792 # space left
1793 global $wgContLang;
1794 $text = $wgContLang->truncate( $text, 150, '...' );
1795
1796 # let's strip out newlines
1797 $text = preg_replace( "/[\n\r]/", '', $text );
1798
1799 if( !$blanked ) {
1800 if( !$all_same_user ) {
1801 $reason = wfMsgForContent( 'excontent', $text );
1802 } else {
1803 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1804 }
1805 } else {
1806 $reason = wfMsgForContent( 'exbeforeblank', $text );
1807 }
1808 }
1809 }
1810
1811 return $this->confirmDelete( '', $reason );
1812 }
1813
1814 /**
1815 * Output deletion confirmation dialog
1816 */
1817 function confirmDelete( $par, $reason ) {
1818 global $wgOut, $wgUser;
1819
1820 wfDebug( "Article::confirmDelete\n" );
1821
1822 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1823 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1824 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1825 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1826
1827 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1828
1829 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1830 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1831 $token = htmlspecialchars( $wgUser->editToken() );
1832
1833 $wgOut->addHTML( "
1834 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1835 <table border='0'>
1836 <tr>
1837 <td align='right'>
1838 <label for='wpReason'>{$delcom}:</label>
1839 </td>
1840 <td align='left'>
1841 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1842 </td>
1843 </tr>
1844 <tr>
1845 <td>&nbsp;</td>
1846 <td>
1847 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1848 </td>
1849 </tr>
1850 </table>
1851 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1852 </form>\n" );
1853
1854 $wgOut->returnToMain( false );
1855 }
1856
1857
1858 /**
1859 * Perform a deletion and output success or failure messages
1860 */
1861 function doDelete( $reason ) {
1862 global $wgOut, $wgUser, $wgContLang;
1863 $fname = 'Article::doDelete';
1864 wfDebug( $fname."\n" );
1865
1866 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1867 if ( $this->doDeleteArticle( $reason ) ) {
1868 $deleted = $this->mTitle->getPrefixedText();
1869
1870 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1871 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1872
1873 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1874 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1875
1876 $wgOut->addWikiText( $text );
1877 $wgOut->returnToMain( false );
1878 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1879 } else {
1880 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1881 }
1882 }
1883 }
1884
1885 /**
1886 * Back-end article deletion
1887 * Deletes the article with database consistency, writes logs, purges caches
1888 * Returns success
1889 */
1890 function doDeleteArticle( $reason ) {
1891 global $wgUser;
1892 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1893 global $wgUseTrackbacks;
1894
1895 $fname = 'Article::doDeleteArticle';
1896 wfDebug( $fname."\n" );
1897
1898 $dbw =& wfGetDB( DB_MASTER );
1899 $ns = $this->mTitle->getNamespace();
1900 $t = $this->mTitle->getDBkey();
1901 $id = $this->mTitle->getArticleID();
1902
1903 if ( $t == '' || $id == 0 ) {
1904 return false;
1905 }
1906
1907 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1908 array_push( $wgDeferredUpdateList, $u );
1909
1910 $linksTo = $this->mTitle->getLinksTo();
1911
1912 # Squid purging
1913 if ( $wgUseSquid ) {
1914 $urls = array(
1915 $this->mTitle->getInternalURL(),
1916 $this->mTitle->getInternalURL( 'history' )
1917 );
1918
1919 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1920 array_push( $wgPostCommitUpdateList, $u );
1921
1922 }
1923
1924 # Client and file cache invalidation
1925 Title::touchArray( $linksTo );
1926
1927
1928 // For now, shunt the revision data into the archive table.
1929 // Text is *not* removed from the text table; bulk storage
1930 // is left intact to avoid breaking block-compression or
1931 // immutable storage schemes.
1932 //
1933 // For backwards compatibility, note that some older archive
1934 // table entries will have ar_text and ar_flags fields still.
1935 //
1936 // In the future, we may keep revisions and mark them with
1937 // the rev_deleted field, which is reserved for this purpose.
1938 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1939 array(
1940 'ar_namespace' => 'page_namespace',
1941 'ar_title' => 'page_title',
1942 'ar_comment' => 'rev_comment',
1943 'ar_user' => 'rev_user',
1944 'ar_user_text' => 'rev_user_text',
1945 'ar_timestamp' => 'rev_timestamp',
1946 'ar_minor_edit' => 'rev_minor_edit',
1947 'ar_rev_id' => 'rev_id',
1948 'ar_text_id' => 'rev_text_id',
1949 ), array(
1950 'page_id' => $id,
1951 'page_id = rev_page'
1952 ), $fname
1953 );
1954
1955 # Now that it's safely backed up, delete it
1956 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1957 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1958
1959 if ($wgUseTrackbacks)
1960 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1961
1962 # Clean up recentchanges entries...
1963 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1964
1965 # Finally, clean up the link tables
1966 $t = $this->mTitle->getPrefixedDBkey();
1967
1968 Article::onArticleDelete( $this->mTitle );
1969
1970 # Delete outgoing links
1971 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1972 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1973 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1974
1975 # Log the deletion
1976 $log = new LogPage( 'delete' );
1977 $log->addEntry( 'delete', $this->mTitle, $reason );
1978
1979 # Clear the cached article id so the interface doesn't act like we exist
1980 $this->mTitle->resetArticleID( 0 );
1981 $this->mTitle->mArticleID = 0;
1982 return true;
1983 }
1984
1985 /**
1986 * Revert a modification
1987 */
1988 function rollback() {
1989 global $wgUser, $wgOut, $wgRequest;
1990 $fname = 'Article::rollback';
1991
1992 if ( ! $wgUser->isAllowed('rollback') ) {
1993 $wgOut->sysopRequired();
1994 return;
1995 }
1996 if ( wfReadOnly() ) {
1997 $wgOut->readOnlyPage( $this->getContent( true ) );
1998 return;
1999 }
2000 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2001 array( $this->mTitle->getPrefixedText(),
2002 $wgRequest->getVal( 'from' ) ) ) ) {
2003 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2004 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2005 return;
2006 }
2007 $dbw =& wfGetDB( DB_MASTER );
2008
2009 # Enhanced rollback, marks edits rc_bot=1
2010 $bot = $wgRequest->getBool( 'bot' );
2011
2012 # Replace all this user's current edits with the next one down
2013 $tt = $this->mTitle->getDBKey();
2014 $n = $this->mTitle->getNamespace();
2015
2016 # Get the last editor, lock table exclusively
2017 $dbw->begin();
2018 $current = Revision::newFromTitle( $this->mTitle );
2019 if( is_null( $current ) ) {
2020 # Something wrong... no page?
2021 $dbw->rollback();
2022 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2023 return;
2024 }
2025
2026 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2027 if( $from != $current->getUserText() ) {
2028 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2029 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2030 htmlspecialchars( $this->mTitle->getPrefixedText()),
2031 htmlspecialchars( $from ),
2032 htmlspecialchars( $current->getUserText() ) ) );
2033 if( $current->getComment() != '') {
2034 $wgOut->addHTML(
2035 wfMsg( 'editcomment',
2036 htmlspecialchars( $current->getComment() ) ) );
2037 }
2038 return;
2039 }
2040
2041 # Get the last edit not by this guy
2042 $user = intval( $current->getUser() );
2043 $user_text = $dbw->addQuotes( $current->getUserText() );
2044 $s = $dbw->selectRow( 'revision',
2045 array( 'rev_id', 'rev_timestamp' ),
2046 array(
2047 'rev_page' => $current->getPage(),
2048 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2049 ), $fname,
2050 array(
2051 'USE INDEX' => 'page_timestamp',
2052 'ORDER BY' => 'rev_timestamp DESC' )
2053 );
2054 if( $s === false ) {
2055 # Something wrong
2056 $dbw->rollback();
2057 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2058 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2059 return;
2060 }
2061
2062 if ( $bot ) {
2063 # Mark all reverted edits as bot
2064 $dbw->update( 'recentchanges',
2065 array( /* SET */
2066 'rc_bot' => 1
2067 ), array( /* WHERE */
2068 'rc_cur_id' => $current->getPage(),
2069 'rc_user_text' => $current->getUserText(),
2070 "rc_timestamp > '{$s->rev_timestamp}'",
2071 ), $fname
2072 );
2073 }
2074
2075 # Save it!
2076 $target = Revision::newFromId( $s->rev_id );
2077 $newcomment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2078
2079 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2080 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2081 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
2082
2083 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
2084 Article::onArticleEdit( $this->mTitle );
2085
2086 $dbw->commit();
2087 $wgOut->returnToMain( false );
2088 }
2089
2090
2091 /**
2092 * Do standard deferred updates after page view
2093 * @private
2094 */
2095 function viewUpdates() {
2096 global $wgDeferredUpdateList, $wgUseEnotif;
2097
2098 if ( 0 != $this->getID() ) {
2099 global $wgDisableCounters;
2100 if( !$wgDisableCounters ) {
2101 Article::incViewCount( $this->getID() );
2102 $u = new SiteStatsUpdate( 1, 0, 0 );
2103 array_push( $wgDeferredUpdateList, $u );
2104 }
2105 }
2106
2107 # Update newtalk status if user is reading their own
2108 # talk page
2109
2110 global $wgUser;
2111 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
2112 $this->mTitle->getText() == $wgUser->getName())
2113 {
2114 if ( $wgUseEnotif ) {
2115 require_once( 'UserTalkUpdate.php' );
2116 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
2117 } else {
2118 $wgUser->setNewtalk(0);
2119 $wgUser->saveNewtalk();
2120 }
2121 } elseif ( $wgUseEnotif ) {
2122 $wgUser->clearNotification( $this->mTitle );
2123 }
2124
2125 }
2126
2127 /**
2128 * Do standard deferred updates after page edit.
2129 * Every 1000th edit, prune the recent changes table.
2130 * @private
2131 * @param string $text
2132 */
2133 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2134 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
2135 global $wgMessageCache, $wgUser, $wgUseEnotif;
2136
2137
2138 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', &$this ) ) {
2139 wfSeedRandom();
2140 if ( 0 == mt_rand( 0, 999 ) ) {
2141 # Periodically flush old entries from the recentchanges table.
2142 global $wgRCMaxAge;
2143
2144 $dbw =& wfGetDB( DB_MASTER );
2145 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2146 $recentchanges = $dbw->tableName( 'recentchanges' );
2147 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2148 $dbw->query( $sql );
2149 }
2150 }
2151
2152 $id = $this->getID();
2153 $title = $this->mTitle->getPrefixedDBkey();
2154 $shortTitle = $this->mTitle->getDBkey();
2155
2156 if ( 0 != $id ) {
2157 $u = new LinksUpdate( $id, $title );
2158 array_push( $wgDeferredUpdateList, $u );
2159 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2160 array_push( $wgDeferredUpdateList, $u );
2161 $u = new SearchUpdate( $id, $title, $text );
2162 array_push( $wgDeferredUpdateList, $u );
2163
2164 # If this is another user's talk page, update newtalk
2165
2166 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2167 if ( $wgUseEnotif ) {
2168 require_once( 'UserTalkUpdate.php' );
2169 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
2170 $minoredit, $timestamp_of_pagechange);
2171 } else {
2172 $other = User::newFromName( $shortTitle );
2173 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2174 // An anonymous user
2175 $other = new User();
2176 $other->setName( $shortTitle );
2177 }
2178 if( $other ) {
2179 $other->setNewtalk(1);
2180 $other->saveNewtalk();
2181 }
2182 }
2183 }
2184
2185 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2186 $wgMessageCache->replace( $shortTitle, $text );
2187 }
2188 }
2189 }
2190
2191 /**
2192 * @todo document this function
2193 * @private
2194 * @param string $oldid Revision ID of this article revision
2195 */
2196 function setOldSubtitle( $oldid=0 ) {
2197 global $wgLang, $wgOut, $wgUser;
2198
2199 $current = ( $oldid == $this->mLatest );
2200 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2201 $sk = $wgUser->getSkin();
2202 $lnk = $current
2203 ? wfMsg( 'currentrevisionlink' )
2204 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2205 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2206 $nextlink = $current
2207 ? wfMsg( 'nextrevision' )
2208 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2209 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2210 $wgOut->setSubtitle( $r );
2211 }
2212
2213 /**
2214 * This function is called right before saving the wikitext,
2215 * so we can do things like signatures and links-in-context.
2216 *
2217 * @param string $text
2218 */
2219 function preSaveTransform( $text ) {
2220 global $wgParser, $wgUser;
2221 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2222 }
2223
2224 /* Caching functions */
2225
2226 /**
2227 * checkLastModified returns true if it has taken care of all
2228 * output to the client that is necessary for this request.
2229 * (that is, it has sent a cached version of the page)
2230 */
2231 function tryFileCache() {
2232 static $called = false;
2233 if( $called ) {
2234 wfDebug( " tryFileCache() -- called twice!?\n" );
2235 return;
2236 }
2237 $called = true;
2238 if($this->isFileCacheable()) {
2239 $touched = $this->mTouched;
2240 $cache = new CacheManager( $this->mTitle );
2241 if($cache->isFileCacheGood( $touched )) {
2242 global $wgOut;
2243 wfDebug( " tryFileCache() - about to load\n" );
2244 $cache->loadFromFileCache();
2245 return true;
2246 } else {
2247 wfDebug( " tryFileCache() - starting buffer\n" );
2248 ob_start( array(&$cache, 'saveToFileCache' ) );
2249 }
2250 } else {
2251 wfDebug( " tryFileCache() - not cacheable\n" );
2252 }
2253 }
2254
2255 /**
2256 * Check if the page can be cached
2257 * @return bool
2258 */
2259 function isFileCacheable() {
2260 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2261 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2262
2263 return $wgUseFileCache
2264 and (!$wgShowIPinHeader)
2265 and ($this->getID() != 0)
2266 and ($wgUser->isAnon())
2267 and (!$wgUser->getNewtalk())
2268 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2269 and (empty( $action ) || $action == 'view')
2270 and (!isset($oldid))
2271 and (!isset($diff))
2272 and (!isset($redirect))
2273 and (!isset($printable))
2274 and (!$this->mRedirectedFrom);
2275 }
2276
2277 /**
2278 * Loads cur_touched and returns a value indicating if it should be used
2279 *
2280 */
2281 function checkTouched() {
2282 $fname = 'Article::checkTouched';
2283 if( !$this->mDataLoaded ) {
2284 $dbr =& $this->getDB();
2285 $data = $this->pageDataFromId( $dbr, $this->getId() );
2286 if( $data ) {
2287 $this->loadPageData( $data );
2288 }
2289 }
2290 return !$this->mIsRedirect;
2291 }
2292
2293 /**
2294 * Edit an article without doing all that other stuff
2295 * The article must already exist; link tables etc
2296 * are not updated, caches are not flushed.
2297 *
2298 * @param string $text text submitted
2299 * @param string $comment comment submitted
2300 * @param bool $minor whereas it's a minor modification
2301 */
2302 function quickEdit( $text, $comment = '', $minor = 0 ) {
2303 $fname = 'Article::quickEdit';
2304 wfProfileIn( $fname );
2305
2306 $dbw =& wfGetDB( DB_MASTER );
2307 $dbw->begin();
2308 $revision = new Revision( array(
2309 'page' => $this->getId(),
2310 'text' => $text,
2311 'comment' => $comment,
2312 'minor_edit' => $minor ? 1 : 0,
2313 ) );
2314 $revisionId = $revision->insertOn( $dbw );
2315 $this->updateRevisionOn( $dbw, $revision );
2316 $dbw->commit();
2317
2318 wfProfileOut( $fname );
2319 }
2320
2321 /**
2322 * Used to increment the view counter
2323 *
2324 * @static
2325 * @param integer $id article id
2326 */
2327 function incViewCount( $id ) {
2328 $id = intval( $id );
2329 global $wgHitcounterUpdateFreq;
2330
2331 $dbw =& wfGetDB( DB_MASTER );
2332 $pageTable = $dbw->tableName( 'page' );
2333 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2334 $acchitsTable = $dbw->tableName( 'acchits' );
2335
2336 if( $wgHitcounterUpdateFreq <= 1 ){ //
2337 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2338 return;
2339 }
2340
2341 # Not important enough to warrant an error page in case of failure
2342 $oldignore = $dbw->ignoreErrors( true );
2343
2344 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2345
2346 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2347 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2348 # Most of the time (or on SQL errors), skip row count check
2349 $dbw->ignoreErrors( $oldignore );
2350 return;
2351 }
2352
2353 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2354 $row = $dbw->fetchObject( $res );
2355 $rown = intval( $row->n );
2356 if( $rown >= $wgHitcounterUpdateFreq ){
2357 wfProfileIn( 'Article::incViewCount-collect' );
2358 $old_user_abort = ignore_user_abort( true );
2359
2360 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2361 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2362 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2363 'GROUP BY hc_id');
2364 $dbw->query("DELETE FROM $hitcounterTable");
2365 $dbw->query('UNLOCK TABLES');
2366 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2367 'WHERE page_id = hc_id');
2368 $dbw->query("DROP TABLE $acchitsTable");
2369
2370 ignore_user_abort( $old_user_abort );
2371 wfProfileOut( 'Article::incViewCount-collect' );
2372 }
2373 $dbw->ignoreErrors( $oldignore );
2374 }
2375
2376 /**#@+
2377 * The onArticle*() functions are supposed to be a kind of hooks
2378 * which should be called whenever any of the specified actions
2379 * are done.
2380 *
2381 * This is a good place to put code to clear caches, for instance.
2382 *
2383 * This is called on page move and undelete, as well as edit
2384 * @static
2385 * @param $title_obj a title object
2386 */
2387
2388 function onArticleCreate($title_obj) {
2389 global $wgUseSquid, $wgPostCommitUpdateList;
2390
2391 $title_obj->touchLinks();
2392 $titles = $title_obj->getLinksTo();
2393
2394 # Purge squid
2395 if ( $wgUseSquid ) {
2396 $urls = $title_obj->getSquidURLs();
2397 foreach ( $titles as $linkTitle ) {
2398 $urls[] = $linkTitle->getInternalURL();
2399 }
2400 $u = new SquidUpdate( $urls );
2401 array_push( $wgPostCommitUpdateList, $u );
2402 }
2403 }
2404
2405 function onArticleDelete( $title ) {
2406 global $wgMessageCache;
2407
2408 $title->touchLinks();
2409
2410 if( $title->getNamespace() == NS_MEDIAWIKI) {
2411 $wgMessageCache->replace( $title->getDBkey(), false );
2412 }
2413 }
2414
2415 function onArticleEdit($title_obj) {
2416 // This would be an appropriate place to purge caches.
2417 // Why's this not in here now?
2418 }
2419
2420 /**#@-*/
2421
2422 /**
2423 * Info about this page
2424 * Called for ?action=info when $wgAllowPageInfo is on.
2425 *
2426 * @access public
2427 */
2428 function info() {
2429 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2430 $fname = 'Article::info';
2431
2432 if ( !$wgAllowPageInfo ) {
2433 $wgOut->setStatusCode( 400 );
2434 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2435 return;
2436 }
2437
2438 $page = $this->mTitle->getSubjectPage();
2439
2440 $wgOut->setPagetitle( $page->getPrefixedText() );
2441 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2442
2443 # first, see if the page exists at all.
2444 $exists = $page->getArticleId() != 0;
2445 if( !$exists ) {
2446 $wgOut->addHTML( wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2447 } else {
2448 $dbr =& $this->getDB( DB_SLAVE );
2449 $wl_clause = array(
2450 'wl_title' => $page->getDBkey(),
2451 'wl_namespace' => $page->getNamespace() );
2452 $numwatchers = $dbr->selectField(
2453 'watchlist',
2454 'COUNT(*)',
2455 $wl_clause,
2456 $fname,
2457 $this->getSelectOptions() );
2458
2459 $pageInfo = $this->pageCountInfo( $page );
2460 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2461
2462 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2463 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2464 if( $talkInfo ) {
2465 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2466 }
2467 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2468 if( $talkInfo ) {
2469 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2470 }
2471 $wgOut->addHTML( '</ul>' );
2472
2473 }
2474 }
2475
2476 /**
2477 * Return the total number of edits and number of unique editors
2478 * on a given page. If page does not exist, returns false.
2479 *
2480 * @param Title $title
2481 * @return array
2482 * @access private
2483 */
2484 function pageCountInfo( $title ) {
2485 $id = $title->getArticleId();
2486 if( $id == 0 ) {
2487 return false;
2488 }
2489
2490 $dbr =& $this->getDB( DB_SLAVE );
2491
2492 $rev_clause = array( 'rev_page' => $id );
2493 $fname = 'Article::pageCountInfo';
2494
2495 $edits = $dbr->selectField(
2496 'revision',
2497 'COUNT(rev_page)',
2498 $rev_clause,
2499 $fname,
2500 $this->getSelectOptions() );
2501
2502 $authors = $dbr->selectField(
2503 'revision',
2504 'COUNT(DISTINCT rev_user_text)',
2505 $rev_clause,
2506 $fname,
2507 $this->getSelectOptions() );
2508
2509 return array( 'edits' => $edits, 'authors' => $authors );
2510 }
2511
2512 /**
2513 * Return a list of templates used by this article.
2514 * Uses the links table to find the templates
2515 *
2516 * @return array
2517 */
2518 function getUsedTemplates() {
2519 $result = array();
2520 $id = $this->mTitle->getArticleID();
2521
2522 $db =& wfGetDB( DB_SLAVE );
2523 $res = $db->select( array( 'pagelinks' ),
2524 array( 'pl_title' ),
2525 array(
2526 'pl_from' => $id,
2527 'pl_namespace' => NS_TEMPLATE ),
2528 'Article:getUsedTemplates' );
2529 if ( false !== $res ) {
2530 if ( $db->numRows( $res ) ) {
2531 while ( $row = $db->fetchObject( $res ) ) {
2532 $result[] = $row->pl_title;
2533 }
2534 }
2535 }
2536 $db->freeResult( $res );
2537 return $result;
2538 }
2539 }
2540
2541 ?>