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