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