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