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