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