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