(Bug 15936) New page's patrol button should always be visible
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
13 *
14 */
15 class Article {
16 /**@{{
17 * @private
18 */
19 var $mComment = ''; //!<
20 var $mContent; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
29 var $mMinorEdit; //!<
30 var $mOldId; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
36 var $mRevision; //!<
37 var $mTimestamp = ''; //!<
38 var $mTitle; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
43 /**@}}*/
44
45 /**
46 * Constructor and clear the article
47 * @param $title Reference to a Title object.
48 * @param $oldId Integer revision ID, null to fetch from request, zero for current
49 */
50 public function __construct( Title $title, $oldId = null ) {
51 $this->mTitle =& $title;
52 $this->mOldId = $oldId;
53 }
54
55 /**
56 * Constructor from an article article
57 * @param $id The article ID to load
58 */
59 public static function newFromID( $id ) {
60 $t = Title::newFromID( $id );
61 return $t == null ? null : new Article( $t );
62 }
63
64 /**
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
68 */
69 public function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom = $from;
71 }
72
73 /**
74 * If this page is a redirect, get its target
75 *
76 * The target will be fetched from the redirect table if possible.
77 * If this page doesn't have an entry there, call insertRedirect()
78 * @return mixed Title object, or null if this page is not a redirect
79 */
80 public function getRedirectTarget() {
81 if( !$this->mTitle || !$this->mTitle->isRedirect() )
82 return null;
83 if( !is_null($this->mRedirectTarget) )
84 return $this->mRedirectTarget;
85 # Query the redirect table
86 $dbr = wfGetDB( DB_SLAVE );
87 $res = $dbr->select( 'redirect',
88 array('rd_namespace', 'rd_title'),
89 array('rd_from' => $this->getID()),
90 __METHOD__
91 );
92 if( $row = $dbr->fetchObject($res) ) {
93 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
94 }
95 # This page doesn't have an entry in the redirect table
96 return $this->mRedirectTarget = $this->insertRedirect();
97 }
98
99 /**
100 * Insert an entry for this page into the redirect table.
101 *
102 * Don't call this function directly unless you know what you're doing.
103 * @return Title object
104 */
105 public function insertRedirect() {
106 $retval = Title::newFromRedirect( $this->getContent() );
107 if( !$retval ) {
108 return null;
109 }
110 $dbw = wfGetDB( DB_MASTER );
111 $dbw->replace( 'redirect', array('rd_from'),
112 array(
113 'rd_from' => $this->getID(),
114 'rd_namespace' => $retval->getNamespace(),
115 'rd_title' => $retval->getDBKey()
116 ),
117 __METHOD__
118 );
119 return $retval;
120 }
121
122 /**
123 * Get the Title object this page redirects to
124 *
125 * @return mixed false, Title of in-wiki target, or string with URL
126 */
127 public function followRedirect() {
128 $text = $this->getContent();
129 return $this->followRedirectText( $text );
130 }
131
132 /**
133 * Get the Title object this text redirects to
134 *
135 * @return mixed false, Title of in-wiki target, or string with URL
136 */
137 public function followRedirectText( $text ) {
138 $rt = Title::newFromRedirect( $text );
139 # process if title object is valid and not special:userlogout
140 if( $rt ) {
141 if( $rt->getInterwiki() != '' ) {
142 if( $rt->isLocal() ) {
143 // Offsite wikis need an HTTP redirect.
144 //
145 // This can be hard to reverse and may produce loops,
146 // so they may be disabled in the site configuration.
147 $source = $this->mTitle->getFullURL( 'redirect=no' );
148 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
149 }
150 } else {
151 if( $rt->getNamespace() == NS_SPECIAL ) {
152 // Gotta handle redirects to special pages differently:
153 // Fill the HTTP response "Location" header and ignore
154 // the rest of the page we're on.
155 //
156 // This can be hard to reverse, so they may be disabled.
157 if( $rt->isSpecial( 'Userlogout' ) ) {
158 // rolleyes
159 } else {
160 return $rt->getFullURL();
161 }
162 }
163 return $rt;
164 }
165 }
166 // No or invalid redirect
167 return false;
168 }
169
170 /**
171 * get the title object of the article
172 */
173 public function getTitle() {
174 return $this->mTitle;
175 }
176
177 /**
178 * Clear the object
179 * @private
180 */
181 public function clear() {
182 $this->mDataLoaded = false;
183 $this->mContentLoaded = false;
184
185 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
186 $this->mRedirectedFrom = null; # Title object if set
187 $this->mRedirectTarget = null; # Title object if set
188 $this->mUserText =
189 $this->mTimestamp = $this->mComment = '';
190 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
191 $this->mTouched = '19700101000000';
192 $this->mForUpdate = false;
193 $this->mIsRedirect = false;
194 $this->mRevIdFetched = 0;
195 $this->mRedirectUrl = false;
196 $this->mLatest = false;
197 $this->mPreparedEdit = false;
198 }
199
200 /**
201 * Note that getContent/loadContent do not follow redirects anymore.
202 * If you need to fetch redirectable content easily, try
203 * the shortcut in Article::followContent()
204 *
205 * @return Return the text of this revision
206 */
207 public function getContent() {
208 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
209 wfProfileIn( __METHOD__ );
210 if( $this->getID() === 0 ) {
211 # If this is a MediaWiki:x message, then load the messages
212 # and return the message value for x.
213 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
214 # If this is a system message, get the default text.
215 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
216 $wgMessageCache->loadAllMessages( $lang );
217 $text = wfMsgGetKey( $message, false, $lang, false );
218 if( wfEmptyMsg( $message, $text ) )
219 $text = '';
220 } else {
221 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
222 }
223 wfProfileOut( __METHOD__ );
224 return $text;
225 } else {
226 $this->loadContent();
227 wfProfileOut( __METHOD__ );
228 return $this->mContent;
229 }
230 }
231
232 /**
233 * Get the text of the current revision. No side-effects...
234 *
235 * @return Return the text of the current revision
236 */
237 public function getRawText() {
238 // Check process cache for current revision
239 if( $this->mContentLoaded && $this->mOldId == 0 ) {
240 return $this->mContent;
241 }
242 $rev = Revision::newFromTitle( $this->mTitle );
243 $text = $rev ? $rev->getRawText() : false;
244 return $text;
245 }
246
247 /**
248 * This function returns the text of a section, specified by a number ($section).
249 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
250 * the first section before any such heading (section 0).
251 *
252 * If a section contains subsections, these are also returned.
253 *
254 * @param $text String: text to look in
255 * @param $section Integer: section number
256 * @return string text of the requested section
257 * @deprecated
258 */
259 public function getSection( $text, $section ) {
260 global $wgParser;
261 return $wgParser->getSection( $text, $section );
262 }
263
264 /**
265 * @return int The oldid of the article that is to be shown, 0 for the
266 * current revision
267 */
268 public function getOldID() {
269 if( is_null( $this->mOldId ) ) {
270 $this->mOldId = $this->getOldIDFromRequest();
271 }
272 return $this->mOldId;
273 }
274
275 /**
276 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
277 *
278 * @return int The old id for the request
279 */
280 public function getOldIDFromRequest() {
281 global $wgRequest;
282 $this->mRedirectUrl = false;
283 $oldid = $wgRequest->getVal( 'oldid' );
284 if( isset( $oldid ) ) {
285 $oldid = intval( $oldid );
286 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
287 $nextid = $this->mTitle->getNextRevisionID( $oldid );
288 if( $nextid ) {
289 $oldid = $nextid;
290 } else {
291 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
292 }
293 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
294 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
295 if( $previd ) {
296 $oldid = $previd;
297 }
298 }
299 }
300 if( !$oldid ) {
301 $oldid = 0;
302 }
303 return $oldid;
304 }
305
306 /**
307 * Load the revision (including text) into this object
308 */
309 function loadContent() {
310 if( $this->mContentLoaded ) return;
311 wfProfileIn( __METHOD__ );
312 # Query variables :P
313 $oldid = $this->getOldID();
314 # Pre-fill content with error message so that if something
315 # fails we'll have something telling us what we intended.
316 $this->mOldId = $oldid;
317 $this->fetchContent( $oldid );
318 wfProfileOut( __METHOD__ );
319 }
320
321
322 /**
323 * Fetch a page record with the given conditions
324 * @param $dbr Database object
325 * @param $conditions Array
326 */
327 protected function pageData( $dbr, $conditions ) {
328 $fields = array(
329 'page_id',
330 'page_namespace',
331 'page_title',
332 'page_restrictions',
333 'page_counter',
334 'page_is_redirect',
335 'page_is_new',
336 'page_random',
337 'page_touched',
338 'page_latest',
339 'page_len',
340 );
341 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
342 $row = $dbr->selectRow(
343 'page',
344 $fields,
345 $conditions,
346 __METHOD__
347 );
348 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
349 return $row ;
350 }
351
352 /**
353 * @param $dbr Database object
354 * @param $title Title object
355 */
356 public function pageDataFromTitle( $dbr, $title ) {
357 return $this->pageData( $dbr, array(
358 'page_namespace' => $title->getNamespace(),
359 'page_title' => $title->getDBkey() ) );
360 }
361
362 /**
363 * @param $dbr Database
364 * @param $id Integer
365 */
366 protected function pageDataFromId( $dbr, $id ) {
367 return $this->pageData( $dbr, array( 'page_id' => $id ) );
368 }
369
370 /**
371 * Set the general counter, title etc data loaded from
372 * some source.
373 *
374 * @param $data Database row object or "fromdb"
375 */
376 public function loadPageData( $data = 'fromdb' ) {
377 if( $data === 'fromdb' ) {
378 $dbr = wfGetDB( DB_MASTER );
379 $data = $this->pageDataFromId( $dbr, $this->getId() );
380 }
381
382 $lc = LinkCache::singleton();
383 if( $data ) {
384 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
385
386 $this->mTitle->mArticleID = $data->page_id;
387
388 # Old-fashioned restrictions
389 $this->mTitle->loadRestrictions( $data->page_restrictions );
390
391 $this->mCounter = $data->page_counter;
392 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
393 $this->mIsRedirect = $data->page_is_redirect;
394 $this->mLatest = $data->page_latest;
395 } else {
396 if( is_object( $this->mTitle ) ) {
397 $lc->addBadLinkObj( $this->mTitle );
398 }
399 $this->mTitle->mArticleID = 0;
400 }
401
402 $this->mDataLoaded = true;
403 }
404
405 /**
406 * Get text of an article from database
407 * Does *NOT* follow redirects.
408 * @param $oldid Int: 0 for whatever the latest revision is
409 * @return string
410 */
411 function fetchContent( $oldid = 0 ) {
412 if( $this->mContentLoaded ) {
413 return $this->mContent;
414 }
415
416 $dbr = wfGetDB( DB_MASTER );
417
418 # Pre-fill content with error message so that if something
419 # fails we'll have something telling us what we intended.
420 $t = $this->mTitle->getPrefixedText();
421 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
422 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
423
424 if( $oldid ) {
425 $revision = Revision::newFromId( $oldid );
426 if( is_null( $revision ) ) {
427 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
428 return false;
429 }
430 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
431 if( !$data ) {
432 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
433 return false;
434 }
435 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
436 $this->loadPageData( $data );
437 } else {
438 if( !$this->mDataLoaded ) {
439 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
440 if( !$data ) {
441 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
442 return false;
443 }
444 $this->loadPageData( $data );
445 }
446 $revision = Revision::newFromId( $this->mLatest );
447 if( is_null( $revision ) ) {
448 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
449 return false;
450 }
451 }
452
453 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
454 // We should instead work with the Revision object when we need it...
455 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
456
457 $this->mUser = $revision->getUser();
458 $this->mUserText = $revision->getUserText();
459 $this->mComment = $revision->getComment();
460 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
461
462 $this->mRevIdFetched = $revision->getId();
463 $this->mContentLoaded = true;
464 $this->mRevision =& $revision;
465
466 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
467
468 return $this->mContent;
469 }
470
471 /**
472 * Read/write accessor to select FOR UPDATE
473 *
474 * @param $x Mixed: FIXME
475 */
476 public function forUpdate( $x = NULL ) {
477 return wfSetVar( $this->mForUpdate, $x );
478 }
479
480 /**
481 * Get the database which should be used for reads
482 *
483 * @return Database
484 * @deprecated - just call wfGetDB( DB_MASTER ) instead
485 */
486 function getDB() {
487 wfDeprecated( __METHOD__ );
488 return wfGetDB( DB_MASTER );
489 }
490
491 /**
492 * Get options for all SELECT statements
493 *
494 * @param $options Array: an optional options array which'll be appended to
495 * the default
496 * @return Array: options
497 */
498 protected function getSelectOptions( $options = '' ) {
499 if( $this->mForUpdate ) {
500 if( is_array( $options ) ) {
501 $options[] = 'FOR UPDATE';
502 } else {
503 $options = 'FOR UPDATE';
504 }
505 }
506 return $options;
507 }
508
509 /**
510 * @return int Page ID
511 */
512 public function getID() {
513 if( $this->mTitle ) {
514 return $this->mTitle->getArticleID();
515 } else {
516 return 0;
517 }
518 }
519
520 /**
521 * @return bool Whether or not the page exists in the database
522 */
523 public function exists() {
524 return $this->getId() > 0;
525 }
526
527 /**
528 * Check if this page is something we're going to be showing
529 * some sort of sensible content for. If we return false, page
530 * views (plain action=view) will return an HTTP 404 response,
531 * so spiders and robots can know they're following a bad link.
532 *
533 * @return bool
534 */
535 public function hasViewableContent() {
536 return $this->exists() || $this->mTitle->isAlwaysKnown();
537 }
538
539 /**
540 * @return int The view count for the page
541 */
542 public function getCount() {
543 if( -1 == $this->mCounter ) {
544 $id = $this->getID();
545 if( $id == 0 ) {
546 $this->mCounter = 0;
547 } else {
548 $dbr = wfGetDB( DB_SLAVE );
549 $this->mCounter = $dbr->selectField( 'page',
550 'page_counter',
551 array( 'page_id' => $id ),
552 __METHOD__,
553 $this->getSelectOptions()
554 );
555 }
556 }
557 return $this->mCounter;
558 }
559
560 /**
561 * Determine whether a page would be suitable for being counted as an
562 * article in the site_stats table based on the title & its content
563 *
564 * @param $text String: text to analyze
565 * @return bool
566 */
567 public function isCountable( $text ) {
568 global $wgUseCommaCount;
569
570 $token = $wgUseCommaCount ? ',' : '[[';
571 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
572 }
573
574 /**
575 * Tests if the article text represents a redirect
576 *
577 * @param $text String: FIXME
578 * @return bool
579 */
580 public function isRedirect( $text = false ) {
581 if( $text === false ) {
582 if( $this->mDataLoaded ) {
583 return $this->mIsRedirect;
584 }
585 // Apparently loadPageData was never called
586 $this->loadContent();
587 $titleObj = Title::newFromRedirect( $this->fetchContent() );
588 } else {
589 $titleObj = Title::newFromRedirect( $text );
590 }
591 return $titleObj !== NULL;
592 }
593
594 /**
595 * Returns true if the currently-referenced revision is the current edit
596 * to this page (and it exists).
597 * @return bool
598 */
599 public function isCurrent() {
600 # If no oldid, this is the current version.
601 if( $this->getOldID() == 0 ) {
602 return true;
603 }
604 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
605 }
606
607 /**
608 * Loads everything except the text
609 * This isn't necessary for all uses, so it's only done if needed.
610 */
611 protected function loadLastEdit() {
612 if( -1 != $this->mUser )
613 return;
614
615 # New or non-existent articles have no user information
616 $id = $this->getID();
617 if( 0 == $id ) return;
618
619 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
620 if( !is_null( $this->mLastRevision ) ) {
621 $this->mUser = $this->mLastRevision->getUser();
622 $this->mUserText = $this->mLastRevision->getUserText();
623 $this->mTimestamp = $this->mLastRevision->getTimestamp();
624 $this->mComment = $this->mLastRevision->getComment();
625 $this->mMinorEdit = $this->mLastRevision->isMinor();
626 $this->mRevIdFetched = $this->mLastRevision->getId();
627 }
628 }
629
630 public function getTimestamp() {
631 // Check if the field has been filled by ParserCache::get()
632 if( !$this->mTimestamp ) {
633 $this->loadLastEdit();
634 }
635 return wfTimestamp(TS_MW, $this->mTimestamp);
636 }
637
638 public function getUser() {
639 $this->loadLastEdit();
640 return $this->mUser;
641 }
642
643 public function getUserText() {
644 $this->loadLastEdit();
645 return $this->mUserText;
646 }
647
648 public function getComment() {
649 $this->loadLastEdit();
650 return $this->mComment;
651 }
652
653 public function getMinorEdit() {
654 $this->loadLastEdit();
655 return $this->mMinorEdit;
656 }
657
658 /* Use this to fetch the rev ID used on page views */
659 public function getRevIdFetched() {
660 $this->loadLastEdit();
661 return $this->mRevIdFetched;
662 }
663
664 /**
665 * @param $limit Integer: default 0.
666 * @param $offset Integer: default 0.
667 */
668 public function getContributors($limit = 0, $offset = 0) {
669 # XXX: this is expensive; cache this info somewhere.
670
671 $contribs = array();
672 $dbr = wfGetDB( DB_SLAVE );
673 $revTable = $dbr->tableName( 'revision' );
674 $userTable = $dbr->tableName( 'user' );
675 $user = $this->getUser();
676 $pageId = $this->getId();
677
678 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
679 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
680 WHERE rev_page = $pageId
681 AND rev_user != $user
682 GROUP BY rev_user, rev_user_text, user_real_name
683 ORDER BY timestamp DESC";
684
685 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
686 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
687
688 $sql .= ' '. $this->getSelectOptions();
689
690 $res = $dbr->query($sql, __METHOD__ );
691
692 return new UserArrayFromResult( $res );
693 }
694
695 /**
696 * This is the default action of the script: just view the page of
697 * the given title.
698 */
699 public function view() {
700 global $wgUser, $wgOut, $wgRequest, $wgContLang;
701 global $wgEnableParserCache, $wgStylePath, $wgParser;
702 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
703 global $wgDefaultRobotPolicy;
704
705 wfProfileIn( __METHOD__ );
706
707 # Get variables from query string
708 $oldid = $this->getOldID();
709
710 # Try file cache
711 if( $oldid === 0 && $this->checkTouched() ) {
712 global $wgUseETag;
713 if( $wgUseETag ) {
714 $parserCache = ParserCache::singleton();
715 $wgOut->setETag( $parserCache->getETag($this,$wgUser) );
716 }
717 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
718 wfProfileOut( __METHOD__ );
719 return;
720 } else if( $this->tryFileCache() ) {
721 # tell wgOut that output is taken care of
722 $wgOut->disable();
723 $this->viewUpdates();
724 wfProfileOut( __METHOD__ );
725 return;
726 }
727 }
728
729 $ns = $this->mTitle->getNamespace(); # shortcut
730 $sk = $wgUser->getSkin();
731
732 # getOldID may want us to redirect somewhere else
733 if( $this->mRedirectUrl ) {
734 $wgOut->redirect( $this->mRedirectUrl );
735 wfProfileOut( __METHOD__ );
736 return;
737 }
738
739 $diff = $wgRequest->getVal( 'diff' );
740 $rcid = $wgRequest->getVal( 'rcid' );
741 $rdfrom = $wgRequest->getVal( 'rdfrom' );
742 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
743 $purge = $wgRequest->getVal( 'action' ) == 'purge';
744 $return404 = false;
745
746 $wgOut->setArticleFlag( true );
747
748 # Discourage indexing of printable versions, but encourage following
749 if( $wgOut->isPrintable() ) {
750 $policy = 'noindex,follow';
751 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
752 $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
753 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
754 # Honour customised robot policies for this namespace
755 $policy = $wgNamespaceRobotPolicies[$ns];
756 } else {
757 $policy = $wgDefaultRobotPolicy;
758 }
759 $wgOut->setRobotPolicy( $policy );
760
761 # If we got diff and oldid in the query, we want to see a
762 # diff page instead of the article.
763
764 if( !is_null( $diff ) ) {
765 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
766
767 $diff = $wgRequest->getVal( 'diff' );
768 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
769 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff);
770 // DifferenceEngine directly fetched the revision:
771 $this->mRevIdFetched = $de->mNewid;
772 $de->showDiffPage( $diffOnly );
773
774 // Needed to get the page's current revision
775 $this->loadPageData();
776 if( $diff == 0 || $diff == $this->mLatest ) {
777 # Run view updates for current revision only
778 $this->viewUpdates();
779 }
780 wfProfileOut( __METHOD__ );
781 return;
782 }
783
784 if( $ns == NS_USER || $ns == NS_USER_TALK ) {
785 # User/User_talk subpages are not modified. (bug 11443)
786 if( !$this->mTitle->isSubpage() ) {
787 $block = new Block();
788 if( $block->load( $this->mTitle->getBaseText() ) ) {
789 $wgOut->setRobotpolicy( 'noindex,nofollow' );
790 }
791 }
792 }
793
794 # Should the parser cache be used?
795 $pcache = $this->useParserCache( $oldid );
796 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
797 if( $wgUser->getOption( 'stubthreshold' ) ) {
798 wfIncrStats( 'pcache_miss_stub' );
799 }
800
801 $wasRedirected = false;
802 if( isset( $this->mRedirectedFrom ) ) {
803 // This is an internally redirected page view.
804 // We'll need a backlink to the source page for navigation.
805 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
806 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
807 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
808 $wgOut->setSubtitle( $s );
809
810 // Set the fragment if one was specified in the redirect
811 if( strval( $this->mTitle->getFragment() ) != '' ) {
812 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
813 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
814 }
815 $wasRedirected = true;
816 }
817 } elseif( !empty( $rdfrom ) ) {
818 // This is an externally redirected view, from some other wiki.
819 // If it was reported from a trusted site, supply a backlink.
820 global $wgRedirectSources;
821 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
822 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
823 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
824 $wgOut->setSubtitle( $s );
825 $wasRedirected = true;
826 }
827 }
828
829 $outputDone = false;
830 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
831 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
832 // Ensure that UI elements requiring revision ID have
833 // the correct version information.
834 $wgOut->setRevisionId( $this->mLatest );
835 $outputDone = true;
836 }
837 # Fetch content and check for errors
838 if( !$outputDone ) {
839 # If the article does not exist and was deleted, show the log
840 if( $this->getID() == 0 ) {
841 $this->showDeletionLog();
842 }
843 $text = $this->getContent();
844 // For now, check also for ID until getContent actually returns
845 // false for pages that do not exists
846 if( $text === false || $this->getID() === 0 ) {
847 # Failed to load, replace text with error message
848 $t = $this->mTitle->getPrefixedText();
849 if( $oldid ) {
850 $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
851 $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
852 } else {
853 $text = wfMsgExt( 'noarticletext', 'parsemag' );
854 }
855 }
856
857 # Non-existent pages
858 if( $this->getID() === 0 ) {
859 $wgOut->setRobotPolicy( 'noindex,nofollow' );
860 $text = "<div class='noarticletext'>\n$text\n</div>";
861 if( !$this->hasViewableContent() ) {
862 // If there's no backing content, send a 404 Not Found
863 // for better machine handling of broken links.
864 $return404 = true;
865 }
866 }
867
868 if( $return404 ) {
869 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
870 }
871
872 # Another whitelist check in case oldid is altering the title
873 if( !$this->mTitle->userCanRead() ) {
874 $wgOut->loginToUse();
875 $wgOut->output();
876 $wgOut->disable();
877 wfProfileOut( __METHOD__ );
878 return;
879 }
880
881 # For ?curid=x urls, disallow indexing
882 if( $wgRequest->getInt('curid') )
883 $wgOut->setRobotPolicy( 'noindex,follow' );
884
885 # We're looking at an old revision
886 if( !empty( $oldid ) ) {
887 $wgOut->setRobotPolicy( 'noindex,nofollow' );
888 if( is_null( $this->mRevision ) ) {
889 // FIXME: This would be a nice place to load the 'no such page' text.
890 } else {
891 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
892 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
893 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
894 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
895 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
896 wfProfileOut( __METHOD__ );
897 return;
898 } else {
899 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
900 // and we are allowed to see...
901 }
902 }
903 }
904 }
905
906 $wgOut->setRevisionId( $this->getRevIdFetched() );
907
908 // Pages containing custom CSS or JavaScript get special treatment
909 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
910 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
911 // Give hooks a chance to customise the output
912 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
913 // Wrap the whole lot in a <pre> and don't parse
914 $m = array();
915 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
916 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
917 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
918 $wgOut->addHTML( "\n</pre>\n" );
919 }
920 } else if( $rt = Title::newFromRedirect( $text ) ) {
921 # Don't append the subtitle if this was an old revision
922 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
923 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
924 $wgOut->addParserOutputNoText( $parseout );
925 } else if( $pcache ) {
926 # Display content and save to parser cache
927 $this->outputWikiText( $text );
928 } else {
929 # Display content, don't attempt to save to parser cache
930 # Don't show section-edit links on old revisions... this way lies madness.
931 if( !$this->isCurrent() ) {
932 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
933 }
934 # Display content and don't save to parser cache
935 # With timing hack -- TS 2006-07-26
936 $time = -wfTime();
937 $this->outputWikiText( $text, false );
938 $time += wfTime();
939
940 # Timing hack
941 if( $time > 3 ) {
942 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
943 $this->mTitle->getPrefixedDBkey()));
944 }
945
946 if( !$this->isCurrent() ) {
947 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
948 }
949 }
950 }
951 /* title may have been set from the cache */
952 $t = $wgOut->getPageTitle();
953 if( empty( $t ) ) {
954 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
955
956 # For the main page, overwrite the <title> element with the con-
957 # tents of 'pagetitle-view-mainpage' instead of the default (if
958 # that's not empty).
959 if( $this->mTitle->equals( Title::newMainPage() ) &&
960 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
961 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
962 }
963 }
964
965 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
966 if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
967 $wgOut->addWikiMsg('anontalkpagetext');
968 }
969
970 # Only diffs and new page links from RC give rcid params, so if
971 # we are just viewing the page normally with no rcid, try to find it.
972 # This is more convenient for users.
973 if( empty($rcid) && $this->mTitle->userCan('patrol') ) {
974 $firstRev = $this->mTitle->getFirstRevision();
975 $rcid = $firstRev->isUnpatrolled();
976 }
977 # If we have been passed an &rcid= parameter, we want to give the user a
978 # chance to mark this new article as patrolled.
979 if( !empty($rcid) && $this->mTitle->exists() && $this->mTitle->userCan('patrol') ) {
980 $wgOut->addHTML(
981 "<div class='patrollink'>" .
982 wfMsgHtml( 'markaspatrolledlink',
983 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
984 "action=markpatrolled&rcid=$rcid" )
985 ) .
986 '</div>'
987 );
988 }
989
990 # Trackbacks
991 if( $wgUseTrackbacks ) {
992 $this->addTrackbacks();
993 }
994
995 $this->viewUpdates();
996 wfProfileOut( __METHOD__ );
997 }
998
999 protected function showDeletionLog() {
1000 global $wgUser, $wgOut;
1001 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1002 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
1003 if( $pager->getNumRows() > 0 ) {
1004 $pager->mLimit = 10;
1005 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1006 $wgOut->addWikiMsg( 'deleted-notice' );
1007 $wgOut->addHTML(
1008 $loglist->beginLogEventsList() .
1009 $pager->getBody() .
1010 $loglist->endLogEventsList()
1011 );
1012 if( $pager->getNumRows() > 10 ) {
1013 $wgOut->addHTML( $wgUser->getSkin()->link(
1014 SpecialPage::getTitleFor( 'Log' ),
1015 wfMsgHtml( 'deletelog-fulllog' ),
1016 array(),
1017 array( 'type' => 'delete', 'page' => $this->mTitle->getPrefixedText() )
1018 ) );
1019 }
1020 $wgOut->addHTML( '</div>' );
1021 }
1022 }
1023
1024 /*
1025 * Should the parser cache be used?
1026 */
1027 protected function useParserCache( $oldid ) {
1028 global $wgUser, $wgEnableParserCache;
1029
1030 return $wgEnableParserCache
1031 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1032 && $this->exists()
1033 && empty( $oldid )
1034 && !$this->mTitle->isCssOrJsPage()
1035 && !$this->mTitle->isCssJsSubpage();
1036 }
1037
1038 /**
1039 * View redirect
1040 * @param $target Title object of destination to redirect
1041 * @param $appendSubtitle Boolean [optional]
1042 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1043 */
1044 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1045 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1046 # Display redirect
1047 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1048 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
1049
1050 if( $appendSubtitle ) {
1051 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1052 }
1053 $sk = $wgUser->getSkin();
1054 if( $forceKnown ) {
1055 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1056 } else {
1057 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1058 }
1059 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1060 '<span class="redirectText">'.$link.'</span>';
1061
1062 }
1063
1064 public function addTrackbacks() {
1065 global $wgOut, $wgUser;
1066 $dbr = wfGetDB( DB_SLAVE );
1067 $tbs = $dbr->select( 'trackbacks',
1068 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1069 array('tb_page' => $this->getID() )
1070 );
1071 if( !$dbr->numRows($tbs) ) return;
1072
1073 $tbtext = "";
1074 while( $o = $dbr->fetchObject($tbs) ) {
1075 $rmvtxt = "";
1076 if( $wgUser->isAllowed( 'trackback' ) ) {
1077 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1078 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1079 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1080 }
1081 $tbtext .= "\n";
1082 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1083 $o->tb_title,
1084 $o->tb_url,
1085 $o->tb_ex,
1086 $o->tb_name,
1087 $rmvtxt);
1088 }
1089 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1090 $this->mTitle->invalidateCache();
1091 }
1092
1093 public function deletetrackback() {
1094 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1095 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1096 $wgOut->addWikiMsg( 'sessionfailure' );
1097 return;
1098 }
1099
1100 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1101 if( count($permission_errors) ) {
1102 $wgOut->showPermissionsErrorPage( $permission_errors );
1103 return;
1104 }
1105
1106 $db = wfGetDB( DB_MASTER );
1107 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1108
1109 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1110 $this->mTitle->invalidateCache();
1111 }
1112
1113 public function render() {
1114 global $wgOut;
1115 $wgOut->setArticleBodyOnly(true);
1116 $this->view();
1117 }
1118
1119 /**
1120 * Handle action=purge
1121 */
1122 public function purge() {
1123 global $wgUser, $wgRequest, $wgOut;
1124 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1125 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1126 $this->doPurge();
1127 $this->view();
1128 }
1129 } else {
1130 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1131 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1132 $form = "<form method=\"post\" action=\"$action\">\n" .
1133 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1134 "</form>\n";
1135 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1136 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1137 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1138 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1139 $wgOut->addHTML( $top . $form . $bottom );
1140 }
1141 }
1142
1143 /**
1144 * Perform the actions of a page purging
1145 */
1146 public function doPurge() {
1147 global $wgUseSquid;
1148 // Invalidate the cache
1149 $this->mTitle->invalidateCache();
1150
1151 if( $wgUseSquid ) {
1152 // Commit the transaction before the purge is sent
1153 $dbw = wfGetDB( DB_MASTER );
1154 $dbw->immediateCommit();
1155
1156 // Send purge
1157 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1158 $update->doUpdate();
1159 }
1160 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1161 global $wgMessageCache;
1162 if( $this->getID() == 0 ) {
1163 $text = false;
1164 } else {
1165 $text = $this->getRawText();
1166 }
1167 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1168 }
1169 }
1170
1171 /**
1172 * Insert a new empty page record for this article.
1173 * This *must* be followed up by creating a revision
1174 * and running $this->updateToLatest( $rev_id );
1175 * or else the record will be left in a funky state.
1176 * Best if all done inside a transaction.
1177 *
1178 * @param $dbw Database
1179 * @return int The newly created page_id key, or false if the title already existed
1180 * @private
1181 */
1182 public function insertOn( $dbw ) {
1183 wfProfileIn( __METHOD__ );
1184
1185 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1186 $dbw->insert( 'page', array(
1187 'page_id' => $page_id,
1188 'page_namespace' => $this->mTitle->getNamespace(),
1189 'page_title' => $this->mTitle->getDBkey(),
1190 'page_counter' => 0,
1191 'page_restrictions' => '',
1192 'page_is_redirect' => 0, # Will set this shortly...
1193 'page_is_new' => 1,
1194 'page_random' => wfRandom(),
1195 'page_touched' => $dbw->timestamp(),
1196 'page_latest' => 0, # Fill this in shortly...
1197 'page_len' => 0, # Fill this in shortly...
1198 ), __METHOD__, 'IGNORE' );
1199
1200 $affected = $dbw->affectedRows();
1201 if( $affected ) {
1202 $newid = $dbw->insertId();
1203 $this->mTitle->resetArticleId( $newid );
1204 }
1205 wfProfileOut( __METHOD__ );
1206 return $affected ? $newid : false;
1207 }
1208
1209 /**
1210 * Update the page record to point to a newly saved revision.
1211 *
1212 * @param $dbw Database object
1213 * @param $revision Revision: For ID number, and text used to set
1214 length and redirect status fields
1215 * @param $lastRevision Integer: if given, will not overwrite the page field
1216 * when different from the currently set value.
1217 * Giving 0 indicates the new page flag should be set
1218 * on.
1219 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1220 * removing rows in redirect table.
1221 * @return bool true on success, false on failure
1222 * @private
1223 */
1224 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1225 wfProfileIn( __METHOD__ );
1226
1227 $text = $revision->getText();
1228 $rt = Title::newFromRedirect( $text );
1229
1230 $conditions = array( 'page_id' => $this->getId() );
1231 if( !is_null( $lastRevision ) ) {
1232 # An extra check against threads stepping on each other
1233 $conditions['page_latest'] = $lastRevision;
1234 }
1235
1236 $dbw->update( 'page',
1237 array( /* SET */
1238 'page_latest' => $revision->getId(),
1239 'page_touched' => $dbw->timestamp(),
1240 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1241 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1242 'page_len' => strlen( $text ),
1243 ),
1244 $conditions,
1245 __METHOD__ );
1246
1247 $result = $dbw->affectedRows() != 0;
1248 if( $result ) {
1249 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1250 }
1251
1252 wfProfileOut( __METHOD__ );
1253 return $result;
1254 }
1255
1256 /**
1257 * Add row to the redirect table if this is a redirect, remove otherwise.
1258 *
1259 * @param $dbw Database
1260 * @param $redirectTitle a title object pointing to the redirect target,
1261 * or NULL if this is not a redirect
1262 * @param $lastRevIsRedirect If given, will optimize adding and
1263 * removing rows in redirect table.
1264 * @return bool true on success, false on failure
1265 * @private
1266 */
1267 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1268 // Always update redirects (target link might have changed)
1269 // Update/Insert if we don't know if the last revision was a redirect or not
1270 // Delete if changing from redirect to non-redirect
1271 $isRedirect = !is_null($redirectTitle);
1272 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1273 wfProfileIn( __METHOD__ );
1274 if( $isRedirect ) {
1275 // This title is a redirect, Add/Update row in the redirect table
1276 $set = array( /* SET */
1277 'rd_namespace' => $redirectTitle->getNamespace(),
1278 'rd_title' => $redirectTitle->getDBkey(),
1279 'rd_from' => $this->getId(),
1280 );
1281 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1282 } else {
1283 // This is not a redirect, remove row from redirect table
1284 $where = array( 'rd_from' => $this->getId() );
1285 $dbw->delete( 'redirect', $where, __METHOD__);
1286 }
1287 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1288 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1289 }
1290 wfProfileOut( __METHOD__ );
1291 return ( $dbw->affectedRows() != 0 );
1292 }
1293 return true;
1294 }
1295
1296 /**
1297 * If the given revision is newer than the currently set page_latest,
1298 * update the page record. Otherwise, do nothing.
1299 *
1300 * @param $dbw Database object
1301 * @param $revision Revision object
1302 */
1303 public function updateIfNewerOn( &$dbw, $revision ) {
1304 wfProfileIn( __METHOD__ );
1305 $row = $dbw->selectRow(
1306 array( 'revision', 'page' ),
1307 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1308 array(
1309 'page_id' => $this->getId(),
1310 'page_latest=rev_id' ),
1311 __METHOD__ );
1312 if( $row ) {
1313 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1314 wfProfileOut( __METHOD__ );
1315 return false;
1316 }
1317 $prev = $row->rev_id;
1318 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1319 } else {
1320 # No or missing previous revision; mark the page as new
1321 $prev = 0;
1322 $lastRevIsRedirect = null;
1323 }
1324 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1325 wfProfileOut( __METHOD__ );
1326 return $ret;
1327 }
1328
1329 /**
1330 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1331 * @return string Complete article text, or null if error
1332 */
1333 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1334 wfProfileIn( __METHOD__ );
1335 if( strval( $section ) == '' ) {
1336 // Whole-page edit; let the whole text through
1337 } else {
1338 if( is_null($edittime) ) {
1339 $rev = Revision::newFromTitle( $this->mTitle );
1340 } else {
1341 $dbw = wfGetDB( DB_MASTER );
1342 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1343 }
1344 if( !$rev ) {
1345 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1346 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1347 return null;
1348 }
1349 $oldtext = $rev->getText();
1350
1351 if( $section == 'new' ) {
1352 # Inserting a new section
1353 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1354 $text = strlen( trim( $oldtext ) ) > 0
1355 ? "{$oldtext}\n\n{$subject}{$text}"
1356 : "{$subject}{$text}";
1357 } else {
1358 # Replacing an existing section; roll out the big guns
1359 global $wgParser;
1360 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1361 }
1362 }
1363 wfProfileOut( __METHOD__ );
1364 return $text;
1365 }
1366
1367 /**
1368 * @deprecated use Article::doEdit()
1369 */
1370 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1371 wfDeprecated( __METHOD__ );
1372 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1373 ( $isminor ? EDIT_MINOR : 0 ) |
1374 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1375 ( $bot ? EDIT_FORCE_BOT : 0 );
1376
1377 # If this is a comment, add the summary as headline
1378 if( $comment && $summary != "" ) {
1379 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1380 }
1381
1382 $this->doEdit( $text, $summary, $flags );
1383
1384 $dbw = wfGetDB( DB_MASTER );
1385 if($watchthis) {
1386 if(!$this->mTitle->userIsWatching()) {
1387 $dbw->begin();
1388 $this->doWatch();
1389 $dbw->commit();
1390 }
1391 } else {
1392 if( $this->mTitle->userIsWatching() ) {
1393 $dbw->begin();
1394 $this->doUnwatch();
1395 $dbw->commit();
1396 }
1397 }
1398 $this->doRedirect( $this->isRedirect( $text ) );
1399 }
1400
1401 /**
1402 * @deprecated use Article::doEdit()
1403 */
1404 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1405 wfDeprecated( __METHOD__ );
1406 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1407 ( $minor ? EDIT_MINOR : 0 ) |
1408 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1409
1410 $status = $this->doEdit( $text, $summary, $flags );
1411 if( !$status->isOK() ) {
1412 return false;
1413 }
1414
1415 $dbw = wfGetDB( DB_MASTER );
1416 if( $watchthis ) {
1417 if(!$this->mTitle->userIsWatching()) {
1418 $dbw->begin();
1419 $this->doWatch();
1420 $dbw->commit();
1421 }
1422 } else {
1423 if( $this->mTitle->userIsWatching() ) {
1424 $dbw->begin();
1425 $this->doUnwatch();
1426 $dbw->commit();
1427 }
1428 }
1429
1430 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1431 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1432
1433 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1434 return true;
1435 }
1436
1437 /**
1438 * Article::doEdit()
1439 *
1440 * Change an existing article or create a new article. Updates RC and all necessary caches,
1441 * optionally via the deferred update array.
1442 *
1443 * $wgUser must be set before calling this function.
1444 *
1445 * @param $text String: new text
1446 * @param $summary String: edit summary
1447 * @param $flags Integer bitfield:
1448 * EDIT_NEW
1449 * Article is known or assumed to be non-existent, create a new one
1450 * EDIT_UPDATE
1451 * Article is known or assumed to be pre-existing, update it
1452 * EDIT_MINOR
1453 * Mark this edit minor, if the user is allowed to do so
1454 * EDIT_SUPPRESS_RC
1455 * Do not log the change in recentchanges
1456 * EDIT_FORCE_BOT
1457 * Mark the edit a "bot" edit regardless of user rights
1458 * EDIT_DEFER_UPDATES
1459 * Defer some of the updates until the end of index.php
1460 * EDIT_AUTOSUMMARY
1461 * Fill in blank summaries with generated text where possible
1462 *
1463 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1464 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1465 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1466 * edit-already-exists error will be returned. These two conditions are also possible with
1467 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1468 *
1469 * @param $baseRevId the revision ID this edit was based off, if any
1470 * @param $user Optional user object, $wgUser will be used if not passed
1471 *
1472 * @return Status object. Possible errors:
1473 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1474 * edit-gone-missing: In update mode, but the article didn't exist
1475 * edit-conflict: In update mode, the article changed unexpectedly
1476 * edit-no-change: Warning that the text was the same as before
1477 * edit-already-exists: In creation mode, but the article already exists
1478 *
1479 * Extensions may define additional errors.
1480 *
1481 * $return->value will contain an associative array with members as follows:
1482 * new: Boolean indicating if the function attempted to create a new article
1483 * revision: The revision object for the inserted revision, or null
1484 *
1485 * Compatibility note: this function previously returned a boolean value indicating success/failure
1486 */
1487 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1488 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1489
1490 # Low-level sanity check
1491 if( $this->mTitle->getText() == '' ) {
1492 throw new MWException( 'Something is trying to edit an article with an empty title' );
1493 }
1494
1495 wfProfileIn( __METHOD__ );
1496
1497 $user = is_null($user) ? $wgUser : $user;
1498 $status = Status::newGood( array() );
1499
1500 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1501 $this->loadPageData();
1502
1503 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1504 $aid = $this->mTitle->getArticleID();
1505 if( $aid ) {
1506 $flags |= EDIT_UPDATE;
1507 } else {
1508 $flags |= EDIT_NEW;
1509 }
1510 }
1511
1512 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1513 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1514 {
1515 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1516 wfProfileOut( __METHOD__ );
1517 if( $status->isOK() ) {
1518 $status->fatal( 'edit-hook-aborted');
1519 }
1520 return $status;
1521 }
1522
1523 # Silently ignore EDIT_MINOR if not allowed
1524 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1525 $bot = $flags & EDIT_FORCE_BOT;
1526
1527 $oldtext = $this->getRawText(); // current revision
1528 $oldsize = strlen( $oldtext );
1529
1530 # Provide autosummaries if one is not provided and autosummaries are enabled.
1531 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1532 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1533 }
1534
1535 $editInfo = $this->prepareTextForEdit( $text );
1536 $text = $editInfo->pst;
1537 $newsize = strlen( $text );
1538
1539 $dbw = wfGetDB( DB_MASTER );
1540 $now = wfTimestampNow();
1541
1542 if( $flags & EDIT_UPDATE ) {
1543 # Update article, but only if changed.
1544 $status->value['new'] = false;
1545 # Make sure the revision is either completely inserted or not inserted at all
1546 if( !$wgDBtransactions ) {
1547 $userAbort = ignore_user_abort( true );
1548 }
1549
1550 $revisionId = 0;
1551
1552 $changed = ( strcmp( $text, $oldtext ) != 0 );
1553
1554 if( $changed ) {
1555 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1556 - (int)$this->isCountable( $oldtext );
1557 $this->mTotalAdjustment = 0;
1558
1559 if( !$this->mLatest ) {
1560 # Article gone missing
1561 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1562 $status->fatal( 'edit-gone-missing' );
1563 wfProfileOut( __METHOD__ );
1564 return $status;
1565 }
1566
1567 $revision = new Revision( array(
1568 'page' => $this->getId(),
1569 'comment' => $summary,
1570 'minor_edit' => $isminor,
1571 'text' => $text,
1572 'parent_id' => $this->mLatest,
1573 'user' => $user->getId(),
1574 'user_text' => $user->getName(),
1575 ) );
1576
1577 $dbw->begin();
1578 $revisionId = $revision->insertOn( $dbw );
1579
1580 # Update page
1581 #
1582 # Note that we use $this->mLatest instead of fetching a value from the master DB
1583 # during the course of this function. This makes sure that EditPage can detect
1584 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1585 # before this function is called. A previous function used a separate query, this
1586 # creates a window where concurrent edits can cause an ignored edit conflict.
1587 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1588
1589 if( !$ok ) {
1590 /* Belated edit conflict! Run away!! */
1591 $status->fatal( 'edit-conflict' );
1592 # Delete the invalid revision if the DB is not transactional
1593 if( !$wgDBtransactions ) {
1594 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1595 }
1596 $revisionId = 0;
1597 $dbw->rollback();
1598 } else {
1599 global $wgUseRCPatrol;
1600 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1601 # Update recentchanges
1602 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1603 # Mark as patrolled if the user can do so
1604 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1605 # Add RC row to the DB
1606 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1607 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1608 $revisionId, $patrolled
1609 );
1610 # Log auto-patrolled edits
1611 if( $patrolled ) {
1612 PatrolLog::record( $rc, true );
1613 }
1614 }
1615 $user->incEditCount();
1616 $dbw->commit();
1617 }
1618 } else {
1619 $status->warning( 'edit-no-change' );
1620 $revision = null;
1621 // Keep the same revision ID, but do some updates on it
1622 $revisionId = $this->getRevIdFetched();
1623 // Update page_touched, this is usually implicit in the page update
1624 // Other cache updates are done in onArticleEdit()
1625 $this->mTitle->invalidateCache();
1626 }
1627
1628 if( !$wgDBtransactions ) {
1629 ignore_user_abort( $userAbort );
1630 }
1631 // Now that ignore_user_abort is restored, we can respond to fatal errors
1632 if( !$status->isOK() ) {
1633 wfProfileOut( __METHOD__ );
1634 return $status;
1635 }
1636
1637 # Invalidate cache of this article and all pages using this article
1638 # as a template. Partly deferred. Leave templatelinks for editUpdates().
1639 Article::onArticleEdit( $this->mTitle, 'skiptransclusions' );
1640 # Update links tables, site stats, etc.
1641 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1642 } else {
1643 # Create new article
1644 $status->value['new'] = true;
1645
1646 # Set statistics members
1647 # We work out if it's countable after PST to avoid counter drift
1648 # when articles are created with {{subst:}}
1649 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1650 $this->mTotalAdjustment = 1;
1651
1652 $dbw->begin();
1653
1654 # Add the page record; stake our claim on this title!
1655 # This will return false if the article already exists
1656 $newid = $this->insertOn( $dbw );
1657
1658 if( $newid === false ) {
1659 $dbw->rollback();
1660 $status->fatal( 'edit-already-exists' );
1661 wfProfileOut( __METHOD__ );
1662 return $status;
1663 }
1664
1665 # Save the revision text...
1666 $revision = new Revision( array(
1667 'page' => $newid,
1668 'comment' => $summary,
1669 'minor_edit' => $isminor,
1670 'text' => $text,
1671 'user' => $user->getId(),
1672 'user_text' => $user->getName(),
1673 ) );
1674 $revisionId = $revision->insertOn( $dbw );
1675
1676 $this->mTitle->resetArticleID( $newid );
1677
1678 # Update the page record with revision data
1679 $this->updateRevisionOn( $dbw, $revision, 0 );
1680
1681 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1682 # Update recentchanges
1683 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1684 global $wgUseRCPatrol, $wgUseNPPatrol;
1685 # Mark as patrolled if the user can do so
1686 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
1687 # Add RC row to the DB
1688 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1689 '', strlen($text), $revisionId, $patrolled );
1690 # Log auto-patrolled edits
1691 if( $patrolled ) {
1692 PatrolLog::record( $rc, true );
1693 }
1694 }
1695 $user->incEditCount();
1696 $dbw->commit();
1697
1698 # Update links, etc.
1699 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1700
1701 # Clear caches
1702 Article::onArticleCreate( $this->mTitle );
1703
1704 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1705 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1706 }
1707
1708 # Do updates right now unless deferral was requested
1709 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
1710 wfDoUpdates();
1711 }
1712
1713 // Return the new revision (or null) to the caller
1714 $status->value['revision'] = $revision;
1715
1716 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1717 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status ) );
1718
1719 wfProfileOut( __METHOD__ );
1720 return $status;
1721 }
1722
1723 /**
1724 * @deprecated wrapper for doRedirect
1725 */
1726 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1727 wfDeprecated( __METHOD__ );
1728 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1729 }
1730
1731 /**
1732 * Output a redirect back to the article.
1733 * This is typically used after an edit.
1734 *
1735 * @param $noRedir Boolean: add redirect=no
1736 * @param $sectionAnchor String: section to redirect to, including "#"
1737 * @param $extraQuery String: extra query params
1738 */
1739 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1740 global $wgOut;
1741 if( $noRedir ) {
1742 $query = 'redirect=no';
1743 if( $extraQuery )
1744 $query .= "&$query";
1745 } else {
1746 $query = $extraQuery;
1747 }
1748 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1749 }
1750
1751 /**
1752 * Mark this particular edit/page as patrolled
1753 */
1754 public function markpatrolled() {
1755 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1756 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1757
1758 # If we haven't been given an rc_id value, we can't do anything
1759 $rcid = (int) $wgRequest->getVal('rcid');
1760 $rc = RecentChange::newFromId($rcid);
1761 if( is_null($rc) ) {
1762 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1763 return;
1764 }
1765
1766 #It would be nice to see where the user had actually come from, but for now just guess
1767 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1768 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1769
1770 $dbw = wfGetDB( DB_MASTER );
1771 $errors = $rc->doMarkPatrolled();
1772
1773 if( in_array(array('rcpatroldisabled'), $errors) ) {
1774 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1775 return;
1776 }
1777
1778 if( in_array(array('hookaborted'), $errors) ) {
1779 // The hook itself has handled any output
1780 return;
1781 }
1782
1783 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1784 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1785 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1786 $wgOut->returnToMain( false, $return );
1787 return;
1788 }
1789
1790 if( !empty($errors) ) {
1791 $wgOut->showPermissionsErrorPage( $errors );
1792 return;
1793 }
1794
1795 # Inform the user
1796 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1797 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1798 $wgOut->returnToMain( false, $return );
1799 }
1800
1801 /**
1802 * User-interface handler for the "watch" action
1803 */
1804
1805 public function watch() {
1806 global $wgUser, $wgOut;
1807 if( $wgUser->isAnon() ) {
1808 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1809 return;
1810 }
1811 if( wfReadOnly() ) {
1812 $wgOut->readOnlyPage();
1813 return;
1814 }
1815 if( $this->doWatch() ) {
1816 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1817 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1818 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1819 }
1820 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1821 }
1822
1823 /**
1824 * Add this page to $wgUser's watchlist
1825 * @return bool true on successful watch operation
1826 */
1827 public function doWatch() {
1828 global $wgUser;
1829 if( $wgUser->isAnon() ) {
1830 return false;
1831 }
1832 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1833 $wgUser->addWatch( $this->mTitle );
1834 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1835 }
1836 return false;
1837 }
1838
1839 /**
1840 * User interface handler for the "unwatch" action.
1841 */
1842 public function unwatch() {
1843 global $wgUser, $wgOut;
1844 if( $wgUser->isAnon() ) {
1845 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1846 return;
1847 }
1848 if( wfReadOnly() ) {
1849 $wgOut->readOnlyPage();
1850 return;
1851 }
1852 if( $this->doUnwatch() ) {
1853 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1854 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1855 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1856 }
1857 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1858 }
1859
1860 /**
1861 * Stop watching a page
1862 * @return bool true on successful unwatch
1863 */
1864 public function doUnwatch() {
1865 global $wgUser;
1866 if( $wgUser->isAnon() ) {
1867 return false;
1868 }
1869 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1870 $wgUser->removeWatch( $this->mTitle );
1871 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1872 }
1873 return false;
1874 }
1875
1876 /**
1877 * action=protect handler
1878 */
1879 public function protect() {
1880 $form = new ProtectionForm( $this );
1881 $form->execute();
1882 }
1883
1884 /**
1885 * action=unprotect handler (alias)
1886 */
1887 public function unprotect() {
1888 $this->protect();
1889 }
1890
1891 /**
1892 * Update the article's restriction field, and leave a log entry.
1893 *
1894 * @param $limit Array: set of restriction keys
1895 * @param $reason String
1896 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1897 * @param $expiry Array: per restriction type expiration
1898 * @return bool true on success
1899 */
1900 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1901 global $wgUser, $wgRestrictionTypes, $wgContLang;
1902
1903 $id = $this->mTitle->getArticleID();
1904 if( $id <= 0 || wfReadOnly() || !$this->mTitle->userCan('protect') ) {
1905 return false;
1906 }
1907
1908 if( !$cascade ) {
1909 $cascade = false;
1910 }
1911
1912 // Take this opportunity to purge out expired restrictions
1913 Title::purgeExpiredRestrictions();
1914
1915 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1916 # we expect a single selection, but the schema allows otherwise.
1917 $current = array();
1918 $updated = Article::flattenRestrictions( $limit );
1919 $changed = false;
1920 foreach( $wgRestrictionTypes as $action ) {
1921 if( isset( $expiry[$action] ) ) {
1922 # Get current restrictions on $action
1923 $aLimits = $this->mTitle->getRestrictions( $action );
1924 $current[$action] = implode( '', $aLimits );
1925 # Are any actual restrictions being dealt with here?
1926 $aRChanged = count($aLimits) || !empty($limit[$action]);
1927 # If something changed, we need to log it. Checking $aRChanged
1928 # assures that "unprotecting" a page that is not protected does
1929 # not log just because the expiry was "changed".
1930 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
1931 $changed = true;
1932 }
1933 }
1934 }
1935
1936 $current = Article::flattenRestrictions( $current );
1937
1938 $changed = ($changed || $current != $updated );
1939 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1940 $protect = ( $updated != '' );
1941
1942 # If nothing's changed, do nothing
1943 if( $changed ) {
1944 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1945
1946 $dbw = wfGetDB( DB_MASTER );
1947
1948 # Prepare a null revision to be added to the history
1949 $modified = $current != '' && $protect;
1950 if( $protect ) {
1951 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1952 } else {
1953 $comment_type = 'unprotectedarticle';
1954 }
1955 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1956
1957 # Only restrictions with the 'protect' right can cascade...
1958 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1959 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1960 # The schema allows multiple restrictions
1961 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
1962 $cascade = false;
1963 $cascade_description = '';
1964 if( $cascade ) {
1965 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1966 }
1967
1968 if( $reason )
1969 $comment .= ": $reason";
1970
1971 $editComment = $comment;
1972 $encodedExpiry = array();
1973 $protect_description = '';
1974 foreach( $limit as $action => $restrictions ) {
1975 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
1976 if( $restrictions != '' ) {
1977 $protect_description .= "[$action=$restrictions] (";
1978 if( $encodedExpiry[$action] != 'infinity' ) {
1979 $protect_description .= wfMsgForContent( 'protect-expiring',
1980 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1981 $wgContLang->date( $expiry[$action], false, false ) ,
1982 $wgContLang->time( $expiry[$action], false, false ) );
1983 } else {
1984 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1985 }
1986 $protect_description .= ') ';
1987 }
1988 }
1989 $protect_description = trim($protect_description);
1990
1991 if( $protect_description && $protect )
1992 $editComment .= " ($protect_description)";
1993 if( $cascade )
1994 $editComment .= "$cascade_description";
1995 # Update restrictions table
1996 foreach( $limit as $action => $restrictions ) {
1997 if($restrictions != '' ) {
1998 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1999 array( 'pr_page' => $id,
2000 'pr_type' => $action,
2001 'pr_level' => $restrictions,
2002 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
2003 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2004 } else {
2005 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2006 'pr_type' => $action ), __METHOD__ );
2007 }
2008 }
2009
2010 # Insert a null revision
2011 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2012 $nullRevId = $nullRevision->insertOn( $dbw );
2013
2014 $latest = $this->getLatest();
2015 # Update page record
2016 $dbw->update( 'page',
2017 array( /* SET */
2018 'page_touched' => $dbw->timestamp(),
2019 'page_restrictions' => '',
2020 'page_latest' => $nullRevId
2021 ), array( /* WHERE */
2022 'page_id' => $id
2023 ), 'Article::protect'
2024 );
2025
2026 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2027 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2028
2029 # Update the protection log
2030 $log = new LogPage( 'protect' );
2031 if( $protect ) {
2032 $params = array($protect_description,$cascade ? 'cascade' : '');
2033 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2034 } else {
2035 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2036 }
2037
2038 } # End hook
2039 } # End "changed" check
2040
2041 return true;
2042 }
2043
2044 /**
2045 * Take an array of page restrictions and flatten it to a string
2046 * suitable for insertion into the page_restrictions field.
2047 * @param $limit Array
2048 * @return String
2049 */
2050 protected static function flattenRestrictions( $limit ) {
2051 if( !is_array( $limit ) ) {
2052 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2053 }
2054 $bits = array();
2055 ksort( $limit );
2056 foreach( $limit as $action => $restrictions ) {
2057 if( $restrictions != '' ) {
2058 $bits[] = "$action=$restrictions";
2059 }
2060 }
2061 return implode( ':', $bits );
2062 }
2063
2064 /**
2065 * Auto-generates a deletion reason
2066 * @param &$hasHistory Boolean: whether the page has a history
2067 */
2068 public function generateReason( &$hasHistory ) {
2069 global $wgContLang;
2070 $dbw = wfGetDB( DB_MASTER );
2071 // Get the last revision
2072 $rev = Revision::newFromTitle( $this->mTitle );
2073 if( is_null( $rev ) )
2074 return false;
2075
2076 // Get the article's contents
2077 $contents = $rev->getText();
2078 $blank = false;
2079 // If the page is blank, use the text from the previous revision,
2080 // which can only be blank if there's a move/import/protect dummy revision involved
2081 if( $contents == '' ) {
2082 $prev = $rev->getPrevious();
2083 if( $prev ) {
2084 $contents = $prev->getText();
2085 $blank = true;
2086 }
2087 }
2088
2089 // Find out if there was only one contributor
2090 // Only scan the last 20 revisions
2091 $limit = 20;
2092 $res = $dbw->select( 'revision', 'rev_user_text',
2093 array( 'rev_page' => $this->getID() ), __METHOD__,
2094 array( 'LIMIT' => $limit )
2095 );
2096 if( $res === false )
2097 // This page has no revisions, which is very weird
2098 return false;
2099 if( $res->numRows() > 1 )
2100 $hasHistory = true;
2101 else
2102 $hasHistory = false;
2103 $row = $dbw->fetchObject( $res );
2104 $onlyAuthor = $row->rev_user_text;
2105 // Try to find a second contributor
2106 foreach( $res as $row ) {
2107 if( $row->rev_user_text != $onlyAuthor ) {
2108 $onlyAuthor = false;
2109 break;
2110 }
2111 }
2112 $dbw->freeResult( $res );
2113
2114 // Generate the summary with a '$1' placeholder
2115 if( $blank ) {
2116 // The current revision is blank and the one before is also
2117 // blank. It's just not our lucky day
2118 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2119 } else {
2120 if( $onlyAuthor )
2121 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2122 else
2123 $reason = wfMsgForContent( 'excontent', '$1' );
2124 }
2125
2126 if( $reason == '-' ) {
2127 // Allow these UI messages to be blanked out cleanly
2128 return '';
2129 }
2130
2131 // Replace newlines with spaces to prevent uglyness
2132 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2133 // Calculate the maximum amount of chars to get
2134 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2135 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2136 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2137 // Remove possible unfinished links
2138 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2139 // Now replace the '$1' placeholder
2140 $reason = str_replace( '$1', $contents, $reason );
2141 return $reason;
2142 }
2143
2144
2145 /*
2146 * UI entry point for page deletion
2147 */
2148 public function delete() {
2149 global $wgUser, $wgOut, $wgRequest;
2150
2151 $confirm = $wgRequest->wasPosted() &&
2152 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2153
2154 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2155 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2156
2157 $reason = $this->DeleteReasonList;
2158
2159 if( $reason != 'other' && $this->DeleteReason != '' ) {
2160 // Entry from drop down menu + additional comment
2161 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2162 } elseif( $reason == 'other' ) {
2163 $reason = $this->DeleteReason;
2164 }
2165 # Flag to hide all contents of the archived revisions
2166 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2167
2168 # This code desperately needs to be totally rewritten
2169
2170 # Read-only check...
2171 if( wfReadOnly() ) {
2172 $wgOut->readOnlyPage();
2173 return;
2174 }
2175
2176 # Check permissions
2177 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2178
2179 if( count( $permission_errors ) > 0 ) {
2180 $wgOut->showPermissionsErrorPage( $permission_errors );
2181 return;
2182 }
2183
2184 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2185
2186 # Better double-check that it hasn't been deleted yet!
2187 $dbw = wfGetDB( DB_MASTER );
2188 $conds = $this->mTitle->pageCond();
2189 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2190 if( $latest === false ) {
2191 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2192 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2193 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2194 return;
2195 }
2196
2197 # Hack for big sites
2198 $bigHistory = $this->isBigDeletion();
2199 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2200 global $wgLang, $wgDeleteRevisionsLimit;
2201 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2202 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2203 return;
2204 }
2205
2206 if( $confirm ) {
2207 $this->doDelete( $reason, $suppress );
2208 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2209 $this->doWatch();
2210 } elseif( $this->mTitle->userIsWatching() ) {
2211 $this->doUnwatch();
2212 }
2213 return;
2214 }
2215
2216 // Generate deletion reason
2217 $hasHistory = false;
2218 if( !$reason ) $reason = $this->generateReason($hasHistory);
2219
2220 // If the page has a history, insert a warning
2221 if( $hasHistory && !$confirm ) {
2222 $skin = $wgUser->getSkin();
2223 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2224 if( $bigHistory ) {
2225 global $wgLang, $wgDeleteRevisionsLimit;
2226 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2227 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2228 }
2229 }
2230
2231 return $this->confirmDelete( $reason );
2232 }
2233
2234 /**
2235 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2236 */
2237 public function isBigDeletion() {
2238 global $wgDeleteRevisionsLimit;
2239 if( $wgDeleteRevisionsLimit ) {
2240 $revCount = $this->estimateRevisionCount();
2241 return $revCount > $wgDeleteRevisionsLimit;
2242 }
2243 return false;
2244 }
2245
2246 /**
2247 * @return int approximate revision count
2248 */
2249 public function estimateRevisionCount() {
2250 $dbr = wfGetDB( DB_SLAVE );
2251 // For an exact count...
2252 //return $dbr->selectField( 'revision', 'COUNT(*)',
2253 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2254 return $dbr->estimateRowCount( 'revision', '*',
2255 array( 'rev_page' => $this->getId() ), __METHOD__ );
2256 }
2257
2258 /**
2259 * Get the last N authors
2260 * @param $num Integer: number of revisions to get
2261 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2262 * @return array Array of authors, duplicates not removed
2263 */
2264 public function getLastNAuthors( $num, $revLatest = 0 ) {
2265 wfProfileIn( __METHOD__ );
2266 // First try the slave
2267 // If that doesn't have the latest revision, try the master
2268 $continue = 2;
2269 $db = wfGetDB( DB_SLAVE );
2270 do {
2271 $res = $db->select( array( 'page', 'revision' ),
2272 array( 'rev_id', 'rev_user_text' ),
2273 array(
2274 'page_namespace' => $this->mTitle->getNamespace(),
2275 'page_title' => $this->mTitle->getDBkey(),
2276 'rev_page = page_id'
2277 ), __METHOD__, $this->getSelectOptions( array(
2278 'ORDER BY' => 'rev_timestamp DESC',
2279 'LIMIT' => $num
2280 ) )
2281 );
2282 if( !$res ) {
2283 wfProfileOut( __METHOD__ );
2284 return array();
2285 }
2286 $row = $db->fetchObject( $res );
2287 if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2288 $db = wfGetDB( DB_MASTER );
2289 $continue--;
2290 } else {
2291 $continue = 0;
2292 }
2293 } while ( $continue );
2294
2295 $authors = array( $row->rev_user_text );
2296 while ( $row = $db->fetchObject( $res ) ) {
2297 $authors[] = $row->rev_user_text;
2298 }
2299 wfProfileOut( __METHOD__ );
2300 return $authors;
2301 }
2302
2303 /**
2304 * Output deletion confirmation dialog
2305 * @param $reason String: prefilled reason
2306 */
2307 public function confirmDelete( $reason ) {
2308 global $wgOut, $wgUser;
2309
2310 wfDebug( "Article::confirmDelete\n" );
2311
2312 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2313 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2314 $wgOut->addWikiMsg( 'confirmdeletetext' );
2315
2316 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2317 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2318 <td></td>
2319 <td class='mw-input'>" .
2320 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2321 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2322 "</td>
2323 </tr>";
2324 } else {
2325 $suppress = '';
2326 }
2327 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2328
2329 $form = Xml::openElement( 'form', array( 'method' => 'post',
2330 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2331 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2332 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2333 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2334 "<tr id=\"wpDeleteReasonListRow\">
2335 <td class='mw-label'>" .
2336 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2337 "</td>
2338 <td class='mw-input'>" .
2339 Xml::listDropDown( 'wpDeleteReasonList',
2340 wfMsgForContent( 'deletereason-dropdown' ),
2341 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2342 "</td>
2343 </tr>
2344 <tr id=\"wpDeleteReasonRow\">
2345 <td class='mw-label'>" .
2346 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2347 "</td>
2348 <td class='mw-input'>" .
2349 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2350 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2351 "</td>
2352 </tr>
2353 <tr>
2354 <td></td>
2355 <td class='mw-input'>" .
2356 Xml::checkLabel( wfMsg( 'watchthis' ),
2357 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2358 "</td>
2359 </tr>
2360 $suppress
2361 <tr>
2362 <td></td>
2363 <td class='mw-submit'>" .
2364 Xml::submitButton( wfMsg( 'deletepage' ),
2365 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2366 "</td>
2367 </tr>" .
2368 Xml::closeElement( 'table' ) .
2369 Xml::closeElement( 'fieldset' ) .
2370 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2371 Xml::closeElement( 'form' );
2372
2373 if( $wgUser->isAllowed( 'editinterface' ) ) {
2374 $skin = $wgUser->getSkin();
2375 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2376 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2377 }
2378
2379 $wgOut->addHTML( $form );
2380 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2381 }
2382
2383 /**
2384 * Perform a deletion and output success or failure messages
2385 */
2386 public function doDelete( $reason, $suppress = false ) {
2387 global $wgOut, $wgUser;
2388 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2389
2390 $error = '';
2391 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2392 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2393 $deleted = $this->mTitle->getPrefixedText();
2394
2395 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2396 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2397
2398 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2399
2400 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2401 $wgOut->returnToMain( false );
2402 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2403 } else {
2404 if( $error == '' ) {
2405 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2406 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2407 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2408 } else {
2409 $wgOut->showFatalError( $error );
2410 }
2411 }
2412 }
2413 }
2414
2415 /**
2416 * Back-end article deletion
2417 * Deletes the article with database consistency, writes logs, purges caches
2418 * Returns success
2419 */
2420 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2421 global $wgUseSquid, $wgDeferredUpdateList;
2422 global $wgUseTrackbacks;
2423
2424 wfDebug( __METHOD__."\n" );
2425
2426 $dbw = wfGetDB( DB_MASTER );
2427 $ns = $this->mTitle->getNamespace();
2428 $t = $this->mTitle->getDBkey();
2429 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2430
2431 if( $t == '' || $id == 0 ) {
2432 return false;
2433 }
2434
2435 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2436 array_push( $wgDeferredUpdateList, $u );
2437
2438 // Bitfields to further suppress the content
2439 if( $suppress ) {
2440 $bitfield = 0;
2441 // This should be 15...
2442 $bitfield |= Revision::DELETED_TEXT;
2443 $bitfield |= Revision::DELETED_COMMENT;
2444 $bitfield |= Revision::DELETED_USER;
2445 $bitfield |= Revision::DELETED_RESTRICTED;
2446 } else {
2447 $bitfield = 'rev_deleted';
2448 }
2449
2450 $dbw->begin();
2451 // For now, shunt the revision data into the archive table.
2452 // Text is *not* removed from the text table; bulk storage
2453 // is left intact to avoid breaking block-compression or
2454 // immutable storage schemes.
2455 //
2456 // For backwards compatibility, note that some older archive
2457 // table entries will have ar_text and ar_flags fields still.
2458 //
2459 // In the future, we may keep revisions and mark them with
2460 // the rev_deleted field, which is reserved for this purpose.
2461 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2462 array(
2463 'ar_namespace' => 'page_namespace',
2464 'ar_title' => 'page_title',
2465 'ar_comment' => 'rev_comment',
2466 'ar_user' => 'rev_user',
2467 'ar_user_text' => 'rev_user_text',
2468 'ar_timestamp' => 'rev_timestamp',
2469 'ar_minor_edit' => 'rev_minor_edit',
2470 'ar_rev_id' => 'rev_id',
2471 'ar_text_id' => 'rev_text_id',
2472 'ar_text' => '\'\'', // Be explicit to appease
2473 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2474 'ar_len' => 'rev_len',
2475 'ar_page_id' => 'page_id',
2476 'ar_deleted' => $bitfield
2477 ), array(
2478 'page_id' => $id,
2479 'page_id = rev_page'
2480 ), __METHOD__
2481 );
2482
2483 # Delete restrictions for it
2484 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2485
2486 # Now that it's safely backed up, delete it
2487 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2488 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2489 if( !$ok ) {
2490 $dbw->rollback();
2491 return false;
2492 }
2493
2494 # If using cascading deletes, we can skip some explicit deletes
2495 if( !$dbw->cascadingDeletes() ) {
2496 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2497
2498 if($wgUseTrackbacks)
2499 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2500
2501 # Delete outgoing links
2502 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2503 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2504 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2505 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2506 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2507 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2508 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2509 }
2510
2511 # If using cleanup triggers, we can skip some manual deletes
2512 if( !$dbw->cleanupTriggers() ) {
2513 # Clean up recentchanges entries...
2514 $dbw->delete( 'recentchanges',
2515 array( 'rc_type != '.RC_LOG,
2516 'rc_namespace' => $this->mTitle->getNamespace(),
2517 'rc_title' => $this->mTitle->getDBKey() ),
2518 __METHOD__ );
2519 $dbw->delete( 'recentchanges',
2520 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2521 __METHOD__ );
2522 }
2523
2524 # Clear caches
2525 Article::onArticleDelete( $this->mTitle );
2526
2527 # Fix category table counts
2528 $cats = array();
2529 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2530 foreach( $res as $row ) {
2531 $cats []= $row->cl_to;
2532 }
2533 $this->updateCategoryCounts( array(), $cats );
2534
2535 # Clear the cached article id so the interface doesn't act like we exist
2536 $this->mTitle->resetArticleID( 0 );
2537 $this->mTitle->mArticleID = 0;
2538
2539 # Log the deletion, if the page was suppressed, log it at Oversight instead
2540 $logtype = $suppress ? 'suppress' : 'delete';
2541 $log = new LogPage( $logtype );
2542
2543 # Make sure logging got through
2544 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2545
2546 $dbw->commit();
2547
2548 return true;
2549 }
2550
2551 /**
2552 * Roll back the most recent consecutive set of edits to a page
2553 * from the same user; fails if there are no eligible edits to
2554 * roll back to, e.g. user is the sole contributor. This function
2555 * performs permissions checks on $wgUser, then calls commitRollback()
2556 * to do the dirty work
2557 *
2558 * @param $fromP String: Name of the user whose edits to rollback.
2559 * @param $summary String: Custom summary. Set to default summary if empty.
2560 * @param $token String: Rollback token.
2561 * @param $bot Boolean: If true, mark all reverted edits as bot.
2562 *
2563 * @param $resultDetails Array: contains result-specific array of additional values
2564 * 'alreadyrolled' : 'current' (rev)
2565 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2566 *
2567 * @return array of errors, each error formatted as
2568 * array(messagekey, param1, param2, ...).
2569 * On success, the array is empty. This array can also be passed to
2570 * OutputPage::showPermissionsErrorPage().
2571 */
2572 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2573 global $wgUser;
2574 $resultDetails = null;
2575
2576 # Check permissions
2577 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2578 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2579 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2580
2581 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2582 $errors[] = array( 'sessionfailure' );
2583
2584 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2585 $errors[] = array( 'actionthrottledtext' );
2586 }
2587 # If there were errors, bail out now
2588 if( !empty( $errors ) )
2589 return $errors;
2590
2591 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2592 }
2593
2594 /**
2595 * Backend implementation of doRollback(), please refer there for parameter
2596 * and return value documentation
2597 *
2598 * NOTE: This function does NOT check ANY permissions, it just commits the
2599 * rollback to the DB Therefore, you should only call this function direct-
2600 * ly if you want to use custom permissions checks. If you don't, use
2601 * doRollback() instead.
2602 */
2603 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2604 global $wgUseRCPatrol, $wgUser, $wgLang;
2605 $dbw = wfGetDB( DB_MASTER );
2606
2607 if( wfReadOnly() ) {
2608 return array( array( 'readonlytext' ) );
2609 }
2610
2611 # Get the last editor
2612 $current = Revision::newFromTitle( $this->mTitle );
2613 if( is_null( $current ) ) {
2614 # Something wrong... no page?
2615 return array(array('notanarticle'));
2616 }
2617
2618 $from = str_replace( '_', ' ', $fromP );
2619 if( $from != $current->getUserText() ) {
2620 $resultDetails = array( 'current' => $current );
2621 return array(array('alreadyrolled',
2622 htmlspecialchars($this->mTitle->getPrefixedText()),
2623 htmlspecialchars($fromP),
2624 htmlspecialchars($current->getUserText())
2625 ));
2626 }
2627
2628 # Get the last edit not by this guy
2629 $user = intval( $current->getUser() );
2630 $user_text = $dbw->addQuotes( $current->getUserText() );
2631 $s = $dbw->selectRow( 'revision',
2632 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2633 array( 'rev_page' => $current->getPage(),
2634 "rev_user != {$user} OR rev_user_text != {$user_text}"
2635 ), __METHOD__,
2636 array( 'USE INDEX' => 'page_timestamp',
2637 'ORDER BY' => 'rev_timestamp DESC' )
2638 );
2639 if( $s === false ) {
2640 # No one else ever edited this page
2641 return array(array('cantrollback'));
2642 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2643 # Only admins can see this text
2644 return array(array('notvisiblerev'));
2645 }
2646
2647 $set = array();
2648 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2649 # Mark all reverted edits as bot
2650 $set['rc_bot'] = 1;
2651 }
2652 if( $wgUseRCPatrol ) {
2653 # Mark all reverted edits as patrolled
2654 $set['rc_patrolled'] = 1;
2655 }
2656
2657 if( $set ) {
2658 $dbw->update( 'recentchanges', $set,
2659 array( /* WHERE */
2660 'rc_cur_id' => $current->getPage(),
2661 'rc_user_text' => $current->getUserText(),
2662 "rc_timestamp > '{$s->rev_timestamp}'",
2663 ), __METHOD__
2664 );
2665 }
2666
2667 # Generate the edit summary if necessary
2668 $target = Revision::newFromId( $s->rev_id );
2669 if( empty( $summary ) ){
2670 $summary = wfMsgForContent( 'revertpage' );
2671 }
2672
2673 # Allow the custom summary to use the same args as the default message
2674 $args = array(
2675 $target->getUserText(), $from, $s->rev_id,
2676 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2677 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2678 );
2679 $summary = wfMsgReplaceArgs( $summary, $args );
2680
2681 # Save
2682 $flags = EDIT_UPDATE;
2683
2684 if( $wgUser->isAllowed('minoredit') )
2685 $flags |= EDIT_MINOR;
2686
2687 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2688 $flags |= EDIT_FORCE_BOT;
2689 # Actually store the edit
2690 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2691 if( !empty( $status->value['revision'] ) ) {
2692 $revId = $status->value['revision']->getId();
2693 } else {
2694 $revId = false;
2695 }
2696
2697 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2698
2699 $resultDetails = array(
2700 'summary' => $summary,
2701 'current' => $current,
2702 'target' => $target,
2703 'newid' => $revId
2704 );
2705 return array();
2706 }
2707
2708 /**
2709 * User interface for rollback operations
2710 */
2711 public function rollback() {
2712 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2713 $details = null;
2714
2715 $result = $this->doRollback(
2716 $wgRequest->getVal( 'from' ),
2717 $wgRequest->getText( 'summary' ),
2718 $wgRequest->getVal( 'token' ),
2719 $wgRequest->getBool( 'bot' ),
2720 $details
2721 );
2722
2723 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2724 $wgOut->rateLimited();
2725 return;
2726 }
2727 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
2728 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2729 $errArray = $result[0];
2730 $errMsg = array_shift( $errArray );
2731 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2732 if( isset( $details['current'] ) ){
2733 $current = $details['current'];
2734 if( $current->getComment() != '' ) {
2735 $wgOut->addWikiMsgArray( 'editcomment', array(
2736 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2737 }
2738 }
2739 return;
2740 }
2741 # Display permissions errors before read-only message -- there's no
2742 # point in misleading the user into thinking the inability to rollback
2743 # is only temporary.
2744 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2745 # array_diff is completely broken for arrays of arrays, sigh. Re-
2746 # move any 'readonlytext' error manually.
2747 $out = array();
2748 foreach( $result as $error ) {
2749 if( $error != array( 'readonlytext' ) ) {
2750 $out []= $error;
2751 }
2752 }
2753 $wgOut->showPermissionsErrorPage( $out );
2754 return;
2755 }
2756 if( $result == array( array( 'readonlytext' ) ) ) {
2757 $wgOut->readOnlyPage();
2758 return;
2759 }
2760
2761 $current = $details['current'];
2762 $target = $details['target'];
2763 $newId = $details['newid'];
2764 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2765 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2766 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2767 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2768 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2769 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2770 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2771 $wgOut->returnToMain( false, $this->mTitle );
2772
2773 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2774 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
2775 $de->showDiff( '', '' );
2776 }
2777 }
2778
2779
2780 /**
2781 * Do standard deferred updates after page view
2782 */
2783 public function viewUpdates() {
2784 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2785 # Don't update page view counters on views from bot users (bug 14044)
2786 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2787 Article::incViewCount( $this->getID() );
2788 $u = new SiteStatsUpdate( 1, 0, 0 );
2789 array_push( $wgDeferredUpdateList, $u );
2790 }
2791 # Update newtalk / watchlist notification status
2792 $wgUser->clearNotification( $this->mTitle );
2793 }
2794
2795 /**
2796 * Prepare text which is about to be saved.
2797 * Returns a stdclass with source, pst and output members
2798 */
2799 public function prepareTextForEdit( $text, $revid=null ) {
2800 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2801 // Already prepared
2802 return $this->mPreparedEdit;
2803 }
2804 global $wgParser;
2805 $edit = (object)array();
2806 $edit->revid = $revid;
2807 $edit->newText = $text;
2808 $edit->pst = $this->preSaveTransform( $text );
2809 $options = new ParserOptions;
2810 $options->setTidy( true );
2811 $options->enableLimitReport();
2812 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2813 $edit->oldText = $this->getContent();
2814 $this->mPreparedEdit = $edit;
2815 return $edit;
2816 }
2817
2818 /**
2819 * Do standard deferred updates after page edit.
2820 * Update links tables, site stats, search index and message cache.
2821 * Purges pages that include this page if the text was changed here.
2822 * Every 100th edit, prune the recent changes table.
2823 *
2824 * @private
2825 * @param $text New text of the article
2826 * @param $summary Edit summary
2827 * @param $minoredit Minor edit
2828 * @param $timestamp_of_pagechange Timestamp associated with the page change
2829 * @param $newid rev_id value of the new revision
2830 * @param $changed Whether or not the content actually changed
2831 */
2832 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2833 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2834
2835 wfProfileIn( __METHOD__ );
2836
2837 # Parse the text
2838 # Be careful not to double-PST: $text is usually already PST-ed once
2839 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2840 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2841 $editInfo = $this->prepareTextForEdit( $text, $newid );
2842 } else {
2843 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2844 $editInfo = $this->mPreparedEdit;
2845 }
2846
2847 # Save it to the parser cache
2848 if( $wgEnableParserCache ) {
2849 $parserCache = ParserCache::singleton();
2850 $parserCache->save( $editInfo->output, $this, $wgUser );
2851 }
2852
2853 # Update the links tables
2854 $u = new LinksUpdate( $this->mTitle, $editInfo->output, false );
2855 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2856 $u->doUpdate();
2857
2858 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2859
2860 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2861 if( 0 == mt_rand( 0, 99 ) ) {
2862 // Flush old entries from the `recentchanges` table; we do this on
2863 // random requests so as to avoid an increase in writes for no good reason
2864 global $wgRCMaxAge;
2865 $dbw = wfGetDB( DB_MASTER );
2866 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2867 $recentchanges = $dbw->tableName( 'recentchanges' );
2868 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2869 $dbw->query( $sql );
2870 }
2871 }
2872
2873 $id = $this->getID();
2874 $title = $this->mTitle->getPrefixedDBkey();
2875 $shortTitle = $this->mTitle->getDBkey();
2876
2877 if( 0 == $id ) {
2878 wfProfileOut( __METHOD__ );
2879 return;
2880 }
2881
2882 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2883 array_push( $wgDeferredUpdateList, $u );
2884 $u = new SearchUpdate( $id, $title, $text );
2885 array_push( $wgDeferredUpdateList, $u );
2886
2887 # If this is another user's talk page, update newtalk
2888 # Don't do this if $changed = false otherwise some idiot can null-edit a
2889 # load of user talk pages and piss people off, nor if it's a minor edit
2890 # by a properly-flagged bot.
2891 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2892 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2893 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2894 $other = User::newFromName( $shortTitle, false );
2895 if( !$other ) {
2896 wfDebug( __METHOD__.": invalid username\n" );
2897 } elseif( User::isIP( $shortTitle ) ) {
2898 // An anonymous user
2899 $other->setNewtalk( true );
2900 } elseif( $other->isLoggedIn() ) {
2901 $other->setNewtalk( true );
2902 } else {
2903 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
2904 }
2905 }
2906 }
2907
2908 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2909 $wgMessageCache->replace( $shortTitle, $text );
2910 }
2911
2912 wfProfileOut( __METHOD__ );
2913 }
2914
2915 /**
2916 * Perform article updates on a special page creation.
2917 *
2918 * @param $rev Revision object
2919 *
2920 * @todo This is a shitty interface function. Kill it and replace the
2921 * other shitty functions like editUpdates and such so it's not needed
2922 * anymore.
2923 */
2924 public function createUpdates( $rev ) {
2925 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2926 $this->mTotalAdjustment = 1;
2927 $this->editUpdates( $rev->getText(), $rev->getComment(),
2928 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2929 }
2930
2931 /**
2932 * Generate the navigation links when browsing through an article revisions
2933 * It shows the information as:
2934 * Revision as of \<date\>; view current revision
2935 * \<- Previous version | Next Version -\>
2936 *
2937 * @param $oldid String: revision ID of this article revision
2938 */
2939 public function setOldSubtitle( $oldid = 0 ) {
2940 global $wgLang, $wgOut, $wgUser;
2941
2942 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
2943 return;
2944 }
2945
2946 $revision = Revision::newFromId( $oldid );
2947
2948 $current = ( $oldid == $this->mLatest );
2949 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2950 $sk = $wgUser->getSkin();
2951 $lnk = $current
2952 ? wfMsgHtml( 'currentrevisionlink' )
2953 : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'currentrevisionlink' ) );
2954 $curdiff = $current
2955 ? wfMsgHtml( 'diff' )
2956 : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
2957 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2958 $prevlink = $prev
2959 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2960 : wfMsgHtml( 'previousrevision' );
2961 $prevdiff = $prev
2962 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
2963 : wfMsgHtml( 'diff' );
2964 $nextlink = $current
2965 ? wfMsgHtml( 'nextrevision' )
2966 : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2967 $nextdiff = $current
2968 ? wfMsgHtml( 'diff' )
2969 : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
2970
2971 $cdel='';
2972 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2973 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2974 if( $revision->isCurrent() ) {
2975 // We don't handle top deleted edits too well
2976 $cdel = wfMsgHtml( 'rev-delundel' );
2977 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2978 // If revision was hidden from sysops
2979 $cdel = wfMsgHtml( 'rev-delundel' );
2980 } else {
2981 $cdel = $sk->makeKnownLinkObj( $revdel,
2982 wfMsgHtml('rev-delundel'),
2983 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2984 '&oldid=' . urlencode( $oldid ) );
2985 // Bolden oversighted content
2986 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2987 $cdel = "<strong>$cdel</strong>";
2988 }
2989 $cdel = "(<small>$cdel</small>) ";
2990 }
2991 # Show user links if allowed to see them. Normally they
2992 # are hidden regardless, but since we can already see the text here...
2993 $userlinks = $sk->revUserTools( $revision, false );
2994
2995 $m = wfMsg( 'revision-info-current' );
2996 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2997 ? 'revision-info-current'
2998 : 'revision-info';
2999
3000 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" .
3001
3002 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgHtml( 'revision-nav', $prevdiff,
3003 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3004 $wgOut->setSubtitle( $r );
3005 }
3006
3007 /**
3008 * This function is called right before saving the wikitext,
3009 * so we can do things like signatures and links-in-context.
3010 *
3011 * @param $text String
3012 */
3013 public function preSaveTransform( $text ) {
3014 global $wgParser, $wgUser;
3015 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3016 }
3017
3018 /* Caching functions */
3019
3020 /**
3021 * checkLastModified returns true if it has taken care of all
3022 * output to the client that is necessary for this request.
3023 * (that is, it has sent a cached version of the page)
3024 */
3025 protected function tryFileCache() {
3026 static $called = false;
3027 if( $called ) {
3028 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3029 return false;
3030 }
3031 $called = true;
3032 if( $this->isFileCacheable() ) {
3033 $cache = new HTMLFileCache( $this->mTitle );
3034 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3035 wfDebug( "Article::tryFileCache(): about to load file\n" );
3036 $cache->loadFromFileCache();
3037 return true;
3038 } else {
3039 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3040 ob_start( array(&$cache, 'saveToFileCache' ) );
3041 }
3042 } else {
3043 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3044 }
3045 return false;
3046 }
3047
3048 /**
3049 * Check if the page can be cached
3050 * @return bool
3051 */
3052 public function isFileCacheable() {
3053 $cacheable = false;
3054 if( HTMLFileCache::useFileCache() ) {
3055 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3056 // Extension may have reason to disable file caching on some pages.
3057 if( $cacheable ) {
3058 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3059 }
3060 }
3061 return $cacheable;
3062 }
3063
3064 /**
3065 * Loads page_touched and returns a value indicating if it should be used
3066 *
3067 */
3068 public function checkTouched() {
3069 if( !$this->mDataLoaded ) {
3070 $this->loadPageData();
3071 }
3072 return !$this->mIsRedirect;
3073 }
3074
3075 /**
3076 * Get the page_touched field
3077 */
3078 public function getTouched() {
3079 # Ensure that page data has been loaded
3080 if( !$this->mDataLoaded ) {
3081 $this->loadPageData();
3082 }
3083 return $this->mTouched;
3084 }
3085
3086 /**
3087 * Get the page_latest field
3088 */
3089 public function getLatest() {
3090 if( !$this->mDataLoaded ) {
3091 $this->loadPageData();
3092 }
3093 return $this->mLatest;
3094 }
3095
3096 /**
3097 * Edit an article without doing all that other stuff
3098 * The article must already exist; link tables etc
3099 * are not updated, caches are not flushed.
3100 *
3101 * @param $text String: text submitted
3102 * @param $comment String: comment submitted
3103 * @param $minor Boolean: whereas it's a minor modification
3104 */
3105 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3106 wfProfileIn( __METHOD__ );
3107
3108 $dbw = wfGetDB( DB_MASTER );
3109 $revision = new Revision( array(
3110 'page' => $this->getId(),
3111 'text' => $text,
3112 'comment' => $comment,
3113 'minor_edit' => $minor ? 1 : 0,
3114 ) );
3115 $revision->insertOn( $dbw );
3116 $this->updateRevisionOn( $dbw, $revision );
3117
3118 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3119
3120 wfProfileOut( __METHOD__ );
3121 }
3122
3123 /**
3124 * Used to increment the view counter
3125 *
3126 * @param $id Integer: article id
3127 */
3128 public static function incViewCount( $id ) {
3129 $id = intval( $id );
3130 global $wgHitcounterUpdateFreq, $wgDBtype;
3131
3132 $dbw = wfGetDB( DB_MASTER );
3133 $pageTable = $dbw->tableName( 'page' );
3134 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3135 $acchitsTable = $dbw->tableName( 'acchits' );
3136
3137 if( $wgHitcounterUpdateFreq <= 1 ) {
3138 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3139 return;
3140 }
3141
3142 # Not important enough to warrant an error page in case of failure
3143 $oldignore = $dbw->ignoreErrors( true );
3144
3145 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3146
3147 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3148 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3149 # Most of the time (or on SQL errors), skip row count check
3150 $dbw->ignoreErrors( $oldignore );
3151 return;
3152 }
3153
3154 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3155 $row = $dbw->fetchObject( $res );
3156 $rown = intval( $row->n );
3157 if( $rown >= $wgHitcounterUpdateFreq ){
3158 wfProfileIn( 'Article::incViewCount-collect' );
3159 $old_user_abort = ignore_user_abort( true );
3160
3161 if($wgDBtype == 'mysql')
3162 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3163 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3164 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3165 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3166 'GROUP BY hc_id');
3167 $dbw->query("DELETE FROM $hitcounterTable");
3168 if($wgDBtype == 'mysql') {
3169 $dbw->query('UNLOCK TABLES');
3170 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3171 'WHERE page_id = hc_id');
3172 }
3173 else {
3174 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3175 "FROM $acchitsTable WHERE page_id = hc_id");
3176 }
3177 $dbw->query("DROP TABLE $acchitsTable");
3178
3179 ignore_user_abort( $old_user_abort );
3180 wfProfileOut( 'Article::incViewCount-collect' );
3181 }
3182 $dbw->ignoreErrors( $oldignore );
3183 }
3184
3185 /**#@+
3186 * The onArticle*() functions are supposed to be a kind of hooks
3187 * which should be called whenever any of the specified actions
3188 * are done.
3189 *
3190 * This is a good place to put code to clear caches, for instance.
3191 *
3192 * This is called on page move and undelete, as well as edit
3193 *
3194 * @param $title a title object
3195 */
3196
3197 public static function onArticleCreate( $title ) {
3198 # Update existence markers on article/talk tabs...
3199 if( $title->isTalkPage() ) {
3200 $other = $title->getSubjectPage();
3201 } else {
3202 $other = $title->getTalkPage();
3203 }
3204 $other->invalidateCache();
3205 $other->purgeSquid();
3206
3207 $title->touchLinks();
3208 $title->purgeSquid();
3209 $title->deleteTitleProtection();
3210 }
3211
3212 public static function onArticleDelete( $title ) {
3213 global $wgMessageCache;
3214 # Update existence markers on article/talk tabs...
3215 if( $title->isTalkPage() ) {
3216 $other = $title->getSubjectPage();
3217 } else {
3218 $other = $title->getTalkPage();
3219 }
3220 $other->invalidateCache();
3221 $other->purgeSquid();
3222
3223 $title->touchLinks();
3224 $title->purgeSquid();
3225
3226 # File cache
3227 HTMLFileCache::clearFileCache( $title );
3228
3229 # Messages
3230 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3231 $wgMessageCache->replace( $title->getDBkey(), false );
3232 }
3233 # Images
3234 if( $title->getNamespace() == NS_FILE ) {
3235 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3236 $update->doUpdate();
3237 }
3238 # User talk pages
3239 if( $title->getNamespace() == NS_USER_TALK ) {
3240 $user = User::newFromName( $title->getText(), false );
3241 $user->setNewtalk( false );
3242 }
3243 }
3244
3245 /**
3246 * Purge caches on page update etc
3247 */
3248 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3249 global $wgDeferredUpdateList;
3250
3251 // Invalidate caches of articles which include this page
3252 if( $transclusions !== 'skiptransclusions' )
3253 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3254
3255 // Invalidate the caches of all pages which redirect here
3256 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3257
3258 # Purge squid for this page only
3259 $title->purgeSquid();
3260
3261 # Clear file cache for this page only
3262 HTMLFileCache::clearFileCache( $title );
3263 }
3264
3265 /**#@-*/
3266
3267 /**
3268 * Overriden by ImagePage class, only present here to avoid a fatal error
3269 * Called for ?action=revert
3270 */
3271 public function revert() {
3272 global $wgOut;
3273 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3274 }
3275
3276 /**
3277 * Info about this page
3278 * Called for ?action=info when $wgAllowPageInfo is on.
3279 */
3280 public function info() {
3281 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3282
3283 if( !$wgAllowPageInfo ) {
3284 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3285 return;
3286 }
3287
3288 $page = $this->mTitle->getSubjectPage();
3289
3290 $wgOut->setPagetitle( $page->getPrefixedText() );
3291 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3292 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3293
3294 if( !$this->mTitle->exists() ) {
3295 $wgOut->addHTML( '<div class="noarticletext">' );
3296 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3297 // This doesn't quite make sense; the user is asking for
3298 // information about the _page_, not the message... -- RC
3299 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3300 } else {
3301 $msg = $wgUser->isLoggedIn()
3302 ? 'noarticletext'
3303 : 'noarticletextanon';
3304 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3305 }
3306 $wgOut->addHTML( '</div>' );
3307 } else {
3308 $dbr = wfGetDB( DB_SLAVE );
3309 $wl_clause = array(
3310 'wl_title' => $page->getDBkey(),
3311 'wl_namespace' => $page->getNamespace() );
3312 $numwatchers = $dbr->selectField(
3313 'watchlist',
3314 'COUNT(*)',
3315 $wl_clause,
3316 __METHOD__,
3317 $this->getSelectOptions() );
3318
3319 $pageInfo = $this->pageCountInfo( $page );
3320 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3321
3322 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3323 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3324 if( $talkInfo ) {
3325 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3326 }
3327 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3328 if( $talkInfo ) {
3329 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3330 }
3331 $wgOut->addHTML( '</ul>' );
3332 }
3333 }
3334
3335 /**
3336 * Return the total number of edits and number of unique editors
3337 * on a given page. If page does not exist, returns false.
3338 *
3339 * @param $title Title object
3340 * @return array
3341 */
3342 protected function pageCountInfo( $title ) {
3343 $id = $title->getArticleId();
3344 if( $id == 0 ) {
3345 return false;
3346 }
3347 $dbr = wfGetDB( DB_SLAVE );
3348 $rev_clause = array( 'rev_page' => $id );
3349 $edits = $dbr->selectField(
3350 'revision',
3351 'COUNT(rev_page)',
3352 $rev_clause,
3353 __METHOD__,
3354 $this->getSelectOptions()
3355 );
3356 $authors = $dbr->selectField(
3357 'revision',
3358 'COUNT(DISTINCT rev_user_text)',
3359 $rev_clause,
3360 __METHOD__,
3361 $this->getSelectOptions()
3362 );
3363 return array( 'edits' => $edits, 'authors' => $authors );
3364 }
3365
3366 /**
3367 * Return a list of templates used by this article.
3368 * Uses the templatelinks table
3369 *
3370 * @return Array of Title objects
3371 */
3372 public function getUsedTemplates() {
3373 $result = array();
3374 $id = $this->mTitle->getArticleID();
3375 if( $id == 0 ) {
3376 return array();
3377 }
3378 $dbr = wfGetDB( DB_SLAVE );
3379 $res = $dbr->select( array( 'templatelinks' ),
3380 array( 'tl_namespace', 'tl_title' ),
3381 array( 'tl_from' => $id ),
3382 __METHOD__ );
3383 if( $res !== false ) {
3384 foreach( $res as $row ) {
3385 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3386 }
3387 }
3388 $dbr->freeResult( $res );
3389 return $result;
3390 }
3391
3392 /**
3393 * Returns a list of hidden categories this page is a member of.
3394 * Uses the page_props and categorylinks tables.
3395 *
3396 * @return Array of Title objects
3397 */
3398 public function getHiddenCategories() {
3399 $result = array();
3400 $id = $this->mTitle->getArticleID();
3401 if( $id == 0 ) {
3402 return array();
3403 }
3404 $dbr = wfGetDB( DB_SLAVE );
3405 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3406 array( 'cl_to' ),
3407 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3408 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3409 __METHOD__ );
3410 if( $res !== false ) {
3411 foreach( $res as $row ) {
3412 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3413 }
3414 }
3415 $dbr->freeResult( $res );
3416 return $result;
3417 }
3418
3419 /**
3420 * Return an applicable autosummary if one exists for the given edit.
3421 * @param $oldtext String: the previous text of the page.
3422 * @param $newtext String: The submitted text of the page.
3423 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3424 * @return string An appropriate autosummary, or an empty string.
3425 */
3426 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3427 # Decide what kind of autosummary is needed.
3428
3429 # Redirect autosummaries
3430 $ot = Title::newFromRedirect( $oldtext );
3431 $rt = Title::newFromRedirect( $newtext );
3432 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3433 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3434 }
3435
3436 # New page autosummaries
3437 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3438 # If they're making a new article, give its text, truncated, in the summary.
3439 global $wgContLang;
3440 $truncatedtext = $wgContLang->truncate(
3441 str_replace("\n", ' ', $newtext),
3442 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3443 '...' );
3444 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3445 }
3446
3447 # Blanking autosummaries
3448 if( $oldtext != '' && $newtext == '' ) {
3449 return wfMsgForContent( 'autosumm-blank' );
3450 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3451 # Removing more than 90% of the article
3452 global $wgContLang;
3453 $truncatedtext = $wgContLang->truncate(
3454 $newtext,
3455 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3456 '...'
3457 );
3458 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3459 }
3460
3461 # If we reach this point, there's no applicable autosummary for our case, so our
3462 # autosummary is empty.
3463 return '';
3464 }
3465
3466 /**
3467 * Add the primary page-view wikitext to the output buffer
3468 * Saves the text into the parser cache if possible.
3469 * Updates templatelinks if it is out of date.
3470 *
3471 * @param $text String
3472 * @param $cache Boolean
3473 */
3474 public function outputWikiText( $text, $cache = true ) {
3475 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3476
3477 $popts = $wgOut->parserOptions();
3478 $popts->setTidy(true);
3479 $popts->enableLimitReport();
3480 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3481 $popts, true, true, $this->getRevIdFetched() );
3482 $popts->setTidy(false);
3483 $popts->enableLimitReport( false );
3484 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3485 $parserCache = ParserCache::singleton();
3486 $parserCache->save( $parserOutput, $this, $wgUser );
3487 }
3488 // Make sure file cache is not used on uncacheable content.
3489 // Output that has magic words in it can still use the parser cache
3490 // (if enabled), though it will generally expire sooner.
3491 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3492 $wgUseFileCache = false;
3493 }
3494
3495 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3496 // templatelinks table may have become out of sync,
3497 // especially if using variable-based transclusions.
3498 // For paranoia, check if things have changed and if
3499 // so apply updates to the database. This will ensure
3500 // that cascaded protections apply as soon as the changes
3501 // are visible.
3502
3503 # Get templates from templatelinks
3504 $id = $this->mTitle->getArticleID();
3505
3506 $tlTemplates = array();
3507
3508 $dbr = wfGetDB( DB_SLAVE );
3509 $res = $dbr->select( array( 'templatelinks' ),
3510 array( 'tl_namespace', 'tl_title' ),
3511 array( 'tl_from' => $id ),
3512 __METHOD__ );
3513
3514 global $wgContLang;
3515
3516 if( $res !== false ) {
3517 foreach( $res as $row ) {
3518 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3519 }
3520 }
3521
3522 # Get templates from parser output.
3523 $poTemplates_allns = $parserOutput->getTemplates();
3524
3525 $poTemplates = array ();
3526 foreach ( $poTemplates_allns as $ns_templates ) {
3527 $poTemplates = array_merge( $poTemplates, $ns_templates );
3528 }
3529
3530 # Get the diff
3531 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3532
3533 if( count( $templates_diff ) > 0 ) {
3534 # Whee, link updates time.
3535 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3536 $u->doUpdate();
3537 }
3538 }
3539
3540 $wgOut->addParserOutput( $parserOutput );
3541 }
3542
3543 /**
3544 * Update all the appropriate counts in the category table, given that
3545 * we've added the categories $added and deleted the categories $deleted.
3546 *
3547 * @param $added array The names of categories that were added
3548 * @param $deleted array The names of categories that were deleted
3549 * @return null
3550 */
3551 public function updateCategoryCounts( $added, $deleted ) {
3552 $ns = $this->mTitle->getNamespace();
3553 $dbw = wfGetDB( DB_MASTER );
3554
3555 # First make sure the rows exist. If one of the "deleted" ones didn't
3556 # exist, we might legitimately not create it, but it's simpler to just
3557 # create it and then give it a negative value, since the value is bogus
3558 # anyway.
3559 #
3560 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3561 $insertCats = array_merge( $added, $deleted );
3562 if( !$insertCats ) {
3563 # Okay, nothing to do
3564 return;
3565 }
3566 $insertRows = array();
3567 foreach( $insertCats as $cat ) {
3568 $insertRows[] = array( 'cat_title' => $cat );
3569 }
3570 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3571
3572 $addFields = array( 'cat_pages = cat_pages + 1' );
3573 $removeFields = array( 'cat_pages = cat_pages - 1' );
3574 if( $ns == NS_CATEGORY ) {
3575 $addFields[] = 'cat_subcats = cat_subcats + 1';
3576 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3577 } elseif( $ns == NS_FILE ) {
3578 $addFields[] = 'cat_files = cat_files + 1';
3579 $removeFields[] = 'cat_files = cat_files - 1';
3580 }
3581
3582 if( $added ) {
3583 $dbw->update(
3584 'category',
3585 $addFields,
3586 array( 'cat_title' => $added ),
3587 __METHOD__
3588 );
3589 }
3590 if( $deleted ) {
3591 $dbw->update(
3592 'category',
3593 $removeFields,
3594 array( 'cat_title' => $deleted ),
3595 __METHOD__
3596 );
3597 }
3598 }
3599 }