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