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