(bug 9575) Accept upload description from GET parameters
[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, $summary,
1461 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1462 }
1463
1464 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1465 wfDoUpdates();
1466 }
1467
1468 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1469 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1470
1471 wfProfileOut( __METHOD__ );
1472 return $good;
1473 }
1474
1475 /**
1476 * @deprecated wrapper for doRedirect
1477 */
1478 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1479 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1480 }
1481
1482 /**
1483 * Output a redirect back to the article.
1484 * This is typically used after an edit.
1485 *
1486 * @param boolean $noRedir Add redirect=no
1487 * @param string $sectionAnchor section to redirect to, including "#"
1488 */
1489 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1490 global $wgOut;
1491 if ( $noRedir ) {
1492 $query = 'redirect=no';
1493 } else {
1494 $query = '';
1495 }
1496 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1497 }
1498
1499 /**
1500 * Mark this particular edit as patrolled
1501 */
1502 function markpatrolled() {
1503 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1504 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1505
1506 # Check RC patrol config. option
1507 if( !$wgUseRCPatrol ) {
1508 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1509 return;
1510 }
1511
1512 # Check permissions
1513 if( !$wgUser->isAllowed( 'patrol' ) ) {
1514 $wgOut->permissionRequired( 'patrol' );
1515 return;
1516 }
1517
1518 # If we haven't been given an rc_id value, we can't do anything
1519 $rcid = $wgRequest->getVal( 'rcid' );
1520 if( !$rcid ) {
1521 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1522 return;
1523 }
1524
1525 # Handle the 'MarkPatrolled' hook
1526 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1527 return;
1528 }
1529
1530 $return = SpecialPage::getTitleFor( 'Recentchanges' );
1531 # If it's left up to us, check that the user is allowed to patrol this edit
1532 # If the user has the "autopatrol" right, then we'll assume there are no
1533 # other conditions stopping them doing so
1534 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1535 $rc = RecentChange::newFromId( $rcid );
1536 # Graceful error handling, as we've done before here...
1537 # (If the recent change doesn't exist, then it doesn't matter whether
1538 # the user is allowed to patrol it or not; nothing is going to happen
1539 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1540 # The user made this edit, and can't patrol it
1541 # Tell them so, and then back off
1542 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1543 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1544 $wgOut->returnToMain( false, $return );
1545 return;
1546 }
1547 }
1548
1549 # Mark the edit as patrolled
1550 RecentChange::markPatrolled( $rcid );
1551 PatrolLog::record( $rcid );
1552 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1553
1554 # Inform the user
1555 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1556 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1557 $wgOut->returnToMain( false, $return );
1558 }
1559
1560 /**
1561 * User-interface handler for the "watch" action
1562 */
1563
1564 function watch() {
1565
1566 global $wgUser, $wgOut;
1567
1568 if ( $wgUser->isAnon() ) {
1569 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1570 return;
1571 }
1572 if ( wfReadOnly() ) {
1573 $wgOut->readOnlyPage();
1574 return;
1575 }
1576
1577 if( $this->doWatch() ) {
1578 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1579 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1580
1581 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1582 $text = wfMsg( 'addedwatchtext', $link );
1583 $wgOut->addWikiText( $text );
1584 }
1585
1586 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1587 }
1588
1589 /**
1590 * Add this page to $wgUser's watchlist
1591 * @return bool true on successful watch operation
1592 */
1593 function doWatch() {
1594 global $wgUser;
1595 if( $wgUser->isAnon() ) {
1596 return false;
1597 }
1598
1599 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1600 $wgUser->addWatch( $this->mTitle );
1601
1602 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1603 }
1604
1605 return false;
1606 }
1607
1608 /**
1609 * User interface handler for the "unwatch" action.
1610 */
1611 function unwatch() {
1612
1613 global $wgUser, $wgOut;
1614
1615 if ( $wgUser->isAnon() ) {
1616 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1617 return;
1618 }
1619 if ( wfReadOnly() ) {
1620 $wgOut->readOnlyPage();
1621 return;
1622 }
1623
1624 if( $this->doUnwatch() ) {
1625 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1626 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1627
1628 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1629 $text = wfMsg( 'removedwatchtext', $link );
1630 $wgOut->addWikiText( $text );
1631 }
1632
1633 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1634 }
1635
1636 /**
1637 * Stop watching a page
1638 * @return bool true on successful unwatch
1639 */
1640 function doUnwatch() {
1641 global $wgUser;
1642 if( $wgUser->isAnon() ) {
1643 return false;
1644 }
1645
1646 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1647 $wgUser->removeWatch( $this->mTitle );
1648
1649 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1650 }
1651
1652 return false;
1653 }
1654
1655 /**
1656 * action=protect handler
1657 */
1658 function protect() {
1659 $form = new ProtectionForm( $this );
1660 $form->execute();
1661 }
1662
1663 /**
1664 * action=unprotect handler (alias)
1665 */
1666 function unprotect() {
1667 $this->protect();
1668 }
1669
1670 /**
1671 * Update the article's restriction field, and leave a log entry.
1672 *
1673 * @param array $limit set of restriction keys
1674 * @param string $reason
1675 * @return bool true on success
1676 */
1677 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1678 global $wgUser, $wgRestrictionTypes, $wgContLang;
1679
1680 $id = $this->mTitle->getArticleID();
1681 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1682 return false;
1683 }
1684
1685 if (!$cascade) {
1686 $cascade = false;
1687 }
1688
1689 // Take this opportunity to purge out expired restrictions
1690 Title::purgeExpiredRestrictions();
1691
1692 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1693 # we expect a single selection, but the schema allows otherwise.
1694 $current = array();
1695 foreach( $wgRestrictionTypes as $action )
1696 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1697
1698 $current = Article::flattenRestrictions( $current );
1699 $updated = Article::flattenRestrictions( $limit );
1700
1701 $changed = ( $current != $updated );
1702 $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
1703 $changed = $changed || ($this->mTitle->mRestrictionsExpiry != $expiry);
1704 $protect = ( $updated != '' );
1705
1706 # If nothing's changed, do nothing
1707 if( $changed ) {
1708 global $wgGroupPermissions;
1709 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1710
1711 $dbw = wfGetDB( DB_MASTER );
1712
1713 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1714
1715 $expiry_description = '';
1716 if ( $encodedExpiry != 'infinity' ) {
1717 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1718 }
1719
1720 # Prepare a null revision to be added to the history
1721 $modified = $current != '' && $protect;
1722 if ( $protect ) {
1723 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1724 } else {
1725 $comment_type = 'unprotectedarticle';
1726 }
1727 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1728
1729 foreach( $limit as $action => $restrictions ) {
1730 # Check if the group level required to edit also can protect pages
1731 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1732 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1733 }
1734
1735 $cascade_description = '';
1736 if ($cascade) {
1737 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1738 }
1739
1740 if( $reason )
1741 $comment .= ": $reason";
1742 if( $protect )
1743 $comment .= " [$updated]";
1744 if ( $expiry_description && $protect )
1745 $comment .= "$expiry_description";
1746 if ( $cascade )
1747 $comment .= "$cascade_description";
1748
1749 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1750 $nullRevId = $nullRevision->insertOn( $dbw );
1751
1752 # Update restrictions table
1753 foreach( $limit as $action => $restrictions ) {
1754 if ($restrictions != '' ) {
1755 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1756 array( 'pr_page' => $id, 'pr_type' => $action
1757 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1758 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1759 } else {
1760 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1761 'pr_type' => $action ), __METHOD__ );
1762 }
1763 }
1764
1765 # Update page record
1766 $dbw->update( 'page',
1767 array( /* SET */
1768 'page_touched' => $dbw->timestamp(),
1769 'page_restrictions' => '',
1770 'page_latest' => $nullRevId
1771 ), array( /* WHERE */
1772 'page_id' => $id
1773 ), 'Article::protect'
1774 );
1775 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1776
1777 # Update the protection log
1778 $log = new LogPage( 'protect' );
1779
1780 if( $protect ) {
1781 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1782 } else {
1783 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1784 }
1785
1786 } # End hook
1787 } # End "changed" check
1788
1789 return true;
1790 }
1791
1792 /**
1793 * Take an array of page restrictions and flatten it to a string
1794 * suitable for insertion into the page_restrictions field.
1795 * @param array $limit
1796 * @return string
1797 * @private
1798 */
1799 function flattenRestrictions( $limit ) {
1800 if( !is_array( $limit ) ) {
1801 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1802 }
1803 $bits = array();
1804 ksort( $limit );
1805 foreach( $limit as $action => $restrictions ) {
1806 if( $restrictions != '' ) {
1807 $bits[] = "$action=$restrictions";
1808 }
1809 }
1810 return implode( ':', $bits );
1811 }
1812
1813 /*
1814 * UI entry point for page deletion
1815 */
1816 function delete() {
1817 global $wgUser, $wgOut, $wgRequest;
1818 $confirm = $wgRequest->wasPosted() &&
1819 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1820 $reason = $wgRequest->getText( 'wpReason' );
1821
1822 # This code desperately needs to be totally rewritten
1823
1824 # Check permissions
1825 if( $wgUser->isAllowed( 'delete' ) ) {
1826 if( $wgUser->isBlocked( !$confirm ) ) {
1827 $wgOut->blockedPage();
1828 return;
1829 }
1830 } else {
1831 $wgOut->permissionRequired( 'delete' );
1832 return;
1833 }
1834
1835 if( wfReadOnly() ) {
1836 $wgOut->readOnlyPage();
1837 return;
1838 }
1839
1840 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1841
1842 # Better double-check that it hasn't been deleted yet!
1843 $dbw = wfGetDB( DB_MASTER );
1844 $conds = $this->mTitle->pageCond();
1845 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1846 if ( $latest === false ) {
1847 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1848 return;
1849 }
1850
1851 if( $confirm ) {
1852 $this->doDelete( $reason );
1853 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1854 $this->doWatch();
1855 } elseif( $this->mTitle->userIsWatching() ) {
1856 $this->doUnwatch();
1857 }
1858 return;
1859 }
1860
1861 # determine whether this page has earlier revisions
1862 # and insert a warning if it does
1863 $maxRevisions = 20;
1864 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1865
1866 if( count( $authors ) > 1 && !$confirm ) {
1867 $skin=$wgUser->getSkin();
1868 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1869 }
1870
1871 # If a single user is responsible for all revisions, find out who they are
1872 if ( count( $authors ) == $maxRevisions ) {
1873 // Query bailed out, too many revisions to find out if they're all the same
1874 $authorOfAll = false;
1875 } else {
1876 $authorOfAll = reset( $authors );
1877 foreach ( $authors as $author ) {
1878 if ( $authorOfAll != $author ) {
1879 $authorOfAll = false;
1880 break;
1881 }
1882 }
1883 }
1884 # Fetch article text
1885 $rev = Revision::newFromTitle( $this->mTitle );
1886
1887 if( !is_null( $rev ) ) {
1888 # if this is a mini-text, we can paste part of it into the deletion reason
1889 $text = $rev->getText();
1890
1891 #if this is empty, an earlier revision may contain "useful" text
1892 $blanked = false;
1893 if( $text == '' ) {
1894 $prev = $rev->getPrevious();
1895 if( $prev ) {
1896 $text = $prev->getText();
1897 $blanked = true;
1898 }
1899 }
1900
1901 $length = strlen( $text );
1902
1903 # this should not happen, since it is not possible to store an empty, new
1904 # page. Let's insert a standard text in case it does, though
1905 if( $length == 0 && $reason === '' ) {
1906 $reason = wfMsgForContent( 'exblank' );
1907 }
1908
1909 if( $reason === '' ) {
1910 # comment field=255, let's grep the first 150 to have some user
1911 # space left
1912 global $wgContLang;
1913 $text = $wgContLang->truncate( $text, 150, '...' );
1914
1915 # let's strip out newlines
1916 $text = preg_replace( "/[\n\r]/", '', $text );
1917
1918 if( !$blanked ) {
1919 if( $authorOfAll === false ) {
1920 $reason = wfMsgForContent( 'excontent', $text );
1921 } else {
1922 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1923 }
1924 } else {
1925 $reason = wfMsgForContent( 'exbeforeblank', $text );
1926 }
1927 }
1928 }
1929
1930 return $this->confirmDelete( '', $reason );
1931 }
1932
1933 /**
1934 * Get the last N authors
1935 * @param int $num Number of revisions to get
1936 * @param string $revLatest The latest rev_id, selected from the master (optional)
1937 * @return array Array of authors, duplicates not removed
1938 */
1939 function getLastNAuthors( $num, $revLatest = 0 ) {
1940 wfProfileIn( __METHOD__ );
1941
1942 // First try the slave
1943 // If that doesn't have the latest revision, try the master
1944 $continue = 2;
1945 $db = wfGetDB( DB_SLAVE );
1946 do {
1947 $res = $db->select( array( 'page', 'revision' ),
1948 array( 'rev_id', 'rev_user_text' ),
1949 array(
1950 'page_namespace' => $this->mTitle->getNamespace(),
1951 'page_title' => $this->mTitle->getDBkey(),
1952 'rev_page = page_id'
1953 ), __METHOD__, $this->getSelectOptions( array(
1954 'ORDER BY' => 'rev_timestamp DESC',
1955 'LIMIT' => $num
1956 ) )
1957 );
1958 if ( !$res ) {
1959 wfProfileOut( __METHOD__ );
1960 return array();
1961 }
1962 $row = $db->fetchObject( $res );
1963 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1964 $db = wfGetDB( DB_MASTER );
1965 $continue--;
1966 } else {
1967 $continue = 0;
1968 }
1969 } while ( $continue );
1970
1971 $authors = array( $row->rev_user_text );
1972 while ( $row = $db->fetchObject( $res ) ) {
1973 $authors[] = $row->rev_user_text;
1974 }
1975 wfProfileOut( __METHOD__ );
1976 return $authors;
1977 }
1978
1979 /**
1980 * Output deletion confirmation dialog
1981 */
1982 function confirmDelete( $par, $reason ) {
1983 global $wgOut, $wgUser;
1984
1985 wfDebug( "Article::confirmDelete\n" );
1986
1987 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1988 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1989 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1990 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1991
1992 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1993
1994 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1995 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1996 $token = htmlspecialchars( $wgUser->editToken() );
1997 $watch = Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '2' ) );
1998
1999 $wgOut->addHTML( "
2000 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2001 <table border='0'>
2002 <tr>
2003 <td align='right'>
2004 <label for='wpReason'>{$delcom}:</label>
2005 </td>
2006 <td align='left'>
2007 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2008 </td>
2009 </tr>
2010 <tr>
2011 <td>&nbsp;</td>
2012 <td>$watch</td>
2013 </tr>
2014 <tr>
2015 <td>&nbsp;</td>
2016 <td>
2017 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2018 </td>
2019 </tr>
2020 </table>
2021 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2022 </form>\n" );
2023
2024 $wgOut->returnToMain( false );
2025
2026 $this->showLogExtract( $wgOut );
2027 }
2028
2029
2030 /**
2031 * Show relevant lines from the deletion log
2032 */
2033 function showLogExtract( $out ) {
2034 $out->addHtml( '<h2>' . htmlspecialchars( LogPage::logName( 'delete' ) ) . '</h2>' );
2035 $logViewer = new LogViewer(
2036 new LogReader(
2037 new FauxRequest(
2038 array( 'page' => $this->mTitle->getPrefixedText(),
2039 'type' => 'delete' ) ) ) );
2040 $logViewer->showList( $out );
2041 }
2042
2043
2044 /**
2045 * Perform a deletion and output success or failure messages
2046 */
2047 function doDelete( $reason ) {
2048 global $wgOut, $wgUser;
2049 wfDebug( __METHOD__."\n" );
2050
2051 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2052 if ( $this->doDeleteArticle( $reason ) ) {
2053 $deleted = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2054
2055 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2056 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2057
2058 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2059 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2060
2061 $wgOut->addWikiText( $text );
2062 $wgOut->returnToMain( false );
2063 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2064 } else {
2065 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2066 }
2067 }
2068 }
2069
2070 /**
2071 * Back-end article deletion
2072 * Deletes the article with database consistency, writes logs, purges caches
2073 * Returns success
2074 */
2075 function doDeleteArticle( $reason ) {
2076 global $wgUseSquid, $wgDeferredUpdateList;
2077 global $wgUseTrackbacks;
2078
2079 wfDebug( __METHOD__."\n" );
2080
2081 $dbw = wfGetDB( DB_MASTER );
2082 $ns = $this->mTitle->getNamespace();
2083 $t = $this->mTitle->getDBkey();
2084 $id = $this->mTitle->getArticleID();
2085
2086 if ( $t == '' || $id == 0 ) {
2087 return false;
2088 }
2089
2090 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2091 array_push( $wgDeferredUpdateList, $u );
2092
2093 // For now, shunt the revision data into the archive table.
2094 // Text is *not* removed from the text table; bulk storage
2095 // is left intact to avoid breaking block-compression or
2096 // immutable storage schemes.
2097 //
2098 // For backwards compatibility, note that some older archive
2099 // table entries will have ar_text and ar_flags fields still.
2100 //
2101 // In the future, we may keep revisions and mark them with
2102 // the rev_deleted field, which is reserved for this purpose.
2103 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2104 array(
2105 'ar_namespace' => 'page_namespace',
2106 'ar_title' => 'page_title',
2107 'ar_comment' => 'rev_comment',
2108 'ar_user' => 'rev_user',
2109 'ar_user_text' => 'rev_user_text',
2110 'ar_timestamp' => 'rev_timestamp',
2111 'ar_minor_edit' => 'rev_minor_edit',
2112 'ar_rev_id' => 'rev_id',
2113 'ar_text_id' => 'rev_text_id',
2114 'ar_text' => '\'\'', // Be explicit to appease
2115 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2116 'ar_len' => 'rev_len',
2117 'ar_page' => $id
2118 ), array(
2119 'page_id' => $id,
2120 'page_id = rev_page'
2121 ), __METHOD__
2122 );
2123
2124 # Delete restrictions for it
2125 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2126
2127 # Now that it's safely backed up, delete it
2128 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2129
2130 # If using cascading deletes, we can skip some explicit deletes
2131 if ( !$dbw->cascadingDeletes() ) {
2132
2133 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2134
2135 if ($wgUseTrackbacks)
2136 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2137
2138 # Delete outgoing links
2139 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2140 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2141 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2142 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2143 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2144 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2145 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2146 }
2147
2148 # If using cleanup triggers, we can skip some manual deletes
2149 if ( !$dbw->cleanupTriggers() ) {
2150
2151 # Clean up recentchanges entries...
2152 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
2153 }
2154
2155 # Clear caches
2156 Article::onArticleDelete( $this->mTitle );
2157
2158 # Log the deletion
2159 $log = new LogPage( 'delete' );
2160 $log->addEntry( 'delete', $this->mTitle, $reason );
2161
2162 # Clear the cached article id so the interface doesn't act like we exist
2163 $this->mTitle->resetArticleID( 0 );
2164 $this->mTitle->mArticleID = 0;
2165 return true;
2166 }
2167
2168 /**
2169 * Roll back the most recent consecutive set of edits to a page
2170 * from the same user; fails if there are no eligible edits to
2171 * roll back to, e.g. user is the sole contributor
2172 *
2173 * @param string $fromP - Name of the user whose edits to rollback.
2174 * @param string $summary - Custom summary. Set to default summary if empty.
2175 * @param string $token - Rollback token.
2176 * @param bool $bot - If true, mark all reverted edits as bot.
2177 *
2178 * @param array $resultDetails contains result-specific dict of additional values
2179 * ALREADY_ROLLED : 'current' (rev)
2180 * SUCCESS : 'summary' (str), 'current' (rev), 'target' (rev)
2181 *
2182 * @return self::SUCCESS on succes, self::* on failure
2183 */
2184 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2185 global $wgUser, $wgUseRCPatrol;
2186 $resultDetails = null;
2187
2188 if( $wgUser->isAllowed( 'rollback' ) ) {
2189 if( $wgUser->isBlocked() ) {
2190 return self::BLOCKED;
2191 }
2192 } else {
2193 return self::PERM_DENIED;
2194 }
2195
2196 if ( wfReadOnly() ) {
2197 return self::READONLY;
2198 }
2199 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2200 return self::BAD_TOKEN;
2201
2202 $dbw = wfGetDB( DB_MASTER );
2203
2204 # Get the last editor
2205 $current = Revision::newFromTitle( $this->mTitle );
2206 if( is_null( $current ) ) {
2207 # Something wrong... no page?
2208 return self::BAD_TITLE;
2209 }
2210
2211 $from = str_replace( '_', ' ', $fromP );
2212 if( $from != $current->getUserText() ) {
2213 $resultDetails = array( 'current' => $current );
2214 return self::ALREADY_ROLLED;
2215 }
2216
2217 # Get the last edit not by this guy
2218 $user = intval( $current->getUser() );
2219 $user_text = $dbw->addQuotes( $current->getUserText() );
2220 $s = $dbw->selectRow( 'revision',
2221 array( 'rev_id', 'rev_timestamp' ),
2222 array(
2223 'rev_page' => $current->getPage(),
2224 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2225 ), __METHOD__,
2226 array(
2227 'USE INDEX' => 'page_timestamp',
2228 'ORDER BY' => 'rev_timestamp DESC' )
2229 );
2230 if( $s === false ) {
2231 # Something wrong
2232 return self::ONLY_AUTHOR;
2233 }
2234
2235 $set = array();
2236 if ( $bot ) {
2237 # Mark all reverted edits as bot
2238 $set['rc_bot'] = 1;
2239 }
2240 if ( $wgUseRCPatrol ) {
2241 # Mark all reverted edits as patrolled
2242 $set['rc_patrolled'] = 1;
2243 }
2244
2245 if ( $set ) {
2246 $dbw->update( 'recentchanges', $set,
2247 array( /* WHERE */
2248 'rc_cur_id' => $current->getPage(),
2249 'rc_user_text' => $current->getUserText(),
2250 "rc_timestamp > '{$s->rev_timestamp}'",
2251 ), __METHOD__
2252 );
2253 }
2254
2255 # Get the edit summary
2256 $target = Revision::newFromId( $s->rev_id );
2257 if( empty( $summary ) )
2258 $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2259
2260 # Save
2261 $flags = EDIT_UPDATE | EDIT_MINOR;
2262 if( $bot )
2263 $flags |= EDIT_FORCE_BOT;
2264 $this->doEdit( $target->getText(), $summary, $flags );
2265
2266 $resultDetails = array(
2267 'summary' => $summary,
2268 'current' => $current,
2269 'target' => $target,
2270 );
2271 return self::SUCCESS;
2272 }
2273
2274 /**
2275 * User interface for rollback operations
2276 */
2277 function rollback() {
2278 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2279
2280 $details = null;
2281 $result = $this->doRollback(
2282 $wgRequest->getVal( 'from' ),
2283 $wgRequest->getText( 'summary' ),
2284 $wgRequest->getVal( 'token' ),
2285 $wgRequest->getBool( 'bot' ),
2286 $details
2287 );
2288
2289 switch( $result ) {
2290 case self::BLOCKED:
2291 $wgOut->blockedPage();
2292 break;
2293 case self::PERM_DENIED:
2294 $wgOut->permissionRequired( 'rollback' );
2295 break;
2296 case self::READONLY:
2297 $wgOut->readOnlyPage( $this->getContent() );
2298 break;
2299 case self::BAD_TOKEN:
2300 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2301 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2302 break;
2303 case self::BAD_TITLE:
2304 $wgOut->addHtml( wfMsg( 'notanarticle' ) );
2305 break;
2306 case self::ALREADY_ROLLED:
2307 $current = $details['current'];
2308 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2309 $wgOut->addWikiText(
2310 wfMsg( 'alreadyrolled',
2311 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2312 htmlspecialchars( $wgRequest->getVal( 'from' ) ),
2313 htmlspecialchars( $current->getUserText() )
2314 )
2315 );
2316 if( $current->getComment() != '' ) {
2317 $wgOut->addHtml( wfMsg( 'editcomment',
2318 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2319 }
2320 break;
2321 case self::ONLY_AUTHOR:
2322 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2323 $wgOut->addHtml( wfMsg( 'cantrollback' ) );
2324 break;
2325 case self::SUCCESS:
2326 $current = $details['current'];
2327 $target = $details['target'];
2328 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2329 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2330 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2331 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2332 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2333 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2334 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2335 $wgOut->returnToMain( false, $this->mTitle );
2336 break;
2337 default:
2338 throw new MWException( __METHOD__ . ": Unknown return value `{$retval}`" );
2339 }
2340
2341 }
2342
2343
2344 /**
2345 * Do standard deferred updates after page view
2346 * @private
2347 */
2348 function viewUpdates() {
2349 global $wgDeferredUpdateList;
2350
2351 if ( 0 != $this->getID() ) {
2352 global $wgDisableCounters;
2353 if( !$wgDisableCounters ) {
2354 Article::incViewCount( $this->getID() );
2355 $u = new SiteStatsUpdate( 1, 0, 0 );
2356 array_push( $wgDeferredUpdateList, $u );
2357 }
2358 }
2359
2360 # Update newtalk / watchlist notification status
2361 global $wgUser;
2362 $wgUser->clearNotification( $this->mTitle );
2363 }
2364
2365 /**
2366 * Do standard deferred updates after page edit.
2367 * Update links tables, site stats, search index and message cache.
2368 * Every 1000th edit, prune the recent changes table.
2369 *
2370 * @private
2371 * @param $text New text of the article
2372 * @param $summary Edit summary
2373 * @param $minoredit Minor edit
2374 * @param $timestamp_of_pagechange Timestamp associated with the page change
2375 * @param $newid rev_id value of the new revision
2376 * @param $changed Whether or not the content actually changed
2377 */
2378 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2379 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2380
2381 wfProfileIn( __METHOD__ );
2382
2383 # Parse the text
2384 $options = new ParserOptions;
2385 $options->setTidy(true);
2386 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2387
2388 # Save it to the parser cache
2389 $parserCache =& ParserCache::singleton();
2390 $parserCache->save( $poutput, $this, $wgUser );
2391
2392 # Update the links tables
2393 $u = new LinksUpdate( $this->mTitle, $poutput );
2394 $u->doUpdate();
2395
2396 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2397 wfSeedRandom();
2398 if ( 0 == mt_rand( 0, 99 ) ) {
2399 # Periodically flush old entries from the recentchanges table.
2400 global $wgRCMaxAge;
2401
2402 $dbw = wfGetDB( DB_MASTER );
2403 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2404 $recentchanges = $dbw->tableName( 'recentchanges' );
2405 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2406 $dbw->query( $sql );
2407 }
2408 }
2409
2410 $id = $this->getID();
2411 $title = $this->mTitle->getPrefixedDBkey();
2412 $shortTitle = $this->mTitle->getDBkey();
2413
2414 if ( 0 == $id ) {
2415 wfProfileOut( __METHOD__ );
2416 return;
2417 }
2418
2419 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2420 array_push( $wgDeferredUpdateList, $u );
2421 $u = new SearchUpdate( $id, $title, $text );
2422 array_push( $wgDeferredUpdateList, $u );
2423
2424 # If this is another user's talk page, update newtalk
2425 # Don't do this if $changed = false otherwise some idiot can null-edit a
2426 # load of user talk pages and piss people off, nor if it's a minor edit
2427 # by a properly-flagged bot.
2428 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2429 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2430 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2431 $other = User::newFromName( $shortTitle );
2432 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2433 // An anonymous user
2434 $other = new User();
2435 $other->setName( $shortTitle );
2436 }
2437 if( $other ) {
2438 $other->setNewtalk( true );
2439 }
2440 }
2441 }
2442
2443 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2444 $wgMessageCache->replace( $shortTitle, $text );
2445 }
2446
2447 wfProfileOut( __METHOD__ );
2448 }
2449
2450 /**
2451 * Perform article updates on a special page creation.
2452 *
2453 * @param Revision $rev
2454 *
2455 * @todo This is a shitty interface function. Kill it and replace the
2456 * other shitty functions like editUpdates and such so it's not needed
2457 * anymore.
2458 */
2459 function createUpdates( $rev ) {
2460 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2461 $this->mTotalAdjustment = 1;
2462 $this->editUpdates( $rev->getText(), $rev->getComment(),
2463 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2464 }
2465
2466 /**
2467 * Generate the navigation links when browsing through an article revisions
2468 * It shows the information as:
2469 * Revision as of \<date\>; view current revision
2470 * \<- Previous version | Next Version -\>
2471 *
2472 * @private
2473 * @param string $oldid Revision ID of this article revision
2474 */
2475 function setOldSubtitle( $oldid=0 ) {
2476 global $wgLang, $wgOut, $wgUser;
2477
2478 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2479 return;
2480 }
2481
2482 $revision = Revision::newFromId( $oldid );
2483
2484 $current = ( $oldid == $this->mLatest );
2485 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2486 $sk = $wgUser->getSkin();
2487 $lnk = $current
2488 ? wfMsg( 'currentrevisionlink' )
2489 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2490 $curdiff = $current
2491 ? wfMsg( 'diff' )
2492 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2493 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2494 $prevlink = $prev
2495 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2496 : wfMsg( 'previousrevision' );
2497 $prevdiff = $prev
2498 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2499 : wfMsg( 'diff' );
2500 $nextlink = $current
2501 ? wfMsg( 'nextrevision' )
2502 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2503 $nextdiff = $current
2504 ? wfMsg( 'diff' )
2505 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2506
2507 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2508 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2509
2510 $m = wfMsg( 'revision-info-current' );
2511 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2512 ? 'revision-info-current'
2513 : 'revision-info';
2514
2515 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2516 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2517 $wgOut->setSubtitle( $r );
2518 }
2519
2520 /**
2521 * This function is called right before saving the wikitext,
2522 * so we can do things like signatures and links-in-context.
2523 *
2524 * @param string $text
2525 */
2526 function preSaveTransform( $text ) {
2527 global $wgParser, $wgUser;
2528 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2529 }
2530
2531 /* Caching functions */
2532
2533 /**
2534 * checkLastModified returns true if it has taken care of all
2535 * output to the client that is necessary for this request.
2536 * (that is, it has sent a cached version of the page)
2537 */
2538 function tryFileCache() {
2539 static $called = false;
2540 if( $called ) {
2541 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2542 return;
2543 }
2544 $called = true;
2545 if($this->isFileCacheable()) {
2546 $touched = $this->mTouched;
2547 $cache = new HTMLFileCache( $this->mTitle );
2548 if($cache->isFileCacheGood( $touched )) {
2549 wfDebug( "Article::tryFileCache(): about to load file\n" );
2550 $cache->loadFromFileCache();
2551 return true;
2552 } else {
2553 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2554 ob_start( array(&$cache, 'saveToFileCache' ) );
2555 }
2556 } else {
2557 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2558 }
2559 }
2560
2561 /**
2562 * Check if the page can be cached
2563 * @return bool
2564 */
2565 function isFileCacheable() {
2566 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2567 $action = $wgRequest->getVal( 'action' );
2568 $oldid = $wgRequest->getVal( 'oldid' );
2569 $diff = $wgRequest->getVal( 'diff' );
2570 $redirect = $wgRequest->getVal( 'redirect' );
2571 $printable = $wgRequest->getVal( 'printable' );
2572 $page = $wgRequest->getVal( 'page' );
2573
2574 //check for non-standard user language; this covers uselang,
2575 //and extensions for auto-detecting user language.
2576 $ulang = $wgLang->getCode();
2577 $clang = $wgContLang->getCode();
2578
2579 $cacheable = $wgUseFileCache
2580 && (!$wgShowIPinHeader)
2581 && ($this->getID() != 0)
2582 && ($wgUser->isAnon())
2583 && (!$wgUser->getNewtalk())
2584 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2585 && (empty( $action ) || $action == 'view')
2586 && (!isset($oldid))
2587 && (!isset($diff))
2588 && (!isset($redirect))
2589 && (!isset($printable))
2590 && !isset($page)
2591 && (!$this->mRedirectedFrom)
2592 && ($ulang === $clang);
2593
2594 if ( $cacheable ) {
2595 //extension may have reason to disable file caching on some pages.
2596 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2597 }
2598
2599 return $cacheable;
2600 }
2601
2602 /**
2603 * Loads page_touched and returns a value indicating if it should be used
2604 *
2605 */
2606 function checkTouched() {
2607 if( !$this->mDataLoaded ) {
2608 $this->loadPageData();
2609 }
2610 return !$this->mIsRedirect;
2611 }
2612
2613 /**
2614 * Get the page_touched field
2615 */
2616 function getTouched() {
2617 # Ensure that page data has been loaded
2618 if( !$this->mDataLoaded ) {
2619 $this->loadPageData();
2620 }
2621 return $this->mTouched;
2622 }
2623
2624 /**
2625 * Get the page_latest field
2626 */
2627 function getLatest() {
2628 if ( !$this->mDataLoaded ) {
2629 $this->loadPageData();
2630 }
2631 return $this->mLatest;
2632 }
2633
2634 /**
2635 * Edit an article without doing all that other stuff
2636 * The article must already exist; link tables etc
2637 * are not updated, caches are not flushed.
2638 *
2639 * @param string $text text submitted
2640 * @param string $comment comment submitted
2641 * @param bool $minor whereas it's a minor modification
2642 */
2643 function quickEdit( $text, $comment = '', $minor = 0 ) {
2644 wfProfileIn( __METHOD__ );
2645
2646 $dbw = wfGetDB( DB_MASTER );
2647 $dbw->begin();
2648 $revision = new Revision( array(
2649 'page' => $this->getId(),
2650 'text' => $text,
2651 'comment' => $comment,
2652 'minor_edit' => $minor ? 1 : 0,
2653 ) );
2654 $revision->insertOn( $dbw );
2655 $this->updateRevisionOn( $dbw, $revision );
2656 $dbw->commit();
2657
2658 wfProfileOut( __METHOD__ );
2659 }
2660
2661 /**
2662 * Used to increment the view counter
2663 *
2664 * @static
2665 * @param integer $id article id
2666 */
2667 function incViewCount( $id ) {
2668 $id = intval( $id );
2669 global $wgHitcounterUpdateFreq, $wgDBtype;
2670
2671 $dbw = wfGetDB( DB_MASTER );
2672 $pageTable = $dbw->tableName( 'page' );
2673 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2674 $acchitsTable = $dbw->tableName( 'acchits' );
2675
2676 if( $wgHitcounterUpdateFreq <= 1 ) {
2677 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2678 return;
2679 }
2680
2681 # Not important enough to warrant an error page in case of failure
2682 $oldignore = $dbw->ignoreErrors( true );
2683
2684 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2685
2686 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2687 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2688 # Most of the time (or on SQL errors), skip row count check
2689 $dbw->ignoreErrors( $oldignore );
2690 return;
2691 }
2692
2693 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2694 $row = $dbw->fetchObject( $res );
2695 $rown = intval( $row->n );
2696 if( $rown >= $wgHitcounterUpdateFreq ){
2697 wfProfileIn( 'Article::incViewCount-collect' );
2698 $old_user_abort = ignore_user_abort( true );
2699
2700 if ($wgDBtype == 'mysql')
2701 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2702 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2703 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2704 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2705 'GROUP BY hc_id');
2706 $dbw->query("DELETE FROM $hitcounterTable");
2707 if ($wgDBtype == 'mysql') {
2708 $dbw->query('UNLOCK TABLES');
2709 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2710 'WHERE page_id = hc_id');
2711 }
2712 else {
2713 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2714 "FROM $acchitsTable WHERE page_id = hc_id");
2715 }
2716 $dbw->query("DROP TABLE $acchitsTable");
2717
2718 ignore_user_abort( $old_user_abort );
2719 wfProfileOut( 'Article::incViewCount-collect' );
2720 }
2721 $dbw->ignoreErrors( $oldignore );
2722 }
2723
2724 /**#@+
2725 * The onArticle*() functions are supposed to be a kind of hooks
2726 * which should be called whenever any of the specified actions
2727 * are done.
2728 *
2729 * This is a good place to put code to clear caches, for instance.
2730 *
2731 * This is called on page move and undelete, as well as edit
2732 * @static
2733 * @param $title_obj a title object
2734 */
2735
2736 static function onArticleCreate($title) {
2737 # The talk page isn't in the regular link tables, so we need to update manually:
2738 if ( $title->isTalkPage() ) {
2739 $other = $title->getSubjectPage();
2740 } else {
2741 $other = $title->getTalkPage();
2742 }
2743 $other->invalidateCache();
2744 $other->purgeSquid();
2745
2746 $title->touchLinks();
2747 $title->purgeSquid();
2748 }
2749
2750 static function onArticleDelete( $title ) {
2751 global $wgUseFileCache, $wgMessageCache;
2752
2753 $title->touchLinks();
2754 $title->purgeSquid();
2755
2756 # File cache
2757 if ( $wgUseFileCache ) {
2758 $cm = new HTMLFileCache( $title );
2759 @unlink( $cm->fileCacheName() );
2760 }
2761
2762 if( $title->getNamespace() == NS_MEDIAWIKI) {
2763 $wgMessageCache->replace( $title->getDBkey(), false );
2764 }
2765 }
2766
2767 /**
2768 * Purge caches on page update etc
2769 */
2770 static function onArticleEdit( $title ) {
2771 global $wgDeferredUpdateList, $wgUseFileCache;
2772
2773 // Invalidate caches of articles which include this page
2774 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2775 $wgDeferredUpdateList[] = $update;
2776
2777 # Purge squid for this page only
2778 $title->purgeSquid();
2779
2780 # Clear file cache
2781 if ( $wgUseFileCache ) {
2782 $cm = new HTMLFileCache( $title );
2783 @unlink( $cm->fileCacheName() );
2784 }
2785 }
2786
2787 /**#@-*/
2788
2789 /**
2790 * Info about this page
2791 * Called for ?action=info when $wgAllowPageInfo is on.
2792 *
2793 * @public
2794 */
2795 function info() {
2796 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2797
2798 if ( !$wgAllowPageInfo ) {
2799 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2800 return;
2801 }
2802
2803 $page = $this->mTitle->getSubjectPage();
2804
2805 $wgOut->setPagetitle( $page->getPrefixedText() );
2806 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2807 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2808
2809 # first, see if the page exists at all.
2810 $exists = $page->getArticleId() != 0;
2811 if( !$exists ) {
2812 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2813 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2814 } else {
2815 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2816 }
2817 } else {
2818 $dbr = wfGetDB( DB_SLAVE );
2819 $wl_clause = array(
2820 'wl_title' => $page->getDBkey(),
2821 'wl_namespace' => $page->getNamespace() );
2822 $numwatchers = $dbr->selectField(
2823 'watchlist',
2824 'COUNT(*)',
2825 $wl_clause,
2826 __METHOD__,
2827 $this->getSelectOptions() );
2828
2829 $pageInfo = $this->pageCountInfo( $page );
2830 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2831
2832 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2833 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2834 if( $talkInfo ) {
2835 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2836 }
2837 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2838 if( $talkInfo ) {
2839 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2840 }
2841 $wgOut->addHTML( '</ul>' );
2842
2843 }
2844 }
2845
2846 /**
2847 * Return the total number of edits and number of unique editors
2848 * on a given page. If page does not exist, returns false.
2849 *
2850 * @param Title $title
2851 * @return array
2852 * @private
2853 */
2854 function pageCountInfo( $title ) {
2855 $id = $title->getArticleId();
2856 if( $id == 0 ) {
2857 return false;
2858 }
2859
2860 $dbr = wfGetDB( DB_SLAVE );
2861
2862 $rev_clause = array( 'rev_page' => $id );
2863
2864 $edits = $dbr->selectField(
2865 'revision',
2866 'COUNT(rev_page)',
2867 $rev_clause,
2868 __METHOD__,
2869 $this->getSelectOptions() );
2870
2871 $authors = $dbr->selectField(
2872 'revision',
2873 'COUNT(DISTINCT rev_user_text)',
2874 $rev_clause,
2875 __METHOD__,
2876 $this->getSelectOptions() );
2877
2878 return array( 'edits' => $edits, 'authors' => $authors );
2879 }
2880
2881 /**
2882 * Return a list of templates used by this article.
2883 * Uses the templatelinks table
2884 *
2885 * @return array Array of Title objects
2886 */
2887 function getUsedTemplates() {
2888 $result = array();
2889 $id = $this->mTitle->getArticleID();
2890 if( $id == 0 ) {
2891 return array();
2892 }
2893
2894 $dbr = wfGetDB( DB_SLAVE );
2895 $res = $dbr->select( array( 'templatelinks' ),
2896 array( 'tl_namespace', 'tl_title' ),
2897 array( 'tl_from' => $id ),
2898 'Article:getUsedTemplates' );
2899 if ( false !== $res ) {
2900 if ( $dbr->numRows( $res ) ) {
2901 while ( $row = $dbr->fetchObject( $res ) ) {
2902 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2903 }
2904 }
2905 }
2906 $dbr->freeResult( $res );
2907 return $result;
2908 }
2909
2910 /**
2911 * Return an auto-generated summary if the text provided is a redirect.
2912 *
2913 * @param string $text The wikitext to check
2914 * @return string '' or an appropriate summary
2915 */
2916 public static function getRedirectAutosummary( $text ) {
2917 $rt = Title::newFromRedirect( $text );
2918 if( is_object( $rt ) )
2919 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2920 else
2921 return '';
2922 }
2923
2924 /**
2925 * Return an auto-generated summary if the new text is much shorter than
2926 * the old text.
2927 *
2928 * @param string $oldtext The previous text of the page
2929 * @param string $text The submitted text of the page
2930 * @return string An appropriate autosummary, or an empty string.
2931 */
2932 public static function getBlankingAutosummary( $oldtext, $text ) {
2933 if ($oldtext!='' && $text=='') {
2934 return wfMsgForContent('autosumm-blank');
2935 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2936 #Removing more than 90% of the article
2937 global $wgContLang;
2938 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2939 return wfMsgForContent('autosumm-replace', $truncatedtext);
2940 } else {
2941 return '';
2942 }
2943 }
2944
2945 /**
2946 * Return an applicable autosummary if one exists for the given edit.
2947 * @param string $oldtext The previous text of the page.
2948 * @param string $newtext The submitted text of the page.
2949 * @param bitmask $flags A bitmask of flags submitted for the edit.
2950 * @return string An appropriate autosummary, or an empty string.
2951 */
2952 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2953
2954 # This code is UGLY UGLY UGLY.
2955 # Somebody PLEASE come up with a more elegant way to do it.
2956
2957 #Redirect autosummaries
2958 $summary = self::getRedirectAutosummary( $newtext );
2959
2960 if ($summary)
2961 return $summary;
2962
2963 #Blanking autosummaries
2964 if (!($flags & EDIT_NEW))
2965 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
2966
2967 if ($summary)
2968 return $summary;
2969
2970 #New page autosummaries
2971 if ($flags & EDIT_NEW && strlen($newtext)) {
2972 #If they're making a new article, give its text, truncated, in the summary.
2973 global $wgContLang;
2974 $truncatedtext = $wgContLang->truncate(
2975 str_replace("\n", ' ', $newtext),
2976 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2977 '...' );
2978 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2979 }
2980
2981 if ($summary)
2982 return $summary;
2983
2984 return $summary;
2985 }
2986
2987 /**
2988 * Add the primary page-view wikitext to the output buffer
2989 * Saves the text into the parser cache if possible.
2990 * Updates templatelinks if it is out of date.
2991 *
2992 * @param string $text
2993 * @param bool $cache
2994 */
2995 public function outputWikiText( $text, $cache = true ) {
2996 global $wgParser, $wgUser, $wgOut;
2997
2998 $popts = $wgOut->parserOptions();
2999 $popts->setTidy(true);
3000 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3001 $popts, true, true, $this->getRevIdFetched() );
3002 $popts->setTidy(false);
3003 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3004 $parserCache =& ParserCache::singleton();
3005 $parserCache->save( $parserOutput, $this, $wgUser );
3006 }
3007
3008 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3009 // templatelinks table may have become out of sync,
3010 // especially if using variable-based transclusions.
3011 // For paranoia, check if things have changed and if
3012 // so apply updates to the database. This will ensure
3013 // that cascaded protections apply as soon as the changes
3014 // are visible.
3015
3016 # Get templates from templatelinks
3017 $id = $this->mTitle->getArticleID();
3018
3019 $tlTemplates = array();
3020
3021 $dbr = wfGetDB( DB_SLAVE );
3022 $res = $dbr->select( array( 'templatelinks' ),
3023 array( 'tl_namespace', 'tl_title' ),
3024 array( 'tl_from' => $id ),
3025 'Article:getUsedTemplates' );
3026
3027 global $wgContLang;
3028
3029 if ( false !== $res ) {
3030 if ( $dbr->numRows( $res ) ) {
3031 while ( $row = $dbr->fetchObject( $res ) ) {
3032 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3033 }
3034 }
3035 }
3036
3037 # Get templates from parser output.
3038 $poTemplates_allns = $parserOutput->getTemplates();
3039
3040 $poTemplates = array ();
3041 foreach ( $poTemplates_allns as $ns_templates ) {
3042 $poTemplates = array_merge( $poTemplates, $ns_templates );
3043 }
3044
3045 # Get the diff
3046 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3047
3048 if ( count( $templates_diff ) > 0 ) {
3049 # Whee, link updates time.
3050 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3051
3052 $dbw = wfGetDb( DB_MASTER );
3053 $dbw->begin();
3054
3055 $u->doUpdate();
3056
3057 $dbw->commit();
3058 }
3059 }
3060
3061 $wgOut->addParserOutput( $parserOutput );
3062 }
3063
3064 }