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