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