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