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