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