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