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