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