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