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