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