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