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