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