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