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