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