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