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