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