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