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