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