* Put a nice style around noarticletext
[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 $sk = $wgUser->getSkin();
764 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
765 'redirect=no' );
766 $s = wfMsg( 'redirectedfrom', $redir );
767 $wgOut->setSubtitle( $s );
768
769 # Can't cache redirects
770 $pcache = false;
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->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1465 return ;
1466 }
1467
1468 $wgOut->setRobotpolicy( 'noindex,follow' );
1469 $revision = $wgRequest->getVal( 'revision' );
1470
1471 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1472
1473 $v = new Validation ;
1474 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1475 $t = $v->showList ( $this ) ;
1476 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1477 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1478 else
1479 $t = $v->validatePageForm ( $this , $revision ) ;
1480
1481 $wgOut->addHTML ( $t ) ;
1482 }
1483
1484 /**
1485 * Add this page to $wgUser's watchlist
1486 */
1487
1488 function watch() {
1489
1490 global $wgUser, $wgOut;
1491
1492 if ( $wgUser->isAnon() ) {
1493 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1494 return;
1495 }
1496 if ( wfReadOnly() ) {
1497 $wgOut->readOnlyPage();
1498 return;
1499 }
1500
1501 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1502
1503 $wgUser->addWatch( $this->mTitle );
1504 $wgUser->saveSettings();
1505
1506 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1507
1508 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1509 $wgOut->setRobotpolicy( 'noindex,follow' );
1510
1511 $link = $this->mTitle->getPrefixedText();
1512 $text = wfMsg( 'addedwatchtext', $link );
1513 $wgOut->addWikiText( $text );
1514 }
1515
1516 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1517 }
1518
1519 /**
1520 * Stop watching a page
1521 */
1522
1523 function unwatch() {
1524
1525 global $wgUser, $wgOut;
1526
1527 if ( $wgUser->isAnon() ) {
1528 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1529 return;
1530 }
1531 if ( wfReadOnly() ) {
1532 $wgOut->readOnlyPage();
1533 return;
1534 }
1535
1536 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1537
1538 $wgUser->removeWatch( $this->mTitle );
1539 $wgUser->saveSettings();
1540
1541 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1542
1543 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1544 $wgOut->setRobotpolicy( 'noindex,follow' );
1545
1546 $link = $this->mTitle->getPrefixedText();
1547 $text = wfMsg( 'removedwatchtext', $link );
1548 $wgOut->addWikiText( $text );
1549 }
1550
1551 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1552 }
1553
1554 /**
1555 * protect a page
1556 */
1557 function protect( $limit = 'sysop' ) {
1558 global $wgUser, $wgOut, $wgRequest;
1559
1560 if ( ! $wgUser->isAllowed('protect') ) {
1561 $wgOut->sysopRequired();
1562 return;
1563 }
1564 if ( wfReadOnly() ) {
1565 $wgOut->readOnlyPage();
1566 return;
1567 }
1568 $id = $this->mTitle->getArticleID();
1569 if ( 0 == $id ) {
1570 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1571 return;
1572 }
1573
1574 $confirm = $wgRequest->wasPosted() &&
1575 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1576 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1577 $reason = $wgRequest->getText( 'wpReasonProtect' );
1578
1579 if ( $confirm ) {
1580 $dbw =& wfGetDB( DB_MASTER );
1581 $dbw->update( 'page',
1582 array( /* SET */
1583 'page_touched' => $dbw->timestamp(),
1584 'page_restrictions' => (string)$limit
1585 ), array( /* WHERE */
1586 'page_id' => $id
1587 ), 'Article::protect'
1588 );
1589
1590 $restrictions = "move=" . $limit;
1591 if( !$moveonly ) {
1592 $restrictions .= ":edit=" . $limit;
1593 }
1594 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1595
1596 $dbw =& wfGetDB( DB_MASTER );
1597 $dbw->update( 'page',
1598 array( /* SET */
1599 'page_touched' => $dbw->timestamp(),
1600 'page_restrictions' => $restrictions
1601 ), array( /* WHERE */
1602 'page_id' => $id
1603 ), 'Article::protect'
1604 );
1605
1606 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1607
1608 $log = new LogPage( 'protect' );
1609 if ( $limit === '' ) {
1610 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1611 } else {
1612 $log->addEntry( 'protect', $this->mTitle, $reason );
1613 }
1614 $wgOut->redirect( $this->mTitle->getFullURL() );
1615 }
1616 return;
1617 } else {
1618 return $this->confirmProtect( '', '', $limit );
1619 }
1620 }
1621
1622 /**
1623 * Output protection confirmation dialog
1624 */
1625 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1626 global $wgOut, $wgUser;
1627
1628 wfDebug( "Article::confirmProtect\n" );
1629
1630 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1631 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1632
1633 $check = '';
1634 $protcom = '';
1635 $moveonly = '';
1636
1637 if ( $limit === '' ) {
1638 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1639 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1640 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1641 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1642 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1643 } else {
1644 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1645 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1646 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1647 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1648 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1649 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1650 }
1651
1652 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1653 $token = htmlspecialchars( $wgUser->editToken() );
1654
1655 $wgOut->addHTML( "
1656 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1657 <table border='0'>
1658 <tr>
1659 <td align='right'>
1660 <label for='wpReasonProtect'>{$protcom}:</label>
1661 </td>
1662 <td align='left'>
1663 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1664 </td>
1665 </tr>" );
1666 if($moveonly != '') {
1667 $wgOut->AddHTML( "
1668 <tr>
1669 <td align='right'>
1670 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1671 </td>
1672 <td align='left'>
1673 <label for='wpMoveOnly'>{$moveonly}</label>
1674 </td>
1675 </tr> " );
1676 }
1677 $wgOut->addHTML( "
1678 <tr>
1679 <td>&nbsp;</td>
1680 <td>
1681 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1682 </td>
1683 </tr>
1684 </table>
1685 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1686 </form>" );
1687
1688 $wgOut->returnToMain( false );
1689 }
1690
1691 /**
1692 * Unprotect the pages
1693 */
1694 function unprotect() {
1695 return $this->protect( '' );
1696 }
1697
1698 /*
1699 * UI entry point for page deletion
1700 */
1701 function delete() {
1702 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1703 $fname = 'Article::delete';
1704 $confirm = $wgRequest->wasPosted() &&
1705 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1706 $reason = $wgRequest->getText( 'wpReason' );
1707
1708 # This code desperately needs to be totally rewritten
1709
1710 # Check permissions
1711 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1712 $wgOut->sysopRequired();
1713 return;
1714 }
1715 if( wfReadOnly() ) {
1716 $wgOut->readOnlyPage();
1717 return;
1718 }
1719
1720 # Better double-check that it hasn't been deleted yet!
1721 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1722 if( !$this->mTitle->exists() ) {
1723 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1724 return;
1725 }
1726
1727 if( $confirm ) {
1728 $this->doDelete( $reason );
1729 return;
1730 }
1731
1732 # determine whether this page has earlier revisions
1733 # and insert a warning if it does
1734 # we select the text because it might be useful below
1735 $dbr =& $this->getDB();
1736 $ns = $this->mTitle->getNamespace();
1737 $title = $this->mTitle->getDBkey();
1738 $revisions = $dbr->select( array( 'page', 'revision' ),
1739 array( 'rev_id', 'rev_user_text' ),
1740 array(
1741 'page_namespace' => $ns,
1742 'page_title' => $title,
1743 'rev_page = page_id'
1744 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1745 );
1746
1747 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1748 $skin=$wgUser->getSkin();
1749 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1750 $wgOut->addHTML( $skin->historyLink() .'</b>');
1751 }
1752
1753 # Fetch cur_text
1754 $rev = Revision::newFromTitle( $this->mTitle );
1755
1756 # Fetch name(s) of contributors
1757 $rev_name = '';
1758 $all_same_user = true;
1759 while( $row = $dbr->fetchObject( $revisions ) ) {
1760 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1761 $all_same_user = false;
1762 } else {
1763 $rev_name = $row->rev_user_text;
1764 }
1765 }
1766
1767 if( !is_null( $rev ) ) {
1768 # if this is a mini-text, we can paste part of it into the deletion reason
1769 $text = $rev->getText();
1770
1771 #if this is empty, an earlier revision may contain "useful" text
1772 $blanked = false;
1773 if( $text == '' ) {
1774 $prev = $rev->getPrevious();
1775 if( $prev ) {
1776 $text = $prev->getText();
1777 $blanked = true;
1778 }
1779 }
1780
1781 $length = strlen( $text );
1782
1783 # this should not happen, since it is not possible to store an empty, new
1784 # page. Let's insert a standard text in case it does, though
1785 if( $length == 0 && $reason === '' ) {
1786 $reason = wfMsgForContent( 'exblank' );
1787 }
1788
1789 if( $length < 500 && $reason === '' ) {
1790 # comment field=255, let's grep the first 150 to have some user
1791 # space left
1792 global $wgContLang;
1793 $text = $wgContLang->truncate( $text, 150, '...' );
1794
1795 # let's strip out newlines
1796 $text = preg_replace( "/[\n\r]/", '', $text );
1797
1798 if( !$blanked ) {
1799 if( !$all_same_user ) {
1800 $reason = wfMsgForContent( 'excontent', $text );
1801 } else {
1802 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1803 }
1804 } else {
1805 $reason = wfMsgForContent( 'exbeforeblank', $text );
1806 }
1807 }
1808 }
1809
1810 return $this->confirmDelete( '', $reason );
1811 }
1812
1813 /**
1814 * Output deletion confirmation dialog
1815 */
1816 function confirmDelete( $par, $reason ) {
1817 global $wgOut, $wgUser;
1818
1819 wfDebug( "Article::confirmDelete\n" );
1820
1821 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1822 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1823 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1824 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1825
1826 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1827
1828 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1829 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1830 $token = htmlspecialchars( $wgUser->editToken() );
1831
1832 $wgOut->addHTML( "
1833 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1834 <table border='0'>
1835 <tr>
1836 <td align='right'>
1837 <label for='wpReason'>{$delcom}:</label>
1838 </td>
1839 <td align='left'>
1840 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1841 </td>
1842 </tr>
1843 <tr>
1844 <td>&nbsp;</td>
1845 <td>
1846 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1847 </td>
1848 </tr>
1849 </table>
1850 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1851 </form>\n" );
1852
1853 $wgOut->returnToMain( false );
1854 }
1855
1856
1857 /**
1858 * Perform a deletion and output success or failure messages
1859 */
1860 function doDelete( $reason ) {
1861 global $wgOut, $wgUser, $wgContLang;
1862 $fname = 'Article::doDelete';
1863 wfDebug( $fname."\n" );
1864
1865 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1866 if ( $this->doDeleteArticle( $reason ) ) {
1867 $deleted = $this->mTitle->getPrefixedText();
1868
1869 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1870 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1871
1872 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1873 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1874
1875 $wgOut->addWikiText( $text );
1876 $wgOut->returnToMain( false );
1877 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1878 } else {
1879 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1880 }
1881 }
1882 }
1883
1884 /**
1885 * Back-end article deletion
1886 * Deletes the article with database consistency, writes logs, purges caches
1887 * Returns success
1888 */
1889 function doDeleteArticle( $reason ) {
1890 global $wgUser;
1891 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1892 global $wgUseTrackbacks;
1893
1894 $fname = 'Article::doDeleteArticle';
1895 wfDebug( $fname."\n" );
1896
1897 $dbw =& wfGetDB( DB_MASTER );
1898 $ns = $this->mTitle->getNamespace();
1899 $t = $this->mTitle->getDBkey();
1900 $id = $this->mTitle->getArticleID();
1901
1902 if ( $t == '' || $id == 0 ) {
1903 return false;
1904 }
1905
1906 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1907 array_push( $wgDeferredUpdateList, $u );
1908
1909 $linksTo = $this->mTitle->getLinksTo();
1910
1911 # Squid purging
1912 if ( $wgUseSquid ) {
1913 $urls = array(
1914 $this->mTitle->getInternalURL(),
1915 $this->mTitle->getInternalURL( 'history' )
1916 );
1917
1918 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1919 array_push( $wgPostCommitUpdateList, $u );
1920
1921 }
1922
1923 # Client and file cache invalidation
1924 Title::touchArray( $linksTo );
1925
1926
1927 // For now, shunt the revision data into the archive table.
1928 // Text is *not* removed from the text table; bulk storage
1929 // is left intact to avoid breaking block-compression or
1930 // immutable storage schemes.
1931 //
1932 // For backwards compatibility, note that some older archive
1933 // table entries will have ar_text and ar_flags fields still.
1934 //
1935 // In the future, we may keep revisions and mark them with
1936 // the rev_deleted field, which is reserved for this purpose.
1937 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1938 array(
1939 'ar_namespace' => 'page_namespace',
1940 'ar_title' => 'page_title',
1941 'ar_comment' => 'rev_comment',
1942 'ar_user' => 'rev_user',
1943 'ar_user_text' => 'rev_user_text',
1944 'ar_timestamp' => 'rev_timestamp',
1945 'ar_minor_edit' => 'rev_minor_edit',
1946 'ar_rev_id' => 'rev_id',
1947 'ar_text_id' => 'rev_text_id',
1948 ), array(
1949 'page_id' => $id,
1950 'page_id = rev_page'
1951 ), $fname
1952 );
1953
1954 # Now that it's safely backed up, delete it
1955 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1956 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1957
1958 if ($wgUseTrackbacks)
1959 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1960
1961 # Clean up recentchanges entries...
1962 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1963
1964 # Finally, clean up the link tables
1965 $t = $this->mTitle->getPrefixedDBkey();
1966
1967 Article::onArticleDelete( $this->mTitle );
1968
1969 # Delete outgoing links
1970 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1971 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1972 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1973
1974 # Log the deletion
1975 $log = new LogPage( 'delete' );
1976 $log->addEntry( 'delete', $this->mTitle, $reason );
1977
1978 # Clear the cached article id so the interface doesn't act like we exist
1979 $this->mTitle->resetArticleID( 0 );
1980 $this->mTitle->mArticleID = 0;
1981 return true;
1982 }
1983
1984 /**
1985 * Revert a modification
1986 */
1987 function rollback() {
1988 global $wgUser, $wgOut, $wgRequest;
1989 $fname = 'Article::rollback';
1990
1991 if ( ! $wgUser->isAllowed('rollback') ) {
1992 $wgOut->sysopRequired();
1993 return;
1994 }
1995 if ( wfReadOnly() ) {
1996 $wgOut->readOnlyPage( $this->getContent( true ) );
1997 return;
1998 }
1999 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2000 array( $this->mTitle->getPrefixedText(),
2001 $wgRequest->getVal( 'from' ) ) ) ) {
2002 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2003 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2004 return;
2005 }
2006 $dbw =& wfGetDB( DB_MASTER );
2007
2008 # Enhanced rollback, marks edits rc_bot=1
2009 $bot = $wgRequest->getBool( 'bot' );
2010
2011 # Replace all this user's current edits with the next one down
2012 $tt = $this->mTitle->getDBKey();
2013 $n = $this->mTitle->getNamespace();
2014
2015 # Get the last editor, lock table exclusively
2016 $dbw->begin();
2017 $current = Revision::newFromTitle( $this->mTitle );
2018 if( is_null( $current ) ) {
2019 # Something wrong... no page?
2020 $dbw->rollback();
2021 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2022 return;
2023 }
2024
2025 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2026 if( $from != $current->getUserText() ) {
2027 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2028 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2029 htmlspecialchars( $this->mTitle->getPrefixedText()),
2030 htmlspecialchars( $from ),
2031 htmlspecialchars( $current->getUserText() ) ) );
2032 if( $current->getComment() != '') {
2033 $wgOut->addHTML(
2034 wfMsg( 'editcomment',
2035 htmlspecialchars( $current->getComment() ) ) );
2036 }
2037 return;
2038 }
2039
2040 # Get the last edit not by this guy
2041 $user = intval( $current->getUser() );
2042 $user_text = $dbw->addQuotes( $current->getUserText() );
2043 $s = $dbw->selectRow( 'revision',
2044 array( 'rev_id', 'rev_timestamp' ),
2045 array(
2046 'rev_page' => $current->getPage(),
2047 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2048 ), $fname,
2049 array(
2050 'USE INDEX' => 'page_timestamp',
2051 'ORDER BY' => 'rev_timestamp DESC' )
2052 );
2053 if( $s === false ) {
2054 # Something wrong
2055 $dbw->rollback();
2056 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2057 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2058 return;
2059 }
2060
2061 if ( $bot ) {
2062 # Mark all reverted edits as bot
2063 $dbw->update( 'recentchanges',
2064 array( /* SET */
2065 'rc_bot' => 1
2066 ), array( /* WHERE */
2067 'rc_cur_id' => $current->getPage(),
2068 'rc_user_text' => $current->getUserText(),
2069 "rc_timestamp > '{$s->rev_timestamp}'",
2070 ), $fname
2071 );
2072 }
2073
2074 # Save it!
2075 $target = Revision::newFromId( $s->rev_id );
2076 $newcomment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2077
2078 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2079 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2080 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
2081
2082 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
2083 Article::onArticleEdit( $this->mTitle );
2084
2085 $dbw->commit();
2086 $wgOut->returnToMain( false );
2087 }
2088
2089
2090 /**
2091 * Do standard deferred updates after page view
2092 * @private
2093 */
2094 function viewUpdates() {
2095 global $wgDeferredUpdateList, $wgUseEnotif;
2096
2097 if ( 0 != $this->getID() ) {
2098 global $wgDisableCounters;
2099 if( !$wgDisableCounters ) {
2100 Article::incViewCount( $this->getID() );
2101 $u = new SiteStatsUpdate( 1, 0, 0 );
2102 array_push( $wgDeferredUpdateList, $u );
2103 }
2104 }
2105
2106 # Update newtalk status if user is reading their own
2107 # talk page
2108
2109 global $wgUser;
2110 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
2111 $this->mTitle->getText() == $wgUser->getName())
2112 {
2113 if ( $wgUseEnotif ) {
2114 require_once( 'UserTalkUpdate.php' );
2115 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
2116 } else {
2117 $wgUser->setNewtalk(0);
2118 $wgUser->saveNewtalk();
2119 }
2120 } elseif ( $wgUseEnotif ) {
2121 $wgUser->clearNotification( $this->mTitle );
2122 }
2123
2124 }
2125
2126 /**
2127 * Do standard deferred updates after page edit.
2128 * Every 1000th edit, prune the recent changes table.
2129 * @private
2130 * @param string $text
2131 */
2132 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2133 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
2134 global $wgMessageCache, $wgUser, $wgUseEnotif;
2135
2136 /*
2137 wfSeedRandom();
2138 if ( 0 == mt_rand( 0, 999 ) ) {
2139 # Periodically flush old entries from the recentchanges table.
2140 global $wgRCMaxAge;
2141 $dbw =& wfGetDB( DB_MASTER );
2142 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2143 $recentchanges = $dbw->tableName( 'recentchanges' );
2144 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2145 //$dbw->query( $sql ); // HACK: disabled for now, slowness
2146
2147 // re-enabled for commit of unrelated live changes -- TS
2148 $dbw->query( $sql );
2149 }
2150 */
2151 $id = $this->getID();
2152 $title = $this->mTitle->getPrefixedDBkey();
2153 $shortTitle = $this->mTitle->getDBkey();
2154
2155 if ( 0 != $id ) {
2156 $u = new LinksUpdate( $id, $title );
2157 array_push( $wgDeferredUpdateList, $u );
2158 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2159 array_push( $wgDeferredUpdateList, $u );
2160 $u = new SearchUpdate( $id, $title, $text );
2161 array_push( $wgDeferredUpdateList, $u );
2162
2163 # If this is another user's talk page, update newtalk
2164
2165 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2166 if ( $wgUseEnotif ) {
2167 require_once( 'UserTalkUpdate.php' );
2168 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
2169 $minoredit, $timestamp_of_pagechange);
2170 } else {
2171 $other = User::newFromName( $shortTitle );
2172 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2173 // An anonymous user
2174 $other = new User();
2175 $other->setName( $shortTitle );
2176 }
2177 if( $other ) {
2178 $other->setNewtalk(1);
2179 $other->saveNewtalk();
2180 }
2181 }
2182 }
2183
2184 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2185 $wgMessageCache->replace( $shortTitle, $text );
2186 }
2187 }
2188 }
2189
2190 /**
2191 * @todo document this function
2192 * @private
2193 * @param string $oldid Revision ID of this article revision
2194 */
2195 function setOldSubtitle( $oldid=0 ) {
2196 global $wgLang, $wgOut, $wgUser;
2197
2198 $current = ( $oldid == $this->mLatest );
2199 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2200 $sk = $wgUser->getSkin();
2201 $lnk = $current
2202 ? wfMsg( 'currentrevisionlink' )
2203 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2204 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2205 $nextlink = $current
2206 ? wfMsg( 'nextrevision' )
2207 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2208 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2209 $wgOut->setSubtitle( $r );
2210 }
2211
2212 /**
2213 * This function is called right before saving the wikitext,
2214 * so we can do things like signatures and links-in-context.
2215 *
2216 * @param string $text
2217 */
2218 function preSaveTransform( $text ) {
2219 global $wgParser, $wgUser;
2220 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2221 }
2222
2223 /* Caching functions */
2224
2225 /**
2226 * checkLastModified returns true if it has taken care of all
2227 * output to the client that is necessary for this request.
2228 * (that is, it has sent a cached version of the page)
2229 */
2230 function tryFileCache() {
2231 static $called = false;
2232 if( $called ) {
2233 wfDebug( " tryFileCache() -- called twice!?\n" );
2234 return;
2235 }
2236 $called = true;
2237 if($this->isFileCacheable()) {
2238 $touched = $this->mTouched;
2239 $cache = new CacheManager( $this->mTitle );
2240 if($cache->isFileCacheGood( $touched )) {
2241 global $wgOut;
2242 wfDebug( " tryFileCache() - about to load\n" );
2243 $cache->loadFromFileCache();
2244 return true;
2245 } else {
2246 wfDebug( " tryFileCache() - starting buffer\n" );
2247 ob_start( array(&$cache, 'saveToFileCache' ) );
2248 }
2249 } else {
2250 wfDebug( " tryFileCache() - not cacheable\n" );
2251 }
2252 }
2253
2254 /**
2255 * Check if the page can be cached
2256 * @return bool
2257 */
2258 function isFileCacheable() {
2259 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2260 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2261
2262 return $wgUseFileCache
2263 and (!$wgShowIPinHeader)
2264 and ($this->getID() != 0)
2265 and ($wgUser->isAnon())
2266 and (!$wgUser->getNewtalk())
2267 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2268 and (empty( $action ) || $action == 'view')
2269 and (!isset($oldid))
2270 and (!isset($diff))
2271 and (!isset($redirect))
2272 and (!isset($printable))
2273 and (!$this->mRedirectedFrom);
2274 }
2275
2276 /**
2277 * Loads cur_touched and returns a value indicating if it should be used
2278 *
2279 */
2280 function checkTouched() {
2281 $fname = 'Article::checkTouched';
2282 if( !$this->mDataLoaded ) {
2283 $dbr =& $this->getDB();
2284 $data = $this->pageDataFromId( $dbr, $this->getId() );
2285 if( $data ) {
2286 $this->loadPageData( $data );
2287 }
2288 }
2289 return !$this->mIsRedirect;
2290 }
2291
2292 /**
2293 * Edit an article without doing all that other stuff
2294 * The article must already exist; link tables etc
2295 * are not updated, caches are not flushed.
2296 *
2297 * @param string $text text submitted
2298 * @param string $comment comment submitted
2299 * @param bool $minor whereas it's a minor modification
2300 */
2301 function quickEdit( $text, $comment = '', $minor = 0 ) {
2302 $fname = 'Article::quickEdit';
2303 wfProfileIn( $fname );
2304
2305 $dbw =& wfGetDB( DB_MASTER );
2306 $dbw->begin();
2307 $revision = new Revision( array(
2308 'page' => $this->getId(),
2309 'text' => $text,
2310 'comment' => $comment,
2311 'minor_edit' => $minor ? 1 : 0,
2312 ) );
2313 $revisionId = $revision->insertOn( $dbw );
2314 $this->updateRevisionOn( $dbw, $revision );
2315 $dbw->commit();
2316
2317 wfProfileOut( $fname );
2318 }
2319
2320 /**
2321 * Used to increment the view counter
2322 *
2323 * @static
2324 * @param integer $id article id
2325 */
2326 function incViewCount( $id ) {
2327 $id = intval( $id );
2328 global $wgHitcounterUpdateFreq;
2329
2330 $dbw =& wfGetDB( DB_MASTER );
2331 $pageTable = $dbw->tableName( 'page' );
2332 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2333 $acchitsTable = $dbw->tableName( 'acchits' );
2334
2335 if( $wgHitcounterUpdateFreq <= 1 ){ //
2336 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2337 return;
2338 }
2339
2340 # Not important enough to warrant an error page in case of failure
2341 $oldignore = $dbw->ignoreErrors( true );
2342
2343 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2344
2345 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2346 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2347 # Most of the time (or on SQL errors), skip row count check
2348 $dbw->ignoreErrors( $oldignore );
2349 return;
2350 }
2351
2352 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2353 $row = $dbw->fetchObject( $res );
2354 $rown = intval( $row->n );
2355 if( $rown >= $wgHitcounterUpdateFreq ){
2356 wfProfileIn( 'Article::incViewCount-collect' );
2357 $old_user_abort = ignore_user_abort( true );
2358
2359 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2360 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2361 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2362 'GROUP BY hc_id');
2363 $dbw->query("DELETE FROM $hitcounterTable");
2364 $dbw->query('UNLOCK TABLES');
2365 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2366 'WHERE page_id = hc_id');
2367 $dbw->query("DROP TABLE $acchitsTable");
2368
2369 ignore_user_abort( $old_user_abort );
2370 wfProfileOut( 'Article::incViewCount-collect' );
2371 }
2372 $dbw->ignoreErrors( $oldignore );
2373 }
2374
2375 /**#@+
2376 * The onArticle*() functions are supposed to be a kind of hooks
2377 * which should be called whenever any of the specified actions
2378 * are done.
2379 *
2380 * This is a good place to put code to clear caches, for instance.
2381 *
2382 * This is called on page move and undelete, as well as edit
2383 * @static
2384 * @param $title_obj a title object
2385 */
2386
2387 function onArticleCreate($title_obj) {
2388 global $wgUseSquid, $wgPostCommitUpdateList;
2389
2390 $title_obj->touchLinks();
2391 $titles = $title_obj->getLinksTo();
2392
2393 # Purge squid
2394 if ( $wgUseSquid ) {
2395 $urls = $title_obj->getSquidURLs();
2396 foreach ( $titles as $linkTitle ) {
2397 $urls[] = $linkTitle->getInternalURL();
2398 }
2399 $u = new SquidUpdate( $urls );
2400 array_push( $wgPostCommitUpdateList, $u );
2401 }
2402 }
2403
2404 function onArticleDelete( $title ) {
2405 global $wgMessageCache;
2406
2407 $title->touchLinks();
2408
2409 if( $title->getNamespace() == NS_MEDIAWIKI) {
2410 $wgMessageCache->replace( $title->getDBkey(), false );
2411 }
2412 }
2413
2414 function onArticleEdit($title_obj) {
2415 // This would be an appropriate place to purge caches.
2416 // Why's this not in here now?
2417 }
2418
2419 /**#@-*/
2420
2421 /**
2422 * Info about this page
2423 * Called for ?action=info when $wgAllowPageInfo is on.
2424 *
2425 * @access public
2426 */
2427 function info() {
2428 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2429 $fname = 'Article::info';
2430
2431 if ( !$wgAllowPageInfo ) {
2432 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2433 return;
2434 }
2435
2436 $page = $this->mTitle->getSubjectPage();
2437
2438 $wgOut->setPagetitle( $page->getPrefixedText() );
2439 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2440
2441 # first, see if the page exists at all.
2442 $exists = $page->getArticleId() != 0;
2443 if( !$exists ) {
2444 $wgOut->addHTML( wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2445 } else {
2446 $dbr =& $this->getDB( DB_SLAVE );
2447 $wl_clause = array(
2448 'wl_title' => $page->getDBkey(),
2449 'wl_namespace' => $page->getNamespace() );
2450 $numwatchers = $dbr->selectField(
2451 'watchlist',
2452 'COUNT(*)',
2453 $wl_clause,
2454 $fname,
2455 $this->getSelectOptions() );
2456
2457 $pageInfo = $this->pageCountInfo( $page );
2458 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2459
2460 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2461 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2462 if( $talkInfo ) {
2463 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2464 }
2465 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2466 if( $talkInfo ) {
2467 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2468 }
2469 $wgOut->addHTML( '</ul>' );
2470
2471 }
2472 }
2473
2474 /**
2475 * Return the total number of edits and number of unique editors
2476 * on a given page. If page does not exist, returns false.
2477 *
2478 * @param Title $title
2479 * @return array
2480 * @access private
2481 */
2482 function pageCountInfo( $title ) {
2483 $id = $title->getArticleId();
2484 if( $id == 0 ) {
2485 return false;
2486 }
2487
2488 $dbr =& $this->getDB( DB_SLAVE );
2489
2490 $rev_clause = array( 'rev_page' => $id );
2491 $fname = 'Article::pageCountInfo';
2492
2493 $edits = $dbr->selectField(
2494 'revision',
2495 'COUNT(rev_page)',
2496 $rev_clause,
2497 $fname,
2498 $this->getSelectOptions() );
2499
2500 $authors = $dbr->selectField(
2501 'revision',
2502 'COUNT(DISTINCT rev_user_text)',
2503 $rev_clause,
2504 $fname,
2505 $this->getSelectOptions() );
2506
2507 return array( 'edits' => $edits, 'authors' => $authors );
2508 }
2509
2510 /**
2511 * Return a list of templates used by this article.
2512 * Uses the links table to find the templates
2513 *
2514 * @return array
2515 */
2516 function getUsedTemplates() {
2517 $result = array();
2518 $id = $this->mTitle->getArticleID();
2519
2520 $db =& wfGetDB( DB_SLAVE );
2521 $res = $db->select( array( 'pagelinks' ),
2522 array( 'pl_title' ),
2523 array(
2524 'pl_from' => $id,
2525 'pl_namespace' => NS_TEMPLATE ),
2526 'Article:getUsedTemplates' );
2527 if ( false !== $res ) {
2528 if ( $db->numRows( $res ) ) {
2529 while ( $row = $db->fetchObject( $res ) ) {
2530 $result[] = $row->pl_title;
2531 }
2532 }
2533 }
2534 $db->freeResult( $res );
2535 return $result;
2536 }
2537 }
2538
2539 ?>