* fixed some doxygen warnings
[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 * @param $text String: new text of the section
1763 * @param $summary String: new section's subject, only if $section is 'new'
1764 * @param $edittime String: revision timestamp or null to use the current revision
1765 * @return string Complete article text, or null if error
1766 */
1767 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1768 wfProfileIn( __METHOD__ );
1769 if ( strval( $section ) == '' ) {
1770 // Whole-page edit; let the whole text through
1771 } else {
1772 if ( is_null( $edittime ) ) {
1773 $rev = Revision::newFromTitle( $this->mTitle );
1774 } else {
1775 $dbw = wfGetDB( DB_MASTER );
1776 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1777 }
1778 if ( !$rev ) {
1779 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1780 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1781 return null;
1782 }
1783 $oldtext = $rev->getText();
1784
1785 if ( $section == 'new' ) {
1786 # Inserting a new section
1787 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1788 $text = strlen( trim( $oldtext ) ) > 0
1789 ? "{$oldtext}\n\n{$subject}{$text}"
1790 : "{$subject}{$text}";
1791 } else {
1792 # Replacing an existing section; roll out the big guns
1793 global $wgParser;
1794 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1795 }
1796 }
1797 wfProfileOut( __METHOD__ );
1798 return $text;
1799 }
1800
1801 /**
1802 * This function is not deprecated until somebody fixes the core not to use
1803 * it. Nevertheless, use Article::doEdit() instead.
1804 */
1805 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1806 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1807 ( $isminor ? EDIT_MINOR : 0 ) |
1808 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1809 ( $bot ? EDIT_FORCE_BOT : 0 );
1810
1811 # If this is a comment, add the summary as headline
1812 if ( $comment && $summary != "" ) {
1813 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
1814 }
1815
1816 $this->doEdit( $text, $summary, $flags );
1817
1818 $dbw = wfGetDB( DB_MASTER );
1819 if ( $watchthis ) {
1820 if ( !$this->mTitle->userIsWatching() ) {
1821 $dbw->begin();
1822 $this->doWatch();
1823 $dbw->commit();
1824 }
1825 } else {
1826 if ( $this->mTitle->userIsWatching() ) {
1827 $dbw->begin();
1828 $this->doUnwatch();
1829 $dbw->commit();
1830 }
1831 }
1832 $this->doRedirect( $this->isRedirect( $text ) );
1833 }
1834
1835 /**
1836 * @deprecated use Article::doEdit()
1837 */
1838 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1839 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1840 ( $minor ? EDIT_MINOR : 0 ) |
1841 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1842
1843 $status = $this->doEdit( $text, $summary, $flags );
1844 if ( !$status->isOK() ) {
1845 return false;
1846 }
1847
1848 $dbw = wfGetDB( DB_MASTER );
1849 if ( $watchthis ) {
1850 if ( !$this->mTitle->userIsWatching() ) {
1851 $dbw->begin();
1852 $this->doWatch();
1853 $dbw->commit();
1854 }
1855 } else {
1856 if ( $this->mTitle->userIsWatching() ) {
1857 $dbw->begin();
1858 $this->doUnwatch();
1859 $dbw->commit();
1860 }
1861 }
1862
1863 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1864 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1865
1866 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1867 return true;
1868 }
1869
1870 /**
1871 * Article::doEdit()
1872 *
1873 * Change an existing article or create a new article. Updates RC and all necessary caches,
1874 * optionally via the deferred update array.
1875 *
1876 * $wgUser must be set before calling this function.
1877 *
1878 * @param $text String: new text
1879 * @param $summary String: edit summary
1880 * @param $flags Integer bitfield:
1881 * EDIT_NEW
1882 * Article is known or assumed to be non-existent, create a new one
1883 * EDIT_UPDATE
1884 * Article is known or assumed to be pre-existing, update it
1885 * EDIT_MINOR
1886 * Mark this edit minor, if the user is allowed to do so
1887 * EDIT_SUPPRESS_RC
1888 * Do not log the change in recentchanges
1889 * EDIT_FORCE_BOT
1890 * Mark the edit a "bot" edit regardless of user rights
1891 * EDIT_DEFER_UPDATES
1892 * Defer some of the updates until the end of index.php
1893 * EDIT_AUTOSUMMARY
1894 * Fill in blank summaries with generated text where possible
1895 *
1896 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1897 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1898 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1899 * edit-already-exists error will be returned. These two conditions are also possible with
1900 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1901 *
1902 * @param $baseRevId the revision ID this edit was based off, if any
1903 * @param $user Optional user object, $wgUser will be used if not passed
1904 *
1905 * @return Status object. Possible errors:
1906 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1907 * edit-gone-missing: In update mode, but the article didn't exist
1908 * edit-conflict: In update mode, the article changed unexpectedly
1909 * edit-no-change: Warning that the text was the same as before
1910 * edit-already-exists: In creation mode, but the article already exists
1911 *
1912 * Extensions may define additional errors.
1913 *
1914 * $return->value will contain an associative array with members as follows:
1915 * new: Boolean indicating if the function attempted to create a new article
1916 * revision: The revision object for the inserted revision, or null
1917 *
1918 * Compatibility note: this function previously returned a boolean value indicating success/failure
1919 */
1920 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1921 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1922
1923 # Low-level sanity check
1924 if ( $this->mTitle->getText() == '' ) {
1925 throw new MWException( 'Something is trying to edit an article with an empty title' );
1926 }
1927
1928 wfProfileIn( __METHOD__ );
1929
1930 $user = is_null( $user ) ? $wgUser : $user;
1931 $status = Status::newGood( array() );
1932
1933 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1934 $this->loadPageData();
1935
1936 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1937 $aid = $this->mTitle->getArticleID();
1938 if ( $aid ) {
1939 $flags |= EDIT_UPDATE;
1940 } else {
1941 $flags |= EDIT_NEW;
1942 }
1943 }
1944
1945 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1946 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1947 {
1948 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1949 wfProfileOut( __METHOD__ );
1950 if ( $status->isOK() ) {
1951 $status->fatal( 'edit-hook-aborted' );
1952 }
1953 return $status;
1954 }
1955
1956 # Silently ignore EDIT_MINOR if not allowed
1957 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1958 $bot = $flags & EDIT_FORCE_BOT;
1959
1960 $oldtext = $this->getRawText(); // current revision
1961 $oldsize = strlen( $oldtext );
1962
1963 # Provide autosummaries if one is not provided and autosummaries are enabled.
1964 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1965 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1966 }
1967
1968 $editInfo = $this->prepareTextForEdit( $text );
1969 $text = $editInfo->pst;
1970 $newsize = strlen( $text );
1971
1972 $dbw = wfGetDB( DB_MASTER );
1973 $now = wfTimestampNow();
1974 $this->mTimestamp = $now;
1975
1976 if ( $flags & EDIT_UPDATE ) {
1977 # Update article, but only if changed.
1978 $status->value['new'] = false;
1979 # Make sure the revision is either completely inserted or not inserted at all
1980 if ( !$wgDBtransactions ) {
1981 $userAbort = ignore_user_abort( true );
1982 }
1983
1984 $revisionId = 0;
1985
1986 $changed = ( strcmp( $text, $oldtext ) != 0 );
1987
1988 if ( $changed ) {
1989 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1990 - (int)$this->isCountable( $oldtext );
1991 $this->mTotalAdjustment = 0;
1992
1993 if ( !$this->mLatest ) {
1994 # Article gone missing
1995 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1996 $status->fatal( 'edit-gone-missing' );
1997 wfProfileOut( __METHOD__ );
1998 return $status;
1999 }
2000
2001 $revision = new Revision( array(
2002 'page' => $this->getId(),
2003 'comment' => $summary,
2004 'minor_edit' => $isminor,
2005 'text' => $text,
2006 'parent_id' => $this->mLatest,
2007 'user' => $user->getId(),
2008 'user_text' => $user->getName(),
2009 ) );
2010
2011 $dbw->begin();
2012 $revisionId = $revision->insertOn( $dbw );
2013
2014 # Update page
2015 #
2016 # Note that we use $this->mLatest instead of fetching a value from the master DB
2017 # during the course of this function. This makes sure that EditPage can detect
2018 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2019 # before this function is called. A previous function used a separate query, this
2020 # creates a window where concurrent edits can cause an ignored edit conflict.
2021 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
2022
2023 if ( !$ok ) {
2024 /* Belated edit conflict! Run away!! */
2025 $status->fatal( 'edit-conflict' );
2026 # Delete the invalid revision if the DB is not transactional
2027 if ( !$wgDBtransactions ) {
2028 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
2029 }
2030 $revisionId = 0;
2031 $dbw->rollback();
2032 } else {
2033 global $wgUseRCPatrol;
2034 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2035 # Update recentchanges
2036 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2037 # Mark as patrolled if the user can do so
2038 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan( 'autopatrol' );
2039 # Add RC row to the DB
2040 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
2041 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2042 $revisionId, $patrolled
2043 );
2044 # Log auto-patrolled edits
2045 if ( $patrolled ) {
2046 PatrolLog::record( $rc, true );
2047 }
2048 }
2049 $user->incEditCount();
2050 $dbw->commit();
2051 }
2052 } else {
2053 $status->warning( 'edit-no-change' );
2054 $revision = null;
2055 // Keep the same revision ID, but do some updates on it
2056 $revisionId = $this->getRevIdFetched();
2057 // Update page_touched, this is usually implicit in the page update
2058 // Other cache updates are done in onArticleEdit()
2059 $this->mTitle->invalidateCache();
2060 }
2061
2062 if ( !$wgDBtransactions ) {
2063 ignore_user_abort( $userAbort );
2064 }
2065 // Now that ignore_user_abort is restored, we can respond to fatal errors
2066 if ( !$status->isOK() ) {
2067 wfProfileOut( __METHOD__ );
2068 return $status;
2069 }
2070
2071 # Invalidate cache of this article and all pages using this article
2072 # as a template. Partly deferred.
2073 Article::onArticleEdit( $this->mTitle );
2074 # Update links tables, site stats, etc.
2075 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2076 } else {
2077 # Create new article
2078 $status->value['new'] = true;
2079
2080 # Set statistics members
2081 # We work out if it's countable after PST to avoid counter drift
2082 # when articles are created with {{subst:}}
2083 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2084 $this->mTotalAdjustment = 1;
2085
2086 $dbw->begin();
2087
2088 # Add the page record; stake our claim on this title!
2089 # This will return false if the article already exists
2090 $newid = $this->insertOn( $dbw );
2091
2092 if ( $newid === false ) {
2093 $dbw->rollback();
2094 $status->fatal( 'edit-already-exists' );
2095 wfProfileOut( __METHOD__ );
2096 return $status;
2097 }
2098
2099 # Save the revision text...
2100 $revision = new Revision( array(
2101 'page' => $newid,
2102 'comment' => $summary,
2103 'minor_edit' => $isminor,
2104 'text' => $text,
2105 'user' => $user->getId(),
2106 'user_text' => $user->getName(),
2107 ) );
2108 $revisionId = $revision->insertOn( $dbw );
2109
2110 $this->mTitle->resetArticleID( $newid );
2111
2112 # Update the page record with revision data
2113 $this->updateRevisionOn( $dbw, $revision, 0 );
2114
2115 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2116 # Update recentchanges
2117 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2118 global $wgUseRCPatrol, $wgUseNPPatrol;
2119 # Mark as patrolled if the user can do so
2120 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && $this->mTitle->userCan( 'autopatrol' );
2121 # Add RC row to the DB
2122 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2123 '', strlen( $text ), $revisionId, $patrolled );
2124 # Log auto-patrolled edits
2125 if ( $patrolled ) {
2126 PatrolLog::record( $rc, true );
2127 }
2128 }
2129 $user->incEditCount();
2130 $dbw->commit();
2131
2132 # Update links, etc.
2133 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2134
2135 # Clear caches
2136 Article::onArticleCreate( $this->mTitle );
2137
2138 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2139 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
2140 }
2141
2142 # Do updates right now unless deferral was requested
2143 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2144 wfDoUpdates();
2145 }
2146
2147 // Return the new revision (or null) to the caller
2148 $status->value['revision'] = $revision;
2149
2150 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2151 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
2152
2153 wfProfileOut( __METHOD__ );
2154 return $status;
2155 }
2156
2157 /**
2158 * @deprecated wrapper for doRedirect
2159 */
2160 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2161 wfDeprecated( __METHOD__ );
2162 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2163 }
2164
2165 /**
2166 * Output a redirect back to the article.
2167 * This is typically used after an edit.
2168 *
2169 * @param $noRedir Boolean: add redirect=no
2170 * @param $sectionAnchor String: section to redirect to, including "#"
2171 * @param $extraQuery String: extra query params
2172 */
2173 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2174 global $wgOut;
2175 if ( $noRedir ) {
2176 $query = 'redirect=no';
2177 if ( $extraQuery )
2178 $query .= "&$query";
2179 } else {
2180 $query = $extraQuery;
2181 }
2182 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2183 }
2184
2185 /**
2186 * Mark this particular edit/page as patrolled
2187 */
2188 public function markpatrolled() {
2189 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2190 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2191
2192 # If we haven't been given an rc_id value, we can't do anything
2193 $rcid = (int) $wgRequest->getVal( 'rcid' );
2194 $rc = RecentChange::newFromId( $rcid );
2195 if ( is_null( $rc ) ) {
2196 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2197 return;
2198 }
2199
2200 # It would be nice to see where the user had actually come from, but for now just guess
2201 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2202 $return = SpecialPage::getTitleFor( $returnto );
2203
2204 $dbw = wfGetDB( DB_MASTER );
2205 $errors = $rc->doMarkPatrolled();
2206
2207 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2208 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2209 return;
2210 }
2211
2212 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2213 // The hook itself has handled any output
2214 return;
2215 }
2216
2217 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2218 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2219 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2220 $wgOut->returnToMain( false, $return );
2221 return;
2222 }
2223
2224 if ( !empty( $errors ) ) {
2225 $wgOut->showPermissionsErrorPage( $errors );
2226 return;
2227 }
2228
2229 # Inform the user
2230 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2231 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2232 $wgOut->returnToMain( false, $return );
2233 }
2234
2235 /**
2236 * User-interface handler for the "watch" action
2237 */
2238 public function watch() {
2239 global $wgUser, $wgOut;
2240 if ( $wgUser->isAnon() ) {
2241 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2242 return;
2243 }
2244 if ( wfReadOnly() ) {
2245 $wgOut->readOnlyPage();
2246 return;
2247 }
2248 if ( $this->doWatch() ) {
2249 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2250 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2251 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2252 }
2253 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2254 }
2255
2256 /**
2257 * Add this page to $wgUser's watchlist
2258 * @return bool true on successful watch operation
2259 */
2260 public function doWatch() {
2261 global $wgUser;
2262 if ( $wgUser->isAnon() ) {
2263 return false;
2264 }
2265 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2266 $wgUser->addWatch( $this->mTitle );
2267 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2268 }
2269 return false;
2270 }
2271
2272 /**
2273 * User interface handler for the "unwatch" action.
2274 */
2275 public function unwatch() {
2276 global $wgUser, $wgOut;
2277 if ( $wgUser->isAnon() ) {
2278 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2279 return;
2280 }
2281 if ( wfReadOnly() ) {
2282 $wgOut->readOnlyPage();
2283 return;
2284 }
2285 if ( $this->doUnwatch() ) {
2286 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2287 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2288 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2289 }
2290 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2291 }
2292
2293 /**
2294 * Stop watching a page
2295 * @return bool true on successful unwatch
2296 */
2297 public function doUnwatch() {
2298 global $wgUser;
2299 if ( $wgUser->isAnon() ) {
2300 return false;
2301 }
2302 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2303 $wgUser->removeWatch( $this->mTitle );
2304 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2305 }
2306 return false;
2307 }
2308
2309 /**
2310 * action=protect handler
2311 */
2312 public function protect() {
2313 $form = new ProtectionForm( $this );
2314 $form->execute();
2315 }
2316
2317 /**
2318 * action=unprotect handler (alias)
2319 */
2320 public function unprotect() {
2321 $this->protect();
2322 }
2323
2324 /**
2325 * Update the article's restriction field, and leave a log entry.
2326 *
2327 * @param $limit Array: set of restriction keys
2328 * @param $reason String
2329 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2330 * @param $expiry Array: per restriction type expiration
2331 * @return bool true on success
2332 */
2333 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2334 global $wgUser, $wgContLang;
2335
2336 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2337
2338 $id = $this->mTitle->getArticleID();
2339 if ( $id <= 0 ) {
2340 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2341 return false;
2342 }
2343
2344 if ( wfReadOnly() ) {
2345 wfDebug( "updateRestrictions failed: read-only\n" );
2346 return false;
2347 }
2348
2349 if ( !$this->mTitle->userCan( 'protect' ) ) {
2350 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2351 return false;
2352 }
2353
2354 if ( !$cascade ) {
2355 $cascade = false;
2356 }
2357
2358 // Take this opportunity to purge out expired restrictions
2359 Title::purgeExpiredRestrictions();
2360
2361 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2362 # we expect a single selection, but the schema allows otherwise.
2363 $current = array();
2364 $updated = Article::flattenRestrictions( $limit );
2365 $changed = false;
2366 foreach ( $restrictionTypes as $action ) {
2367 if ( isset( $expiry[$action] ) ) {
2368 # Get current restrictions on $action
2369 $aLimits = $this->mTitle->getRestrictions( $action );
2370 $current[$action] = implode( '', $aLimits );
2371 # Are any actual restrictions being dealt with here?
2372 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2373 # If something changed, we need to log it. Checking $aRChanged
2374 # assures that "unprotecting" a page that is not protected does
2375 # not log just because the expiry was "changed".
2376 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2377 $changed = true;
2378 }
2379 }
2380 }
2381
2382 $current = Article::flattenRestrictions( $current );
2383
2384 $changed = ( $changed || $current != $updated );
2385 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2386 $protect = ( $updated != '' );
2387
2388 # If nothing's changed, do nothing
2389 if ( $changed ) {
2390 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2391
2392 $dbw = wfGetDB( DB_MASTER );
2393
2394 # Prepare a null revision to be added to the history
2395 $modified = $current != '' && $protect;
2396 if ( $protect ) {
2397 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2398 } else {
2399 $comment_type = 'unprotectedarticle';
2400 }
2401 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2402
2403 # Only restrictions with the 'protect' right can cascade...
2404 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2405 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2406 # The schema allows multiple restrictions
2407 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) )
2408 $cascade = false;
2409 $cascade_description = '';
2410 if ( $cascade ) {
2411 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2412 }
2413
2414 if ( $reason )
2415 $comment .= ": $reason";
2416
2417 $editComment = $comment;
2418 $encodedExpiry = array();
2419 $protect_description = '';
2420 foreach ( $limit as $action => $restrictions ) {
2421 if ( !isset( $expiry[$action] ) )
2422 $expiry[$action] = 'infinite';
2423
2424 $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
2425 if ( $restrictions != '' ) {
2426 $protect_description .= "[$action=$restrictions] (";
2427 if ( $encodedExpiry[$action] != 'infinity' ) {
2428 $protect_description .= wfMsgForContent( 'protect-expiring',
2429 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2430 $wgContLang->date( $expiry[$action], false, false ) ,
2431 $wgContLang->time( $expiry[$action], false, false ) );
2432 } else {
2433 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2434 }
2435 $protect_description .= ') ';
2436 }
2437 }
2438 $protect_description = trim( $protect_description );
2439
2440 if ( $protect_description && $protect )
2441 $editComment .= " ($protect_description)";
2442 if ( $cascade )
2443 $editComment .= "$cascade_description";
2444 # Update restrictions table
2445 foreach ( $limit as $action => $restrictions ) {
2446 if ( $restrictions != '' ) {
2447 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2448 array( 'pr_page' => $id,
2449 'pr_type' => $action,
2450 'pr_level' => $restrictions,
2451 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2452 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2453 } else {
2454 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2455 'pr_type' => $action ), __METHOD__ );
2456 }
2457 }
2458
2459 # Insert a null revision
2460 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2461 $nullRevId = $nullRevision->insertOn( $dbw );
2462
2463 $latest = $this->getLatest();
2464 # Update page record
2465 $dbw->update( 'page',
2466 array( /* SET */
2467 'page_touched' => $dbw->timestamp(),
2468 'page_restrictions' => '',
2469 'page_latest' => $nullRevId
2470 ), array( /* WHERE */
2471 'page_id' => $id
2472 ), 'Article::protect'
2473 );
2474
2475 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2476 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2477
2478 # Update the protection log
2479 $log = new LogPage( 'protect' );
2480 if ( $protect ) {
2481 $params = array( $protect_description, $cascade ? 'cascade' : '' );
2482 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2483 } else {
2484 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2485 }
2486
2487 } # End hook
2488 } # End "changed" check
2489
2490 return true;
2491 }
2492
2493 /**
2494 * Take an array of page restrictions and flatten it to a string
2495 * suitable for insertion into the page_restrictions field.
2496 * @param $limit Array
2497 * @return String
2498 */
2499 protected static function flattenRestrictions( $limit ) {
2500 if ( !is_array( $limit ) ) {
2501 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2502 }
2503 $bits = array();
2504 ksort( $limit );
2505 foreach ( $limit as $action => $restrictions ) {
2506 if ( $restrictions != '' ) {
2507 $bits[] = "$action=$restrictions";
2508 }
2509 }
2510 return implode( ':', $bits );
2511 }
2512
2513 /**
2514 * Auto-generates a deletion reason
2515 *
2516 * @param &$hasHistory Boolean: whether the page has a history
2517 * @return mixed String containing deletion reason or empty string, or boolean false
2518 * if no revision occurred
2519 */
2520 public function generateReason( &$hasHistory ) {
2521 global $wgContLang;
2522 $dbw = wfGetDB( DB_MASTER );
2523 // Get the last revision
2524 $rev = Revision::newFromTitle( $this->mTitle );
2525 if ( is_null( $rev ) )
2526 return false;
2527
2528 // Get the article's contents
2529 $contents = $rev->getText();
2530 $blank = false;
2531 // If the page is blank, use the text from the previous revision,
2532 // which can only be blank if there's a move/import/protect dummy revision involved
2533 if ( $contents == '' ) {
2534 $prev = $rev->getPrevious();
2535 if ( $prev ) {
2536 $contents = $prev->getText();
2537 $blank = true;
2538 }
2539 }
2540
2541 // Find out if there was only one contributor
2542 // Only scan the last 20 revisions
2543 $res = $dbw->select( 'revision', 'rev_user_text',
2544 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2545 __METHOD__,
2546 array( 'LIMIT' => 20 )
2547 );
2548 if ( $res === false )
2549 // This page has no revisions, which is very weird
2550 return false;
2551
2552 $hasHistory = ( $res->numRows() > 1 );
2553 $row = $dbw->fetchObject( $res );
2554 if ( $row ) { // $row is false if the only contributor is hidden
2555 $onlyAuthor = $row->rev_user_text;
2556 // Try to find a second contributor
2557 foreach ( $res as $row ) {
2558 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2559 $onlyAuthor = false;
2560 break;
2561 }
2562 }
2563 } else {
2564 $onlyAuthor = false;
2565 }
2566 $dbw->freeResult( $res );
2567
2568 // Generate the summary with a '$1' placeholder
2569 if ( $blank ) {
2570 // The current revision is blank and the one before is also
2571 // blank. It's just not our lucky day
2572 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2573 } else {
2574 if ( $onlyAuthor )
2575 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2576 else
2577 $reason = wfMsgForContent( 'excontent', '$1' );
2578 }
2579
2580 if ( $reason == '-' ) {
2581 // Allow these UI messages to be blanked out cleanly
2582 return '';
2583 }
2584
2585 // Replace newlines with spaces to prevent uglyness
2586 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2587 // Calculate the maximum amount of chars to get
2588 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2589 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2590 $contents = $wgContLang->truncate( $contents, $maxLength );
2591 // Remove possible unfinished links
2592 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2593 // Now replace the '$1' placeholder
2594 $reason = str_replace( '$1', $contents, $reason );
2595 return $reason;
2596 }
2597
2598
2599 /*
2600 * UI entry point for page deletion
2601 */
2602 public function delete() {
2603 global $wgUser, $wgOut, $wgRequest;
2604
2605 $confirm = $wgRequest->wasPosted() &&
2606 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2607
2608 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2609 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2610
2611 $reason = $this->DeleteReasonList;
2612
2613 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2614 // Entry from drop down menu + additional comment
2615 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2616 } elseif ( $reason == 'other' ) {
2617 $reason = $this->DeleteReason;
2618 }
2619 # Flag to hide all contents of the archived revisions
2620 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2621
2622 # This code desperately needs to be totally rewritten
2623
2624 # Read-only check...
2625 if ( wfReadOnly() ) {
2626 $wgOut->readOnlyPage();
2627 return;
2628 }
2629
2630 # Check permissions
2631 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2632
2633 if ( count( $permission_errors ) > 0 ) {
2634 $wgOut->showPermissionsErrorPage( $permission_errors );
2635 return;
2636 }
2637
2638 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2639
2640 # Better double-check that it hasn't been deleted yet!
2641 $dbw = wfGetDB( DB_MASTER );
2642 $conds = $this->mTitle->pageCond();
2643 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2644 if ( $latest === false ) {
2645 $wgOut->showFatalError(
2646 Html::rawElement(
2647 'div',
2648 array( 'class' => 'error mw-error-cannotdelete' ),
2649 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2650 )
2651 );
2652 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2653 LogEventsList::showLogExtract(
2654 $wgOut,
2655 'delete',
2656 $this->mTitle->getPrefixedText()
2657 );
2658 return;
2659 }
2660
2661 # Hack for big sites
2662 $bigHistory = $this->isBigDeletion();
2663 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2664 global $wgLang, $wgDeleteRevisionsLimit;
2665 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2666 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2667 return;
2668 }
2669
2670 if ( $confirm ) {
2671 $this->doDelete( $reason, $suppress );
2672 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2673 $this->doWatch();
2674 } elseif ( $this->mTitle->userIsWatching() ) {
2675 $this->doUnwatch();
2676 }
2677 return;
2678 }
2679
2680 // Generate deletion reason
2681 $hasHistory = false;
2682 if ( !$reason ) $reason = $this->generateReason( $hasHistory );
2683
2684 // If the page has a history, insert a warning
2685 if ( $hasHistory && !$confirm ) {
2686 global $wgLang;
2687 $skin = $wgUser->getSkin();
2688 $revisions = $this->estimateRevisionCount();
2689 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2690 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2691 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2692 '</strong>'
2693 );
2694 if ( $bigHistory ) {
2695 global $wgDeleteRevisionsLimit;
2696 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2697 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2698 }
2699 }
2700
2701 return $this->confirmDelete( $reason );
2702 }
2703
2704 /**
2705 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2706 */
2707 public function isBigDeletion() {
2708 global $wgDeleteRevisionsLimit;
2709 if ( $wgDeleteRevisionsLimit ) {
2710 $revCount = $this->estimateRevisionCount();
2711 return $revCount > $wgDeleteRevisionsLimit;
2712 }
2713 return false;
2714 }
2715
2716 /**
2717 * @return int approximate revision count
2718 */
2719 public function estimateRevisionCount() {
2720 $dbr = wfGetDB( DB_SLAVE );
2721 // For an exact count...
2722 // return $dbr->selectField( 'revision', 'COUNT(*)',
2723 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2724 return $dbr->estimateRowCount( 'revision', '*',
2725 array( 'rev_page' => $this->getId() ), __METHOD__ );
2726 }
2727
2728 /**
2729 * Get the last N authors
2730 * @param $num Integer: number of revisions to get
2731 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2732 * @return array Array of authors, duplicates not removed
2733 */
2734 public function getLastNAuthors( $num, $revLatest = 0 ) {
2735 wfProfileIn( __METHOD__ );
2736 // First try the slave
2737 // If that doesn't have the latest revision, try the master
2738 $continue = 2;
2739 $db = wfGetDB( DB_SLAVE );
2740 do {
2741 $res = $db->select( array( 'page', 'revision' ),
2742 array( 'rev_id', 'rev_user_text' ),
2743 array(
2744 'page_namespace' => $this->mTitle->getNamespace(),
2745 'page_title' => $this->mTitle->getDBkey(),
2746 'rev_page = page_id'
2747 ), __METHOD__, $this->getSelectOptions( array(
2748 'ORDER BY' => 'rev_timestamp DESC',
2749 'LIMIT' => $num
2750 ) )
2751 );
2752 if ( !$res ) {
2753 wfProfileOut( __METHOD__ );
2754 return array();
2755 }
2756 $row = $db->fetchObject( $res );
2757 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2758 $db = wfGetDB( DB_MASTER );
2759 $continue--;
2760 } else {
2761 $continue = 0;
2762 }
2763 } while ( $continue );
2764
2765 $authors = array( $row->rev_user_text );
2766 while ( $row = $db->fetchObject( $res ) ) {
2767 $authors[] = $row->rev_user_text;
2768 }
2769 wfProfileOut( __METHOD__ );
2770 return $authors;
2771 }
2772
2773 /**
2774 * Output deletion confirmation dialog
2775 * @param $reason String: prefilled reason
2776 */
2777 public function confirmDelete( $reason ) {
2778 global $wgOut, $wgUser;
2779
2780 wfDebug( "Article::confirmDelete\n" );
2781
2782 $deleteBackLink = $wgUser->getSkin()->link(
2783 $this->mTitle,
2784 null,
2785 array(),
2786 array(),
2787 array( 'known', 'noclasses' )
2788 );
2789 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2790 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2791 $wgOut->addWikiMsg( 'confirmdeletetext' );
2792
2793 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2794
2795 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
2796 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2797 <td></td>
2798 <td class='mw-input'><strong>" .
2799 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2800 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2801 "</strong></td>
2802 </tr>";
2803 } else {
2804 $suppress = '';
2805 }
2806 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2807
2808 $form = Xml::openElement( 'form', array( 'method' => 'post',
2809 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2810 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2811 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2812 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2813 "<tr id=\"wpDeleteReasonListRow\">
2814 <td class='mw-label'>" .
2815 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2816 "</td>
2817 <td class='mw-input'>" .
2818 Xml::listDropDown( 'wpDeleteReasonList',
2819 wfMsgForContent( 'deletereason-dropdown' ),
2820 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2821 "</td>
2822 </tr>
2823 <tr id=\"wpDeleteReasonRow\">
2824 <td class='mw-label'>" .
2825 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2826 "</td>
2827 <td class='mw-input'>" .
2828 Html::input( 'wpReason', $reason, 'text', array(
2829 'size' => '60',
2830 'maxlength' => '255',
2831 'tabindex' => '2',
2832 'id' => 'wpReason',
2833 'autofocus'
2834 ) ) .
2835 "</td>
2836 </tr>";
2837 # Dissalow watching is user is not logged in
2838 if ( $wgUser->isLoggedIn() ) {
2839 $form .= "
2840 <tr>
2841 <td></td>
2842 <td class='mw-input'>" .
2843 Xml::checkLabel( wfMsg( 'watchthis' ),
2844 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2845 "</td>
2846 </tr>";
2847 }
2848 $form .= "
2849 $suppress
2850 <tr>
2851 <td></td>
2852 <td class='mw-submit'>" .
2853 Xml::submitButton( wfMsg( 'deletepage' ),
2854 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2855 "</td>
2856 </tr>" .
2857 Xml::closeElement( 'table' ) .
2858 Xml::closeElement( 'fieldset' ) .
2859 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2860 Xml::closeElement( 'form' );
2861
2862 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2863 $skin = $wgUser->getSkin();
2864 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2865 $link = $skin->link(
2866 $title,
2867 wfMsgHtml( 'delete-edit-reasonlist' ),
2868 array(),
2869 array( 'action' => 'edit' )
2870 );
2871 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2872 }
2873
2874 $wgOut->addHTML( $form );
2875 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2876 LogEventsList::showLogExtract(
2877 $wgOut,
2878 'delete',
2879 $this->mTitle->getPrefixedText()
2880 );
2881 }
2882
2883 /**
2884 * Perform a deletion and output success or failure messages
2885 */
2886 public function doDelete( $reason, $suppress = false ) {
2887 global $wgOut, $wgUser;
2888 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2889
2890 $error = '';
2891 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
2892 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2893 $deleted = $this->mTitle->getPrefixedText();
2894
2895 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2896 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2897
2898 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2899
2900 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2901 $wgOut->returnToMain( false );
2902 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
2903 }
2904 } else {
2905 if ( $error == '' ) {
2906 $wgOut->showFatalError(
2907 Html::rawElement(
2908 'div',
2909 array( 'class' => 'error mw-error-cannotdelete' ),
2910 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2911 )
2912 );
2913 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2914 LogEventsList::showLogExtract(
2915 $wgOut,
2916 'delete',
2917 $this->mTitle->getPrefixedText()
2918 );
2919 } else {
2920 $wgOut->showFatalError( $error );
2921 }
2922 }
2923 }
2924
2925 /**
2926 * Back-end article deletion
2927 * Deletes the article with database consistency, writes logs, purges caches
2928 *
2929 * @param $reason string delete reason for deletion log
2930 * @param suppress bitfield
2931 * Revision::DELETED_TEXT
2932 * Revision::DELETED_COMMENT
2933 * Revision::DELETED_USER
2934 * Revision::DELETED_RESTRICTED
2935 * @param $id int article ID
2936 * @param $commit boolean defaults to true, triggers transaction end
2937 * @return boolean true if successful
2938 */
2939 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
2940 global $wgUseSquid, $wgDeferredUpdateList;
2941 global $wgUseTrackbacks;
2942
2943 wfDebug( __METHOD__ . "\n" );
2944
2945 $dbw = wfGetDB( DB_MASTER );
2946 $ns = $this->mTitle->getNamespace();
2947 $t = $this->mTitle->getDBkey();
2948 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2949
2950 if ( $t == '' || $id == 0 ) {
2951 return false;
2952 }
2953
2954 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
2955 array_push( $wgDeferredUpdateList, $u );
2956
2957 // Bitfields to further suppress the content
2958 if ( $suppress ) {
2959 $bitfield = 0;
2960 // This should be 15...
2961 $bitfield |= Revision::DELETED_TEXT;
2962 $bitfield |= Revision::DELETED_COMMENT;
2963 $bitfield |= Revision::DELETED_USER;
2964 $bitfield |= Revision::DELETED_RESTRICTED;
2965 } else {
2966 $bitfield = 'rev_deleted';
2967 }
2968
2969 $dbw->begin();
2970 // For now, shunt the revision data into the archive table.
2971 // Text is *not* removed from the text table; bulk storage
2972 // is left intact to avoid breaking block-compression or
2973 // immutable storage schemes.
2974 //
2975 // For backwards compatibility, note that some older archive
2976 // table entries will have ar_text and ar_flags fields still.
2977 //
2978 // In the future, we may keep revisions and mark them with
2979 // the rev_deleted field, which is reserved for this purpose.
2980 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2981 array(
2982 'ar_namespace' => 'page_namespace',
2983 'ar_title' => 'page_title',
2984 'ar_comment' => 'rev_comment',
2985 'ar_user' => 'rev_user',
2986 'ar_user_text' => 'rev_user_text',
2987 'ar_timestamp' => 'rev_timestamp',
2988 'ar_minor_edit' => 'rev_minor_edit',
2989 'ar_rev_id' => 'rev_id',
2990 'ar_text_id' => 'rev_text_id',
2991 'ar_text' => '\'\'', // Be explicit to appease
2992 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2993 'ar_len' => 'rev_len',
2994 'ar_page_id' => 'page_id',
2995 'ar_deleted' => $bitfield
2996 ), array(
2997 'page_id' => $id,
2998 'page_id = rev_page'
2999 ), __METHOD__
3000 );
3001
3002 # Delete restrictions for it
3003 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
3004
3005 # Now that it's safely backed up, delete it
3006 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
3007 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3008 if ( !$ok ) {
3009 $dbw->rollback();
3010 return false;
3011 }
3012
3013 # Fix category table counts
3014 $cats = array();
3015 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
3016 foreach ( $res as $row ) {
3017 $cats [] = $row->cl_to;
3018 }
3019 $this->updateCategoryCounts( array(), $cats );
3020
3021 # If using cascading deletes, we can skip some explicit deletes
3022 if ( !$dbw->cascadingDeletes() ) {
3023 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
3024
3025 if ( $wgUseTrackbacks )
3026 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
3027
3028 # Delete outgoing links
3029 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3030 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3031 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3032 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3033 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3034 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3035 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3036 }
3037
3038 # If using cleanup triggers, we can skip some manual deletes
3039 if ( !$dbw->cleanupTriggers() ) {
3040 # Clean up recentchanges entries...
3041 $dbw->delete( 'recentchanges',
3042 array( 'rc_type != ' . RC_LOG,
3043 'rc_namespace' => $this->mTitle->getNamespace(),
3044 'rc_title' => $this->mTitle->getDBkey() ),
3045 __METHOD__ );
3046 $dbw->delete( 'recentchanges',
3047 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
3048 __METHOD__ );
3049 }
3050
3051 # Clear caches
3052 Article::onArticleDelete( $this->mTitle );
3053
3054 # Clear the cached article id so the interface doesn't act like we exist
3055 $this->mTitle->resetArticleID( 0 );
3056
3057 # Log the deletion, if the page was suppressed, log it at Oversight instead
3058 $logtype = $suppress ? 'suppress' : 'delete';
3059 $log = new LogPage( $logtype );
3060
3061 # Make sure logging got through
3062 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
3063
3064 if ( $commit ) {
3065 $dbw->commit();
3066 }
3067
3068 return true;
3069 }
3070
3071 /**
3072 * Roll back the most recent consecutive set of edits to a page
3073 * from the same user; fails if there are no eligible edits to
3074 * roll back to, e.g. user is the sole contributor. This function
3075 * performs permissions checks on $wgUser, then calls commitRollback()
3076 * to do the dirty work
3077 *
3078 * @param $fromP String: Name of the user whose edits to rollback.
3079 * @param $summary String: Custom summary. Set to default summary if empty.
3080 * @param $token String: Rollback token.
3081 * @param $bot Boolean: If true, mark all reverted edits as bot.
3082 *
3083 * @param $resultDetails Array: contains result-specific array of additional values
3084 * 'alreadyrolled' : 'current' (rev)
3085 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3086 *
3087 * @return array of errors, each error formatted as
3088 * array(messagekey, param1, param2, ...).
3089 * On success, the array is empty. This array can also be passed to
3090 * OutputPage::showPermissionsErrorPage().
3091 */
3092 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3093 global $wgUser;
3094 $resultDetails = null;
3095
3096 # Check permissions
3097 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3098 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3099 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3100
3101 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
3102 $errors[] = array( 'sessionfailure' );
3103
3104 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3105 $errors[] = array( 'actionthrottledtext' );
3106 }
3107 # If there were errors, bail out now
3108 if ( !empty( $errors ) )
3109 return $errors;
3110
3111 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3112 }
3113
3114 /**
3115 * Backend implementation of doRollback(), please refer there for parameter
3116 * and return value documentation
3117 *
3118 * NOTE: This function does NOT check ANY permissions, it just commits the
3119 * rollback to the DB Therefore, you should only call this function direct-
3120 * ly if you want to use custom permissions checks. If you don't, use
3121 * doRollback() instead.
3122 */
3123 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3124 global $wgUseRCPatrol, $wgUser, $wgLang;
3125 $dbw = wfGetDB( DB_MASTER );
3126
3127 if ( wfReadOnly() ) {
3128 return array( array( 'readonlytext' ) );
3129 }
3130
3131 # Get the last editor
3132 $current = Revision::newFromTitle( $this->mTitle );
3133 if ( is_null( $current ) ) {
3134 # Something wrong... no page?
3135 return array( array( 'notanarticle' ) );
3136 }
3137
3138 $from = str_replace( '_', ' ', $fromP );
3139 # User name given should match up with the top revision.
3140 # If the user was deleted then $from should be empty.
3141 if ( $from != $current->getUserText() ) {
3142 $resultDetails = array( 'current' => $current );
3143 return array( array( 'alreadyrolled',
3144 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3145 htmlspecialchars( $fromP ),
3146 htmlspecialchars( $current->getUserText() )
3147 ) );
3148 }
3149
3150 # Get the last edit not by this guy...
3151 # Note: these may not be public values
3152 $user = intval( $current->getRawUser() );
3153 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3154 $s = $dbw->selectRow( 'revision',
3155 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3156 array( 'rev_page' => $current->getPage(),
3157 "rev_user != {$user} OR rev_user_text != {$user_text}"
3158 ), __METHOD__,
3159 array( 'USE INDEX' => 'page_timestamp',
3160 'ORDER BY' => 'rev_timestamp DESC' )
3161 );
3162 if ( $s === false ) {
3163 # No one else ever edited this page
3164 return array( array( 'cantrollback' ) );
3165 } else if ( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
3166 # Only admins can see this text
3167 return array( array( 'notvisiblerev' ) );
3168 }
3169
3170 $set = array();
3171 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3172 # Mark all reverted edits as bot
3173 $set['rc_bot'] = 1;
3174 }
3175 if ( $wgUseRCPatrol ) {
3176 # Mark all reverted edits as patrolled
3177 $set['rc_patrolled'] = 1;
3178 }
3179
3180 if ( count( $set ) ) {
3181 $dbw->update( 'recentchanges', $set,
3182 array( /* WHERE */
3183 'rc_cur_id' => $current->getPage(),
3184 'rc_user_text' => $current->getUserText(),
3185 "rc_timestamp > '{$s->rev_timestamp}'",
3186 ), __METHOD__
3187 );
3188 }
3189
3190 # Generate the edit summary if necessary
3191 $target = Revision::newFromId( $s->rev_id );
3192 if ( empty( $summary ) ) {
3193 if ( $from == '' ) { // no public user name
3194 $summary = wfMsgForContent( 'revertpage-nouser' );
3195 } else {
3196 $summary = wfMsgForContent( 'revertpage' );
3197 }
3198 }
3199
3200 # Allow the custom summary to use the same args as the default message
3201 $args = array(
3202 $target->getUserText(), $from, $s->rev_id,
3203 $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3204 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3205 );
3206 $summary = wfMsgReplaceArgs( $summary, $args );
3207
3208 # Save
3209 $flags = EDIT_UPDATE;
3210
3211 if ( $wgUser->isAllowed( 'minoredit' ) )
3212 $flags |= EDIT_MINOR;
3213
3214 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) )
3215 $flags |= EDIT_FORCE_BOT;
3216 # Actually store the edit
3217 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3218 if ( !empty( $status->value['revision'] ) ) {
3219 $revId = $status->value['revision']->getId();
3220 } else {
3221 $revId = false;
3222 }
3223
3224 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3225
3226 $resultDetails = array(
3227 'summary' => $summary,
3228 'current' => $current,
3229 'target' => $target,
3230 'newid' => $revId
3231 );
3232 return array();
3233 }
3234
3235 /**
3236 * User interface for rollback operations
3237 */
3238 public function rollback() {
3239 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3240 $details = null;
3241
3242 $result = $this->doRollback(
3243 $wgRequest->getVal( 'from' ),
3244 $wgRequest->getText( 'summary' ),
3245 $wgRequest->getVal( 'token' ),
3246 $wgRequest->getBool( 'bot' ),
3247 $details
3248 );
3249
3250 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3251 $wgOut->rateLimited();
3252 return;
3253 }
3254 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3255 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3256 $errArray = $result[0];
3257 $errMsg = array_shift( $errArray );
3258 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3259 if ( isset( $details['current'] ) ) {
3260 $current = $details['current'];
3261 if ( $current->getComment() != '' ) {
3262 $wgOut->addWikiMsgArray( 'editcomment', array(
3263 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3264 }
3265 }
3266 return;
3267 }
3268 # Display permissions errors before read-only message -- there's no
3269 # point in misleading the user into thinking the inability to rollback
3270 # is only temporary.
3271 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3272 # array_diff is completely broken for arrays of arrays, sigh. Re-
3273 # move any 'readonlytext' error manually.
3274 $out = array();
3275 foreach ( $result as $error ) {
3276 if ( $error != array( 'readonlytext' ) ) {
3277 $out [] = $error;
3278 }
3279 }
3280 $wgOut->showPermissionsErrorPage( $out );
3281 return;
3282 }
3283 if ( $result == array( array( 'readonlytext' ) ) ) {
3284 $wgOut->readOnlyPage();
3285 return;
3286 }
3287
3288 $current = $details['current'];
3289 $target = $details['target'];
3290 $newId = $details['newid'];
3291 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3292 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3293 if ( $current->getUserText() === '' ) {
3294 $old = wfMsg( 'rev-deleted-user' );
3295 } else {
3296 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3297 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3298 }
3299 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3300 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3301 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3302 $wgOut->returnToMain( false, $this->mTitle );
3303
3304 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3305 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3306 $de->showDiff( '', '' );
3307 }
3308 }
3309
3310
3311 /**
3312 * Do standard deferred updates after page view
3313 */
3314 public function viewUpdates() {
3315 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3316 if ( wfReadOnly() ) {
3317 return;
3318 }
3319 # Don't update page view counters on views from bot users (bug 14044)
3320 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3321 Article::incViewCount( $this->getID() );
3322 $u = new SiteStatsUpdate( 1, 0, 0 );
3323 array_push( $wgDeferredUpdateList, $u );
3324 }
3325 # Update newtalk / watchlist notification status
3326 $wgUser->clearNotification( $this->mTitle );
3327 }
3328
3329 /**
3330 * Prepare text which is about to be saved.
3331 * Returns a stdclass with source, pst and output members
3332 */
3333 public function prepareTextForEdit( $text, $revid = null ) {
3334 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3335 // Already prepared
3336 return $this->mPreparedEdit;
3337 }
3338 global $wgParser;
3339 $edit = (object)array();
3340 $edit->revid = $revid;
3341 $edit->newText = $text;
3342 $edit->pst = $this->preSaveTransform( $text );
3343 $options = $this->getParserOptions();
3344 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3345 $edit->oldText = $this->getContent();
3346 $this->mPreparedEdit = $edit;
3347 return $edit;
3348 }
3349
3350 /**
3351 * Do standard deferred updates after page edit.
3352 * Update links tables, site stats, search index and message cache.
3353 * Purges pages that include this page if the text was changed here.
3354 * Every 100th edit, prune the recent changes table.
3355 *
3356 * @private
3357 * @param $text New text of the article
3358 * @param $summary Edit summary
3359 * @param $minoredit Minor edit
3360 * @param $timestamp_of_pagechange Timestamp associated with the page change
3361 * @param $newid rev_id value of the new revision
3362 * @param $changed Whether or not the content actually changed
3363 */
3364 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3365 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3366
3367 wfProfileIn( __METHOD__ );
3368
3369 # Parse the text
3370 # Be careful not to double-PST: $text is usually already PST-ed once
3371 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3372 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3373 $editInfo = $this->prepareTextForEdit( $text, $newid );
3374 } else {
3375 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3376 $editInfo = $this->mPreparedEdit;
3377 }
3378
3379 # Save it to the parser cache
3380 if ( $wgEnableParserCache ) {
3381 $popts = $this->getParserOptions();
3382 $parserCache = ParserCache::singleton();
3383 $parserCache->save( $editInfo->output, $this, $popts );
3384 }
3385
3386 # Update the links tables
3387 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3388 $u->doUpdate();
3389
3390 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3391
3392 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3393 if ( 0 == mt_rand( 0, 99 ) ) {
3394 // Flush old entries from the `recentchanges` table; we do this on
3395 // random requests so as to avoid an increase in writes for no good reason
3396 global $wgRCMaxAge;
3397 $dbw = wfGetDB( DB_MASTER );
3398 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3399 $recentchanges = $dbw->tableName( 'recentchanges' );
3400 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3401 $dbw->query( $sql );
3402 }
3403 }
3404
3405 $id = $this->getID();
3406 $title = $this->mTitle->getPrefixedDBkey();
3407 $shortTitle = $this->mTitle->getDBkey();
3408
3409 if ( 0 == $id ) {
3410 wfProfileOut( __METHOD__ );
3411 return;
3412 }
3413
3414 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3415 array_push( $wgDeferredUpdateList, $u );
3416 $u = new SearchUpdate( $id, $title, $text );
3417 array_push( $wgDeferredUpdateList, $u );
3418
3419 # If this is another user's talk page, update newtalk
3420 # Don't do this if $changed = false otherwise some idiot can null-edit a
3421 # load of user talk pages and piss people off, nor if it's a minor edit
3422 # by a properly-flagged bot.
3423 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3424 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3425 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3426 $other = User::newFromName( $shortTitle, false );
3427 if ( !$other ) {
3428 wfDebug( __METHOD__ . ": invalid username\n" );
3429 } elseif ( User::isIP( $shortTitle ) ) {
3430 // An anonymous user
3431 $other->setNewtalk( true );
3432 } elseif ( $other->isLoggedIn() ) {
3433 $other->setNewtalk( true );
3434 } else {
3435 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3436 }
3437 }
3438 }
3439
3440 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3441 $wgMessageCache->replace( $shortTitle, $text );
3442 }
3443
3444 wfProfileOut( __METHOD__ );
3445 }
3446
3447 /**
3448 * Perform article updates on a special page creation.
3449 *
3450 * @param $rev Revision object
3451 *
3452 * @todo This is a shitty interface function. Kill it and replace the
3453 * other shitty functions like editUpdates and such so it's not needed
3454 * anymore.
3455 */
3456 public function createUpdates( $rev ) {
3457 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3458 $this->mTotalAdjustment = 1;
3459 $this->editUpdates( $rev->getText(), $rev->getComment(),
3460 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3461 }
3462
3463 /**
3464 * Generate the navigation links when browsing through an article revisions
3465 * It shows the information as:
3466 * Revision as of \<date\>; view current revision
3467 * \<- Previous version | Next Version -\>
3468 *
3469 * @param $oldid String: revision ID of this article revision
3470 */
3471 public function setOldSubtitle( $oldid = 0 ) {
3472 global $wgLang, $wgOut, $wgUser, $wgRequest;
3473
3474 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3475 return;
3476 }
3477
3478 $unhide = $wgRequest->getInt( 'unhide' ) == 1 &&
3479 $wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $oldid );
3480 # Cascade unhide param in links for easy deletion browsing
3481 $extraParams = array();
3482 if ( $wgRequest->getVal( 'unhide' ) ) {
3483 $extraParams['unhide'] = 1;
3484 }
3485 $revision = Revision::newFromId( $oldid );
3486
3487 $current = ( $oldid == $this->mLatest );
3488 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3489 $tddate = $wgLang->date( $this->mTimestamp, true );
3490 $tdtime = $wgLang->time( $this->mTimestamp, true );
3491 $sk = $wgUser->getSkin();
3492 $lnk = $current
3493 ? wfMsgHtml( 'currentrevisionlink' )
3494 : $sk->link(
3495 $this->mTitle,
3496 wfMsgHtml( 'currentrevisionlink' ),
3497 array(),
3498 $extraParams,
3499 array( 'known', 'noclasses' )
3500 );
3501 $curdiff = $current
3502 ? wfMsgHtml( 'diff' )
3503 : $sk->link(
3504 $this->mTitle,
3505 wfMsgHtml( 'diff' ),
3506 array(),
3507 array(
3508 'diff' => 'cur',
3509 'oldid' => $oldid
3510 ) + $extraParams,
3511 array( 'known', 'noclasses' )
3512 );
3513 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3514 $prevlink = $prev
3515 ? $sk->link(
3516 $this->mTitle,
3517 wfMsgHtml( 'previousrevision' ),
3518 array(),
3519 array(
3520 'direction' => 'prev',
3521 'oldid' => $oldid
3522 ) + $extraParams,
3523 array( 'known', 'noclasses' )
3524 )
3525 : wfMsgHtml( 'previousrevision' );
3526 $prevdiff = $prev
3527 ? $sk->link(
3528 $this->mTitle,
3529 wfMsgHtml( 'diff' ),
3530 array(),
3531 array(
3532 'diff' => 'prev',
3533 'oldid' => $oldid
3534 ) + $extraParams,
3535 array( 'known', 'noclasses' )
3536 )
3537 : wfMsgHtml( 'diff' );
3538 $nextlink = $current
3539 ? wfMsgHtml( 'nextrevision' )
3540 : $sk->link(
3541 $this->mTitle,
3542 wfMsgHtml( 'nextrevision' ),
3543 array(),
3544 array(
3545 'direction' => 'next',
3546 'oldid' => $oldid
3547 ) + $extraParams,
3548 array( 'known', 'noclasses' )
3549 );
3550 $nextdiff = $current
3551 ? wfMsgHtml( 'diff' )
3552 : $sk->link(
3553 $this->mTitle,
3554 wfMsgHtml( 'diff' ),
3555 array(),
3556 array(
3557 'diff' => 'next',
3558 'oldid' => $oldid
3559 ) + $extraParams,
3560 array( 'known', 'noclasses' )
3561 );
3562
3563 $cdel = '';
3564 // User can delete revisions or view deleted revisions...
3565 $canHide = $wgUser->isAllowed( 'deleterevision' );
3566 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3567 if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3568 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3569 } else {
3570 $query = array(
3571 'type' => 'revision',
3572 'target' => $this->mTitle->getPrefixedDbkey(),
3573 'ids' => $oldid
3574 );
3575 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3576 }
3577 $cdel .= ' ';
3578 }
3579
3580 # Show user links if allowed to see them. If hidden, then show them only if requested...
3581 $userlinks = $sk->revUserTools( $revision, !$unhide );
3582
3583 $m = wfMsg( 'revision-info-current' );
3584 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3585 ? 'revision-info-current'
3586 : 'revision-info';
3587
3588 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3589 wfMsgExt(
3590 $infomsg,
3591 array( 'parseinline', 'replaceafter' ),
3592 $td,
3593 $userlinks,
3594 $revision->getID(),
3595 $tddate,
3596 $tdtime,
3597 $revision->getUser()
3598 ) .
3599 "</div>\n" .
3600 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3601 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3602 $wgOut->setSubtitle( $r );
3603 }
3604
3605 /**
3606 * This function is called right before saving the wikitext,
3607 * so we can do things like signatures and links-in-context.
3608 *
3609 * @param $text String article contents
3610 * @return string article contents with altered wikitext markup (signatures
3611 * converted, {{subst:}}, templates, etc.)
3612 */
3613 public function preSaveTransform( $text ) {
3614 global $wgParser, $wgUser;
3615 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3616 }
3617
3618 /* Caching functions */
3619
3620 /**
3621 * checkLastModified returns true if it has taken care of all
3622 * output to the client that is necessary for this request.
3623 * (that is, it has sent a cached version of the page)
3624 *
3625 * @return boolean true if cached version send, false otherwise
3626 */
3627 protected function tryFileCache() {
3628 static $called = false;
3629 if ( $called ) {
3630 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3631 return false;
3632 }
3633 $called = true;
3634 if ( $this->isFileCacheable() ) {
3635 $cache = new HTMLFileCache( $this->mTitle );
3636 if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3637 wfDebug( "Article::tryFileCache(): about to load file\n" );
3638 $cache->loadFromFileCache();
3639 return true;
3640 } else {
3641 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3642 ob_start( array( &$cache, 'saveToFileCache' ) );
3643 }
3644 } else {
3645 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3646 }
3647 return false;
3648 }
3649
3650 /**
3651 * Check if the page can be cached
3652 * @return bool
3653 */
3654 public function isFileCacheable() {
3655 $cacheable = false;
3656 if ( HTMLFileCache::useFileCache() ) {
3657 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3658 // Extension may have reason to disable file caching on some pages.
3659 if ( $cacheable ) {
3660 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3661 }
3662 }
3663 return $cacheable;
3664 }
3665
3666 /**
3667 * Loads page_touched and returns a value indicating if it should be used
3668 * @return boolean true if not a redirect
3669 */
3670 public function checkTouched() {
3671 if ( !$this->mDataLoaded ) {
3672 $this->loadPageData();
3673 }
3674 return !$this->mIsRedirect;
3675 }
3676
3677 /**
3678 * Get the page_touched field
3679 * @return string containing GMT timestamp
3680 */
3681 public function getTouched() {
3682 # Ensure that page data has been loaded
3683 if ( !$this->mDataLoaded ) {
3684 $this->loadPageData();
3685 }
3686 return $this->mTouched;
3687 }
3688
3689 /**
3690 * Get the page_latest field
3691 * @return integer rev_id of current revision
3692 */
3693 public function getLatest() {
3694 if ( !$this->mDataLoaded ) {
3695 $this->loadPageData();
3696 }
3697 return (int)$this->mLatest;
3698 }
3699
3700 /**
3701 * Edit an article without doing all that other stuff
3702 * The article must already exist; link tables etc
3703 * are not updated, caches are not flushed.
3704 *
3705 * @param $text String: text submitted
3706 * @param $comment String: comment submitted
3707 * @param $minor Boolean: whereas it's a minor modification
3708 */
3709 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3710 wfProfileIn( __METHOD__ );
3711
3712 $dbw = wfGetDB( DB_MASTER );
3713 $revision = new Revision( array(
3714 'page' => $this->getId(),
3715 'text' => $text,
3716 'comment' => $comment,
3717 'minor_edit' => $minor ? 1 : 0,
3718 ) );
3719 $revision->insertOn( $dbw );
3720 $this->updateRevisionOn( $dbw, $revision );
3721
3722 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3723
3724 wfProfileOut( __METHOD__ );
3725 }
3726
3727 /**
3728 * Used to increment the view counter
3729 *
3730 * @param $id Integer: article id
3731 */
3732 public static function incViewCount( $id ) {
3733 $id = intval( $id );
3734 global $wgHitcounterUpdateFreq;
3735
3736 $dbw = wfGetDB( DB_MASTER );
3737 $pageTable = $dbw->tableName( 'page' );
3738 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3739 $acchitsTable = $dbw->tableName( 'acchits' );
3740
3741 if ( $wgHitcounterUpdateFreq <= 1 ) {
3742 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3743 return;
3744 }
3745
3746 # Not important enough to warrant an error page in case of failure
3747 $oldignore = $dbw->ignoreErrors( true );
3748
3749 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3750
3751 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 + 1 );
3752 if ( ( rand() % $checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
3753 # Most of the time (or on SQL errors), skip row count check
3754 $dbw->ignoreErrors( $oldignore );
3755 return;
3756 }
3757
3758 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
3759 $row = $dbw->fetchObject( $res );
3760 $rown = intval( $row->n );
3761 if ( $rown >= $wgHitcounterUpdateFreq ) {
3762 wfProfileIn( 'Article::incViewCount-collect' );
3763 $old_user_abort = ignore_user_abort( true );
3764
3765 $dbType = $dbw->getType();
3766 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__, false );
3767 $tabletype = $dbType == 'mysql' ? "ENGINE=HEAP " : '';
3768 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
3769 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
3770 'GROUP BY hc_id', __METHOD__ );
3771 $dbw->delete( 'hitcounter', '*', __METHOD__ );
3772 $dbw->unlockTables( __METHOD__ );
3773 if ( $dbType == 'mysql' ) {
3774 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
3775 'WHERE page_id = hc_id', __METHOD__ );
3776 }
3777 else {
3778 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
3779 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__ );
3780 }
3781 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__ );
3782
3783 ignore_user_abort( $old_user_abort );
3784 wfProfileOut( 'Article::incViewCount-collect' );
3785 }
3786 $dbw->ignoreErrors( $oldignore );
3787 }
3788
3789 /**#@+
3790 * The onArticle*() functions are supposed to be a kind of hooks
3791 * which should be called whenever any of the specified actions
3792 * are done.
3793 *
3794 * This is a good place to put code to clear caches, for instance.
3795 *
3796 * This is called on page move and undelete, as well as edit
3797 *
3798 * @param $title a title object
3799 */
3800 public static function onArticleCreate( $title ) {
3801 # Update existence markers on article/talk tabs...
3802 if ( $title->isTalkPage() ) {
3803 $other = $title->getSubjectPage();
3804 } else {
3805 $other = $title->getTalkPage();
3806 }
3807 $other->invalidateCache();
3808 $other->purgeSquid();
3809
3810 $title->touchLinks();
3811 $title->purgeSquid();
3812 $title->deleteTitleProtection();
3813 }
3814
3815 /**
3816 * Clears caches when article is deleted
3817 */
3818 public static function onArticleDelete( $title ) {
3819 global $wgMessageCache;
3820 # Update existence markers on article/talk tabs...
3821 if ( $title->isTalkPage() ) {
3822 $other = $title->getSubjectPage();
3823 } else {
3824 $other = $title->getTalkPage();
3825 }
3826 $other->invalidateCache();
3827 $other->purgeSquid();
3828
3829 $title->touchLinks();
3830 $title->purgeSquid();
3831
3832 # File cache
3833 HTMLFileCache::clearFileCache( $title );
3834
3835 # Messages
3836 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3837 $wgMessageCache->replace( $title->getDBkey(), false );
3838 }
3839 # Images
3840 if ( $title->getNamespace() == NS_FILE ) {
3841 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3842 $update->doUpdate();
3843 }
3844 # User talk pages
3845 if ( $title->getNamespace() == NS_USER_TALK ) {
3846 $user = User::newFromName( $title->getText(), false );
3847 $user->setNewtalk( false );
3848 }
3849 # Image redirects
3850 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3851 }
3852
3853 /**
3854 * Purge caches on page update etc
3855 *
3856 * @param $title Title object
3857 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3858 */
3859 public static function onArticleEdit( $title ) {
3860 global $wgDeferredUpdateList;
3861
3862 // Invalidate caches of articles which include this page
3863 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3864
3865 // Invalidate the caches of all pages which redirect here
3866 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3867
3868 # Purge squid for this page only
3869 $title->purgeSquid();
3870
3871 # Clear file cache for this page only
3872 HTMLFileCache::clearFileCache( $title );
3873 }
3874
3875 /**#@-*/
3876
3877 /**
3878 * Overriden by ImagePage class, only present here to avoid a fatal error
3879 * Called for ?action=revert
3880 */
3881 public function revert() {
3882 global $wgOut;
3883 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3884 }
3885
3886 /**
3887 * Info about this page
3888 * Called for ?action=info when $wgAllowPageInfo is on.
3889 */
3890 public function info() {
3891 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3892
3893 if ( !$wgAllowPageInfo ) {
3894 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3895 return;
3896 }
3897
3898 $page = $this->mTitle->getSubjectPage();
3899
3900 $wgOut->setPagetitle( $page->getPrefixedText() );
3901 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3902 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3903
3904 if ( !$this->mTitle->exists() ) {
3905 $wgOut->addHTML( '<div class="noarticletext">' );
3906 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3907 // This doesn't quite make sense; the user is asking for
3908 // information about the _page_, not the message... -- RC
3909 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3910 } else {
3911 $msg = $wgUser->isLoggedIn()
3912 ? 'noarticletext'
3913 : 'noarticletextanon';
3914 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3915 }
3916 $wgOut->addHTML( '</div>' );
3917 } else {
3918 $dbr = wfGetDB( DB_SLAVE );
3919 $wl_clause = array(
3920 'wl_title' => $page->getDBkey(),
3921 'wl_namespace' => $page->getNamespace() );
3922 $numwatchers = $dbr->selectField(
3923 'watchlist',
3924 'COUNT(*)',
3925 $wl_clause,
3926 __METHOD__,
3927 $this->getSelectOptions() );
3928
3929 $pageInfo = $this->pageCountInfo( $page );
3930 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3931
3932 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3933 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
3934 if ( $talkInfo ) {
3935 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
3936 }
3937 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3938 if ( $talkInfo ) {
3939 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3940 }
3941 $wgOut->addHTML( '</ul>' );
3942 }
3943 }
3944
3945 /**
3946 * Return the total number of edits and number of unique editors
3947 * on a given page. If page does not exist, returns false.
3948 *
3949 * @param $title Title object
3950 * @return mixed array or boolean false
3951 */
3952 public function pageCountInfo( $title ) {
3953 $id = $title->getArticleId();
3954 if ( $id == 0 ) {
3955 return false;
3956 }
3957 $dbr = wfGetDB( DB_SLAVE );
3958 $rev_clause = array( 'rev_page' => $id );
3959 $edits = $dbr->selectField(
3960 'revision',
3961 'COUNT(rev_page)',
3962 $rev_clause,
3963 __METHOD__,
3964 $this->getSelectOptions()
3965 );
3966 $authors = $dbr->selectField(
3967 'revision',
3968 'COUNT(DISTINCT rev_user_text)',
3969 $rev_clause,
3970 __METHOD__,
3971 $this->getSelectOptions()
3972 );
3973 return array( 'edits' => $edits, 'authors' => $authors );
3974 }
3975
3976 /**
3977 * Return a list of templates used by this article.
3978 * Uses the templatelinks table
3979 *
3980 * @return Array of Title objects
3981 */
3982 public function getUsedTemplates() {
3983 $result = array();
3984 $id = $this->mTitle->getArticleID();
3985 if ( $id == 0 ) {
3986 return array();
3987 }
3988 $dbr = wfGetDB( DB_SLAVE );
3989 $res = $dbr->select( array( 'templatelinks' ),
3990 array( 'tl_namespace', 'tl_title' ),
3991 array( 'tl_from' => $id ),
3992 __METHOD__ );
3993 if ( $res !== false ) {
3994 foreach ( $res as $row ) {
3995 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3996 }
3997 }
3998 $dbr->freeResult( $res );
3999 return $result;
4000 }
4001
4002 /**
4003 * Returns a list of hidden categories this page is a member of.
4004 * Uses the page_props and categorylinks tables.
4005 *
4006 * @return Array of Title objects
4007 */
4008 public function getHiddenCategories() {
4009 $result = array();
4010 $id = $this->mTitle->getArticleID();
4011 if ( $id == 0 ) {
4012 return array();
4013 }
4014 $dbr = wfGetDB( DB_SLAVE );
4015 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4016 array( 'cl_to' ),
4017 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4018 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
4019 __METHOD__ );
4020 if ( $res !== false ) {
4021 foreach ( $res as $row ) {
4022 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
4023 }
4024 }
4025 $dbr->freeResult( $res );
4026 return $result;
4027 }
4028
4029 /**
4030 * Return an applicable autosummary if one exists for the given edit.
4031 * @param $oldtext String: the previous text of the page.
4032 * @param $newtext String: The submitted text of the page.
4033 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4034 * @return string An appropriate autosummary, or an empty string.
4035 */
4036 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4037 # Decide what kind of autosummary is needed.
4038
4039 # Redirect autosummaries
4040 $ot = Title::newFromRedirect( $oldtext );
4041 $rt = Title::newFromRedirect( $newtext );
4042 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
4043 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4044 }
4045
4046 # New page autosummaries
4047 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
4048 # If they're making a new article, give its text, truncated, in the summary.
4049 global $wgContLang;
4050 $truncatedtext = $wgContLang->truncate(
4051 str_replace( "\n", ' ', $newtext ),
4052 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4053 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4054 }
4055
4056 # Blanking autosummaries
4057 if ( $oldtext != '' && $newtext == '' ) {
4058 return wfMsgForContent( 'autosumm-blank' );
4059 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4060 # Removing more than 90% of the article
4061 global $wgContLang;
4062 $truncatedtext = $wgContLang->truncate(
4063 $newtext,
4064 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4065 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4066 }
4067
4068 # If we reach this point, there's no applicable autosummary for our case, so our
4069 # autosummary is empty.
4070 return '';
4071 }
4072
4073 /**
4074 * Add the primary page-view wikitext to the output buffer
4075 * Saves the text into the parser cache if possible.
4076 * Updates templatelinks if it is out of date.
4077 *
4078 * @param $text String
4079 * @param $cache Boolean
4080 * @param $parserOptions mixed ParserOptions object, or boolean false
4081 */
4082 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4083 global $wgOut;
4084
4085 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4086 $wgOut->addParserOutput( $this->mParserOutput );
4087 }
4088
4089 /**
4090 * This does all the heavy lifting for outputWikitext, except it returns the parser
4091 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4092 * say, embedding thread pages within a discussion system (LiquidThreads)
4093 *
4094 * @param $text string
4095 * @param $cache boolean
4096 * @param $parserOptions parsing options, defaults to false
4097 * @return string containing parsed output
4098 */
4099 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4100 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4101
4102 if ( !$parserOptions ) {
4103 $parserOptions = $this->getParserOptions();
4104 }
4105
4106 $time = - wfTime();
4107 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4108 $parserOptions, true, true, $this->getRevIdFetched() );
4109 $time += wfTime();
4110
4111 # Timing hack
4112 if ( $time > 3 ) {
4113 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4114 $this->mTitle->getPrefixedDBkey() ) );
4115 }
4116
4117 if ( $wgEnableParserCache && $cache && $this && $this->mParserOutput->getCacheTime() != -1 ) {
4118 $parserCache = ParserCache::singleton();
4119 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4120 }
4121 // Make sure file cache is not used on uncacheable content.
4122 // Output that has magic words in it can still use the parser cache
4123 // (if enabled), though it will generally expire sooner.
4124 if ( $this->mParserOutput->getCacheTime() == -1 || $this->mParserOutput->containsOldMagic() ) {
4125 $wgUseFileCache = false;
4126 }
4127 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4128 return $this->mParserOutput;
4129 }
4130
4131 /**
4132 * Get parser options suitable for rendering the primary article wikitext
4133 * @return mixed ParserOptions object or boolean false
4134 */
4135 public function getParserOptions() {
4136 global $wgUser;
4137 if ( !$this->mParserOptions ) {
4138 $this->mParserOptions = new ParserOptions( $wgUser );
4139 $this->mParserOptions->setTidy( true );
4140 $this->mParserOptions->enableLimitReport();
4141 }
4142 return $this->mParserOptions;
4143 }
4144
4145 /**
4146 * Updates cascading protections
4147 *
4148 * @param $parserOutput mixed ParserOptions object, or boolean false
4149 **/
4150
4151 protected function doCascadeProtectionUpdates( $parserOutput ) {
4152 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4153 return;
4154 }
4155
4156 // templatelinks table may have become out of sync,
4157 // especially if using variable-based transclusions.
4158 // For paranoia, check if things have changed and if
4159 // so apply updates to the database. This will ensure
4160 // that cascaded protections apply as soon as the changes
4161 // are visible.
4162
4163 # Get templates from templatelinks
4164 $id = $this->mTitle->getArticleID();
4165
4166 $tlTemplates = array();
4167
4168 $dbr = wfGetDB( DB_SLAVE );
4169 $res = $dbr->select( array( 'templatelinks' ),
4170 array( 'tl_namespace', 'tl_title' ),
4171 array( 'tl_from' => $id ),
4172 __METHOD__ );
4173
4174 global $wgContLang;
4175 foreach ( $res as $row ) {
4176 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4177 }
4178
4179 # Get templates from parser output.
4180 $poTemplates = array();
4181 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4182 foreach ( $templates as $dbk => $id ) {
4183 $poTemplates["$ns:$dbk"] = true;
4184 }
4185 }
4186
4187 # Get the diff
4188 # Note that we simulate array_diff_key in PHP <5.0.x
4189 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4190
4191 if ( count( $templates_diff ) > 0 ) {
4192 # Whee, link updates time.
4193 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4194 $u->doUpdate();
4195 }
4196 }
4197
4198 /**
4199 * Update all the appropriate counts in the category table, given that
4200 * we've added the categories $added and deleted the categories $deleted.
4201 *
4202 * @param $added array The names of categories that were added
4203 * @param $deleted array The names of categories that were deleted
4204 */
4205 public function updateCategoryCounts( $added, $deleted ) {
4206 $ns = $this->mTitle->getNamespace();
4207 $dbw = wfGetDB( DB_MASTER );
4208
4209 # First make sure the rows exist. If one of the "deleted" ones didn't
4210 # exist, we might legitimately not create it, but it's simpler to just
4211 # create it and then give it a negative value, since the value is bogus
4212 # anyway.
4213 #
4214 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4215 $insertCats = array_merge( $added, $deleted );
4216 if ( !$insertCats ) {
4217 # Okay, nothing to do
4218 return;
4219 }
4220 $insertRows = array();
4221 foreach ( $insertCats as $cat ) {
4222 $insertRows[] = array(
4223 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4224 'cat_title' => $cat
4225 );
4226 }
4227 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4228
4229 $addFields = array( 'cat_pages = cat_pages + 1' );
4230 $removeFields = array( 'cat_pages = cat_pages - 1' );
4231 if ( $ns == NS_CATEGORY ) {
4232 $addFields[] = 'cat_subcats = cat_subcats + 1';
4233 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4234 } elseif ( $ns == NS_FILE ) {
4235 $addFields[] = 'cat_files = cat_files + 1';
4236 $removeFields[] = 'cat_files = cat_files - 1';
4237 }
4238
4239 if ( $added ) {
4240 $dbw->update(
4241 'category',
4242 $addFields,
4243 array( 'cat_title' => $added ),
4244 __METHOD__
4245 );
4246 }
4247 if ( $deleted ) {
4248 $dbw->update(
4249 'category',
4250 $removeFields,
4251 array( 'cat_title' => $deleted ),
4252 __METHOD__
4253 );
4254 }
4255 }
4256
4257 /**
4258 * Lightweight method to get the parser output for a page, checking the parser cache
4259 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4260 * consider, so it's not appropriate to use there.
4261 *
4262 * @param $oldid mixed integer Revision ID or null
4263 */
4264 public function getParserOutput( $oldid = null ) {
4265 global $wgEnableParserCache, $wgUser, $wgOut;
4266
4267 // Should the parser cache be used?
4268 $useParserCache = $wgEnableParserCache &&
4269 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4270 $this->exists() &&
4271 $oldid === null;
4272
4273 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4274 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4275 wfIncrStats( 'pcache_miss_stub' );
4276 }
4277
4278 $parserOutput = false;
4279 if ( $useParserCache ) {
4280 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4281 }
4282
4283 if ( $parserOutput === false ) {
4284 // Cache miss; parse and output it.
4285 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4286
4287 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4288 } else {
4289 return $parserOutput;
4290 }
4291 }
4292 }