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