*Add two vars to ArticleViewHeader hook, $outputDone, $pcache
[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, &$outputDone, &$pcache ) );
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 /**
856 * If it's a non-existant page, stick the deletion log after the "noarticle" message.
857 * This won't appear when editing a new page, but will when viewing a nonexistant one.
858 */
859 if ( 0 == $this->getID() ) {
860 $this->showLogExtract( $wgOut );
861 }
862
863 # Trackbacks
864 if ($wgUseTrackbacks)
865 $this->addTrackbacks();
866
867 $this->viewUpdates();
868 wfProfileOut( __METHOD__ );
869 }
870
871 function addTrackbacks() {
872 global $wgOut, $wgUser;
873
874 $dbr = wfGetDB(DB_SLAVE);
875 $tbs = $dbr->select(
876 /* FROM */ 'trackbacks',
877 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
878 /* WHERE */ array('tb_page' => $this->getID())
879 );
880
881 if (!$dbr->numrows($tbs))
882 return;
883
884 $tbtext = "";
885 while ($o = $dbr->fetchObject($tbs)) {
886 $rmvtxt = "";
887 if ($wgUser->isAllowed( 'trackback' )) {
888 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
889 . $o->tb_id . "&token=" . $wgUser->editToken());
890 $rmvtxt = wfMsg('trackbackremove', $delurl);
891 }
892 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
893 $o->tb_title,
894 $o->tb_url,
895 $o->tb_ex,
896 $o->tb_name,
897 $rmvtxt);
898 }
899 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
900 }
901
902 function deletetrackback() {
903 global $wgUser, $wgRequest, $wgOut, $wgTitle;
904
905 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
906 $wgOut->addWikitext(wfMsg('sessionfailure'));
907 return;
908 }
909
910 if ((!$wgUser->isAllowed('delete'))) {
911 $wgOut->permissionRequired( 'delete' );
912 return;
913 }
914
915 if (wfReadOnly()) {
916 $wgOut->readOnlyPage();
917 return;
918 }
919
920 $db = wfGetDB(DB_MASTER);
921 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
922 $wgTitle->invalidateCache();
923 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
924 }
925
926 function render() {
927 global $wgOut;
928
929 $wgOut->setArticleBodyOnly(true);
930 $this->view();
931 }
932
933 /**
934 * Handle action=purge
935 */
936 function purge() {
937 global $wgUser, $wgRequest, $wgOut;
938
939 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
940 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
941 $this->doPurge();
942 }
943 } else {
944 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
945 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
946 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
947 $msg = str_replace( '$1',
948 "<form method=\"post\" action=\"$action\">\n" .
949 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
950 "</form>\n", $msg );
951
952 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
953 $wgOut->setRobotpolicy( 'noindex,nofollow' );
954 $wgOut->addHTML( $msg );
955 }
956 }
957
958 /**
959 * Perform the actions of a page purging
960 */
961 function doPurge() {
962 global $wgUseSquid;
963 // Invalidate the cache
964 $this->mTitle->invalidateCache();
965
966 if ( $wgUseSquid ) {
967 // Commit the transaction before the purge is sent
968 $dbw = wfGetDB( DB_MASTER );
969 $dbw->immediateCommit();
970
971 // Send purge
972 $update = SquidUpdate::newSimplePurge( $this->mTitle );
973 $update->doUpdate();
974 }
975 $this->view();
976 }
977
978 /**
979 * Insert a new empty page record for this article.
980 * This *must* be followed up by creating a revision
981 * and running $this->updateToLatest( $rev_id );
982 * or else the record will be left in a funky state.
983 * Best if all done inside a transaction.
984 *
985 * @param Database $dbw
986 * @return int The newly created page_id key
987 * @private
988 */
989 function insertOn( $dbw ) {
990 wfProfileIn( __METHOD__ );
991
992 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
993 $dbw->insert( 'page', array(
994 'page_id' => $page_id,
995 'page_namespace' => $this->mTitle->getNamespace(),
996 'page_title' => $this->mTitle->getDBkey(),
997 'page_counter' => 0,
998 'page_restrictions' => '',
999 'page_is_redirect' => 0, # Will set this shortly...
1000 'page_is_new' => 1,
1001 'page_random' => wfRandom(),
1002 'page_touched' => $dbw->timestamp(),
1003 'page_latest' => 0, # Fill this in shortly...
1004 'page_len' => 0, # Fill this in shortly...
1005 ), __METHOD__ );
1006 $newid = $dbw->insertId();
1007
1008 $this->mTitle->resetArticleId( $newid );
1009
1010 wfProfileOut( __METHOD__ );
1011 return $newid;
1012 }
1013
1014 /**
1015 * Update the page record to point to a newly saved revision.
1016 *
1017 * @param Database $dbw
1018 * @param Revision $revision For ID number, and text used to set
1019 length and redirect status fields
1020 * @param int $lastRevision If given, will not overwrite the page field
1021 * when different from the currently set value.
1022 * Giving 0 indicates the new page flag should
1023 * be set on.
1024 * @param bool $lastRevIsRedirect If given, will optimize adding and
1025 * removing rows in redirect table.
1026 * @return bool true on success, false on failure
1027 * @private
1028 */
1029 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1030 wfProfileIn( __METHOD__ );
1031
1032 $text = $revision->getText();
1033 $rt = Title::newFromRedirect( $text );
1034
1035 $conditions = array( 'page_id' => $this->getId() );
1036 if( !is_null( $lastRevision ) ) {
1037 # An extra check against threads stepping on each other
1038 $conditions['page_latest'] = $lastRevision;
1039 }
1040
1041 $dbw->update( 'page',
1042 array( /* SET */
1043 'page_latest' => $revision->getId(),
1044 'page_touched' => $dbw->timestamp(),
1045 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1046 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1047 'page_len' => strlen( $text ),
1048 ),
1049 $conditions,
1050 __METHOD__ );
1051
1052 $result = $dbw->affectedRows() != 0;
1053
1054 if ($result) {
1055 // FIXME: Should the result from updateRedirectOn() be returned instead?
1056 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1057 }
1058
1059 wfProfileOut( __METHOD__ );
1060 return $result;
1061 }
1062
1063 /**
1064 * Add row to the redirect table if this is a redirect, remove otherwise.
1065 *
1066 * @param Database $dbw
1067 * @param $redirectTitle a title object pointing to the redirect target,
1068 * or NULL if this is not a redirect
1069 * @param bool $lastRevIsRedirect If given, will optimize adding and
1070 * removing rows in redirect table.
1071 * @return bool true on success, false on failure
1072 * @private
1073 */
1074 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1075
1076 // Always update redirects (target link might have changed)
1077 // Update/Insert if we don't know if the last revision was a redirect or not
1078 // Delete if changing from redirect to non-redirect
1079 $isRedirect = !is_null($redirectTitle);
1080 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1081
1082 wfProfileIn( __METHOD__ );
1083
1084 if ($isRedirect) {
1085
1086 // This title is a redirect, Add/Update row in the redirect table
1087 $set = array( /* SET */
1088 'rd_namespace' => $redirectTitle->getNamespace(),
1089 'rd_title' => $redirectTitle->getDBkey(),
1090 'rd_from' => $this->getId(),
1091 );
1092
1093 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1094 } else {
1095 // This is not a redirect, remove row from redirect table
1096 $where = array( 'rd_from' => $this->getId() );
1097 $dbw->delete( 'redirect', $where, __METHOD__);
1098 }
1099
1100 wfProfileOut( __METHOD__ );
1101 return ( $dbw->affectedRows() != 0 );
1102 }
1103
1104 return true;
1105 }
1106
1107 /**
1108 * If the given revision is newer than the currently set page_latest,
1109 * update the page record. Otherwise, do nothing.
1110 *
1111 * @param Database $dbw
1112 * @param Revision $revision
1113 */
1114 function updateIfNewerOn( &$dbw, $revision ) {
1115 wfProfileIn( __METHOD__ );
1116
1117 $row = $dbw->selectRow(
1118 array( 'revision', 'page' ),
1119 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1120 array(
1121 'page_id' => $this->getId(),
1122 'page_latest=rev_id' ),
1123 __METHOD__ );
1124 if( $row ) {
1125 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1126 wfProfileOut( __METHOD__ );
1127 return false;
1128 }
1129 $prev = $row->rev_id;
1130 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1131 } else {
1132 # No or missing previous revision; mark the page as new
1133 $prev = 0;
1134 $lastRevIsRedirect = null;
1135 }
1136
1137 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1138 wfProfileOut( __METHOD__ );
1139 return $ret;
1140 }
1141
1142 /**
1143 * @return string Complete article text, or null if error
1144 */
1145 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1146 wfProfileIn( __METHOD__ );
1147
1148 if( $section == '' ) {
1149 // Whole-page edit; let the text through unmolested.
1150 } else {
1151 if( is_null( $edittime ) ) {
1152 $rev = Revision::newFromTitle( $this->mTitle );
1153 } else {
1154 $dbw = wfGetDB( DB_MASTER );
1155 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1156 }
1157 if( is_null( $rev ) ) {
1158 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1159 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1160 return null;
1161 }
1162 $oldtext = $rev->getText();
1163
1164 if( $section == 'new' ) {
1165 # Inserting a new section
1166 $subject = $summary ? "== {$summary} ==\n\n" : '';
1167 $text = strlen( trim( $oldtext ) ) > 0
1168 ? "{$oldtext}\n\n{$subject}{$text}"
1169 : "{$subject}{$text}";
1170 } else {
1171 # Replacing an existing section; roll out the big guns
1172 global $wgParser;
1173 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1174 }
1175
1176 }
1177
1178 wfProfileOut( __METHOD__ );
1179 return $text;
1180 }
1181
1182 /**
1183 * @deprecated use Article::doEdit()
1184 */
1185 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1186 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1187 ( $isminor ? EDIT_MINOR : 0 ) |
1188 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 );
1189
1190 # If this is a comment, add the summary as headline
1191 if ( $comment && $summary != "" ) {
1192 $text = "== {$summary} ==\n\n".$text;
1193 }
1194
1195 $this->doEdit( $text, $summary, $flags );
1196
1197 $dbw = wfGetDB( DB_MASTER );
1198 if ($watchthis) {
1199 if (!$this->mTitle->userIsWatching()) {
1200 $dbw->begin();
1201 $this->doWatch();
1202 $dbw->commit();
1203 }
1204 } else {
1205 if ( $this->mTitle->userIsWatching() ) {
1206 $dbw->begin();
1207 $this->doUnwatch();
1208 $dbw->commit();
1209 }
1210 }
1211 $this->doRedirect( $this->isRedirect( $text ) );
1212 }
1213
1214 /**
1215 * @deprecated use Article::doEdit()
1216 */
1217 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1218 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1219 ( $minor ? EDIT_MINOR : 0 ) |
1220 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1221
1222 $good = $this->doEdit( $text, $summary, $flags );
1223 if ( $good ) {
1224 $dbw = wfGetDB( DB_MASTER );
1225 if ($watchthis) {
1226 if (!$this->mTitle->userIsWatching()) {
1227 $dbw->begin();
1228 $this->doWatch();
1229 $dbw->commit();
1230 }
1231 } else {
1232 if ( $this->mTitle->userIsWatching() ) {
1233 $dbw->begin();
1234 $this->doUnwatch();
1235 $dbw->commit();
1236 }
1237 }
1238
1239 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1240 }
1241 return $good;
1242 }
1243
1244 /**
1245 * Article::doEdit()
1246 *
1247 * Change an existing article or create a new article. Updates RC and all necessary caches,
1248 * optionally via the deferred update array.
1249 *
1250 * $wgUser must be set before calling this function.
1251 *
1252 * @param string $text New text
1253 * @param string $summary Edit summary
1254 * @param integer $flags bitfield:
1255 * EDIT_NEW
1256 * Article is known or assumed to be non-existent, create a new one
1257 * EDIT_UPDATE
1258 * Article is known or assumed to be pre-existing, update it
1259 * EDIT_MINOR
1260 * Mark this edit minor, if the user is allowed to do so
1261 * EDIT_SUPPRESS_RC
1262 * Do not log the change in recentchanges
1263 * EDIT_FORCE_BOT
1264 * Mark the edit a "bot" edit regardless of user rights
1265 * EDIT_DEFER_UPDATES
1266 * Defer some of the updates until the end of index.php
1267 * EDIT_AUTOSUMMARY
1268 * Fill in blank summaries with generated text where possible
1269 *
1270 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1271 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1272 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1273 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1274 * to MediaWiki's performance-optimised locking strategy.
1275 *
1276 * @return bool success
1277 */
1278 function doEdit( $text, $summary, $flags = 0 ) {
1279 global $wgUser, $wgDBtransactions;
1280
1281 wfProfileIn( __METHOD__ );
1282 $good = true;
1283
1284 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1285 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1286 if ( $aid ) {
1287 $flags |= EDIT_UPDATE;
1288 } else {
1289 $flags |= EDIT_NEW;
1290 }
1291 }
1292
1293 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1294 &$summary, $flags & EDIT_MINOR,
1295 null, null, &$flags ) ) )
1296 {
1297 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1298 wfProfileOut( __METHOD__ );
1299 return false;
1300 }
1301
1302 # Silently ignore EDIT_MINOR if not allowed
1303 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1304 $bot = $wgUser->isAllowed( 'bot' ) || ( $flags & EDIT_FORCE_BOT );
1305
1306 $oldtext = $this->getContent();
1307 $oldsize = strlen( $oldtext );
1308
1309 # Provide autosummaries if one is not provided.
1310 if ($flags & EDIT_AUTOSUMMARY && $summary == '')
1311 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1312
1313 $text = $this->preSaveTransform( $text );
1314 $newsize = strlen( $text );
1315
1316 $dbw = wfGetDB( DB_MASTER );
1317 $now = wfTimestampNow();
1318
1319 if ( $flags & EDIT_UPDATE ) {
1320 # Update article, but only if changed.
1321
1322 # Make sure the revision is either completely inserted or not inserted at all
1323 if( !$wgDBtransactions ) {
1324 $userAbort = ignore_user_abort( true );
1325 }
1326
1327 $lastRevision = 0;
1328 $revisionId = 0;
1329
1330 if ( 0 != strcmp( $text, $oldtext ) ) {
1331 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1332 - (int)$this->isCountable( $oldtext );
1333 $this->mTotalAdjustment = 0;
1334
1335 $lastRevision = $dbw->selectField(
1336 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1337
1338 if ( !$lastRevision ) {
1339 # Article gone missing
1340 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1341 wfProfileOut( __METHOD__ );
1342 return false;
1343 }
1344
1345 $revision = new Revision( array(
1346 'page' => $this->getId(),
1347 'comment' => $summary,
1348 'minor_edit' => $isminor,
1349 'text' => $text
1350 ) );
1351
1352 $dbw->begin();
1353 $revisionId = $revision->insertOn( $dbw );
1354
1355 # Update page
1356 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1357
1358 if( !$ok ) {
1359 /* Belated edit conflict! Run away!! */
1360 $good = false;
1361 $dbw->rollback();
1362 } else {
1363 # Update recentchanges
1364 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1365 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1366 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1367 $revisionId );
1368
1369 # Mark as patrolled if the user can do so
1370 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1371 RecentChange::markPatrolled( $rcid );
1372 PatrolLog::record( $rcid, true );
1373 }
1374 }
1375 $wgUser->incEditCount();
1376 $dbw->commit();
1377 }
1378 } else {
1379 // Keep the same revision ID, but do some updates on it
1380 $revisionId = $this->getRevIdFetched();
1381 // Update page_touched, this is usually implicit in the page update
1382 // Other cache updates are done in onArticleEdit()
1383 $this->mTitle->invalidateCache();
1384 }
1385
1386 if( !$wgDBtransactions ) {
1387 ignore_user_abort( $userAbort );
1388 }
1389
1390 if ( $good ) {
1391 # Invalidate cache of this article and all pages using this article
1392 # as a template. Partly deferred.
1393 Article::onArticleEdit( $this->mTitle );
1394
1395 # Update links tables, site stats, etc.
1396 $changed = ( strcmp( $oldtext, $text ) != 0 );
1397 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1398 }
1399 } else {
1400 # Create new article
1401
1402 # Set statistics members
1403 # We work out if it's countable after PST to avoid counter drift
1404 # when articles are created with {{subst:}}
1405 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1406 $this->mTotalAdjustment = 1;
1407
1408 $dbw->begin();
1409
1410 # Add the page record; stake our claim on this title!
1411 # This will fail with a database query exception if the article already exists
1412 $newid = $this->insertOn( $dbw );
1413
1414 # Save the revision text...
1415 $revision = new Revision( array(
1416 'page' => $newid,
1417 'comment' => $summary,
1418 'minor_edit' => $isminor,
1419 'text' => $text
1420 ) );
1421 $revisionId = $revision->insertOn( $dbw );
1422
1423 $this->mTitle->resetArticleID( $newid );
1424
1425 # Update the page record with revision data
1426 $this->updateRevisionOn( $dbw, $revision, 0 );
1427
1428 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1429 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1430 '', strlen( $text ), $revisionId );
1431 # Mark as patrolled if the user can
1432 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1433 RecentChange::markPatrolled( $rcid );
1434 PatrolLog::record( $rcid, true );
1435 }
1436 }
1437 $wgUser->incEditCount();
1438 $dbw->commit();
1439
1440 # Update links, etc.
1441 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1442
1443 # Clear caches
1444 Article::onArticleCreate( $this->mTitle );
1445
1446 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1447 $summary, $flags & EDIT_MINOR,
1448 null, null, &$flags ) );
1449 }
1450
1451 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1452 wfDoUpdates();
1453 }
1454
1455 wfRunHooks( 'ArticleSaveComplete',
1456 array( &$this, &$wgUser, $text,
1457 $summary, $flags & EDIT_MINOR,
1458 null, null, &$flags ) );
1459
1460 wfProfileOut( __METHOD__ );
1461 return $good;
1462 }
1463
1464 /**
1465 * @deprecated wrapper for doRedirect
1466 */
1467 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1468 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1469 }
1470
1471 /**
1472 * Output a redirect back to the article.
1473 * This is typically used after an edit.
1474 *
1475 * @param boolean $noRedir Add redirect=no
1476 * @param string $sectionAnchor section to redirect to, including "#"
1477 */
1478 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1479 global $wgOut;
1480 if ( $noRedir ) {
1481 $query = 'redirect=no';
1482 } else {
1483 $query = '';
1484 }
1485 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1486 }
1487
1488 /**
1489 * Mark this particular edit as patrolled
1490 */
1491 function markpatrolled() {
1492 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1493 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1494
1495 # Check RC patrol config. option
1496 if( !$wgUseRCPatrol ) {
1497 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1498 return;
1499 }
1500
1501 # Check permissions
1502 if( !$wgUser->isAllowed( 'patrol' ) ) {
1503 $wgOut->permissionRequired( 'patrol' );
1504 return;
1505 }
1506
1507 # If we haven't been given an rc_id value, we can't do anything
1508 $rcid = $wgRequest->getVal( 'rcid' );
1509 if( !$rcid ) {
1510 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1511 return;
1512 }
1513
1514 # Handle the 'MarkPatrolled' hook
1515 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1516 return;
1517 }
1518
1519 $return = SpecialPage::getTitleFor( 'Recentchanges' );
1520 # If it's left up to us, check that the user is allowed to patrol this edit
1521 # If the user has the "autopatrol" right, then we'll assume there are no
1522 # other conditions stopping them doing so
1523 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1524 $rc = RecentChange::newFromId( $rcid );
1525 # Graceful error handling, as we've done before here...
1526 # (If the recent change doesn't exist, then it doesn't matter whether
1527 # the user is allowed to patrol it or not; nothing is going to happen
1528 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1529 # The user made this edit, and can't patrol it
1530 # Tell them so, and then back off
1531 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1532 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1533 $wgOut->returnToMain( false, $return );
1534 return;
1535 }
1536 }
1537
1538 # Mark the edit as patrolled
1539 RecentChange::markPatrolled( $rcid );
1540 PatrolLog::record( $rcid );
1541 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1542
1543 # Inform the user
1544 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1545 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1546 $wgOut->returnToMain( false, $return );
1547 }
1548
1549 /**
1550 * User-interface handler for the "watch" action
1551 */
1552
1553 function watch() {
1554
1555 global $wgUser, $wgOut;
1556
1557 if ( $wgUser->isAnon() ) {
1558 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1559 return;
1560 }
1561 if ( wfReadOnly() ) {
1562 $wgOut->readOnlyPage();
1563 return;
1564 }
1565
1566 if( $this->doWatch() ) {
1567 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1568 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1569
1570 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1571 $text = wfMsg( 'addedwatchtext', $link );
1572 $wgOut->addWikiText( $text );
1573 }
1574
1575 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1576 }
1577
1578 /**
1579 * Add this page to $wgUser's watchlist
1580 * @return bool true on successful watch operation
1581 */
1582 function doWatch() {
1583 global $wgUser;
1584 if( $wgUser->isAnon() ) {
1585 return false;
1586 }
1587
1588 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1589 $wgUser->addWatch( $this->mTitle );
1590
1591 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1592 }
1593
1594 return false;
1595 }
1596
1597 /**
1598 * User interface handler for the "unwatch" action.
1599 */
1600 function unwatch() {
1601
1602 global $wgUser, $wgOut;
1603
1604 if ( $wgUser->isAnon() ) {
1605 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1606 return;
1607 }
1608 if ( wfReadOnly() ) {
1609 $wgOut->readOnlyPage();
1610 return;
1611 }
1612
1613 if( $this->doUnwatch() ) {
1614 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1615 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1616
1617 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1618 $text = wfMsg( 'removedwatchtext', $link );
1619 $wgOut->addWikiText( $text );
1620 }
1621
1622 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1623 }
1624
1625 /**
1626 * Stop watching a page
1627 * @return bool true on successful unwatch
1628 */
1629 function doUnwatch() {
1630 global $wgUser;
1631 if( $wgUser->isAnon() ) {
1632 return false;
1633 }
1634
1635 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1636 $wgUser->removeWatch( $this->mTitle );
1637
1638 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1639 }
1640
1641 return false;
1642 }
1643
1644 /**
1645 * action=protect handler
1646 */
1647 function protect() {
1648 $form = new ProtectionForm( $this );
1649 $form->execute();
1650 }
1651
1652 /**
1653 * action=unprotect handler (alias)
1654 */
1655 function unprotect() {
1656 $this->protect();
1657 }
1658
1659 /**
1660 * Update the article's restriction field, and leave a log entry.
1661 *
1662 * @param array $limit set of restriction keys
1663 * @param string $reason
1664 * @return bool true on success
1665 */
1666 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1667 global $wgUser, $wgRestrictionTypes, $wgContLang;
1668
1669 $id = $this->mTitle->getArticleID();
1670 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1671 return false;
1672 }
1673
1674 if (!$cascade) {
1675 $cascade = false;
1676 }
1677
1678 // Take this opportunity to purge out expired restrictions
1679 Title::purgeExpiredRestrictions();
1680
1681 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1682 # we expect a single selection, but the schema allows otherwise.
1683 $current = array();
1684 foreach( $wgRestrictionTypes as $action )
1685 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1686
1687 $current = Article::flattenRestrictions( $current );
1688 $updated = Article::flattenRestrictions( $limit );
1689
1690 $changed = ( $current != $updated );
1691 $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
1692 $changed = $changed || ($this->mTitle->mRestrictionsExpiry != $expiry);
1693 $protect = ( $updated != '' );
1694
1695 # If nothing's changed, do nothing
1696 if( $changed ) {
1697 global $wgGroupPermissions;
1698 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1699
1700 $dbw = wfGetDB( DB_MASTER );
1701
1702 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1703
1704 $expiry_description = '';
1705 if ( $encodedExpiry != 'infinity' ) {
1706 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1707 }
1708
1709 # Prepare a null revision to be added to the history
1710 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1711
1712 foreach( $limit as $action => $restrictions ) {
1713 # Check if the group level required to edit also can protect pages
1714 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1715 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1716 }
1717
1718 $cascade_description = '';
1719 if ($cascade) {
1720 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1721 }
1722
1723 if( $reason )
1724 $comment .= ": $reason";
1725 if( $protect )
1726 $comment .= " [$updated]";
1727 if ( $expiry_description && $protect )
1728 $comment .= "$expiry_description";
1729 if ( $cascade )
1730 $comment .= "$cascade_description";
1731
1732 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1733 $nullRevId = $nullRevision->insertOn( $dbw );
1734
1735 # Update restrictions table
1736 foreach( $limit as $action => $restrictions ) {
1737 if ($restrictions != '' ) {
1738 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1739 array( 'pr_page' => $id, 'pr_type' => $action
1740 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1741 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1742 } else {
1743 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1744 'pr_type' => $action ), __METHOD__ );
1745 }
1746 }
1747
1748 # Update page record
1749 $dbw->update( 'page',
1750 array( /* SET */
1751 'page_touched' => $dbw->timestamp(),
1752 'page_restrictions' => '',
1753 'page_latest' => $nullRevId
1754 ), array( /* WHERE */
1755 'page_id' => $id
1756 ), 'Article::protect'
1757 );
1758 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1759
1760 # Update the protection log
1761 $log = new LogPage( 'protect' );
1762
1763 if( $protect ) {
1764 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1765 } else {
1766 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1767 }
1768
1769 } # End hook
1770 } # End "changed" check
1771
1772 return true;
1773 }
1774
1775 /**
1776 * Take an array of page restrictions and flatten it to a string
1777 * suitable for insertion into the page_restrictions field.
1778 * @param array $limit
1779 * @return string
1780 * @private
1781 */
1782 function flattenRestrictions( $limit ) {
1783 if( !is_array( $limit ) ) {
1784 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1785 }
1786 $bits = array();
1787 ksort( $limit );
1788 foreach( $limit as $action => $restrictions ) {
1789 if( $restrictions != '' ) {
1790 $bits[] = "$action=$restrictions";
1791 }
1792 }
1793 return implode( ':', $bits );
1794 }
1795
1796 /*
1797 * UI entry point for page deletion
1798 */
1799 function delete() {
1800 global $wgUser, $wgOut, $wgRequest;
1801 $confirm = $wgRequest->wasPosted() &&
1802 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1803 $reason = $wgRequest->getText( 'wpReason' );
1804
1805 # This code desperately needs to be totally rewritten
1806
1807 # Check permissions
1808 if( $wgUser->isAllowed( 'delete' ) ) {
1809 if( $wgUser->isBlocked( !$confirm ) ) {
1810 $wgOut->blockedPage();
1811 return;
1812 }
1813 } else {
1814 $wgOut->permissionRequired( 'delete' );
1815 return;
1816 }
1817
1818 if( wfReadOnly() ) {
1819 $wgOut->readOnlyPage();
1820 return;
1821 }
1822
1823 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1824
1825 # Better double-check that it hasn't been deleted yet!
1826 $dbw = wfGetDB( DB_MASTER );
1827 $conds = $this->mTitle->pageCond();
1828 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1829 if ( $latest === false ) {
1830 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1831 return;
1832 }
1833
1834 if( $confirm ) {
1835 $this->doDelete( $reason );
1836 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1837 $this->doWatch();
1838 } elseif( $this->mTitle->userIsWatching() ) {
1839 $this->doUnwatch();
1840 }
1841 return;
1842 }
1843
1844 # determine whether this page has earlier revisions
1845 # and insert a warning if it does
1846 $maxRevisions = 20;
1847 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1848
1849 if( count( $authors ) > 1 && !$confirm ) {
1850 $skin=$wgUser->getSkin();
1851 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1852 }
1853
1854 # If a single user is responsible for all revisions, find out who they are
1855 if ( count( $authors ) == $maxRevisions ) {
1856 // Query bailed out, too many revisions to find out if they're all the same
1857 $authorOfAll = false;
1858 } else {
1859 $authorOfAll = reset( $authors );
1860 foreach ( $authors as $author ) {
1861 if ( $authorOfAll != $author ) {
1862 $authorOfAll = false;
1863 break;
1864 }
1865 }
1866 }
1867 # Fetch article text
1868 $rev = Revision::newFromTitle( $this->mTitle );
1869
1870 if( !is_null( $rev ) ) {
1871 # if this is a mini-text, we can paste part of it into the deletion reason
1872 $text = $rev->getText();
1873
1874 #if this is empty, an earlier revision may contain "useful" text
1875 $blanked = false;
1876 if( $text == '' ) {
1877 $prev = $rev->getPrevious();
1878 if( $prev ) {
1879 $text = $prev->getText();
1880 $blanked = true;
1881 }
1882 }
1883
1884 $length = strlen( $text );
1885
1886 # this should not happen, since it is not possible to store an empty, new
1887 # page. Let's insert a standard text in case it does, though
1888 if( $length == 0 && $reason === '' ) {
1889 $reason = wfMsgForContent( 'exblank' );
1890 }
1891
1892 if( $reason === '' ) {
1893 # comment field=255, let's grep the first 150 to have some user
1894 # space left
1895 global $wgContLang;
1896 $text = $wgContLang->truncate( $text, 150, '...' );
1897
1898 # let's strip out newlines
1899 $text = preg_replace( "/[\n\r]/", '', $text );
1900
1901 if( !$blanked ) {
1902 if( $authorOfAll === false ) {
1903 $reason = wfMsgForContent( 'excontent', $text );
1904 } else {
1905 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1906 }
1907 } else {
1908 $reason = wfMsgForContent( 'exbeforeblank', $text );
1909 }
1910 }
1911 }
1912
1913 return $this->confirmDelete( '', $reason );
1914 }
1915
1916 /**
1917 * Get the last N authors
1918 * @param int $num Number of revisions to get
1919 * @param string $revLatest The latest rev_id, selected from the master (optional)
1920 * @return array Array of authors, duplicates not removed
1921 */
1922 function getLastNAuthors( $num, $revLatest = 0 ) {
1923 wfProfileIn( __METHOD__ );
1924
1925 // First try the slave
1926 // If that doesn't have the latest revision, try the master
1927 $continue = 2;
1928 $db = wfGetDB( DB_SLAVE );
1929 do {
1930 $res = $db->select( array( 'page', 'revision' ),
1931 array( 'rev_id', 'rev_user_text' ),
1932 array(
1933 'page_namespace' => $this->mTitle->getNamespace(),
1934 'page_title' => $this->mTitle->getDBkey(),
1935 'rev_page = page_id'
1936 ), __METHOD__, $this->getSelectOptions( array(
1937 'ORDER BY' => 'rev_timestamp DESC',
1938 'LIMIT' => $num
1939 ) )
1940 );
1941 if ( !$res ) {
1942 wfProfileOut( __METHOD__ );
1943 return array();
1944 }
1945 $row = $db->fetchObject( $res );
1946 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1947 $db = wfGetDB( DB_MASTER );
1948 $continue--;
1949 } else {
1950 $continue = 0;
1951 }
1952 } while ( $continue );
1953
1954 $authors = array( $row->rev_user_text );
1955 while ( $row = $db->fetchObject( $res ) ) {
1956 $authors[] = $row->rev_user_text;
1957 }
1958 wfProfileOut( __METHOD__ );
1959 return $authors;
1960 }
1961
1962 /**
1963 * Output deletion confirmation dialog
1964 */
1965 function confirmDelete( $par, $reason ) {
1966 global $wgOut, $wgUser;
1967
1968 wfDebug( "Article::confirmDelete\n" );
1969
1970 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1971 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1972 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1973 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1974
1975 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1976
1977 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1978 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1979 $token = htmlspecialchars( $wgUser->editToken() );
1980 $watch = Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '2' ) );
1981
1982 $wgOut->addHTML( "
1983 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1984 <table border='0'>
1985 <tr>
1986 <td align='right'>
1987 <label for='wpReason'>{$delcom}:</label>
1988 </td>
1989 <td align='left'>
1990 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
1991 </td>
1992 </tr>
1993 <tr>
1994 <td>&nbsp;</td>
1995 <td>$watch</td>
1996 </tr>
1997 <tr>
1998 <td>&nbsp;</td>
1999 <td>
2000 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2001 </td>
2002 </tr>
2003 </table>
2004 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2005 </form>\n" );
2006
2007 $wgOut->returnToMain( false );
2008
2009 $this->showLogExtract( $wgOut );
2010 }
2011
2012
2013 /**
2014 * Fetch deletion log
2015 */
2016 function showLogExtract( &$out ) {
2017 # Show relevant lines from the deletion log:
2018 $out->addHTML( "<h2>" . htmlspecialchars( LogPage::logName( 'delete' ) ) . "</h2>\n" );
2019 $logViewer = new LogViewer(
2020 new LogReader(
2021 new FauxRequest(
2022 array( 'page' => $this->mTitle->getPrefixedText(),
2023 'type' => 'delete' ) ) ) );
2024 $logViewer->showList( $out );
2025 }
2026
2027
2028 /**
2029 * Perform a deletion and output success or failure messages
2030 */
2031 function doDelete( $reason ) {
2032 global $wgOut, $wgUser;
2033 wfDebug( __METHOD__."\n" );
2034
2035 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2036 if ( $this->doDeleteArticle( $reason ) ) {
2037 $deleted = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2038
2039 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2040 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2041
2042 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2043 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2044
2045 $wgOut->addWikiText( $text );
2046 $wgOut->returnToMain( false );
2047 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2048 } else {
2049 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2050 }
2051 }
2052 }
2053
2054 /**
2055 * Back-end article deletion
2056 * Deletes the article with database consistency, writes logs, purges caches
2057 * Returns success
2058 */
2059 function doDeleteArticle( $reason ) {
2060 global $wgUseSquid, $wgDeferredUpdateList;
2061 global $wgUseTrackbacks;
2062
2063 wfDebug( __METHOD__."\n" );
2064
2065 $dbw = wfGetDB( DB_MASTER );
2066 $ns = $this->mTitle->getNamespace();
2067 $t = $this->mTitle->getDBkey();
2068 $id = $this->mTitle->getArticleID();
2069
2070 if ( $t == '' || $id == 0 ) {
2071 return false;
2072 }
2073
2074 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2075 array_push( $wgDeferredUpdateList, $u );
2076
2077 // For now, shunt the revision data into the archive table.
2078 // Text is *not* removed from the text table; bulk storage
2079 // is left intact to avoid breaking block-compression or
2080 // immutable storage schemes.
2081 //
2082 // For backwards compatibility, note that some older archive
2083 // table entries will have ar_text and ar_flags fields still.
2084 //
2085 // In the future, we may keep revisions and mark them with
2086 // the rev_deleted field, which is reserved for this purpose.
2087 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2088 array(
2089 'ar_namespace' => 'page_namespace',
2090 'ar_title' => 'page_title',
2091 'ar_comment' => 'rev_comment',
2092 'ar_user' => 'rev_user',
2093 'ar_user_text' => 'rev_user_text',
2094 'ar_timestamp' => 'rev_timestamp',
2095 'ar_minor_edit' => 'rev_minor_edit',
2096 'ar_rev_id' => 'rev_id',
2097 'ar_text_id' => 'rev_text_id',
2098 'ar_text' => '\'\'', // Be explicit to appease
2099 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2100 'ar_len' => 'rev_len'
2101 ), array(
2102 'page_id' => $id,
2103 'page_id = rev_page'
2104 ), __METHOD__
2105 );
2106
2107 # Delete restrictions for it
2108 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2109
2110 # Now that it's safely backed up, delete it
2111 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2112
2113 # If using cascading deletes, we can skip some explicit deletes
2114 if ( !$dbw->cascadingDeletes() ) {
2115
2116 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2117
2118 if ($wgUseTrackbacks)
2119 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2120
2121 # Delete outgoing links
2122 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2123 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2124 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2125 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2126 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2127 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2128 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2129 }
2130
2131 # If using cleanup triggers, we can skip some manual deletes
2132 if ( !$dbw->cleanupTriggers() ) {
2133
2134 # Clean up recentchanges entries...
2135 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
2136 }
2137
2138 # Clear caches
2139 Article::onArticleDelete( $this->mTitle );
2140
2141 # Log the deletion
2142 $log = new LogPage( 'delete' );
2143 $log->addEntry( 'delete', $this->mTitle, $reason );
2144
2145 # Clear the cached article id so the interface doesn't act like we exist
2146 $this->mTitle->resetArticleID( 0 );
2147 $this->mTitle->mArticleID = 0;
2148 return true;
2149 }
2150
2151 /**
2152 * Revert a modification
2153 */
2154 function rollback() {
2155 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2156
2157 if( $wgUser->isAllowed( 'rollback' ) ) {
2158 if( $wgUser->isBlocked() ) {
2159 $wgOut->blockedPage();
2160 return;
2161 }
2162 } else {
2163 $wgOut->permissionRequired( 'rollback' );
2164 return;
2165 }
2166
2167 if ( wfReadOnly() ) {
2168 $wgOut->readOnlyPage( $this->getContent() );
2169 return;
2170 }
2171 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2172 array( $this->mTitle->getPrefixedText(),
2173 $wgRequest->getVal( 'from' ) ) ) ) {
2174 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2175 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2176 return;
2177 }
2178 $dbw = wfGetDB( DB_MASTER );
2179
2180 # Enhanced rollback, marks edits rc_bot=1
2181 $bot = $wgRequest->getBool( 'bot' );
2182
2183 # Replace all this user's current edits with the next one down
2184
2185 # Get the last editor
2186 $current = Revision::newFromTitle( $this->mTitle );
2187 if( is_null( $current ) ) {
2188 # Something wrong... no page?
2189 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2190 return;
2191 }
2192
2193 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2194 if( $from != $current->getUserText() ) {
2195 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2196 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2197 htmlspecialchars( $this->mTitle->getPrefixedText()),
2198 htmlspecialchars( $from ),
2199 htmlspecialchars( $current->getUserText() ) ) );
2200 if( $current->getComment() != '') {
2201 $wgOut->addHTML(
2202 wfMsg( 'editcomment',
2203 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2204 }
2205 return;
2206 }
2207
2208 # Get the last edit not by this guy
2209 $user = intval( $current->getUser() );
2210 $user_text = $dbw->addQuotes( $current->getUserText() );
2211 $s = $dbw->selectRow( 'revision',
2212 array( 'rev_id', 'rev_timestamp' ),
2213 array(
2214 'rev_page' => $current->getPage(),
2215 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2216 ), __METHOD__,
2217 array(
2218 'USE INDEX' => 'page_timestamp',
2219 'ORDER BY' => 'rev_timestamp DESC' )
2220 );
2221 if( $s === false ) {
2222 # Something wrong
2223 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2224 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2225 return;
2226 }
2227
2228 $set = array();
2229 if ( $bot ) {
2230 # Mark all reverted edits as bot
2231 $set['rc_bot'] = 1;
2232 }
2233 if ( $wgUseRCPatrol ) {
2234 # Mark all reverted edits as patrolled
2235 $set['rc_patrolled'] = 1;
2236 }
2237
2238 if ( $set ) {
2239 $dbw->update( 'recentchanges', $set,
2240 array( /* WHERE */
2241 'rc_cur_id' => $current->getPage(),
2242 'rc_user_text' => $current->getUserText(),
2243 "rc_timestamp > '{$s->rev_timestamp}'",
2244 ), __METHOD__
2245 );
2246 }
2247
2248 # Get the edit summary
2249 $target = Revision::newFromId( $s->rev_id );
2250 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2251 $newComment = $wgRequest->getText( 'summary', $newComment );
2252
2253 # Save it!
2254 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2255 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2256 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2257
2258 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2259
2260 $wgOut->returnToMain( false );
2261 }
2262
2263
2264 /**
2265 * Do standard deferred updates after page view
2266 * @private
2267 */
2268 function viewUpdates() {
2269 global $wgDeferredUpdateList;
2270
2271 if ( 0 != $this->getID() ) {
2272 global $wgDisableCounters;
2273 if( !$wgDisableCounters ) {
2274 Article::incViewCount( $this->getID() );
2275 $u = new SiteStatsUpdate( 1, 0, 0 );
2276 array_push( $wgDeferredUpdateList, $u );
2277 }
2278 }
2279
2280 # Update newtalk / watchlist notification status
2281 global $wgUser;
2282 $wgUser->clearNotification( $this->mTitle );
2283 }
2284
2285 /**
2286 * Do standard deferred updates after page edit.
2287 * Update links tables, site stats, search index and message cache.
2288 * Every 1000th edit, prune the recent changes table.
2289 *
2290 * @private
2291 * @param $text New text of the article
2292 * @param $summary Edit summary
2293 * @param $minoredit Minor edit
2294 * @param $timestamp_of_pagechange Timestamp associated with the page change
2295 * @param $newid rev_id value of the new revision
2296 * @param $changed Whether or not the content actually changed
2297 */
2298 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2299 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2300
2301 wfProfileIn( __METHOD__ );
2302
2303 # Parse the text
2304 $options = new ParserOptions;
2305 $options->setTidy(true);
2306 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2307
2308 # Save it to the parser cache
2309 $parserCache =& ParserCache::singleton();
2310 $parserCache->save( $poutput, $this, $wgUser );
2311
2312 # Update the links tables
2313 $u = new LinksUpdate( $this->mTitle, $poutput );
2314 $u->doUpdate();
2315
2316 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2317 wfSeedRandom();
2318 if ( 0 == mt_rand( 0, 999 ) ) {
2319 # Periodically flush old entries from the recentchanges table.
2320 global $wgRCMaxAge;
2321
2322 $dbw = wfGetDB( DB_MASTER );
2323 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2324 $recentchanges = $dbw->tableName( 'recentchanges' );
2325 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2326 $dbw->query( $sql );
2327 }
2328 }
2329
2330 $id = $this->getID();
2331 $title = $this->mTitle->getPrefixedDBkey();
2332 $shortTitle = $this->mTitle->getDBkey();
2333
2334 if ( 0 == $id ) {
2335 wfProfileOut( __METHOD__ );
2336 return;
2337 }
2338
2339 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2340 array_push( $wgDeferredUpdateList, $u );
2341 $u = new SearchUpdate( $id, $title, $text );
2342 array_push( $wgDeferredUpdateList, $u );
2343
2344 # If this is another user's talk page, update newtalk
2345 # Don't do this if $changed = false otherwise some idiot can null-edit a
2346 # load of user talk pages and piss people off, nor if it's a minor edit
2347 # by a properly-flagged bot.
2348 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2349 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2350 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2351 $other = User::newFromName( $shortTitle );
2352 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2353 // An anonymous user
2354 $other = new User();
2355 $other->setName( $shortTitle );
2356 }
2357 if( $other ) {
2358 $other->setNewtalk( true );
2359 }
2360 }
2361 }
2362
2363 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2364 $wgMessageCache->replace( $shortTitle, $text );
2365 }
2366
2367 wfProfileOut( __METHOD__ );
2368 }
2369
2370 /**
2371 * Perform article updates on a special page creation.
2372 *
2373 * @param Revision $rev
2374 *
2375 * @todo This is a shitty interface function. Kill it and replace the
2376 * other shitty functions like editUpdates and such so it's not needed
2377 * anymore.
2378 */
2379 function createUpdates( $rev ) {
2380 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2381 $this->mTotalAdjustment = 1;
2382 $this->editUpdates( $rev->getText(), $rev->getComment(),
2383 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2384 }
2385
2386 /**
2387 * Generate the navigation links when browsing through an article revisions
2388 * It shows the information as:
2389 * Revision as of \<date\>; view current revision
2390 * \<- Previous version | Next Version -\>
2391 *
2392 * @private
2393 * @param string $oldid Revision ID of this article revision
2394 */
2395 function setOldSubtitle( $oldid=0 ) {
2396 global $wgLang, $wgOut, $wgUser;
2397
2398 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2399 return;
2400 }
2401
2402 $revision = Revision::newFromId( $oldid );
2403
2404 $current = ( $oldid == $this->mLatest );
2405 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2406 $sk = $wgUser->getSkin();
2407 $lnk = $current
2408 ? wfMsg( 'currentrevisionlink' )
2409 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2410 $curdiff = $current
2411 ? wfMsg( 'diff' )
2412 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2413 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2414 $prevlink = $prev
2415 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2416 : wfMsg( 'previousrevision' );
2417 $prevdiff = $prev
2418 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2419 : wfMsg( 'diff' );
2420 $nextlink = $current
2421 ? wfMsg( 'nextrevision' )
2422 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2423 $nextdiff = $current
2424 ? wfMsg( 'diff' )
2425 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2426
2427 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2428 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2429
2430 $r = "\n\t\t\t\t<div id=\"mw-revision-info\">" . wfMsg( 'revision-info', $td, $userlinks ) . "</div>\n" .
2431 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2432 $wgOut->setSubtitle( $r );
2433 }
2434
2435 /**
2436 * This function is called right before saving the wikitext,
2437 * so we can do things like signatures and links-in-context.
2438 *
2439 * @param string $text
2440 */
2441 function preSaveTransform( $text ) {
2442 global $wgParser, $wgUser;
2443 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2444 }
2445
2446 /* Caching functions */
2447
2448 /**
2449 * checkLastModified returns true if it has taken care of all
2450 * output to the client that is necessary for this request.
2451 * (that is, it has sent a cached version of the page)
2452 */
2453 function tryFileCache() {
2454 static $called = false;
2455 if( $called ) {
2456 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2457 return;
2458 }
2459 $called = true;
2460 if($this->isFileCacheable()) {
2461 $touched = $this->mTouched;
2462 $cache = new HTMLFileCache( $this->mTitle );
2463 if($cache->isFileCacheGood( $touched )) {
2464 wfDebug( "Article::tryFileCache(): about to load file\n" );
2465 $cache->loadFromFileCache();
2466 return true;
2467 } else {
2468 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2469 ob_start( array(&$cache, 'saveToFileCache' ) );
2470 }
2471 } else {
2472 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2473 }
2474 }
2475
2476 /**
2477 * Check if the page can be cached
2478 * @return bool
2479 */
2480 function isFileCacheable() {
2481 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2482 $action = $wgRequest->getVal( 'action' );
2483 $oldid = $wgRequest->getVal( 'oldid' );
2484 $diff = $wgRequest->getVal( 'diff' );
2485 $redirect = $wgRequest->getVal( 'redirect' );
2486 $printable = $wgRequest->getVal( 'printable' );
2487 $page = $wgRequest->getVal( 'page' );
2488
2489 //check for non-standard user language; this covers uselang,
2490 //and extensions for auto-detecting user language.
2491 $ulang = $wgLang->getCode();
2492 $clang = $wgContLang->getCode();
2493
2494 $cacheable = $wgUseFileCache
2495 && (!$wgShowIPinHeader)
2496 && ($this->getID() != 0)
2497 && ($wgUser->isAnon())
2498 && (!$wgUser->getNewtalk())
2499 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2500 && (empty( $action ) || $action == 'view')
2501 && (!isset($oldid))
2502 && (!isset($diff))
2503 && (!isset($redirect))
2504 && (!isset($printable))
2505 && !isset($page)
2506 && (!$this->mRedirectedFrom)
2507 && ($ulang === $clang);
2508
2509 if ( $cacheable ) {
2510 //extension may have reason to disable file caching on some pages.
2511 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2512 }
2513
2514 return $cacheable;
2515 }
2516
2517 /**
2518 * Loads page_touched and returns a value indicating if it should be used
2519 *
2520 */
2521 function checkTouched() {
2522 if( !$this->mDataLoaded ) {
2523 $this->loadPageData();
2524 }
2525 return !$this->mIsRedirect;
2526 }
2527
2528 /**
2529 * Get the page_touched field
2530 */
2531 function getTouched() {
2532 # Ensure that page data has been loaded
2533 if( !$this->mDataLoaded ) {
2534 $this->loadPageData();
2535 }
2536 return $this->mTouched;
2537 }
2538
2539 /**
2540 * Get the page_latest field
2541 */
2542 function getLatest() {
2543 if ( !$this->mDataLoaded ) {
2544 $this->loadPageData();
2545 }
2546 return $this->mLatest;
2547 }
2548
2549 /**
2550 * Edit an article without doing all that other stuff
2551 * The article must already exist; link tables etc
2552 * are not updated, caches are not flushed.
2553 *
2554 * @param string $text text submitted
2555 * @param string $comment comment submitted
2556 * @param bool $minor whereas it's a minor modification
2557 */
2558 function quickEdit( $text, $comment = '', $minor = 0 ) {
2559 wfProfileIn( __METHOD__ );
2560
2561 $dbw = wfGetDB( DB_MASTER );
2562 $dbw->begin();
2563 $revision = new Revision( array(
2564 'page' => $this->getId(),
2565 'text' => $text,
2566 'comment' => $comment,
2567 'minor_edit' => $minor ? 1 : 0,
2568 ) );
2569 $revision->insertOn( $dbw );
2570 $this->updateRevisionOn( $dbw, $revision );
2571 $dbw->commit();
2572
2573 wfProfileOut( __METHOD__ );
2574 }
2575
2576 /**
2577 * Used to increment the view counter
2578 *
2579 * @static
2580 * @param integer $id article id
2581 */
2582 function incViewCount( $id ) {
2583 $id = intval( $id );
2584 global $wgHitcounterUpdateFreq, $wgDBtype;
2585
2586 $dbw = wfGetDB( DB_MASTER );
2587 $pageTable = $dbw->tableName( 'page' );
2588 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2589 $acchitsTable = $dbw->tableName( 'acchits' );
2590
2591 if( $wgHitcounterUpdateFreq <= 1 ) {
2592 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2593 return;
2594 }
2595
2596 # Not important enough to warrant an error page in case of failure
2597 $oldignore = $dbw->ignoreErrors( true );
2598
2599 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2600
2601 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2602 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2603 # Most of the time (or on SQL errors), skip row count check
2604 $dbw->ignoreErrors( $oldignore );
2605 return;
2606 }
2607
2608 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2609 $row = $dbw->fetchObject( $res );
2610 $rown = intval( $row->n );
2611 if( $rown >= $wgHitcounterUpdateFreq ){
2612 wfProfileIn( 'Article::incViewCount-collect' );
2613 $old_user_abort = ignore_user_abort( true );
2614
2615 if ($wgDBtype == 'mysql')
2616 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2617 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2618 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2619 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2620 'GROUP BY hc_id');
2621 $dbw->query("DELETE FROM $hitcounterTable");
2622 if ($wgDBtype == 'mysql') {
2623 $dbw->query('UNLOCK TABLES');
2624 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2625 'WHERE page_id = hc_id');
2626 }
2627 else {
2628 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2629 "FROM $acchitsTable WHERE page_id = hc_id");
2630 }
2631 $dbw->query("DROP TABLE $acchitsTable");
2632
2633 ignore_user_abort( $old_user_abort );
2634 wfProfileOut( 'Article::incViewCount-collect' );
2635 }
2636 $dbw->ignoreErrors( $oldignore );
2637 }
2638
2639 /**#@+
2640 * The onArticle*() functions are supposed to be a kind of hooks
2641 * which should be called whenever any of the specified actions
2642 * are done.
2643 *
2644 * This is a good place to put code to clear caches, for instance.
2645 *
2646 * This is called on page move and undelete, as well as edit
2647 * @static
2648 * @param $title_obj a title object
2649 */
2650
2651 static function onArticleCreate($title) {
2652 # The talk page isn't in the regular link tables, so we need to update manually:
2653 if ( $title->isTalkPage() ) {
2654 $other = $title->getSubjectPage();
2655 } else {
2656 $other = $title->getTalkPage();
2657 }
2658 $other->invalidateCache();
2659 $other->purgeSquid();
2660
2661 $title->touchLinks();
2662 $title->purgeSquid();
2663 }
2664
2665 static function onArticleDelete( $title ) {
2666 global $wgUseFileCache, $wgMessageCache;
2667
2668 $title->touchLinks();
2669 $title->purgeSquid();
2670
2671 # File cache
2672 if ( $wgUseFileCache ) {
2673 $cm = new HTMLFileCache( $title );
2674 @unlink( $cm->fileCacheName() );
2675 }
2676
2677 if( $title->getNamespace() == NS_MEDIAWIKI) {
2678 $wgMessageCache->replace( $title->getDBkey(), false );
2679 }
2680 }
2681
2682 /**
2683 * Purge caches on page update etc
2684 */
2685 static function onArticleEdit( $title ) {
2686 global $wgDeferredUpdateList, $wgUseFileCache;
2687
2688 // Invalidate caches of articles which include this page
2689 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2690 $wgDeferredUpdateList[] = $update;
2691
2692 # Purge squid for this page only
2693 $title->purgeSquid();
2694
2695 # Clear file cache
2696 if ( $wgUseFileCache ) {
2697 $cm = new HTMLFileCache( $title );
2698 @unlink( $cm->fileCacheName() );
2699 }
2700 }
2701
2702 /**#@-*/
2703
2704 /**
2705 * Info about this page
2706 * Called for ?action=info when $wgAllowPageInfo is on.
2707 *
2708 * @public
2709 */
2710 function info() {
2711 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2712
2713 if ( !$wgAllowPageInfo ) {
2714 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2715 return;
2716 }
2717
2718 $page = $this->mTitle->getSubjectPage();
2719
2720 $wgOut->setPagetitle( $page->getPrefixedText() );
2721 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2722
2723 # first, see if the page exists at all.
2724 $exists = $page->getArticleId() != 0;
2725 if( !$exists ) {
2726 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2727 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2728 } else {
2729 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2730 }
2731 } else {
2732 $dbr = wfGetDB( DB_SLAVE );
2733 $wl_clause = array(
2734 'wl_title' => $page->getDBkey(),
2735 'wl_namespace' => $page->getNamespace() );
2736 $numwatchers = $dbr->selectField(
2737 'watchlist',
2738 'COUNT(*)',
2739 $wl_clause,
2740 __METHOD__,
2741 $this->getSelectOptions() );
2742
2743 $pageInfo = $this->pageCountInfo( $page );
2744 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2745
2746 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2747 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2748 if( $talkInfo ) {
2749 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2750 }
2751 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2752 if( $talkInfo ) {
2753 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2754 }
2755 $wgOut->addHTML( '</ul>' );
2756
2757 }
2758 }
2759
2760 /**
2761 * Return the total number of edits and number of unique editors
2762 * on a given page. If page does not exist, returns false.
2763 *
2764 * @param Title $title
2765 * @return array
2766 * @private
2767 */
2768 function pageCountInfo( $title ) {
2769 $id = $title->getArticleId();
2770 if( $id == 0 ) {
2771 return false;
2772 }
2773
2774 $dbr = wfGetDB( DB_SLAVE );
2775
2776 $rev_clause = array( 'rev_page' => $id );
2777
2778 $edits = $dbr->selectField(
2779 'revision',
2780 'COUNT(rev_page)',
2781 $rev_clause,
2782 __METHOD__,
2783 $this->getSelectOptions() );
2784
2785 $authors = $dbr->selectField(
2786 'revision',
2787 'COUNT(DISTINCT rev_user_text)',
2788 $rev_clause,
2789 __METHOD__,
2790 $this->getSelectOptions() );
2791
2792 return array( 'edits' => $edits, 'authors' => $authors );
2793 }
2794
2795 /**
2796 * Return a list of templates used by this article.
2797 * Uses the templatelinks table
2798 *
2799 * @return array Array of Title objects
2800 */
2801 function getUsedTemplates() {
2802 $result = array();
2803 $id = $this->mTitle->getArticleID();
2804 if( $id == 0 ) {
2805 return array();
2806 }
2807
2808 $dbr = wfGetDB( DB_SLAVE );
2809 $res = $dbr->select( array( 'templatelinks' ),
2810 array( 'tl_namespace', 'tl_title' ),
2811 array( 'tl_from' => $id ),
2812 'Article:getUsedTemplates' );
2813 if ( false !== $res ) {
2814 if ( $dbr->numRows( $res ) ) {
2815 while ( $row = $dbr->fetchObject( $res ) ) {
2816 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2817 }
2818 }
2819 }
2820 $dbr->freeResult( $res );
2821 return $result;
2822 }
2823
2824 /**
2825 * Return an auto-generated summary if the text provided is a redirect.
2826 *
2827 * @param string $text The wikitext to check
2828 * @return string '' or an appropriate summary
2829 */
2830 public static function getRedirectAutosummary( $text ) {
2831 $rt = Title::newFromRedirect( $text );
2832 if( is_object( $rt ) )
2833 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2834 else
2835 return '';
2836 }
2837
2838 /**
2839 * Return an auto-generated summary if the new text is much shorter than
2840 * the old text.
2841 *
2842 * @param string $oldtext The previous text of the page
2843 * @param string $text The submitted text of the page
2844 * @return string An appropriate autosummary, or an empty string.
2845 */
2846 public static function getBlankingAutosummary( $oldtext, $text ) {
2847 if ($oldtext!='' && $text=='') {
2848 return wfMsgForContent('autosumm-blank');
2849 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2850 #Removing more than 90% of the article
2851 global $wgContLang;
2852 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2853 return wfMsgForContent('autosumm-replace', $truncatedtext);
2854 } else {
2855 return '';
2856 }
2857 }
2858
2859 /**
2860 * Return an applicable autosummary if one exists for the given edit.
2861 * @param string $oldtext The previous text of the page.
2862 * @param string $newtext The submitted text of the page.
2863 * @param bitmask $flags A bitmask of flags submitted for the edit.
2864 * @return string An appropriate autosummary, or an empty string.
2865 */
2866 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2867
2868 # This code is UGLY UGLY UGLY.
2869 # Somebody PLEASE come up with a more elegant way to do it.
2870
2871 #Redirect autosummaries
2872 $summary = self::getRedirectAutosummary( $newtext );
2873
2874 if ($summary)
2875 return $summary;
2876
2877 #Blanking autosummaries
2878 if (!($flags & EDIT_NEW))
2879 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
2880
2881 if ($summary)
2882 return $summary;
2883
2884 #New page autosummaries
2885 if ($flags & EDIT_NEW && strlen($newtext)) {
2886 #If they're making a new article, give its text, truncated, in the summary.
2887 global $wgContLang;
2888 $truncatedtext = $wgContLang->truncate(
2889 str_replace("\n", ' ', $newtext),
2890 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2891 '...' );
2892 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2893 }
2894
2895 if ($summary)
2896 return $summary;
2897
2898 return $summary;
2899 }
2900
2901 /**
2902 * Add the primary page-view wikitext to the output buffer
2903 * Saves the text into the parser cache if possible.
2904 * Updates templatelinks if it is out of date.
2905 *
2906 * @param string $text
2907 * @param bool $cache
2908 */
2909 public function outputWikiText( $text, $cache = true ) {
2910 global $wgParser, $wgUser, $wgOut;
2911
2912 $popts = $wgOut->parserOptions();
2913 $popts->setTidy(true);
2914 $parserOutput = $wgParser->parse( $text, $this->mTitle,
2915 $popts, true, true, $this->getRevIdFetched() );
2916 $popts->setTidy(false);
2917 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
2918 $parserCache =& ParserCache::singleton();
2919 $parserCache->save( $parserOutput, $this, $wgUser );
2920 }
2921
2922 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
2923 // templatelinks table may have become out of sync,
2924 // especially if using variable-based transclusions.
2925 // For paranoia, check if things have changed and if
2926 // so apply updates to the database. This will ensure
2927 // that cascaded protections apply as soon as the changes
2928 // are visible.
2929
2930 # Get templates from templatelinks
2931 $id = $this->mTitle->getArticleID();
2932
2933 $tlTemplates = array();
2934
2935 $dbr = wfGetDB( DB_SLAVE );
2936 $res = $dbr->select( array( 'templatelinks' ),
2937 array( 'tl_namespace', 'tl_title' ),
2938 array( 'tl_from' => $id ),
2939 'Article:getUsedTemplates' );
2940
2941 global $wgContLang;
2942
2943 if ( false !== $res ) {
2944 if ( $dbr->numRows( $res ) ) {
2945 while ( $row = $dbr->fetchObject( $res ) ) {
2946 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
2947 }
2948 }
2949 }
2950
2951 # Get templates from parser output.
2952 $poTemplates_allns = $parserOutput->getTemplates();
2953
2954 $poTemplates = array ();
2955 foreach ( $poTemplates_allns as $ns_templates ) {
2956 $poTemplates = array_merge( $poTemplates, $ns_templates );
2957 }
2958
2959 # Get the diff
2960 $templates_diff = array_diff( $poTemplates, $tlTemplates );
2961
2962 if ( count( $templates_diff ) > 0 ) {
2963 # Whee, link updates time.
2964 $u = new LinksUpdate( $this->mTitle, $parserOutput );
2965
2966 $dbw = wfGetDb( DB_MASTER );
2967 $dbw->begin();
2968
2969 $u->doUpdate();
2970
2971 $dbw->commit();
2972 }
2973 }
2974
2975 $wgOut->addParserOutput( $parserOutput );
2976 }
2977
2978 }
2979
2980 ?>