I LOVE OO PEOPLE <3 <3 <3
[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 'size' => '60',
2645 'maxlength' => '255',
2646 'tabindex' => '2',
2647 'id' => 'wpReason',
2648 'autofocus'
2649 ) ) .
2650 "</td>
2651 </tr>
2652 <tr>
2653 <td></td>
2654 <td class='mw-input'>" .
2655 Xml::checkLabel( wfMsg( 'watchthis' ),
2656 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2657 "</td>
2658 </tr>
2659 $suppress
2660 <tr>
2661 <td></td>
2662 <td class='mw-submit'>" .
2663 Xml::submitButton( wfMsg( 'deletepage' ),
2664 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2665 "</td>
2666 </tr>" .
2667 Xml::closeElement( 'table' ) .
2668 Xml::closeElement( 'fieldset' ) .
2669 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2670 Xml::closeElement( 'form' );
2671
2672 if( $wgUser->isAllowed( 'editinterface' ) ) {
2673 $skin = $wgUser->getSkin();
2674 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2675 $link = $skin->link(
2676 $title,
2677 wfMsgHtml( 'delete-edit-reasonlist' ),
2678 array(),
2679 array( 'action' => 'edit' )
2680 );
2681 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2682 }
2683
2684 $wgOut->addHTML( $form );
2685 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2686 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2687 }
2688
2689 /**
2690 * Perform a deletion and output success or failure messages
2691 */
2692 public function doDelete( $reason, $suppress = false ) {
2693 global $wgOut, $wgUser;
2694 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2695
2696 $error = '';
2697 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2698 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2699 $deleted = $this->mTitle->getPrefixedText();
2700
2701 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2702 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2703
2704 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2705
2706 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2707 $wgOut->returnToMain( false );
2708 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2709 }
2710 } else {
2711 if( $error == '' ) {
2712 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2713 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2714 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2715 } else {
2716 $wgOut->showFatalError( $error );
2717 }
2718 }
2719 }
2720
2721 /**
2722 * Back-end article deletion
2723 * Deletes the article with database consistency, writes logs, purges caches
2724 * Returns success
2725 */
2726 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2727 global $wgUseSquid, $wgDeferredUpdateList;
2728 global $wgUseTrackbacks;
2729
2730 wfDebug( __METHOD__."\n" );
2731
2732 $dbw = wfGetDB( DB_MASTER );
2733 $ns = $this->mTitle->getNamespace();
2734 $t = $this->mTitle->getDBkey();
2735 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2736
2737 if( $t == '' || $id == 0 ) {
2738 return false;
2739 }
2740
2741 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2742 array_push( $wgDeferredUpdateList, $u );
2743
2744 // Bitfields to further suppress the content
2745 if( $suppress ) {
2746 $bitfield = 0;
2747 // This should be 15...
2748 $bitfield |= Revision::DELETED_TEXT;
2749 $bitfield |= Revision::DELETED_COMMENT;
2750 $bitfield |= Revision::DELETED_USER;
2751 $bitfield |= Revision::DELETED_RESTRICTED;
2752 } else {
2753 $bitfield = 'rev_deleted';
2754 }
2755
2756 $dbw->begin();
2757 // For now, shunt the revision data into the archive table.
2758 // Text is *not* removed from the text table; bulk storage
2759 // is left intact to avoid breaking block-compression or
2760 // immutable storage schemes.
2761 //
2762 // For backwards compatibility, note that some older archive
2763 // table entries will have ar_text and ar_flags fields still.
2764 //
2765 // In the future, we may keep revisions and mark them with
2766 // the rev_deleted field, which is reserved for this purpose.
2767 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2768 array(
2769 'ar_namespace' => 'page_namespace',
2770 'ar_title' => 'page_title',
2771 'ar_comment' => 'rev_comment',
2772 'ar_user' => 'rev_user',
2773 'ar_user_text' => 'rev_user_text',
2774 'ar_timestamp' => 'rev_timestamp',
2775 'ar_minor_edit' => 'rev_minor_edit',
2776 'ar_rev_id' => 'rev_id',
2777 'ar_text_id' => 'rev_text_id',
2778 'ar_text' => '\'\'', // Be explicit to appease
2779 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2780 'ar_len' => 'rev_len',
2781 'ar_page_id' => 'page_id',
2782 'ar_deleted' => $bitfield
2783 ), array(
2784 'page_id' => $id,
2785 'page_id = rev_page'
2786 ), __METHOD__
2787 );
2788
2789 # Delete restrictions for it
2790 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2791
2792 # Now that it's safely backed up, delete it
2793 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2794 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2795 if( !$ok ) {
2796 $dbw->rollback();
2797 return false;
2798 }
2799
2800 # Fix category table counts
2801 $cats = array();
2802 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2803 foreach( $res as $row ) {
2804 $cats []= $row->cl_to;
2805 }
2806 $this->updateCategoryCounts( array(), $cats );
2807
2808 # If using cascading deletes, we can skip some explicit deletes
2809 if( !$dbw->cascadingDeletes() ) {
2810 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2811
2812 if($wgUseTrackbacks)
2813 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2814
2815 # Delete outgoing links
2816 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2817 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2818 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2819 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2820 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2821 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2822 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2823 }
2824
2825 # If using cleanup triggers, we can skip some manual deletes
2826 if( !$dbw->cleanupTriggers() ) {
2827 # Clean up recentchanges entries...
2828 $dbw->delete( 'recentchanges',
2829 array( 'rc_type != '.RC_LOG,
2830 'rc_namespace' => $this->mTitle->getNamespace(),
2831 'rc_title' => $this->mTitle->getDBkey() ),
2832 __METHOD__ );
2833 $dbw->delete( 'recentchanges',
2834 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2835 __METHOD__ );
2836 }
2837
2838 # Clear caches
2839 Article::onArticleDelete( $this->mTitle );
2840
2841 # Clear the cached article id so the interface doesn't act like we exist
2842 $this->mTitle->resetArticleID( 0 );
2843
2844 # Log the deletion, if the page was suppressed, log it at Oversight instead
2845 $logtype = $suppress ? 'suppress' : 'delete';
2846 $log = new LogPage( $logtype );
2847
2848 # Make sure logging got through
2849 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2850
2851 $dbw->commit();
2852
2853 return true;
2854 }
2855
2856 /**
2857 * Roll back the most recent consecutive set of edits to a page
2858 * from the same user; fails if there are no eligible edits to
2859 * roll back to, e.g. user is the sole contributor. This function
2860 * performs permissions checks on $wgUser, then calls commitRollback()
2861 * to do the dirty work
2862 *
2863 * @param $fromP String: Name of the user whose edits to rollback.
2864 * @param $summary String: Custom summary. Set to default summary if empty.
2865 * @param $token String: Rollback token.
2866 * @param $bot Boolean: If true, mark all reverted edits as bot.
2867 *
2868 * @param $resultDetails Array: contains result-specific array of additional values
2869 * 'alreadyrolled' : 'current' (rev)
2870 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2871 *
2872 * @return array of errors, each error formatted as
2873 * array(messagekey, param1, param2, ...).
2874 * On success, the array is empty. This array can also be passed to
2875 * OutputPage::showPermissionsErrorPage().
2876 */
2877 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2878 global $wgUser;
2879 $resultDetails = null;
2880
2881 # Check permissions
2882 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2883 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2884 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2885
2886 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2887 $errors[] = array( 'sessionfailure' );
2888
2889 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2890 $errors[] = array( 'actionthrottledtext' );
2891 }
2892 # If there were errors, bail out now
2893 if( !empty( $errors ) )
2894 return $errors;
2895
2896 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2897 }
2898
2899 /**
2900 * Backend implementation of doRollback(), please refer there for parameter
2901 * and return value documentation
2902 *
2903 * NOTE: This function does NOT check ANY permissions, it just commits the
2904 * rollback to the DB Therefore, you should only call this function direct-
2905 * ly if you want to use custom permissions checks. If you don't, use
2906 * doRollback() instead.
2907 */
2908 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2909 global $wgUseRCPatrol, $wgUser, $wgLang;
2910 $dbw = wfGetDB( DB_MASTER );
2911
2912 if( wfReadOnly() ) {
2913 return array( array( 'readonlytext' ) );
2914 }
2915
2916 # Get the last editor
2917 $current = Revision::newFromTitle( $this->mTitle );
2918 if( is_null( $current ) ) {
2919 # Something wrong... no page?
2920 return array(array('notanarticle'));
2921 }
2922
2923 $from = str_replace( '_', ' ', $fromP );
2924 if( $from != $current->getUserText() ) {
2925 $resultDetails = array( 'current' => $current );
2926 return array(array('alreadyrolled',
2927 htmlspecialchars($this->mTitle->getPrefixedText()),
2928 htmlspecialchars($fromP),
2929 htmlspecialchars($current->getUserText())
2930 ));
2931 }
2932
2933 # Get the last edit not by this guy
2934 $user = intval( $current->getUser() );
2935 $user_text = $dbw->addQuotes( $current->getUserText() );
2936 $s = $dbw->selectRow( 'revision',
2937 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2938 array( 'rev_page' => $current->getPage(),
2939 "rev_user != {$user} OR rev_user_text != {$user_text}"
2940 ), __METHOD__,
2941 array( 'USE INDEX' => 'page_timestamp',
2942 'ORDER BY' => 'rev_timestamp DESC' )
2943 );
2944 if( $s === false ) {
2945 # No one else ever edited this page
2946 return array(array('cantrollback'));
2947 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2948 # Only admins can see this text
2949 return array(array('notvisiblerev'));
2950 }
2951
2952 $set = array();
2953 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2954 # Mark all reverted edits as bot
2955 $set['rc_bot'] = 1;
2956 }
2957 if( $wgUseRCPatrol ) {
2958 # Mark all reverted edits as patrolled
2959 $set['rc_patrolled'] = 1;
2960 }
2961
2962 if( $set ) {
2963 $dbw->update( 'recentchanges', $set,
2964 array( /* WHERE */
2965 'rc_cur_id' => $current->getPage(),
2966 'rc_user_text' => $current->getUserText(),
2967 "rc_timestamp > '{$s->rev_timestamp}'",
2968 ), __METHOD__
2969 );
2970 }
2971
2972 # Generate the edit summary if necessary
2973 $target = Revision::newFromId( $s->rev_id );
2974 if( empty( $summary ) ){
2975 $summary = wfMsgForContent( 'revertpage' );
2976 }
2977
2978 # Allow the custom summary to use the same args as the default message
2979 $args = array(
2980 $target->getUserText(), $from, $s->rev_id,
2981 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2982 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2983 );
2984 $summary = wfMsgReplaceArgs( $summary, $args );
2985
2986 # Save
2987 $flags = EDIT_UPDATE;
2988
2989 if( $wgUser->isAllowed('minoredit') )
2990 $flags |= EDIT_MINOR;
2991
2992 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2993 $flags |= EDIT_FORCE_BOT;
2994 # Actually store the edit
2995 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2996 if( !empty( $status->value['revision'] ) ) {
2997 $revId = $status->value['revision']->getId();
2998 } else {
2999 $revId = false;
3000 }
3001
3002 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3003
3004 $resultDetails = array(
3005 'summary' => $summary,
3006 'current' => $current,
3007 'target' => $target,
3008 'newid' => $revId
3009 );
3010 return array();
3011 }
3012
3013 /**
3014 * User interface for rollback operations
3015 */
3016 public function rollback() {
3017 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3018 $details = null;
3019
3020 $result = $this->doRollback(
3021 $wgRequest->getVal( 'from' ),
3022 $wgRequest->getText( 'summary' ),
3023 $wgRequest->getVal( 'token' ),
3024 $wgRequest->getBool( 'bot' ),
3025 $details
3026 );
3027
3028 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
3029 $wgOut->rateLimited();
3030 return;
3031 }
3032 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3033 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3034 $errArray = $result[0];
3035 $errMsg = array_shift( $errArray );
3036 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3037 if( isset( $details['current'] ) ){
3038 $current = $details['current'];
3039 if( $current->getComment() != '' ) {
3040 $wgOut->addWikiMsgArray( 'editcomment', array(
3041 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3042 }
3043 }
3044 return;
3045 }
3046 # Display permissions errors before read-only message -- there's no
3047 # point in misleading the user into thinking the inability to rollback
3048 # is only temporary.
3049 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3050 # array_diff is completely broken for arrays of arrays, sigh. Re-
3051 # move any 'readonlytext' error manually.
3052 $out = array();
3053 foreach( $result as $error ) {
3054 if( $error != array( 'readonlytext' ) ) {
3055 $out []= $error;
3056 }
3057 }
3058 $wgOut->showPermissionsErrorPage( $out );
3059 return;
3060 }
3061 if( $result == array( array( 'readonlytext' ) ) ) {
3062 $wgOut->readOnlyPage();
3063 return;
3064 }
3065
3066 $current = $details['current'];
3067 $target = $details['target'];
3068 $newId = $details['newid'];
3069 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3070 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3071 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3072 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3073 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3074 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3075 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3076 $wgOut->returnToMain( false, $this->mTitle );
3077
3078 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3079 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3080 $de->showDiff( '', '' );
3081 }
3082 }
3083
3084
3085 /**
3086 * Do standard deferred updates after page view
3087 */
3088 public function viewUpdates() {
3089 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3090 if ( wfReadOnly() ) {
3091 return;
3092 }
3093 # Don't update page view counters on views from bot users (bug 14044)
3094 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
3095 Article::incViewCount( $this->getID() );
3096 $u = new SiteStatsUpdate( 1, 0, 0 );
3097 array_push( $wgDeferredUpdateList, $u );
3098 }
3099 # Update newtalk / watchlist notification status
3100 $wgUser->clearNotification( $this->mTitle );
3101 }
3102
3103 /**
3104 * Prepare text which is about to be saved.
3105 * Returns a stdclass with source, pst and output members
3106 */
3107 public function prepareTextForEdit( $text, $revid=null ) {
3108 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
3109 // Already prepared
3110 return $this->mPreparedEdit;
3111 }
3112 global $wgParser;
3113 $edit = (object)array();
3114 $edit->revid = $revid;
3115 $edit->newText = $text;
3116 $edit->pst = $this->preSaveTransform( $text );
3117 $options = $this->getParserOptions();
3118 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3119 $edit->oldText = $this->getContent();
3120 $this->mPreparedEdit = $edit;
3121 return $edit;
3122 }
3123
3124 /**
3125 * Do standard deferred updates after page edit.
3126 * Update links tables, site stats, search index and message cache.
3127 * Purges pages that include this page if the text was changed here.
3128 * Every 100th edit, prune the recent changes table.
3129 *
3130 * @private
3131 * @param $text New text of the article
3132 * @param $summary Edit summary
3133 * @param $minoredit Minor edit
3134 * @param $timestamp_of_pagechange Timestamp associated with the page change
3135 * @param $newid rev_id value of the new revision
3136 * @param $changed Whether or not the content actually changed
3137 */
3138 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3139 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
3140
3141 wfProfileIn( __METHOD__ );
3142
3143 # Parse the text
3144 # Be careful not to double-PST: $text is usually already PST-ed once
3145 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3146 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3147 $editInfo = $this->prepareTextForEdit( $text, $newid );
3148 } else {
3149 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3150 $editInfo = $this->mPreparedEdit;
3151 }
3152
3153 # Save it to the parser cache
3154 if( $wgEnableParserCache ) {
3155 $popts = $this->getParserOptions();
3156 $parserCache = ParserCache::singleton();
3157 $parserCache->save( $editInfo->output, $this, $popts );
3158 }
3159
3160 # Update the links tables
3161 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3162 $u->doUpdate();
3163
3164 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3165
3166 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3167 if( 0 == mt_rand( 0, 99 ) ) {
3168 // Flush old entries from the `recentchanges` table; we do this on
3169 // random requests so as to avoid an increase in writes for no good reason
3170 global $wgRCMaxAge;
3171 $dbw = wfGetDB( DB_MASTER );
3172 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3173 $recentchanges = $dbw->tableName( 'recentchanges' );
3174 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3175 $dbw->query( $sql );
3176 }
3177 }
3178
3179 $id = $this->getID();
3180 $title = $this->mTitle->getPrefixedDBkey();
3181 $shortTitle = $this->mTitle->getDBkey();
3182
3183 if( 0 == $id ) {
3184 wfProfileOut( __METHOD__ );
3185 return;
3186 }
3187
3188 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3189 array_push( $wgDeferredUpdateList, $u );
3190 $u = new SearchUpdate( $id, $title, $text );
3191 array_push( $wgDeferredUpdateList, $u );
3192
3193 # If this is another user's talk page, update newtalk
3194 # Don't do this if $changed = false otherwise some idiot can null-edit a
3195 # load of user talk pages and piss people off, nor if it's a minor edit
3196 # by a properly-flagged bot.
3197 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3198 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3199 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3200 $other = User::newFromName( $shortTitle, false );
3201 if( !$other ) {
3202 wfDebug( __METHOD__.": invalid username\n" );
3203 } elseif( User::isIP( $shortTitle ) ) {
3204 // An anonymous user
3205 $other->setNewtalk( true );
3206 } elseif( $other->isLoggedIn() ) {
3207 $other->setNewtalk( true );
3208 } else {
3209 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
3210 }
3211 }
3212 }
3213
3214 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3215 $wgMessageCache->replace( $shortTitle, $text );
3216 }
3217
3218 wfProfileOut( __METHOD__ );
3219 }
3220
3221 /**
3222 * Perform article updates on a special page creation.
3223 *
3224 * @param $rev Revision object
3225 *
3226 * @todo This is a shitty interface function. Kill it and replace the
3227 * other shitty functions like editUpdates and such so it's not needed
3228 * anymore.
3229 */
3230 public function createUpdates( $rev ) {
3231 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3232 $this->mTotalAdjustment = 1;
3233 $this->editUpdates( $rev->getText(), $rev->getComment(),
3234 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3235 }
3236
3237 /**
3238 * Generate the navigation links when browsing through an article revisions
3239 * It shows the information as:
3240 * Revision as of \<date\>; view current revision
3241 * \<- Previous version | Next Version -\>
3242 *
3243 * @param $oldid String: revision ID of this article revision
3244 */
3245 public function setOldSubtitle( $oldid = 0 ) {
3246 global $wgLang, $wgOut, $wgUser, $wgRequest;
3247
3248 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3249 return;
3250 }
3251
3252 $revision = Revision::newFromId( $oldid );
3253
3254 $current = ( $oldid == $this->mLatest );
3255 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3256 $tddate = $wgLang->date( $this->mTimestamp, true );
3257 $tdtime = $wgLang->time( $this->mTimestamp, true );
3258 $sk = $wgUser->getSkin();
3259 $lnk = $current
3260 ? wfMsgHtml( 'currentrevisionlink' )
3261 : $sk->link(
3262 $this->mTitle,
3263 wfMsgHtml( 'currentrevisionlink' ),
3264 array(),
3265 array(),
3266 array( 'known', 'noclasses' )
3267 );
3268 $curdiff = $current
3269 ? wfMsgHtml( 'diff' )
3270 : $sk->link(
3271 $this->mTitle,
3272 wfMsgHtml( 'diff' ),
3273 array(),
3274 array(
3275 'diff' => 'cur',
3276 'oldid' => $oldid
3277 ),
3278 array( 'known', 'noclasses' )
3279 );
3280 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3281 $prevlink = $prev
3282 ? $sk->link(
3283 $this->mTitle,
3284 wfMsgHtml( 'previousrevision' ),
3285 array(),
3286 array(
3287 'direction' => 'prev',
3288 'oldid' => $oldid
3289 ),
3290 array( 'known', 'noclasses' )
3291 )
3292 : wfMsgHtml( 'previousrevision' );
3293 $prevdiff = $prev
3294 ? $sk->link(
3295 $this->mTitle,
3296 wfMsgHtml( 'diff' ),
3297 array(),
3298 array(
3299 'diff' => 'prev',
3300 'oldid' => $oldid
3301 ),
3302 array( 'known', 'noclasses' )
3303 )
3304 : wfMsgHtml( 'diff' );
3305 $nextlink = $current
3306 ? wfMsgHtml( 'nextrevision' )
3307 : $sk->link(
3308 $this->mTitle,
3309 wfMsgHtml( 'nextrevision' ),
3310 array(),
3311 array(
3312 'direction' => 'next',
3313 'oldid' => $oldid
3314 ),
3315 array( 'known', 'noclasses' )
3316 );
3317 $nextdiff = $current
3318 ? wfMsgHtml( 'diff' )
3319 : $sk->link(
3320 $this->mTitle,
3321 wfMsgHtml( 'diff' ),
3322 array(),
3323 array(
3324 'diff' => 'next',
3325 'oldid' => $oldid
3326 ),
3327 array( 'known', 'noclasses' )
3328 );
3329
3330 $cdel='';
3331 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3332 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
3333 if( $revision->isCurrent() ) {
3334 // We don't handle top deleted edits too well
3335 $cdel = wfMsgHtml( 'rev-delundel' );
3336 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3337 // If revision was hidden from sysops
3338 $cdel = wfMsgHtml( 'rev-delundel' );
3339 } else {
3340 $cdel = $sk->link(
3341 $revdel,
3342 wfMsgHtml('rev-delundel'),
3343 array(),
3344 array(
3345 'type' => 'revision',
3346 'target' => urlencode( $this->mTitle->getPrefixedDbkey() ),
3347 'ids' => urlencode( $oldid )
3348 ),
3349 array( 'known', 'noclasses' )
3350 );
3351 // Bolden oversighted content
3352 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
3353 $cdel = "<strong>$cdel</strong>";
3354 }
3355 $cdel = "(<small>$cdel</small>) ";
3356 }
3357 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3358 # Show user links if allowed to see them. If hidden, then show them only if requested...
3359 $userlinks = $sk->revUserTools( $revision, !$unhide );
3360
3361 $m = wfMsg( 'revision-info-current' );
3362 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3363 ? 'revision-info-current'
3364 : 'revision-info';
3365
3366 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3367 wfMsgExt(
3368 $infomsg,
3369 array( 'parseinline', 'replaceafter' ),
3370 $td,
3371 $userlinks,
3372 $revision->getID(),
3373 $tddate,
3374 $tdtime,
3375 $revision->getUser()
3376 ) .
3377 "</div>\n" .
3378 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3379 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3380 $wgOut->setSubtitle( $r );
3381 }
3382
3383 /**
3384 * This function is called right before saving the wikitext,
3385 * so we can do things like signatures and links-in-context.
3386 *
3387 * @param $text String
3388 */
3389 public function preSaveTransform( $text ) {
3390 global $wgParser, $wgUser;
3391 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3392 }
3393
3394 /* Caching functions */
3395
3396 /**
3397 * checkLastModified returns true if it has taken care of all
3398 * output to the client that is necessary for this request.
3399 * (that is, it has sent a cached version of the page)
3400 */
3401 protected function tryFileCache() {
3402 static $called = false;
3403 if( $called ) {
3404 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3405 return false;
3406 }
3407 $called = true;
3408 if( $this->isFileCacheable() ) {
3409 $cache = new HTMLFileCache( $this->mTitle );
3410 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3411 wfDebug( "Article::tryFileCache(): about to load file\n" );
3412 $cache->loadFromFileCache();
3413 return true;
3414 } else {
3415 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3416 ob_start( array(&$cache, 'saveToFileCache' ) );
3417 }
3418 } else {
3419 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3420 }
3421 return false;
3422 }
3423
3424 /**
3425 * Check if the page can be cached
3426 * @return bool
3427 */
3428 public function isFileCacheable() {
3429 $cacheable = false;
3430 global $wgUseFileCache;
3431 if( $wgUseFileCache and HTMLFileCache::useFileCache() ) {
3432 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3433 // Extension may have reason to disable file caching on some pages.
3434 if( $cacheable ) {
3435 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3436 }
3437 }
3438 return $cacheable;
3439 }
3440
3441 /**
3442 * Loads page_touched and returns a value indicating if it should be used
3443 *
3444 */
3445 public function checkTouched() {
3446 if( !$this->mDataLoaded ) {
3447 $this->loadPageData();
3448 }
3449 return !$this->mIsRedirect;
3450 }
3451
3452 /**
3453 * Get the page_touched field
3454 */
3455 public function getTouched() {
3456 # Ensure that page data has been loaded
3457 if( !$this->mDataLoaded ) {
3458 $this->loadPageData();
3459 }
3460 return $this->mTouched;
3461 }
3462
3463 /**
3464 * Get the page_latest field
3465 */
3466 public function getLatest() {
3467 if( !$this->mDataLoaded ) {
3468 $this->loadPageData();
3469 }
3470 return (int)$this->mLatest;
3471 }
3472
3473 /**
3474 * Edit an article without doing all that other stuff
3475 * The article must already exist; link tables etc
3476 * are not updated, caches are not flushed.
3477 *
3478 * @param $text String: text submitted
3479 * @param $comment String: comment submitted
3480 * @param $minor Boolean: whereas it's a minor modification
3481 */
3482 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3483 wfProfileIn( __METHOD__ );
3484
3485 $dbw = wfGetDB( DB_MASTER );
3486 $revision = new Revision( array(
3487 'page' => $this->getId(),
3488 'text' => $text,
3489 'comment' => $comment,
3490 'minor_edit' => $minor ? 1 : 0,
3491 ) );
3492 $revision->insertOn( $dbw );
3493 $this->updateRevisionOn( $dbw, $revision );
3494
3495 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3496
3497 wfProfileOut( __METHOD__ );
3498 }
3499
3500 /**
3501 * Used to increment the view counter
3502 *
3503 * @param $id Integer: article id
3504 */
3505 public static function incViewCount( $id ) {
3506 $id = intval( $id );
3507 global $wgHitcounterUpdateFreq, $wgDBtype;
3508
3509 $dbw = wfGetDB( DB_MASTER );
3510 $pageTable = $dbw->tableName( 'page' );
3511 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3512 $acchitsTable = $dbw->tableName( 'acchits' );
3513
3514 if( $wgHitcounterUpdateFreq <= 1 ) {
3515 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3516 return;
3517 }
3518
3519 # Not important enough to warrant an error page in case of failure
3520 $oldignore = $dbw->ignoreErrors( true );
3521
3522 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3523
3524 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3525 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3526 # Most of the time (or on SQL errors), skip row count check
3527 $dbw->ignoreErrors( $oldignore );
3528 return;
3529 }
3530
3531 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3532 $row = $dbw->fetchObject( $res );
3533 $rown = intval( $row->n );
3534 if( $rown >= $wgHitcounterUpdateFreq ){
3535 wfProfileIn( 'Article::incViewCount-collect' );
3536 $old_user_abort = ignore_user_abort( true );
3537
3538 if($wgDBtype == 'mysql')
3539 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3540 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3541 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3542 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3543 'GROUP BY hc_id');
3544 $dbw->query("DELETE FROM $hitcounterTable");
3545 if($wgDBtype == 'mysql') {
3546 $dbw->query('UNLOCK TABLES');
3547 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3548 'WHERE page_id = hc_id');
3549 }
3550 else {
3551 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3552 "FROM $acchitsTable WHERE page_id = hc_id");
3553 }
3554 $dbw->query("DROP TABLE $acchitsTable");
3555
3556 ignore_user_abort( $old_user_abort );
3557 wfProfileOut( 'Article::incViewCount-collect' );
3558 }
3559 $dbw->ignoreErrors( $oldignore );
3560 }
3561
3562 /**#@+
3563 * The onArticle*() functions are supposed to be a kind of hooks
3564 * which should be called whenever any of the specified actions
3565 * are done.
3566 *
3567 * This is a good place to put code to clear caches, for instance.
3568 *
3569 * This is called on page move and undelete, as well as edit
3570 *
3571 * @param $title a title object
3572 */
3573
3574 public static function onArticleCreate( $title ) {
3575 # Update existence markers on article/talk tabs...
3576 if( $title->isTalkPage() ) {
3577 $other = $title->getSubjectPage();
3578 } else {
3579 $other = $title->getTalkPage();
3580 }
3581 $other->invalidateCache();
3582 $other->purgeSquid();
3583
3584 $title->touchLinks();
3585 $title->purgeSquid();
3586 $title->deleteTitleProtection();
3587 }
3588
3589 public static function onArticleDelete( $title ) {
3590 global $wgMessageCache;
3591 # Update existence markers on article/talk tabs...
3592 if( $title->isTalkPage() ) {
3593 $other = $title->getSubjectPage();
3594 } else {
3595 $other = $title->getTalkPage();
3596 }
3597 $other->invalidateCache();
3598 $other->purgeSquid();
3599
3600 $title->touchLinks();
3601 $title->purgeSquid();
3602
3603 # File cache
3604 HTMLFileCache::clearFileCache( $title );
3605
3606 # Messages
3607 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3608 $wgMessageCache->replace( $title->getDBkey(), false );
3609 }
3610 # Images
3611 if( $title->getNamespace() == NS_FILE ) {
3612 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3613 $update->doUpdate();
3614 }
3615 # User talk pages
3616 if( $title->getNamespace() == NS_USER_TALK ) {
3617 $user = User::newFromName( $title->getText(), false );
3618 $user->setNewtalk( false );
3619 }
3620 # Image redirects
3621 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3622 }
3623
3624 /**
3625 * Purge caches on page update etc
3626 */
3627 public static function onArticleEdit( $title, $flags = '' ) {
3628 global $wgDeferredUpdateList;
3629
3630 // Invalidate caches of articles which include this page
3631 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3632
3633 // Invalidate the caches of all pages which redirect here
3634 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3635
3636 # Purge squid for this page only
3637 $title->purgeSquid();
3638
3639 # Clear file cache for this page only
3640 HTMLFileCache::clearFileCache( $title );
3641 }
3642
3643 /**#@-*/
3644
3645 /**
3646 * Overriden by ImagePage class, only present here to avoid a fatal error
3647 * Called for ?action=revert
3648 */
3649 public function revert() {
3650 global $wgOut;
3651 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3652 }
3653
3654 /**
3655 * Info about this page
3656 * Called for ?action=info when $wgAllowPageInfo is on.
3657 */
3658 public function info() {
3659 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3660
3661 if( !$wgAllowPageInfo ) {
3662 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3663 return;
3664 }
3665
3666 $page = $this->mTitle->getSubjectPage();
3667
3668 $wgOut->setPagetitle( $page->getPrefixedText() );
3669 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3670 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3671
3672 if( !$this->mTitle->exists() ) {
3673 $wgOut->addHTML( '<div class="noarticletext">' );
3674 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3675 // This doesn't quite make sense; the user is asking for
3676 // information about the _page_, not the message... -- RC
3677 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3678 } else {
3679 $msg = $wgUser->isLoggedIn()
3680 ? 'noarticletext'
3681 : 'noarticletextanon';
3682 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3683 }
3684 $wgOut->addHTML( '</div>' );
3685 } else {
3686 $dbr = wfGetDB( DB_SLAVE );
3687 $wl_clause = array(
3688 'wl_title' => $page->getDBkey(),
3689 'wl_namespace' => $page->getNamespace() );
3690 $numwatchers = $dbr->selectField(
3691 'watchlist',
3692 'COUNT(*)',
3693 $wl_clause,
3694 __METHOD__,
3695 $this->getSelectOptions() );
3696
3697 $pageInfo = $this->pageCountInfo( $page );
3698 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3699
3700 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3701 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3702 if( $talkInfo ) {
3703 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3704 }
3705 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3706 if( $talkInfo ) {
3707 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3708 }
3709 $wgOut->addHTML( '</ul>' );
3710 }
3711 }
3712
3713 /**
3714 * Return the total number of edits and number of unique editors
3715 * on a given page. If page does not exist, returns false.
3716 *
3717 * @param $title Title object
3718 * @return array
3719 */
3720 public function pageCountInfo( $title ) {
3721 $id = $title->getArticleId();
3722 if( $id == 0 ) {
3723 return false;
3724 }
3725 $dbr = wfGetDB( DB_SLAVE );
3726 $rev_clause = array( 'rev_page' => $id );
3727 $edits = $dbr->selectField(
3728 'revision',
3729 'COUNT(rev_page)',
3730 $rev_clause,
3731 __METHOD__,
3732 $this->getSelectOptions()
3733 );
3734 $authors = $dbr->selectField(
3735 'revision',
3736 'COUNT(DISTINCT rev_user_text)',
3737 $rev_clause,
3738 __METHOD__,
3739 $this->getSelectOptions()
3740 );
3741 return array( 'edits' => $edits, 'authors' => $authors );
3742 }
3743
3744 /**
3745 * Return a list of templates used by this article.
3746 * Uses the templatelinks table
3747 *
3748 * @return Array of Title objects
3749 */
3750 public function getUsedTemplates() {
3751 $result = array();
3752 $id = $this->mTitle->getArticleID();
3753 if( $id == 0 ) {
3754 return array();
3755 }
3756 $dbr = wfGetDB( DB_SLAVE );
3757 $res = $dbr->select( array( 'templatelinks' ),
3758 array( 'tl_namespace', 'tl_title' ),
3759 array( 'tl_from' => $id ),
3760 __METHOD__ );
3761 if( $res !== false ) {
3762 foreach( $res as $row ) {
3763 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3764 }
3765 }
3766 $dbr->freeResult( $res );
3767 return $result;
3768 }
3769
3770 /**
3771 * Returns a list of hidden categories this page is a member of.
3772 * Uses the page_props and categorylinks tables.
3773 *
3774 * @return Array of Title objects
3775 */
3776 public function getHiddenCategories() {
3777 $result = array();
3778 $id = $this->mTitle->getArticleID();
3779 if( $id == 0 ) {
3780 return array();
3781 }
3782 $dbr = wfGetDB( DB_SLAVE );
3783 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3784 array( 'cl_to' ),
3785 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3786 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3787 __METHOD__ );
3788 if( $res !== false ) {
3789 foreach( $res as $row ) {
3790 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3791 }
3792 }
3793 $dbr->freeResult( $res );
3794 return $result;
3795 }
3796
3797 /**
3798 * Return an applicable autosummary if one exists for the given edit.
3799 * @param $oldtext String: the previous text of the page.
3800 * @param $newtext String: The submitted text of the page.
3801 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3802 * @return string An appropriate autosummary, or an empty string.
3803 */
3804 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3805 # Decide what kind of autosummary is needed.
3806
3807 # Redirect autosummaries
3808 $ot = Title::newFromRedirect( $oldtext );
3809 $rt = Title::newFromRedirect( $newtext );
3810 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3811 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3812 }
3813
3814 # New page autosummaries
3815 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3816 # If they're making a new article, give its text, truncated, in the summary.
3817 global $wgContLang;
3818 $truncatedtext = $wgContLang->truncate(
3819 str_replace("\n", ' ', $newtext),
3820 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3821 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3822 }
3823
3824 # Blanking autosummaries
3825 if( $oldtext != '' && $newtext == '' ) {
3826 return wfMsgForContent( 'autosumm-blank' );
3827 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3828 # Removing more than 90% of the article
3829 global $wgContLang;
3830 $truncatedtext = $wgContLang->truncate(
3831 $newtext,
3832 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3833 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3834 }
3835
3836 # If we reach this point, there's no applicable autosummary for our case, so our
3837 # autosummary is empty.
3838 return '';
3839 }
3840
3841 /**
3842 * Add the primary page-view wikitext to the output buffer
3843 * Saves the text into the parser cache if possible.
3844 * Updates templatelinks if it is out of date.
3845 *
3846 * @param $text String
3847 * @param $cache Boolean
3848 */
3849 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
3850 global $wgOut;
3851
3852 $parserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
3853 $wgOut->addParserOutput( $parserOutput );
3854 }
3855
3856 /**
3857 * This does all the heavy lifting for outputWikitext, except it returns the parser
3858 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
3859 * say, embedding thread pages within a discussion system (LiquidThreads)
3860 */
3861 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
3862 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3863
3864 if ( !$parserOptions ) {
3865 $parserOptions = $this->getParserOptions();
3866 }
3867
3868 $time = -wfTime();
3869 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3870 $parserOptions, true, true, $this->getRevIdFetched() );
3871 $time += wfTime();
3872
3873 # Timing hack
3874 if( $time > 3 ) {
3875 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3876 $this->mTitle->getPrefixedDBkey()));
3877 }
3878
3879 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3880 $parserCache = ParserCache::singleton();
3881 $parserCache->save( $parserOutput, $this, $parserOptions );
3882 }
3883 // Make sure file cache is not used on uncacheable content.
3884 // Output that has magic words in it can still use the parser cache
3885 // (if enabled), though it will generally expire sooner.
3886 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3887 $wgUseFileCache = false;
3888 }
3889 $this->doCascadeProtectionUpdates( $parserOutput );
3890 return $parserOutput;
3891 }
3892
3893 /**
3894 * Get parser options suitable for rendering the primary article wikitext
3895 */
3896 public function getParserOptions() {
3897 global $wgUser;
3898 if ( !$this->mParserOptions ) {
3899 $this->mParserOptions = new ParserOptions( $wgUser );
3900 $this->mParserOptions->setTidy( true );
3901 $this->mParserOptions->enableLimitReport();
3902 }
3903 return $this->mParserOptions;
3904 }
3905
3906 protected function doCascadeProtectionUpdates( $parserOutput ) {
3907 if( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3908 return;
3909 }
3910
3911 // templatelinks table may have become out of sync,
3912 // especially if using variable-based transclusions.
3913 // For paranoia, check if things have changed and if
3914 // so apply updates to the database. This will ensure
3915 // that cascaded protections apply as soon as the changes
3916 // are visible.
3917
3918 # Get templates from templatelinks
3919 $id = $this->mTitle->getArticleID();
3920
3921 $tlTemplates = array();
3922
3923 $dbr = wfGetDB( DB_SLAVE );
3924 $res = $dbr->select( array( 'templatelinks' ),
3925 array( 'tl_namespace', 'tl_title' ),
3926 array( 'tl_from' => $id ),
3927 __METHOD__ );
3928
3929 global $wgContLang;
3930 foreach( $res as $row ) {
3931 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3932 }
3933
3934 # Get templates from parser output.
3935 $poTemplates = array();
3936 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3937 foreach ( $templates as $dbk => $id ) {
3938 $poTemplates["$ns:$dbk"] = true;
3939 }
3940 }
3941
3942 # Get the diff
3943 # Note that we simulate array_diff_key in PHP <5.0.x
3944 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3945
3946 if( count( $templates_diff ) > 0 ) {
3947 # Whee, link updates time.
3948 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3949 $u->doUpdate();
3950 }
3951 }
3952
3953 /**
3954 * Update all the appropriate counts in the category table, given that
3955 * we've added the categories $added and deleted the categories $deleted.
3956 *
3957 * @param $added array The names of categories that were added
3958 * @param $deleted array The names of categories that were deleted
3959 * @return null
3960 */
3961 public function updateCategoryCounts( $added, $deleted ) {
3962 $ns = $this->mTitle->getNamespace();
3963 $dbw = wfGetDB( DB_MASTER );
3964
3965 # First make sure the rows exist. If one of the "deleted" ones didn't
3966 # exist, we might legitimately not create it, but it's simpler to just
3967 # create it and then give it a negative value, since the value is bogus
3968 # anyway.
3969 #
3970 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3971 $insertCats = array_merge( $added, $deleted );
3972 if( !$insertCats ) {
3973 # Okay, nothing to do
3974 return;
3975 }
3976 $insertRows = array();
3977 foreach( $insertCats as $cat ) {
3978 $insertRows[] = array( 'cat_title' => $cat );
3979 }
3980 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3981
3982 $addFields = array( 'cat_pages = cat_pages + 1' );
3983 $removeFields = array( 'cat_pages = cat_pages - 1' );
3984 if( $ns == NS_CATEGORY ) {
3985 $addFields[] = 'cat_subcats = cat_subcats + 1';
3986 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3987 } elseif( $ns == NS_FILE ) {
3988 $addFields[] = 'cat_files = cat_files + 1';
3989 $removeFields[] = 'cat_files = cat_files - 1';
3990 }
3991
3992 if( $added ) {
3993 $dbw->update(
3994 'category',
3995 $addFields,
3996 array( 'cat_title' => $added ),
3997 __METHOD__
3998 );
3999 }
4000 if( $deleted ) {
4001 $dbw->update(
4002 'category',
4003 $removeFields,
4004 array( 'cat_title' => $deleted ),
4005 __METHOD__
4006 );
4007 }
4008 }
4009
4010 /** Lightweight method to get the parser output for a page, checking the parser cache
4011 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4012 * consider, so it's not appropriate to use there. */
4013 function getParserOutput( $oldid = null ) {
4014 global $wgEnableParserCache, $wgUser, $wgOut;
4015
4016 // Should the parser cache be used?
4017 $useParserCache = $wgEnableParserCache &&
4018 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4019 $this->exists() &&
4020 $oldid === null;
4021
4022 wfDebug( __METHOD__.': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4023 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4024 wfIncrStats( 'pcache_miss_stub' );
4025 }
4026
4027 $parserOutput = false;
4028 if ( $useParserCache ) {
4029 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4030 }
4031
4032 if ( $parserOutput === false ) {
4033 // Cache miss; parse and output it.
4034 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4035
4036 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4037 } else {
4038 return $parserOutput;
4039 }
4040 }
4041 }