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